UNPKG

1.49 kBPlain TextView Raw
1'use strict';
2import { shouldBeUseWeb } from './PlatformChecker';
3import type { ShareableRef } from './commonTypes';
4
5const SHOULD_BE_USE_WEB = shouldBeUseWeb();
6
7/**
8 * This symbol is used to represent a mapping from the value to itself.
9 *
10 * It's used to prevent converting a shareable that's already converted -
11 * for example a Shared Value that's in worklet's closure.
12 **/
13export const shareableMappingFlag = Symbol('shareable flag');
14
15/*
16During a fast refresh, React holds the same instance of a Mutable
17(that's guaranteed by `useRef`) but `shareableCache` gets regenerated and thus
18becoming empty. This happens when editing the file that contains the definition of this cache.
19
20Because of it, `makeShareableCloneRecursive` can't find given mapping
21in `shareableCache` for the Mutable and tries to clone it as if it was a regular JS object.
22During cloning we use `Object.entries` to iterate over the keys which throws an error on accessing `_value`.
23For convenience we moved this cache to a separate file so it doesn't scare us with red squiggles.
24*/
25
26const cache = SHOULD_BE_USE_WEB
27 ? null
28 : new WeakMap<object, ShareableRef | symbol>();
29
30export const shareableMappingCache = SHOULD_BE_USE_WEB
31 ? {
32 set() {
33 // NOOP
34 },
35 get() {
36 return null;
37 },
38 }
39 : {
40 set(shareable: object, shareableRef?: ShareableRef): void {
41 cache!.set(shareable, shareableRef || shareableMappingFlag);
42 },
43 get: cache!.get.bind(cache),
44 };