|
1 | 1 | import { bodyAttributes } from './attributes'; |
2 | 2 |
|
3 | 3 | if (typeof window !== 'undefined') { |
4 | | - const toDatasetKey = (dataKey: string) => dataKey.slice(5).replace(/-([a-z])/g, (_, c) => c.toUpperCase()); |
| 4 | + const toCamel = (key: string) => key.slice(5).replace(/-([a-z])/g, (_, c) => c.toUpperCase()); |
5 | 5 |
|
6 | | - const act = { |
7 | | - // toggle:theme-test(dark,light) |
8 | | - toggle: (k: string, [on = 'on']: string[]) => { |
9 | | - document.body.dataset[k] = document.body.dataset[k] ? '' : on; |
10 | | - }, |
11 | | - // cycle:theme-test(dark,light) |
12 | | - cycle: (k: string, vals: string[]) => { |
13 | | - const cur = document.body.dataset[k] ?? vals[0]; |
14 | | - const next = vals[(vals.indexOf(cur) + 1) % vals.length]; |
15 | | - document.body.dataset[k] = next; |
16 | | - }, |
17 | | - // set:theme-test(dark) |
18 | | - set: (k: string, [v = '']: string[]) => { |
19 | | - document.body.dataset[k] = v; |
20 | | - }, |
21 | | - // attr:theme-test(data-theme) |
22 | | - attr: (k: string, [attr]: string[], el: HTMLElement) => { |
23 | | - document.body.dataset[k] = el.getAttribute(attr) ?? ''; |
24 | | - }, |
| 6 | + const cycle = (target: HTMLElement, k: string, vals: string[]) => { |
| 7 | + const cur = target.dataset[k] ?? vals[0]; // default = first value |
| 8 | + const next = vals[(vals.indexOf(cur) + 1) % vals.length]; |
| 9 | + target.dataset[k] = next; |
25 | 10 | }; |
26 | 11 |
|
27 | 12 | document.addEventListener('click', (e) => { |
28 | 13 | const el = (e.target as HTMLElement).closest<HTMLElement>('[data-ui]'); |
29 | 14 | if (!el) return; |
30 | 15 |
|
31 | | - const [, cmd, key, raw] = el.dataset.ui!.match(/^(\w+):([\w-]+)(?:\((.*?)\))?$/) || []; |
32 | | - if (!cmd || !(`data-${key}` in bodyAttributes)) return; |
| 16 | + const [, key, rawVals = ''] = el.dataset.ui!.match(/^cycle:([\w-]+)(?:\((.*?)\))?$/) || []; |
33 | 17 |
|
34 | | - const dsKey = toDatasetKey(`data-${key}`); |
35 | | - console.log('dsKey: ', dsKey); |
36 | | - act[cmd as keyof typeof act]?.(dsKey, raw ? raw.split(',') : [], el); |
| 18 | + if (!(`data-${key}` in bodyAttributes)) return; // unknown variant → bail |
| 19 | + |
| 20 | + const vals = rawVals.split(','); // '' → [''] OK for toggle |
| 21 | + const dsKey = toCamel(`data-${key}`); |
| 22 | + const target = (el.closest(`[data-${key}]`) as HTMLElement) ?? document.body; |
| 23 | + |
| 24 | + cycle(target, dsKey, vals); |
37 | 25 | }); |
38 | 26 | } |
0 commit comments