Skip to content

dmjio/sphynx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

sphynx 🐈

About

This is a barebones LynxJS project meant to demonstrate cross-thread communication between background (BTS) and main threads (MTS). This will help other compile-to-JS languages target LynxJS. This also enables the consumption of Native Modules for interacting with device APIs.

Walkthrough

The background thread is able to communicate with the main thread via a context object.

const context = lynx.getCoreContext();

Similarly, the main thread is able to communicate with the background thread via the same mechanism.

const context = lynx.getJSContext();

Event listeners for the "message" event (shown below) are added to each thread. This allows each thread to relay messsages between each other via a call to .postMessage(data). This is made possible via the Web Worker API.

MTS setup

// dmj: executed by MTS
globalThis['renderPage'] = function () {
  const context = lynx.getJSContext();
  context.addEventListener("message", (event) => {
    console.log('got event in js context', event);
  });
  lynx.requestAnimationFrame(stepMain);
}

BTS setup

This function should be invoked top-level (e.g. initBackground())

function initBackground () {
  'background only'
  const context = lynx.getCoreContext();
  context.addEventListener("message", (event) => {
    console.log('got event in core context', event);
  });
  lynx.requestAnimationFrame(stepBG);
}

The communication occurs in each thread's event loop.

function stepMain (frame) {
  const context = lynx.getJSContext();
  context.postMessage({ bg : frame });
  lynx.requestAnimationFrame(stepMain);
}

function stepBG (frame) {
  const context = lynx.getCoreContext();
  context.postMessage({ main : frame });
  lynx.requestAnimationFrame(stepBG);
}

Lynx DevTool

The communication can be observed in the LynxExplorer.

Screenshot 2025-08-30 at 10 06 08 AM

Plugin

The ReactLynxPlugin is used to facilitate code splitting. This ensures code marked with 'background-only' only executes on the background thread.

 import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin'

See the full source.

Getting Started

First, install the dependencies:

pnpm install

Then, run the development server:

pnpm run dev

Scan the QRCode in the terminal with your LynxExplorer App to see the result.

You can start editing the page by modifying src/App.tsx. The page auto-updates as you edit the file.

Name

The sphynx cat has no hair.

About

This is a barebones LynxJS project meant to demonstrate cross-thread communication

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published