@gateweb/react-utils 1.17.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,6 +30,8 @@ const createQueryStore = ({ query, handleChangeQuery })=>zustand.createStore()((
30
30
  const QueryContext = /*#__PURE__*/ React.createContext(null);
31
31
  /**
32
32
  * Provider to provide the store to the context
33
+ *
34
+ * @deprecated use `StoreProvider` from `core/store` instead
33
35
  */ const QueryProvider = ({ children, query, handleChangeQuery })=>{
34
36
  const storeRef = React.useRef(null);
35
37
  if (!storeRef.current) {
@@ -61,6 +63,8 @@ const QueryContext = /*#__PURE__*/ React.createContext(null);
61
63
  * const result2 = useQueryContext<MyObject>()(q => q.changeQuery);
62
64
  * const result3 = useQueryContext<MyObject>()(q => q.query);
63
65
  * ```
66
+ *
67
+ * @deprecated use `useStoreContext` from `core/store` instead
64
68
  */ const useQueryContext = ()=>{
65
69
  const store = React.useContext(QueryContext);
66
70
  if (!store) throw new Error('Missing QueryContext.Provider in the tree');
@@ -0,0 +1,122 @@
1
+ 'use client';
2
+ var React = require('react');
3
+ var zustand = require('zustand');
4
+ var traditional = require('zustand/traditional');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
+
8
+ var React__default = /*#__PURE__*/_interopDefault(React);
9
+
10
+ const isObject = (value)=>value !== null && typeof value === 'object';
11
+ /**
12
+ * merge two objects deeply
13
+ *
14
+ * @param target - the target object
15
+ * @param source - the source object
16
+ *
17
+ * @example
18
+ *
19
+ * const obja = { a: { a1: { a11: 'value 1', a12: 'value 2' }, a2: 'value 3' }, b: 'value 4' };
20
+ * const objb = { a: { a1: { a13: 'value 5', a14: 'value 6' }, a3: 'value 7' }};
21
+ *
22
+ * const mergeResult = deepMerge(obja, objb); // { a: { a1: { a11: 'value 1', a12: 'value 2', a13: 'value 5', a14: 'value 6' }, a2: 'value 3', a3: 'value 7' }, b: 'value 4' }
23
+ *
24
+ */ const deepMerge = (target, source)=>Object.entries(source).reduce((acc, [key, value])=>{
25
+ if (isObject(value)) {
26
+ acc[key] = key in target && isObject(target[key]) ? deepMerge(target[key], value) : value;
27
+ } else {
28
+ acc[key] = value;
29
+ }
30
+ return acc;
31
+ }, {
32
+ ...target
33
+ });
34
+
35
+ /**
36
+ * create a zustand store with changeStore method
37
+ */ const createZustandStore = ({ store, handleChangeStore, defaultMerge })=>zustand.createStore()((set)=>({
38
+ store,
39
+ changeStore: (updater, options)=>{
40
+ set((pre)=>{
41
+ const patch = typeof updater === 'function' ? updater(pre.store) : updater;
42
+ const newStore = handleChangeStore ? handleChangeStore(pre.store, patch) : patch;
43
+ const strategy = options?.merge ?? defaultMerge;
44
+ if (strategy === 'shallow') {
45
+ return {
46
+ store: {
47
+ ...pre.store,
48
+ ...newStore
49
+ }
50
+ };
51
+ }
52
+ return {
53
+ store: deepMerge(pre.store, newStore)
54
+ };
55
+ });
56
+ }
57
+ }));
58
+ /**
59
+ * create a store context with provider and hooks
60
+ *
61
+ * @example
62
+ *
63
+ * ```tsx
64
+ * // create a store context
65
+ * const { StoreProvider, useStore, useStoreApi } = createStoreContext<MyObject>();
66
+ *
67
+ * // use the StoreProvider to provide the store to the context
68
+ * <StoreProvider store={{ key: 'value' }}>
69
+ * <App />
70
+ * </StoreProvider>
71
+ * ```
72
+ */ const createStoreContext = ()=>{
73
+ const StoreContext = /*#__PURE__*/ React.createContext(null);
74
+ /**
75
+ * Provider to provide the store to the context
76
+ *
77
+ * @example
78
+ *
79
+ * ```tsx
80
+ * // use the StoreProvider to provide the store to the context
81
+ * const { StoreProvider } = createStoreContext<MyObject>();
82
+ *
83
+ * <StoreProvider store={{ key: 'value' }}>
84
+ * <App />
85
+ * </StoreProvider>
86
+ * ```
87
+ */ const StoreProvider = ({ children, store = {}, handleChangeStore, defaultMerge = 'shallow' })=>{
88
+ const storeRef = React.useRef(null);
89
+ if (!storeRef.current) {
90
+ storeRef.current = createZustandStore({
91
+ store,
92
+ handleChangeStore,
93
+ defaultMerge
94
+ });
95
+ }
96
+ return /*#__PURE__*/ React__default.default.createElement(StoreContext.Provider, {
97
+ value: storeRef.current
98
+ }, children);
99
+ };
100
+ /**
101
+ * a hook to get the store from the context
102
+ *
103
+ * @example
104
+ * ```tsx
105
+ * const { useStore } = createStoreContext<MyObject>();
106
+ * const value = useStore(s => s.store);
107
+ * ```
108
+ *
109
+ * @param selector - the selector to get the state from the store
110
+ * @param equalityFn - the equality function to compare the previous and next state
111
+ */ const useStore = (selector, equalityFn)=>{
112
+ const store = React.useContext(StoreContext);
113
+ if (!store) throw new Error('Missing StoreContext.Provider in the tree');
114
+ return traditional.useStoreWithEqualityFn(store, selector, equalityFn);
115
+ };
116
+ return {
117
+ StoreProvider,
118
+ useStore
119
+ };
120
+ };
121
+
122
+ exports.createStoreContext = createStoreContext;
@@ -0,0 +1,136 @@
1
+ 'use client';
2
+ /* eslint-disable no-bitwise */ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3
+ /**
4
+ * 將位元組陣列編碼為 base64 字串
5
+ *
6
+ * @param bytes 要編碼的位元組陣列
7
+ * @returns base64 編碼的字串
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const bytes = new TextEncoder().encode('Hello World');
12
+ * const encoded = encodeBase64(bytes);
13
+ * console.log(encoded); // 'SGVsbG8gV29ybGQ='
14
+ * ```
15
+ */ const encodeBase64 = (bytes)=>{
16
+ let out = '';
17
+ for(let i = 0; i < bytes.length; i += 3){
18
+ const n = bytes[i] << 16 | (bytes[i + 1] || 0) << 8 | (bytes[i + 2] || 0);
19
+ out += chars[n >> 18 & 63] + chars[n >> 12 & 63] + (i + 1 < bytes.length ? chars[n >> 6 & 63] : '=') + (i + 2 < bytes.length ? chars[n & 63] : '=');
20
+ }
21
+ return out;
22
+ };
23
+ /**
24
+ * 將 base64 字串解碼為位元組陣列
25
+ *
26
+ * @param base64 要解碼的 base64 字串(支援 base64url 格式)
27
+ * @returns 解碼後的位元組陣列
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const decoded = decodeBase64('SGVsbG8gV29ybGQ=');
32
+ * const text = new TextDecoder().decode(decoded);
33
+ * console.log(text); // 'Hello World'
34
+ * ```
35
+ */ const decodeBase64 = (base64)=>{
36
+ let out = base64.replace(/-/g, '+').replace(/_/g, '/'); // 支援 base64url
37
+ while(out.length % 4)out += '='; // 自動補 "="
38
+ const buffer = [];
39
+ for(let i = 0; i < out.length; i += 4){
40
+ const n = chars.indexOf(out[i]) << 18 | chars.indexOf(out[i + 1]) << 12 | (chars.indexOf(out[i + 2]) & 63) << 6 | chars.indexOf(out[i + 3]) & 63;
41
+ buffer.push(n >> 16 & 255);
42
+ if (out[i + 2] !== '=') buffer.push(n >> 8 & 255);
43
+ if (out[i + 3] !== '=') buffer.push(n & 255);
44
+ }
45
+ return new Uint8Array(buffer);
46
+ };
47
+ /**
48
+ * 將 JSON 資料編碼為 base64 字串
49
+ *
50
+ * @param data 要編碼的 JSON 可序列化資料
51
+ * @returns base64 編碼的字串
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * const data = { name: 'John', age: 30 };
56
+ * const encoded = encodeJson(data);
57
+ * console.log(encoded); // 'eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9'
58
+ *
59
+ * const array = [1, 2, 3];
60
+ * const encodedArray = encodeJson(array);
61
+ * ```
62
+ */ const encodeJson = (data)=>{
63
+ const json = JSON.stringify(data);
64
+ return encodeBase64(new TextEncoder().encode(json));
65
+ };
66
+ /**
67
+ * 將 base64 字串解碼為 JSON 資料
68
+ *
69
+ * @param b64 要解碼的 base64 字串
70
+ * @returns 解碼後的資料
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * const encoded = 'eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9';
75
+ * const decoded = decodeJson<{ name: string; age: number }>(encoded);
76
+ * console.log(decoded); // { name: 'John', age: 30 }
77
+ *
78
+ * const decodedArray = decodeJson<number[]>(encodedArray);
79
+ * ```
80
+ */ const decodeJson = (b64)=>{
81
+ const json = new TextDecoder().decode(decodeBase64(b64));
82
+ return JSON.parse(json);
83
+ };
84
+
85
+ /**
86
+ * 從 localStorage 取得資料,支援槽狀取值(Json 物件)
87
+ *
88
+ * @param key 鍵值
89
+ * @param deCode 是否解碼
90
+ * @returns 取得的資料
91
+ * @example
92
+ * const data = getLocalStorage('key');
93
+ *
94
+ * const data = getLocalStorage('key.subKey');
95
+ */ const getLocalStorage = (key, deCode = true)=>{
96
+ const keys = key.split('.');
97
+ const storage = localStorage.getItem(keys[0]);
98
+ if (!storage) return undefined;
99
+ let currentObject;
100
+ try {
101
+ if (deCode) {
102
+ currentObject = decodeJson(storage);
103
+ } else {
104
+ currentObject = JSON.parse(storage);
105
+ }
106
+ } catch (_error) {
107
+ return undefined;
108
+ }
109
+ // let currentObject = JSON.parse(storage);
110
+ if (keys.length === 1) {
111
+ return currentObject;
112
+ }
113
+ keys.shift();
114
+ while(keys.length > 0){
115
+ const currentKey = keys.shift();
116
+ if (!currentKey) break;
117
+ currentObject = currentObject[currentKey];
118
+ if (!currentObject) break;
119
+ }
120
+ return currentObject;
121
+ };
122
+ /**
123
+ * 將資料(Json 物件)存入 localStorage
124
+ * @param key 鍵值
125
+ * @param value 可序列化的資料
126
+ * @param enCode 是否編碼
127
+ */ const setLocalStorage = (key, value, enCode = true)=>{
128
+ if (enCode) {
129
+ localStorage.setItem(key, encodeJson(value));
130
+ } else {
131
+ localStorage.setItem(key, JSON.stringify(value));
132
+ }
133
+ };
134
+
135
+ exports.getLocalStorage = getLocalStorage;
136
+ exports.setLocalStorage = setLocalStorage;
@@ -0,0 +1,289 @@
1
+ import React, { ReactNode } from 'react';
2
+ import { AtLeastOne } from './types.mjs';
3
+
4
+ type TStoreProps<S> = {
5
+ /**
6
+ * the store object
7
+ */
8
+ store: Partial<S>;
9
+ };
10
+ type TStoreObject<S> = TStoreProps<S>['store'];
11
+ type TStoreState<S> = {
12
+ /**
13
+ * trigger the change of store
14
+ *
15
+ * @param updater - the new store or a update function
16
+ * @param options - the options for changing the store
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * // update with new store object
21
+ * changeStore({ key: 'newValue' });
22
+ * // update with a function
23
+ * changeStore(preStore => ({ ...preStore, key: 'newValue' }));
24
+ * ```
25
+ */
26
+ changeStore: (updater: TStoreObject<S> | ((preStore: TStoreObject<S>) => TStoreObject<S>), options?: {
27
+ merge: TInitialProps$1<S>['defaultMerge'];
28
+ }) => void;
29
+ } & TStoreProps<S>;
30
+ type TInitialProps$1<S> = TStoreProps<S> & {
31
+ /**
32
+ * handle the change of store when calling `changeStore`
33
+ *
34
+ * @param preStore - the previous store
35
+ * @param newStore - the new store
36
+ *
37
+ * @example
38
+ *
39
+ * ```tsx
40
+ * <StoreProvider store={{ key: 'value' }} handleChangeStore={(preStore, newStore) => {
41
+ * // Special handling: reset key when changing anotherKey
42
+ * if (newStore.anotherKey && newStore.anotherKey !== preStore.anotherKey) {
43
+ * return {
44
+ * ...preStore,
45
+ * ...newStore,
46
+ * key: 'resetValue',
47
+ * };
48
+ * }
49
+ * return {
50
+ * ...preStore,
51
+ * ...newStore,
52
+ * };
53
+ * }}>
54
+ * <App />
55
+ * </StoreProvider>
56
+ * ```
57
+ */
58
+ handleChangeStore?: (preStore: TStoreObject<S>, newStore: TStoreObject<S>) => TStoreObject<S>;
59
+ /**
60
+ * the default merge strategy when calling `changeStore`
61
+ *
62
+ * @default 'shallow'
63
+ *
64
+ * @example
65
+ *
66
+ * ```tsx
67
+ * // shallow merge
68
+ * <StoreProvider store={{ key: 'value', anotherKey: { nestedKey: 'nestedValue' } }}>
69
+ * // deep merge
70
+ * <StoreProvider store={{ key: 'value', anotherKey: { nestedKey: 'nestedValue' } }} defaultMerge="deep">
71
+ * ```
72
+ */
73
+ defaultMerge: 'shallow' | 'deep';
74
+ };
75
+ /**
76
+ * create a store context with provider and hooks
77
+ *
78
+ * @example
79
+ *
80
+ * ```tsx
81
+ * // create a store context
82
+ * const { StoreProvider, useStore, useStoreApi } = createStoreContext<MyObject>();
83
+ *
84
+ * // use the StoreProvider to provide the store to the context
85
+ * <StoreProvider store={{ key: 'value' }}>
86
+ * <App />
87
+ * </StoreProvider>
88
+ * ```
89
+ */
90
+ declare const createStoreContext: <S>() => {
91
+ StoreProvider: ({ children, store, handleChangeStore, defaultMerge, }: React.PropsWithChildren<Partial<TInitialProps$1<S>>>) => React.JSX.Element;
92
+ useStore: <T>(selector: (state: TStoreState<S>) => T, equalityFn?: (left: T, right: T) => boolean) => T;
93
+ };
94
+
95
+ type TQueryProps<Q> = {
96
+ /**
97
+ * the query object
98
+ */
99
+ query: Partial<Q>;
100
+ };
101
+ type TQueryState<Q> = {
102
+ /**
103
+ * trigger the change of query
104
+ *
105
+ * @param query - the new query
106
+ */
107
+ changeQuery: (query: TQueryProps<Q>['query']) => void;
108
+ } & TQueryProps<Q>;
109
+ type TInitialProps<Q> = Partial<TQueryProps<Q> & {
110
+ /**
111
+ * handle the change of query when calling `changeQuery`
112
+ *
113
+ * @param preQuery - the previous query
114
+ * @param newQuery - the new query
115
+ * @returns the custom new query
116
+ */
117
+ handleChangeQuery: (preQuery: TQueryProps<Q>['query'], newQuery: TQueryProps<Q>['query']) => TQueryProps<Q>['query'];
118
+ }>;
119
+ /**
120
+ * Provider to provide the store to the context
121
+ *
122
+ * @deprecated use `StoreProvider` from `core/store` instead
123
+ */
124
+ declare const QueryProvider: <Q>({ children, query, handleChangeQuery, }: React.PropsWithChildren<TInitialProps<Q>>) => React.JSX.Element;
125
+ /**
126
+ * hook to get the store from the context
127
+ *
128
+ * because we want the return type of `selector` to be inferred by ts, we use HOF to implement the hook
129
+ *
130
+ * so you should use it like this:
131
+ *
132
+ * ```tsx
133
+ * const useQuery = useQueryContext<MyObject>(); // => will return the store hook
134
+ * const result = useQuery(q => q.query); // => will return the query object
135
+ * ```
136
+ *
137
+ * @example
138
+ *
139
+ * ```tsx
140
+ * const result1 = useQueryContext<MyObject>()(q => '1234');
141
+ * const result2 = useQueryContext<MyObject>()(q => q.changeQuery);
142
+ * const result3 = useQueryContext<MyObject>()(q => q.query);
143
+ * ```
144
+ *
145
+ * @deprecated use `useStoreContext` from `core/store` instead
146
+ */
147
+ declare const useQueryContext: <Q>() => <T>(selector: (state: TQueryState<Q>) => T, equalityFn?: (left: T, right: T) => boolean) => T;
148
+
149
+ /**
150
+ * Creates a strongly-typed React Context and Provider pair for data sharing.
151
+ *
152
+ * This utility helps you avoid prop drilling by providing a reusable way to define
153
+ * context with strict type inference. It returns a custom hook for consuming the context
154
+ * and a Provider component for supplying context values.
155
+ *
156
+ * @template T - The value type for the context.
157
+ * @returns {object} An object containing:
158
+ * - useDataContext: A custom hook to access the context value. Throws an error if used outside the provider.
159
+ * - DataProvider: A Provider component to wrap your component tree and supply the context value.
160
+ *
161
+ * @example
162
+ * // Example usage:
163
+ * const { useDataContext, DataProvider } = createDataContext<{ count: number }>();
164
+ *
165
+ * function Counter() {
166
+ * const { count } = useDataContext();
167
+ * return <span>{count}</span>;
168
+ * }
169
+ *
170
+ * function App() {
171
+ * return (
172
+ * <DataProvider value={{ count: 42 }}>
173
+ * <Counter />
174
+ * </DataProvider>
175
+ * );
176
+ * }
177
+ */
178
+ declare const createDataContext: <T>() => {
179
+ readonly useDataContext: () => T & ({} | null);
180
+ readonly DataProvider: ({ children, value }: {
181
+ children: ReactNode;
182
+ value: T;
183
+ }) => React.JSX.Element;
184
+ };
185
+
186
+ type TCountdownActions = {
187
+ /** 目前秒數 */
188
+ countdown: number;
189
+ /** 是否正在倒數計時 */
190
+ isCounting: boolean;
191
+ /** 開始倒數計時 */
192
+ start: () => void;
193
+ /** 停止倒數計時 */
194
+ stop: () => void;
195
+ /** 重置倒數計時 */
196
+ reset: () => void;
197
+ };
198
+ /**
199
+ * 倒數計時器
200
+ *
201
+ * 可以透過 start() 來啟動倒數計時器
202
+ * 可以透過 stop() 來停止倒數計時器
203
+ * 可以透過 reset() 來重置倒數計時器
204
+ *
205
+ * @param initialCountdown 倒數計時器初始值
206
+ * @param enableReinitialize 允許重設初始值
207
+ */
208
+ declare const useCountdown: (initialCountdown: number, enableReinitialize?: boolean) => TCountdownActions;
209
+
210
+ type UseDisclosureReturn = {
211
+ /** Whether the disclosure is currently open. */
212
+ isOpen: boolean;
213
+ /** Open the disclosure (sets isOpen = true). */
214
+ open: () => void;
215
+ /** Close the disclosure (sets isOpen = false). */
216
+ close: () => void;
217
+ /** Toggle the disclosure state (open -> close or close -> open). */
218
+ toggle: () => void;
219
+ };
220
+ /**
221
+ * A small hook to control open/close state.
222
+ *
223
+ * Supports an optional controlled pattern by passing `isOpen` and `onChange`.
224
+ *
225
+ * @example
226
+ * const { isOpen, open, close, toggle } = useDisclosure();
227
+ */
228
+ declare function useDisclosure(initialState?: boolean): UseDisclosureReturn;
229
+
230
+ type TValueOptions<T> = AtLeastOne<{
231
+ /**
232
+ * The controlled value.
233
+ */
234
+ value?: T;
235
+ /**
236
+ * The default value.
237
+ */
238
+ defaultValue?: T;
239
+ }>;
240
+ /**
241
+ * A hook to manage a value.
242
+ *
243
+ * @example
244
+ *
245
+ * ```tsx
246
+ * const MyComponent = ({ value }: { value?: number }) => {
247
+ * const [currentValue, setCurrentValue] = useValue({ value });
248
+ * };
249
+ * ```
250
+ */
251
+ declare const useValue: <T>({ value, defaultValue }: TValueOptions<T>) => readonly [T, (newValue: T) => void];
252
+
253
+ declare function mergeRefs<T = any>(refs: Array<React.MutableRefObject<T> | React.LegacyRef<T> | undefined | null>): React.RefCallback<T>;
254
+
255
+ /**
256
+ * Downloads a file from a given source.
257
+ *
258
+ * @param source - The source of the file to be downloaded. It can be a URL string or a Blob object.
259
+ * @param filename - The name of the file to be downloaded. Defaults to the current timestamp if not provided.
260
+ * @param fileExtension - The file extension to be appended to the filename. Optional.
261
+ *
262
+ * @example
263
+ * downloadFile('http://example.com/file.txt', 'testfile', 'txt');
264
+ * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
265
+ */
266
+ declare const downloadFile: (source: string | Blob, filename?: string, fileExtension?: string) => void;
267
+
268
+ /**
269
+ * 從 localStorage 取得資料,支援槽狀取值(Json 物件)
270
+ *
271
+ * @param key 鍵值
272
+ * @param deCode 是否解碼
273
+ * @returns 取得的資料
274
+ * @example
275
+ * const data = getLocalStorage('key');
276
+ *
277
+ * const data = getLocalStorage('key.subKey');
278
+ */
279
+ declare const getLocalStorage: <T>(key: string, deCode?: boolean) => T | undefined;
280
+ /**
281
+ * 將資料(Json 物件)存入 localStorage
282
+ * @param key 鍵值
283
+ * @param value 可序列化的資料
284
+ * @param enCode 是否編碼
285
+ */
286
+ declare const setLocalStorage: (key: string, value: Record<string, any>, enCode?: boolean) => void;
287
+
288
+ export { QueryProvider, createDataContext, createStoreContext, downloadFile, getLocalStorage, mergeRefs, setLocalStorage, useCountdown, useDisclosure, useQueryContext, useValue };
289
+ export type { TCountdownActions, UseDisclosureReturn };
@@ -0,0 +1,103 @@
1
+ export { c as createStoreContext } from './store-12s-DsXc3Uo0.mjs';
2
+ export { Q as QueryProvider, u as useQueryContext } from './queryStore-12s-Dkb-Af1n.mjs';
3
+ import React, { useMemo, createContext, useContext, useState, useCallback } from 'react';
4
+ export { u as useCountdown } from './useCountdown-12s-t52WIHfq.mjs';
5
+ export { u as useDisclosure } from './useDisclosure-12s-BQAHpAXK.mjs';
6
+ export { d as downloadFile } from './download-12s-CnaJ0p_f.mjs';
7
+ export { g as getLocalStorage, s as setLocalStorage } from './webStorage-12s-Bo7x8q5t.mjs';
8
+
9
+ /**
10
+ * Creates a strongly-typed React Context and Provider pair for data sharing.
11
+ *
12
+ * This utility helps you avoid prop drilling by providing a reusable way to define
13
+ * context with strict type inference. It returns a custom hook for consuming the context
14
+ * and a Provider component for supplying context values.
15
+ *
16
+ * @template T - The value type for the context.
17
+ * @returns {object} An object containing:
18
+ * - useDataContext: A custom hook to access the context value. Throws an error if used outside the provider.
19
+ * - DataProvider: A Provider component to wrap your component tree and supply the context value.
20
+ *
21
+ * @example
22
+ * // Example usage:
23
+ * const { useDataContext, DataProvider } = createDataContext<{ count: number }>();
24
+ *
25
+ * function Counter() {
26
+ * const { count } = useDataContext();
27
+ * return <span>{count}</span>;
28
+ * }
29
+ *
30
+ * function App() {
31
+ * return (
32
+ * <DataProvider value={{ count: 42 }}>
33
+ * <Counter />
34
+ * </DataProvider>
35
+ * );
36
+ * }
37
+ */ const createDataContext = ()=>{
38
+ const Context = /*#__PURE__*/ createContext(undefined);
39
+ const useDataContext = ()=>{
40
+ const context = useContext(Context);
41
+ if (context === undefined) {
42
+ throw new Error(`useDataContext must be used within a DataProvider`);
43
+ }
44
+ return context;
45
+ };
46
+ const DataProvider = ({ children, value })=>{
47
+ const memoized = useMemo(()=>value, [
48
+ value
49
+ ]);
50
+ return /*#__PURE__*/ React.createElement(Context.Provider, {
51
+ value: memoized
52
+ }, children);
53
+ };
54
+ return {
55
+ useDataContext,
56
+ DataProvider
57
+ };
58
+ };
59
+
60
+ /**
61
+ * A hook to manage a value.
62
+ *
63
+ * @example
64
+ *
65
+ * ```tsx
66
+ * const MyComponent = ({ value }: { value?: number }) => {
67
+ * const [currentValue, setCurrentValue] = useValue({ value });
68
+ * };
69
+ * ```
70
+ */ const useValue = ({ value, defaultValue })=>{
71
+ if (value === undefined && defaultValue === undefined) {
72
+ throw new Error('Either `value` or `defaultValue` must be provided.');
73
+ }
74
+ const isControlled = value !== undefined;
75
+ const [internalValue, setInternalValue] = useState(defaultValue);
76
+ const setValue = useCallback((newValue)=>{
77
+ if (!isControlled) {
78
+ setInternalValue(newValue);
79
+ }
80
+ }, [
81
+ isControlled
82
+ ]);
83
+ const currentValue = isControlled ? value : internalValue;
84
+ return [
85
+ currentValue,
86
+ setValue
87
+ ];
88
+ };
89
+
90
+ function mergeRefs(refs) {
91
+ return (value)=>{
92
+ refs.forEach((ref)=>{
93
+ if (typeof ref === 'function') {
94
+ ref(value);
95
+ } else if (ref != null) {
96
+ // eslint-disable-next-line no-param-reassign
97
+ ref.current = value;
98
+ }
99
+ });
100
+ };
101
+ }
102
+
103
+ export { createDataContext, mergeRefs, useValue };