1import { ExpoWebGLRenderingContext } from './GLView.types';
2
3// This method needs to be in a separate file because react-native-reanimated
4// import wrapped in try catch does not work correctly with inlineRequires option
5// in metro.config.js
6//
7// It looks like in generated bundle "react-native-reanimated" is not present
8// in _dependencyMap, but references to it count it as if it was, e.g. bundle contains
9// a line "(0, _$$_REQUIRE(_dependencyMap[15], "./GLUtils").configureLogging)(gl);"
10// but dependencyMap contains only 15 elements
11export function createWorkletContextManager(): {
12  getContext: (contextId: number) => ExpoWebGLRenderingContext | undefined;
13  unregister?: (contextId: number) => void;
14} {
15  try {
16    // reanimated needs to be imported before any workletized code
17    // is created, but we don't want to make it dependency on expo-gl.
18    const { runOnUI } = require('react-native-reanimated');
19    return {
20      getContext: (contextId: number): ExpoWebGLRenderingContext | undefined => {
21        'worklet';
22        return global.__EXGLContexts?.[String(contextId)];
23      },
24      unregister: (contextId: number): void => {
25        runOnUI((contextId: number) => {
26          'worklet';
27          if (global.__EXGLContexts) {
28            delete global.__EXGLContexts[String(contextId)];
29          }
30        })(contextId);
31      },
32    };
33  } catch {
34    return {
35      getContext: () => {
36        throw new Error('Worklet runtime is not available');
37      },
38    };
39  }
40}
41