|
| 1 | +import { |
| 2 | + blockStatement, |
| 3 | + directive, |
| 4 | + directiveLiteral, |
| 5 | + returnStatement, |
| 6 | +} from '@babel/types'; |
| 7 | + |
| 8 | +import type { |
| 9 | + Expression, |
| 10 | + Program, |
| 11 | + BlockStatement, |
| 12 | + VariableDeclaration, |
| 13 | +} from '@babel/types'; |
| 14 | +import type { NodePath } from '@babel/core'; |
| 15 | +import type { ReanimatedPluginPass } from './types'; |
| 16 | + |
| 17 | +export function processIfWorkletFile( |
| 18 | + path: NodePath<Program>, |
| 19 | + state: ReanimatedPluginPass |
| 20 | +) { |
| 21 | + if ( |
| 22 | + path.node.directives.some( |
| 23 | + (functionDirective) => functionDirective.value.value === 'worklet' |
| 24 | + ) |
| 25 | + ) { |
| 26 | + processWorkletFile(path, state); |
| 27 | + // Remove 'worklet' directive from the file afterwards. |
| 28 | + path.node.directives = path.node.directives.filter( |
| 29 | + (functionDirective) => functionDirective.value.value !== 'worklet' |
| 30 | + ); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +function processWorkletFile( |
| 35 | + path: NodePath<Program>, |
| 36 | + _state: ReanimatedPluginPass |
| 37 | +) { |
| 38 | + path.get('body').forEach((bodyPath) => { |
| 39 | + if (bodyPath.isVariableDeclaration()) { |
| 40 | + processVariableDeclaration(bodyPath); |
| 41 | + } |
| 42 | + if (bodyPath.isFunctionDeclaration()) { |
| 43 | + appendWorkletDirective(bodyPath.node.body); |
| 44 | + } |
| 45 | + }); |
| 46 | +} |
| 47 | + |
| 48 | +function processVariableDeclaration(path: NodePath<VariableDeclaration>) { |
| 49 | + path.get('declarations').forEach((declaration) => { |
| 50 | + const initPath = declaration.get('init'); |
| 51 | + if (initPath.isFunctionExpression()) { |
| 52 | + appendWorkletDirective(initPath.node.body); |
| 53 | + } else if (initPath.isArrowFunctionExpression()) { |
| 54 | + const bodyPath = initPath.get('body'); |
| 55 | + |
| 56 | + // In case of arrow function with no body, i.e. () => 1. |
| 57 | + if (!bodyPath.isBlockStatement()) { |
| 58 | + bodyPath.replaceWith( |
| 59 | + blockStatement([returnStatement(bodyPath.node as Expression)]) |
| 60 | + ); |
| 61 | + } |
| 62 | + appendWorkletDirective(bodyPath.node as BlockStatement); |
| 63 | + } else if (initPath.isObjectExpression()) { |
| 64 | + initPath.node.properties.forEach((property) => { |
| 65 | + if (property.type === 'ObjectMethod') { |
| 66 | + appendWorkletDirective(property.body); |
| 67 | + } |
| 68 | + }); |
| 69 | + } |
| 70 | + }); |
| 71 | +} |
| 72 | + |
| 73 | +function appendWorkletDirective(node: BlockStatement) { |
| 74 | + if ( |
| 75 | + !node.directives.some( |
| 76 | + (functionDirective) => functionDirective.value.value === 'worklet' |
| 77 | + ) |
| 78 | + ) { |
| 79 | + node.directives.push(directive(directiveLiteral('worklet'))); |
| 80 | + } |
| 81 | +} |
0 commit comments