|
1 | 1 | import { writable } from 'svelte/store'
|
2 | 2 |
|
| 3 | +const defaults = { |
| 4 | + duration: 4000, |
| 5 | + dismissable: true, |
| 6 | + initial: 1, |
| 7 | + progress: 0, |
| 8 | + reversed: false, |
| 9 | + intro: { x: 256 }, |
| 10 | + theme: {} |
| 11 | +} |
| 12 | + |
3 | 13 | const createToast = () => {
|
4 | 14 | const { subscribe, update } = writable([])
|
5 | 15 | let count = 0
|
6 |
| - let defaults = {} |
7 |
| - const _obj = obj => typeof obj === 'object' |
| 16 | + const options = {} |
| 17 | + const _obj = obj => obj instanceof Object |
8 | 18 | const push = (msg, opts = {}) => {
|
9 |
| - opts = _obj(msg) ? { ...msg } : { ...opts, msg } |
10 |
| - const entry = { ...defaults, ...opts, id: ++count, theme: { ...defaults.theme, ...opts.theme } } |
| 19 | + const param = { target: 'default', ..._obj(msg) ? msg : { ...opts, msg } } |
| 20 | + const conf = options[param.target] || {} |
| 21 | + const entry = { ...defaults, ...conf, ...param, theme: { ...conf.theme, ...param.theme }, id: ++count } |
11 | 22 | update(n => entry.reversed ? [...n, entry] : [entry, ...n])
|
12 | 23 | return count
|
13 | 24 | }
|
14 | 25 | const pop = id => {
|
15 | 26 | update(n => {
|
16 |
| - if (n.length === 0 || id === 0) return [] |
| 27 | + if (!n.length || id === 0) return [] |
| 28 | + if (_obj(id)) return n.filter(i => id(i)) |
17 | 29 | const target = id || Math.max(...n.map(i => i.id))
|
18 | 30 | return n.filter(i => i.id !== target)
|
19 | 31 | })
|
20 | 32 | }
|
21 | 33 | const set = (id, opts = {}) => {
|
22 |
| - opts = _obj(id) ? { ...id } : { ...opts, id } |
| 34 | + const param = _obj(id) ? { ...id } : { ...opts, id } |
23 | 35 | update(n => {
|
24 |
| - const idx = n.findIndex(i => i.id === opts.id) |
| 36 | + const idx = n.findIndex(i => i.id === param.id) |
25 | 37 | if (idx > -1) {
|
26 |
| - n[idx] = { ...n[idx], ...opts } |
| 38 | + n[idx] = { ...n[idx], ...param } |
27 | 39 | }
|
28 | 40 | return n
|
29 | 41 | })
|
30 | 42 | }
|
31 |
| - const _opts = (obj = {}) => { |
32 |
| - defaults = { ...defaults, ...obj, theme: { ...defaults.theme, ...obj.theme } } |
33 |
| - return defaults |
| 43 | + const _init = (target = 'default', opts = {}) => { |
| 44 | + options[target] = opts |
| 45 | + return options |
34 | 46 | }
|
35 |
| - return { subscribe, push, pop, set, _opts } |
| 47 | + return { subscribe, push, pop, set, _init } |
36 | 48 | }
|
37 | 49 |
|
38 | 50 | export const toast = createToast()
|
0 commit comments