1 | 'use strict';
|
2 | import { useRef } from 'react';
|
3 | import { makeMutable } from './core';
|
4 | import type { SharedValue } from './commonTypes';
|
5 | import type { Descriptor } from './hook/commonTypes';
|
6 | import { shouldBeUseWeb } from './PlatformChecker';
|
7 |
|
8 | export interface ViewRefSet<T> {
|
9 | items: Set<T>;
|
10 | add: (item: T) => void;
|
11 | remove: (item: T) => void;
|
12 | }
|
13 |
|
14 | export interface ViewDescriptorsSet {
|
15 | shareableViewDescriptors: SharedValue<Descriptor[]>;
|
16 | add: (item: Descriptor) => void;
|
17 | remove: (viewTag: number) => void;
|
18 | }
|
19 |
|
20 | export function makeViewDescriptorsSet(): ViewDescriptorsSet {
|
21 | const shareableViewDescriptors = makeMutable<Descriptor[]>([]);
|
22 | const data: ViewDescriptorsSet = {
|
23 | shareableViewDescriptors,
|
24 | add: (item: Descriptor) => {
|
25 | shareableViewDescriptors.modify((descriptors) => {
|
26 | 'worklet';
|
27 | const index = descriptors.findIndex(
|
28 | (descriptor) => descriptor.tag === item.tag
|
29 | );
|
30 | if (index !== -1) {
|
31 | descriptors[index] = item;
|
32 | } else {
|
33 | descriptors.push(item);
|
34 | }
|
35 | return descriptors;
|
36 | }, false);
|
37 | },
|
38 |
|
39 | remove: (viewTag: number) => {
|
40 | shareableViewDescriptors.modify((descriptors) => {
|
41 | 'worklet';
|
42 | const index = descriptors.findIndex(
|
43 | (descriptor) => descriptor.tag === viewTag
|
44 | );
|
45 | if (index !== -1) {
|
46 | descriptors.splice(index, 1);
|
47 | }
|
48 | return descriptors;
|
49 | }, false);
|
50 | },
|
51 | };
|
52 | return data;
|
53 | }
|
54 |
|
55 | const SHOULD_BE_USE_WEB = shouldBeUseWeb();
|
56 |
|
57 | export const useViewRefSet = SHOULD_BE_USE_WEB
|
58 | ? useViewRefSetJS
|
59 | : useViewRefSetNative;
|
60 |
|
61 | function useViewRefSetNative() {
|
62 |
|
63 | return undefined;
|
64 | }
|
65 |
|
66 | function useViewRefSetJS<T>(): ViewRefSet<T> {
|
67 | const ref = useRef<ViewRefSet<T> | null>(null);
|
68 | if (ref.current === null) {
|
69 | const data: ViewRefSet<T> = {
|
70 | items: new Set(),
|
71 |
|
72 | add: (item: T) => {
|
73 | if (data.items.has(item)) {
|
74 | return;
|
75 | }
|
76 | data.items.add(item);
|
77 | },
|
78 |
|
79 | remove: (item: T) => {
|
80 | data.items.delete(item);
|
81 | },
|
82 | };
|
83 | ref.current = data;
|
84 | }
|
85 |
|
86 | return ref.current;
|
87 | }
|