|
1 | 1 | import { useCallback } from 'react'; |
2 | 2 |
|
3 | | -// Convert kebab-case to camelCase for dataset API |
4 | | -// "theme-secondary" -> "themeSecondary" |
5 | | -function kebabToCamelCase(str) { |
6 | | - return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); |
7 | | -} |
8 | | - |
9 | 3 | function useUI(key, initialValue) { |
10 | | - const parseValue = stringValue => { |
11 | | - if (stringValue === null || stringValue === undefined) return initialValue; |
12 | | - |
13 | | - if (typeof initialValue === 'boolean') { |
14 | | - return stringValue === 'true'; |
15 | | - } else if (typeof initialValue === 'number') { |
16 | | - return Number(stringValue); |
17 | | - } else { |
18 | | - return stringValue; |
19 | | - } |
20 | | - }; |
21 | | - |
| 4 | + //setValue(valueOrUpdater) |
22 | 5 | const setValue = useCallback( |
23 | 6 | valueOrUpdater => { |
24 | | - if (typeof window === 'undefined' || typeof document === 'undefined') return; |
25 | | - const datasetKey = kebabToCamelCase(key); |
26 | | - const getCurrentValue = () => parseValue(document.body.dataset[datasetKey]); |
27 | | - |
| 7 | + if (typeof window === 'undefined') return; |
| 8 | + // Convert kebab-case to camelCase for dataset API |
| 9 | + // "theme-secondary" -> "themeSecondary" |
| 10 | + const camelKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); |
28 | 11 | let newValue; |
29 | 12 | if (typeof valueOrUpdater === 'function') { |
30 | | - newValue = valueOrUpdater(getCurrentValue()); |
| 13 | + const parse = v => { |
| 14 | + if (!v) return initialValue; |
| 15 | + switch (typeof initialValue) { |
| 16 | + case 'boolean': |
| 17 | + return v === 'true'; |
| 18 | + case 'number': { |
| 19 | + const n = Number(v); |
| 20 | + return isNaN(n) ? initialValue : n; |
| 21 | + } |
| 22 | + default: |
| 23 | + return v; |
| 24 | + } |
| 25 | + }; |
| 26 | + newValue = valueOrUpdater(parse(document.body.dataset[camelKey])); |
31 | 27 | } else { |
32 | 28 | newValue = valueOrUpdater; |
33 | 29 | } |
34 | | - document.body.dataset[datasetKey] = String(newValue); |
| 30 | + document.body.dataset[camelKey] = String(newValue); |
35 | 31 | }, |
36 | 32 | [key] |
37 | 33 | ); |
38 | | - |
39 | | - // The actual current value lives in the DOM! |
40 | 34 | return [initialValue, setValue]; |
41 | 35 | } |
42 | 36 |
|
|
0 commit comments