@umituz/react-native-design-system 2.8.7 → 2.8.8

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.
Files changed (128) hide show
  1. package/package.json +5 -6
  2. package/src/device/infrastructure/repositories/LegacyDeviceIdRepository.ts +1 -1
  3. package/src/device/infrastructure/services/DeviceFeatureService.ts +1 -1
  4. package/src/exception/infrastructure/services/ExceptionLogger.ts +1 -1
  5. package/src/exception/infrastructure/storage/ExceptionStore.ts +1 -1
  6. package/src/exports/filesystem.ts +1 -0
  7. package/src/exports/storage.ts +1 -0
  8. package/src/filesystem/domain/constants/FileConstants.ts +20 -0
  9. package/src/filesystem/domain/entities/File.ts +20 -0
  10. package/src/filesystem/domain/types/FileTypes.ts +43 -0
  11. package/src/filesystem/domain/utils/FileUtils.ts +86 -0
  12. package/src/filesystem/index.ts +23 -0
  13. package/src/filesystem/infrastructure/services/FileSystemService.ts +45 -0
  14. package/src/filesystem/infrastructure/services/cache.service.ts +48 -0
  15. package/src/filesystem/infrastructure/services/directory.service.ts +66 -0
  16. package/src/filesystem/infrastructure/services/download.constants.ts +6 -0
  17. package/src/filesystem/infrastructure/services/download.service.ts +74 -0
  18. package/src/filesystem/infrastructure/services/download.types.ts +7 -0
  19. package/src/filesystem/infrastructure/services/encoding.service.ts +25 -0
  20. package/src/filesystem/infrastructure/services/file-info.service.ts +52 -0
  21. package/src/filesystem/infrastructure/services/file-manager.service.ts +81 -0
  22. package/src/filesystem/infrastructure/services/file-path.service.ts +22 -0
  23. package/src/filesystem/infrastructure/services/file-reader.service.ts +52 -0
  24. package/src/filesystem/infrastructure/services/file-writer.service.ts +32 -0
  25. package/src/filesystem/infrastructure/utils/blob.utils.ts +20 -0
  26. package/src/image/infrastructure/services/ImageStorageService.ts +1 -1
  27. package/src/index.ts +9 -0
  28. package/src/molecules/alerts/AlertStore.ts +1 -1
  29. package/src/molecules/calendar/infrastructure/storage/EventActions.ts +1 -1
  30. package/src/molecules/calendar/infrastructure/stores/storageAdapter.ts +1 -1
  31. package/src/offline/infrastructure/storage/OfflineStore.ts +1 -1
  32. package/src/onboarding/infrastructure/storage/OnboardingStore.ts +2 -2
  33. package/src/onboarding/infrastructure/storage/__tests__/OnboardingStore.test.ts +1 -1
  34. package/src/onboarding/infrastructure/storage/actions/answerActions.ts +1 -1
  35. package/src/onboarding/infrastructure/storage/actions/storageHelpers.ts +1 -1
  36. package/src/storage/README.md +185 -0
  37. package/src/storage/__tests__/integration.test.ts +391 -0
  38. package/src/storage/__tests__/mocks/asyncStorage.mock.ts +52 -0
  39. package/src/storage/__tests__/performance.test.tsx +352 -0
  40. package/src/storage/__tests__/setup.ts +63 -0
  41. package/src/storage/application/README.md +158 -0
  42. package/src/storage/application/ports/IStorageRepository.ts +61 -0
  43. package/src/storage/application/ports/README.md +127 -0
  44. package/src/storage/cache/README.md +154 -0
  45. package/src/storage/cache/__tests__/PerformanceAndMemory.test.ts +387 -0
  46. package/src/storage/cache/__tests__/setup.ts +19 -0
  47. package/src/storage/cache/domain/Cache.ts +146 -0
  48. package/src/storage/cache/domain/CacheManager.md +83 -0
  49. package/src/storage/cache/domain/CacheManager.ts +48 -0
  50. package/src/storage/cache/domain/CacheStatsTracker.md +169 -0
  51. package/src/storage/cache/domain/CacheStatsTracker.ts +49 -0
  52. package/src/storage/cache/domain/CachedValue.md +97 -0
  53. package/src/storage/cache/domain/ErrorHandler.md +99 -0
  54. package/src/storage/cache/domain/ErrorHandler.ts +42 -0
  55. package/src/storage/cache/domain/PatternMatcher.md +122 -0
  56. package/src/storage/cache/domain/PatternMatcher.ts +30 -0
  57. package/src/storage/cache/domain/README.md +118 -0
  58. package/src/storage/cache/domain/__tests__/Cache.test.ts +293 -0
  59. package/src/storage/cache/domain/__tests__/CacheManager.test.ts +276 -0
  60. package/src/storage/cache/domain/__tests__/ErrorHandler.test.ts +303 -0
  61. package/src/storage/cache/domain/__tests__/PatternMatcher.test.ts +261 -0
  62. package/src/storage/cache/domain/strategies/EvictionStrategy.ts +9 -0
  63. package/src/storage/cache/domain/strategies/FIFOStrategy.ts +12 -0
  64. package/src/storage/cache/domain/strategies/LFUStrategy.ts +22 -0
  65. package/src/storage/cache/domain/strategies/LRUStrategy.ts +22 -0
  66. package/src/storage/cache/domain/strategies/README.md +117 -0
  67. package/src/storage/cache/domain/strategies/TTLStrategy.ts +23 -0
  68. package/src/storage/cache/domain/strategies/__tests__/EvictionStrategies.test.ts +293 -0
  69. package/src/storage/cache/domain/types/Cache.ts +28 -0
  70. package/src/storage/cache/domain/types/README.md +107 -0
  71. package/src/storage/cache/index.ts +28 -0
  72. package/src/storage/cache/infrastructure/README.md +126 -0
  73. package/src/storage/cache/infrastructure/TTLCache.ts +103 -0
  74. package/src/storage/cache/infrastructure/__tests__/TTLCache.test.ts +303 -0
  75. package/src/storage/cache/presentation/README.md +123 -0
  76. package/src/storage/cache/presentation/__tests__/ReactHooks.test.ts +514 -0
  77. package/src/storage/cache/presentation/useCache.ts +76 -0
  78. package/src/storage/cache/presentation/useCachedValue.ts +88 -0
  79. package/src/storage/cache/types.d.ts +3 -0
  80. package/src/storage/domain/README.md +128 -0
  81. package/src/storage/domain/constants/CacheDefaults.ts +64 -0
  82. package/src/storage/domain/constants/README.md +105 -0
  83. package/src/storage/domain/entities/CachedValue.ts +86 -0
  84. package/src/storage/domain/entities/README.md +109 -0
  85. package/src/storage/domain/entities/StorageResult.ts +75 -0
  86. package/src/storage/domain/entities/__tests__/CachedValue.test.ts +149 -0
  87. package/src/storage/domain/entities/__tests__/StorageResult.test.ts +122 -0
  88. package/src/storage/domain/errors/README.md +126 -0
  89. package/src/storage/domain/errors/StorageError.ts +81 -0
  90. package/src/storage/domain/errors/__tests__/StorageError.test.ts +127 -0
  91. package/src/storage/domain/factories/README.md +138 -0
  92. package/src/storage/domain/factories/StoreFactory.ts +59 -0
  93. package/src/storage/domain/types/README.md +522 -0
  94. package/src/storage/domain/types/Store.ts +44 -0
  95. package/src/storage/domain/utils/CacheKeyGenerator.ts +66 -0
  96. package/src/storage/domain/utils/README.md +127 -0
  97. package/src/storage/domain/utils/__tests__/devUtils.test.ts +97 -0
  98. package/src/storage/domain/utils/devUtils.ts +37 -0
  99. package/src/storage/domain/value-objects/README.md +120 -0
  100. package/src/storage/domain/value-objects/StorageKey.ts +60 -0
  101. package/src/storage/index.ts +175 -0
  102. package/src/storage/infrastructure/README.md +165 -0
  103. package/src/storage/infrastructure/adapters/README.md +175 -0
  104. package/src/storage/infrastructure/adapters/StorageService.md +103 -0
  105. package/src/storage/infrastructure/adapters/StorageService.ts +49 -0
  106. package/src/storage/infrastructure/repositories/AsyncStorageRepository.ts +98 -0
  107. package/src/storage/infrastructure/repositories/BaseStorageOperations.ts +100 -0
  108. package/src/storage/infrastructure/repositories/BatchStorageOperations.ts +42 -0
  109. package/src/storage/infrastructure/repositories/README.md +121 -0
  110. package/src/storage/infrastructure/repositories/StringStorageOperations.ts +44 -0
  111. package/src/storage/infrastructure/repositories/__tests__/AsyncStorageRepository.test.ts +170 -0
  112. package/src/storage/infrastructure/repositories/__tests__/BaseStorageOperations.test.ts +201 -0
  113. package/src/storage/presentation/README.md +181 -0
  114. package/src/storage/presentation/hooks/CacheStorageOperations.ts +94 -0
  115. package/src/storage/presentation/hooks/README.md +128 -0
  116. package/src/storage/presentation/hooks/__tests__/usePersistentCache.test.ts +405 -0
  117. package/src/storage/presentation/hooks/__tests__/useStorage.test.ts +247 -0
  118. package/src/storage/presentation/hooks/__tests__/useStorageState.test.ts +293 -0
  119. package/src/storage/presentation/hooks/useCacheState.ts +53 -0
  120. package/src/storage/presentation/hooks/usePersistentCache.ts +154 -0
  121. package/src/storage/presentation/hooks/useStorage.ts +102 -0
  122. package/src/storage/presentation/hooks/useStorageState.ts +71 -0
  123. package/src/storage/presentation/hooks/useStore.ts +15 -0
  124. package/src/storage/types/README.md +103 -0
  125. package/src/theme/infrastructure/globalThemeStore.ts +1 -1
  126. package/src/theme/infrastructure/storage/ThemeStorage.ts +1 -1
  127. package/src/theme/infrastructure/stores/themeStore.ts +1 -1
  128. package/src/utilities/sharing/infrastructure/services/SharingService.ts +1 -1
