Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: binding errors
Preetham Pemmasanieee492437333
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0138825..ef1fc4d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,14 +7,25 @@ All notable changes to **blenderui** (BUI). The format follows## [Unreleased]### Added (JavaScript)-- **`@blenderui/native`** (`bindings/node`, napi-rs crate `blenderui-node`): BUI from Node.js in native windows, GPUIX style.- - A DOM-like API: `createElement`, `setAttribute`, `appendChild`, `addEventListener`, `requestAnimationFrame`, `getBoundingClientRect`, `screenshot`.- - BUI runs on its own UI thread, so Node is never blocked and an idle UI uses no CPU.+- **`@blender-ui/native`** (`bindings/node`, napi-rs crate `blenderui-node`): BUI from JavaScript in native windows, GPUIX style, on **Node.js and Bun**.+ - A DOM-like API: `createElement`, `setAttribute`, `appendChild`, `insertBefore`, `addEventListener` (events bubble; `stopPropagation` works), `requestAnimationFrame`, `getBoundingClientRect`, `screenshot`.+ - BUI runs on its own UI thread, so JavaScript is never blocked and an idle UI uses no CPU.- Each tick sends only the changes: one `Int32Array` of ops and a string table per window. Events return through a thread-safe function.- Animation frames are vsync-paced with one rebuild per frame.- Headless mode for tests.-- **`@blenderui/react`** (`bindings/react`): a React 19 renderer (react-reconciler 0.31) with HTML host components, `className` / `style` objects / events, and one native batch per commit.-- **Signals in JavaScript**: the Rust hooks' `Signal` / `Memo` / `Effect` as `signal`, `memo`, `effect`, `batch` (plain JS) and `useSignal`, `useComputed`, `useSignalEffect`, `useSignalValue` (React). A signal passed as an attribute, `style`, text, React prop or React child updates that node alone, without a re-render: React at 3,000 cells drops from ~184 MB to ~95 MB.+ - **Signals** (the Rust hooks' `Signal` / `Memo` / `Effect`): `signal`, `memo`, `effect`, `batch`, `untrack`, `startTransition`, `ref`. A signal bound to an attribute, `style` or text updates that node alone. Also usable without the addon (`@blender-ui/native/signals`).+ - Push-pull and glitch-free.+ - Unobserved memos hold no subscriptions.+ - Transitions run their effects after urgent ones, in 5 ms slices.+- **`@blender-ui/react`** (`bindings/react`): a React 19.3 renderer (react-reconciler 0.34).+ - **Hooks by React's names, backed by signals:** `useState`, `useReducer`, `useRef`, `useMemo`, `useCallback`, `useEffectEvent`, `useEffect` / `useLayoutEffect` / `useInsertionEffect`, `useSyncExternalStore`, `useTransition`, `useDeferredValue`, `useActionState` and `useOptimistic` take React's arguments and run at React's moments.+ - Passed as a prop or child, their state updates that node without a re-render.+ - Read while rendering, it re-renders the component, as with React.+ - At 3,000 cells, React with signals costs about what the plain API does: about a quarter less CPU per frame and memory than re-rendering (production builds).+ - **Conformance suite:** runs each hook beside React's original (development and production builds, StrictMode). It fails when React adds a hook that isn't covered, which caught React 19.2's `useEffectEvent`.+ - **JSX runtime** (`"jsxImportSource": "@blender-ui/react"`): render tracking for components, and types that let host props take signals.+ - **Host components:** HTML host components, `className` / `style` objects / events, and one native batch per commit. `<Suspense>`, `<Activity>`, actions and `<ViewTransition>` (without animation) work.+- **Benchmarks** for JavaScript (`bindings/node/bench/cells.js`, Node or Bun) measure CPU with the process cycle counter, as the Rust benchmark does.- **Rust:**- `UiSender` / `App::ui_sender()`: run closures on the UI thread from any thread.- `Application::keep_alive`, `App::run_pending`, `App::on_window_closed`, `App::close_window`, `Div::key`, `blenderui::native_windows()`.diff --git a/README.md b/README.mdindex 628985b..fa2c0b7 100644--- a/README.md+++ b/README.md@@ -46,7 +46,7 @@ You can drive it five ways, and all of them share the same C runtime:| **Qt-style** Python (`QWidget`, layouts, `clicked.connect`) | The common subset of Qt widgets | π‘ Partial || **Blender components** in Python (`Panel`, `NumberSlider`, `PieMenu` ...) | 45 native Blender widgets and editors | β Complete || **Rust**: HTML + CSS + Tailwind, JSX (`rsx!`), hooks, or gpui syntax | A web-like framework rendered with Blender widgets | β Working |-| **JavaScript / React** from Node: a DOM-like API or JSX | The same engine in native windows, driven over napi-rs ([guide](docs/javascript.md)) | π‘ New (Windows) |+| **JavaScript / React** on Node.js or Bun: a DOM-like API or JSX | The same engine in native windows, over napi-rs; React's hooks backed by signals ([guide](docs/javascript.md)) | π‘ New (Windows) |## Quick start@@ -92,6 +92,33 @@ App("Object", (420, 520),).run()```+### JavaScript and React++```sh+npm install @blender-ui/react react # or: bun add @blender-ui/react react+```++```jsx+/** @jsxImportSource @blender-ui/react */+import { render, useState } from '@blender-ui/react'++function Counter () {+ const [count, setCount] = useState(0) // React's hook, backed by a signal+ return (+ <main className="p-6 flex flex-col gap-3">+ <span>Clicks: {count}</span>+ <button onClick={() => setCount(c => c + 1)}>Add one</button>+ </main>+ )+}++render(<Counter />, { title: 'Counter', width: 360, height: 200, gpu: true })+```++A click updates the one text node; `Counter` doesn't re-render. Without+React, `@blender-ui/native` gives you a DOM-like API with signals. Both run on+Node.js and Bun, Windows x64 for now ([guide](docs/javascript.md)).+### Rust```bash@@ -242,7 +269,7 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o| Components | 45 Blender components, including the color ramp and curve editors || Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 82/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, headless testing || Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine |-| JavaScript / React | `@blenderui/native` (DOM-like API over napi-rs, its own UI thread, only changes cross the boundary, vsync-paced `requestAnimationFrame`) and `@blenderui/react` (React 19 renderer), with BUI's signals (`useSignal`, `useComputed`, `useSignalEffect`) updating nodes without re-renders; headless testing ([guide](docs/javascript.md)) |+| JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing ([guide](docs/javascript.md)) || Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms |### π‘ Partial or in progress@@ -253,7 +280,7 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o| CSS (207 of 745 W3C properties render, 177 more parse) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`, non-solid borders. Also animations and transitions. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) || Text | No text wrapping around floats; no right-to-left shaping || Rust components | No async resources (`use_resource`); no generic components |-| JavaScript / React | Native windows on Windows only (headless elsewhere); npm packages not published yet; events are asynchronous (no native `preventDefault`) |+| JavaScript / React | Prebuilt for Windows x64 only (elsewhere: build from source, headless); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest *listening* element || Linux / macOS | They work through a fallback window (the stdlib Tk window shows BUI's frame), but they're less tested. No native window host and no GPU renderer yet || crates.io | The crates are ready to publish but not published yet; use the git dependency for now |@@ -261,7 +288,7 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o| Target | Plan ||---|---|-| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blenderui/react` and the DOM-like API on top, unchanged |+| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blender-ui/react` and the DOM-like API on top, unchanged || **egui** | BUI panels inside egui, plus a Blender-styled theme || **Native Linux / macOS windows** | Wayland / X11 and Cocoa hosts in C, like the Win32 one || **More GPU backends** | Vulkan / Metal / WebGPU drawing the same instance stream as Direct3D 11 |@@ -343,6 +370,22 @@ gpui-fast's heavy-scene frame rate varies between sessions on this laptop[bindings/rust/bench/README.md](bindings/rust/bench/README.md).</details>+JavaScript, on the same scene in `one` mode: one cell changes per frame, the+GPU renderer, medians of 3 runs. CPU is the whole process, counted the same+way as for Rust. Plain JS uses `@blender-ui/native`; React uses+`@blender-ui/react` in its production build.++| 3,000 cells | FPS | CPU per frame | RAM |+|---|---:|---:|---:|+| Rust | 59.6 | **12.0 ms** | **43 MB** |+| Bun 1.4: plain JS / React with signals / React with state | 58.8 / 58.4 / 55.8 | 13.1 / 13.3 / 20.8 ms | 80 / 85 / 118 MB |+| Node 22: plain JS / React with signals / React with state | 55.8 / 56.7 / 54.8 | 14.4 / 14.0 / 18.9 ms | 88 / 93 / 121 MB |++At 1,000 cells every configuration holds 60 FPS, at 4.8 ms per frame (Rust)+to 7.5 ms (React re-rendering). Method and more:+[docs/javascript.md](docs/javascript.md#performance).++## Documentation| Guide | What's inside |@@ -352,7 +395,7 @@ gpui-fast's heavy-scene frame rate varies between sessions on this laptop| [Qt syntax](docs/qt.md) | Classes, signals, layouts, painting, coverage || [Components](docs/components.md) | The `bui.components` reference || [Rust](docs/rust.md) | `rsx!`, hooks, HTML, CSS and Tailwind coverage, events, headless tests |-| [JavaScript and React](docs/javascript.md) | `@blenderui/native`, `@blenderui/react`, how changes cross to the UI thread, performance |+| [JavaScript and React](docs/javascript.md) | `@blender-ui/native`, `@blender-ui/react`, how changes cross to the UI thread, performance || [C API](docs/c-api.md) | The C kit (`BUI_kit.h`) || [Integration](INTEGRATION.md) | Embedding BUI drawing in C, C++, Qt or PySide hosts || [Architecture](ARCHITECTURE.md) | Modules and what was taken from Blender |diff --git a/bindings/.gitignore b/bindings/.gitignorenew file mode 100644index 0000000..c2658d7--- /dev/null+++ b/bindings/.gitignore@@ -0,0 +1 @@+node_modules/diff --git a/bindings/node/.gitignore b/bindings/node/.gitignoreindex 4c8908a..e41c098 100644--- a/bindings/node/.gitignore+++ b/bindings/node/.gitignore@@ -1,2 +1,3 @@*.nodenode_modules/+LICENSEdiff --git a/bindings/node/README.md b/bindings/node/README.mdindex 165d6e4..4e25cf4 100644--- a/bindings/node/README.md+++ b/bindings/node/README.md@@ -1,30 +1,69 @@-# @blenderui/native+# @blender-ui/native-Blender's UI from JavaScript: native windows (CPU or Direct3D 11), HTML-elements, CSS and Tailwind classes, driven from Node through napi-rs. BUI-runs on its own thread, and only the changes of each tick cross into Rust.+Blender's UI toolkit from JavaScript: native windows drawn on the CPU or with+Direct3D 11, HTML elements, CSS and Tailwind classes, and signals. It runs on+Node.js and Bun through a native addon (napi-rs), with no browser and no+Electron. For React, see+[`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react).++```sh+npm install @blender-ui/native+``````js-const { App } = require('@blenderui/native')+const { App, signal } = require('@blender-ui/native')+const app = new App({ gpu: true })const win = app.window({ title: 'Hello', width: 360, height: 200 })+win.body.className = 'm-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]'++const clicks = signal(0)+const label = win.createElement('span')+label.textContent = clicks // follows the signalconst button = win.createElement('button')-button.className = 'm-4'-button.textContent = 'Click me'-button.addEventListener('click', () => { button.textContent = 'Clicked' })+button.textContent = 'Add one'+button.addEventListener('click', () => clicks.value++)+win.body.appendChild(label)win.body.appendChild(button)```-Signals (BUI's hooks: `signal`, `memo`, `effect`, `batch`) bind to-attributes, `style` and text, so a change updates that node alone:+## API-```js-const { signal } = require('@blenderui/native')-const clicks = signal(0)-button.textContent = clicks // follows the signal-button.addEventListener('click', () => clicks.value++)-```+- **A DOM-like tree:** `createElement`, `createTextNode`, `appendChild`,+ `insertBefore`, `removeChild`, `setAttribute`, `className` (with Tailwind+ classes), `style` (a string or an object), `textContent`.+- **Events:** `addEventListener` for `click`, `mousedown`, `mouseup`,+ `mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input`+ and `change`. They bubble through the tree, and `stopPropagation()` works.+ They arrive after BUI has handled them, so `preventDefault()` only marks the+ event.+- **Frames and measurement:** `win.requestAnimationFrame(cb)` is paced by the+ display. `el.getBoundingClientRect()` and `win.screenshot()` return+ promises.+- **Signals:** `signal`, `memo`, `effect`, `batch`, `untrack`,+ `startTransition`. Pass a signal to `setAttribute`, `style`, `textContent`+ or `createTextNode`, and its changes update that node alone. The signals are+ also available without the addon: `require('@blender-ui/native/signals')`.+- **Tests:** `new App({ headless: true })` renders off-screen, and+ `win.click(x, y)` simulates input.++## How it's fast++- **Its own UI thread:** BUI renders on a thread of its own, so it never+ blocks Node and an idle window uses no CPU.+- **Only changes cross:** each tick, a window sends one batch of operations+ (an `Int32Array` and a string table) to the UI thread.+- **Styles parsed once:** a `style` value is parsed when it's set, not every+ frame.++## Requirements++- **Prebuilt for Windows x64.** On other platforms, build from a clone of the+ [repository](https://github.com/ppmpreetham/BUI) with `npm run build` in+ `bindings/node`. That needs Rust, CMake and a C compiler; native windows+ there are not supported yet, so use `headless: true`.+- **Runtimes:** Node.js 18 or newer, or Bun.-React: [`@blenderui/react`](../react). Guide, internals and benchmarks:-[docs/javascript.md](../../docs/javascript.md). Windows x64 for native-windows; `headless: true` works anywhere. License: GPL-2.0-or-later.+Guide, benchmarks and internals:+[docs/javascript.md](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md).+License: GPL-2.0-or-later.diff --git a/bindings/node/bench/cells.js b/bindings/node/bench/cells.jsindex ce00ddc..f4490f0 100644--- a/bindings/node/bench/cells.js+++ b/bindings/node/bench/cells.js@@ -2,15 +2,19 @@// grid of N cells; every frame (16 ms) cell 0 changes colour and label.// node bench/cells.js [cells=3000] [--react [--signals]] [--gpu] [--seconds=5]// --signals: cell 0's style and label are BUI signals; the grid renders once.-// Prints CPU per update (whole process: JS thread + BUI's UI thread).+// --dev: React's development build. Runs on Node or Bun (`bun bench/cells.js`).+// Prints frames per second, CPU per frame (the whole process: JavaScript,+// BUI's UI thread, the runtime) and resident memory.'use strict'const args = process.argv.slice(2)+// React's production build, as an app ships (--dev: the development build)+if (!args.includes('--dev')) process.env.NODE_ENV = 'production'const cells = Number(args.find(a => /^\d+$/.test(a)) ?? 3000)const useReact = args.includes('--react')const useSignals = args.includes('--signals')const gpu = args.includes('--gpu')const seconds = Number((args.find(a => a.startsWith('--seconds=')) ?? '--seconds=5').split('=')[1])-const warmup = 2+const warmup = 3// same grid and colours as bindings/rust/bench/common/measure.rsconst W = 1000, H = 800, GAP = 2@@ -80,20 +84,60 @@ if (useReact) {tick = (t) => { first.style = cellStyle(0, t); firstText.data = label(0, t) }}-let t = 0, updates = 0, cpu0, wall0, rss = 0, samples = 0, running = true+// CPU: the process's cycle count (every thread: JS, BUI's UI thread, Node's+// own), turned into time with the cycle counter's rate measured during the+// warm-up, as bindings/rust/bench/common/measure.rs does. Tick-based CPU+// time (process.cpuUsage) under-reports threads that wake on each vsync; it+// is the fallback where the cycle counter isn't available.+const { native } = require('..')+const cycles = () => native.processCpuCycles()+const tsc = () => native.timestampCounter()+const exact = cycles() != null && tsc() != null++let t = 0, updates = 0, running = true+let wall0, cpu0, tsc0, cal0+let rss = 0, peakRss = 0, samples = 0// one update per displayed frame (vsync), like the Rust benchmarkconst frame = () => { if (!running) return; tick(++t); updates++; win.requestAnimationFrame(frame) }setTimeout(() => win.requestAnimationFrame(frame), 200)-setTimeout(() => { cpu0 = process.cpuUsage(); wall0 = performance.now(); updates = 0 }, warmup * 1000)-const sampler = setInterval(() => { rss += process.memoryUsage.rss(); samples++ }, 250)+setTimeout(() => { cal0 = [performance.now(), exact ? tsc() : 0] }, 200)+setTimeout(() => {+ wall0 = performance.now()+ cpu0 = exact ? cycles() : process.cpuUsage()+ tsc0 = exact ? tsc() : 0+ updates = 0+ rss = peakRss = samples = 0+}, warmup * 1000)+const sampler = setInterval(() => {+ if (wall0 === undefined) return+ const r = process.memoryUsage.rss()+ rss += r+ peakRss = Math.max(peakRss, r)+ samples+++}, 100)setTimeout(() => {- const cpu = process.cpuUsage(cpu0), wall = performance.now() - wall0- const ms = (cpu.user + cpu.system) / 1000- running = false; clearInterval(sampler)+ const wall = performance.now() - wall0+ let ms+ if (exact) {+ const hz = (tsc0 - cal0[1]) / ((wall0 - cal0[0]) / 1000)+ ms = (cycles() - cpu0) / hz * 1000+ } else {+ const c = process.cpuUsage(cpu0)+ ms = (c.user + c.system) / 1000+ }+ running = false+ clearInterval(sampler)console.log(JSON.stringify({- app: useReact ? (useSignals ? 'blenderui-react-signals' : 'blenderui-react') : 'blenderui-js', gpu, cells, updates_per_s: +(updates / wall * 1000).toFixed(1),- cpu_pct: +(ms / wall * 100).toFixed(1), cpu_ms_per_update: +(ms / updates).toFixed(2),+ app: useReact ? (useSignals ? 'blenderui-react-signals' : 'blenderui-react') : 'blenderui-js',+ runtime: typeof Bun !== 'undefined' ? `bun ${Bun.version}` : `node ${process.versions.node}`,+ gpu,+ cells,+ fps: +(updates / wall * 1000).toFixed(1),+ cpu_pct: +(ms / wall * 100).toFixed(1),+ cpu_ms_per_frame: +(ms / updates).toFixed(2),+ cpu_counter: exact ? 'cycles' : 'ticks',rss_mb: +(rss / samples / 1048576).toFixed(1),+ peak_rss_mb: +(peakRss / 1048576).toFixed(1),}))app.quit()}, (warmup + seconds) * 1000)diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.tsindex bbd66d6..fab789f 100644--- a/bindings/node/index.d.ts+++ b/bindings/node/index.d.ts@@ -1,4 +1,4 @@-// Types for @blenderui/native.+// Types for @blender-ui/native.export interface AppOptions {/** Draw on the GPU (Direct3D 11). */gpu?: boolean@@ -127,6 +127,8 @@ export interface ReadSignal<T> {with<R> (fn: (value: T) => R): R/** Call `fn` now and on every change; returns the unsubscribe function. */subscribe (fn: (value: T) => void): () => void+ /** `count + 1`, `count > 5` read the value (`===` and truthiness don't: use `.value`). */+ valueOf (): T}export class Signal<T> implements ReadSignal<T> {@@ -138,6 +140,7 @@ export class Signal<T> implements ReadSignal<T> {update (fn: (value: T) => T): voidwith<R> (fn: (value: T) => R): Rsubscribe (fn: (value: T) => void): () => void+ valueOf (): T}export class Memo<T> implements ReadSignal<T> {@@ -146,8 +149,7 @@ export class Memo<T> implements ReadSignal<T> {peek (): Twith<R> (fn: (value: T) => R): Rsubscribe (fn: (value: T) => void): () => void- /** Stop tracking (a later read starts again). */- dispose (): void+ valueOf (): T}export function signal<T> (value: T, options?: { equals?: (a: T, b: T) => boolean }): Signal<T>@@ -162,3 +164,24 @@ export function untrack<R> (fn: () => R): R/** Leptos / Solid style getter and setter. */export function createSignal<T> (value: T): [() => T, (value: T | ((prev: T) => T)) => void]export function isSignal (x: unknown): x is ReadSignal<unknown>+/** Writes in `fn` update what they affect after urgent work, in slices. Settles+ * when done; rejects with the error of an async `fn`. */+export function startTransition (fn: () => void | Promise<void>): Promise<void>+/** Run `fn` at urgent priority, even inside a transition. */+export function urgent<R> (fn: () => R): R++/** A ref whose `.current` effects and memos can follow (reading it while a+ * React component renders doesn't subscribe). */+export class Ref<T> extends Signal<T> { current: T }+export function ref<T> (value: T): Ref<T>+/** Run `fn` outside any owning effect: effects it creates live until disposed. */+export function unowned<R> (fn: () => R): R++/** The addon (internal), plus counters for benchmarks. */+export const native: {+ /** CPU cycles of every thread of this process (Windows), or null. */+ processCpuCycles (): number | null+ /** The x86-64 time-stamp counter, or null. */+ timestampCounter (): number | null+ [key: string]: unknown+}diff --git a/bindings/node/index.js b/bindings/node/index.jsindex f0ca78b..2fe274d 100644--- a/bindings/node/index.js+++ b/bindings/node/index.js@@ -1,4 +1,4 @@-// @blenderui/native: Blender's UI from JavaScript.+// @blender-ui/native: Blender's UI from JavaScript.//// A DOM-like retained tree (createElement, setAttribute, appendChild,// addEventListener) rendered by BUI in native windows: HTML elements, CSS,@@ -14,9 +14,17 @@ const path = require('node:path')const addon = process.env.BUI_NODE_ADDON ||path.join(__dirname, `blenderui.${process.platform}-${process.arch}.node`)-const native = require(addon)+let native+try {+ native = require(addon)+} catch (err) {+ throw new Error(`@blender-ui/native: no native addon for ${process.platform}-${process.arch} (${addon}). ` ++ 'Prebuilt binaries are for Windows x64; elsewhere, build it from a clone of ' ++ 'https://github.com/ppmpreetham/BUI with `npm run build` in bindings/node (needs Rust, CMake and a C compiler).',+ { cause: err })+}const signals = require('./signals')-const { isSignal, effect } = signals+const { isSignal, effect, unowned } = signals// Keep in sync with bindings/rust/blenderui-node/src/lib.rs.const OP = { CREATE: 0, TEXT: 1, SET_ATTR: 2, REMOVE_ATTR: 3, APPEND: 4, INSERT: 5, REMOVE: 6, SET_TEXT: 7, LISTEN: 8, FREE: 9 }@@ -25,11 +33,15 @@ const EVENT_BITS = {wheel: 32, keydown: 64, keyup: 128, change: 256, input: 512,}const BUTTONS = ['left', 'middle', 'right']+// DOM: these don't bubble+const NO_BUBBLE = new Set(['mouseenter', 'mouseleave'])/** The event object handlers receive (a subset of the DOM's). */class BuiEvent {constructor (raw, target) {this.type = raw.kind+ this.bubbles = !NO_BUBBLE.has(raw.kind)+ // the deepest element listening for this type (BUI reports no deeper target)this.target = targetthis.currentTarget = targetthis.clientX = this.x = raw.x@@ -46,10 +58,13 @@ class BuiEvent {this.timeStamp = performance.now()this.defaultPrevented = falsethis.propagationStopped = false+ this.immediatePropagationStopped = false}+ /** Events reach JavaScript after BUI handled them: this marks the event only. */preventDefault () { this.defaultPrevented = true }stopPropagation () { this.propagationStopped = true }+ stopImmediatePropagation () { this.propagationStopped = this.immediatePropagationStopped = true }}class Node {@@ -69,6 +84,7 @@ class Node {}appendChild (child) {+ this._adopt(child)child._detach()this.childNodes.push(child)child.parentNode = this@@ -78,6 +94,9 @@ class Node {insertBefore (child, before) {if (!before) return this.appendChild(child)+ if (before.parentNode !== this) throw new Error('blenderui: insertBefore: the reference node is not a child of this node')+ if (child === before) return child+ this._adopt(child)child._detach()this.childNodes.splice(this.childNodes.indexOf(before), 0, child)child.parentNode = this@@ -98,18 +117,29 @@ class Node {remove () { this.parentNode?.removeChild(this) }_detach () {- if (this.parentNode) {- const p = this.parentNode+ const p = this.parentNode+ if (p) {p.childNodes.splice(p.childNodes.indexOf(this), 1)- this.parentNode = null // the APPEND/INSERT that follows moves it natively+ this.parentNode = null+ if (p !== this._nextParent) this.ownerWindow._op(OP.REMOVE, p.id, this.id)}}+ /** Checks before `child` moves under this node (as the DOM does). */+ _adopt (child) {+ if (child.ownerWindow !== this.ownerWindow) throw new Error('blenderui: the node belongs to another window')+ for (let n = this; n; n = n.parentNode) {+ if (n === child) throw new Error('blenderui: a node cannot be inserted into itself or its descendants')+ }+ child._nextParent = this // same parent: APPEND / INSERT reorders it natively+ }+/** Keep `key` (an attribute, or the text) following `source`: each change* updates this node alone. */_bind (key, source, apply) {this._unbind(key)- ;(this._bindings ??= new Map()).set(key, effect(() => { apply(source.value) }))+ // unowned: a binding made inside an effect lives as long as the node, not that effect's run+ ;(this._bindings ??= new Map()).set(key, unowned(() => effect(() => { apply(source.value) })))}_unbind (key) {@@ -251,12 +281,19 @@ class Element extends Node {this.checked = raw.checkedthis.valueAsNumber = raw.number}- const set = this._listeners.get(raw.kind)- if (!set || !set.size) returnconst e = new BuiEvent(raw, this)- for (const fn of [...set]) {- try { fn.call(this, e) } catch (err) { queueMicrotask(() => { throw err }) }+ for (let n = this; n !== null; n = n.parentNode) {+ const set = n._listeners?.get(raw.kind)+ if (set && set.size) {+ e.currentTarget = n+ for (const fn of [...set]) {+ try { fn.call(n, e) } catch (err) { queueMicrotask(() => { throw err }) }+ if (e.immediatePropagationStopped) break+ }+ }+ if (e.propagationStopped || !e.bubbles) break}+ e.currentTarget = null}/** Layout box `{ x, y, width, height }` in logical pixels (or null). */@@ -328,7 +365,13 @@ class Window {/** Changes are sent once per tick; `flush()` sends them now. */flush () {this._scheduled = false- if (!this._ops.length || this.closed) return+ if (this.closed) {+ this._ops = []+ this._strings = []+ this._stringIds.clear()+ return+ }+ if (!this._ops.length) returnconst ops = Int32Array.from(this._ops)const strings = this._stringsthis._ops = []@@ -398,7 +441,16 @@ class Window {_closed () {if (this.closed) returnthis.closed = true- for (const fn of this._onClose) fn()+ for (const fn of this._onClose) {+ try { fn() } catch (err) { queueMicrotask(() => { throw err }) }+ }+ // the native window is gone: free what follows signals or holds listeners+ for (const n of this._nodes.values()) {+ n._unbindAll()+ n._listeners?.clear()+ }+ this._frameCallbacks.clear()+ this.flush()this.app._windowClosed(this)}@@ -421,8 +473,7 @@ class Window {_free (node) {node._unbindAll()- if (node.id === 0) return- this._nodes.delete(node.id)+ if (node.id === 0 || !this._nodes.delete(node.id)) return // the body, or freed alreadythis._op(OP.FREE, node.id)}}@@ -455,8 +506,12 @@ class App {/** Close every window and end the UI thread (Node may then exit). */quit () {- for (const w of this.windows.values()) w.flush()- this.windows.clear()+ if (this._quit) return+ this._quit = true+ for (const w of [...this.windows.values()]) {+ w.flush()+ w._closed()+ }this.native.quit()}@@ -476,7 +531,10 @@ class App {_windowClosed (win) {this.windows.delete(win.id)- if (this.quitOnLastWindowClosed && this.windows.size === 0) this.native.quit()+ if (this.quitOnLastWindowClosed && this.windows.size === 0 && !this._quit) {+ this._quit = true+ this.native.quit()+ }}}diff --git a/bindings/node/package.json b/bindings/node/package.jsonindex c12b795..30ce3ab 100644--- a/bindings/node/package.json+++ b/bindings/node/package.json@@ -1,18 +1,62 @@{- "name": "@blenderui/native",+ "name": "@blender-ui/native","version": "0.1.0",- "description": "Blender's UI from JavaScript: native windows, HTML/CSS/Tailwind, driven from Node through napi-rs",+ "description": "Blender's UI from JavaScript: native windows (CPU or Direct3D 11), HTML elements, CSS and Tailwind classes, signals. Node.js and Bun, through napi-rs.","main": "index.js","types": "index.d.ts",- "files": ["index.js", "signals.js", "index.d.ts", "*.node", "README.md"],+ "exports": {+ ".": {+ "types": "./index.d.ts",+ "default": "./index.js"+ },+ "./signals": "./signals.js",+ "./package.json": "./package.json"+ },+ "files": [+ "index.js",+ "signals.js",+ "index.d.ts",+ "blenderui.*.node",+ "README.md",+ "LICENSE"+ ],"scripts": {"build": "node scripts/build.js",- "test": "node --test"+ "test": "node --test",+ "prepublishOnly": "node scripts/build.js && node --test",+ "prepack": "node -e \"require('fs').copyFileSync('../../LICENSE', 'LICENSE')\"",+ "postpack": "node -e \"require('fs').rmSync('LICENSE', { force: true })\""+ },+ "engines": {+ "node": ">=18"},- "engines": { "node": ">=18" },- "os": ["win32"],- "cpu": ["x64"],+ "os": [+ "win32"+ ],+ "cpu": [+ "x64"+ ],"license": "GPL-2.0-or-later",- "repository": { "type": "git", "url": "git+https://github.com/ppmpreetham/BUI.git", "directory": "bindings/node" },- "keywords": ["blender", "ui", "gui", "napi", "native", "desktop", "tailwind", "react"]+ "repository": {+ "type": "git",+ "url": "git+https://github.com/ppmpreetham/BUI.git",+ "directory": "bindings/node"+ },+ "homepage": "https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md",+ "bugs": {+ "url": "https://github.com/ppmpreetham/BUI/issues"+ },+ "keywords": [+ "blender",+ "ui",+ "gui",+ "desktop",+ "native",+ "napi",+ "tailwind",+ "css",+ "signals",+ "bun",+ "react"+ ]}diff --git a/bindings/node/signals.js b/bindings/node/signals.jsindex c4a3233..5935144 100644--- a/bindings/node/signals.js+++ b/bindings/node/signals.js@@ -76,6 +76,8 @@ class Signal {/** Call `fn(value)` now and on every change; returns the unsubscribe function. */subscribe (fn) { return effect(() => { fn(this.value) }) }toString () { return String(this.value) }+ /** `count + 1`, `count > 5` read the value (`===` and truthiness don't: use `.value`). */+ valueOf () { return this.value }toJSON () { return this.value }_addSub (s) { this._subs.add(s) }@@ -116,8 +118,12 @@ class Computation {}}}- if (this._state === DIRTY) this._run()- this._state = CLEAN+ if (this._state === DIRTY) {+ this._state = CLEAN // a mark made while running (a write to a source) re-queues it+ this._run()+ } else {+ this._state = CLEAN+ }}}@@ -129,44 +135,67 @@ class Memo extends Computation {this._value = undefinedthis._init = falsethis._seen = -1 // `writes` when last known up to date while detached+ this._error = null // { error } when the computation threw: rethrown on read+ this._lowPriority = false // marked by a transition onlythis._equals = options?.equals ?? Object.is}get value () {track(this)this._refresh()+ if (this._error !== null) throw this._error.errorreturn this._value}get () { return this.value }- peek () { this._refresh(); return this._value }+ peek () {+ this._refresh()+ if (this._error !== null) throw this._error.error+ return this._value+ }with (fn) { return fn(this.value) }subscribe (fn) { return effect(() => { fn(this.value) }) }toString () { return String(this.value) }+ /** `count + 1`, `count > 5` read the value (`===` and truthiness don't: use `.value`). */+ valueOf () { return this.value }toJSON () { return this.value }_refresh () {if (this._attached) return super._refresh()// nobody observes this memo: revalidate against the global write count- if (this._seen !== writes || !this._init) this._run()- this._seen = writes+ const at = writesthis._state = CLEAN+ if (this._seen !== at || !this._init) this._run()+ this._seen = at}_run () {- const v = this._track()- if (!this._init || !this._equals(this._value, v)) {+ let v+ try {+ v = this._track()+ } catch (error) {this._init = true+ this._error = { error }+ for (const s of this._subs) if (s._state === CHECK) s._state = DIRTY // readers waiting on this check+ return+ }+ if (!this._init || this._error !== null || !this._equals(this._value, v)) {+ this._init = true+ this._error = nullthis._value = v- for (const s of this._subs) s._state = DIRTY+ for (const s of this._subs) if (s._state === CHECK) s._state = DIRTY // readers waiting on this check}}_mark (state) {- if (this._state >= state) return+ const urgent = transition === nullconst was = this._state- this._state = state- if (was === CLEAN) for (const s of this._subs) s._mark(CHECK)+ // already marked: pass it on only to make a transition's mark urgent+ if (was >= state && !(urgent && this._lowPriority)) return+ if (state > was) this._state = state+ const propagate = was === CLEAN || (urgent && this._lowPriority)+ this._lowPriority = !urgent && (was === CLEAN || this._lowPriority)+ if (propagate) for (const s of this._subs) s._mark(CHECK)}_addSub (s) {@@ -200,8 +229,17 @@ class Effect extends Computation {this._disposed = falsethis._queued = NONEif (owner !== null) (owner._children ??= []).push(this)- this._run()this._state = CLEAN+ batchDepth++ // writes made by this run re-run it after, not inside, the run+ try {+ this._run()+ } catch (error) {+ this.dispose() // no half-subscribed effect left behind+ throw error+ } finally {+ batchDepth--+ flush()+ }}_run () {@@ -238,6 +276,8 @@ class Effect extends Computation {} else if (this._queued === NONE) {this._queued = DEFERREDdefer(this)+ } else if (this._queued === DEFERRED) {+ holdTransition() // this transition also waits for the deferred run}}@@ -245,6 +285,7 @@ class Effect extends Computation {if (this._disposed) returnthis._disposed = truethis._unsubscribe()+ this._attached = false // reads after dispose (mid-run) don't subscribethis._clean()}}@@ -263,12 +304,14 @@ function runEffect (e) {function flush () {if (batchDepth > 0 || flushing) returnflushing = true+ let i = 0try {- for (let i = 0; i < pending.length; i++) {+ for (; i < pending.length; i++) {if (i > 100000) throw new Error('blenderui: effects keep re-triggering each other')if (pending[i]._queued === URGENT) runEffect(pending[i])}} finally {+ for (; i < pending.length; i++) if (pending[i]._queued === URGENT) pending[i]._queued = NONEpending.length = 0flushing = false}@@ -297,14 +340,19 @@ class Transition {const now = typeof performance !== 'undefined' ? () => performance.now() : () => Date.now()const macrotask = typeof setImmediate === 'function' ? setImmediate : (f) => setTimeout(f, 0)-/** Queue an effect or task of the current transition. */-function defer (item) {- deferred.push(item)+/** The current transition waits for the deferred queue to drain. */+function holdTransition () {if (transition !== null && !transition._queued) {transition._queued = truetransition._hold()waiting.add(transition)}+}++/** Queue an effect or task of the current transition. */+function defer (item) {+ deferred.push(item)+ holdTransition()if (!deferredScheduled) {deferredScheduled = truemacrotask(runDeferred)@@ -354,17 +402,24 @@ const IDLE = new Transition()* Run `fn` as a transition: what its signal writes trigger (bindings,* effects) runs after urgent work, in slices. Like React, only writes made* before `fn`'s first `await` belong to it. Returns a promise that settles- * when `fn` (and its promise, if any) and the deferred work are done.+ * when `fn` (and its promise, if any) and the deferred work are done; it+ * rejects with the error of an async `fn` (a synchronous throw propagates).*/function startTransition (fn) {const t = new Transition()- const done = new Promise((resolve) => t._done.push(resolve))+ let failure = null+ const done = new Promise((resolve, reject) => {+ t._done.push(() => (failure ? reject(failure.error) : resolve()))+ })const prev = transitiontransition = tbatchDepth++let resulttry {result = fn()+ } catch (error) {+ t._release()+ throw error} finally {batchDepth--transition = prev@@ -372,7 +427,7 @@ function startTransition (fn) {}if (result && typeof result.then === 'function') {t._hold()- result.then(() => t._release(), (err) => { reportError(err); t._release() })+ result.then(() => t._release(), (error) => { failure = { error }; t._release() })}t._release()return done@@ -410,6 +465,87 @@ function urgent (fn) {const inTransition = () => transition !== null+// ---- render tracking (components) ------------------------------------------++/**+ * What a component's render read, and a callback when any of it changes.+ * `run(fn)` collects reads without subscribing (a render may be thrown+ * away); `commit(reads)` subscribes once the render is committed; `pause`+ * / `resume` follow mount and unmount. Built for React components.+ */+class Tracker extends Computation {+ constructor (onChange) {+ super(null)+ this._attached = true+ this._state = CLEAN+ this._queued = NONE+ this._disposed = false+ this._onChange = onChange+ this._pausedAt = 0+ }++ /** Run `fn`, collecting the signals it reads. Returns `[result, reads]`. */+ run (fn) {+ const reads = { _deps: new Set(), _attached: false, _render: true, _at: 0 }+ const prev = observer+ observer = reads+ try {+ const result = fn()+ reads._at = writes // writes made by the render itself don't count+ return [result, reads]+ } finally {+ observer = prev+ }+ }++ /** The render that read `reads` was committed: follow those signals now. */+ commit (reads) {+ if (reads === null) return+ const next = reads._deps+ if (this._attached) {+ for (const d of this._deps) if (!next.has(d)) d._removeSub(this)+ for (const d of next) if (!this._deps.has(d)) d._addSub(this)+ }+ this._deps = next+ this._state = CLEAN+ if (writes !== reads._at && next.size > 0) this._onChange() // changed in between+ }++ pause () {+ if (!this._attached) return+ for (const d of this._deps) d._removeSub(this)+ this._attached = false+ this._pausedAt = writes+ }++ resume () {+ if (this._attached) return+ this._attached = true+ for (const d of this._deps) d._addSub(this)+ if (writes !== this._pausedAt && this._deps.size > 0) this._onChange()+ }++ _run () { this._onChange() }+ dispose () { this.pause(); this._disposed = true }+}+Tracker.prototype._mark = Effect.prototype._mark++const inRender = () => observer !== null && observer._render === true++/** A ref whose `.current` is a signal for effects and memos, but not for+ * renders (reading a ref while rendering doesn't subscribe, as in React). */+class Ref extends Signal {+ constructor (value) {+ super(value)+ // an own property: React (dev) rejects ref objects without one+ Object.defineProperty(this, 'current', {+ get () { return inRender() ? this._value : this.value },+ set (v) { this.set(v) },+ enumerable: true,+ })+ }+}+// ---- API -------------------------------------------------------------------/** `signal(0)`: a read-write signal (`.value`, `.set`, `.update`). */@@ -435,6 +571,17 @@ function batch (fn) {}}+/** Run `fn` outside any owning effect: effects it creates live until disposed. */+function unowned (fn) {+ const prev = owner+ owner = null+ try {+ return fn()+ } finally {+ owner = prev+ }+}+/** Run `fn` without subscribing to what it reads. */function untrack (fn) {const prev = observer@@ -454,6 +601,9 @@ function createSignal (value, options) {const isSignal = (x) => x instanceof Signal || x instanceof Memo+/** A ref (`{ current }`) whose changes effects and memos can follow. */+function ref (value) { return new Ref(value) }+module.exports = {Signal,Memo,@@ -464,6 +614,7 @@ module.exports = {effect,batch,untrack,+ unowned,createSignal,isSignal,startTransition,@@ -471,4 +622,7 @@ module.exports = {inTransition,onTransitionDone,scheduleDeferred,+ Tracker,+ Ref,+ ref,}diff --git a/bindings/node/test/native.test.js b/bindings/node/test/native.test.jsindex 9bb7c65..94b6476 100644--- a/bindings/node/test/native.test.js+++ b/bindings/node/test/native.test.js@@ -89,3 +89,36 @@ test('signals bound to attributes and text update only their node (headless)', aawait tick()assert.deepStrictEqual(at(await win.screenshot(), 10, 10), [255, 0, 0])})++test('DOM semantics: moving nodes, insertBefore checks, bubbling with stopPropagation (headless)', async (t) => {+ const { App } = require('..')+ const app = new App({ headless: true })+ t.after(() => app.quit())+ const win = app.window({ width: 100, height: 100 })+ win.body.style = 'margin: 0'+ const a = win.createElement('div'), b = win.createElement('div'), x = win.createElement('div')+ x.style = 'width: 20px; height: 20px; background: #f00'+ win.body.appendChild(a)+ win.body.appendChild(b)+ a.appendChild(x)+ b.appendChild(x) // a move: must leave `a` natively too+ assert.strictEqual(a.childNodes.length, 0)+ assert.throws(() => a.insertBefore(win.createElement('i'), x), /not a child/)+ assert.throws(() => x.appendChild(b), /itself or its descendants/)+ const tick = () => new Promise(r => setTimeout(r, 30))+ await tick()+ const box = await x.getBoundingClientRect()+ assert.ok(box && box.width === 20, 'rendered once, in b')+ const log = []+ b.addEventListener('click', (e) => log.push(`b target=${e.target === x} current=${e.currentTarget === b}`))+ x.addEventListener('click', () => log.push('x'))+ win.body.addEventListener('click', () => log.push('body'))+ win.click(10, 10)+ await tick()+ assert.deepStrictEqual(log, ['x', 'b target=true current=true', 'body'], 'bubbles once through the JS tree')+ log.length = 0+ b.addEventListener('click', (e) => e.stopPropagation())+ win.click(10, 10)+ await tick()+ assert.deepStrictEqual(log, ['x', 'b target=true current=true'], 'stopPropagation stops it')+})diff --git a/bindings/node/test/signals.test.js b/bindings/node/test/signals.test.jsindex 6dbf245..f580ec5 100644--- a/bindings/node/test/signals.test.js+++ b/bindings/node/test/signals.test.js@@ -58,3 +58,111 @@ test('signals: equality cut-off, cleanups, nested effects, untrack', () => {setCount(c => c + 1)assert.strictEqual(count(), 2)})++test('signals: unobserved memos hold no subscriptions and stay correct', () => {+ const a = signal(1)+ const m = memo(() => a.value * 2)+ assert.strictEqual(m.value, 2)+ assert.strictEqual(a._subs.size, 0, 'read outside an effect: not subscribed (collectable)')+ a.value = 2+ assert.strictEqual(m.value, 4, 'revalidated on read')+ const seen = []+ const stop = effect(() => { seen.push(m.value) })+ assert.strictEqual(a._subs.size, 1, 'observed: subscribed')+ a.value = 3+ stop()+ assert.strictEqual(a._subs.size, 0, 'last observer gone: detached')+ a.value = 4+ assert.strictEqual(m.value, 8)+ const again = effect(() => { seen.push(m.value) })+ a.value = 5+ again()+ assert.deepStrictEqual(seen, [4, 6, 8, 10])+})++test('signals: transitions defer their effects; urgent writes go first', async () => {+ const { startTransition } = require('../signals')+ const a = signal(0), b = signal(0)+ const order = []+ const s1 = effect(() => { if (a.value) order.push('a') })+ const s2 = effect(() => { if (b.value) order.push('b') })+ const done = startTransition(() => { a.value = 1 })+ b.value = 1+ assert.deepStrictEqual(order, ['b'])+ await done+ assert.deepStrictEqual(order, ['b', 'a'])+ await assert.rejects(startTransition(async () => { throw new Error('x') }), /x/)+ s1()+ s2()+})++test('signals: a write inside an effect re-runs it (clamping), without re-entering', () => {+ const x = signal(15)+ let label = ''+ let depth = 0, maxDepth = 0+ effect(() => {+ depth+++ maxDepth = Math.max(maxDepth, depth)+ label = String(x.value)+ if (x.value > 10) x.value = 10+ depth--+ })+ assert.strictEqual(x.peek(), 10)+ assert.strictEqual(label, '10', 'the clamped value was rendered')+ assert.strictEqual(maxDepth, 1, 'never ran inside itself')+ x.value = 20+ assert.strictEqual(label, '10')+})++test('signals: a memo that throws recovers; its readers keep following it', () => {+ const a = signal(false), b = signal(1)+ const m = memo(() => { if (a.value) throw new Error('bad'); return b.value })+ const seen = []+ effect(() => { try { seen.push(m.value) } catch (e) { seen.push(e.message) } })+ a.value = true+ a.value = false+ b.value = 2+ assert.deepStrictEqual(seen, [1, 'bad', 1, 2])+ assert.throws(() => { a.value = true; m.peek() }, /bad/)+})++test('signals: an urgent write overtakes a pending transition through a memo', async () => {+ const { startTransition } = require('../signals')+ const s = signal(0)+ const m = memo(() => s.value * 2)+ const seen = []+ effect(() => { seen.push(m.value) })+ const done = startTransition(() => { s.value = 1 })+ s.value = 5 // urgent+ assert.deepStrictEqual(seen, [0, 10], 'ran now, not after the transition slice')+ await done+ assert.deepStrictEqual(seen, [0, 10])+})++test('signals: a second transition waits for an already deferred effect', async () => {+ const { startTransition } = require('../signals')+ const s = signal(0)+ const seen = []+ effect(() => { seen.push(s.value) })+ startTransition(() => { s.value = 1 })+ const second = startTransition(() => { s.value = 2 })+ await second+ assert.strictEqual(seen.at(-1), 2, 'resolved only after its value was applied')+})++test('signals: a failing first run leaves no subscription; bindings outlive outer effects', () => {+ const s = signal(1)+ assert.throws(() => effect(() => { s.value; throw new Error('first') }), /first/)+ assert.strictEqual(s._subs.size, 0)+ const { unowned } = require('../signals')+ const outer = signal(0)+ const inner = signal('a')+ let seen = ''+ effect(() => {+ outer.value+ unowned(() => effect(() => { seen = inner.value }))+ })+ outer.value = 1 // re-runs the outer effect+ inner.value = 'b'+ assert.strictEqual(seen, 'b')+})diff --git a/bindings/package-lock.json b/bindings/package-lock.jsonnew file mode 100644index 0000000..a43ea6d--- /dev/null+++ b/bindings/package-lock.json@@ -0,0 +1,84 @@+{+ "name": "blenderui-js",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "blenderui-js",+ "workspaces": [+ "node",+ "react"+ ]+ },+ "node": {+ "name": "@blender-ui/native",+ "version": "0.1.0",+ "cpu": [+ "x64"+ ],+ "license": "GPL-2.0-or-later",+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@blender-ui/native": {+ "resolved": "node",+ "link": true+ },+ "node_modules/@blender-ui/react": {+ "resolved": "react",+ "link": true+ },+ "node_modules/react": {+ "version": "19.3.1",+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",+ "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-reconciler": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.34.0.tgz",+ "integrity": "sha512-eVibvB1fc9j5Qf1KRkiM3GzRPBdjg2P6G6QV2f3P6Eb3OGMxRBhdg2rrUwjbV5JrQaJj8nOa8uajmmJA5tJWjQ==",+ "license": "MIT",+ "dependencies": {+ "scheduler": "^0.28.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "peerDependencies": {+ "react": "^19.3.0"+ }+ },+ "node_modules/scheduler": {+ "version": "0.28.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",+ "license": "MIT"+ },+ "react": {+ "name": "@blender-ui/react",+ "version": "0.1.0",+ "license": "GPL-2.0-or-later",+ "dependencies": {+ "@blender-ui/native": "^0.1.0",+ "react-reconciler": "0.34.0"+ },+ "devDependencies": {+ "react": "19.3.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "react": "^19.3.0"+ }+ }+ }+}diff --git a/bindings/package.json b/bindings/package.jsonnew file mode 100644index 0000000..0d1f5ae--- /dev/null+++ b/bindings/package.json@@ -0,0 +1,10 @@+{+ "name": "blenderui-js",+ "private": true,+ "description": "Workspace for the JavaScript packages: @blender-ui/native and @blender-ui/react",+ "workspaces": ["node", "react"],+ "scripts": {+ "build": "npm run build -w @blender-ui/native",+ "test": "npm test --workspaces"+ }+}diff --git a/bindings/react/.gitignore b/bindings/react/.gitignoreindex 4c8908a..e41c098 100644--- a/bindings/react/.gitignore+++ b/bindings/react/.gitignore@@ -1,2 +1,3 @@*.nodenode_modules/+LICENSEdiff --git a/bindings/react/README.md b/bindings/react/README.mdindex 6f6900d..0881c0f 100644--- a/bindings/react/README.md+++ b/bindings/react/README.md@@ -1,31 +1,101 @@-# @blenderui/react+# @blender-ui/react-A React 19 renderer for BUI: JSX rendered with Blender's UI in native-windows, over [`@blenderui/native`](../node).+A React 19 renderer for [BUI](https://github.com/ppmpreetham/BUI): JSX+rendered with Blender's UI toolkit in native windows, with no browser and no+Electron. It runs on Node.js and Bun. React's hooks are exported by their own+names, with signals underneath, so a state change can update a single node+without re-rendering its component.++```sh+npm install @blender-ui/react react+``````jsx-import { useState } from 'react'-import { render } from '@blenderui/react'+import { render, useState } from '@blender-ui/react'function Counter () {- const [n, setN] = useState(0)- return <button className="m-4" onClick={() => setN(n + 1)}>Clicked {n} times</button>+ const [count, setCount] = useState(0)+ return (+ <main className="p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]">+ <span>Clicks: {count}</span>+ <button onClick={() => setCount(c => c + 1)}>Add one</button>+ </main>+ )}-render(<Counter />, { title: 'Counter', width: 320, height: 160 })+render(<Counter />, { title: 'Counter', width: 360, height: 200, gpu: true })```-BUI's hooks work alongside React's. A signal passed as a prop or child-updates that node alone, without re-rendering the component:+Set `"jsxImportSource": "@blender-ui/react"` in your `tsconfig.json`, or in+your bundler's JSX options. This does two things: components re-render when+a signal they read while rendering changes, and in TypeScript, host-element+props accept signals.-```jsx-import { render, useSignal } from '@blenderui/react'+## Hooks-function Counter () {- const n = useSignal(0) // also useComputed, useSignalEffect, useSignalValue- return <button className="m-4" onClick={() => n.value++}>Clicked {n} times</button>-}-```+The hooks have React's names, arguments and timing, but the state they hold+is a **signal**:++- **Passed as a prop or child** (`<span>{count}</span>`,+ `style={styleMemo}`): a change updates that node. The component doesn't+ re-render.+- **Read while rendering** (`count.value`; in plain JavaScript also+ `count + 1` or `count > 5`): the component re-renders when it changes, as+ with React. TypeScript needs `.value` for arithmetic.+- **Conditions and `===` need `.value`.** A signal is an object, so it's always+ truthy: write `{isPending.value && <Spinner />}` and `count.value === 0`.++| Hook | Returns |+|---|---|+| `useState(init)` | `[signal, setState]` |+| `useReducer(reducer, arg, init?)` | `[signal, dispatch]` |+| `useMemo(fn, deps?)` | a memo, recomputed when the signals it reads change |+| `useRef(v)` | `{ current }`, observable by effects and memos |+| `useCallback(fn, deps?)` / `useEffectEvent(fn)` | a function whose calls are batched |+| `useEffect` / `useLayoutEffect` / `useInsertionEffect` | React's timing and deps, plus a re-run when signals the effect read change |+| `useSyncExternalStore(subscribe, get)` | a signal following the store |+| `useTransition()` | `[isPending, startTransition]`; signal updates run after urgent ones |+| `useDeferredValue(value, initial?)` | a signal that follows `value` at low priority |+| `useActionState(action, initial)` | `[state, dispatch, isPending]` |+| `useOptimistic(state, reducer?)` | `[optimistic, addOptimistic]` |+| `use`, `useContext`, `useId`, `useDebugValue`, `useImperativeHandle` | React's own |++Also exported:++- **Rust-style names:** `useSignal(v)` and `useComputed(fn)`.+- **`useSignalValue(sig)`:** re-renders its component when `sig` changes.+- **Plain signals:** `signal`, `computed`, `effect`, `batch`, `untrack`,+ `startTransition`.++Want React's plain-value hooks instead? Import them from `react`; they work+here too.++Every hook is built from React's public hooks. A test suite runs each one+beside React's original, in development and production builds and under+StrictMode. The suite fails when a new React release adds a hook this package+doesn't cover yet.++## The renderer++- **Host components are HTML elements.** `className` takes Tailwind classes,+ `style` takes strings, objects or signals. `onClick`, `onChange` and the+ other mouse and keyboard handlers work. Events bubble, and+ `stopPropagation` works.+- **One native batch per commit:** only what changed crosses to BUI's UI+ thread.+- **React 19.3 features:** `<Suspense>`, `<Activity>`, transitions, actions,+ and `<ViewTransition>` (it commits, without animating).+- **API:** `render(element, options)` opens a window. `createRoot(window)`+ renders into a window you opened with+ [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native).+ `act(fn)` is for tests.++## Requirements++- Windows x64 for native windows; `headless: true` renders off-screen.+- Node.js 18 or newer, or Bun.+- React 19.3.-Guide and benchmarks: [docs/javascript.md](../../docs/javascript.md).+Guide, benchmarks and internals:+[docs/javascript.md](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md).License: GPL-2.0-or-later.diff --git a/bindings/react/examples/counter.js b/bindings/react/examples/counter.jsindex fcc19b7..1991a7d 100644--- a/bindings/react/examples/counter.js+++ b/bindings/react/examples/counter.js@@ -1,21 +1,21 @@-// A React counter in a native BUI window (no build step: React.createElement).-// With a JSX toolchain, write the same with JSX, e.g. `npx tsx counter.jsx`.-// node examples/counter.js+// A React counter in a native BUI window, without a build step (createElement).+// node examples/counter.js (or: bun examples/counter.js)+// The hooks are React's, by React's names, with signals for state: `count`+// below updates its text node without re-rendering Counter; `name.value`,+// read while rendering, re-renders it when the name changes.'use strict'-const React = require('react')-const { render } = require('..')-const h = React.createElement+const { render, createElement: h, useState } = require('..')function Counter () {- const [count, setCount] = React.useState(0)- const [name, setName] = React.useState('')+ const [count, setCount] = useState(0)+ const [name, setName] = useState('')return h('main', { className: 'p-6 flex flex-col gap-3' },h('h1', { className: 'text-xl font-bold' }, 'BUI + React'),h('div', { className: 'flex items-center gap-3' },- h('span', null, `Clicks: ${count}`),+ h('span', null, 'Clicks: ', count),h('button', { onClick: () => setCount(c => c + 1) }, 'Add one')),h('input', { placeholder: 'Your name', value: name, onChange: e => setName(e.target.value) }),- name && h('p', { className: 'text-[#9ab8e8]' }, `Hello, ${name}!`))+ name.value && h('p', { className: 'text-[#9ab8e8]' }, `Hello, ${name}!`))}const { app, window } = render(h(Counter), { title: 'BUI + React', width: 420, height: 260 })diff --git a/bindings/react/examples/counter.jsx b/bindings/react/examples/counter.jsxindex d6bd71b..64e84d9 100644--- a/bindings/react/examples/counter.jsx+++ b/bindings/react/examples/counter.jsx@@ -1,9 +1,11 @@-// The same counter in JSX (run with a JSX-aware runner: `npx tsx counter.jsx`).-import React, { useState } from 'react'-import { render } from '@blenderui/react'+/** @jsxImportSource @blender-ui/react */+// The same counter in JSX. Bun runs it as is: `bun examples/counter.jsx`.+// Elsewhere, compile with `"jsxImportSource": "@blender-ui/react"`.+import { render, useState } from '@blender-ui/react'function Counter () {const [count, setCount] = useState(0)+ const [name, setName] = useState('')return (<main className="p-6 flex flex-col gap-3"><h1 className="text-xl font-bold">BUI + React</h1>@@ -11,8 +13,12 @@ function Counter () {<span>Clicks: {count}</span><button onClick={() => setCount(c => c + 1)}>Add one</button></div>+ <input placeholder="Your name" value={name} onChange={e => setName(e.target.value)} />+ {name.value && <p className="text-[#9ab8e8]">Hello, {name}!</p>}</main>)}-render(<Counter />, { title: 'BUI + React', width: 420, height: 220 })+const { app, window } = render(<Counter />, { title: 'BUI + React', width: 420, height: 260 })+window.body.className = 'm-0 bg-[#2b2b2b] text-[#e6e6e6]'+if (process.env.BUI_EXAMPLE_SECONDS) setTimeout(() => app.quit(), Number(process.env.BUI_EXAMPLE_SECONDS) * 1000)diff --git a/bindings/react/hooks.js b/bindings/react/hooks.jsindex 2bda63d..83365f8 100644--- a/bindings/react/hooks.js+++ b/bindings/react/hooks.js@@ -1,28 +1,36 @@-// Signal twins of React's hooks: `useSignal<Name>` for each React `use<Name>`-// that holds or reacts to state. Same arguments, same return shape, same-// timing, but the state is a signal: pass it as a prop or child and a change-// updates that node without re-rendering the component.+// React's hooks, by React's names, with signals for state.//-// Built only on React's public hooks (useState, useRef, useMemo, the effect-// hooks, startTransition), so they follow React's own semantics (StrictMode,-// concurrent rendering) as React evolves. test/hooks.test.js runs each twin-// beside its React original, and fails when React adds a hook that has-// neither a twin nor an entry in NO_TWIN.+// `useState`, `useReducer`, `useMemo` ... take React's arguments, run at+// React's moments and return React's shapes, but the state they hold is a+// signal. Pass it as a prop or child (`<span>{count}</span>`) and a change+// updates that one node: the component doesn't re-render. Read it while+// rendering (`count.value`, `count + 1`, a condition) and the component+// re-renders when it changes, exactly as with React's own hooks.+//+// The second part needs to know which component is rendering: components+// created through this package's JSX runtime (`jsxImportSource:+// "@blender-ui/react"`) or `createElement` are wrapped with `track()`.+//+// Built only on React's public hooks (useState, useReducer, useRef, useMemo,+// the effect hooks, startTransition), so React's semantics (StrictMode,+// concurrent rendering) come from React itself. test/hooks.test.js runs each+// hook beside React's original and fails when React adds a hook that has+// neither a signal version here nor an entry in NO_TWIN.//// SPDX-License-Identifier: GPL-2.0-or-later'use strict'const React = require('react')-const S = require('@blenderui/native')-const { signal, memo, effect, batch, untrack, isSignal } = S+const S = require('@blender-ui/native')+const { signal, memo, effect, batch, untrack, isSignal, Tracker, Ref } = S-/** React hooks without a twin, and why (the coverage test reads this). */+/** React hooks re-exported unchanged, and why (the coverage test reads this). */const NO_TWIN = {use: 'suspends rendering: inherently a render-time read',useContext: 'pass a signal as the context value: consumers bind to it without re-rendering',useDebugValue: 'no state',useId: 'no state',- useImperativeHandle: 'no state (works with useSignalRef)',+ useImperativeHandle: 'no state (works with useRef)',}// The latest value, for callbacks that outlive the render that made them.@@ -32,73 +40,128 @@ function useLatest (value) {return ref}-/** A component-owned signal, created once (lazily when `init` is a function). */+/** A component-owned value, created once. */function useOnce (create) {return React.useState(create)[0]}+// ---- render tracking -----------------------------------------------------------++const bump = (n) => n + 1++/** Re-render this component when a signal its render read changes. */+function useRenderTracker () {+ const [, force] = React.useReducer(bump, 0)+ const tracker = useOnce(() => new Tracker(() => force()))+ const reads = React.useRef(null)+ // after each commit: follow what that render read+ React.useLayoutEffect(() => { tracker.commit(reads.current) })+ // mount / unmount (StrictMode re-mounts: pause, then resume)+ React.useLayoutEffect(() => {+ tracker.resume()+ return () => tracker.pause()+ }, [tracker])+ return { tracker, reads }+}++const tracked = new WeakMap()+const MEMO = Symbol.for('react.memo')+const FORWARD_REF = Symbol.for('react.forward_ref')++/** `type` with render tracking: function components, `memo` and `forwardRef`. */+function track (type) {+ if (type == null) return type+ if (typeof type === 'function') {+ if (type.prototype?.isReactComponent) return type // class components: no hooks+ } else if (typeof type !== 'object' || (type.$$typeof !== MEMO && type.$$typeof !== FORWARD_REF)) {+ return type // host components, fragments, providers, lazy ...+ }+ let t = tracked.get(type)+ if (t !== undefined) return t+ if (typeof type === 'function') {+ t = function (props, secondArg) {+ const { tracker, reads } = useRenderTracker()+ const [result, r] = tracker.run(() => type(props, secondArg))+ reads.current = r+ return result+ }+ Object.defineProperty(t, 'name', { value: type.name })+ t.displayName = type.displayName || type.name+ } else if (type.$$typeof === MEMO) {+ t = React.memo(track(type.type), type.compare)+ t.displayName = type.displayName+ } else {+ t = React.forwardRef(track(type.render))+ t.displayName = type.displayName+ }+ tracked.set(type, t)+ tracked.set(t, t)+ return t+}++/** React's `createElement`, with render tracking for components. */+function createElement (type, props, ...children) {+ return React.createElement(track(type), props, ...children)+}++// ---- state -----------------------------------------------------------------+/** Rust's `use_signal`: a signal owned by this component. */function useSignal (initial) {return useOnce(() => signal(typeof initial === 'function' ? initial() : initial))}-// ---- state -------------------------------------------------------------------/** `useState` twin: `[signal, setState]`; `setState(v | prev => next)`. */-function useSignalState (initialState) {+/** `[signal, setState]`; `setState(v | prev => next)`; the same value: no update. */+function useState (initialState) {const s = useSignal(initialState)const set = React.useCallback((v) => s.set(typeof v === 'function' ? v(s.peek()) : v), [s])return [s, set]}-/** `useReducer` twin: `[signal, dispatch]`, with the latest render's reducer. */-function useSignalReducer (reducer, initialArg, init) {+/** `[signal, dispatch]`, with the latest render's reducer (as React does). */+function useReducer (reducer, initialArg, init) {const s = useOnce(() => signal(init !== undefined ? init(initialArg) : initialArg))const latest = useLatest(reducer)const dispatch = React.useCallback((action) => s.set(latest.current(s.peek(), action)), [s])return [s, dispatch]}-/** `useRef` twin: `.current` is a signal, so memos and effects see the ref change- * (an element mounting, for instance). The ref is itself a signal. */-class SignalRef extends S.Signal {- constructor (value) {- super(value)- // an own property: React (dev) rejects ref objects without one- Object.defineProperty(this, 'current', {- get () { return this.value },- set (v) { this.set(v) },- enumerable: true,- })- }-}--function useSignalRef (initialValue) {- return useOnce(() => new SignalRef(initialValue))+/** `{ current }`, observable by effects and memos (an element mounting re-runs+ * them); reading it while rendering doesn't subscribe, as with React's refs. */+function useRef (initialValue) {+ return useOnce(() => new Ref(initialValue))}// ---- derived values -----------------------------------------------------------/** `useMemo` twin: a memo, recomputed when the signals it reads change, and- * replaced (like useMemo's value) when `deps` change; no deps: every render. */-function useSignalMemo (fn, deps) {+/** A memo: recomputed when the signals it reads change, and replaced (like+ * useMemo's value) when `deps` change; without deps, every render. */+function useMemo (fn, deps) {const latest = useLatest(fn)// eslint-disable-next-line react-hooks/exhaustive-depsreturn React.useMemo(() => memo(() => latest.current()), deps)}-/** Rust's `Memo::new`: `useSignalMemo` with `deps = []` by default. */+/** Rust's `Memo::new`: `useMemo` with `deps = []` by default. */function useComputed (fn, deps = []) {- return useSignalMemo(fn, deps)+ return useMemo(fn, deps)}-/** `useCallback` twin: the callback runs batched (its writes make one update)- * and untracked (calling it in an effect doesn't subscribe to what it reads). */-function useSignalCallback (fn, deps) {+/** React's `useCallback`; calls are batched (their writes make one update) and+ * untracked (calling it in an effect doesn't subscribe to what it reads). */+function useCallback (fn, deps) {// eslint-disable-next-line react-hooks/exhaustive-depsreturn React.useCallback((...args) => batch(() => untrack(() => fn(...args))), deps)}+/** React's `useEffectEvent`: a stable function that calls the latest render's+ * `fn`; calls are batched and untracked (an effect calling it doesn't+ * subscribe to the signals `fn` reads). */+function useEffectEvent (fn) {+ const latest = useLatest(fn)+ return React.useCallback((...args) => batch(() => untrack(() => latest.current(...args))), [latest])+}+// ---- effects -----------------------------------------------------------------function effectHook (reactHook) {@@ -109,17 +172,17 @@ function effectHook (reactHook) {}}-/** `useEffect` twin; also re-runs when the signals it read change. */-const useSignalEffect = effectHook(React.useEffect)-/** `useLayoutEffect` twin. */-const useSignalLayoutEffect = effectHook(React.useLayoutEffect)-/** `useInsertionEffect` twin. */-const useSignalInsertionEffect = effectHook(React.useInsertionEffect)+/** React's `useEffect`, also re-run when the signals it read change. */+const useEffect = effectHook(React.useEffect)+/** React's `useLayoutEffect`, also re-run when the signals it read change. */+const useLayoutEffect = effectHook(React.useLayoutEffect)+/** React's `useInsertionEffect`, also re-run when the signals it read change. */+const useInsertionEffect = effectHook(React.useInsertionEffect)// ---- external stores ----------------------------------------------------------/** `useSyncExternalStore` twin: a signal following the store, without re-renders. */-function useSignalSyncExternalStore (subscribe, getSnapshot) {+/** A signal following the store. */+function useSyncExternalStore (subscribe, getSnapshot) {const s = useOnce(() => signal(getSnapshot()))const latest = useLatest(getSnapshot)React.useLayoutEffect(() => {@@ -131,7 +194,8 @@ function useSignalSyncExternalStore (subscribe, getSnapshot) {return s}-/** Re-render this component when `source` changes; returns its value. */+/** Re-render this component when `source` changes; returns its value (for+ * components rendered without this package's JSX runtime). */function useSignalValue (source) {const subscribe = React.useCallback((onChange) => {let first = true@@ -148,74 +212,115 @@ function useSignalValue (source) {// Run `action` as a BUI transition and a React transition at once: signal// writes defer their effects, React state updates render at transition priority.+// React tracks the action's promise (its optimistic updates last until it+// settles) but never sees its rejection: each hook sends errors where React's does.+const quiet = () => {}function transition (action) {return S.startTransition(() => {let result+ let failure = nullReact.startTransition(() => {- result = action()- return result+ try {+ result = action()+ } catch (error) {+ failure = { error } // React would report it globally and swallow it+ return+ }+ return result && typeof result.then === 'function' ? result.then(quiet, quiet) : undefined})+ if (failure !== null) throw failure.errorreturn result})}-/** `useTransition` twin: `[isPending signal, startTransition(action)]`. `action`- * may be async; isPending stays true until it settles and its deferred- * updates have run. */-function useSignalTransition () {+/** React's `startTransition`, for signal writes too. Returns a promise that+ * settles when the action and the updates it caused are done. */+function startTransition (action) {+ return transition(action)+}++/** A setter that rethrows `error` during render: React's way to reach the+ * nearest error boundary from an async callback. */+function useThrowToBoundary () {+ const [, set] = React.useState(null)+ return React.useCallback((error) => set(() => { throw error }), [])+}++/** `[isPending signal, startTransition(action)]`. `action` may be async;+ * isPending stays true until it settles and its deferred updates have run.+ * An error goes to the nearest error boundary. */+function useTransition () {const isPending = useOnce(() => signal(false))+ const fail = useThrowToBoundary()const start = React.useCallback((action) => {isPending._count = (isPending._count ?? 0) + 1S.urgent(() => isPending.set(true))- transition(action).then(() => {+ const settle = () => {if (--isPending._count === 0) S.urgent(() => isPending.set(false))- })- }, [isPending])+ }+ let done+ try {+ done = transition(action)+ } catch (error) {+ settle()+ return fail(error)+ }+ done.then(settle, (error) => { settle(); fail(error) })+ }, [isPending, fail])return [isPending, start]}-/** `useDeferredValue` twin: a signal that follows `value` (a signal or a plain- * value) at transition priority, after urgent updates. */-function useSignalDeferredValue (value, initialValue) {+/** A signal following `value` (a signal or a value) at transition priority,+ * after urgent updates; `initialValue` first, if given. */+function useDeferredValue (value, initialValue) {const read = () => (isSignal(value) ? value.peek() : value)const out = useOnce(() => signal(initialValue !== undefined ? initialValue : read()))const latest = useLatest(value)React.useEffect(() => {let scheduled = false+ let live = trueconst push = () => {if (scheduled) returnscheduled = trueS.scheduleDeferred(() => {scheduled = false+ if (!live) returnconst v = latest.currentout.set(isSignal(v) ? v.peek() : v)})}- if (isSignal(value)) return effect(() => { value.value; push() })+ if (isSignal(value)) {+ const stop = effect(() => { value.value; push() })+ return () => { live = false; stop() }+ }push()+ return () => { live = false }}, [value, out])return out}-/** `useActionState` twin: `[state signal, dispatch, isPending signal]`.- * Dispatches queue and run in order, each with the previous state; an action- * may be async. A thrown error goes to the nearest error boundary, and the- * queued actions are dropped, as in React. */-function useSignalActionState (action, initialState) {+/** `[state signal, dispatch, isPending signal]`. Dispatches queue and run in+ * order, each with the previous state; an action may be async. A thrown+ * error goes to the nearest error boundary and drops the queue, as in React. */+function useActionState (action, initialState) {const state = useOnce(() => signal(initialState))const isPending = useOnce(() => signal(false))const latest = useLatest(action)const queue = useOnce(() => ({ items: [], running: false }))- const [, setError] = React.useState(null)+ const fail = useThrowToBoundary()const runNext = React.useCallback(() => {const payload = queue.items.shift()queue.running = truelet result- transition(() => {- result = latest.current(state.peek(), payload)- return result- })+ try {+ transition(() => {+ result = latest.current(state.peek(), payload)+ return result+ }).catch(quiet) // the error is handled below, from `result`+ } catch (error) {+ result = Promise.reject(error)+ }Promise.resolve(result).then((next) => {const more = queue.items.length > 0batch(() => {@@ -228,9 +333,9 @@ function useSignalActionState (action, initialState) {queue.items.length = 0queue.running = falseisPending.set(false)- setError(() => { throw err })+ fail(err)})- }, [state, isPending, queue])+ }, [state, isPending, queue, fail])const dispatch = React.useCallback((payload) => {queue.items.push(payload)@@ -243,10 +348,10 @@ function useSignalActionState (action, initialState) {return [state, dispatch, isPending]}-/** `useOptimistic` twin: `[optimistic signal, addOptimistic]`. Updates added- * during a transition or action show at once and are dropped when it ends;- * `passthrough` (a signal or a value) shows through otherwise. */-function useSignalOptimistic (passthrough, reducer) {+/** `[optimistic signal, addOptimistic]`. Updates added during a transition or+ * action show at once and are dropped when it ends; `passthrough` (a signal+ * or a value) shows through otherwise. */+function useOptimistic (passthrough, reducer) {const updates = useOnce(() => signal([]))const latestReducer = useLatest(reducer)const out = React.useMemo(() => memo(() => {@@ -269,21 +374,24 @@ function useSignalOptimistic (passthrough, reducer) {module.exports = {NO_TWIN,- SignalRef,+ track,+ createElement,+ startTransition,useSignal,useComputed,useSignalValue,- useSignalState,- useSignalReducer,- useSignalRef,- useSignalMemo,- useSignalCallback,- useSignalEffect,- useSignalLayoutEffect,- useSignalInsertionEffect,- useSignalSyncExternalStore,- useSignalTransition,- useSignalDeferredValue,- useSignalActionState,- useSignalOptimistic,+ useState,+ useReducer,+ useRef,+ useMemo,+ useCallback,+ useEffectEvent,+ useEffect,+ useLayoutEffect,+ useInsertionEffect,+ useSyncExternalStore,+ useTransition,+ useDeferredValue,+ useActionState,+ useOptimistic,}diff --git a/bindings/react/index.d.ts b/bindings/react/index.d.tsindex 4828154..ae6eaff 100644--- a/bindings/react/index.d.ts+++ b/bindings/react/index.d.ts@@ -1,33 +1,92 @@-// Types for @blenderui/react.-import type { ReactNode } from 'react'-import type { App, Window, AppOptions, WindowOptions } from '@blenderui/native'+// Types for @blender-ui/react.+import type { ReactNode, ReactElement, DependencyList, EffectCallback, Dispatch, SetStateAction, ElementType } from 'react'+import type { App, Window, AppOptions, WindowOptions, Signal, Memo, ReadSignal, Ref } from '@blender-ui/native'export interface Root {render (element: ReactNode): voidunmount (): void}+/** A React root rendering into `window`'s body (unmounted when the window closes). */export function createRoot (window: Window): Root+/** Open a window (and an App, unless `app` is given) and render `element` into it. */export function render (element: ReactNode, options?: WindowOptions & AppOptions & { app?: App }):{ app: App, window: Window, root: Root }-export function act (fn: () => void): void+/** Run `fn` and flush React's work synchronously (tests). */+export function act<R> (fn: () => R): R-// BUI's hooks (the Rust crate's use_signal / Memo / Effect). Pass a signal-// as a prop or child and only that node updates: no re-render.-import type { Signal, Memo, ReadSignal } from '@blenderui/native'-export { signal, memo, computed, effect, batch, untrack, createSignal, Signal, Memo, ReadSignal } from '@blenderui/native'+/** React's `createElement`, with render tracking for components. */+export const createElement: typeof import('react').createElement+/** A component type with render tracking (re-renders when a signal its render read changes). */+export function track<T extends ElementType> (type: T): T-/** A signal owned by this component (Rust's `use_signal`). */+// React's hooks that hold no state, as React exports them.+export { use, useContext, useDebugValue, useId, useImperativeHandle } from 'react'++// Signals.+export { signal, effect, batch, untrack, createSignal, isSignal, Signal, Memo, ReadSignal, Ref } from '@blender-ui/native'+/** A derived, cached signal (`memo` in @blender-ui/native; here `memo` stays React's). */+export { memo as computed, ref } from '@blender-ui/native'++/** React hooks re-exported unchanged, and why. */+export const NO_TWIN: Record<string, string>++// React's hooks by React's names, with signals for state. Same arguments and+// timing as React's. A signal passed as a prop or child updates that node+// alone; read while rendering (`.value`, `count + 1`), it re-renders the+// component when it changes. Conditions and `===` need `.value`: a signal+// object is always truthy.++/** `[signal, setState]`: `setState(v)` or `setState(prev => next)`. */+export function useState<T> (initialState: T | (() => T)): [Signal<T>, Dispatch<SetStateAction<T>>]+export function useState<T = undefined> (): [Signal<T | undefined>, Dispatch<SetStateAction<T | undefined>>]+/** `[signal, dispatch]`, with the latest render's reducer. */+export function useReducer<S, A> (reducer: (state: S, action: A) => S, initialArg: S): [Signal<S>, Dispatch<A>]+export function useReducer<S, A, I> (reducer: (state: S, action: A) => S, initialArg: I, init: (arg: I) => S): [Signal<S>, Dispatch<A>]+/** `{ current }`, observable by effects and memos; reading it while rendering doesn't subscribe. */+export function useRef<T> (initialValue: T): Ref<T>+export function useRef<T = undefined> (): Ref<T | undefined>+/** A memo following its signals, replaced when `deps` change (without deps: every render). */+export function useMemo<T> (fn: () => T, deps?: DependencyList): Memo<T>+/** React's `useCallback`; calls are batched and untracked. */+export function useCallback<F extends (...args: any[]) => any> (fn: F, deps?: DependencyList): F+/** React's `useEffectEvent`; calls are batched and untracked. */+export function useEffectEvent<F extends (...args: any[]) => any> (fn: F): F+/** React's `useEffect`, also re-run when the signals it read change. */+export function useEffect (effect: EffectCallback, deps?: DependencyList): void+/** React's `useLayoutEffect`, also re-run when the signals it read change. */+export function useLayoutEffect (effect: EffectCallback, deps?: DependencyList): void+/** React's `useInsertionEffect`, also re-run when the signals it read change. */+export function useInsertionEffect (effect: EffectCallback, deps?: DependencyList): void+/** A signal following the store. */+export function useSyncExternalStore<T> (subscribe: (onChange: () => void) => () => void, getSnapshot: () => T,+ getServerSnapshot?: () => T): Signal<T>+/** `[isPending, startTransition]`: what the action's writes trigger runs after urgent updates. */+export function useTransition (): [Signal<boolean>, (action: () => void | Promise<void>) => void]+/** React's `startTransition`, for signal writes too; settles when the action and its updates are done. */+export function startTransition (action: () => void | Promise<void>): Promise<void>+/** A signal following `value` (a signal or a value) at transition priority. */+export function useDeferredValue<T> (value: T | ReadSignal<T>, initialValue?: T): Signal<T>+/** `[state, dispatch, isPending]`: actions run in order, each with the previous state. */+export function useActionState<S, P = void> (action: (state: S, payload: P) => S | Promise<S>, initialState: S,+ permalink?: string): [Signal<S>, (payload: P) => void, Signal<boolean>]+/** `[optimistic, addOptimistic]`: updates last until their transition or action ends. */+export function useOptimistic<S> (passthrough: S | ReadSignal<S>): [Memo<S>, (value: S) => void]+export function useOptimistic<S, A> (passthrough: S | ReadSignal<S>, reducer: (state: S, action: A) => S):+ [Memo<S>, (action: A) => void]++/** Rust's `use_signal`: a signal owned by this component. */export function useSignal<T> (initial: T | (() => T)): Signal<T>-/** A memo owned by this component (Rust's `Memo::new`). */-export function useComputed<T> (fn: () => T): Memo<T>-/** An effect owned by this component (Rust's `Effect::new`); may return a cleanup. */-export function useSignalEffect (fn: () => void | (() => void)): void-/** Re-render this component when `source` changes; returns its value. */+/** Rust's `Memo::new`: `useMemo(fn, deps = [])`. */+export function useComputed<T> (fn: () => T, deps?: DependencyList): Memo<T>+/** Re-render this component when `source` changes; returns its value (components+ * rendered without this package's JSX runtime or createElement). */export function useSignalValue<T> (source: ReadSignal<T>): T+export type { ReactElement }+// A signal is a valid child: `<span>Clicks: {count}</span>`.declare module 'react' {interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {diff --git a/bindings/react/index.js b/bindings/react/index.jsindex af5b0d4..0ddee67 100644--- a/bindings/react/index.js+++ b/bindings/react/index.js@@ -1,10 +1,10 @@-// @blenderui/react: a React renderer for BUI (react-reconciler 0.31 / React 19).+// @blender-ui/react: a React renderer for BUI (react-reconciler 0.34 / React 19.3).//-// const { render } = require('@blenderui/react')+// const { render } = require('@blender-ui/react')// render(<div className="p-4 bg-[#4772b3]" onClick={...}>Hello</div>,// { title: 'App', width: 400, height: 300 })//-// Host components are HTML elements: React mutates @blenderui/native's+// Host components are HTML elements: React mutates @blender-ui/native's// retained tree, which sends only the changes of each commit to the native// UI thread. Events arrive as BUI events (onClick, onChange, onKeyDown ...).//@@ -15,8 +15,9 @@ const React = require('react')const Reconciler = require('react-reconciler')const { ConcurrentRoot, DefaultEventPriority, DiscreteEventPriority, NoEventPriority } =require('react-reconciler/constants')-const native = require('@blenderui/native')-const { App, TextNode, Signal, Memo, signal, memo, effect, isSignal } = native+const native = require('@blender-ui/native')+const { App, TextNode, Signal, Memo, isSignal } = native+const hooks = require('./hooks')// A signal rendered as a child (`<span>{count}</span>`) becomes this host// type: a text node bound to the signal, updated without re-rendering.@@ -44,6 +45,7 @@ const TEXT_INPUTS = new Set(['textarea'])const ATTR_ALIASES = { className: 'class', htmlFor: 'for', tabIndex: 'tabindex' }const SKIP = new Set(['children', 'key', 'ref', 'dangerouslySetInnerHTML', 'suppressHydrationWarning','suppressContentEditableWarning'])+const NO_PROPS = {}function eventName (el, prop) {if (prop === 'onChange') {@@ -55,29 +57,43 @@ function eventName (el, prop) {return EVENTS[prop]}+/** Listen with `fn` (or stop, when it isn't a function) for React prop `k`.+ * The DOM event is remembered with it: onChange's depends on `type`. */+function listen (el, k, fn) {+ const cur = el._react[k]+ const type = typeof fn === 'function' ? eventName(el, k) : null+ if (cur !== undefined && cur.fn === fn && cur.type === type) return+ if (cur !== undefined) el.removeEventListener(cur.type, cur.fn)+ if (type === null) delete el._react[k]+ else {+ el.addEventListener(type, fn)+ el._react[k] = { type, fn }+ }+}+function isText (children) {return typeof children === 'string' || typeof children === 'number' || typeof children === 'bigint'}-/** Apply the difference between two prop objects to an element. */+/** Apply the difference between two prop objects to an element. Hot: React+ * calls it for every element of a re-rendered list, mostly with equal props. */function applyProps (el, prev, next) {- for (const k in prev) {- if (SKIP.has(k) || k in next) continue- if (k in EVENTS) {- el.removeEventListener(eventName(el, k), el._react[k])- delete el._react[k]- } else {- el.removeAttribute(ATTR_ALIASES[k] ?? k)+ if (prev !== NO_PROPS) {+ for (const k in prev) {+ if (k in next || SKIP.has(k)) continue+ if (k in EVENTS) {+ listen(el, k, null)+ } else {+ el.removeAttribute(ATTR_ALIASES[k] ?? k)+ }}}+ let events = falsefor (const k in next) {const v = next[k]- if (SKIP.has(k) || prev[k] === v) continue+ if (prev[k] === v || SKIP.has(k)) continueif (k in EVENTS) {- const type = eventName(el, k)- if (el._react[k]) el.removeEventListener(type, el._react[k])- if (typeof v === 'function') el.addEventListener(type, (el._react[k] = v))- else delete el._react[k]+ events = true // after the attributes: onChange's event depends on `type`} else if (k === 'style') {if (v == null) el.removeAttribute('style')else el.style = v // a string, an object or a signal of either@@ -89,16 +105,39 @@ function applyProps (el, prev, next) {el.setAttribute(ATTR_ALIASES[k] ?? k, v === true ? '' : v)}}- if (isText(next.children) && next.children !== prev.children) el.textContent = String(next.children)- else if (isText(prev.children) && !isText(next.children)) el.textContent = ''+ if (events || (next.onChange !== undefined && prev.type !== next.type)) {+ for (const k in next) if (k in EVENTS) listen(el, k, next[k])+ }+ // text children; text -> elements is React's resetTextContent (before it+ // inserts them), so nothing to clear here+ const c = next.children+ if (c !== prev.children && isText(c)) el.textContent = String(c)+}++// Nodes a render created. React may throw a render away (an interrupted or+// suspended concurrent render); its nodes are then never attached, and are+// freed after the next commit.+function created (container, node) {+ container.created.push(node)+ return node+}++function sweep (container) {+ const body = container.window.body+ for (const node of container.created) {+ let top = node+ while (top.parentNode !== null) top = top.parentNode+ if (top !== body && container.window._nodes.has(top.id)) top.destroy()+ }+ container.created.length = 0}let updatePriority = NoEventPriorityconst ROOT_CONTEXT = {}const host = {- rendererPackageName: '@blenderui/react',- rendererVersion: '0.1.0',+ rendererPackageName: '@blender-ui/react',+ rendererVersion: require('./package.json').version,supportsMutation: true,supportsPersistence: false,supportsHydration: false,@@ -114,17 +153,20 @@ const host = {getChildHostContext: (parent) => parent,getPublicInstance: (instance) => instance,prepareForCommit: () => null,- resetAfterCommit (container) { container.window.flush() }, // one native call per commit+ resetAfterCommit (container) {+ if (container.created.length > 0) sweep(container)+ container.window.flush() // one native call per commit+ },preparePortalMount () {},createInstance (type, props, container) {- if (type === SIGNAL_TEXT) return container.window.createTextNode(props.signal)+ if (type === SIGNAL_TEXT) return created(container, container.window.createTextNode(props.signal))const el = container.window.createElement(type)el._react = {}- applyProps(el, {}, props)- return el+ applyProps(el, NO_PROPS, props)+ return created(container, el)},- createTextInstance: (text, container) => container.window.createTextNode(text),+ createTextInstance: (text, container) => created(container, container.window.createTextNode(text)),appendInitialChild: (parent, child) => parent.appendChild(child),finalizeInitialChildren: () => false,shouldSetTextContent: (type, props) => isText(props.children),@@ -133,12 +175,19 @@ const host = {appendChildToContainer: (container, child) => container.window.body.appendChild(child),insertBefore: (parent, child, before) => parent.insertBefore(child, before),insertInContainerBefore: (container, child, before) => container.window.body.insertBefore(child, before),- removeChild: (parent, child) => parent.removeChild(child),- removeChildFromContainer: (container, child) => container.window.body.removeChild(child),+ removeChild (parent, child) {+ parent.removeChild(child)+ child.destroy()+ },+ removeChildFromContainer (container, child) {+ container.window.body.removeChild(child)+ child.destroy()+ },clearContainer (container) {for (const c of [...container.window.body.childNodes]) container.window.body.removeChild(c)},- detachDeletedInstance: (node) => node.ownerWindow._free(node),+ // the subtree: text set through textContent has no fiber of its own (freeing twice is a no-op)+ detachDeletedInstance: (node) => node.destroy(),commitUpdate (el, type, prev, next) {if (type === SIGNAL_TEXT) {@@ -183,6 +232,44 @@ const host = {afterActiveInstanceBlur () {},prepareScopeUpdate () {},bindToConsole: (method, args) => Function.prototype.bind.apply(console[method], [console, ...args]),++ // Commits that wait on resources: none here.+ maySuspendCommitOnUpdate: () => false,+ maySuspendCommitInSyncRender: () => false,+ getSuspendedCommitReason: () => null,++ // View transitions (<ViewTransition>): not animated here. As React DOM does+ // without the browser API: run the commit's phases now and report none.+ startViewTransition (suspendedState, container, types, mutation, layout, afterMutation, spawnedWork) {+ mutation()+ layout()+ spawnedWork()+ return null+ },+ startGestureTransition: () => null,+ stopViewTransition () {},+ suspendOnActiveViewTransition () {},+ addViewTransitionFinishedListener (transition, callback) { callback() },+ createViewTransitionInstance: (name) => ({ name, group: null, imagePair: null, old: null, new: null }),+ applyViewTransitionName () {},+ restoreViewTransitionName () {},+ cancelViewTransitionName () {},+ cancelRootViewTransitionName () {},+ restoreRootViewTransitionName () {},+ cloneRootViewTransitionContainer: (container) => container,+ removeRootViewTransitionClone () {},+ measureInstance: () => null,+ measureClonedInstance: () => null,+ wasInstanceInViewport: () => true,+ hasInstanceChanged: () => false,+ hasInstanceAffectedParent: () => false,+ getCurrentGestureOffset: () => 0,++ // <Fragment ref>: the fragment's fiber, nothing more (no DOM-like API yet).+ createFragmentInstance: (fiber) => ({ _fragmentFiber: fiber }),+ updateFragmentInstanceFiber (fiber, instance) { instance._fragmentFiber = fiber },+ commitNewChildToFragmentInstance () {},+ deleteChildFromFragmentInstance () {},}const reconciler = Reconciler(host)@@ -201,16 +288,27 @@ native.Element.prototype._dispatch = function (raw) {}function report (kind) {- return (err) => console.error(`@blenderui/react: ${kind}`, err)+ return (err) => console.error(`@blender-ui/react: ${kind}`, err)+}++// The root component gets render tracking even when created with React's+// own createElement (components below need this package's JSX runtime or+// createElement).+function trackRoot (element) {+ if (!React.isValidElement(element)) return element+ const type = hooks.track(element.type)+ if (type === element.type) return element+ return React.createElement(type, element.key != null ? { ...element.props, key: element.key } : element.props)}/** A React root rendering into `window`'s body. */function createRoot (window) {- const container = { window }+ const container = { window, created: [] }const root = reconciler.createContainer(container, ConcurrentRoot, null, false, null, 'bui',report('uncaught error'), report('caught error'), report('recoverable error'), null)+ window.on('close', () => reconciler.updateContainer(null, root, null, null))return {- render (element) { reconciler.updateContainer(element, root, null, null) },+ render (element) { reconciler.updateContainer(trackRoot(element), root, null, null) },unmount () { reconciler.updateContainer(null, root, null, null) },}}@@ -220,7 +318,7 @@ function createRoot (window) {* @param {React.ReactNode} element* @param {{ title?: string, width?: number, height?: number, resizable?: boolean,* gpu?: boolean, slug?: boolean, headless?: boolean, app?: App }} [options]- * @returns {{ app: App, window: import('@blenderui/native').Window, root: ReturnType<typeof createRoot> }}+ * @returns {{ app: App, window: import('@blender-ui/native').Window, root: ReturnType<typeof createRoot> }}*/function render (element, options = {}) {const app = options.app ?? new App({ gpu: options.gpu, slug: options.slug, headless: options.headless })@@ -232,27 +330,30 @@ function render (element, options = {}) {/** Run `fn` and flush React's work synchronously (tests). */function act (fn) {- reconciler.flushSyncFromReconciler?.(fn) ?? reconciler.flushSync?.(fn) ?? fn()+ const flushSync = reconciler.flushSyncFromReconciler ?? reconciler.flushSync+ return typeof flushSync === 'function' ? flushSync(fn) : fn()}-// React's hooks, re-exported as they are (whatever this React version has),-// so one import serves both; then BUI's signal twins (hooks.js).+// React's hooks by React's names: those that hold or react to state are the+// signal versions (hooks.js), the others are React's own.const reactHooks = {}for (const k of Object.keys(React)) if (/^use([A-Z]|$)/.test(k)) reactHooks[k] = React[k]module.exports = {...reactHooks,- ...require('./hooks'),+ ...hooks,render,createRoot,act,reconciler,- signal,- memo,- computed: memo,- effect,+ signal: native.signal,+ computed: native.memo, // `memo` stays React's (components)+ effect: native.effect,batch: native.batch,untrack: native.untrack,createSignal: native.createSignal,- startTransition: native.startTransition,+ ref: native.ref,+ isSignal,+ Signal,+ Memo,}diff --git a/bindings/react/jsx-dev-runtime.d.ts b/bindings/react/jsx-dev-runtime.d.tsnew file mode 100644index 0000000..190ecfe--- /dev/null+++ b/bindings/react/jsx-dev-runtime.d.ts@@ -0,0 +1,2 @@+export { Fragment, jsxDEV } from 'react/jsx-dev-runtime'+export type { JSX } from './jsx-runtime'diff --git a/bindings/react/jsx-dev-runtime.js b/bindings/react/jsx-dev-runtime.jsnew file mode 100644index 0000000..365974c--- /dev/null+++ b/bindings/react/jsx-dev-runtime.js@@ -0,0 +1,9 @@+// SPDX-License-Identifier: GPL-2.0-or-later+'use strict'+const runtime = require('react/jsx-dev-runtime')+const { track } = require('./hooks')++exports.Fragment = runtime.Fragment+// undefined in React's production build, as in React+exports.jsxDEV = runtime.jsxDEV && ((type, props, key, isStatic, source, self) =>+ runtime.jsxDEV(track(type), props, key, isStatic, source, self))diff --git a/bindings/react/jsx-runtime.d.ts b/bindings/react/jsx-runtime.d.tsnew file mode 100644index 0000000..548061e--- /dev/null+++ b/bindings/react/jsx-runtime.d.ts@@ -0,0 +1,26 @@+// With `"jsxImportSource": "@blender-ui/react"` in tsconfig, host elements'+// props accept signals: `<div style={styleMemo} className={cls}>`.+import type * as React from 'react'+import type { ReadSignal } from '@blender-ui/native'+export { Fragment, jsx, jsxs } from 'react/jsx-runtime'++type Fixed = 'children' | 'key' | 'ref' | 'dangerouslySetInnerHTML'+/** Each prop also takes a signal of its value (event handlers stay functions). */+export type Bindable<P> = {+ [K in keyof P]: K extends Fixed | `on${string}` ? P[K]+ : K extends 'style' ? P[K] | string | ReadSignal<Exclude<P[K], undefined> | string>+ : P[K] | ReadSignal<Exclude<P[K], undefined>>+}+type Intrinsic = { [K in keyof React.JSX.IntrinsicElements]: Bindable<React.JSX.IntrinsicElements[K]> }++export namespace JSX {+ type ElementType = React.JSX.ElementType+ interface Element extends React.JSX.Element {}+ interface ElementClass extends React.JSX.ElementClass {}+ interface ElementAttributesProperty extends React.JSX.ElementAttributesProperty {}+ interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {}+ type LibraryManagedAttributes<C, P> = React.JSX.LibraryManagedAttributes<C, P>+ interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {}+ interface IntrinsicClassAttributes<T> extends React.JSX.IntrinsicClassAttributes<T> {}+ interface IntrinsicElements extends Intrinsic {}+}diff --git a/bindings/react/jsx-runtime.js b/bindings/react/jsx-runtime.jsnew file mode 100644index 0000000..16c8c85--- /dev/null+++ b/bindings/react/jsx-runtime.js@@ -0,0 +1,11 @@+// `"jsxImportSource": "@blender-ui/react"`: React's JSX runtime. Components+// get render tracking (they re-render when a signal their render read+// changes); the types let every host-element prop take a signal.+// SPDX-License-Identifier: GPL-2.0-or-later+'use strict'+const runtime = require('react/jsx-runtime')+const { track } = require('./hooks')++exports.Fragment = runtime.Fragment+exports.jsx = (type, props, key) => runtime.jsx(track(type), props, key)+exports.jsxs = (type, props, key) => runtime.jsxs(track(type), props, key)diff --git a/bindings/react/package-lock.json b/bindings/react/package-lock.jsondeleted file mode 100644index d0be4ce..0000000--- a/bindings/react/package-lock.json+++ /dev/null@@ -1,74 +0,0 @@-{- "name": "@blenderui/react",- "version": "0.1.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "@blenderui/react",- "version": "0.1.0",- "license": "GPL-2.0-or-later",- "dependencies": {- "@blenderui/native": "file:../node",- "react-reconciler": "0.31.0"- },- "devDependencies": {- "react": "19.0.0"- },- "engines": {- "node": ">=18"- },- "peerDependencies": {- "react": "^19.0.0"- }- },- "../node": {- "name": "@blenderui/native",- "version": "0.1.0",- "cpu": [- "x64"- ],- "license": "GPL-2.0-or-later",- "os": [- "win32"- ],- "engines": {- "node": ">=18"- }- },- "node_modules/@blenderui/native": {- "resolved": "../node",- "link": true- },- "node_modules/react": {- "version": "19.0.0",- "resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz",- "integrity": "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==",- "license": "MIT",- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/react-reconciler": {- "version": "0.31.0",- "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.31.0.tgz",- "integrity": "sha512-7Ob7Z+URmesIsIVRjnLoDGwBEG/tVitidU0nMsqX/eeJaLY89RISO/10ERe0MqmzuKUUB1rmY+h1itMbUHg9BQ==",- "license": "MIT",- "dependencies": {- "scheduler": "^0.25.0"- },- "engines": {- "node": ">=0.10.0"- },- "peerDependencies": {- "react": "^19.0.0"- }- },- "node_modules/scheduler": {- "version": "0.25.0",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz",- "integrity": "sha512-xFVuu11jh+xcO7JOAGJNOXld8/TcEHK/4CituBUeUb5hqxJLj9YuemAEuvm9gQ/+pgXYfbQuqAkiYu+u7YEsNA==",- "license": "MIT"- }- }-}diff --git a/bindings/react/package.json b/bindings/react/package.jsonindex 05d5192..86c0245 100644--- a/bindings/react/package.json+++ b/bindings/react/package.json@@ -1,19 +1,74 @@{- "name": "@blenderui/react",+ "name": "@blender-ui/react","version": "0.1.0",- "description": "React renderer for BUI: Blender's UI in native windows, from JSX",+ "description": "React renderer for BUI: Blender's UI in native windows from JSX, with React's hooks backed by signals. Node.js and Bun.","main": "index.js","types": "index.d.ts",- "files": ["index.js", "hooks.js", "index.d.ts", "README.md"],- "scripts": { "test": "node --test" },- "engines": { "node": ">=18" },+ "exports": {+ ".": {+ "types": "./index.d.ts",+ "default": "./index.js"+ },+ "./jsx-runtime": {+ "types": "./jsx-runtime.d.ts",+ "default": "./jsx-runtime.js"+ },+ "./jsx-dev-runtime": {+ "types": "./jsx-dev-runtime.d.ts",+ "default": "./jsx-dev-runtime.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "index.js",+ "hooks.js",+ "index.d.ts",+ "jsx-runtime.js",+ "jsx-runtime.d.ts",+ "jsx-dev-runtime.js",+ "jsx-dev-runtime.d.ts",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test",+ "prepublishOnly": "node --test",+ "prepack": "node -e \"require('fs').copyFileSync('../../LICENSE', 'LICENSE')\"",+ "postpack": "node -e \"require('fs').rmSync('LICENSE', { force: true })\""+ },+ "engines": {+ "node": ">=18"+ },"dependencies": {- "@blenderui/native": "file:../node",- "react-reconciler": "0.31.0"+ "@blender-ui/native": "^0.1.0",+ "react-reconciler": "0.34.0"+ },+ "peerDependencies": {+ "react": "^19.3.0"+ },+ "devDependencies": {+ "react": "19.3.1"},- "peerDependencies": { "react": "^19.0.0" },- "devDependencies": { "react": "19.0.0" },"license": "GPL-2.0-or-later",- "repository": { "type": "git", "url": "git+https://github.com/ppmpreetham/BUI.git", "directory": "bindings/react" },- "keywords": ["react", "renderer", "blender", "ui", "native", "desktop", "napi", "tailwind"]+ "repository": {+ "type": "git",+ "url": "git+https://github.com/ppmpreetham/BUI.git",+ "directory": "bindings/react"+ },+ "homepage": "https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md",+ "bugs": {+ "url": "https://github.com/ppmpreetham/BUI/issues"+ },+ "keywords": [+ "react",+ "renderer",+ "react-reconciler",+ "signals",+ "blender",+ "ui",+ "desktop",+ "native",+ "tailwind",+ "bun"+ ]}diff --git a/bindings/react/test/hooks.test.js b/bindings/react/test/hooks.test.jsnew file mode 100644index 0000000..d79f405--- /dev/null+++ b/bindings/react/test/hooks.test.js@@ -0,0 +1,499 @@+// Each signal twin beside its React original: same inputs, same observable+// results. And coverage: every hook React exports is re-exported, and has a+// twin or a reason in NO_TWIN (so a React upgrade that adds one fails here).+'use strict'+const test = require('node:test')+const assert = require('node:assert')+const React = require('react')+const bui = require('..')+const { App } = require('@blender-ui/native')+const h = React.createElement++const tick = (ms = 30) => new Promise(r => setTimeout(r, ms))+let app+test.before(() => { app = new App({ headless: true }) })+test.after(() => app.quit())++function mount (element, strict = false) {+ const r = bui.render(strict ? h(React.StrictMode, null, element) : element,+ { app, headless: true, width: 120, height: 80 })+ return r+}+function unmount (r) {+ r.root.unmount()+ r.window.close()+}++test('coverage: every React hook is exported by its name: a signal version, or React\'s own with a reason', () => {+ const hooks = Object.keys(React).filter(k => /^use([A-Z]|$)/.test(k))+ assert.ok(hooks.length >= 18, 'found React\'s hooks')+ for (const k of hooks) {+ assert.strictEqual(typeof bui[k], 'function', `${k} is exported`)+ if (k in bui.NO_TWIN) assert.strictEqual(bui[k], React[k], `${k} is React's own`)+ else {+ assert.notStrictEqual(bui[k], React[k],+ `React ${React.version} has ${k}: add its signal version to hooks.js, or a reason to NO_TWIN`)+ }+ }+ const extra = ['useSignal', 'useComputed', 'useSignalValue']+ for (const k of Object.keys(bui)) {+ if (/^use([A-Z]|$)/.test(k) && !extra.includes(k)) assert.ok(k in React, `${k} is a React hook`)+ }+})++test('render tracking: a render that reads a signal re-renders; one that passes it on does not', async () => {+ const c = bui.createElement+ let readerRenders = 0, passerRenders = 0, set+ function Reader ({ n }) {+ readerRenders+++ return c('span', null, n.value > 1 ? 'big' : 'small', ' ', n + 1)+ }+ function Passer () {+ passerRenders+++ const [n, setN] = bui.useState(1)+ set = setN+ return c('div', null, n, c(Reader, { n }))+ }+ const r = mount(c(Passer))+ await tick()+ const text = () => [...r.window._nodes.values()].filter(x => x.nodeType === 3).map(x => x.data).join('|')+ assert.strictEqual(text(), '1|small| |2')+ set(2)+ await tick()+ assert.strictEqual(text(), '2|big| |3', 'Reader re-rendered with the new value')+ assert.strictEqual(passerRenders, 1, 'Passer only passed the signal: no re-render')+ assert.strictEqual(readerRenders, 2)+ unmount(r)+ await tick()+ set(3)+ await tick()+ assert.strictEqual(readerRenders, 2, 'unmounted: no longer subscribed')+})++test('render tracking under StrictMode, memo and forwardRef; refs read in render do not subscribe', async () => {+ const c = bui.createElement+ const s = bui.signal(0)+ let renders = 0+ const Inner = React.memo(React.forwardRef(function Inner (props, ref) {+ renders+++ const own = bui.useRef(0)+ own.current++ // a render-time ref write must not loop+ return c('span', { ref }, `v${s.value}`)+ }))+ const r = mount(c(Inner, {}), true)+ await tick()+ const before = renders+ s.value = 1+ await tick()+ assert.ok(renders > before, 'still subscribed after StrictMode\'s unmount and remount')+ const after = renders+ await tick(60)+ assert.strictEqual(renders, after, 'settled: no render loop')+ assert.ok([...r.window._nodes.values()].some(x => x.data === 'v1'))+ unmount(r)+})++test('nodes of a render React throws away are freed', async () => {+ const c = bui.createElement+ let resolve+ const promise = new Promise(r => { resolve = r })+ let suspend = true+ function Slow () {+ if (suspend) throw promise+ return c('b', null, 'done')+ }+ function App () {+ return c(React.Suspense, { fallback: c('i', null, 'wait') }, c('section', null, c('p', null, 'a'), c(Slow)))+ }+ const r = mount(c(App))+ await tick()+ const live = () => r.window._nodes.size+ const n0 = live()+ suspend = false+ resolve()+ await tick(500) // React 19 shows a fallback for at least 300 ms+ assert.ok([...r.window._nodes.values()].some(x => x.data === 'done'))+ const attached = (x) => { while (x.parentNode) x = x.parentNode; return x === r.window.body }+ const orphans = [...r.window._nodes.values()].filter(x => x.id !== 0 && !attached(x))+ assert.deepStrictEqual(orphans.map(x => x.localName ?? x.data), [], `no detached nodes left (had ${n0})`)+ unmount(r)+})++test('signal useState matches useState (values, updaters, bail-out) and skips re-renders', async () => {+ let renders = 0, rv, rset, sv, sset+ function C () {+ renders+++ ;[rv, rset] = React.useState(() => 1)+ ;[sv, sset] = bui.useState(() => 1)+ return null+ }+ const r = mount(h(C))+ await tick()+ assert.strictEqual(sv.value, rv)+ const steps = [5, (p) => p * 2, 10, 10, (p) => p + 1]+ for (const step of steps) {+ rset(step)+ sset(step)+ await tick()+ assert.strictEqual(sv.value, rv, `after ${step}`)+ }+ const before = renders+ sset(99)+ await tick()+ assert.strictEqual(renders, before, 'a signal write re-renders nothing')+ assert.strictEqual(sv.value, 99)+ assert.strictEqual(rset.length === undefined, false)+ unmount(r)+})++test('signal useReducer matches useReducer (init, actions, same-state bail-out)', async () => {+ const reducer = (s, a) => a.type === 'add' ? { n: s.n + a.by } : a.type === 'noop' ? s : { n: 0 }+ const init = (arg) => ({ n: arg * 10 })+ let rv, rd, sv, sd+ function C () {+ ;[rv, rd] = React.useReducer(reducer, 2, init)+ ;[sv, sd] = bui.useReducer(reducer, 2, init)+ return null+ }+ const r = mount(h(C))+ await tick()+ assert.deepStrictEqual(sv.value, rv)+ for (const a of [{ type: 'add', by: 3 }, { type: 'noop' }, { type: 'reset' }, { type: 'add', by: 7 }]) {+ const prevSignal = sv.peek()+ rd(a)+ sd(a)+ await tick()+ assert.deepStrictEqual(sv.value, rv)+ if (a.type === 'noop') assert.strictEqual(sv.peek(), prevSignal, 'same state object kept')+ }+ unmount(r)+})++test('signal useMemo matches useMemo across deps, and follows signals', async () => {+ const src = bui.signal(1)+ let rv, m, rRuns = 0, sRuns = 0, setX+ function C () {+ const [x, sx] = React.useState(1)+ setX = sx+ rv = React.useMemo(() => { rRuns++; return x * 100 }, [x])+ m = bui.useMemo(() => { sRuns++; return x * 100 + src.value }, [x])+ return h('div', null, m)+ }+ const r = mount(h(C))+ await tick()+ assert.strictEqual(m.value, rv + 1)+ setX(1) // same deps+ await tick()+ setX(2)+ await tick()+ assert.strictEqual(m.value, rv + 1)+ assert.strictEqual(rRuns, 2)+ src.value = 5 // only the signal memo depends on it+ assert.strictEqual(m.value, rv + 5)+ const text = [...r.window._nodes.values()].find(n => n.nodeType === 3 && n.data === '205')+ assert.ok(text, 'the bound text node follows the memo')+ assert.ok(sRuns <= 4, `signal memo recomputed only when needed (${sRuns})`)+ unmount(r)+})++test('signal useCallback: identity follows deps like useCallback; calls are batched and untracked', async () => {+ const ids = { r: [], s: [] }+ let setDep+ const a = bui.signal(0), b = bui.signal(0)+ let cb+ function C () {+ const [dep, sd] = React.useState(0)+ const [, force] = React.useState(0)+ setDep = (v) => { sd(v); force(n => n + 1) }+ ids.r.push(React.useCallback(() => dep, [dep]))+ cb = bui.useCallback(() => { a.value++; b.value++; return dep }, [dep])+ ids.s.push(cb)+ return null+ }+ const r = mount(h(C))+ await tick()+ setDep(0)+ await tick()+ setDep(1)+ await tick()+ const same = (list) => list.slice(1).map((f, i) => f === list[i])+ assert.deepStrictEqual(same(ids.s), same(ids.r))+ let runs = 0+ const stop = bui.effect(() => { a.value; b.value; runs++; if (runs === 1) cb() })+ assert.strictEqual(runs, 2, 'two writes, one re-run; and calling cb inside did not subscribe to more')+ stop()+ unmount(r)+})++test('signal useRef matches useRef: same .current, attached to the element, observable', async () => {+ let rref, sref+ const seen = []+ function C () {+ rref = React.useRef(null)+ sref = bui.useRef(null)+ bui.useEffect(() => { seen.push(sref.current ? sref.current.localName : null) }, [])+ return h('div', null, h('section', { ref: rref }), h('section', { ref: sref }))+ }+ const r = mount(h(C))+ await tick()+ assert.strictEqual(rref.current.localName, 'section')+ assert.strictEqual(sref.current.localName, 'section')+ assert.deepStrictEqual(seen, ['section'], 'mounted before the effect ran (as with useRef)')+ unmount(r)+ await tick()+ assert.strictEqual(rref.current, null)+ assert.strictEqual(sref.current, null)+})++for (const strict of [false, true]) {+ test(`effect twins run when React's do, deps and cleanups alike${strict ? ' (StrictMode)' : ''}`, async () => {+ const log = { r: [], s: [] }+ let setX+ function C () {+ const [x, sx] = React.useState(0)+ setX = sx+ for (const [kind, rh, sh] of [['insertion', React.useInsertionEffect, bui.useInsertionEffect],+ ['layout', React.useLayoutEffect, bui.useLayoutEffect], ['effect', React.useEffect, bui.useEffect]]) {+ for (const [d, deps] of [['always', undefined], ['once', []], ['x', [x]]]) {+ rh(() => { log.r.push(`${kind} ${d} ${x}`); return () => log.r.push(`${kind} ${d} cleanup ${x}`) }, deps)+ sh(() => { log.s.push(`${kind} ${d} ${x}`); return () => log.s.push(`${kind} ${d} cleanup ${x}`) }, deps)+ }+ }+ return null+ }+ const r = mount(h(C), strict)+ await tick()+ setX(1)+ await tick()+ setX(1)+ await tick()+ unmount(r)+ await tick()+ assert.ok(log.r.length > 10)+ assert.deepStrictEqual(log.s, log.r)+ })+}++test('signal useEffect also re-runs when a signal it read changes (with cleanup)', async () => {+ const s = bui.signal('a')+ const log = []+ function C () {+ bui.useEffect(() => { const v = s.value; log.push(v); return () => log.push(`-${v}`) }, [])+ return null+ }+ const r = mount(h(C))+ await tick()+ s.value = 'b'+ unmount(r)+ await tick()+ assert.deepStrictEqual(log, ['a', '-a', 'b', '-b'])+})++test('signal useSyncExternalStore matches useSyncExternalStore', async () => {+ let value = 1+ const listeners = new Set()+ const store = {+ subscribe: (l) => { listeners.add(l); return () => listeners.delete(l) },+ get: () => value,+ set: (v) => { value = v; for (const l of listeners) l() },+ }+ let rv, sv+ function C () {+ rv = React.useSyncExternalStore(store.subscribe, store.get)+ sv = bui.useSyncExternalStore(store.subscribe, store.get)+ return null+ }+ const r = mount(h(C))+ await tick()+ for (const v of [2, 2, 7]) {+ store.set(v)+ await tick()+ assert.strictEqual(sv.value, rv)+ }+ unmount(r)+ await tick()+ assert.strictEqual(listeners.size, 0, 'both unsubscribed')+})++test('signal useTransition matches useTransition: isPending through an async action', async () => {+ const seen = { r: [], s: [] }+ let rStart, sStart, sPending+ function C () {+ const [rp, rs] = React.useTransition()+ seen.r.push(rp)+ rStart = rs+ ;[sPending, sStart] = bui.useTransition()+ return null+ }+ const r = mount(h(C))+ await tick()+ const stop = bui.effect(() => { seen.s.push(sPending.value) })+ const action = () => new Promise(resolve => setTimeout(resolve, 50))+ rStart(action)+ sStart(action)+ await tick(10)+ assert.strictEqual(seen.s.at(-1), true)+ assert.strictEqual(seen.r.at(-1), true)+ await tick(100)+ assert.strictEqual(seen.s.at(-1), false)+ assert.strictEqual(seen.r.at(-1), false)+ const dedupe = (l) => l.filter((v, i) => i === 0 || v !== l[i - 1])+ assert.deepStrictEqual(dedupe(seen.s), dedupe(seen.r))+ stop()+ unmount(r)+})++test('signal transitions run their effects after urgent ones', async () => {+ const a = bui.signal(0), b = bui.signal(0)+ const order = []+ const s1 = bui.effect(() => { if (a.value) order.push('transition') })+ const s2 = bui.effect(() => { if (b.value) order.push('urgent') })+ const done = bui.startTransition(() => { a.value = 1 })+ assert.deepStrictEqual(order, [], 'deferred')+ b.value = 1+ assert.deepStrictEqual(order, ['urgent'])+ await done+ assert.deepStrictEqual(order, ['urgent', 'transition'])+ s1()+ s2()+})++test('signal useDeferredValue matches useDeferredValue: initialValue first, then the value', async () => {+ const seen = { r: [], s: [] }+ let setV, out+ function C () {+ const [v, sv] = React.useState('a')+ setV = sv+ seen.r.push(React.useDeferredValue(v, 'init'))+ out = bui.useDeferredValue(v, 'init')+ bui.useLayoutEffect(() => { seen.s.push(out.value) }, [])+ return null+ }+ const r = mount(h(C))+ await tick()+ setV('b')+ await tick()+ const dedupe = (l) => l.filter((v, i) => i === 0 || v !== l[i - 1])+ assert.deepStrictEqual(dedupe(seen.s), dedupe(seen.r))+ assert.deepStrictEqual(dedupe(seen.s), ['init', 'a', 'b'])+ // a signal source: follows without re-rendering+ const src = bui.signal(1)+ let def+ function D () { def = bui.useDeferredValue(src); return null }+ const r2 = mount(h(D))+ await tick()+ src.value = 2+ assert.strictEqual(def.peek(), 1, 'deferred: not yet')+ await tick()+ assert.strictEqual(def.peek(), 2)+ unmount(r)+ unmount(r2)+})++test('signal useActionState matches useActionState: queued, in order, with isPending', async () => {+ const action = async (prev, n) => { await tick(10); return prev + n }+ let rs, rd, rp, ss, sd, sp+ function C () {+ ;[rs, rd, rp] = React.useActionState(action, 0)+ ;[ss, sd, sp] = bui.useActionState(action, 0)+ return null+ }+ const r = mount(h(C))+ await tick()+ const pend = []+ const stop = bui.effect(() => { pend.push(sp.value) })+ React.startTransition(() => { rd(1); rd(2); rd(3) })+ sd(1); sd(2); sd(3)+ await tick(5)+ assert.strictEqual(sp.value, true)+ assert.strictEqual(rp, true)+ await tick(150)+ assert.strictEqual(ss.value, rs)+ assert.strictEqual(ss.value, 6)+ assert.strictEqual(rp, false)+ assert.deepStrictEqual(pend, [false, true, false], 'pending once across the queue')+ stop()+ unmount(r)+})++test('signal useActionState and useTransition send errors to the error boundary, as React does', async () => {+ class Boundary extends React.Component {+ constructor (p) { super(p); this.state = { error: null } }+ static getDerivedStateFromError (error) { return { error } }+ render () { return this.state.error ? h('span', null, `caught ${this.state.error.message}`) : this.props.children }+ }+ const caught = {}+ const fail = async () => { await tick(5); throw new Error('boom') }+ const cases = {+ actionState: (c) => { const [, d] = React.useActionState(fail, 0); c.go = () => React.startTransition(() => d()) },+ signalActionState: (c) => { const [, d] = bui.useActionState(fail, 0); c.go = () => d() },+ transition: (c) => { const [, start] = React.useTransition(); c.go = () => start(fail) },+ signalTransition: (c) => { const [, start] = bui.useTransition(); c.go = () => start(fail) },+ signalActionStateSync: (c) => {+ const [, d] = bui.useActionState(() => { throw new Error('boom') }, 0)+ c.go = () => d()+ },+ }+ for (const [kind, use] of Object.entries(cases)) {+ const c = {}+ function C () { use(c); return null }+ const r = mount(h(Boundary, null, h(C)))+ await tick()+ c.go()+ await tick(80)+ caught[kind] = [...r.window._nodes.values()].some(n => n.nodeType === 3 && n.data === 'caught boom')+ unmount(r)+ }+ assert.deepStrictEqual(caught, { actionState: true, signalActionState: true, transition: true, signalTransition: true, signalActionStateSync: true })+})++test('signal useOptimistic matches useOptimistic during and after an action', async () => {+ let rOpt, rAdd, rSet, sOpt, sAdd, sState, start+ function C () {+ const [rs, setRs] = React.useState(['a'])+ rSet = setRs+ ;[rOpt, rAdd] = React.useOptimistic(rs, (cur, item) => [...cur, item + '?'])+ sState = bui.useSignal(['a'])+ ;[sOpt, sAdd] = bui.useOptimistic(sState, (cur, item) => [...cur, item + '?'])+ ;[, start] = bui.useTransition()+ return null+ }+ const r = mount(h(C))+ await tick()+ start(async () => {+ rAdd('b')+ sAdd('b')+ await tick(40)+ React.startTransition(() => rSet(l => [...l, 'b']))+ sState.value = [...sState.peek(), 'b']+ })+ await tick(15)+ assert.deepStrictEqual(sOpt.value, ['a', 'b?'])+ assert.deepStrictEqual(rOpt, ['a', 'b?'])+ await tick(100)+ assert.deepStrictEqual(sOpt.value, ['a', 'b'])+ assert.deepStrictEqual(rOpt, ['a', 'b'])+ unmount(r)+})++test('signal useEffectEvent matches useEffectEvent: effects call the latest render\'s callback', async () => {+ const seen = { r: [], s: [] }+ let setX, fire+ function C () {+ const [x, sx] = React.useState(0)+ setX = sx+ const r = React.useEffectEvent(() => seen.r.push(x))+ const s = bui.useEffectEvent(() => seen.s.push(x))+ React.useEffect(() => { fire = () => { r(); s() } }, []) // captured once, on mount+ return null+ }+ const r = mount(h(C))+ await tick()+ fire()+ setX(5)+ await tick()+ fire()+ assert.deepStrictEqual(seen.s, seen.r)+ assert.deepStrictEqual(seen.s, [0, 5])+ unmount(r)+})diff --git a/bindings/react/test/react.test.js b/bindings/react/test/react.test.jsindex 76abae8..8486424 100644--- a/bindings/react/test/react.test.js+++ b/bindings/react/test/react.test.js@@ -36,7 +36,7 @@ test('React: render, state, events, conditional children (headless)', async (t)assert.deepStrictEqual(at(shot, 10, 42), [255, 0, 0], 'conditional child mounted (8px gap below the button)')})-test('React: BUI signals as props and children update without re-rendering', async (t) => {+test('React: signals as props and children update without re-rendering', async (t) => {const { useSignal, useComputed, useSignalValue, signal } = require('..')const external = signal(0)let renders = 0@@ -77,3 +77,61 @@ test('React: BUI signals as props and children update without re-rendering', asyconst span = [...window._nodes.values()].find(n => n.textContent === 'ext 5' && n.localName === 'span')assert.ok(span)})++test('React: text children switching to elements and back; onChange follows type', async (t) => {+ let setMode+ function C () {+ const [mode, sm] = React.useState('text')+ setMode = sm+ return h('div', { id: 'box' },+ mode === 'text' ? 'hello' : mode === 'el' ? h('span', null, 'inner') : null,+ h('input', { onChange: () => {}, type: mode === 'el' ? 'checkbox' : 'text', id: 'in' }))+ }+ const { app, window } = render(h(C), { headless: true, width: 100, height: 100 })+ t.after(() => app.quit())+ const find = (id) => [...window._nodes.values()].find(n => n.getAttribute?.('id') === id)+ await tick()+ assert.strictEqual(find('box').textContent, 'hello')+ assert.ok(find('in')._listeners.get('input')?.size, 'a text field: onChange is input')+ setMode('el')+ await tick()+ assert.strictEqual(find('box').childNodes[0].localName, 'span', 'the new element survived the text reset')+ assert.strictEqual(find('box').textContent, 'inner')+ assert.ok(find('in')._listeners.get('change')?.size, 'a checkbox: onChange is change')+ assert.ok(!find('in')._listeners.get('input')?.size, 'the input listener went away')+ setMode('none')+ await tick()+ assert.strictEqual(find('box').childNodes.length, 1, 'only the input left')+ const before = window._nodes.size+ setMode('el')+ await tick()+ setMode('none')+ await tick()+ assert.strictEqual(window._nodes.size, before, 'removed elements and their text are freed')+})++test('React: <Activity> hides and shows a subtree; <ViewTransition> commits without animating', async (t) => {+ const Activity = React.Activity ?? React.unstable_Activity+ const ViewTransition = React.ViewTransition ?? React.unstable_ViewTransition+ let setShow+ function C () {+ const [show, ss] = React.useState(true)+ setShow = ss+ const inner = h('span', { id: 'kid' }, 'kept')+ return h('div', null,+ h(Activity, { mode: show ? 'visible' : 'hidden' }, inner),+ ViewTransition ? h(ViewTransition, null, h('b', { id: 'vt' }, show ? 'a' : 'b')) : null)+ }+ const { app, window } = render(h(C), { headless: true, width: 100, height: 100 })+ t.after(() => app.quit())+ const find = (id) => [...window._nodes.values()].find(n => n.getAttribute?.('id') === id)+ await tick()+ assert.strictEqual(find('kid').hasAttribute('hidden'), false)+ React.startTransition(() => setShow(false))+ await tick(100)+ assert.strictEqual(find('kid').hasAttribute('hidden'), true, 'hidden, and kept')+ if (ViewTransition) assert.strictEqual(find('vt').textContent, 'b', 'the view transition committed')+ React.startTransition(() => setShow(true))+ await tick(100)+ assert.strictEqual(find('kid').hasAttribute('hidden'), false)+})diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rsindex 583c1b3..7235934 100644--- a/bindings/rust/blenderui-node/src/lib.rs+++ b/bindings/rust/blenderui-node/src/lib.rs@@ -7,8 +7,8 @@//! applies the ops to its mirror of the tree and re-renders; events come back//! through a thread-safe function.//!-//! The JavaScript side lives in `bindings/node` (`@blenderui/native`, with-//! `@blenderui/react` on top).+//! The JavaScript side lives in `bindings/node` (`@blender-ui/native`, with+//! `@blender-ui/react` on top).//!//! SPDX-License-Identifier: GPL-2.0-or-later@@ -130,10 +130,30 @@ fn parse_style(css: &str) -> Box<[blenderui::css::Decl]> {}).collect()}-/// One window's tree; node ids are per window and dense (root = 0).+/// Hashes a node id as itself: ids are unique, increasing integers.+#[derive(Default, Clone, Copy)]+struct IdHasher(u64);++impl std::hash::Hasher for IdHasher {+ fn finish(&self) -> u64 {+ self.0+ }+ fn write(&mut self, bytes: &[u8]) {+ for &b in bytes {+ self.0 = (self.0 << 8) | u64::from(b);+ }+ }+ fn write_u32(&mut self, n: u32) {+ self.0 = u64::from(n);+ }+}++type NodeMap = HashMap<u32, JsNode, std::hash::BuildHasherDefault<IdHasher>>;++/// One window's tree; node ids are per window, never reused (root = 0).struct JsView {window: u32,- nodes: Vec<Option<JsNode>>,+ nodes: NodeMap,tsfn: Tsfn,/// JS asked for an animation frame: tell it when this one renders.raf: bool,@@ -152,15 +172,13 @@ fn intern_tag(tag: &str, custom: &mut HashMap<String, &'static str>) -> &'staticimpl JsView {fn node(&mut self, id: i32) -> Option<&mut JsNode> {- self.nodes.get_mut(usize::try_from(id).ok()?)?.as_mut()+ self.nodes.get_mut(&u32::try_from(id).ok()?)}fn put(&mut self, id: i32, n: JsNode) {- let Ok(i) = usize::try_from(id) else { return };- if i >= self.nodes.len() {- self.nodes.resize_with(i + 1, || None);+ if let Ok(i) = u32::try_from(id) {+ self.nodes.insert(i, n);}- self.nodes[i] = Some(n);}fn apply(&mut self, ops: &[i32], strings: &[String], tags: &mut HashMap<String, &'static str>) {@@ -243,10 +261,8 @@ impl JsView {i += 3;}op::FREE => {- if let Ok(k) = usize::try_from(a(1)) {- if let Some(slot) = self.nodes.get_mut(k) {- *slot = None;- }+ if let Ok(k) = u32::try_from(a(1)) {+ self.nodes.remove(&k);}i += 2;}@@ -256,7 +272,7 @@ impl JsView {}fn build(&self, id: u32) -> AnyElement {- let Some(Some(n)) = self.nodes.get(id as usize) else {+ let Some(n) = self.nodes.get(&id) else {return String::new().into_any_element();};if let Some(t) = &n.text {@@ -301,14 +317,23 @@ impl JsView {MouseButton::Right => 2,}}+ // The deepest listening node gets the event, and native propagation+ // stops there: JavaScript bubbles it through its own tree, so+ // stopPropagation() works. Hover (mouseenter / mouseleave) doesn't bubble.macro_rules! on {($bit:expr, $method:ident $(($arg:expr))?, |$e:ident, $ev:ident| $body:block) => {+ on!(@ true, $bit, $method $(($arg))?, |$e, $ev| $body)+ };+ (@ $stop:expr, $bit:expr, $method:ident $(($arg:expr))?, |$e:ident, $ev:ident| $body:block) => {if bits & $bit != 0 {let (send, base) = (send.clone(), base.clone());- d = d.$method($($arg,)? move |$ev, _, _| {+ d = d.$method($($arg,)? move |$ev, _, app| {let mut $e = base.clone();$bodysend($e);+ if $stop {+ app.stop_propagation();+ }});}};@@ -340,7 +365,7 @@ impl JsView {(e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);mods(&mut e, &m.modifiers);});- on!(ev::HOVER, on_hover, |e, h| {+ on!(@ false, ev::HOVER, on_hover, |e, h| {e.kind = if *h { "mouseenter" } else { "mouseleave" }.into();});on!(ev::WHEEL, on_scroll_wheel, |e, w| {@@ -458,7 +483,9 @@ impl NativeApp {if let Some(w) = js {close.call(BuiEvent { kind: "close".into(), window: w, ..Default::default() },ThreadsafeFunctionCallMode::NonBlocking);- cx.global_mut::<UiState>().windows.remove(&w);+ let st = cx.global_mut::<UiState>();+ st.windows.remove(&w);+ st.by_native.remove(&id.0);}});if headless {@@ -510,7 +537,7 @@ impl NativeApp {};let handle = cx.open_window(opts, |_, cx| {cx.new(|_| {- let mut v = JsView { window: id, nodes: Vec::new(), tsfn, raf: false, frame_scheduled: false };+ let mut v = JsView { window: id, nodes: NodeMap::default(), tsfn, raf: false, frame_scheduled: false };v.put(0, JsNode { tag: "body", key: "n0".into(), text: None, attrs: Vec::new(),style: None, children: Vec::new(), events: 0 });v@@ -565,7 +592,9 @@ impl NativeApp {#[napi]pub fn close_window(&self, window: u32) {self.link.send(move |cx| {- if let Some(h) = cx.global_mut::<UiState>().windows.remove(&window) {+ let st = cx.global_mut::<UiState>();+ if let Some(h) = st.windows.remove(&window) {+ st.by_native.remove(&h.id.0);cx.close_window(h.id);}});@@ -652,3 +681,45 @@ pub struct Screenshot {/// RGBA, row-major.pub data: Buffer,}++// ==========================================================================+// Measuring (benchmarks): the same counters as bench/common/measure.rs.++#[cfg(windows)]+#[link(name = "kernel32")]+unsafe extern "system" {+ fn GetCurrentProcess() -> isize;+ fn QueryProcessCycleTime(p: isize, cycles: *mut u64) -> i32;+}++/// CPU cycles used by every thread of this process (Windows; otherwise null).+/// Unlike tick-based CPU time, exact for threads that wake on each vsync.+#[napi]+pub fn process_cpu_cycles() -> Option<f64> {+ #[cfg(windows)]+ {+ let mut c = 0u64;+ // SAFETY: the current-process pseudo handle and a valid out pointer.+ unsafe { QueryProcessCycleTime(GetCurrentProcess(), &mut c) };+ Some(c as f64)+ }+ #[cfg(not(windows))]+ {+ None+ }+}++/// The time-stamp counter (x86-64; otherwise null): divide cycle counts by+/// its rate, measured against the wall clock, to get CPU time.+#[napi]+pub fn timestamp_counter() -> Option<f64> {+ #[cfg(target_arch = "x86_64")]+ {+ // SAFETY: rdtsc has no preconditions on x86-64.+ Some(unsafe { core::arch::x86_64::_rdtsc() } as f64)+ }+ #[cfg(not(target_arch = "x86_64"))]+ {+ None+ }+}diff --git a/docs/javascript.md b/docs/javascript.mdindex f3e7398..7ee9d6d 100644--- a/docs/javascript.md+++ b/docs/javascript.md@@ -1,53 +1,77 @@# JavaScript and React-BUI runs from Node.js through a native addon (napi-rs), the way-[GPUIX](https://www.npmjs.com/package/@gpuix/react) drives GPUI: native-windows (CPU or Direct3D 11), no browser, with HTML elements, CSS and-Tailwind classes, and the same engine as the Rust crate.+BUI runs from JavaScript through a native addon built with napi-rs, much as+[GPUIX](https://www.npmjs.com/package/@gpuix/react) drives GPUI. You get native+windows drawn on the CPU or with Direct3D 11, HTML elements, CSS and Tailwind+classes, and the same engine as the Rust crate. There's no browser and no+Electron. It works on **Node.js** and **Bun**.| Package | What it is ||---|---|-| `@blenderui/native` (`bindings/node`) | A DOM-like API: `createElement`, `setAttribute`, `appendChild`, `addEventListener`, `requestAnimationFrame` |-| `@blenderui/react` (`bindings/react`) | A React 19 renderer on top of it |+| [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native) (`bindings/node`) | A DOM-like API (`createElement`, `setAttribute`, `appendChild`, `addEventListener`, `requestAnimationFrame`) and signals |+| [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) (`bindings/react`) | A React 19.3 renderer; React's hooks by React's names, backed by signals |-Status: Windows x64 with native windows. Elsewhere, `headless: true` works-(tests, screenshots). The browser (WebAssembly) build is next.+**Platforms:** prebuilt for Windows x64. On other platforms, build the addon+from source (see [Building](#building)) and use `headless: true` for now. A+browser (WebAssembly) build is planned.## Plain JavaScript```js-const { App } = require('@blenderui/native')+const { App, signal } = require('@blender-ui/native')const app = new App({ gpu: true })const win = app.window({ title: 'Hello', width: 360, height: 220 })win.body.className = 'm-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]'+const clicks = signal(0)const label = win.createElement('span')-label.textContent = 'Clicks: 0'+label.textContent = clicks // bound: follows the signalconst button = win.createElement('button')button.textContent = 'Add one'-let n = 0-button.addEventListener('click', () => { label.textContent = `Clicks: ${++n}` })+button.addEventListener('click', () => clicks.value++)win.body.appendChild(label)win.body.appendChild(button)```-Elements take the attributes the Rust crate does: `class` / `className`-(Tailwind classes included), `style` (a CSS string or an object such as-`{ backgroundColor: 'red', width: 40 }`), `id`, `href`, `value`, `src` ...-Events: `click`, `mousedown`, `mouseup`, `mousemove`, `mouseenter`,-`mouseleave`, `wheel`, `keydown`, `keyup`, `input`, `change`.+**Attributes** are the ones the Rust crate takes:-`win.requestAnimationFrame(cb)` runs `cb` before the next frame, paced by the-display; what it changes renders in that frame. `el.getBoundingClientRect()`-and `win.screenshot()` return promises. `new App({ headless: true })` renders-off-screen, and `win.click(x, y)` simulates input (for tests).+- `class` / `className`, including Tailwind classes;+- `style`, as a CSS string or an object such as+ `{ backgroundColor: 'red', width: 40 }`;+- `id`, `href`, `value`, `src` and so on.++Any of them can be a signal.++**Events** are `click`, `mousedown`, `mouseup`, `mousemove`, `mouseenter`,+`mouseleave`, `wheel`, `keydown`, `keyup`, `input` and `change`.++- **Bubbling:** events bubble through the tree, except `mouseenter` and+ `mouseleave`, as in the DOM. `stopPropagation()` and+ `stopImmediatePropagation()` work.+- **`event.target`** is the deepest element listening for that event type.+- **`preventDefault()`** only marks the event: events reach JavaScript after+ BUI has handled them.++**Frames and measurement:** `win.requestAnimationFrame(cb)` runs `cb` before+the next frame, paced by the display, and what it changes renders in that+frame. `el.getBoundingClientRect()` and `win.screenshot()` return promises.++**Tests:** `new App({ headless: true })` renders off-screen, and+`win.click(x, y)` simulates input.++The tree behaves like the DOM:++- **Moving a node:** `appendChild` or `insertBefore` moves a node that already+ has a parent.+- **Errors:** inserting a node into itself, or before a node that isn't a+ child, throws.+- **Freeing nodes:** `destroy()` frees a removed subtree natively.## React```jsx-import { useState } from 'react'-import { render } from '@blenderui/react'+import { render, useState } from '@blender-ui/react'function Counter () {const [count, setCount] = useState(0)@@ -62,117 +86,247 @@ function Counter () {render(<Counter />, { title: 'BUI + React', width: 420, height: 220, gpu: true })```-Host components are HTML elements. `className`, `style` objects, `htmlFor`-and boolean attributes work as in React DOM. `onChange` fires on every edit-of a text field, as in React DOM. Event handlers run as discrete updates, so-a click's state change commits immediately. `createRoot(window)` renders-into a window you opened yourself.+Set `"jsxImportSource": "@blender-ui/react"` in `tsconfig.json` or in your+bundler's JSX options. For code without JSX, use this package's+`createElement`. The runtime does two things:-## Hooks and signals+- **Render tracking:** a component that reads a signal while rendering+ re-renders when it changes.+- **TypeScript:** host-element props accept signals of their type.-React's hooks work as usual. BUI's own hooks, the Rust crate's `Signal`,-`Memo` and `Effect`, come along too, in both packages:+Host components are HTML elements, as in React DOM:-| Rust (`blenderui::hooks`) | JavaScript (`@blenderui/native`) | React component (`@blenderui/react`) |-|---|---|---|-| `use_signal(v)` / `RwSignal` | `signal(v)` | `useSignal(v)` |-| `Memo::new(f)` | `memo(f)` (alias `computed`) | `useComputed(f)` |-| `Effect::new(f)` | `effect(f)` (returns `dispose`) | `useSignalEffect(f)` |-| `signal(v)` / `create_signal(v)` | `createSignal(v)` (`[get, set]`) | |-| `use_state`, `use_effect`, `use_memo`, context | | React's own hooks |+- `className`, `style` objects, `htmlFor` and boolean attributes work.+- `onChange` fires on every edit of a text field. On checkboxes, radios,+ selects and other controls, it fires when the value changes, even if the+ control's `type` changes later.+- Event handlers run as discrete updates, so a click's state change commits+ immediately.-A signal is read with `.value` (or `.get()`), written with `.value = v`,-`.set(v)` or `.update(fn)`. Memos and effects track what they read, like-Leptos: no dependency arrays. `batch(fn)` groups writes into one update.+`<Suspense>`, `<Activity>`, transitions, actions and `<ViewTransition>` work;+view transitions commit without animating. `createRoot(window)` renders into a+window you opened yourself, and closing the window unmounts its root.-The point of signals is what they skip. Pass a signal where a value goes and-the node follows it:+## Hooks and signals-```jsx-import { render, useSignal, useComputed } from '@blenderui/react'+`@blender-ui/react` exports React's hooks by React's names. The ones that hold+or react to state take React's arguments and run at React's moments, but the+state they hold is a **signal**:++- **Passed as a prop or child** (`<span>{count}</span>`, `style={style}`): a+ change updates that one node. The component doesn't re-render.+- **Read while rendering** (`count.value`, or in plain JavaScript also+ `count + 1`, `count > 5`, `${count}`): the component re-renders when it+ changes, exactly as with React's hooks. TypeScript needs `.value` for+ arithmetic.+- **Conditions and `===` need `.value`.** A signal is an object, so it's always+ truthy: write `{isPending.value && <Spinner />}` and `count.value === 0`.+ TypeScript catches `===`, but not truthiness.+```jsxfunction Counter () {- const count = useSignal(0)- const style = useComputed(() => ({ color: count.value > 9 ? '#e5a50a' : '#e6e6e6' }))+ const [count, setCount] = useState(0)+ const style = useMemo(() => ({ color: count.value > 9 ? '#e5a50a' : '#e6e6e6' }), [])return (<main className="p-6 flex flex-col gap-3"><span style={style}>Clicks: {count}</span>- <button onClick={() => count.value++}>Add one</button>+ <button onClick={() => setCount(c => c + 1)}>Add one</button></main>)}```-A click writes `count`, which updates one text node and one `style`. `Counter`-renders once, ever. Without the reconciler running, there's no new element-tree, no props diff and almost no garbage, which is why the React numbers-below drop to those of the plain API. `useSignalValue(sig)` does the opposite-when you want it: it re-renders its component on changes.+A click updates one text node and one `style`. `Counter` renders once. With+no reconciler running, there's no new element tree, no props diff and almost+no garbage. That's why React with signals costs about what the plain API does+(see Performance).-In plain JavaScript, the same binding works with `el.setAttribute(name, sig)`,-`el.style = sig`, `el.textContent = sig` and `win.createTextNode(sig)`. A-plain value unbinds; `destroy()` frees the bindings of a subtree.+| Hook | Returns | Notes |+|---|---|---|+| `useState(init)` | `[signal, setState]` | `setState(v)` or `setState(prev => next)`; the same value doesn't update |+| `useReducer(reducer, arg, init?)` | `[signal, dispatch]` | Uses the latest render's reducer, as React does |+| `useRef(v)` | a ref | Effects and memos see `.current` change (an element mounting re-runs them); reading it while rendering doesn't subscribe |+| `useMemo(fn, deps?)` | a memo | Recomputes when the signals it read change; replaced when `deps` change; without deps, every render |+| `useCallback(fn, deps?)` | a function | Identity follows `deps`; calls are batched and don't subscribe the caller |+| `useEffectEvent(fn)` | a function | Calls the latest render's `fn`; batched and untracked |+| `useEffect(fn, deps?)` | | React's timing, deps and cleanups; also re-runs when the signals it read change |+| `useLayoutEffect(fn, deps?)` | | Same, at layout time |+| `useInsertionEffect(fn, deps?)` | | Same, at insertion time |+| `useSyncExternalStore(subscribe, get)` | a signal | Follows the store without re-rendering |+| `useTransition()` | `[isPending, start]` | Updates caused by the writes in `start(action)` run after urgent ones, in 5 ms slices; `action` may be async |+| `useDeferredValue(value, initial?)` | a signal | Follows a value or a signal at transition priority |+| `useActionState(action, initial)` | `[state, dispatch, isPending]` | Actions queue and run in order; errors reach the error boundary |+| `useOptimistic(state, reducer?)` | `[optimistic, add]` | Updates last until their transition or action ends |++`use`, `useContext`, `useId`, `useDebugValue` and `useImperativeHandle` are+React's own. They hold no state; for context, pass a signal as the value and+consumers bind to it. React's plain-value hooks are still available from+`react`, and they work in this renderer too.++Also:++- **`useSignal(v)` and `useComputed(fn)`:** the Rust crate's names+ (`use_signal`, `Memo::new`).+- **`useSignalValue(sig)`:** re-renders its component when `sig` changes,+ for components rendered without this package's JSX runtime.+- **Reading and writing a signal:** read with `.value` or `.get()`; write+ with `.value = v`, `.set(v)` or `.update(fn)`.+- **Grouping updates:** `batch(fn)` turns several writes into one update, and+ `startTransition(fn)` makes the writes in `fn` low priority.+- **Signal names here:** `computed` is `memo` from `@blender-ui/native`. The+ name `memo` stays React's, for components.++**Keeping up with React.** Every hook is built from React's public hooks:+`useState`, `useReducer`, `useRef`, `useMemo`, the effect hooks and+`startTransition`. StrictMode, concurrent rendering and React's timing+therefore come from React itself. `bindings/react/test/hooks.test.js` runs+each hook beside React's original, in development and production builds and+under StrictMode. It fails when a React release adds a hook that has neither+a signal version nor an entry in `NO_TWIN`. That is how it caught React+19.2's `useEffectEvent`.++**Plain JavaScript** has the same core: `signal`, `memo`, `effect`, `batch`,+`untrack` and `startTransition`.++- **Binding:** `el.setAttribute(name, sig)`, `el.style = sig`,+ `el.textContent = sig` or `win.createTextNode(sig)`.+- **Unbinding:** setting a plain value unbinds the signal, and `destroy()`+ frees the bindings of a subtree.+- **Without the addon:** `require('@blender-ui/native/signals')`.++| Rust (`blenderui::hooks`) | `@blender-ui/native` | `@blender-ui/react` |+|---|---|---|+| `use_signal(v)` / `RwSignal` | `signal(v)` | `useSignal(v)` / `useState(v)` |+| `Memo::new(f)` | `memo(f)` | `useComputed(f)` / `useMemo(f, deps)` |+| `Effect::new(f)` | `effect(f)` (returns `dispose`) | `useEffect(f, [])` |+| `signal(v)` / `create_signal(v)` | `createSignal(v)` (`[get, set]`) | `useState(v)` |++The signals are push-pull and glitch-free:++- **Each memo or effect runs once per change:** a write marks direct readers+ dirty and indirect ones "check", and every memo or effect then runs at most+ once for it, after all its sources have settled.+- **Memos stop changes early:** a memo whose value didn't change stops the+ change from spreading further.+- **Unread memos hold nothing:** a memo that nothing observes keeps no+ subscriptions, so it is garbage once dropped.+- **Writes inside an effect:** a write to a signal the effect itself reads+ re-runs it after the current run.+- **Errors:** a memo that throws rethrows on read and recovers when its+ sources change.## How it works-- **A UI thread.** BUI runs its own message loop on a thread of its own. Node's- thread is never blocked, and an idle UI uses no CPU. A message-only window- wakes the loop from Node (`BK_window_wake`), and it survives Win32's modal- move and resize loops.+- **A UI thread.** BUI runs its own message loop on a thread of its own, so+ the JavaScript thread is never blocked and an idle UI uses no CPU. A+ message-only window wakes the loop from JavaScript (`BK_window_wake`), and it+ survives Win32's modal move and resize loops.- **Only changes cross.** JavaScript keeps the tree. Each tick, a window sends- one `Int32Array` of ops (create, set attribute, append, insert, remove,- set text, listen) and a string table that is deduplicated per batch. React- sends one batch per commit.-- **Retained mirror.** The UI thread applies the ops to its copy of the tree- and rebuilds elements from it, keyed per node. Layout caches and form state- persist, and a `style` attribute is parsed once, when it is set.-- **Events** come back through a napi thread-safe function. They are- asynchronous, so `preventDefault()` has no native effect.+ one `Int32Array` of operations (create, set attribute, append, insert,+ remove, set text, listen, free) plus a string table deduplicated per batch.+ React sends one batch per commit.+- **Retained mirror.** The UI thread applies the operations to its copy of the+ tree and rebuilds elements from it, keyed per node. Layout caches and form+ state persist, and a `style` attribute is parsed once, when it's set.+- **Events** come back through a napi thread-safe function. The deepest+ listening element gets each event natively, and JavaScript bubbles it.- **Animation.** While `requestAnimationFrame` is active, the native side- schedules the next vsync during the current render, as browsers do. The- changes JavaScript makes in its callback join that frame, giving one rebuild+ schedules the next vsync during the current render, as browsers do. Changes+ JavaScript makes in its callback join that frame, so there is one rebuildper frame.+- **Freeing.** Nodes that React removes, or creates in a render it throws away+ (an interrupted or suspended concurrent render), are freed natively. So is+ a closed window's tree: its bindings and listeners are released.## Performance-A 1000x800 window with a grid of N cells, where one cell changes colour and-label every frame. This is the Rust benchmark's `one` mode, driven from-`requestAnimationFrame` (`node bench/cells.js N [--gpu] [--react]`). UI work-is the UI thread's per-frame time from `BUI_PROFILE=1`. It is wall time, which-is reliable here, unlike Windows' tick-based CPU accounting for-vsync-aligned threads.--| 3000 cells, GPU | Rust | JS (plain) | React, signals | React, state |-|---|---:|---:|---:|---:|-| Frames per second | 60 | 55β57 | 56 | 53β58 |-| UI thread work per frame | 10.0 ms | 12.9 ms | β plain JS | 14.1 ms |-| Resident memory | ~42 MB | ~87 MB | ~95 MB | ~184 MB |--"React, state" re-renders the 3,000-cell grid every frame with `useState`;-"React, signals" binds cell 0's style and label to signals-(`--react --signals`), so the grid renders once.--At 1,000 cells, all of them hold 60 fps. Where the memory goes:+The Rust benchmark's `one` mode: a 1000Γ800 window with a grid of N cells,+where one cell changes colour and label every frame, driven from+`requestAnimationFrame`. Command: `bench/cells.js N --gpu [--react+[--signals]]`, run with `node` or `bun`.++- **"React, signals":** cell 0's style and label are signals, so the grid+ renders once.+- **"React, state":** the grid re-renders every frame, as with React's+ `useState`.+- **React build:** the benchmark uses React's production build; `--dev` uses+ the development build.++CPU is the whole process: JavaScript, BUI's UI thread and the runtime. It is+counted with the process cycle counter, as the Rust benchmark does+(`bindings/rust/bench`), because Windows' tick-based CPU time misses threads+that wake on each vsync.++The table shows medians of 3 runs, GPU renderer, on a Ryzen 7 5800U laptop+(Windows 11, 60 Hz) with Node.js 22.17 and Bun 1.4.4, all in one session.++| 3,000 cells | FPS | CPU per frame | RAM (resident) |+|---|---:|---:|---:|+| Rust | 59.6 | **12.0 ms** | **43 MB** |+| Bun, plain JS | **58.8** | 13.1 ms | 80 MB |+| Bun, React with signals | 58.4 | 13.3 ms | 85 MB |+| Bun, React with state | 55.8 | 20.8 ms | 118 MB |+| Node, plain JS | 55.8 | 14.4 ms | 88 MB |+| Node, React with signals | 56.7 | 14.0 ms | 93 MB |+| Node, React with state | 54.8 | 18.9 ms | 121 MB |++| 1,000 cells (all at 60 FPS) | CPU per frame | RAM |+|---|---:|---:|+| Rust | **4.8 ms** | **32 MB** |+| Bun: plain JS / React with signals / React with state | 5.2 / 5.2 / 7.5 ms | 58 / 63 / 81 MB |+| Node: plain JS / React with signals / React with state | 5.6 / 5.6 / 6.9 ms | 68 / 71 / 97 MB |++What these show:++- **Overhead over Rust:** JavaScript adds 0.4β0.8 ms per frame at 1,000 cells+ and 1.1β2.4 ms at 3,000. That's the cost of sending changes to the UI+ thread, and of its copy of the tree.+- **Memory:** most of the extra RAM is the runtime itself. Node alone is about+ 32 MB, and Bun's footprint is about 10 MB smaller.+- **React with signals:** costs what the plain API does. At 3,000 cells it+ uses about a quarter less CPU and memory than re-rendering, because the+ component never re-renders.+- **React's development build:** much heavier. Re-rendering 3,000 cells took+ about 184 MB, so measure with `NODE_ENV=production`.+- **Bun vs Node:** Bun is slightly faster with plain JS and signals, and+ leaner everywhere. Node is faster when React re-renders every frame.++Where the memory goes, for plain JS on Node at 3,000 cells:- **Node itself:** 32 MB before anything loads.-- **A GPU window:** about 21 MB (driver, swap chain, glyph atlas). Rust pays- this too.-- **The native tree:** about 7 MB more than Rust for 3,000 cells, because the- UI thread keeps its own copy of the tree.-- **React re-rendering:** the live JS heap is only about 15 MB, but each- re-render of the grid creates about 3,000 elements, props objects and- strings. V8 grows its heap to about 113 MB to absorb that garbage, and- Windows keeps counting the pages. Signals avoid the re-render, and so the- garbage.+- **A GPU window:** about 21 MB, for the driver, swap chain and glyph atlas.+ Rust pays this too.+- **The native tree:** about 7 MB more than Rust, because the UI thread keeps+ its own copy of the tree.+- **JavaScript objects:** a few MB live.## Building```sh-cd bindings/node && npm run build # cargo build -p blenderui-node --release, copies the .node file-npm test # headless tests-node examples/counter.js-cd ../react && npm install && npm test && node examples/counter.js+cd bindings+npm install # links the two packages (npm workspaces)+npm run build # cargo build -p blenderui-node --release, copies the .node file+npm test # both packages' tests (headless)+node node/examples/counter.js+node react/examples/counter.js+bun node/bench/cells.js 3000 --gpu --react --signals # Bun works too```-The build needs what the Rust crate needs: CMake and a C compiler. With+The build needs what the Rust crate needs: Rust, CMake and a C compiler. WithMinGW, put its `bin` folder on `PATH`.++## Publishing++Both packages are ready for `npm publish` from their folders, in this order:++1. Bump the versions. `@blender-ui/react` depends on `@blender-ui/native` by+ version, so publish that first.+2. Run `npm publish --access public` in `bindings/node`, then in+ `bindings/react`.+ - `prepublishOnly` builds the addon and runs the tests.+ - `prepack` copies the repository's `LICENSE` into the package.++The native package ships `blenderui.win32-x64.node` and is limited to Windows+x64 (`os` and `cpu` in `package.json`). Supporting more platforms means+building the addon on each one, typically in CI, and publishing them as+optional per-platform packages, the napi-rs convention.