Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Workletizable Context Objects #6284

Merged
merged 4 commits into from
Jul 17, 2024
Merged

Workletizable Context Objects #6284

merged 4 commits into from
Jul 17, 2024

Conversation

tjzel
Copy link
Collaborator

@tjzel tjzel commented Jul 17, 2024

This pull request introduces the concept of Context Objects on the Worklet Runtime.

What?

Context Object is a shareable object that doesn't lose its this binding when it goes to the Worklet Runtime. To define an object as a Context Object, the user has to define property __workletContextObject on it. The value of this property doesn't matter.

// Explicit Context Object
const obj = {
  foo() { return 1; },
  bar() { return this.foo(); },
  __workletContextObject: true,
}

Context Objects are also auto-detected when Babel processes files marked with a worklet directive. If a top level object has a method that references this inside we treat is as a Context Object.

'worklet';
// Implicit Context Object
const obj = {
  foo() { return 1; },
  bar() { return this.foo(); },
};

Why?

Currently it's not possible to refer to an object's methods from its other methods.

const obj = {
  foo() {
    console.log("foo");
  }
  bar() {
    this.foo();
  }
}

runOnUI(() => {
  obj.bar(); // Crash, the binding is lost on serialization.
})();

How?

Context Objects are handled as another type of shareable entity on the React Runtime.

  1. The plugin adds a special property __workletObjectFactory to Context Objects. It's a function that creates an identical object.
  2. We serialize the factory instead of the object itself.
  3. We recreate the object on the Worklet Runtime via ShareableHandle mechanism.

Test plan

  • Add unit tests
  • Add a runtime test suite

@tjzel tjzel changed the title @tjzel/plugin/context objects Workletizable Context Objects Jul 17, 2024
@tjzel tjzel force-pushed the @tjzel/plugin/context-objects branch from 2717279 to ce914e6 Compare July 17, 2024 12:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants