forked from rough-stuff/rough
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact-hooks.ts
More file actions
813 lines (709 loc) · 25.9 KB
/
react-hooks.ts
File metadata and controls
813 lines (709 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
import { useEffect, useRef, useMemo, useSyncExternalStore } from 'react';
import { RoughReactNativeSVG } from './react-native-svg';
import { Config, Options } from './core';
import { Point } from './geometry';
import { CONFIG } from './config';
// Concurrent-safe store for managing RoughReactNativeSVG instances
class RoughInstanceStore {
private instances = new Map<string, RoughReactNativeSVG>();
private listeners = new Set<() => void>();
private nextId = 0;
createInstance(config?: Config): string {
const id = `${CONFIG.REACT_HOOK.ID_PREFIX}${this.nextId++}`;
const instance = new RoughReactNativeSVG(config);
this.instances.set(id, instance);
this.notifyListeners();
return id;
}
getInstance(id: string): RoughReactNativeSVG | undefined {
return this.instances.get(id);
}
updateInstance(id: string, config?: Config): void {
const existingInstance = this.instances.get(id);
if (existingInstance) {
existingInstance.dispose();
}
const newInstance = new RoughReactNativeSVG(config);
this.instances.set(id, newInstance);
this.notifyListeners();
}
deleteInstance(id: string): void {
const instance = this.instances.get(id);
if (instance) {
instance.dispose();
this.instances.delete(id);
this.notifyListeners();
}
}
subscribe(callback: () => void): () => void {
this.listeners.add(callback);
return () => {
this.listeners.delete(callback);
};
}
getSnapshot(): Map<string, RoughReactNativeSVG> {
// Return immutable snapshot for concurrent safety
return new Map(this.instances);
}
private notifyListeners(): void {
this.listeners.forEach((callback) => callback());
}
// Cleanup method for testing/debugging
clear(): void {
this.instances.forEach((instance) => instance.dispose());
this.instances.clear();
this.notifyListeners();
}
}
// Global store instance
const roughStore = new RoughInstanceStore();
// Concurrent-safe shape generation store with adaptive memory management
class ShapeGenerationStore {
private cache = new Map<string, any>();
private listeners = new Set<() => void>();
private pendingGenerations = new Set<string>();
private memoryMonitor = MemoryMonitor.getInstance();
private get maxCacheSize(): number {
// Shape cache can be larger since shapes are more valuable to cache
return this.memoryMonitor.getRecommendedCacheSize() * CONFIG.MEMORY.SHAPE_CACHE_MULTIPLIER;
}
generateShape(key: string, generator: () => any): any {
// Check if we have cached result
if (this.cache.has(key)) {
return this.cache.get(key);
}
// Under high memory pressure, limit concurrent generations
if (this.memoryMonitor.shouldAgressivelyCleanup() && this.pendingGenerations.size > 2) {
return null; // Defer generation under memory pressure
}
// Mark as pending to prevent duplicate work
if (this.pendingGenerations.has(key)) {
return null; // Return null for pending generations
}
// Check cache size before generating
if (this.cache.size >= this.maxCacheSize) {
this.performMemoryPressureCleanup();
}
this.pendingGenerations.add(key);
try {
const result = generator();
this.cache.set(key, result);
this.pendingGenerations.delete(key);
this.notifyListeners();
return result;
} catch (error) {
this.pendingGenerations.delete(key);
// Cache error result to prevent retry storms (but only if not under memory pressure)
if (!this.memoryMonitor.shouldAgressivelyCleanup()) {
const errorResult = { props: {}, children: [], error: String(error) };
this.cache.set(key, errorResult);
}
this.notifyListeners();
return { props: {}, children: [], error: String(error) };
}
}
private performMemoryPressureCleanup(): void {
const pressureLevel = this.memoryMonitor.getMemoryPressureLevel();
if (pressureLevel === 'high') {
// Aggressive cleanup - clear 75% of cache
const entries = Array.from(this.cache.entries());
const keepCount = Math.floor(entries.length * CONFIG.MEMORY.HIGH_PRESSURE_KEEP_PERCENT);
const toKeep = entries.slice(-keepCount); // Keep most recent
this.cache.clear();
toKeep.forEach(([key, value]) => this.cache.set(key, value));
} else if (pressureLevel === 'medium') {
// Moderate cleanup - clear 50% of cache
const entries = Array.from(this.cache.entries());
const keepCount = Math.floor(entries.length * CONFIG.MEMORY.MEDIUM_PRESSURE_KEEP_PERCENT);
const toKeep = entries.slice(-keepCount); // Keep most recent
this.cache.clear();
toKeep.forEach(([key, value]) => this.cache.set(key, value));
}
// Low pressure - let normal cache size limits handle it
}
subscribe(callback: () => void): () => void {
this.listeners.add(callback);
return () => {
this.listeners.delete(callback);
};
}
getSnapshot(): Map<string, any> {
return new Map(this.cache);
}
private notifyListeners(): void {
this.listeners.forEach((callback) => callback());
}
clearCache(): void {
this.cache.clear();
this.pendingGenerations.clear();
this.notifyListeners();
}
}
const shapeStore = new ShapeGenerationStore();
// Memory pressure detection utility
class MemoryMonitor {
private static instance: MemoryMonitor;
private memoryPressureLevel: 'low' | 'medium' | 'high' = 'low';
private lastMemoryCheck = 0;
private checkInterval = CONFIG.MEMORY.MEMORY_CHECK_INTERVAL_MS;
static getInstance(): MemoryMonitor {
if (!MemoryMonitor.instance) {
MemoryMonitor.instance = new MemoryMonitor();
}
return MemoryMonitor.instance;
}
getMemoryPressureLevel(): 'low' | 'medium' | 'high' {
const now = Date.now();
if (now - this.lastMemoryCheck > this.checkInterval) {
this.checkMemoryPressure();
this.lastMemoryCheck = now;
}
return this.memoryPressureLevel;
}
private checkMemoryPressure(): void {
try {
// React Native memory detection
if (typeof global !== 'undefined' && global.performance && (global.performance as any).memory) {
const memory = (global.performance as any).memory;
const usedRatio = memory.usedJSHeapSize / memory.jsHeapSizeLimit;
if (usedRatio > CONFIG.MEMORY.HIGH_MEMORY_PRESSURE_THRESHOLD) {
this.memoryPressureLevel = 'high';
} else if (usedRatio > CONFIG.MEMORY.MEDIUM_MEMORY_PRESSURE_THRESHOLD) {
this.memoryPressureLevel = 'medium';
} else {
this.memoryPressureLevel = 'low';
}
return;
}
// Fallback: Browser memory API
if (typeof performance !== 'undefined' && (performance as any).memory) {
const memory = (performance as any).memory;
const usedRatio = memory.usedJSHeapSize / memory.jsHeapSizeLimit;
if (usedRatio > CONFIG.MEMORY.HIGH_MEMORY_PRESSURE_THRESHOLD) {
this.memoryPressureLevel = 'high';
} else if (usedRatio > CONFIG.MEMORY.MEDIUM_MEMORY_PRESSURE_THRESHOLD) {
this.memoryPressureLevel = 'medium';
} else {
this.memoryPressureLevel = 'low';
}
return;
}
// React Native specific checks
if (typeof global !== 'undefined') {
// Estimate memory pressure based on device characteristics
const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';
const isLowEndDevice = /Android.*4\.|Android.*[0-3]\./i.test(userAgent);
if (isLowEndDevice) {
this.memoryPressureLevel = 'high';
} else {
this.memoryPressureLevel = 'medium';
}
return;
}
// Default to medium pressure for unknown environments
this.memoryPressureLevel = 'medium';
} catch (error) {
// If memory detection fails, assume medium pressure
this.memoryPressureLevel = 'medium';
}
}
getRecommendedCacheSize(): number {
switch (this.memoryPressureLevel) {
case 'high':
return CONFIG.MEMORY.CACHE_SIZE_HIGH_PRESSURE; // Very conservative for low-memory devices
case 'medium':
return CONFIG.MEMORY.CACHE_SIZE_MEDIUM_PRESSURE; // Balanced for typical devices
case 'low':
return CONFIG.MEMORY.CACHE_SIZE_LOW_PRESSURE; // Generous for high-memory devices
default:
return CONFIG.MEMORY.CACHE_SIZE_DEFAULT;
}
}
shouldAgressivelyCleanup(): boolean {
return this.memoryPressureLevel === 'high';
}
}
// Optimized deep equality with adaptive caching based on memory pressure
class DeepEqualityCache {
private cache = new WeakMap<any, WeakMap<any, boolean>>();
private cacheCount = 0;
private cacheHits = 0;
private cacheMisses = 0;
private memoryMonitor = MemoryMonitor.getInstance();
private get maxCacheSize(): number {
return this.memoryMonitor.getRecommendedCacheSize();
}
get(a: any, b: any): boolean | undefined {
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
return undefined; // Don't cache primitives
}
const aCache = this.cache.get(a);
if (aCache) {
const result = aCache.get(b);
if (result !== undefined) {
this.cacheHits++;
return result;
}
}
this.cacheMisses++;
return undefined;
}
set(a: any, b: any, result: boolean): void {
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
return; // Don't cache primitives
}
// Adaptive cache management based on memory pressure
const currentMaxSize = this.maxCacheSize;
this.cacheCount++;
if (this.cacheCount > currentMaxSize) {
this.cache = new WeakMap();
this.cacheCount = 0;
// Under high memory pressure, be more aggressive about clearing
if (this.memoryMonitor.shouldAgressivelyCleanup()) {
// Force garbage collection hint (if available)
if (typeof global !== 'undefined' && global.gc) {
try {
global.gc();
} catch (e) {
// Ignore GC errors
}
}
}
}
let aCache = this.cache.get(a);
if (!aCache) {
aCache = new WeakMap();
this.cache.set(a, aCache);
}
aCache.set(b, result);
// Only cache reverse direction if we're not under memory pressure
if (!this.memoryMonitor.shouldAgressivelyCleanup()) {
let bCache = this.cache.get(b);
if (!bCache) {
bCache = new WeakMap();
this.cache.set(b, bCache);
}
bCache.set(a, result);
}
}
getStats() {
return {
hits: this.cacheHits,
misses: this.cacheMisses,
hitRate: this.cacheHits / (this.cacheHits + this.cacheMisses),
memoryPressure: this.memoryMonitor.getMemoryPressureLevel(),
maxCacheSize: this.maxCacheSize,
currentCacheCount: this.cacheCount,
};
}
}
// Global cache instance
const deepEqualCache = new DeepEqualityCache();
// Optimized deep equality utility for React hooks
function deepEqual(a: any, b: any, depth: number = 0): boolean {
// Early exits for performance
if (a === b) return true;
if (depth > CONFIG.REACT_HOOK.MAX_RECURSION_DEPTH) return false; // Prevent infinite recursion
// Quick type checks
const typeA = typeof a;
const typeB = typeof b;
if (typeA !== typeB) return false;
// Handle null/undefined
if (a === null || b === null || a === undefined || b === undefined) return a === b;
// Handle primitives (fastest path)
if (typeA !== 'object') {
return typeA === 'function' ? a === b : a === b;
}
// Check cache for objects
const cachedResult = deepEqualCache.get(a, b);
if (cachedResult !== undefined) {
return cachedResult;
}
let result: boolean;
// Handle special object types
if (a instanceof Date && b instanceof Date) {
result = a.getTime() === b.getTime();
} else if (Array.isArray(a)) {
if (!Array.isArray(b) || a.length !== b.length) {
result = false;
} else {
result = true;
for (let i = 0; i < a.length; i++) {
if (!deepEqual(a[i], b[i], depth + 1)) {
result = false;
break;
}
}
}
} else if (Array.isArray(b)) {
result = false;
} else {
// Handle plain objects
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) {
result = false;
} else {
result = true;
// Use Set for O(1) key lookups with many keys
const keySetB = keysA.length > CONFIG.REACT_HOOK.KEY_LOOKUP_SET_THRESHOLD ? new Set(keysB) : keysB;
for (const key of keysA) {
const hasKey = Array.isArray(keySetB) ? keySetB.includes(key) : keySetB.has(key);
if (!hasKey || !deepEqual(a[key], b[key], depth + 1)) {
result = false;
break;
}
}
}
}
// Cache the result
deepEqualCache.set(a, b, result);
return result;
}
// Memory-safe deep memoization hook with proper cleanup
function useDeepMemo<T>(value: T, deps?: React.DependencyList): T {
// Use separate refs to avoid closure capturing issues
const currentValueRef = useRef<T>(value);
const previousValueRef = useRef<T>(value);
const previousDepsRef = useRef<React.DependencyList | undefined>(deps);
const isFirstRenderRef = useRef(true);
// Calculate if value has changed without capturing it in closure
const shouldUpdate = useMemo(() => {
// First render - always use the new value
if (isFirstRenderRef.current) {
isFirstRenderRef.current = false;
return true;
}
// No dependencies provided - compare values directly
if (!deps && !previousDepsRef.current) {
return !deepEqual(value, previousValueRef.current);
}
// Dependencies provided - check if they changed
if (!deps || !previousDepsRef.current || deps.length !== previousDepsRef.current.length) {
return true;
}
// Deep compare each dependency
for (let i = 0; i < deps.length; i++) {
if (!deepEqual(deps[i], previousDepsRef.current[i])) {
return true;
}
}
return false;
}, deps || []);
// Update refs when necessary - avoid memory leaks by updating both refs
if (shouldUpdate) {
// Clear previous value to help GC
previousValueRef.current = currentValueRef.current;
currentValueRef.current = value;
previousDepsRef.current = deps;
}
// Cleanup effect to clear refs on unmount
useEffect(() => {
return () => {
// Clear all refs to prevent memory leaks
currentValueRef.current = null as any;
previousValueRef.current = null as any;
previousDepsRef.current = undefined;
};
}, []);
return currentValueRef.current;
}
// Enhanced hook that tracks memory usage and provides debugging
export function useDeepMemoWithDebug<T>(value: T, deps?: React.DependencyList, debugName?: string): T {
const result = useDeepMemo(value, deps);
// Development-only memory tracking
useEffect(() => {
if (process.env.NODE_ENV === 'development' && debugName) {
try {
const memUsage = typeof performance !== 'undefined' ? (performance as any).memory : undefined;
if (memUsage && memUsage.usedJSHeapSize) {
console.debug(`useDeepMemo[${debugName}]: ${(memUsage.usedJSHeapSize / CONFIG.MEMORY.BYTES_TO_KB / CONFIG.MEMORY.KB_TO_MB).toFixed(2)}MB`);
}
} catch (e) {
// Ignore memory access errors
}
}
});
return result;
}
// Export performance debugging utilities
export const debugUtils = {
getDeepEqualStats: () => deepEqualCache.getStats(),
clearDeepEqualCache: () => {
(deepEqualCache as any).cache = new WeakMap();
},
// Concurrent rendering debugging
getRoughInstanceCount: () => roughStore.getSnapshot().size,
getShapeCacheSize: () => shapeStore.getSnapshot().size,
clearRoughInstances: () => roughStore.clear(),
clearShapeCache: () => shapeStore.clearCache(),
// Memory pressure monitoring
getMemoryPressure: () => MemoryMonitor.getInstance().getMemoryPressureLevel(),
getRecommendedCacheSize: () => MemoryMonitor.getInstance().getRecommendedCacheSize(),
forceMemoryCleanup: () => {
const monitor = MemoryMonitor.getInstance();
if (monitor.shouldAgressivelyCleanup()) {
shapeStore.clearCache();
(deepEqualCache as any).cache = new WeakMap();
if (typeof global !== 'undefined' && global.gc) {
try { global.gc(); } catch (e) { /* ignore */ }
}
}
},
// Full cleanup for testing
clearAllCaches: () => {
(deepEqualCache as any).cache = new WeakMap();
roughStore.clear();
shapeStore.clearCache();
},
};
/**
* React hook that provides a RoughReactNativeSVG instance with automatic cleanup
* Concurrent rendering safe with useSyncExternalStore
* @param config - Optional configuration for the rough instance
* @returns RoughReactNativeSVG instance that will be automatically disposed on unmount
*/
export function useRough(config?: Config): RoughReactNativeSVG {
const instanceIdRef = useRef<string | null>(null);
const stableConfig = useDeepMemo(config, [config]);
// Use concurrent-safe external store
const storeSnapshot = useSyncExternalStore(
roughStore.subscribe.bind(roughStore),
roughStore.getSnapshot.bind(roughStore),
roughStore.getSnapshot.bind(roughStore) // Server snapshot (same as client)
);
// Get or create instance with concurrent safety
const rough = useMemo(() => {
if (!instanceIdRef.current) {
instanceIdRef.current = roughStore.createInstance(stableConfig);
} else {
// Update existing instance if config changed
roughStore.updateInstance(instanceIdRef.current, stableConfig);
}
return roughStore.getInstance(instanceIdRef.current);
}, [stableConfig, storeSnapshot]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (instanceIdRef.current) {
roughStore.deleteInstance(instanceIdRef.current);
instanceIdRef.current = null;
}
};
}, []);
if (!rough) {
throw new Error('Failed to create RoughReactNativeSVG instance');
}
return rough;
}
/**
* React hook for creating shapes with automatic lifecycle management
* Concurrent rendering safe with cached shape generation
* @param shapeType - Type of shape to create
* @param params - Parameters for the shape
* @param options - Rough.js options
* @param config - Optional configuration for the rough instance
* @returns Rendered shape element
*/
export function useRoughShape<T extends keyof ShapeParams>(
shapeType: T,
params: ShapeParams[T],
options?: Options,
config?: Config
) {
const rough = useRough(config);
// Use deep memoization for complex parameters
const stableParams = useDeepMemo(params, [params]);
const stableOptions = useDeepMemo(options, [options]);
// Generate stable cache key for this shape
const shapeKey = useMemo(() => {
return `${shapeType}-${JSON.stringify(stableParams)}-${JSON.stringify(stableOptions)}`;
}, [shapeType, stableParams, stableOptions]);
// Use concurrent-safe shape generation store
const storeSnapshot = useSyncExternalStore(
shapeStore.subscribe.bind(shapeStore),
shapeStore.getSnapshot.bind(shapeStore),
shapeStore.getSnapshot.bind(shapeStore)
);
// Generate shape with concurrent safety
const shape = useMemo(() => {
return shapeStore.generateShape(shapeKey, () => {
switch (shapeType) {
case 'line': {
const [x1, y1, x2, y2] = stableParams as [number, number, number, number];
return rough.line(x1, y1, x2, y2, stableOptions);
}
case 'rectangle': {
const [x, y, width, height] = stableParams as [number, number, number, number];
return rough.rectangle(x, y, width, height, stableOptions);
}
case 'ellipse': {
const [ex, ey, ew, eh] = stableParams as [number, number, number, number];
return rough.ellipse(ex, ey, ew, eh, stableOptions);
}
case 'circle': {
const [cx, cy, diameter] = stableParams as [number, number, number];
return rough.circle(cx, cy, diameter, stableOptions);
}
case 'linearPath': {
const points = stableParams as Point[];
return rough.linearPath(points, stableOptions);
}
case 'polygon': {
const polyPoints = stableParams as Point[];
return rough.polygon(polyPoints, stableOptions);
}
case 'arc': {
const [ax, ay, aw, ah, start, stop, closed] = stableParams as [number, number, number, number, number, number, boolean?];
return rough.arc(ax, ay, aw, ah, start, stop, closed || false, stableOptions);
}
case 'curve': {
const curvePoints = stableParams as Point[] | Point[][];
return rough.curve(curvePoints, stableOptions);
}
case 'path': {
const pathData = stableParams as string;
return rough.path(pathData, stableOptions);
}
default:
throw new Error(`Unknown shape type: ${shapeType}`);
}
});
}, [shapeKey, rough, shapeType, stableParams, stableOptions, storeSnapshot]);
// Return cached result or empty element if still generating
return shape || { props: {}, children: [] };
}
/**
* React hook for batch creating multiple shapes with shared configuration
* Concurrent rendering safe with batch shape generation
* @param shapes - Array of shape definitions
* @param config - Optional configuration for the rough instance
* @returns Array of rendered shape elements
*/
export function useRoughShapes(
shapes: ShapeDefinition[],
config?: Config
) {
const rough = useRough(config);
// Use deep memoization for the shapes array
const stableShapes = useDeepMemo(shapes, [shapes]);
// Generate stable cache key for the entire batch
const batchKey = useMemo(() => {
return `batch-${JSON.stringify(stableShapes)}`;
}, [stableShapes]);
// Use concurrent-safe shape generation store
const storeSnapshot = useSyncExternalStore(
shapeStore.subscribe.bind(shapeStore),
shapeStore.getSnapshot.bind(shapeStore),
shapeStore.getSnapshot.bind(shapeStore)
);
// Generate batch of shapes with concurrent safety
const renderedShapes = useMemo(() => {
return shapeStore.generateShape(batchKey, () => {
return stableShapes.map((shape, shapeIndex) => {
try {
const { type, params, options } = shape;
switch (type) {
case 'line': {
const [x1, y1, x2, y2] = params as [number, number, number, number];
return rough.line(x1, y1, x2, y2, options);
}
case 'rectangle': {
const [x, y, width, height] = params as [number, number, number, number];
return rough.rectangle(x, y, width, height, options);
}
case 'ellipse': {
const [ex, ey, ew, eh] = params as [number, number, number, number];
return rough.ellipse(ex, ey, ew, eh, options);
}
case 'circle': {
const [cx, cy, diameter] = params as [number, number, number];
return rough.circle(cx, cy, diameter, options);
}
case 'linearPath': {
const points = params as Point[];
return rough.linearPath(points, options);
}
case 'polygon': {
const polyPoints = params as Point[];
return rough.polygon(polyPoints, options);
}
case 'arc': {
const [ax, ay, aw, ah, start, stop, closed] = params as [number, number, number, number, number, number, boolean?];
return rough.arc(ax, ay, aw, ah, start, stop, closed || false, options);
}
case 'curve': {
const curvePoints = params as Point[] | Point[][];
return rough.curve(curvePoints, options);
}
case 'path': {
const pathData = params as string;
return rough.path(pathData, options);
}
default:
return { props: {}, children: [] };
}
} catch (error) {
// Return empty element for individual shape errors
return { props: {}, children: [], error: `Shape ${shapeIndex} failed: ${String(error)}` };
}
});
});
}, [batchKey, rough, stableShapes, storeSnapshot]);
// Return cached results or empty array if still generating
return renderedShapes || [];
}
/**
* React hook that provides a stable rough instance that only recreates when config changes deeply
* @param config - Configuration for the rough instance
* @returns RoughReactNativeSVG instance
*/
export function useStableRough(config?: Config): RoughReactNativeSVG {
const configRef = useRef<Config | undefined>(undefined);
const roughRef = useRef<RoughReactNativeSVG | null>(null);
// Use deep equality instead of JSON.stringify for better performance
const configChanged = useMemo(() => {
if (!config && !configRef.current) return false;
if (!config || !configRef.current) return true;
return !deepEqual(config, configRef.current);
}, [config]);
const rough = useMemo(() => {
if (!roughRef.current || configChanged) {
if (roughRef.current) {
roughRef.current.dispose();
}
roughRef.current = new RoughReactNativeSVG(config);
configRef.current = config;
}
return roughRef.current;
}, [config, configChanged]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (roughRef.current) {
roughRef.current.dispose();
roughRef.current = null;
}
};
}, []);
return rough;
}
// Type definitions for shape parameters
interface ShapeParams {
line: [number, number, number, number];
rectangle: [number, number, number, number];
ellipse: [number, number, number, number];
circle: [number, number, number];
linearPath: Point[];
polygon: Point[];
arc: [number, number, number, number, number, number, boolean?];
curve: Point[] | Point[][];
path: string;
}
interface ShapeDefinition {
type: keyof ShapeParams;
params: ShapeParams[keyof ShapeParams];
options?: Options;
}
// Export types for consumers
export type { ShapeParams, ShapeDefinition };