@nasi/ppx-reanimated-worklet
v0.1.3
Published
[Esy dependency] PPX rewriters for React Native Reanimated
Readme
ppx-reanimated-worklet
PPX Rewriters for React Native Reanimated
This rewriter adds the following extensions:
%wklt%worklet%runOnJS%runOnUI%apply
Installation
- Install
ppx-install
npm install --save-dev ppx-install- Add the following to
package.json
{
"ppx": ["@nasi/ppx-reanimated-worklet"]
}- Add the following to
bsconfig.json
{
"ppx-flags": ["ppx-install"]
}- Prebuild the PPX rewriter
npx ppx-install --build%wklt
This extension works on ReasonML and OCaml, and rewrites the following:
let%wklt f a b = a + binto
function f(a, b) {
"worklet";
return a + b;
}here, f has type:
type f : (int -> int -> int) Reanimated.worklet2NOTE The equivalent syntax in ReScript is below. However, it is untested.
%%wklt(let f = (a, b) => a + b)%worklet
This allows any function expression to be written as a React Native Reanimated 2 worklet, as such:
@react.component
let make = () => {
let f = %worklet(() => viewStyle());
// useAnimatedStyle expects the function inside to be a worklet.
// Although it can take any function expression that doesn't have
// the "worklet" directive, if you're passing a function by value,
// then that function must be defined with the "worklet" directive
// for it to be visible on the UI JS runtime.
let style = useAnimatedStyle(f);
<Reanimated.View style />
}%runOnJS
A wrapper around React Native Reanimated 2's runOnJS method. Use as such:
let log = (a) => {
// some logic that doesn't exist in UI thread
Js.log(foo(a));
}
let f = %worklet((a) => {
%runOnJS(log(a))
})The above function translates roughly to:
function log(a) {
console.log(foo(a));
}
// Note that Curry._x utility functions won't be
// generated here. However, if lists and other ML
// data structures are used, they'll show up here,
// and since they're not serialised into the UI
// thread, the app will crash.
function f(a) {
"worklet";
let g = runOnJS(log);
g(a);
}%runOnUI
Similar to %runOnJS, wraps the runOnUI method in React Native Reanimated 2.
%apply
This extension is used to wrap a function call to a worklet. A worklet can be called in either a host function or a worklet.
let worklet = %worklet((a) => a + 1)
let f = (a) => %apply(worklet(a))
let worklet2 = %worklet((a) => %apply(worklet(a)))This creates the below translation:
function worklet(a) {
"worklet";
return a + 1;
}
function f(a) {
return worklet(a);
}
// Note that Curry._x utility functions won't be
// generated here. However, if lists and other ML
// data structures are used, they'll show up here,
// and since they're not serialised into the UI
// thread, the app will crash.
function worklet2(a) {
"worklet";
return worklet(a);
}