react-hooks-core 1.0.2 → 1.1.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.
@@ -0,0 +1,292 @@
1
+ import { useState, useRef, useEffect, useCallback } from 'react';
2
+
3
+ // src/storage/hooks/useStorage.ts
4
+ var StoragePollingManager = class {
5
+ constructor() {
6
+ this.intervalId = null;
7
+ this.subscribers = /* @__PURE__ */ new Set();
8
+ this.POLL_INTERVAL = 2e3;
9
+ }
10
+ // 2 seconds - longer interval to reduce overhead
11
+ subscribe(callback) {
12
+ this.subscribers.add(callback);
13
+ if (this.subscribers.size === 1 && this.intervalId === null) {
14
+ this.startPolling();
15
+ }
16
+ return () => {
17
+ this.subscribers.delete(callback);
18
+ if (this.subscribers.size === 0 && this.intervalId !== null) {
19
+ this.stopPolling();
20
+ }
21
+ };
22
+ }
23
+ startPolling() {
24
+ if (typeof window === "undefined") {
25
+ return;
26
+ }
27
+ this.intervalId = setInterval(() => {
28
+ this.subscribers.forEach((callback) => {
29
+ try {
30
+ callback();
31
+ } catch (error) {
32
+ }
33
+ });
34
+ }, this.POLL_INTERVAL);
35
+ }
36
+ stopPolling() {
37
+ if (this.intervalId !== null) {
38
+ if (typeof clearInterval !== "undefined") {
39
+ clearInterval(this.intervalId);
40
+ }
41
+ this.intervalId = null;
42
+ }
43
+ }
44
+ };
45
+ var pollingManager = new StoragePollingManager();
46
+ function useStorage(key, options) {
47
+ const {
48
+ storageType = "localStorage",
49
+ defaultValue = null,
50
+ sync = false,
51
+ cookieOptions,
52
+ onChange
53
+ } = options || {};
54
+ const [value, setValueState] = useState(() => {
55
+ if (typeof window === "undefined") {
56
+ return defaultValue ?? null;
57
+ }
58
+ try {
59
+ let rawValue = null;
60
+ if (storageType === "cookie") {
61
+ rawValue = getCookie(key);
62
+ } else if (storageType === "localStorage") {
63
+ rawValue = window.localStorage.getItem(key);
64
+ } else if (storageType === "sessionStorage") {
65
+ rawValue = window.sessionStorage.getItem(key);
66
+ }
67
+ if (rawValue === null) {
68
+ return defaultValue ?? null;
69
+ }
70
+ try {
71
+ const parsed = JSON.parse(rawValue);
72
+ return parsed;
73
+ } catch {
74
+ return rawValue;
75
+ }
76
+ } catch (error) {
77
+ console.warn(`Error reading storage for key "${key}":`, error);
78
+ return defaultValue ?? null;
79
+ }
80
+ });
81
+ const onChangeRef = useRef(onChange);
82
+ const keyRef = useRef(key);
83
+ const storageTypeRef = useRef(storageType);
84
+ const lastValueRef = useRef(null);
85
+ useEffect(() => {
86
+ onChangeRef.current = onChange;
87
+ keyRef.current = key;
88
+ storageTypeRef.current = storageType;
89
+ }, [onChange, key, storageType]);
90
+ const setValue = useCallback(
91
+ (newValue) => {
92
+ if (typeof window === "undefined") {
93
+ return;
94
+ }
95
+ try {
96
+ const storageKey = keyRef.current;
97
+ const type = storageTypeRef.current;
98
+ if (newValue === null) {
99
+ if (type === "cookie") {
100
+ removeCookie(storageKey, cookieOptions);
101
+ lastValueRef.current = null;
102
+ } else if (type === "localStorage") {
103
+ window.localStorage.removeItem(storageKey);
104
+ lastValueRef.current = null;
105
+ } else if (type === "sessionStorage") {
106
+ window.sessionStorage.removeItem(storageKey);
107
+ lastValueRef.current = null;
108
+ }
109
+ } else {
110
+ const stringValue = typeof newValue === "string" ? newValue : JSON.stringify(newValue);
111
+ if (type === "cookie") {
112
+ setCookie(storageKey, stringValue, cookieOptions);
113
+ lastValueRef.current = stringValue;
114
+ } else if (type === "localStorage") {
115
+ window.localStorage.setItem(storageKey, stringValue);
116
+ lastValueRef.current = stringValue;
117
+ } else if (type === "sessionStorage") {
118
+ window.sessionStorage.setItem(storageKey, stringValue);
119
+ lastValueRef.current = stringValue;
120
+ }
121
+ }
122
+ setValueState(newValue);
123
+ onChangeRef.current?.(newValue);
124
+ } catch (error) {
125
+ console.warn(`Error setting ${storageTypeRef.current} for key "${keyRef.current}":`, error);
126
+ }
127
+ },
128
+ [cookieOptions]
129
+ );
130
+ const removeValue = useCallback(() => {
131
+ setValue(null);
132
+ }, [setValue]);
133
+ const clear = useCallback(() => {
134
+ if (typeof window === "undefined") {
135
+ return;
136
+ }
137
+ try {
138
+ const type = storageTypeRef.current;
139
+ if (type === "localStorage") {
140
+ window.localStorage.clear();
141
+ } else if (type === "sessionStorage") {
142
+ window.sessionStorage.clear();
143
+ }
144
+ } catch (error) {
145
+ console.warn(`Error clearing ${storageTypeRef.current}:`, error);
146
+ }
147
+ }, []);
148
+ const hasValue = value !== null;
149
+ useEffect(() => {
150
+ if (typeof window === "undefined" || !sync || storageType !== "localStorage") {
151
+ return;
152
+ }
153
+ const handleStorageChange = (e) => {
154
+ if (e.key === key && e.storageArea === window.localStorage) {
155
+ const rawValue = e.newValue;
156
+ lastValueRef.current = rawValue;
157
+ let newValue = null;
158
+ if (rawValue !== null) {
159
+ try {
160
+ newValue = JSON.parse(rawValue);
161
+ } catch {
162
+ newValue = rawValue;
163
+ }
164
+ }
165
+ setValueState(newValue);
166
+ onChangeRef.current?.(newValue);
167
+ }
168
+ };
169
+ window.addEventListener("storage", handleStorageChange);
170
+ return () => {
171
+ window.removeEventListener("storage", handleStorageChange);
172
+ };
173
+ }, [key, sync, storageType]);
174
+ useEffect(() => {
175
+ if (typeof window === "undefined") {
176
+ return;
177
+ }
178
+ const type = storageTypeRef.current;
179
+ if (sync && type === "localStorage") {
180
+ return;
181
+ }
182
+ const checkValue = () => {
183
+ try {
184
+ const storageKey2 = keyRef.current;
185
+ const currentType = storageTypeRef.current;
186
+ let rawValue = null;
187
+ if (currentType === "cookie") {
188
+ rawValue = getCookie(storageKey2);
189
+ } else if (currentType === "localStorage") {
190
+ rawValue = window.localStorage.getItem(storageKey2);
191
+ } else if (currentType === "sessionStorage") {
192
+ rawValue = window.sessionStorage.getItem(storageKey2);
193
+ }
194
+ if (rawValue !== lastValueRef.current) {
195
+ lastValueRef.current = rawValue;
196
+ let currentValue = null;
197
+ if (rawValue !== null) {
198
+ try {
199
+ currentValue = JSON.parse(rawValue);
200
+ } catch {
201
+ currentValue = rawValue;
202
+ }
203
+ }
204
+ setValueState(currentValue);
205
+ onChangeRef.current?.(currentValue);
206
+ }
207
+ } catch (error) {
208
+ }
209
+ };
210
+ const storageKey = keyRef.current;
211
+ try {
212
+ if (type === "cookie") {
213
+ lastValueRef.current = getCookie(storageKey);
214
+ } else if (type === "localStorage") {
215
+ lastValueRef.current = window.localStorage.getItem(storageKey);
216
+ } else if (type === "sessionStorage") {
217
+ lastValueRef.current = window.sessionStorage.getItem(storageKey);
218
+ }
219
+ } catch (error) {
220
+ lastValueRef.current = null;
221
+ }
222
+ const unsubscribe = pollingManager.subscribe(checkValue);
223
+ return () => {
224
+ unsubscribe();
225
+ lastValueRef.current = null;
226
+ };
227
+ }, [key, storageType, sync]);
228
+ return {
229
+ value,
230
+ setValue,
231
+ removeValue,
232
+ hasValue,
233
+ clear
234
+ };
235
+ }
236
+ function getCookie(name) {
237
+ if (typeof document === "undefined") {
238
+ return null;
239
+ }
240
+ const nameEQ = name + "=";
241
+ const cookies = document.cookie.split(";");
242
+ for (let i = 0; i < cookies.length; i++) {
243
+ let cookie = cookies[i];
244
+ while (cookie.charAt(0) === " ") {
245
+ cookie = cookie.substring(1, cookie.length);
246
+ }
247
+ if (cookie.indexOf(nameEQ) === 0) {
248
+ return decodeURIComponent(cookie.substring(nameEQ.length, cookie.length));
249
+ }
250
+ }
251
+ return null;
252
+ }
253
+ function setCookie(name, value, options) {
254
+ if (typeof document === "undefined") {
255
+ return;
256
+ }
257
+ const { expires, path = "/", domain, secure = false, sameSite = "Lax" } = options || {};
258
+ let cookieString = `${name}=${encodeURIComponent(value)}`;
259
+ if (expires !== void 0 && expires !== 0) {
260
+ const date = /* @__PURE__ */ new Date();
261
+ date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1e3);
262
+ cookieString += `; expires=${date.toUTCString()}`;
263
+ } else if (expires === void 0) {
264
+ const date = /* @__PURE__ */ new Date();
265
+ date.setTime(date.getTime() + 365 * 24 * 60 * 60 * 1e3);
266
+ cookieString += `; expires=${date.toUTCString()}`;
267
+ }
268
+ cookieString += `; path=${path}`;
269
+ if (domain) {
270
+ cookieString += `; domain=${domain}`;
271
+ }
272
+ if (secure) {
273
+ cookieString += "; secure";
274
+ }
275
+ cookieString += `; SameSite=${sameSite}`;
276
+ document.cookie = cookieString;
277
+ }
278
+ function removeCookie(name, options) {
279
+ if (typeof document === "undefined") {
280
+ return;
281
+ }
282
+ const { path = "/", domain } = options || {};
283
+ let cookieString = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
284
+ if (domain) {
285
+ cookieString += `; domain=${domain}`;
286
+ }
287
+ document.cookie = cookieString;
288
+ }
289
+
290
+ export { useStorage };
291
+ //# sourceMappingURL=chunk-3OHPGV6V.mjs.map
292
+ //# sourceMappingURL=chunk-3OHPGV6V.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/hooks/useStorage.ts"],"names":["storageKey"],"mappings":";;;AAOA,IAAM,wBAAN,MAA4B;AAAA,EAA5B,WAAA,GAAA;AACE,IAAA,IAAA,CAAQ,UAAA,GAAoC,IAAA;AAC5C,IAAA,IAAA,CAAQ,WAAA,uBAAmC,GAAA,EAAI;AAC/C,IAAA,IAAA,CAAiB,aAAA,GAAgB,GAAA;AAAA,EAAA;AAAA;AAAA,EAEjC,UAAU,QAAA,EAAkC;AAC1C,IAAA,IAAA,CAAK,WAAA,CAAY,IAAI,QAAQ,CAAA;AAG7B,IAAA,IAAI,KAAK,WAAA,CAAY,IAAA,KAAS,CAAA,IAAK,IAAA,CAAK,eAAe,IAAA,EAAM;AAC3D,MAAA,IAAA,CAAK,YAAA,EAAa;AAAA,IACpB;AAGA,IAAA,OAAO,MAAM;AACX,MAAA,IAAA,CAAK,WAAA,CAAY,OAAO,QAAQ,CAAA;AAGhC,MAAA,IAAI,KAAK,WAAA,CAAY,IAAA,KAAS,CAAA,IAAK,IAAA,CAAK,eAAe,IAAA,EAAM;AAC3D,QAAA,IAAA,C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AAE,IAAA,GAAO,GAAA,EAAK,MAAA,EAAO,GAAI,WAAW,EAAC;AAE3C,EAAA,IAAI,YAAA,GAAe,CAAA,EAAG,IAAI,CAAA,+CAAA,EAAkD,IAAI,CAAA,CAAA;AAEhF,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,YAAA,IAAgB,YAAY,MAAM,CAAA,CAAA;AAAA,EACpC;AAEA,EAAA,QAAA,CAAS,MAAA,GAAS,YAAA;AACpB","file":"chunk-3OHPGV6V.mjs","sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react'\nimport type { IUseStorageOptions, IUseStorageReturn, StorageValue } from '../interface'\n\n/**\n * Shared polling manager for all useStorage hooks\n * Prevents multiple intervals when using multiple hooks\n */\nclass StoragePollingManager {\n private intervalId: NodeJS.Timeout | null = null\n private subscribers: Set<() => void> = new Set()\n private readonly POLL_INTERVAL = 2000 // 2 seconds - longer interval to reduce overhead\n\n subscribe(callback: () => void): () => void {\n this.subscribers.add(callback)\n\n // Start polling if this is the first subscriber\n if (this.subscribers.size === 1 && this.intervalId === null) {\n this.startPolling()\n }\n\n // Return unsubscribe function\n return () => {\n this.subscribers.delete(callback)\n\n // Stop polling if no more subscribers\n if (this.subscribers.size === 0 && this.intervalId !== null) {\n this.stopPolling()\n }\n }\n }\n\n private startPolling(): void {\n if (typeof window === 'undefined') {\n return\n }\n\n this.intervalId = setInterval(() => {\n // Notify all subscribers\n this.subscribers.forEach((callback) => {\n try {\n callback()\n } catch (error) {\n // Silently handle errors in callbacks\n }\n })\n }, this.POLL_INTERVAL)\n }\n\n private stopPolling(): void {\n if (this.intervalId !== null) {\n if (typeof clearInterval !== 'undefined') {\n clearInterval(this.intervalId)\n }\n this.intervalId = null\n }\n }\n}\n\n// Singleton instance\nconst pollingManager = new StoragePollingManager()\n\n/**\n * Hook for managing storage (localStorage, sessionStorage, or cookies)\n * Supports string, number, boolean, array, and JSON object values\n *\n * @template T - Type of the stored value\n * @param {string} key - Storage key\n * @param {IUseStorageOptions<T>} options - Optional configuration\n * @returns {IUseStorageReturn<T>} Storage management object\n *\n * @example\n * ```tsx\n * function App() {\n * const { value, setValue, removeValue } = useStorage('user', {\n * defaultValue: null,\n * storageType: 'localStorage'\n * })\n *\n * return (\n * <div>\n * <p>Value: {JSON.stringify(value)}</p>\n * <button onClick={() => setValue({ name: 'John' })}>Set Value</button>\n * <button onClick={removeValue}>Remove</button>\n * </div>\n * )\n * }\n * ```\n *\n * @see https://github.com/yourusername/react-hookify#usestorage\n */\nexport function useStorage<T extends StorageValue = StorageValue>(\n key: string,\n options?: IUseStorageOptions<T>\n): IUseStorageReturn<T> {\n const {\n storageType = 'localStorage',\n defaultValue = null,\n sync = false,\n cookieOptions,\n onChange,\n } = options || {}\n\n // SSR-safe initialization\n const [value, setValueState] = useState<T | null>(() => {\n if (typeof window === 'undefined') {\n return defaultValue ?? null\n }\n\n try {\n let rawValue: string | null = null\n\n if (storageType === 'cookie') {\n rawValue = getCookie(key)\n } else if (storageType === 'localStorage') {\n rawValue = window.localStorage.getItem(key)\n } else if (storageType === 'sessionStorage') {\n rawValue = window.sessionStorage.getItem(key)\n }\n\n if (rawValue === null) {\n return defaultValue ?? null\n }\n\n // Try to parse as JSON first, fallback to string\n try {\n const parsed = JSON.parse(rawValue)\n return parsed as T\n } catch {\n // If not JSON, return as string (handles plain strings stored without JSON.stringify)\n return rawValue as T\n }\n } catch (error) {\n console.warn(`Error reading storage for key \"${key}\":`, error)\n return defaultValue ?? null\n }\n })\n\n const onChangeRef = useRef(onChange)\n const keyRef = useRef(key)\n const storageTypeRef = useRef(storageType)\n const lastValueRef = useRef<string | null>(null) // Track last raw value for polling optimization\n\n // Update refs\n useEffect(() => {\n onChangeRef.current = onChange\n keyRef.current = key\n storageTypeRef.current = storageType\n }, [onChange, key, storageType])\n\n // Set value in storage\n const setValue = useCallback(\n (newValue: T | null) => {\n if (typeof window === 'undefined') {\n return\n }\n\n try {\n const storageKey = keyRef.current\n const type = storageTypeRef.current\n\n if (newValue === null) {\n // Remove value\n if (type === 'cookie') {\n removeCookie(storageKey, cookieOptions)\n lastValueRef.current = null\n } else if (type === 'localStorage') {\n window.localStorage.removeItem(storageKey)\n lastValueRef.current = null\n } else if (type === 'sessionStorage') {\n window.sessionStorage.removeItem(storageKey)\n lastValueRef.current = null\n }\n } else {\n // Store value - serialize based on type for efficiency\n // Strings are stored as-is, other types are JSON stringified\n const stringValue = typeof newValue === 'string' ? newValue : JSON.stringify(newValue)\n\n if (type === 'cookie') {\n setCookie(storageKey, stringValue, cookieOptions)\n lastValueRef.current = stringValue\n } else if (type === 'localStorage') {\n window.localStorage.setItem(storageKey, stringValue)\n lastValueRef.current = stringValue\n } else if (type === 'sessionStorage') {\n window.sessionStorage.setItem(storageKey, stringValue)\n lastValueRef.current = stringValue\n }\n }\n\n setValueState(newValue)\n onChangeRef.current?.(newValue)\n } catch (error) {\n console.warn(`Error setting ${storageTypeRef.current} for key \"${keyRef.current}\":`, error)\n }\n },\n [cookieOptions]\n )\n\n // Remove value from storage\n const removeValue = useCallback(() => {\n setValue(null)\n }, [setValue])\n\n // Clear all storage (only for localStorage/sessionStorage)\n const clear = useCallback(() => {\n if (typeof window === 'undefined') {\n return\n }\n\n try {\n const type = storageTypeRef.current\n if (type === 'localStorage') {\n window.localStorage.clear()\n } else if (type === 'sessionStorage') {\n window.sessionStorage.clear()\n }\n // Cookies cannot be cleared all at once\n } catch (error) {\n console.warn(`Error clearing ${storageTypeRef.current}:`, error)\n }\n }, [])\n\n // Check if value exists\n const hasValue = value !== null\n\n // Sync with other tabs/windows (only for localStorage)\n useEffect(() => {\n if (typeof window === 'undefined' || !sync || storageType !== 'localStorage') {\n return\n }\n\n const handleStorageChange = (e: StorageEvent) => {\n if (e.key === key && e.storageArea === window.localStorage) {\n const rawValue = e.newValue\n lastValueRef.current = rawValue\n\n let newValue: T | null = null\n if (rawValue !== null) {\n try {\n // Try to parse as JSON first\n newValue = JSON.parse(rawValue) as T\n } catch {\n // If not JSON, treat as string\n newValue = rawValue as T\n }\n }\n\n setValueState(newValue)\n onChangeRef.current?.(newValue)\n }\n }\n\n window.addEventListener('storage', handleStorageChange)\n return () => {\n window.removeEventListener('storage', handleStorageChange)\n }\n }, [key, sync, storageType])\n\n // Listen for changes in the same window (for programmatic changes)\n // Uses shared polling manager to prevent multiple intervals when using multiple hooks\n // Polls for localStorage, sessionStorage, and cookies to detect programmatic changes\n // Only skips polling when sync is enabled for localStorage (storage events handle it)\n useEffect(() => {\n if (typeof window === 'undefined') {\n return\n }\n\n const type = storageTypeRef.current\n\n // Skip polling only if sync is enabled for localStorage (storage events handle it)\n if (sync && type === 'localStorage') {\n return\n }\n\n const checkValue = () => {\n try {\n const storageKey = keyRef.current\n const currentType = storageTypeRef.current\n let rawValue: string | null = null\n\n if (currentType === 'cookie') {\n rawValue = getCookie(storageKey)\n } else if (currentType === 'localStorage') {\n rawValue = window.localStorage.getItem(storageKey)\n } else if (currentType === 'sessionStorage') {\n rawValue = window.sessionStorage.getItem(storageKey)\n }\n\n // Only update if the raw value changed (avoid unnecessary JSON.stringify)\n if (rawValue !== lastValueRef.current) {\n lastValueRef.current = rawValue\n\n let currentValue: T | null = null\n if (rawValue !== null) {\n try {\n // Try to parse as JSON first\n currentValue = JSON.parse(rawValue) as T\n } catch {\n // If not JSON, treat as string\n currentValue = rawValue as T\n }\n }\n\n setValueState(currentValue)\n onChangeRef.current?.(currentValue)\n }\n } catch (error) {\n // Silently fail\n }\n }\n\n // Initialize last value (with error handling)\n const storageKey = keyRef.current\n try {\n if (type === 'cookie') {\n lastValueRef.current = getCookie(storageKey)\n } else if (type === 'localStorage') {\n lastValueRef.current = window.localStorage.getItem(storageKey)\n } else if (type === 'sessionStorage') {\n lastValueRef.current = window.sessionStorage.getItem(storageKey)\n }\n } catch (error) {\n // Silently handle errors during initialization\n lastValueRef.current = null\n }\n\n // Subscribe to shared polling manager (prevents multiple intervals)\n const unsubscribe = pollingManager.subscribe(checkValue)\n\n return () => {\n unsubscribe()\n lastValueRef.current = null\n }\n }, [key, storageType, sync])\n\n return {\n value,\n setValue,\n removeValue,\n hasValue,\n clear,\n }\n}\n\n/**\n * Get cookie value\n */\nfunction getCookie(name: string): string | null {\n if (typeof document === 'undefined') {\n return null\n }\n\n const nameEQ = name + '='\n const cookies = document.cookie.split(';')\n\n for (let i = 0; i < cookies.length; i++) {\n let cookie = cookies[i]\n while (cookie.charAt(0) === ' ') {\n cookie = cookie.substring(1, cookie.length)\n }\n if (cookie.indexOf(nameEQ) === 0) {\n return decodeURIComponent(cookie.substring(nameEQ.length, cookie.length))\n }\n }\n\n return null\n}\n\n/**\n * Set cookie value\n */\nfunction setCookie(\n name: string,\n value: string,\n options?: IUseStorageOptions['cookieOptions']\n): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const { expires, path = '/', domain, secure = false, sameSite = 'Lax' } = options || {}\n\n let cookieString = `${name}=${encodeURIComponent(value)}`\n\n // Handle expiration: undefined = default (365 days), 0 = session cookie, number = days\n if (expires !== undefined && expires !== 0) {\n const date = new Date()\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000)\n cookieString += `; expires=${date.toUTCString()}`\n } else if (expires === undefined) {\n // Default to 365 days if not specified\n const date = new Date()\n date.setTime(date.getTime() + 365 * 24 * 60 * 60 * 1000)\n cookieString += `; expires=${date.toUTCString()}`\n }\n // If expires === 0, don't add expires attribute (session cookie)\n\n cookieString += `; path=${path}`\n\n if (domain) {\n cookieString += `; domain=${domain}`\n }\n\n if (secure) {\n cookieString += '; secure'\n }\n\n cookieString += `; SameSite=${sameSite}`\n\n document.cookie = cookieString\n}\n\n/**\n * Remove cookie\n */\nfunction removeCookie(name: string, options?: IUseStorageOptions['cookieOptions']): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const { path = '/', domain } = options || {}\n\n let cookieString = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`\n\n if (domain) {\n cookieString += `; domain=${domain}`\n }\n\n document.cookie = cookieString\n}\n"]}
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+
5
+ // src/storage/hooks/useStorage.ts
6
+ var StoragePollingManager = class {
7
+ constructor() {
8
+ this.intervalId = null;
9
+ this.subscribers = /* @__PURE__ */ new Set();
10
+ this.POLL_INTERVAL = 2e3;
11
+ }
12
+ // 2 seconds - longer interval to reduce overhead
13
+ subscribe(callback) {
14
+ this.subscribers.add(callback);
15
+ if (this.subscribers.size === 1 && this.intervalId === null) {
16
+ this.startPolling();
17
+ }
18
+ return () => {
19
+ this.subscribers.delete(callback);
20
+ if (this.subscribers.size === 0 && this.intervalId !== null) {
21
+ this.stopPolling();
22
+ }
23
+ };
24
+ }
25
+ startPolling() {
26
+ if (typeof window === "undefined") {
27
+ return;
28
+ }
29
+ this.intervalId = setInterval(() => {
30
+ this.subscribers.forEach((callback) => {
31
+ try {
32
+ callback();
33
+ } catch (error) {
34
+ }
35
+ });
36
+ }, this.POLL_INTERVAL);
37
+ }
38
+ stopPolling() {
39
+ if (this.intervalId !== null) {
40
+ if (typeof clearInterval !== "undefined") {
41
+ clearInterval(this.intervalId);
42
+ }
43
+ this.intervalId = null;
44
+ }
45
+ }
46
+ };
47
+ var pollingManager = new StoragePollingManager();
48
+ function useStorage(key, options) {
49
+ const {
50
+ storageType = "localStorage",
51
+ defaultValue = null,
52
+ sync = false,
53
+ cookieOptions,
54
+ onChange
55
+ } = options || {};
56
+ const [value, setValueState] = react.useState(() => {
57
+ if (typeof window === "undefined") {
58
+ return defaultValue ?? null;
59
+ }
60
+ try {
61
+ let rawValue = null;
62
+ if (storageType === "cookie") {
63
+ rawValue = getCookie(key);
64
+ } else if (storageType === "localStorage") {
65
+ rawValue = window.localStorage.getItem(key);
66
+ } else if (storageType === "sessionStorage") {
67
+ rawValue = window.sessionStorage.getItem(key);
68
+ }
69
+ if (rawValue === null) {
70
+ return defaultValue ?? null;
71
+ }
72
+ try {
73
+ const parsed = JSON.parse(rawValue);
74
+ return parsed;
75
+ } catch {
76
+ return rawValue;
77
+ }
78
+ } catch (error) {
79
+ console.warn(`Error reading storage for key "${key}":`, error);
80
+ return defaultValue ?? null;
81
+ }
82
+ });
83
+ const onChangeRef = react.useRef(onChange);
84
+ const keyRef = react.useRef(key);
85
+ const storageTypeRef = react.useRef(storageType);
86
+ const lastValueRef = react.useRef(null);
87
+ react.useEffect(() => {
88
+ onChangeRef.current = onChange;
89
+ keyRef.current = key;
90
+ storageTypeRef.current = storageType;
91
+ }, [onChange, key, storageType]);
92
+ const setValue = react.useCallback(
93
+ (newValue) => {
94
+ if (typeof window === "undefined") {
95
+ return;
96
+ }
97
+ try {
98
+ const storageKey = keyRef.current;
99
+ const type = storageTypeRef.current;
100
+ if (newValue === null) {
101
+ if (type === "cookie") {
102
+ removeCookie(storageKey, cookieOptions);
103
+ lastValueRef.current = null;
104
+ } else if (type === "localStorage") {
105
+ window.localStorage.removeItem(storageKey);
106
+ lastValueRef.current = null;
107
+ } else if (type === "sessionStorage") {
108
+ window.sessionStorage.removeItem(storageKey);
109
+ lastValueRef.current = null;
110
+ }
111
+ } else {
112
+ const stringValue = typeof newValue === "string" ? newValue : JSON.stringify(newValue);
113
+ if (type === "cookie") {
114
+ setCookie(storageKey, stringValue, cookieOptions);
115
+ lastValueRef.current = stringValue;
116
+ } else if (type === "localStorage") {
117
+ window.localStorage.setItem(storageKey, stringValue);
118
+ lastValueRef.current = stringValue;
119
+ } else if (type === "sessionStorage") {
120
+ window.sessionStorage.setItem(storageKey, stringValue);
121
+ lastValueRef.current = stringValue;
122
+ }
123
+ }
124
+ setValueState(newValue);
125
+ onChangeRef.current?.(newValue);
126
+ } catch (error) {
127
+ console.warn(`Error setting ${storageTypeRef.current} for key "${keyRef.current}":`, error);
128
+ }
129
+ },
130
+ [cookieOptions]
131
+ );
132
+ const removeValue = react.useCallback(() => {
133
+ setValue(null);
134
+ }, [setValue]);
135
+ const clear = react.useCallback(() => {
136
+ if (typeof window === "undefined") {
137
+ return;
138
+ }
139
+ try {
140
+ const type = storageTypeRef.current;
141
+ if (type === "localStorage") {
142
+ window.localStorage.clear();
143
+ } else if (type === "sessionStorage") {
144
+ window.sessionStorage.clear();
145
+ }
146
+ } catch (error) {
147
+ console.warn(`Error clearing ${storageTypeRef.current}:`, error);
148
+ }
149
+ }, []);
150
+ const hasValue = value !== null;
151
+ react.useEffect(() => {
152
+ if (typeof window === "undefined" || !sync || storageType !== "localStorage") {
153
+ return;
154
+ }
155
+ const handleStorageChange = (e) => {
156
+ if (e.key === key && e.storageArea === window.localStorage) {
157
+ const rawValue = e.newValue;
158
+ lastValueRef.current = rawValue;
159
+ let newValue = null;
160
+ if (rawValue !== null) {
161
+ try {
162
+ newValue = JSON.parse(rawValue);
163
+ } catch {
164
+ newValue = rawValue;
165
+ }
166
+ }
167
+ setValueState(newValue);
168
+ onChangeRef.current?.(newValue);
169
+ }
170
+ };
171
+ window.addEventListener("storage", handleStorageChange);
172
+ return () => {
173
+ window.removeEventListener("storage", handleStorageChange);
174
+ };
175
+ }, [key, sync, storageType]);
176
+ react.useEffect(() => {
177
+ if (typeof window === "undefined") {
178
+ return;
179
+ }
180
+ const type = storageTypeRef.current;
181
+ if (sync && type === "localStorage") {
182
+ return;
183
+ }
184
+ const checkValue = () => {
185
+ try {
186
+ const storageKey2 = keyRef.current;
187
+ const currentType = storageTypeRef.current;
188
+ let rawValue = null;
189
+ if (currentType === "cookie") {
190
+ rawValue = getCookie(storageKey2);
191
+ } else if (currentType === "localStorage") {
192
+ rawValue = window.localStorage.getItem(storageKey2);
193
+ } else if (currentType === "sessionStorage") {
194
+ rawValue = window.sessionStorage.getItem(storageKey2);
195
+ }
196
+ if (rawValue !== lastValueRef.current) {
197
+ lastValueRef.current = rawValue;
198
+ let currentValue = null;
199
+ if (rawValue !== null) {
200
+ try {
201
+ currentValue = JSON.parse(rawValue);
202
+ } catch {
203
+ currentValue = rawValue;
204
+ }
205
+ }
206
+ setValueState(currentValue);
207
+ onChangeRef.current?.(currentValue);
208
+ }
209
+ } catch (error) {
210
+ }
211
+ };
212
+ const storageKey = keyRef.current;
213
+ try {
214
+ if (type === "cookie") {
215
+ lastValueRef.current = getCookie(storageKey);
216
+ } else if (type === "localStorage") {
217
+ lastValueRef.current = window.localStorage.getItem(storageKey);
218
+ } else if (type === "sessionStorage") {
219
+ lastValueRef.current = window.sessionStorage.getItem(storageKey);
220
+ }
221
+ } catch (error) {
222
+ lastValueRef.current = null;
223
+ }
224
+ const unsubscribe = pollingManager.subscribe(checkValue);
225
+ return () => {
226
+ unsubscribe();
227
+ lastValueRef.current = null;
228
+ };
229
+ }, [key, storageType, sync]);
230
+ return {
231
+ value,
232
+ setValue,
233
+ removeValue,
234
+ hasValue,
235
+ clear
236
+ };
237
+ }
238
+ function getCookie(name) {
239
+ if (typeof document === "undefined") {
240
+ return null;
241
+ }
242
+ const nameEQ = name + "=";
243
+ const cookies = document.cookie.split(";");
244
+ for (let i = 0; i < cookies.length; i++) {
245
+ let cookie = cookies[i];
246
+ while (cookie.charAt(0) === " ") {
247
+ cookie = cookie.substring(1, cookie.length);
248
+ }
249
+ if (cookie.indexOf(nameEQ) === 0) {
250
+ return decodeURIComponent(cookie.substring(nameEQ.length, cookie.length));
251
+ }
252
+ }
253
+ return null;
254
+ }
255
+ function setCookie(name, value, options) {
256
+ if (typeof document === "undefined") {
257
+ return;
258
+ }
259
+ const { expires, path = "/", domain, secure = false, sameSite = "Lax" } = options || {};
260
+ let cookieString = `${name}=${encodeURIComponent(value)}`;
261
+ if (expires !== void 0 && expires !== 0) {
262
+ const date = /* @__PURE__ */ new Date();
263
+ date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1e3);
264
+ cookieString += `; expires=${date.toUTCString()}`;
265
+ } else if (expires === void 0) {
266
+ const date = /* @__PURE__ */ new Date();
267
+ date.setTime(date.getTime() + 365 * 24 * 60 * 60 * 1e3);
268
+ cookieString += `; expires=${date.toUTCString()}`;
269
+ }
270
+ cookieString += `; path=${path}`;
271
+ if (domain) {
272
+ cookieString += `; domain=${domain}`;
273
+ }
274
+ if (secure) {
275
+ cookieString += "; secure";
276
+ }
277
+ cookieString += `; SameSite=${sameSite}`;
278
+ document.cookie = cookieString;
279
+ }
280
+ function removeCookie(name, options) {
281
+ if (typeof document === "undefined") {
282
+ return;
283
+ }
284
+ const { path = "/", domain } = options || {};
285
+ let cookieString = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
286
+ if (domain) {
287
+ cookieString += `; domain=${domain}`;
288
+ }
289
+ document.cookie = cookieString;
290
+ }
291
+
292
+ exports.useStorage = useStorage;
293
+ //# sourceMappingURL=chunk-3QXSUE3X.js.map
294
+ //# sourceMappingURL=chunk-3QXSUE3X.js.map