Skip to content

Commit

Permalink
feat: support DOM as message (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
2nthony authored Aug 1, 2020
1 parent 2654b4d commit b289d97
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
23 changes: 22 additions & 1 deletion example/public/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ createToast('The Evil Rabbit jumped over the fence.', {

<button @click="showDefault">Show toast</button>

## Multiline
### Multiline

```js
import { createToast } from 'vercel-toast'
Expand All @@ -75,6 +75,19 @@ createToast(

<button @click="multiline">Show toast</button>

### Use a DOM node as message

```js
const message = document.createElement('div')
message.innerHTML = `<i style="color:magenta;">The Evil Rabbit jumped over the fence.</i>`

createToast(message, {
timeout: 3000
})
```

<button @click="domNode">Show toast</button>

### Action

```js
Expand Down Expand Up @@ -155,6 +168,14 @@ createToast('The Evil Rabbit jumped over the fence.', {
})
},

domNode() {
const message = document.createElement('div')
message.innerHTML = '<i style="color:magenta;">The Evil Rabbit jumped over the fence.</i>'
createToast(message, {
timeout: 3000
})
},

action() {
createToast('The Evil Rabbit jumped over the fence.', {
action: {
Expand Down
18 changes: 13 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export interface Action {
callback?: ActionCallback
}

export type Message = string | HTMLElement

export type ActionCallback = (toast: Toast) => void

export interface ToastOptions {
Expand All @@ -28,13 +30,13 @@ export interface ToastOptions {
}

export class Toast {
message: string
message: Message
options: ToastOptions
el?: HTMLDivElement

private timeoutId?: number

constructor(message: string, options: ToastOptions = {}) {
constructor(message: Message, options: ToastOptions = {}) {
const { timeout = 0, action, type = 'default', cancel } = options

this.message = message
Expand Down Expand Up @@ -63,10 +65,16 @@ export class Toast {
const inner = document.createElement('div')
inner.className = 'toast-inner'

const text = document.createElement('span')
const text = document.createElement('div')
text.className = 'toast-text'
inner.classList.add(type as string)
text.textContent = this.message

if (typeof this.message === 'string') {
text.textContent = this.message
} else {
text.appendChild(this.message)
}

inner.appendChild(text)

if (cancel) {
Expand Down Expand Up @@ -152,7 +160,7 @@ export class Toast {
}
}

export function createToast(message: string, options?: ToastOptions): Toast {
export function createToast(message: Message, options?: ToastOptions): Toast {
return new Toast(message, options)
}

Expand Down

0 comments on commit b289d97

Please sign in to comment.