@@ -0,0 +1,293 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ /**
3
+ * useStorageState Hook Tests
4
+ *
5
+ * Unit tests for useStorageState hook
6
+ */
7
+
8
+ import { renderHook, act } from '@testing-library/react-hooks';
9
+ import { useStorageState } from '../useStorageState';
10
+ import { AsyncStorage } from '../../__tests__/mocks/asyncStorage.mock';
11
+
12
+ describe('useStorageState Hook', () => {
13
+ beforeEach(() => {
14
+ (AsyncStorage as any).__clear();
15
+ jest.clearAllMocks();
16
+ });
17
+
18
+ describe('Initial Load', () => {
19
+ it('should load initial value from storage', async () => {
20
+ const key = 'test-key';
21
+ const defaultValue = 'default';
22
+ const storedValue = 'stored-value';
23
+
24
+ await AsyncStorage.setItem(key, JSON.stringify(storedValue));
25
+
26
+ const { result, waitForNextUpdate } = renderHook(() =>
27
+ useStorageState(key, defaultValue)
28
+ );
29
+
30
+ // Initial state
31
+ expect(result.current[0]).toBe(defaultValue);
32
+ expect(result.current[2]).toBe(true); // isLoading
33
+
34
+ // Wait for load
35
+ await act(async () => {
36
+ await waitForNextUpdate();
37
+ });
38
+
39
+ expect(result.current[0]).toBe(storedValue);
40
+ expect(result.current[2]).toBe(false); // isLoading
41
+ });
42
+
43
+ it('should use default value for missing key', async () => {
44
+ const key = 'missing-key';
45
+ const defaultValue = 'default';
46
+
47
+ const { result, waitForNextUpdate } = renderHook(() =>
48
+ useStorageState(key, defaultValue)
49
+ );
50
+
51
+ await act(async () => {
52
+ await waitForNextUpdate();
53
+ });
54
+
55
+ expect(result.current[0]).toBe(defaultValue);
56
+ expect(result.current[2]).toBe(false);
57
+ });
58
+
59
+ it('should handle StorageKey enum', async () => {
60
+ const key = '@ui_preferences';
61
+ const defaultValue = 'default';
62
+ const storedValue = 'stored-value';
63
+
64
+ await AsyncStorage.setItem(key, JSON.stringify(storedValue));
65
+
66
+ const { result, waitForNextUpdate } = renderHook(() =>
67
+ useStorageState(key as any, defaultValue)
68
+ );
69
+
70
+ await act(async () => {
71
+ await waitForNextUpdate();
72
+ });
73
+
74
+ expect(result.current[0]).toBe(storedValue);
75
+ });
76
+ });
77
+
78
+ describe('Update State', () => {
79
+ it('should update state and persist to storage', async () => {
80
+ const key = 'test-key';
81
+ const defaultValue = 'default';
82
+ const newValue = 'new-value';
83
+
84
+ const { result, waitForNextUpdate } = renderHook(() =>
85
+ useStorageState(key, defaultValue)
86
+ );
87
+
88
+ await act(async () => {
89
+ await waitForNextUpdate();
90
+ });
91
+
92
+ // Update state
93
+ await act(async () => {
94
+ await result.current[1](newValue);
95
+ });
96
+
97
+ expect(result.current[0]).toBe(newValue);
98
+
99
+ // Verify storage
100
+ const stored = await AsyncStorage.getItem(key);
101
+ expect(JSON.parse(stored!)).toBe(newValue);
102
+ });
103
+
104
+ it('should handle update during loading', async () => {
105
+ const key = 'test-key';
106
+ const defaultValue = 'default';
107
+ const newValue = 'new-value';
108
+
109
+ // Mock slow storage
110
+ let resolveStorage: (value: string) => void;
111
+ (AsyncStorage.getItem as jest.Mock).mockImplementation(() =>
112
+ new Promise(resolve => {
113
+ resolveStorage = resolve;
114
+ })
115
+ );
116
+
117
+ const { result } = renderHook(() =>
118
+ useStorageState(key, defaultValue)
119
+ );
120
+
121
+ // Update while loading
122
+ await act(async () => {
123
+ await result.current[1](newValue);
124
+ });
125
+
126
+ expect(result.current[0]).toBe(newValue);
127
+ });
128
+ });
129
+
130
+ describe('Memory Leak Prevention', () => {
131
+ it('should cleanup on unmount', async () => {
132
+ const key = 'test-key';
133
+ const defaultValue = 'default';
134
+
135
+ // Mock slow storage
136
+ let resolveStorage: (value: string) => void;
137
+ (AsyncStorage.getItem as jest.Mock).mockImplementation(() =>
138
+ new Promise(resolve => {
139
+ resolveStorage = resolve;
140
+ })
141
+ );
142
+
143
+ const { result, unmount } = renderHook(() =>
144
+ useStorageState(key, defaultValue)
145
+ );
146
+
147
+ // Unmount before load completes
148
+ unmount();
149
+
150
+ // Resolve storage after unmount
151
+ await act(async () => {
152
+ resolveStorage!('stored-value');
153
+ });
154
+
155
+ // State should not be updated after unmount
156
+ expect(result.current[0]).toBe(defaultValue);
157
+ });
158
+
159
+ it('should handle unmount during update', async () => {
160
+ const key = 'test-key';
161
+ const defaultValue = 'default';
162
+ const newValue = 'new-value';
163
+
164
+ // Mock slow storage
165
+ let resolveStorage: () => void;
166
+ (AsyncStorage.setItem as jest.Mock).mockImplementation(() =>
167
+ new Promise(resolve => {
168
+ resolveStorage = resolve;
169
+ })
170
+ );
171
+
172
+ const { result, unmount } = renderHook(() =>
173
+ useStorageState(key, defaultValue)
174
+ );
175
+
176
+ // Start update
177
+ const updatePromise = act(async () => {
178
+ await result.current[1](newValue);
179
+ });
180
+
181
+ // Unmount before update completes
182
+ unmount();
183
+
184
+ // Complete update
185
+ await act(async () => {
186
+ resolveStorage!();
187
+ });
188
+
189
+ await updatePromise;
190
+ });
191
+ });
192
+
193
+ describe('Performance', () => {
194
+ it('should not re-run effect when defaultValue changes', async () => {
195
+ const key = 'test-key';
196
+ const defaultValue1 = 'default1';
197
+ const defaultValue2 = 'default2';
198
+
199
+ await AsyncStorage.setItem(key, JSON.stringify('stored-value'));
200
+
201
+ const { result, rerender, waitForNextUpdate } = renderHook(
202
+ ({ defaultValue }) => useStorageState(key, defaultValue),
203
+ { initialProps: { defaultValue: defaultValue1 } }
204
+ );
205
+
206
+ await act(async () => {
207
+ await waitForNextUpdate();
208
+ });
209
+
210
+ const getItemCalls = (AsyncStorage.getItem as jest.Mock).mock.calls.length;
211
+
212
+ // Rerender with different default value
213
+ rerender({ defaultValue: defaultValue2 });
214
+
215
+ // Should not trigger another storage read
216
+ expect((AsyncStorage.getItem as jest.Mock).mock.calls.length).toBe(getItemCalls);
217
+ });
218
+
219
+ it('should re-run effect when key changes', async () => {
220
+ const key1 = 'key1';
221
+ const key2 = 'key2';
222
+ const defaultValue = 'default';
223
+
224
+ await AsyncStorage.setItem(key1, JSON.stringify('value1'));
225
+ await AsyncStorage.setItem(key2, JSON.stringify('value2'));
226
+
227
+ const { result, rerender, waitForNextUpdate } = renderHook(
228
+ ({ key }) => useStorageState(key, defaultValue),
229
+ { initialProps: { key: key1 } }
230
+ );
231
+
232
+ await act(async () => {
233
+ await waitForNextUpdate();
234
+ });
235
+
236
+ expect(result.current[0]).toBe('value1');
237
+
238
+ // Change key
239
+ rerender({ key: key2 });
240
+
241
+ await act(async () => {
242
+ await waitForNextUpdate();
243
+ });
244
+
245
+ expect(result.current[0]).toBe('value2');
246
+ });
247
+ });
248
+
249
+ describe('Error Handling', () => {
250
+ it('should handle storage read error', async () => {
251
+ const key = 'test-key';
252
+ const defaultValue = 'default';
253
+
254
+ // Mock storage error
255
+ (AsyncStorage.getItem as jest.Mock).mockRejectedValue(new Error('Storage error'));
256
+
257
+ const { result, waitForNextUpdate } = renderHook(() =>
258
+ useStorageState(key, defaultValue)
259
+ );
260
+
261
+ await act(async () => {
262
+ await waitForNextUpdate();
263
+ });
264
+
265
+ expect(result.current[0]).toBe(defaultValue);
266
+ expect(result.current[2]).toBe(false); // isLoading should be false
267
+ });
268
+
269
+ it('should handle storage write error', async () => {
270
+ const key = 'test-key';
271
+ const defaultValue = 'default';
272
+ const newValue = 'new-value';
273
+
274
+ // Mock storage error
275
+ (AsyncStorage.setItem as jest.Mock).mockRejectedValue(new Error('Storage error'));
276
+
277
+ const { result, waitForNextUpdate } = renderHook(() =>
278
+ useStorageState(key, defaultValue)
279
+ );
280
+
281
+ await act(async () => {
282
+ await waitForNextUpdate();
283
+ });
284
+
285
+ // State should still update even if storage fails
286
+ await act(async () => {
287
+ await result.current[1](newValue);
288
+ });
289
+
290
+ expect(result.current[0]).toBe(newValue);
291
+ });
292
+ });
293
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Cache State Manager
3
+ *
4
+ * Manages cache state following Single Responsibility Principle
5
+ */
6
+
7
+ import { useState, useCallback, useMemo } from 'react';
8
+
9
+ export interface CacheState<T> {
10
+ data: T | null;
11
+ isLoading: boolean;
12
+ isExpired: boolean;
13
+ }
14
+
15
+ export interface CacheActions<T> {
16
+ setData: (value: T) => void;
17
+ clearData: () => void;
18
+ setLoading: (loading: boolean) => void;
19
+ setExpired: (expired: boolean) => void;
20
+ }
21
+
22
+ /**
23
+ * Hook for managing cache state
24
+ */
25
+ export function useCacheState<T>(): [CacheState<T>, CacheActions<T>] {
26
+ const [data, setDataState] = useState<T | null>(null);
27
+ const [isLoading, setIsLoading] = useState(true);
28
+ const [isExpired, setIsExpired] = useState(false);
29
+
30
+ const setData = useCallback((value: T) => {
31
+ setDataState(value);
32
+ setIsExpired(false);
33
+ }, []);
34
+
35
+ const clearData = useCallback(() => {
36
+ setDataState(null);
37
+ setIsExpired(true);
38
+ }, []);
39
+
40
+ const setLoading = useCallback((loading: boolean) => {
41
+ setIsLoading(loading);
42
+ }, []);
43
+
44
+ const setExpired = useCallback((expired: boolean) => {
45
+ setIsExpired(expired);
46
+ }, []);
47
+
48
+ // Memoize state and actions objects for performance
49
+ const state: CacheState<T> = useMemo(() => ({ data, isLoading, isExpired }), [data, isLoading, isExpired]);
50
+ const actions: CacheActions<T> = useMemo(() => ({ setData, clearData, setLoading, setExpired }), [setData, clearData, setLoading, setExpired]);
51
+
52
+ return [state, actions];
53
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * usePersistentCache Hook
3
+ * Presentation layer - Hook for persistent caching with TTL
4
+ *
5
+ * General-purpose cache hook for any app
6
+ */
7
+
8
+ import { useEffect, useCallback, useMemo } from 'react';
9
+ import { useCacheState } from './useCacheState';
10
+ import { CacheStorageOperations } from './CacheStorageOperations';
11
+ import { isCacheExpired } from '../../domain/entities/CachedValue';
12
+ import { DEFAULT_TTL } from '../../domain/constants/CacheDefaults';
13
+
14
+ /**
15
+ * Options for persistent cache
16
+ */
17
+ export interface PersistentCacheOptions {
18
+ /**
19
+ * Time-to-live in milliseconds
20
+ * @default DEFAULT_TTL.MEDIUM (30 minutes)
21
+ */
22
+ ttl?: number;
23
+
24
+ /**
25
+ * Cache version for invalidation
26
+ * Increment to invalidate existing caches
27
+ */
28
+ version?: number;
29
+
30
+ /**
31
+ * Whether cache is enabled
32
+ * @default true
33
+ */
34
+ enabled?: boolean;
35
+ }
36
+
37
+ /**
38
+ * Result from usePersistentCache hook
39
+ */
40
+ export interface PersistentCacheResult<T> {
41
+ /**
42
+ * Cached data (null if not loaded or expired)
43
+ */
44
+ data: T | null;
45
+
46
+ /**
47
+ * Whether data is being loaded from storage
48
+ */
49
+ isLoading: boolean;
50
+
51
+ /**
52
+ * Whether cached data is expired
53
+ */
54
+ isExpired: boolean;
55
+
56
+ /**
57
+ * Set data to cache
58
+ */
59
+ setData: (value: T) => Promise<void>;
60
+
61
+ /**
62
+ * Clear cached data
63
+ */
64
+ clearData: () => Promise<void>;
65
+
66
+ /**
67
+ * Refresh cache (reload from storage)
68
+ */
69
+ refresh: () => Promise<void>;
70
+ }
71
+
72
+ /**
73
+ * Hook for persistent caching with TTL support
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const { data, setData, isExpired } = usePersistentCache<Post[]>('posts-page-1', {
78
+ * ttl: TIME_MS.HOUR,
79
+ * version: 1,
80
+ * });
81
+ *
82
+ * // Check if need to fetch
83
+ * if (!data || isExpired) {
84
+ * const freshData = await fetchPosts();
85
+ * await setData(freshData);
86
+ * }
87
+ * ```
88
+ */
89
+ export function usePersistentCache<T>(
90
+ key: string,
91
+ options: PersistentCacheOptions = {},
92
+ ): PersistentCacheResult<T> {
93
+ const { ttl = DEFAULT_TTL.MEDIUM, version, enabled = true } = options;
94
+ const [state, actions] = useCacheState<T>();
95
+
96
+ // Use singleton pattern to prevent memory leaks
97
+ const cacheOps = useMemo(() => CacheStorageOperations.getInstance(), []);
98
+
99
+ const loadFromStorage = useCallback(async () => {
100
+ if (!enabled) {
101
+ actions.setLoading(false);
102
+ return;
103
+ }
104
+
105
+ actions.setLoading(true);
106
+
107
+ try {
108
+ const cached = await cacheOps.loadFromStorage<T>(key);
109
+
110
+ if (cached) {
111
+ const expired = isCacheExpired(cached, version);
112
+ actions.setData(cached.value);
113
+ actions.setExpired(expired);
114
+ } else {
115
+ actions.clearData();
116
+ }
117
+ } catch {
118
+ actions.clearData();
119
+ } finally {
120
+ actions.setLoading(false);
121
+ }
122
+ }, [key, version, enabled, actions, cacheOps]);
123
+
124
+ const setData = useCallback(
125
+ async (value: T) => {
126
+ await cacheOps.saveToStorage(key, value, { ttl, version, enabled });
127
+ actions.setData(value);
128
+ },
129
+ [key, ttl, version, enabled, actions, cacheOps],
130
+ );
131
+
132
+ const clearData = useCallback(async () => {
133
+ await cacheOps.clearFromStorage(key, enabled);
134
+ actions.clearData();
135
+ }, [key, enabled, actions, cacheOps]);
136
+
137
+ const refresh = useCallback(async () => {
138
+ await loadFromStorage();
139
+ }, [loadFromStorage]);
140
+
141
+ // Prevent infinite loops by only running when key or enabled changes
142
+ useEffect(() => {
143
+ loadFromStorage();
144
+ }, [key, enabled]);
145
+
146
+ return {
147
+ data: state.data,
148
+ isLoading: state.isLoading,
149
+ isExpired: state.isExpired,
150
+ setData,
151
+ clearData,
152
+ refresh,
153
+ };
154
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * useStorage Hook
3
+ *
4
+ * Domain-Driven Design: Presentation layer hook for storage operations
5
+ * Provides clean API for components to interact with storage domain
6
+ */
7
+
8
+ import { useCallback, useMemo } from 'react';
9
+ import { storageRepository } from '../../infrastructure/repositories/AsyncStorageRepository';
10
+ import type { StorageResult } from '../../domain/entities/StorageResult';
11
+ import { unwrap } from '../../domain/entities/StorageResult';
12
+ import type { StorageKey } from '../../domain/value-objects/StorageKey';
13
+
14
+ /**
15
+ * Storage Hook
16
+ * Provides type-safe storage operations
17
+ */
18
+ export const useStorage = () => {
19
+ /**
20
+ * Get item from storage
21
+ */
22
+ const getItem = useCallback(async <T>(key: string | StorageKey, defaultValue: T): Promise<T> => {
23
+ const keyString = typeof key === 'string' ? key : String(key);
24
+ const result = await storageRepository.getItem(keyString, defaultValue);
25
+ return unwrap(result, defaultValue);
26
+ }, []);
27
+
28
+ /**
29
+ * Set item in storage
30
+ */
31
+ const setItem = useCallback(async <T>(key: string | StorageKey, value: T): Promise<boolean> => {
32
+ const keyString = typeof key === 'string' ? key : String(key);
33
+ const result = await storageRepository.setItem(keyString, value);
34
+ return result.success;
35
+ }, []);
36
+
37
+ /**
38
+ * Get string from storage
39
+ */
40
+ const getString = useCallback(async (key: string | StorageKey, defaultValue: string): Promise<string> => {
41
+ const keyString = typeof key === 'string' ? key : String(key);
42
+ const result = await storageRepository.getString(keyString, defaultValue);
43
+ return unwrap(result, defaultValue);
44
+ }, []);
45
+
46
+ /**
47
+ * Set string in storage
48
+ */
49
+ const setString = useCallback(async (key: string | StorageKey, value: string): Promise<boolean> => {
50
+ const keyString = typeof key === 'string' ? key : String(key);
51
+ const result = await storageRepository.setString(keyString, value);
52
+ return result.success;
53
+ }, []);
54
+
55
+ /**
56
+ * Remove item from storage
57
+ */
58
+ const removeItem = useCallback(async (key: string | StorageKey): Promise<boolean> => {
59
+ const keyString = typeof key === 'string' ? key : String(key);
60
+ const result = await storageRepository.removeItem(keyString);
61
+ return result.success;
62
+ }, []);
63
+
64
+ /**
65
+ * Check if item exists
66
+ */
67
+ const hasItem = useCallback(async (key: string | StorageKey): Promise<boolean> => {
68
+ const keyString = typeof key === 'string' ? key : String(key);
69
+ return storageRepository.hasItem(keyString);
70
+ }, []);
71
+
72
+ /**
73
+ * Clear all storage
74
+ */
75
+ const clearAll = useCallback(async (): Promise<boolean> => {
76
+ const result = await storageRepository.clearAll();
77
+ return result.success;
78
+ }, []);
79
+
80
+ /**
81
+ * Get item with full result (success/error)
82
+ */
83
+ const getItemWithResult = useCallback(async <T>(
84
+ key: string | StorageKey,
85
+ defaultValue: T
86
+ ): Promise<StorageResult<T>> => {
87
+ const keyString = typeof key === 'string' ? key : String(key);
88
+ return storageRepository.getItem(keyString, defaultValue);
89
+ }, []);
90
+
91
+ // Memoize return object to prevent unnecessary re-renders
92
+ return useMemo(() => ({
93
+ getItem,
94
+ setItem,
95
+ getString,
96
+ setString,
97
+ removeItem,
98
+ hasItem,
99
+ clearAll,
100
+ getItemWithResult,
101
+ }), [getItem, setItem, getString, setString, removeItem, hasItem, clearAll, getItemWithResult]);
102
+ };
@@ -0,0 +1,71 @@
1
+ /**
2
+ * useStorageState Hook
3
+ *
4
+ * Domain-Driven Design: Presentation layer hook for state + storage sync
5
+ * Combines React state with automatic storage persistence
6
+ */
7
+
8
+ import { useState, useEffect, useCallback } from 'react';
9
+ import { storageRepository } from '../../infrastructure/repositories/AsyncStorageRepository';
10
+ import { unwrap } from '../../domain/entities/StorageResult';
11
+ import type { StorageKey } from '../../domain/value-objects/StorageKey';
12
+
13
+ /**
14
+ * Storage State Hook
15
+ * Syncs React state with AsyncStorage automatically
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const [settings, setSettings] = useStorageState('user_settings', { theme: 'light' });
20
+ * // State is automatically persisted to storage
21
+ * ```
22
+ */
23
+ export const useStorageState = <T>(
24
+ key: string | StorageKey,
25
+ defaultValue: T
26
+ ): [T, (value: T) => Promise<void>, boolean] => {
27
+ const keyString = typeof key === 'string' ? key : String(key);
28
+ const [state, setState] = useState<T>(defaultValue);
29
+ const [isLoading, setIsLoading] = useState(true);
30
+
31
+ // Load initial value from storage
32
+ useEffect(() => {
33
+ let isMounted = true;
34
+
35
+ const loadFromStorage = async () => {
36
+ try {
37
+ const result = await storageRepository.getItem(keyString, defaultValue);
38
+ const value = unwrap(result, defaultValue);
39
+
40
+ // Memory leak önlemek için component mount kontrolü
41
+ if (isMounted) {
42
+ setState(value);
43
+ setIsLoading(false);
44
+ }
45
+ } catch {
46
+ // Hata durumunda bile cleanup yap
47
+ if (isMounted) {
48
+ setIsLoading(false);
49
+ }
50
+ }
51
+ };
52
+
53
+ loadFromStorage();
54
+
55
+ // Cleanup function
56
+ return () => {
57
+ isMounted = false;
58
+ };
59
+ }, [keyString]); // defaultValue'ı dependency array'den çıkar
60
+
61
+ // Update state and persist to storage
62
+ const updateState = useCallback(
63
+ async (value: T) => {
64
+ setState(value);
65
+ await storageRepository.setItem(keyString, value);
66
+ },
67
+ [keyString]
68
+ );
69
+
70
+ return [state, updateState, isLoading];
71
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * useStore Hook
3
+ * Helper for creating stores in components
4
+ */
5
+
6
+ import { useMemo } from 'react';
7
+ import { createStore } from '../../domain/factories/StoreFactory';
8
+ import type { StoreConfig } from '../../domain/types/Store';
9
+
10
+ export function useStore<T extends object>(config: StoreConfig<T>) {
11
+ // Config objesini stabilize et ki sonsuz re-render olmasın
12
+ const stableConfig = useMemo(() => config, [config.name, JSON.stringify(config)]);
13
+ const store = useMemo(() => createStore(stableConfig), [stableConfig]);
14
+ return store;
15
+ }