Skip to content

Commit d58ec1a

Browse files
committed
refactor: updated index useUI function
1 parent 1e6603d commit d58ec1a

File tree

1 file changed

+20
-26
lines changed

1 file changed

+20
-26
lines changed

packages/core/src/index.js

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,36 @@
11
import { useCallback } from 'react';
22

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-
93
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)
225
const setValue = useCallback(
236
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());
2811
let newValue;
2912
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]));
3127
} else {
3228
newValue = valueOrUpdater;
3329
}
34-
document.body.dataset[datasetKey] = String(newValue);
30+
document.body.dataset[camelKey] = String(newValue);
3531
},
3632
[key]
3733
);
38-
39-
// The actual current value lives in the DOM!
4034
return [initialValue, setValue];
4135
}
4236

0 commit comments

Comments
 (0)