Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: add js support
Preetham Pemmasani849e22cf60e8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3731984..0138825 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,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.+ - 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.+- **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()`.+ - `css::Value::Shared`, and `StyleBlock` for `&[Decl]`, for pre-parsed styles.+- **C:** `BK_window_wake_init` / `BK_window_wake` (a cross-thread wake through a message-only window) and `BK_window_set_keep_alive`.++### Fixed+- **GPU text:** `BUI_gpu_slug()` read the environment on every text run, which pushed the GPU raster from 1.6 to 9.4 ms per frame at 3,000 cells. It now reads it once.+- **`WindowHandle::update`:** `cx.notify()` inside the closure didn't re-render that window.+### Changed- **Text looks like Blender's:** Inter, Blender's UI font, is embedded and is the default face on every platform. The portable stb_truetype engine is now the default on Windows too. `-DBUI_TEXT_GDI=ON` (Rust: the `gdi-text` feature) restores GDI and system fonts. `BUI_TEXT_STB` and `portable-text` are now no-ops.diff --git a/README.md b/README.mdindex 506de8e..628985b 100644--- a/README.md+++ b/README.md@@ -38,7 +38,7 @@ UI library with a small C core. Your code builds the widget tree and handlescallbacks. Layout, input, drawing and presenting all happen in fast nativecode.-You can drive it four ways, and all of them share the same C runtime:+You can drive it five ways, and all of them share the same C runtime:| You write | You get | Status ||---|---|---|@@ -46,6 +46,7 @@ You can drive it four 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) |## Quick start@@ -241,6 +242,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)) || Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms |### 🟡 Partial or in progress@@ -251,6 +253,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`) || 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 |@@ -258,8 +261,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. This unlocks the React, JS/TS and Tauri targets |-| **React** (`@blenderui/react`) | A JSX reconciler over the WASM build |+| **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 || **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 |@@ -350,6 +352,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 || [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/node/.gitignore b/bindings/node/.gitignorenew file mode 100644index 0000000..4c8908a--- /dev/null+++ b/bindings/node/.gitignore@@ -0,0 +1,2 @@+*.node+node_modules/diff --git a/bindings/node/README.md b/bindings/node/README.mdnew file mode 100644index 0000000..165d6e4--- /dev/null+++ b/bindings/node/README.md@@ -0,0 +1,30 @@+# @blenderui/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.++```js+const { App } = require('@blenderui/native')+const app = new App({ gpu: true })+const win = app.window({ title: 'Hello', width: 360, height: 200 })+const button = win.createElement('button')+button.className = 'm-4'+button.textContent = 'Click me'+button.addEventListener('click', () => { button.textContent = 'Clicked' })+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:++```js+const { signal } = require('@blenderui/native')+const clicks = signal(0)+button.textContent = clicks // follows the signal+button.addEventListener('click', () => clicks.value++)+```++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.diff --git a/bindings/node/bench/cells.js b/bindings/node/bench/cells.jsnew file mode 100644index 0000000..ce00ddc--- /dev/null+++ b/bindings/node/bench/cells.js@@ -0,0 +1,99 @@+// The Rust benchmark's "one" mode from JavaScript: a 1000x800 window with a+// 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).+'use strict'+const args = process.argv.slice(2)+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++// same grid and colours as bindings/rust/bench/common/measure.rs+const W = 1000, H = 800, GAP = 2+const cols = Math.max(1, Math.ceil(Math.sqrt(cells * W / H)))+const rows = Math.ceil(cells / cols)+const cw = Math.floor((W - GAP) / cols - GAP), ch = Math.floor((H - GAP) / rows - GAP)+const font = Math.floor(Math.min(14, Math.max(8, ((H - GAP) / rows - GAP) * 0.55)))+function color (i, t) {+ const h = ((i * 7 + t * 3) % 360) / 60, s = 0.55, v = 0.75, c = v * s+ const x = c * (1 - Math.abs((h % 2) - 1)), m = v - c+ const [r, g, b] = [[c, x, 0], [x, c, 0], [0, c, x], [0, x, c], [x, 0, c], [c, 0, x]][Math.floor(h) % 6]+ const hex = (u) => Math.round((u + m) * 255).toString(16).padStart(2, '0')+ return `#${hex(r)}${hex(g)}${hex(b)}`+}+const label = (i, t) => String((i * 13 + t) % 1000)+const cellStyle = (i, t) => `width: ${cw}px; height: ${ch}px; background: ${color(i, t)}; border-radius: 3px; ` ++ `display: flex; align-items: center; justify-content: center; font-size: ${font}px; color: #fff`+const gridStyle = `width: 100%; height: 100%; background: #303030; display: flex; flex-wrap: wrap; ` ++ `align-content: flex-start; gap: ${GAP}px; padding: ${GAP}px`++let tick+let app+let win+if (useReact) {+ const React = require(require.resolve('react', { paths: [require('node:path').join(__dirname, '../../react')] }))+ const { render } = require('../../react')+ const h = React.createElement+ let setT+ const { signal, batch } = require('..')+ const style0 = signal(cellStyle(0, 0))+ const label0 = signal(label(0, 0))+ function Grid () {+ const [t, set] = React.useState(0)+ setT = set+ const kids = []+ for (let i = 0; i < cells; i++) {+ const ti = i === 0 ? t : 0+ if (i === 0 && useSignals) kids.push(h('div', { key: i, style: style0 }, label0))+ else kids.push(h('div', { key: i, style: cellStyle(i, ti) }, label(i, ti)))+ }+ return h('div', { style: gridStyle }, kids)+ }+ const r = render(h(Grid), { title: 'BUI bench (React)', width: W, height: H, gpu })+ app = r.app+ win = r.window+ r.window.body.style = 'margin: 0'+ tick = useSignals+ ? (t) => batch(() => { style0.value = cellStyle(0, t); label0.value = label(0, t) })+ : (t) => setT(t)+} else {+ const { App } = require('..')+ app = new App({ gpu })+ win = app.window({ title: 'BUI bench (JS)', width: W, height: H })+ win.body.style = 'margin: 0'+ const grid = win.createElement('div')+ grid.style = gridStyle+ let first, firstText+ for (let i = 0; i < cells; i++) {+ const c = win.createElement('div')+ c.style = cellStyle(i, 0)+ const text = win.createTextNode(label(i, 0))+ c.appendChild(text)+ grid.appendChild(c)+ if (i === 0) { first = c; firstText = text }+ }+ win.body.appendChild(grid)+ 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+// one update per displayed frame (vsync), like the Rust benchmark+const 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(() => {+ const cpu = process.cpuUsage(cpu0), wall = performance.now() - wall0+ const ms = (cpu.user + cpu.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),+ rss_mb: +(rss / samples / 1048576).toFixed(1),+ }))+ app.quit()+}, (warmup + seconds) * 1000)diff --git a/bindings/node/examples/counter.js b/bindings/node/examples/counter.jsnew file mode 100644index 0000000..c9c1394--- /dev/null+++ b/bindings/node/examples/counter.js@@ -0,0 +1,32 @@+// A counter in a native window, with the plain DOM-like API.+// node examples/counter.js (BUI_GPU=1 for the GPU renderer)+'use strict'+const { App } = require('..')++const app = new App({ gpu: process.env.BUI_GPU === '1' })+const win = app.window({ title: 'BUI from Node', width: 360, height: 220 })+win.body.className = 'm-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]'++const title = win.createElement('h1')+title.className = 'text-xl font-bold'+title.textContent = 'Hello from JavaScript'+win.body.appendChild(title)++const row = win.createElement('div')+row.className = 'flex items-center gap-3'+const label = win.createElement('span')+label.textContent = 'Clicks: 0'+const button = win.createElement('button')+button.textContent = 'Add one'+let n = 0+button.addEventListener('click', () => { label.textContent = `Clicks: ${++n}` })+row.appendChild(label)+row.appendChild(button)+win.body.appendChild(row)++win.on('close', () => console.log(`closed after ${n} clicks`))+if (process.env.BUI_EXAMPLE_SECONDS) {+ // CI / smoke tests: click once, then quit+ setTimeout(() => { const r = button.getBoundingClientRect(); r.then(b => win.click(b.x + 5, b.y + 5)) }, 300)+ setTimeout(() => { console.log(`label: ${label.textContent}`); app.quit() }, Number(process.env.BUI_EXAMPLE_SECONDS) * 1000)+}diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.tsnew file mode 100644index 0000000..bbd66d6--- /dev/null+++ b/bindings/node/index.d.ts@@ -0,0 +1,164 @@+// Types for @blenderui/native.+export interface AppOptions {+ /** Draw on the GPU (Direct3D 11). */+ gpu?: boolean+ /** GPU text from glyph outlines (Slug, default) or a per-glyph atlas. */+ slug?: boolean+ /** No native windows: tests, screenshots, CI. */+ headless?: boolean+ /** Quit when the last window closes (default true). */+ quitOnLastWindowClosed?: boolean+}++export interface WindowOptions {+ title?: string+ width?: number+ height?: number+ resizable?: boolean+ gpu?: boolean+}++export type EventType = 'click' | 'mousedown' | 'mouseup' | 'mousemove' | 'mouseenter' | 'mouseleave' |+ 'wheel' | 'keydown' | 'keyup' | 'change' | 'input'++export class BuiEvent {+ type: EventType+ target: Element+ currentTarget: Element+ clientX: number+ clientY: number+ x: number+ y: number+ button: number+ detail: number+ deltaY: number+ key?: string+ char?: string+ shiftKey: boolean+ ctrlKey: boolean+ altKey: boolean+ metaKey: boolean+ timeStamp: number+ preventDefault (): void+ stopPropagation (): void+}++export class Node {+ readonly ownerWindow: Window+ readonly id: number+ parentNode: Element | null+ childNodes: Node[]+ readonly firstChild: Node | null+ readonly lastChild: Node | null+ readonly nextSibling: Node | null+ textContent: string+ appendChild<T extends Node> (child: T): T+ insertBefore<T extends Node> (child: T, before: Node | null): T+ removeChild<T extends Node> (child: T): T+ remove (): void+ /** Free the node and its subtree natively (after removing it). */+ destroy (): void+}++export class TextNode extends Node {+ /** A string, or a signal (the text then follows it). */+ data: string | ReadSignal<unknown>+ nodeValue: string+}++export class Element extends Node {+ readonly tagName: string+ readonly localName: string+ className: string+ /** CSS text, or an object such as `{ backgroundColor: 'red', width: 40 }`. */+ style: string | Record<string, string | number | null | undefined> | ReadSignal<string | Record<string, string | number | null | undefined>>+ /** Form controls: the latest value from input / change events. */+ value?: string+ checked?: boolean+ /** A value, or a signal: the attribute then follows it (null / false removes it). */+ setAttribute (name: string, value: unknown): void+ getAttribute (name: string): string | null+ hasAttribute (name: string): boolean+ removeAttribute (name: string): void+ addEventListener (type: EventType, listener: (event: BuiEvent) => void): void+ removeEventListener (type: EventType, listener: (event: BuiEvent) => void): void+ getBoundingClientRect (): Promise<{ x: number, y: number, width: number, height: number } | null>+}++export class Window {+ readonly app: App+ readonly id: number+ readonly body: Element+ closed: boolean+ createElement (tag: string): Element+ createTextNode (text: string | ReadSignal<unknown>): TextNode+ /** Send pending changes now (they are otherwise sent once per tick). */+ flush (): void+ /** Run `cb` before the next frame, paced by the display. */+ requestAnimationFrame (cb: (time: number) => void): number+ cancelAnimationFrame (id: number): void+ screenshot (): Promise<{ width: number, height: number, data: Buffer }>+ click (x: number, y: number): void+ close (): void+ on (event: 'close', listener: () => void): this+}++export class App {+ constructor (options?: AppOptions)+ readonly headless: boolean+ readonly windows: Map<number, Window>+ quitOnLastWindowClosed: boolean+ window (options?: WindowOptions): Window+ setSlug (on: boolean): void+ quit (): void+}++export function styleText (style: Record<string, string | number | null | undefined>): string++// Signals: BUI's hooks (the Rust crate's Signal / Memo / Effect).+// Bind one to an attribute, `style` or text and that node alone updates.++export interface ReadSignal<T> {+ /** Read, subscribing the running memo / effect. */+ readonly value: T+ get (): T+ /** Read without subscribing. */+ peek (): 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+}++export class Signal<T> implements ReadSignal<T> {+ constructor (value: T, options?: { equals?: (a: T, b: T) => boolean })+ value: T+ get (): T+ peek (): T+ set (value: T): void+ update (fn: (value: T) => T): void+ with<R> (fn: (value: T) => R): R+ subscribe (fn: (value: T) => void): () => void+}++export class Memo<T> implements ReadSignal<T> {+ readonly value: T+ get (): T+ peek (): T+ with<R> (fn: (value: T) => R): R+ subscribe (fn: (value: T) => void): () => void+ /** Stop tracking (a later read starts again). */+ dispose (): void+}++export function signal<T> (value: T, options?: { equals?: (a: T, b: T) => boolean }): Signal<T>+/** A lazily derived, cached value, recomputed when the signals it read change. */+export function memo<T> (fn: () => T, options?: { equals?: (a: T, b: T) => boolean }): Memo<T>+export const computed: typeof memo+/** Runs `fn` now and when what it read changes; `fn` may return a cleanup. Returns `dispose`. */+export function effect (fn: () => void | (() => void)): () => void+/** Several writes, one update. */+export function batch<R> (fn: () => R): R+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>diff --git a/bindings/node/index.js b/bindings/node/index.jsnew file mode 100644index 0000000..f0ca78b--- /dev/null+++ b/bindings/node/index.js@@ -0,0 +1,483 @@+// @blenderui/native: Blender's UI from JavaScript.+//+// A DOM-like retained tree (createElement, setAttribute, appendChild,+// addEventListener) rendered by BUI in native windows: HTML elements, CSS,+// Tailwind classes. BUI runs on its own thread; each window collects the+// tree changes of a tick and sends them in one call (an Int32Array of ops+// and a string table), so only what changed crosses into Rust. Events come+// back asynchronously.+//+// SPDX-License-Identifier: GPL-2.0-or-later+'use strict'++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)+const signals = require('./signals')+const { isSignal, effect } = 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 }+const EVENT_BITS = {+ click: 1, mousedown: 2, mouseup: 4, mousemove: 8, mouseenter: 16, mouseleave: 16,+ wheel: 32, keydown: 64, keyup: 128, change: 256, input: 512,+}+const BUTTONS = ['left', 'middle', 'right']++/** The event object handlers receive (a subset of the DOM's). */+class BuiEvent {+ constructor (raw, target) {+ this.type = raw.kind+ this.target = target+ this.currentTarget = target+ this.clientX = this.x = raw.x+ this.clientY = this.y = raw.y+ this.button = raw.button+ this.detail = raw.clickCount+ this.deltaY = -raw.delta * 100 // DOM: positive scrolls down+ this.key = raw.key ?? undefined+ this.char = raw.keyChar ?? undefined+ this.shiftKey = raw.shift+ this.ctrlKey = raw.ctrl+ this.altKey = raw.alt+ this.metaKey = false+ this.timeStamp = performance.now()+ this.defaultPrevented = false+ this.propagationStopped = false+ }++ preventDefault () { this.defaultPrevented = true }+ stopPropagation () { this.propagationStopped = true }+}++class Node {+ constructor (win, id) {+ this.ownerWindow = win+ this.id = id+ this.parentNode = null+ this._bindings = null+ this.childNodes = []+ }++ get firstChild () { return this.childNodes[0] ?? null }+ get lastChild () { return this.childNodes[this.childNodes.length - 1] ?? null }+ get nextSibling () {+ const p = this.parentNode+ return p ? p.childNodes[p.childNodes.indexOf(this) + 1] ?? null : null+ }++ appendChild (child) {+ child._detach()+ this.childNodes.push(child)+ child.parentNode = this+ this.ownerWindow._op(OP.APPEND, this.id, child.id)+ return child+ }++ insertBefore (child, before) {+ if (!before) return this.appendChild(child)+ child._detach()+ this.childNodes.splice(this.childNodes.indexOf(before), 0, child)+ child.parentNode = this+ this.ownerWindow._op(OP.INSERT, this.id, child.id, before.id)+ return child+ }++ removeChild (child) {+ const i = this.childNodes.indexOf(child)+ if (i >= 0) {+ this.childNodes.splice(i, 1)+ child.parentNode = null+ this.ownerWindow._op(OP.REMOVE, this.id, child.id)+ }+ return child+ }++ remove () { this.parentNode?.removeChild(this) }++ _detach () {+ if (this.parentNode) {+ const p = this.parentNode+ p.childNodes.splice(p.childNodes.indexOf(this), 1)+ this.parentNode = null // the APPEND/INSERT that follows moves 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) }))+ }++ _unbind (key) {+ const dispose = this._bindings?.get(key)+ if (dispose) {+ dispose()+ this._bindings.delete(key)+ }+ }++ _unbindAll () {+ if (this._bindings) {+ for (const dispose of this._bindings.values()) dispose()+ this._bindings = null+ }+ }++ /** Free this node and its subtree on the native side (after removing it). */+ destroy () {+ for (const c of this.childNodes) c.destroy()+ this.ownerWindow._free(this)+ }++ get textContent () { return this.childNodes.map(c => c.textContent).join('') }+}++class TextNode extends Node {+ constructor (win, id, text) {+ super(win, id)+ this._text = text+ }++ get nodeType () { return 3 }+ get data () { return this._text }+ /** A string, or a signal (the text then follows it). */+ set data (t) {+ if (isSignal(t)) return this._bind('data', t, (v) => this._setText(v))+ this._unbind('data')+ this._setText(t)+ }++ _setText (t) {+ t = t == null ? '' : String(t)+ if (t !== this._text) {+ this._text = t+ this.ownerWindow._op(OP.SET_TEXT, this.id, this.ownerWindow._s(t))+ }+ }++ get nodeValue () { return this._text }+ set nodeValue (t) { this.data = t }+ get textContent () { return this._text }+ set textContent (t) { this.data = t }+}++class Element extends Node {+ constructor (win, id, tag) {+ super(win, id)+ this.tagName = tag.toUpperCase()+ this.localName = tag+ this._attrs = new Map()+ this._listeners = new Map()+ this._bits = 0+ // form controls: the latest value from input / change events+ this.value = undefined+ this.checked = undefined+ }++ get nodeType () { return 1 }++ /** A value, or a signal: the attribute then follows it (null / false removes it). */+ setAttribute (name, value) {+ if (isSignal(value)) {+ return this._bind(name, value, (v) => {+ if (v == null || v === false) this._removeAttr(name)+ else this._setAttr(name, name === 'style' && typeof v === 'object' ? styleText(v) : v === true ? '' : v)+ })+ }+ this._unbind(name)+ this._setAttr(name, value)+ }++ _setAttr (name, value) {+ value = String(value)+ if (this._attrs.get(name) === value) return+ this._attrs.set(name, value)+ const w = this.ownerWindow+ w._op(OP.SET_ATTR, this.id, w._s(name), w._s(value))+ }++ getAttribute (name) { return this._attrs.get(name) ?? null }+ hasAttribute (name) { return this._attrs.has(name) }++ removeAttribute (name) {+ this._unbind(name)+ this._removeAttr(name)+ }++ _removeAttr (name) {+ if (this._attrs.delete(name)) this.ownerWindow._op(OP.REMOVE_ATTR, this.id, this.ownerWindow._s(name))+ }++ get className () { return this._attrs.get('class') ?? '' }+ set className (v) { this.setAttribute('class', v) }+ get style () { return this._attrs.get('style') ?? '' }+ /** A CSS declaration string, or an object (`{ backgroundColor: 'red', width: 40 }`). */+ set style (v) { this.setAttribute('style', typeof v === 'string' || isSignal(v) ? v : styleText(v)) }+ get textContent () { return super.textContent }+ set textContent (t) {+ for (const c of [...this.childNodes]) { this.removeChild(c); c.destroy() }+ if (t !== '' && t != null) this.appendChild(this.ownerWindow.createTextNode(isSignal(t) ? t : String(t)))+ }++ addEventListener (type, fn) {+ if (!(type in EVENT_BITS)) throw new Error(`blenderui: unsupported event "${type}"`)+ let set = this._listeners.get(type)+ if (!set) this._listeners.set(type, (set = new Set()))+ set.add(fn)+ this._listen()+ }++ removeEventListener (type, fn) {+ this._listeners.get(type)?.delete(fn)+ this._listen()+ }++ _listen () {+ let bits = 0+ for (const [type, set] of this._listeners) if (set.size) bits |= EVENT_BITS[type]+ if (bits !== this._bits) {+ this._bits = bits+ this.ownerWindow._op(OP.LISTEN, this.id, bits)+ }+ }++ _dispatch (raw) {+ if (raw.kind === 'input' || raw.kind === 'change') {+ this.value = raw.value+ this.checked = raw.checked+ this.valueAsNumber = raw.number+ }+ const set = this._listeners.get(raw.kind)+ if (!set || !set.size) return+ const e = new BuiEvent(raw, this)+ for (const fn of [...set]) {+ try { fn.call(this, e) } catch (err) { queueMicrotask(() => { throw err }) }+ }+ }++ /** Layout box `{ x, y, width, height }` in logical pixels (or null). */+ getBoundingClientRect () {+ this.ownerWindow.flush() // the UI thread must see the tree first+ return this.ownerWindow.app.native.bounds(this.ownerWindow.id, this.id)+ }+}++const UNITLESS = new Set(['opacity', 'z-index', 'flex', 'flex-grow', 'flex-shrink', 'order', 'font-weight',+ 'line-height', 'zoom', 'aspect-ratio', 'grid-row', 'grid-column', 'scale'])++/** `{ backgroundColor: 'red', width: 40 }` -> `background-color: red; width: 40px` */+function styleText (o) {+ let s = ''+ for (const k in o) {+ const v = o[k]+ if (v == null || v === false || v === '') continue+ const prop = k.startsWith('--') ? k : k.replace(/[A-Z]/g, m => '-' + m.toLowerCase())+ s += `${prop}: ${typeof v === 'number' && v !== 0 && !UNITLESS.has(prop) ? v + 'px' : v}; `+ }+ return s+}++class Window {+ constructor (app, id, options = {}) {+ this.app = app+ this.id = id+ this.closed = false+ this._next = 1+ this._nodes = new Map()+ this._ops = []+ this._strings = []+ this._stringIds = new Map()+ this._scheduled = false+ this._onClose = new Set()+ this._frameCallbacks = new Map()+ this._nextFrameId = 1+ this._framePending = false+ this._inFrame = false+ /** The root element: node 0. */+ this.body = new Element(this, 0, 'body')+ this._nodes.set(0, this.body)+ app.native.openWindow(id, {+ title: options.title, width: options.width, height: options.height,+ resizable: options.resizable, gpu: options.gpu,+ })+ }++ createElement (tag) {+ const id = this._next+++ const el = new Element(this, id, tag)+ this._nodes.set(id, el)+ this._op(OP.CREATE, id, this._s(tag))+ return el+ }++ /** A text node; `text` may be a signal (the text then follows it). */+ createTextNode (text) {+ const id = this._next+++ const bound = isSignal(text)+ const t = new TextNode(this, id, bound ? String(text.peek() ?? '') : String(text))+ this._nodes.set(id, t)+ this._op(OP.TEXT, id, this._s(t._text))+ if (bound) t.data = text+ return t+ }++ /** Changes are sent once per tick; `flush()` sends them now. */+ flush () {+ this._scheduled = false+ if (!this._ops.length || this.closed) return+ const ops = Int32Array.from(this._ops)+ const strings = this._strings+ this._ops = []+ this._strings = []+ this._stringIds.clear()+ // while animating, changes render on the next vsync (one rebuild per frame)+ this.app.native.commit(this.id, ops, strings, this._inFrame || this._framePending)+ }++ /**+ * Run `cb(timestamp)` before the next frame renders, paced by the display+ * (like the browser's). Changes made in it render in that frame.+ */+ requestAnimationFrame (cb) {+ const id = this._nextFrameId+++ this._frameCallbacks.set(id, cb)+ if (!this._framePending) {+ this._framePending = true+ this.flush()+ this.app.native.requestFrame(this.id)+ }+ return id+ }++ cancelAnimationFrame (id) { this._frameCallbacks.delete(id) }++ _frame () {+ this._framePending = false+ const cbs = [...this._frameCallbacks.values()]+ this._frameCallbacks.clear()+ this._inFrame = true+ const now = performance.now()+ try {+ for (const cb of cbs) {+ try { cb(now) } catch (err) { queueMicrotask(() => { throw err }) }+ }+ } finally {+ this._inFrame = false+ }+ this.flush()+ }++ /** Render and read the pixels: `{ width, height, data }` (RGBA). */+ async screenshot () {+ this.flush()+ return this.app.native.screenshot(this.id)+ }++ /** Click at (x, y) logical pixels (tests). */+ click (x, y) {+ this.flush()+ this.app.native.simulateClick(this.id, x, y)+ }++ close () {+ this.flush()+ this.app.native.closeWindow(this.id)+ this._closed()+ }++ on (event, fn) {+ if (event !== 'close') throw new Error(`blenderui: unsupported window event "${event}"`)+ this._onClose.add(fn)+ return this+ }++ _closed () {+ if (this.closed) return+ this.closed = true+ for (const fn of this._onClose) fn()+ this.app._windowClosed(this)+ }++ _op (...args) {+ for (const a of args) this._ops.push(a)+ if (!this._scheduled) {+ this._scheduled = true+ queueMicrotask(() => this.flush())+ }+ }++ _s (str) {+ let i = this._stringIds.get(str)+ if (i === undefined) {+ i = this._strings.push(str) - 1+ this._stringIds.set(str, i)+ }+ return i+ }++ _free (node) {+ node._unbindAll()+ if (node.id === 0) return+ this._nodes.delete(node.id)+ this._op(OP.FREE, node.id)+ }+}++class App {+ /**+ * @param {{ gpu?: boolean, slug?: boolean, headless?: boolean,+ * quitOnLastWindowClosed?: boolean }} [options]+ */+ constructor (options = {}) {+ this.windows = new Map()+ this._nextWindow = 1+ this.quitOnLastWindowClosed = options.quitOnLastWindowClosed ?? true+ this.native = new native.NativeApp(+ { gpu: options.gpu, slug: options.slug, headless: options.headless },+ raw => this._event(raw))+ }++ get headless () { return this.native.headless }++ /** Open a window: `{ title, width, height, resizable, gpu }`. */+ window (options) {+ const w = new Window(this, this._nextWindow++, options)+ this.windows.set(w.id, w)+ return w+ }++ /** GPU text: Slug (glyph outlines) or the glyph atlas. */+ setSlug (on) { this.native.setSlug(!!on) }++ /** 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()+ this.native.quit()+ }++ _event (raw) {+ const win = this.windows.get(raw.window)+ if (!win) return+ if (raw.kind === 'close') {+ win._closed()+ return+ }+ if (raw.kind === 'frame') {+ win._frame()+ return+ }+ win._nodes.get(raw.target)?._dispatch(raw)+ }++ _windowClosed (win) {+ this.windows.delete(win.id)+ if (this.quitOnLastWindowClosed && this.windows.size === 0) this.native.quit()+ }+}++module.exports = { App, Window, Element, TextNode, Node, BuiEvent, styleText, BUTTONS, native, ...signals }diff --git a/bindings/node/package.json b/bindings/node/package.jsonnew file mode 100644index 0000000..c12b795--- /dev/null+++ b/bindings/node/package.json@@ -0,0 +1,18 @@+{+ "name": "@blenderui/native",+ "version": "0.1.0",+ "description": "Blender's UI from JavaScript: native windows, HTML/CSS/Tailwind, driven from Node through napi-rs",+ "main": "index.js",+ "types": "index.d.ts",+ "files": ["index.js", "signals.js", "index.d.ts", "*.node", "README.md"],+ "scripts": {+ "build": "node scripts/build.js",+ "test": "node --test"+ },+ "engines": { "node": ">=18" },+ "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"]+}diff --git a/bindings/node/scripts/build.js b/bindings/node/scripts/build.jsnew file mode 100644index 0000000..acee233--- /dev/null+++ b/bindings/node/scripts/build.js@@ -0,0 +1,16 @@+// Builds the native addon (bindings/rust/blenderui-node) and copies it here+// as blenderui.<platform>-<arch>.node. `--debug` for a debug build.+'use strict'+const { execFileSync } = require('node:child_process')+const fs = require('node:fs')+const path = require('node:path')++const debug = process.argv.includes('--debug')+const rust = path.resolve(__dirname, '../../rust')+const args = ['build', '-p', 'blenderui-node', ...(debug ? [] : ['--release'])]+execFileSync('cargo', args, { cwd: rust, stdio: 'inherit' })+const lib = { win32: 'blenderui_node.dll', darwin: 'libblenderui_node.dylib' }[process.platform] ?? 'libblenderui_node.so'+const from = path.join(rust, 'target', debug ? 'debug' : 'release', lib)+const to = path.join(__dirname, '..', `blenderui.${process.platform}-${process.arch}.node`)+fs.copyFileSync(from, to)+console.log(`wrote ${path.relative(process.cwd(), to)}`)diff --git a/bindings/node/signals.js b/bindings/node/signals.jsnew file mode 100644index 0000000..c4a3233--- /dev/null+++ b/bindings/node/signals.js@@ -0,0 +1,474 @@+// Signals: BUI's hooks for JavaScript (the Rust crate's Signal / Memo /+// Effect, bindings/rust/blenderui/src/hooks.rs).+//+// const count = signal(0)+// const doubled = memo(() => count.value * 2) // recomputed when count changes+// effect(() => console.log(doubled.value)) // re-runs when doubled changes+// label.textContent = doubled // bound: only this text node updates+// count.value+++//+// Bound to an element (`el.setAttribute('class', sig)`, `el.style = sig`,+// `text.data = sig`, or a signal as a React prop or child), a write updates+// that one node: no component re-renders, no tree rebuilt, almost no garbage.+//+// Push-pull, glitch-free: a write marks direct readers dirty and indirect+// ones "check"; memos recompute lazily and stop propagation when their value+// is unchanged; effects run once per batch, after their sources settle. A+// memo nobody observes holds no subscriptions (it is garbage once dropped)+// and revalidates on read.+//+// Transitions (`startTransition`) mark the effects their writes trigger as+// low priority: they run after urgent work, in 5 ms slices.+//+// SPDX-License-Identifier: GPL-2.0-or-later+'use strict'++const CLEAN = 0, CHECK = 1, DIRTY = 2+const NONE = 0, URGENT = 1, DEFERRED = 2++let observer = null // the memo / effect running now (collects what it reads)+let owner = null // the effect running now (owns effects created inside it)+let batchDepth = 0+let flushing = false+let writes = 0 // bumped by every signal write: unobserved memos revalidate against it+const pending = []++let transition = null // the transition whose writes are being made now+const deferred = [] // effects and tasks of transitions, run in slices+let deferredAt = 0+let deferredScheduled = false+const waiting = new Set() // transitions waiting for the deferred queue++function track (source) {+ if (observer !== null && !observer._deps.has(source)) {+ observer._deps.add(source)+ if (observer._attached) source._addSub(observer)+ }+}++/** A value that re-runs what reads it when it changes (Rust's `Signal`). */+class Signal {+ constructor (value, options) {+ this._value = value+ this._subs = new Set()+ this._equals = options?.equals ?? Object.is+ }++ /** Read (and subscribe the running memo / effect). */+ get value () { track(this); return this._value }+ set value (v) { this.set(v) }+ get () { return this.value }+ /** Read without subscribing. */+ peek () { return this._value }++ set (v) {+ if (this._equals(this._value, v)) return+ this._value = v+ writes+++ for (const s of this._subs) s._mark(DIRTY)+ flush()+ }++ /** `count.update(n => n + 1)` */+ update (fn) { this.set(fn(this._value)) }+ /** Rust's `with`: `fn(value)`, subscribing. */+ with (fn) { return fn(this.value) }+ /** Call `fn(value)` now and on every change; returns the unsubscribe function. */+ subscribe (fn) { return effect(() => { fn(this.value) }) }+ toString () { return String(this.value) }+ toJSON () { return this.value }++ _addSub (s) { this._subs.add(s) }+ _removeSub (s) { this._subs.delete(s) }+}++class Computation {+ constructor (fn) {+ this._fn = fn+ this._deps = new Set()+ this._state = DIRTY+ this._attached = false+ }++ _unsubscribe () {+ if (this._attached) for (const d of this._deps) d._removeSub(this)+ this._deps.clear()+ }++ _track () {+ this._unsubscribe()+ const prev = observer+ observer = this+ try {+ return this._fn()+ } finally {+ observer = prev+ }+ }++ /** Bring up to date: re-run only if a source really changed. */+ _refresh () {+ if (this._state === CHECK) {+ for (const d of this._deps) {+ if (d instanceof Memo) {+ d._refresh()+ if (this._state === DIRTY) break+ }+ }+ }+ if (this._state === DIRTY) this._run()+ this._state = CLEAN+ }+}++/** A derived value, recomputed only when what it read changed (Rust's `Memo`). */+class Memo extends Computation {+ constructor (fn, options) {+ super(fn)+ this._subs = new Set()+ this._value = undefined+ this._init = false+ this._seen = -1 // `writes` when last known up to date while detached+ this._equals = options?.equals ?? Object.is+ }++ get value () {+ track(this)+ this._refresh()+ return this._value+ }++ get () { return this.value }+ peek () { this._refresh(); return this._value }+ with (fn) { return fn(this.value) }+ subscribe (fn) { return effect(() => { fn(this.value) }) }+ toString () { return String(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+ this._state = CLEAN+ }++ _run () {+ const v = this._track()+ if (!this._init || !this._equals(this._value, v)) {+ this._init = true+ this._value = v+ for (const s of this._subs) s._state = DIRTY+ }+ }++ _mark (state) {+ if (this._state >= state) return+ const was = this._state+ this._state = state+ if (was === CLEAN) for (const s of this._subs) s._mark(CHECK)+ }++ _addSub (s) {+ this._subs.add(s)+ if (!this._attached) {+ // first observer: subscribe to the sources (stale if anything was written since)+ this._attached = true+ if (this._seen !== writes) this._state = DIRTY+ for (const d of this._deps) d._addSub(this)+ }+ }++ _removeSub (s) {+ this._subs.delete(s)+ if (this._subs.size === 0 && this._attached) {+ // last observer gone: let go of the sources, so this memo can be collected+ for (const d of this._deps) d._removeSub(this)+ this._attached = false+ this._seen = this._state === CLEAN ? writes : -1+ }+ }+}++/** Runs `fn` now and again when what it read changes (Rust's `Effect`). */+class Effect extends Computation {+ constructor (fn) {+ super(fn)+ this._attached = true+ this._cleanup = undefined+ this._children = null+ this._disposed = false+ this._queued = NONE+ if (owner !== null) (owner._children ??= []).push(this)+ this._run()+ this._state = CLEAN+ }++ _run () {+ this._clean()+ const prevOwner = owner+ owner = this+ try {+ const r = this._track()+ if (typeof r === 'function') this._cleanup = r+ } finally {+ owner = prevOwner+ }+ }++ _clean () {+ if (this._children !== null) {+ for (const c of this._children) c.dispose()+ this._children = null+ }+ if (this._cleanup !== undefined) {+ const c = this._cleanup+ this._cleanup = undefined+ untrack(c)+ }+ }++ _mark (state) {+ if (state > this._state) this._state = state+ if (transition === null) {+ if (this._queued !== URGENT) {+ this._queued = URGENT+ pending.push(this)+ }+ } else if (this._queued === NONE) {+ this._queued = DEFERRED+ defer(this)+ }+ }++ dispose () {+ if (this._disposed) return+ this._disposed = true+ this._unsubscribe()+ this._clean()+ }+}++function runEffect (e) {+ e._queued = NONE+ if (e._disposed) return+ try {+ e._refresh()+ } catch (err) {+ e._state = CLEAN+ reportError(err)+ }+}++function flush () {+ if (batchDepth > 0 || flushing) return+ flushing = true+ try {+ for (let i = 0; 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 {+ pending.length = 0+ flushing = false+ }+}++function reportError (err) {+ // like a browser: one effect's error doesn't stop the others+ queueMicrotask(() => { throw err })+}++// ---- transitions -----------------------------------------------------------++class Transition {+ constructor () {+ this._open = 1 // the synchronous part+ this._done = []+ this._queued = false+ }++ _hold () { this._open++ }+ _release () {+ if (--this._open === 0) for (const f of this._done.splice(0)) f()+ }+}++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)+ if (transition !== null && !transition._queued) {+ transition._queued = true+ transition._hold()+ waiting.add(transition)+ }+ if (!deferredScheduled) {+ deferredScheduled = true+ macrotask(runDeferred)+ }+}++function runDeferred () {+ deferredScheduled = false+ const end = now() + 5+ while (deferredAt < deferred.length) {+ const item = deferred[deferredAt++]+ const t = item._transition+ const prev = transition+ transition = t ?? IDLE+ batchDepth+++ try {+ if (typeof item === 'function') {+ try { item() } catch (err) { reportError(err) }+ } else if (item._queued === DEFERRED) {+ runEffect(item)+ }+ } finally {+ batchDepth--+ transition = prev+ }+ flush()+ if (now() >= end && deferredAt < deferred.length) {+ // yield to urgent work (input, frames), then carry on+ deferredScheduled = true+ macrotask(runDeferred)+ return+ }+ }+ deferred.length = 0+ deferredAt = 0+ const done = [...waiting]+ waiting.clear()+ for (const t of done) {+ t._queued = false+ t._release()+ }+}++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.+ */+function startTransition (fn) {+ const t = new Transition()+ const done = new Promise((resolve) => t._done.push(resolve))+ const prev = transition+ transition = t+ batchDepth+++ let result+ try {+ result = fn()+ } finally {+ batchDepth--+ transition = prev+ flush()+ }+ if (result && typeof result.then === 'function') {+ t._hold()+ result.then(() => t._release(), (err) => { reportError(err); t._release() })+ }+ t._release()+ return done+}++/** Inside a transition: call `cb` when it completes. False outside one. */+function onTransitionDone (cb) {+ if (transition === null || transition === IDLE) return false+ transition._done.push(cb) // the transition is open while its body runs+ return true+}++/** Run `fn` at transition priority, later (deferred values). */+function scheduleDeferred (fn) {+ fn._transition = IDLE+ const prev = transition+ transition = IDLE+ try {+ defer(fn)+ } finally {+ transition = prev+ }+}++/** Run `fn` with urgent priority, even inside a transition. */+function urgent (fn) {+ const prev = transition+ transition = null+ try {+ return fn()+ } finally {+ transition = prev+ }+}++const inTransition = () => transition !== null++// ---- API -------------------------------------------------------------------++/** `signal(0)`: a read-write signal (`.value`, `.set`, `.update`). */+function signal (value, options) { return new Signal(value, options) }++/** `memo(() => a.value + b.value)`: a lazily derived, cached signal. */+function memo (fn, options) { return new Memo(fn, options) }++/** `effect(() => ...)`: runs now and on changes; `fn` may return a cleanup. Returns `dispose`. */+function effect (fn) {+ const e = new Effect(fn)+ return () => e.dispose()+}++/** Run `fn`, deferring effects until it returns (several writes, one update). */+function batch (fn) {+ batchDepth+++ try {+ return fn()+ } finally {+ batchDepth--+ flush()+ }+}++/** Run `fn` without subscribing to what it reads. */+function untrack (fn) {+ const prev = observer+ observer = null+ try {+ return fn()+ } finally {+ observer = prev+ }+}++/** Leptos / Solid style: `const [count, setCount] = createSignal(0)`. */+function createSignal (value, options) {+ const s = new Signal(value, options)+ return [() => s.value, (v) => s.set(typeof v === 'function' ? v(s._value) : v)]+}++const isSignal = (x) => x instanceof Signal || x instanceof Memo++module.exports = {+ Signal,+ Memo,+ Effect,+ signal,+ memo,+ computed: memo,+ effect,+ batch,+ untrack,+ createSignal,+ isSignal,+ startTransition,+ urgent,+ inTransition,+ onTransitionDone,+ scheduleDeferred,+}diff --git a/bindings/node/test/native.test.js b/bindings/node/test/native.test.jsnew file mode 100644index 0000000..9bb7c65--- /dev/null+++ b/bindings/node/test/native.test.js@@ -0,0 +1,91 @@+'use strict'+const test = require('node:test')+const assert = require('node:assert')+const { App } = require('..')++test('tree, styles, Tailwind, events, screenshot (headless)', async (t) => {+ const app = new App({ headless: true })+ t.after(() => app.quit())+ const win = app.window({ width: 320, height: 200 })+ win.body.style = 'margin: 0; background: #000'+ const box = win.createElement('div')+ box.className = 'w-[100px] h-[40px] bg-[#ff0000]'+ win.body.appendChild(box)+ const btn = win.createElement('div')+ btn.style = { width: 80, height: 30, backgroundColor: '#0000ff' }+ const label = win.createTextNode('0')+ btn.appendChild(label)+ win.body.appendChild(btn)+ let clicks = 0+ const clicked = new Promise(resolve => btn.addEventListener('click', e => {+ clicks+++ label.data = String(clicks)+ btn.style = { width: 80, height: 30, backgroundColor: '#00ff00' }+ resolve(e)+ }))++ const r = await btn.getBoundingClientRect()+ assert.deepStrictEqual([r.x, r.y, r.width, r.height], [0, 40, 80, 30])+ let shot = await win.screenshot()+ const at = (s, x, y) => { const i = (y * s.width + x) * 4; return [...s.data.subarray(i, i + 3)] }+ assert.deepStrictEqual(at(shot, 10, 10), [255, 0, 0], 'Tailwind arbitrary class')+ assert.deepStrictEqual(at(shot, 70, 60), [0, 0, 255], 'style object')++ win.click(40, 55)+ const e = await clicked+ assert.strictEqual(e.type, 'click')+ assert.strictEqual(e.target, btn)+ shot = await win.screenshot()+ assert.deepStrictEqual(at(shot, 70, 60), [0, 255, 0], 'handler re-styled it')+ assert.strictEqual(btn.textContent, '1')+})++test('requestAnimationFrame runs callbacks per frame (headless)', async (t) => {+ const app = new App({ headless: true })+ t.after(() => app.quit())+ const win = app.window({ width: 100, height: 100 })+ const box = win.createElement('div')+ win.body.appendChild(box)+ let frames = 0+ await new Promise(resolve => {+ const step = () => {+ box.style = { width: ++frames, height: 10 }+ if (frames < 5) win.requestAnimationFrame(step)+ else resolve()+ }+ win.requestAnimationFrame(step)+ })+ const r = await box.getBoundingClientRect()+ assert.strictEqual(frames, 5)+ assert.strictEqual(r.width, 5, 'the last frame\'s change rendered')+})++test('signals bound to attributes and text update only their node (headless)', async (t) => {+ const { App, signal, memo } = require('..')+ const app = new App({ headless: true })+ t.after(() => app.quit())+ const win = app.window({ width: 100, height: 60 })+ win.body.style = 'margin: 0; background: #000'+ const color = signal('#0000ff')+ const n = signal(1)+ const box = win.createElement('div')+ box.style = memo(() => ({ width: 40, height: 20, backgroundColor: color.value }))+ const label = win.createElement('span')+ label.textContent = memo(() => `n = ${n.value}`)+ win.body.appendChild(box)+ win.body.appendChild(label)+ const tick = () => new Promise(r => setTimeout(r, 30))+ const at = (s, x, y) => { const i = (y * s.width + x) * 4; return [...s.data.subarray(i, i + 3)] }+ await tick()+ assert.deepStrictEqual(at(await win.screenshot(), 10, 10), [0, 0, 255])+ assert.strictEqual(label.textContent, 'n = 1')+ color.value = '#00ff00'+ n.value = 2+ assert.strictEqual(label.textContent, 'n = 2')+ await tick()+ assert.deepStrictEqual(at(await win.screenshot(), 10, 10), [0, 255, 0])+ box.style = 'width: 40px; height: 20px; background: #ff0000' // a plain value unbinds+ color.value = '#ffffff'+ await tick()+ assert.deepStrictEqual(at(await win.screenshot(), 10, 10), [255, 0, 0])+})diff --git a/bindings/node/test/signals.test.js b/bindings/node/test/signals.test.jsnew file mode 100644index 0000000..6dbf245--- /dev/null+++ b/bindings/node/test/signals.test.js@@ -0,0 +1,60 @@+'use strict'+const test = require('node:test')+const assert = require('node:assert')+const { signal, memo, effect, batch, untrack, createSignal } = require('../signals')++test('signals: memo is lazy, cached and glitch-free', () => {+ const a = signal(1)+ const b = signal(2)+ let runs = 0+ const sum = memo(() => { runs++; return a.value + b.value })+ assert.strictEqual(runs, 0, 'lazy')+ assert.strictEqual(sum.value, 3)+ assert.strictEqual(sum.value, 3)+ assert.strictEqual(runs, 1, 'cached')+ const seen = []+ const parity = memo(() => sum.value % 2)+ const stop = effect(() => { seen.push(`${sum.value}:${parity.value}`) })+ batch(() => { a.value = 2; b.value = 3 })+ assert.deepStrictEqual(seen, ['3:1', '5:1'], 'one run per batch, never an inconsistent pair')+ a.value = 4 // sum 7, parity unchanged+ assert.deepStrictEqual(seen, ['3:1', '5:1', '7:1'])+ stop()+ a.value = 100+ assert.strictEqual(seen.length, 3, 'disposed effects stay quiet')+})++test('signals: equality cut-off, cleanups, nested effects, untrack', () => {+ const n = signal(1)+ const even = memo(() => n.value % 2 === 0)+ let runs = 0+ effect(() => { even.value; runs++ })+ n.value = 3 // even is still false: the effect doesn't re-run+ assert.strictEqual(runs, 1)+ n.value = 4+ assert.strictEqual(runs, 2)++ const log = []+ const outer = signal('x')+ const inner = signal(0)+ const stop = effect(() => {+ const o = outer.value+ effect(() => { log.push(`${o}${inner.value}`) })+ return () => log.push(`cleanup ${o}`)+ })+ inner.value = 1+ outer.value = 'y' // disposes the old inner effect+ inner.value = 2+ assert.deepStrictEqual(log, ['x0', 'x1', 'cleanup x', 'y1', 'y2'])+ stop()++ let reads = 0+ const s = signal(0)+ effect(() => { untrack(() => s.value); reads++ })+ s.value = 1+ assert.strictEqual(reads, 1, 'untracked reads do not subscribe')++ const [count, setCount] = createSignal(1)+ setCount(c => c + 1)+ assert.strictEqual(count(), 2)+})diff --git a/bindings/react/.gitignore b/bindings/react/.gitignorenew file mode 100644index 0000000..4c8908a--- /dev/null+++ b/bindings/react/.gitignore@@ -0,0 +1,2 @@+*.node+node_modules/diff --git a/bindings/react/README.md b/bindings/react/README.mdnew file mode 100644index 0000000..6f6900d--- /dev/null+++ b/bindings/react/README.md@@ -0,0 +1,31 @@+# @blenderui/react++A React 19 renderer for BUI: JSX rendered with Blender's UI in native+windows, over [`@blenderui/native`](../node).++```jsx+import { useState } from 'react'+import { render } from '@blenderui/react'++function Counter () {+ const [n, setN] = useState(0)+ return <button className="m-4" onClick={() => setN(n + 1)}>Clicked {n} times</button>+}++render(<Counter />, { title: 'Counter', width: 320, height: 160 })+```++BUI's hooks work alongside React's. A signal passed as a prop or child+updates that node alone, without re-rendering the component:++```jsx+import { render, useSignal } from '@blenderui/react'++function Counter () {+ const n = useSignal(0) // also useComputed, useSignalEffect, useSignalValue+ return <button className="m-4" onClick={() => n.value++}>Clicked {n} times</button>+}+```++Guide and benchmarks: [docs/javascript.md](../../docs/javascript.md).+License: GPL-2.0-or-later.diff --git a/bindings/react/examples/counter.js b/bindings/react/examples/counter.jsnew file mode 100644index 0000000..fcc19b7--- /dev/null+++ b/bindings/react/examples/counter.js@@ -0,0 +1,23 @@+// 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+'use strict'+const React = require('react')+const { render } = require('..')+const h = React.createElement++function Counter () {+ const [count, setCount] = React.useState(0)+ const [name, setName] = React.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('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}!`))+}++const { app, window } = render(h(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/examples/counter.jsx b/bindings/react/examples/counter.jsxnew file mode 100644index 0000000..d6bd71b--- /dev/null+++ b/bindings/react/examples/counter.jsx@@ -0,0 +1,18 @@+// 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'++function Counter () {+ const [count, setCount] = useState(0)+ return (+ <main className="p-6 flex flex-col gap-3">+ <h1 className="text-xl font-bold">BUI + React</h1>+ <div className="flex items-center gap-3">+ <span>Clicks: {count}</span>+ <button onClick={() => setCount(c => c + 1)}>Add one</button>+ </div>+ </main>+ )+}++render(<Counter />, { title: 'BUI + React', width: 420, height: 220 })diff --git a/bindings/react/hooks.js b/bindings/react/hooks.jsnew file mode 100644index 0000000..2bda63d--- /dev/null+++ b/bindings/react/hooks.js@@ -0,0 +1,289 @@+// 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.+//+// 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.+//+// 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++/** React hooks without a twin, 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)',+}++// The latest value, for callbacks that outlive the render that made them.+function useLatest (value) {+ const ref = React.useRef(value)+ ref.current = value+ return ref+}++/** A component-owned signal, created once (lazily when `init` is a function). */+function useOnce (create) {+ return React.useState(create)[0]+}++/** 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) {+ 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) {+ 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))+}++// ---- 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) {+ const latest = useLatest(fn)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ return React.useMemo(() => memo(() => latest.current()), deps)+}++/** Rust's `Memo::new`: `useSignalMemo` with `deps = []` by default. */+function useComputed (fn, deps = []) {+ return useSignalMemo(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) {+ // eslint-disable-next-line react-hooks/exhaustive-deps+ return React.useCallback((...args) => batch(() => untrack(() => fn(...args))), deps)+}++// ---- effects -----------------------------------------------------------------++function effectHook (reactHook) {+ return function (fn, deps) {+ const latest = useLatest(fn)+ // React's timing and deps; in between, re-runs when the signals it read change+ reactHook(() => effect(() => latest.current()), deps)+ }+}++/** `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)++// ---- external stores ---------------------------------------------------------++/** `useSyncExternalStore` twin: a signal following the store, without re-renders. */+function useSignalSyncExternalStore (subscribe, getSnapshot) {+ const s = useOnce(() => signal(getSnapshot()))+ const latest = useLatest(getSnapshot)+ React.useLayoutEffect(() => {+ const check = () => s.set(latest.current())+ check() // changed between render and subscribe+ return subscribe(check)+ }, [subscribe, s])+ React.useLayoutEffect(() => { s.set(latest.current()) }) // a new getSnapshot+ return s+}++/** Re-render this component when `source` changes; returns its value. */+function useSignalValue (source) {+ const subscribe = React.useCallback((onChange) => {+ let first = true+ return effect(() => {+ source.value // subscribe+ if (first) first = false+ else onChange()+ })+ }, [source])+ return React.useSyncExternalStore(subscribe, () => source.peek())+}++// ---- transitions and actions -------------------------------------------------++// Run `action` as a BUI transition and a React transition at once: signal+// writes defer their effects, React state updates render at transition priority.+function transition (action) {+ return S.startTransition(() => {+ let result+ React.startTransition(() => {+ result = action()+ return result+ })+ return 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 () {+ const isPending = useOnce(() => signal(false))+ const start = React.useCallback((action) => {+ isPending._count = (isPending._count ?? 0) + 1+ S.urgent(() => isPending.set(true))+ transition(action).then(() => {+ if (--isPending._count === 0) S.urgent(() => isPending.set(false))+ })+ }, [isPending])+ 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) {+ const read = () => (isSignal(value) ? value.peek() : value)+ const out = useOnce(() => signal(initialValue !== undefined ? initialValue : read()))+ const latest = useLatest(value)+ React.useEffect(() => {+ let scheduled = false+ const push = () => {+ if (scheduled) return+ scheduled = true+ S.scheduleDeferred(() => {+ scheduled = false+ const v = latest.current+ out.set(isSignal(v) ? v.peek() : v)+ })+ }+ if (isSignal(value)) return effect(() => { value.value; push() })+ push()+ }, [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) {+ 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 runNext = React.useCallback(() => {+ const payload = queue.items.shift()+ queue.running = true+ let result+ transition(() => {+ result = latest.current(state.peek(), payload)+ return result+ })+ Promise.resolve(result).then((next) => {+ const more = queue.items.length > 0+ batch(() => {+ state.set(next)+ if (!more) isPending.set(false)+ })+ if (more) runNext()+ else queue.running = false+ }, (err) => {+ queue.items.length = 0+ queue.running = false+ isPending.set(false)+ setError(() => { throw err })+ })+ }, [state, isPending, queue])++ const dispatch = React.useCallback((payload) => {+ queue.items.push(payload)+ if (!queue.running) {+ S.urgent(() => isPending.set(true))+ runNext()+ }+ }, [queue, isPending, runNext])++ 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) {+ const updates = useOnce(() => signal([]))+ const latestReducer = useLatest(reducer)+ const out = React.useMemo(() => memo(() => {+ let v = isSignal(passthrough) ? passthrough.value : passthrough+ for (const u of updates.value) v = latestReducer.current ? latestReducer.current(v, u.action) : u.action+ return v+ }), [passthrough, updates])+ const add = React.useCallback((action) => {+ const entry = { action }+ const remove = () => S.urgent(() => updates.set(updates.peek().filter((e) => e !== entry)))+ S.urgent(() => updates.set([...updates.peek(), entry]))+ if (!S.onTransitionDone(remove)) {+ console.error('An optimistic state update occurred outside a transition or action. ' ++ 'To fix, move the update to an action, or wrap it in startTransition.')+ setTimeout(remove, 0)+ }+ }, [updates])+ return [out, add]+}++module.exports = {+ NO_TWIN,+ SignalRef,+ useSignal,+ useComputed,+ useSignalValue,+ useSignalState,+ useSignalReducer,+ useSignalRef,+ useSignalMemo,+ useSignalCallback,+ useSignalEffect,+ useSignalLayoutEffect,+ useSignalInsertionEffect,+ useSignalSyncExternalStore,+ useSignalTransition,+ useSignalDeferredValue,+ useSignalActionState,+ useSignalOptimistic,+}diff --git a/bindings/react/index.d.ts b/bindings/react/index.d.tsnew file mode 100644index 0000000..4828154--- /dev/null+++ b/bindings/react/index.d.ts@@ -0,0 +1,36 @@+// Types for @blenderui/react.+import type { ReactNode } from 'react'+import type { App, Window, AppOptions, WindowOptions } from '@blenderui/native'++export interface Root {+ render (element: ReactNode): void+ unmount (): void+}++export function createRoot (window: Window): Root++export function render (element: ReactNode, options?: WindowOptions & AppOptions & { app?: App }):+ { app: App, window: Window, root: Root }++export function act (fn: () => void): void++// 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'++/** A signal owned by this component (Rust's `use_signal`). */+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. */+export function useSignalValue<T> (source: ReadSignal<T>): T++// 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 {+ buiSignal: ReadSignal<unknown>+ }+}diff --git a/bindings/react/index.js b/bindings/react/index.jsnew file mode 100644index 0000000..af5b0d4--- /dev/null+++ b/bindings/react/index.js@@ -0,0 +1,258 @@+// @blenderui/react: a React renderer for BUI (react-reconciler 0.31 / React 19).+//+// const { render } = require('@blenderui/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+// retained tree, which sends only the changes of each commit to the native+// UI thread. Events arrive as BUI events (onClick, onChange, onKeyDown ...).+//+// SPDX-License-Identifier: GPL-2.0-or-later+'use strict'++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++// A signal rendered as a child (`<span>{count}</span>`) becomes this host+// type: a text node bound to the signal, updated without re-rendering.+const SIGNAL_TEXT = '#bui-signal-text'+for (const C of [Signal, Memo]) {+ Object.defineProperties(C.prototype, {+ $$typeof: { value: Symbol.for('react.transitional.element'), configurable: true },+ type: { value: SIGNAL_TEXT, configurable: true },+ key: { value: null, configurable: true },+ ref: { value: null, configurable: true },+ _owner: { value: null, configurable: true },+ // React (dev) marks list children validated here: a fresh object each time+ _store: { get () { return { validated: 1 } }, configurable: true },+ props: { get () { return (this._reactProps ??= { signal: this }) }, configurable: true },+ })+}++// React prop -> BUI event; onChange is per keystroke on text fields, as in React DOM.+const EVENTS = {+ onClick: 'click', onMouseDown: 'mousedown', onMouseUp: 'mouseup', onMouseMove: 'mousemove',+ onMouseEnter: 'mouseenter', onMouseLeave: 'mouseleave', onWheel: 'wheel',+ onKeyDown: 'keydown', onKeyUp: 'keyup', onInput: 'input', onChange: 'change',+}+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'])++function eventName (el, prop) {+ if (prop === 'onChange') {+ // text fields report every edit as `input`; checkboxes, selects: `change`+ const type = el.getAttribute('type')+ if (TEXT_INPUTS.has(el.localName) || (el.localName === 'input' &&+ !['checkbox', 'radio', 'range', 'color', 'file'].includes(type))) return 'input'+ }+ return EVENTS[prop]+}++function isText (children) {+ return typeof children === 'string' || typeof children === 'number' || typeof children === 'bigint'+}++/** Apply the difference between two prop objects to an element. */+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)+ }+ }+ for (const k in next) {+ const v = next[k]+ if (SKIP.has(k) || prev[k] === v) continue+ if (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]+ } else if (k === 'style') {+ if (v == null) el.removeAttribute('style')+ else el.style = v // a string, an object or a signal of either+ } else if (v == null || v === false) {+ el.removeAttribute(ATTR_ALIASES[k] ?? k)+ } else if (isSignal(v)) {+ el.setAttribute(ATTR_ALIASES[k] ?? k, v) // bound: updates without a re-render+ } else {+ 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 = ''+}++let updatePriority = NoEventPriority+const ROOT_CONTEXT = {}++const host = {+ rendererPackageName: '@blenderui/react',+ rendererVersion: '0.1.0',+ supportsMutation: true,+ supportsPersistence: false,+ supportsHydration: false,+ supportsMicrotasks: true,+ isPrimaryRenderer: true,+ warnsIfNotActing: false,+ noTimeout: -1,+ scheduleTimeout: setTimeout,+ cancelTimeout: clearTimeout,+ scheduleMicrotask: queueMicrotask,++ getRootHostContext: () => ROOT_CONTEXT, // must not be null (React checks)+ getChildHostContext: (parent) => parent,+ getPublicInstance: (instance) => instance,+ prepareForCommit: () => null,+ resetAfterCommit (container) { container.window.flush() }, // one native call per commit+ preparePortalMount () {},++ createInstance (type, props, container) {+ if (type === SIGNAL_TEXT) return container.window.createTextNode(props.signal)+ const el = container.window.createElement(type)+ el._react = {}+ applyProps(el, {}, props)+ return el+ },+ createTextInstance: (text, container) => container.window.createTextNode(text),+ appendInitialChild: (parent, child) => parent.appendChild(child),+ finalizeInitialChildren: () => false,+ shouldSetTextContent: (type, props) => isText(props.children),++ appendChild: (parent, child) => parent.appendChild(child),+ 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),+ clearContainer (container) {+ for (const c of [...container.window.body.childNodes]) container.window.body.removeChild(c)+ },+ detachDeletedInstance: (node) => node.ownerWindow._free(node),++ commitUpdate (el, type, prev, next) {+ if (type === SIGNAL_TEXT) {+ if (prev.signal !== next.signal) el.data = next.signal+ } else {+ applyProps(el, prev, next)+ }+ },+ commitTextUpdate: (text, prev, next) => { text.data = next },+ commitMount () {},+ resetTextContent: (el) => { el.textContent = '' },+ hideInstance (el) {+ if (el instanceof TextNode) el.data = '' // a signal's text: unbound while hidden+ else el.setAttribute('hidden', '')+ },+ unhideInstance (el, props) {+ if (el instanceof TextNode) el.data = props.signal+ else if (!props.hidden) el.removeAttribute('hidden')+ },+ hideTextInstance: (text) => { text._hidden = text.data; text.data = '' },+ unhideTextInstance: (text, value) => { text.data = value },++ setCurrentUpdatePriority: (p) => { updatePriority = p },+ getCurrentUpdatePriority: () => updatePriority,+ resolveUpdatePriority: () => updatePriority || DefaultEventPriority,+ resolveEventType: () => null,+ resolveEventTimeStamp: () => -1.1,+ shouldAttemptEagerTransition: () => false,+ trackSchedulerEvent () {},+ requestPostPaintCallback () {},+ maySuspendCommit: () => false,+ preloadInstance: () => true,+ startSuspendingCommit () {},+ suspendInstance () {},+ waitForCommitToBeReady: () => null,+ NotPendingTransition: null,+ HostTransitionContext: React.createContext(null),+ resetFormInstance () {},+ getInstanceFromNode: () => null,+ getInstanceFromScope: () => null,+ beforeActiveInstanceBlur () {},+ afterActiveInstanceBlur () {},+ prepareScopeUpdate () {},+ bindToConsole: (method, args) => Function.prototype.bind.apply(console[method], [console, ...args]),+}++const reconciler = Reconciler(host)++// Events: run handlers as discrete updates (React DOM does the same), so a+// click's state change commits right away.+const nativeDispatch = native.Element.prototype._dispatch+native.Element.prototype._dispatch = function (raw) {+ const prev = updatePriority+ updatePriority = DiscreteEventPriority+ try {+ nativeDispatch.call(this, raw)+ } finally {+ updatePriority = prev+ }+}++function report (kind) {+ return (err) => console.error(`@blenderui/react: ${kind}`, err)+}++/** A React root rendering into `window`'s body. */+function createRoot (window) {+ const container = { window }+ const root = reconciler.createContainer(container, ConcurrentRoot, null, false, null, 'bui',+ report('uncaught error'), report('caught error'), report('recoverable error'), null)+ return {+ render (element) { reconciler.updateContainer(element, root, null, null) },+ unmount () { reconciler.updateContainer(null, root, null, null) },+ }+}++/**+ * Open a window and render `element` into it.+ * @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> }}+ */+function render (element, options = {}) {+ const app = options.app ?? new App({ gpu: options.gpu, slug: options.slug, headless: options.headless })+ const window = app.window(options)+ const root = createRoot(window)+ root.render(element)+ return { app, window, root }+}++/** Run `fn` and flush React's work synchronously (tests). */+function act (fn) {+ reconciler.flushSyncFromReconciler?.(fn) ?? reconciler.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).+const reactHooks = {}+for (const k of Object.keys(React)) if (/^use([A-Z]|$)/.test(k)) reactHooks[k] = React[k]++module.exports = {+ ...reactHooks,+ ...require('./hooks'),+ render,+ createRoot,+ act,+ reconciler,+ signal,+ memo,+ computed: memo,+ effect,+ batch: native.batch,+ untrack: native.untrack,+ createSignal: native.createSignal,+ startTransition: native.startTransition,+}diff --git a/bindings/react/package-lock.json b/bindings/react/package-lock.jsonnew file mode 100644index 0000000..d0be4ce--- /dev/null+++ b/bindings/react/package-lock.json@@ -0,0 +1,74 @@+{+ "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.jsonnew file mode 100644index 0000000..05d5192--- /dev/null+++ b/bindings/react/package.json@@ -0,0 +1,19 @@+{+ "name": "@blenderui/react",+ "version": "0.1.0",+ "description": "React renderer for BUI: Blender's UI in native windows, from JSX",+ "main": "index.js",+ "types": "index.d.ts",+ "files": ["index.js", "hooks.js", "index.d.ts", "README.md"],+ "scripts": { "test": "node --test" },+ "engines": { "node": ">=18" },+ "dependencies": {+ "@blenderui/native": "file:../node",+ "react-reconciler": "0.31.0"+ },+ "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"]+}diff --git a/bindings/react/test/react.test.js b/bindings/react/test/react.test.jsnew file mode 100644index 0000000..76abae8--- /dev/null+++ b/bindings/react/test/react.test.js@@ -0,0 +1,79 @@+'use strict'+const test = require('node:test')+const assert = require('node:assert')+const React = require('react')+const { render } = require('..')+const h = React.createElement++function Counter () {+ const [n, setN] = React.useState(0)+ return h('div', { className: 'flex flex-col gap-2', style: { margin: 0 } },+ h('div', {+ id: 'btn',+ style: { width: 80, height: 30, backgroundColor: n ? '#00ff00' : '#0000ff' },+ onClick: () => setN(n + 1),+ }, `count ${n}`),+ n > 0 && h('div', { className: 'w-[50px] h-[10px] bg-[#ff0000]' }))+}++const tick = (ms = 30) => new Promise(r => setTimeout(r, ms))+const at = (s, x, y) => { const i = (y * s.width + x) * 4; return [...s.data.subarray(i, i + 3)] }++test('React: render, state, events, conditional children (headless)', async (t) => {+ const { app, window } = render(h(Counter), { headless: true, width: 200, height: 120 })+ t.after(() => app.quit())+ window.body.style = 'margin: 0; background: #000'+ await tick()+ let shot = await window.screenshot()+ assert.deepStrictEqual(at(shot, 70, 20), [0, 0, 255])+ const btn = [...window._nodes.values()].find(n => n.getAttribute?.('id') === 'btn')+ assert.strictEqual(btn.textContent, 'count 0')+ window.click(10, 10)+ await tick()+ assert.strictEqual(btn.textContent, 'count 1', 'state update re-rendered the text')+ shot = await window.screenshot()+ assert.deepStrictEqual(at(shot, 70, 20), [0, 255, 0], 'style prop updated')+ 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) => {+ const { useSignal, useComputed, useSignalValue, signal } = require('..')+ const external = signal(0)+ let renders = 0+ let sig+ function Panel () {+ renders+++ const n = useSignal(0)+ sig = n+ const color = useComputed(() => (n.value % 2 ? '#00ff00' : '#0000ff'))+ const style = useComputed(() => ({ width: 80, height: 30, backgroundColor: color.value }))+ return h('div', { style: { margin: 0 } },+ h('div', { id: 'box', style, onClick: () => n.update(v => v + 1) }, 'count ', n),+ h(Watcher))+ }+ let watcherRenders = 0+ function Watcher () {+ watcherRenders+++ return h('span', null, `ext ${useSignalValue(external)}`)+ }+ const { app, window } = render(h(Panel), { headless: true, width: 200, height: 120 })+ t.after(() => app.quit())+ window.body.style = 'margin: 0; background: #000'+ await tick()+ const box = [...window._nodes.values()].find(n => n.getAttribute?.('id') === 'box')+ assert.strictEqual(box.textContent, 'count 0')+ assert.deepStrictEqual(at(await window.screenshot(), 70, 20), [0, 0, 255])+ window.click(10, 10)+ await tick()+ assert.strictEqual(box.textContent, 'count 1')+ assert.deepStrictEqual(at(await window.screenshot(), 70, 20), [0, 255, 0])+ sig.value = 2+ await tick()+ assert.strictEqual(box.textContent, 'count 2')+ assert.strictEqual(renders, 1, 'Panel rendered once: signal writes went straight to the nodes')+ external.value = 5+ await tick()+ assert.strictEqual(watcherRenders, 2, 'useSignalValue re-renders its component')+ const span = [...window._nodes.values()].find(n => n.textContent === 'ext 5' && n.localName === 'span')+ assert.ok(span)+})diff --git a/bindings/rust/Cargo.lock b/bindings/rust/Cargo.lockindex a4f129c..86307c8 100644--- a/bindings/rust/Cargo.lock+++ b/bindings/rust/Cargo.lock@@ -8,12 +8,27 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]+[[package]]name = "bitflags"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"+[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+[[package]]name = "blenderui"version = "0.1.0"@@ -34,6 +49,16 @@ dependencies = ["blenderui-tailwind",]+[[package]]+name = "blenderui-node"+version = "0.1.0"+dependencies = [+ "blenderui",+ "napi",+ "napi-build",+ "napi-derive",+]+[[package]]name = "blenderui-sys"version = "0.1.0"@@ -70,6 +95,15 @@ dependencies = ["cc",]+[[package]]+name = "convert_case"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"+dependencies = [+ "unicode-segmentation",+]+[[package]]name = "crc32fast"version = "1.5.4"@@ -79,6 +113,16 @@ dependencies = ["cfg-if",]+[[package]]+name = "ctor"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"+dependencies = [+ "quote",+ "syn 2.0.119",+]+[[package]]name = "fdeflate"version = "0.3.7"@@ -105,6 +149,22 @@ dependencies = ["zlib-rs",]+[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]name = "miniz_oxide"version = "0.8.9"@@ -125,6 +185,69 @@ dependencies = ["simd-adler32",]+[[package]]+name = "napi"+version = "2.16.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"+dependencies = [+ "bitflags 2.13.2",+ "ctor",+ "napi-derive",+ "napi-sys",+ "once_cell",+]++[[package]]+name = "napi-build"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d"++[[package]]+name = "napi-derive"+version = "2.16.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"+dependencies = [+ "cfg-if",+ "convert_case",+ "napi-derive-backend",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "napi-derive-backend"+version = "1.0.75"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"+dependencies = [+ "convert_case",+ "once_cell",+ "proc-macro2",+ "quote",+ "regex",+ "semver",+ "syn 2.0.119",+]++[[package]]+name = "napi-sys"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"+dependencies = [+ "libloading",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"+[[package]]name = "paste"version = "1.0.15"@@ -137,7 +260,7 @@ version = "0.17.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"dependencies = [- "bitflags",+ "bitflags 1.3.2","crc32fast","fdeflate","flate2",@@ -162,6 +285,41 @@ dependencies = ["proc-macro2",]+[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+[[package]]name = "serde"version = "1.0.229"@@ -189,7 +347,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"dependencies = ["proc-macro2","quote",- "syn",+ "syn 3.0.9",][[package]]@@ -219,6 +377,17 @@ version = "1.16.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"+[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "syn"version = "3.0.9"@@ -247,12 +416,24 @@ version = "1.0.27"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"+[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"+[[package]]name = "version_check"version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]name = "zlib-rs"version = "0.6.8"diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.tomlindex e37f2de..ccd79cf 100644--- a/bindings/rust/Cargo.toml+++ b/bindings/rust/Cargo.toml@@ -1,6 +1,6 @@[workspace]resolver = "2"-members = ["blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui"]+members = ["blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui", "blenderui-node"]exclude = ["bench"][workspace.package]diff --git a/bindings/rust/blenderui-node/Cargo.toml b/bindings/rust/blenderui-node/Cargo.tomlnew file mode 100644index 0000000..a681bcc--- /dev/null+++ b/bindings/rust/blenderui-node/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "blenderui-node"+description = "Node.js bindings for blenderui (napi-rs): Blender's UI from JavaScript and React"+version.workspace = true+edition.workspace = true+license.workspace = true+repository.workspace = true+rust-version.workspace = true+publish = false++[lib]+crate-type = ["cdylib"]++[dependencies]+blenderui = { path = "../blenderui" }+napi = { version = "2.16", default-features = false, features = ["napi6"] }+napi-derive = "2.16"++[build-dependencies]+napi-build = "2"diff --git a/bindings/rust/blenderui-node/build.rs b/bindings/rust/blenderui-node/build.rsnew file mode 100644index 0000000..0f1b010--- /dev/null+++ b/bindings/rust/blenderui-node/build.rs@@ -0,0 +1,3 @@+fn main() {+ napi_build::setup();+}diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rsnew file mode 100644index 0000000..583c1b3--- /dev/null+++ b/bindings/rust/blenderui-node/src/lib.rs@@ -0,0 +1,654 @@+//! Node.js bindings (napi-rs): BUI driven from JavaScript, GPUIX style.+//!+//! BUI runs on its own UI thread: Node's thread is never blocked, and an+//! idle UI costs no CPU. JavaScript keeps a retained element tree and sends+//! only what changed: per window and per tick, one `Int32Array` of ops plus+//! a string table (no tree serialization, no per-node calls). The UI thread+//! 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).+//!+//! SPDX-License-Identifier: GPL-2.0-or-later++use std::collections::HashMap;+use std::sync::mpsc;++use blenderui::prelude::*;+use napi::bindgen_prelude::*;+use napi::threadsafe_function::{+ ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,+};+use napi::{Env, JsFunction, JsObject};+use napi_derive::napi;++type Tsfn = ThreadsafeFunction<BuiEvent, ErrorStrategy::Fatal>;++// ==========================================================================+// Values crossing the boundary++/// An event from a window (`kind`: click, mousedown, mouseup, mousemove,+/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, close).+#[napi(object)]+#[derive(Clone, Default)]+pub struct BuiEvent {+ pub kind: String,+ pub window: u32,+ /// The node whose listener fired.+ pub target: u32,+ pub x: f64,+ pub y: f64,+ /// 0 left, 1 middle, 2 right (DOM numbering).+ pub button: u32,+ pub click_count: u32,+ pub delta: f64,+ pub key: Option<String>,+ pub key_char: Option<String>,+ pub value: Option<String>,+ pub checked: bool,+ pub number: f64,+ pub shift: bool,+ pub ctrl: bool,+ pub alt: bool,+}++#[napi(object)]+pub struct AppOptions {+ /// Draw on the GPU (Direct3D 11).+ pub gpu: Option<bool>,+ /// GPU text from glyph outlines (Slug) or a glyph atlas.+ pub slug: Option<bool>,+ /// No native windows (tests, screenshots, CI).+ pub headless: Option<bool>,+}++#[napi(object)]+pub struct WindowConfig {+ pub title: Option<String>,+ pub width: Option<f64>,+ pub height: Option<f64>,+ pub resizable: Option<bool>,+ pub gpu: Option<bool>,+}++#[napi(object)]+pub struct Rect {+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+}++/// Ops (`commit`): opcode, then its arguments; `s` = index into the strings.+mod op {+ pub const CREATE: i32 = 0; // id, s(tag)+ pub const TEXT: i32 = 1; // id, s(text)+ pub const SET_ATTR: i32 = 2; // id, s(name), s(value)+ pub const REMOVE_ATTR: i32 = 3; // id, s(name)+ pub const APPEND: i32 = 4; // parent, child+ pub const INSERT: i32 = 5; // parent, child, before+ pub const REMOVE: i32 = 6; // parent, child+ pub const SET_TEXT: i32 = 7; // id, s(text)+ pub const LISTEN: i32 = 8; // id, event bits (replaces)+ pub const FREE: i32 = 9; // id+}++/// Event bits (`LISTEN`), matching `bindings/node/index.js`.+mod ev {+ pub const CLICK: u32 = 1;+ pub const MOUSE_DOWN: u32 = 2;+ pub const MOUSE_UP: u32 = 4;+ pub const MOUSE_MOVE: u32 = 8;+ pub const HOVER: u32 = 16;+ pub const WHEEL: u32 = 32;+ pub const KEY_DOWN: u32 = 64;+ pub const KEY_UP: u32 = 128;+ pub const CHANGE: u32 = 256;+ pub const INPUT: u32 = 512;+}++// ==========================================================================+// The retained tree (UI thread)++struct JsNode {+ tag: &'static str,+ key: SharedString,+ text: Option<SharedString>,+ attrs: Vec<(SharedString, SharedString)>,+ /// The `style` attribute, parsed once when set (renders reuse it).+ style: Option<Box<[blenderui::css::Decl]>>,+ children: Vec<u32>,+ events: u32,+}++/// `style="..."` parsed into declarations whose values are shared.+fn parse_style(css: &str) -> Box<[blenderui::css::Decl]> {+ blenderui::css::parse_declarations(css).into_iter().map(|d| blenderui::css::Decl {+ value: blenderui::css::Value::Shared(std::sync::Arc::from(&*d.value)),+ ..d+ }).collect()+}++/// One window's tree; node ids are per window and dense (root = 0).+struct JsView {+ window: u32,+ nodes: Vec<Option<JsNode>>,+ tsfn: Tsfn,+ /// JS asked for an animation frame: tell it when this one renders.+ raf: bool,+ /// The next vsync frame is already scheduled (changes just wait for it).+ frame_scheduled: bool,+}++/// Tag names as the `&'static str` elements need: HTML tags from the+/// table, others interned once.+fn intern_tag(tag: &str, custom: &mut HashMap<String, &'static str>) -> &'static str {+ if let Some((t, _)) = blenderui::html::TAGS.iter().find(|(t, _)| *t == tag) {+ return t;+ }+ *custom.entry(tag.to_string()).or_insert_with(|| Box::leak(tag.to_string().into_boxed_str()))+}++impl JsView {+ fn node(&mut self, id: i32) -> Option<&mut JsNode> {+ self.nodes.get_mut(usize::try_from(id).ok()?)?.as_mut()+ }++ 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);+ }+ self.nodes[i] = Some(n);+ }++ fn apply(&mut self, ops: &[i32], strings: &[String], tags: &mut HashMap<String, &'static str>) {+ let s = |k: i32| strings.get(k as usize).map(String::as_str).unwrap_or("");+ let mut i = 0;+ while i < ops.len() {+ let a = |k: usize| ops.get(i + k).copied().unwrap_or(-1);+ match ops[i] {+ op::CREATE => {+ let tag = intern_tag(s(a(2)), tags);+ self.put(a(1), JsNode { tag, key: format!("n{}", a(1)).into(), text: None, attrs: Vec::new(),+ style: None, children: Vec::new(), events: 0 });+ i += 3;+ }+ op::TEXT => {+ let text = s(a(2)).to_string();+ self.put(a(1), JsNode { tag: "", key: SharedString::Borrowed(""), text: Some(text.into()),+ attrs: Vec::new(), style: None, children: Vec::new(), events: 0 });+ i += 3;+ }+ op::SET_ATTR => {+ let (name, value) = (s(a(2)).to_string(), s(a(3)).to_string());+ if let Some(n) = self.node(a(1)) {+ if name == "style" {+ n.style = Some(parse_style(&value));+ }+ match n.attrs.iter_mut().find(|(k, _)| *k == name) {+ Some((_, v)) => *v = value.into(),+ None => n.attrs.push((name.into(), value.into())),+ }+ }+ i += 4;+ }+ op::REMOVE_ATTR => {+ let name = s(a(2));+ if let Some(n) = self.node(a(1)) {+ if name == "style" {+ n.style = None;+ }+ n.attrs.retain(|(k, _)| k != name);+ }+ i += 3;+ }+ op::APPEND => {+ let child = a(2) as u32;+ if let Some(n) = self.node(a(1)) {+ n.children.retain(|&c| c != child);+ n.children.push(child);+ }+ i += 3;+ }+ op::INSERT => {+ let (child, before) = (a(2) as u32, a(3) as u32);+ if let Some(n) = self.node(a(1)) {+ n.children.retain(|&c| c != child);+ let at = n.children.iter().position(|&c| c == before).unwrap_or(n.children.len());+ n.children.insert(at, child);+ }+ i += 4;+ }+ op::REMOVE => {+ let child = a(2) as u32;+ if let Some(n) = self.node(a(1)) {+ n.children.retain(|&c| c != child);+ }+ i += 3;+ }+ op::SET_TEXT => {+ let text = s(a(2)).to_string();+ if let Some(n) = self.node(a(1)) {+ n.text = Some(text.into());+ }+ i += 3;+ }+ op::LISTEN => {+ let bits = a(2) as u32;+ if let Some(n) = self.node(a(1)) {+ n.events = bits;+ }+ i += 3;+ }+ op::FREE => {+ if let Ok(k) = usize::try_from(a(1)) {+ if let Some(slot) = self.nodes.get_mut(k) {+ *slot = None;+ }+ }+ i += 2;+ }+ _ => break, // malformed: stop rather than misread+ }+ }+ }++ fn build(&self, id: u32) -> AnyElement {+ let Some(Some(n)) = self.nodes.get(id as usize) else {+ return String::new().into_any_element();+ };+ if let Some(t) = &n.text {+ return t.clone().into_any_element();+ }+ let mut d = Div::new(n.tag).key(n.key.clone());+ for (k, v) in &n.attrs {+ d = match &**k {+ "class" | "className" => d.class(v.clone()),+ "style" => d, // parsed: below+ "id" => d.id(v.clone()),+ _ => d.attr(k.clone(), v.clone()),+ };+ }+ if let Some(s) = &n.style {+ d = d.style(&s[..]);+ }+ if n.events != 0 {+ d = self.listeners(d, id, n.events);+ }+ for &c in &n.children {+ d = d.child(self.build(c));+ }+ d.into_any_element()+ }++ fn listeners(&self, mut d: Div, id: u32, bits: u32) -> Div {+ let base = BuiEvent { window: self.window, target: id, ..Default::default() };+ let send = {+ let t = self.tsfn.clone();+ move |e: BuiEvent| {+ t.call(e, ThreadsafeFunctionCallMode::NonBlocking);+ }+ };+ fn mods(e: &mut BuiEvent, m: &Modifiers) {+ (e.shift, e.ctrl, e.alt) = (m.shift, m.control, m.alt);+ }+ fn button(b: &MouseButton) -> u32 {+ match b {+ MouseButton::Left => 0,+ MouseButton::Middle => 1,+ MouseButton::Right => 2,+ }+ }+ macro_rules! on {+ ($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, _, _| {+ let mut $e = base.clone();+ $body+ send($e);+ });+ }+ };+ }+ on!(ev::CLICK, on_click, |e, c| {+ e.kind = "click".into();+ (e.x, e.y) = (c.up.position.x.0 as f64, c.up.position.y.0 as f64);+ e.button = button(&c.up.button);+ e.click_count = c.down.click_count as u32;+ mods(&mut e, &c.up.modifiers);+ });+ on!(ev::MOUSE_DOWN, on_any_mouse_down, |e, m| {+ e.kind = "mousedown".into();+ (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);+ e.button = button(&m.button);+ e.click_count = m.click_count as u32;+ mods(&mut e, &m.modifiers);+ });+ for b in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {+ on!(ev::MOUSE_UP, on_mouse_up(b.clone()), |e, m| {+ e.kind = "mouseup".into();+ (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);+ e.button = button(&m.button);+ mods(&mut e, &m.modifiers);+ });+ }+ on!(ev::MOUSE_MOVE, on_mouse_move, |e, m| {+ e.kind = "mousemove".into();+ (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| {+ e.kind = if *h { "mouseenter" } else { "mouseleave" }.into();+ });+ on!(ev::WHEEL, on_scroll_wheel, |e, w| {+ e.kind = "wheel".into();+ (e.x, e.y) = (w.position.x.0 as f64, w.position.y.0 as f64);+ e.delta = w.delta as f64;+ mods(&mut e, &w.modifiers);+ });+ on!(ev::KEY_DOWN, on_key_down, |e, k| {+ e.kind = "keydown".into();+ e.key = Some(k.keystroke.key.clone());+ e.key_char = k.keystroke.key_char.clone();+ mods(&mut e, &k.keystroke.modifiers);+ });+ on!(ev::KEY_UP, on_key_up, |e, k| {+ e.kind = "keyup".into();+ e.key = Some(k.keystroke.key.clone());+ e.key_char = k.keystroke.key_char.clone();+ mods(&mut e, &k.keystroke.modifiers);+ });+ on!(ev::CHANGE, on_change, |e, c| {+ e.kind = "change".into();+ (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);+ });+ on!(ev::INPUT, on_input, |e, c| {+ e.kind = "input".into();+ (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);+ });+ d+ }+}++impl Render for JsView {+ fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ self.frame_scheduled = false;+ if self.raf {+ // requestAnimationFrame: JS runs its callbacks while this frame+ // presents, and the next vsync frame is scheduled now (as a+ // browser does), so their changes make it into that frame+ self.raf = false;+ self.frame_scheduled = true;+ window.request_animation_frame();+ self.tsfn.call(BuiEvent { kind: "frame".into(), window: self.window, ..Default::default() },+ ThreadsafeFunctionCallMode::NonBlocking);+ }+ self.build(0)+ }+}++/// UI-thread state: JS window ids -> windows.+#[derive(Default)]+struct UiState {+ windows: HashMap<u32, WindowHandle<JsView>>,+ by_native: HashMap<usize, u32>,+ tags: HashMap<String, &'static str>,+}++type Job = Box<dyn FnOnce(&mut App) + Send>;++/// How jobs reach the UI thread: the native loop's sender, or (headless) a+/// channel the UI thread blocks on.+#[derive(Clone)]+enum Link {+ Native(UiSender),+ Headless(mpsc::Sender<Job>),+}++impl Link {+ fn send(&self, f: impl FnOnce(&mut App) + Send + 'static) -> bool {+ match self {+ Link::Native(s) => s.send(f),+ Link::Headless(tx) => tx.send(Box::new(f)).is_ok(),+ }+ }+}++// ==========================================================================+// The JavaScript class++/// A BUI application: owns the UI thread.+#[napi]+pub struct NativeApp {+ link: Link,+ headless: bool,+}++#[napi]+impl NativeApp {+ #[napi(constructor)]+ pub fn new(options: Option<AppOptions>,+ #[napi(ts_arg_type = "(event: BuiEvent) => void")] on_event: JsFunction) -> Result<Self> {+ let tsfn: Tsfn = on_event.create_threadsafe_function(0, |ctx: ThreadSafeCallContext<BuiEvent>| {+ Ok(vec![ctx.value])+ })?;+ let (gpu, slug, headless) = match &options {+ Some(o) => (o.gpu, o.slug, o.headless.unwrap_or(false)),+ None => (None, None, false),+ };+ let headless = headless || !blenderui::native_windows();+ let (ltx, lrx) = mpsc::channel::<Link>();+ std::thread::Builder::new().name("bui-ui".into()).spawn(move || {+ let mut a = if headless { Application::headless() } else { Application::new().keep_alive(true) };+ if let Some(g) = gpu {+ a = a.gpu(g);+ }+ if let Some(s) = slug {+ a = a.slug(s);+ }+ let close = tsfn.clone();+ a.run(move |cx| {+ cx.set_global(UiState::default());+ cx.set_global(close.clone());+ cx.on_window_closed(move |id, cx| {+ let js = cx.global::<UiState>().by_native.get(&id.0).copied();+ if let Some(w) = js {+ close.call(BuiEvent { kind: "close".into(), window: w, ..Default::default() },+ ThreadsafeFunctionCallMode::NonBlocking);+ cx.global_mut::<UiState>().windows.remove(&w);+ }+ });+ if headless {+ let (tx, rx) = mpsc::channel::<Job>();+ let _ = ltx.send(Link::Headless(tx));+ // jobs until every sender is gone+ while let Ok(job) = rx.recv() {+ job(cx);+ cx.run_pending();+ if cx.try_global::<Quit>().is_some() {+ break;+ }+ }+ } else {+ let _ = ltx.send(Link::Native(cx.ui_sender()));+ }+ });+ // the loop ended: let Node exit+ drop(tsfn);+ }).map_err(|e| Error::from_reason(format!("starting the UI thread: {e}")))?;+ let link = lrx.recv().map_err(|_| Error::from_reason("the UI thread failed to start"))?;+ Ok(NativeApp { link, headless })+ }++ /// Whether windows are off-screen.+ #[napi(getter)]+ pub fn headless(&self) -> bool {+ self.headless+ }++ /// Open window `id` (chosen by JS) with an empty `<body>` as node 0.+ #[napi]+ pub fn open_window(&self, id: u32, config: Option<WindowConfig>) {+ let (title, w, h, resizable, gpu) = match config {+ Some(c) => (c.title, c.width.unwrap_or(800.0), c.height.unwrap_or(600.0), c.resizable, c.gpu),+ None => (None, 800.0, 600.0, None, None),+ };+ self.link.send(move |cx| {+ let tsfn = cx.global::<Tsfn>().clone();+ let opts = blenderui::WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(w as f32), px(h as f32)),+ })),+ titlebar: title.map(|t| TitlebarOptions { title: Some(t.into()) }),+ is_resizable: resizable,+ gpu,+ ..Default::default()+ };+ let handle = cx.open_window(opts, |_, cx| {+ cx.new(|_| {+ let mut v = JsView { window: id, nodes: Vec::new(), 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+ })+ });+ if let Ok(handle) = handle {+ let st = cx.global_mut::<UiState>();+ st.by_native.insert(handle.id.0, id);+ st.windows.insert(id, handle);+ }+ });+ }++ /// Apply a batch of ops to window `window` and re-render it: right away,+ /// or (`animated`, during requestAnimationFrame) on the next vsync.+ #[napi]+ pub fn commit(&self, window: u32, ops: Int32Array, strings: Vec<String>, animated: Option<bool>) {+ let ops: Vec<i32> = ops.to_vec();+ let animated = animated.unwrap_or(false);+ self.link.send(move |cx| {+ let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() else { return };+ let mut tags = std::mem::take(&mut cx.global_mut::<UiState>().tags);+ handle.update(cx, |v, w, _| {+ v.apply(&ops, &strings, &mut tags);+ if !animated {+ w.refresh(); // this window only+ } else if !v.frame_scheduled {+ v.frame_scheduled = true;+ w.request_animation_frame();+ }+ });+ cx.global_mut::<UiState>().tags = tags;+ });+ }++ /// Ask for a `frame` event when window `window` next renders (vsync).+ #[napi]+ pub fn request_frame(&self, window: u32) {+ self.link.send(move |cx| {+ if let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() {+ handle.update(cx, |v, w, _| {+ v.raf = true;+ if !v.frame_scheduled {+ v.frame_scheduled = true;+ w.request_animation_frame();+ }+ });+ }+ });+ }++ #[napi]+ pub fn close_window(&self, window: u32) {+ self.link.send(move |cx| {+ if let Some(h) = cx.global_mut::<UiState>().windows.remove(&window) {+ cx.close_window(h.id);+ }+ });+ }++ /// Draw on the GPU from now on (new windows) / GPU text mode.+ #[napi]+ pub fn set_slug(&self, on: bool) {+ self.link.send(move |cx| {+ blenderui::set_slug(on);+ cx.notify_all();+ });+ }++ /// End the UI thread (closes every window).+ #[napi]+ pub fn quit(&self) {+ self.link.send(|cx| {+ let ids: Vec<WindowId> = cx.global::<UiState>().windows.values().map(|h| h.id).collect();+ for id in ids {+ cx.close_window(id);+ }+ cx.global_mut::<UiState>().windows.clear();+ cx.set_global(Quit);+ cx.quit();+ });+ }++ /// Render window `window` and resolve with its pixels: `{ width, height,+ /// data }` (RGBA bytes, device pixels).+ #[napi(ts_return_type = "Promise<{ width: number, height: number, data: Buffer }>")]+ pub fn screenshot(&self, env: Env, window: u32) -> Result<JsObject> {+ let (deferred, promise) = env.create_deferred()?;+ self.link.send(move |cx| {+ let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() else {+ deferred.reject(Error::from_reason("no such window"));+ return;+ };+ let (w, h, px) = cx.draw(handle.id);+ let mut rgba = Vec::with_capacity(px.len() * 4);+ for p in px {+ rgba.extend_from_slice(&[(p >> 16) as u8, (p >> 8) as u8, p as u8, 255]);+ }+ deferred.resolve(move |_| Ok(Screenshot { width: w as u32, height: h as u32, data: rgba.into() }));+ });+ Ok(promise)+ }++ /// Bounds of node `node` (logical pixels), or null.+ #[napi(ts_return_type = "Promise<Rect | null>")]+ pub fn bounds(&self, env: Env, window: u32, node: u32) -> Result<JsObject> {+ let (deferred, promise) = env.create_deferred()?;+ self.link.send(move |cx| {+ let handle = cx.global::<UiState>().windows.get(&window).cloned();+ let r = handle.and_then(|h| {+ cx.draw(h.id);+ cx.element_bounds(h.id, &format!("n{node}"))+ });+ deferred.resolve(move |_| Ok(r.map(|b| Rect { x: b.origin.x as f64, y: b.origin.y as f64,+ width: b.size.width as f64,+ height: b.size.height as f64 })));+ });+ Ok(promise)+ }++ /// Click at (x, y) in window `window` (tests; logical pixels).+ #[napi]+ pub fn simulate_click(&self, window: u32, x: f64, y: f64) {+ self.link.send(move |cx| {+ if let Some(h) = cx.global::<UiState>().windows.get(&window).cloned() {+ cx.simulate_click(h.id, x as f32, y as f32);+ }+ });+ }+}++/// The headless loop ends after the job that set this.+struct Quit;++#[napi(object)]+pub struct Screenshot {+ pub width: u32,+ pub height: u32,+ /// RGBA, row-major.+ pub data: Buffer,+}diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rsindex 7519f9a..d3fd5fc 100644--- a/bindings/rust/blenderui-sys/src/lib.rs+++ b/bindings/rust/blenderui-sys/src/lib.rs@@ -235,6 +235,9 @@ unsafe extern "C" {pub fn BK_window_wm_get(win: *mut BKWindow, key: *const c_char, r_a: *mut c_double,r_b: *mut c_double) -> c_int;pub fn BK_window_run();+ pub fn BK_window_wake_init(cb: Option<unsafe extern "C" fn()>) -> c_int;+ pub fn BK_window_wake();+ pub fn BK_window_set_keep_alive(on: c_int);pub fn BK_window_pump() -> c_int;pub fn BK_window_quit();diff --git a/bindings/rust/blenderui/src/css.rs b/bindings/rust/blenderui/src/css.rsindex 1399b08..d056d07 100644--- a/bindings/rust/blenderui/src/css.rs+++ b/bindings/rust/blenderui/src/css.rs@@ -342,6 +342,9 @@ pub enum Value {One(Tok),Static(&'static [Tok]),Owned(Box<[Tok]>),+ /// Shared between elements: cloning bumps a count (styles parsed once+ /// and reused every render, e.g. by the Node binding).+ Shared(std::sync::Arc<[Tok]>),}impl std::ops::Deref for Value {@@ -351,6 +354,7 @@ impl std::ops::Deref for Value {Value::One(t) => std::slice::from_ref(t),Value::Static(s) => s,Value::Owned(b) => b,+ Value::Shared(a) => a,}}}@@ -359,6 +363,7 @@ impl PartialEq for Value {fn eq(&self, o: &Value) -> bool {match (self, o) {(Value::Static(a), Value::Static(b)) if std::ptr::eq(*a, *b) => true,+ (Value::Shared(a), Value::Shared(b)) if std::sync::Arc::ptr_eq(a, b) => true,_ => **self == **o,}}diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rsindex 22af336..f4f56d7 100644--- a/bindings/rust/blenderui/src/element.rs+++ b/bindings/rust/blenderui/src/element.rs@@ -135,6 +135,13 @@ impl Div {self}+ /// Identity without an `id` attribute: keeps state (scroll position,+ /// form values) across renders, invisible to CSS (`#id` doesn't match).+ pub fn key(mut self, key: impl Into<ElementId>) -> Self {+ self.id = Some(key.into());+ self+ }+/// Set an HTML attribute (`href`, `type`, `value`, `placeholder` ...).pub fn attr(mut self, name: impl Into<SharedString>, value: impl Into<SharedString>) -> Self {let name = name.into();diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rsindex a6edc92..5fb0b98 100644--- a/bindings/rust/blenderui/src/lib.rs+++ b/bindings/rust/blenderui/src/lib.rs@@ -155,6 +155,13 @@ pub fn set_slug(on: bool) {unsafe { sys::BUI_gpu_set_slug(on as std::os::raw::c_int) }}+/// Whether this platform has native windows (Windows today); elsewhere+/// apps run headless or through a host such as the Tk fallback.+pub fn native_windows() -> bool {+ // SAFETY: a constant query.+ unsafe { sys::BK_window_supported() != 0 }+}+/// Whether GPU text is drawn with Slug (see [`set_slug`]).pub fn slug() -> bool {// SAFETY: reads a global flag.diff --git a/bindings/rust/blenderui/src/styled.rs b/bindings/rust/blenderui/src/styled.rsindex 92ce061..0a4842d 100644--- a/bindings/rust/blenderui/src/styled.rs+++ b/bindings/rust/blenderui/src/styled.rs@@ -39,6 +39,13 @@ impl<const N: usize> StyleBlock for [Decl; N] {out.extend(self);}}+/// Declarations parsed earlier (`css::parse_declarations`), reused as they+/// are: values that are `Value::Shared` clone without allocating.+impl StyleBlock for &[Decl] {+ fn push_into(self, out: &mut Vec<Decl>) {+ out.extend_from_slice(self);+ }+}impl StyleBlock for &str {fn push_into(self, out: &mut Vec<Decl>) {out.extend(parse_declarations(self));diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rsindex 0b3beb8..0ef0df9 100644--- a/bindings/rust/blenderui/src/window.rs+++ b/bindings/rust/blenderui/src/window.rs@@ -185,7 +185,11 @@ impl<V: 'static> WindowHandle<V> {pub fn update<R>(&self, cx: &mut App,f: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R) -> Option<R> {let mut w = cx.windows.get_mut(self.id.0)?.take()?;+ let notified = cx.notified;let r = self.entity.update(cx, |v, cx| f(v, &mut w, cx));+ if cx.notified != notified {+ w.refresh(); // `cx.notify()` ran while this window was out of the list+ }cx.windows[self.id.0] = Some(w);Some(r)}@@ -221,6 +225,7 @@ pub struct Application {headless: bool,gpu: Option<bool>,slug: Option<bool>,+ keep_alive: bool,}impl Default for Application {@@ -232,7 +237,7 @@ impl Default for Application {impl Application {/// Native windows.pub fn new() -> Application {- Application { headless: false, gpu: None, slug: None }+ Application { headless: false, gpu: None, slug: None, keep_alive: false }}/// Draw every window on the GPU (Direct3D 11 on Windows): the same@@ -253,10 +258,17 @@ impl Application {self}+ /// Keep the event loop running with no windows open, until+ /// [`App::quit`]: for apps driven from another thread ([`App::ui_sender`]).+ pub fn keep_alive(mut self, on: bool) -> Application {+ self.keep_alive = on;+ self+ }+/// Off-screen windows (tests, screenshots, CI): nothing is shown, the/// `simulate_*` and `draw` methods drive it.pub fn headless() -> Application {- Application { headless: true, gpu: None, slug: None }+ Application { headless: true, gpu: None, slug: None, keep_alive: false }}/// Run `f`, then the event loop until every window is closed.@@ -280,6 +292,7 @@ impl Application {}// the app stays on this stack frame; kit callbacks reach it through APPAPP.with(|a| a.set(&mut app as *mut App));+ unsafe { sys::BK_window_set_keep_alive(self.keep_alive as c_int) };// SAFETY: plain message loop; `app` isn't touched here until it returns.unsafe { sys::BK_window_run() };APP.with(|a| a.set(std::ptr::null_mut()));@@ -329,11 +342,48 @@ pub struct App {headless: bool,globals: HashMap<TypeId, Box<dyn Any>>,propagate: bool,+ /// Work sent from other threads ([`UiSender`]).+ remote: Option<(std::sync::mpsc::Sender<RemoteJob>, std::sync::mpsc::Receiver<RemoteJob>)>,+ /// Called when the user closes a window.+ close_hooks: Vec<Box<dyn FnMut(WindowId, &mut App)>>,+ /// Counts `notify_all` calls (see `WindowHandle::update`).+ notified: u64,+}++type RemoteJob = Box<dyn FnOnce(&mut App) + Send>;++/// Runs closures on the UI thread from any thread ([`App::ui_sender`]):+/// the UI loop wakes, runs them in order, then re-renders what they changed.+#[derive(Clone)]+pub struct UiSender {+ tx: std::sync::mpsc::Sender<RemoteJob>,+}++impl UiSender {+ /// Queue `f` for the UI thread. False when the app has ended.+ pub fn send(&self, f: impl FnOnce(&mut App) + Send + 'static) -> bool {+ let ok = self.tx.send(Box::new(f)).is_ok();+ // SAFETY: posts a message; callable from any thread.+ unsafe { sys::BK_window_wake() };+ ok+ }+}++unsafe extern "C" fn on_wake() {+ let ran = with_running_app(|app| {+ app.drain();+ app.flush();+ });+ if !ran {+ // a callback further up holds the app: try again on the next turn+ unsafe { sys::BK_window_wake() };+ }}impl App {fn create(headless: bool) -> App {- App { windows: Vec::new(), entities: Vec::new(), headless, globals: HashMap::new(), propagate: true }+ App { windows: Vec::new(), entities: Vec::new(), headless, globals: HashMap::new(), propagate: true,+ remote: None, close_hooks: Vec::new(), notified: 0 }}/// Create an entity (gpui's `cx.new`).@@ -404,11 +454,46 @@ impl App {/// Mark every window for re-render.pub fn notify_all(&mut self) {+ self.notified = self.notified.wrapping_add(1);for w in self.windows.iter_mut().flatten() {w.refresh();}}+ /// A handle other threads use to run code on this (the UI) thread.+ pub fn ui_sender(&mut self) -> UiSender {+ if self.remote.is_none() {+ self.remote = Some(std::sync::mpsc::channel());+ if !self.headless {+ unsafe { sys::BK_window_wake_init(Some(on_wake)) };+ }+ }+ UiSender { tx: self.remote.as_ref().map(|(tx, _)| tx.clone()).unwrap() }+ }++ /// Run work queued by [`UiSender`]s and re-render what changed (for a+ /// loop that isn't the native one, e.g. headless apps driven by+ /// another thread).+ pub fn run_pending(&mut self) {+ self.drain();+ self.flush();+ }++ /// Call `f` whenever the user closes a window.+ pub fn on_window_closed(&mut self, f: impl FnMut(WindowId, &mut App) + 'static) {+ self.close_hooks.push(Box::new(f));+ }++ /// Close a window (as if the user had).+ pub fn close_window(&mut self, id: WindowId) {+ if let Some(w) = self.windows.get_mut(id.0).and_then(|w| w.as_deref_mut()) {+ w.closed = true;+ if let Some(n) = w.native {+ unsafe { sys::BK_window_close(n) };+ }+ }+ }+/// Stop the event loop.pub fn quit(&mut self) {unsafe { sys::BK_window_quit() };@@ -451,6 +536,17 @@ impl App {while let Some(ev) = queue_pop() {self.with_window(ev.window, |w, app| w.dispatch(ev, app));}+ // work from other threads (UiSender)+ loop {+ let job = match &self.remote {+ Some((_, rx)) => rx.try_recv().ok(),+ None => None,+ };+ match job {+ Some(f) => f(self),+ None => break,+ }+ }}/// Re-render dirty windows now (headless) or soon (native: next loop turn).@@ -631,6 +727,12 @@ unsafe extern "C" fn on_close(data: *mut c_void, _win: *mut sys::BKWindow) -> c_if let Some(w) = app.windows.get_mut(id).and_then(|w| w.as_deref_mut()) {w.closed = true;}+ let mut hooks = std::mem::take(&mut app.close_hooks);+ for h in hooks.iter_mut() {+ h(WindowId(id), app);+ }+ hooks.append(&mut app.close_hooks);+ app.close_hooks = hooks;});1}diff --git a/docs/javascript.md b/docs/javascript.mdnew file mode 100644index 0000000..f3e7398--- /dev/null+++ b/docs/javascript.md@@ -0,0 +1,178 @@+# 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.++| 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 |++Status: Windows x64 with native windows. Elsewhere, `headless: true` works+(tests, screenshots). The browser (WebAssembly) build is next.++## Plain JavaScript++```js+const { App } = require('@blenderui/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 label = win.createElement('span')+label.textContent = 'Clicks: 0'+const button = win.createElement('button')+button.textContent = 'Add one'+let n = 0+button.addEventListener('click', () => { label.textContent = `Clicks: ${++n}` })+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`.++`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).++## React++```jsx+import { useState } from 'react'+import { render } from '@blenderui/react'++function Counter () {+ const [count, setCount] = useState(0)+ 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: '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.++## Hooks and signals++React's hooks work as usual. BUI's own hooks, the Rust crate's `Signal`,+`Memo` and `Effect`, come along too, in both packages:++| 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 |++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.++The point of signals is what they skip. Pass a signal where a value goes and+the node follows it:++```jsx+import { render, useSignal, useComputed } from '@blenderui/react'++function Counter () {+ const count = useSignal(0)+ const style = useComputed(() => ({ 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>+ </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.++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.++## 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.+- **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.+- **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+ per frame.++## 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:++- **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.++## 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+```++The build needs what the Rust crate needs: CMake and a C compiler. With+MinGW, put its `bin` folder on `PATH`.diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.cindex e09cb2c..8869581 100644--- a/gpu/intern/gpu_raster.c+++ b/gpu/intern/gpu_raster.c@@ -251,9 +251,16 @@ void BUI_gpu_set_slug(int on)int BUI_gpu_slug(void){- const char *env = getenv("BUI_SLUG");- if (env && env[0]) {- return env[0] == '1' || env[0] == 'y' || env[0] == 'Y' || env[0] == 't' || env[0] == 'T';+ /* called per text run: read the environment once */+ static int env_slug = -2; /* -2 unread, -1 unset */+ if (env_slug == -2) {+ const char *env = getenv("BUI_SLUG");+ env_slug = (env && env[0]) ? (env[0] == '1' || env[0] == 'y' || env[0] == 'Y' || env[0] == 't' ||+ env[0] == 'T') :+ -1;+ }+ if (env_slug >= 0) {+ return env_slug;}return g_slug >= 0 ? g_slug : BUI_SLUG_DEFAULT;}diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.hindex d56cb96..fe38e87 100644--- a/kit/include/BUI_kit.h+++ b/kit/include/BUI_kit.h@@ -365,6 +365,14 @@ void BK_window_run(void);int BK_window_pump(void); /* handle pending messages; returns open windows */void BK_window_quit(void);void BK_window_set_stop_check(int (*stop)(void)); /* polled after each message */+/* Waking the loop from other threads (a UI thread driven by another runtime,+ * e.g. Node): BK_window_wake_init(cb) on the loop's thread, then+ * BK_window_wake() from any thread makes the loop call cb soon (wakes are+ * coalesced, and survive Win32's modal move/resize loops). With keep-alive,+ * BK_window_run keeps running with no windows open, until BK_window_quit. */+int BK_window_wake_init(void (*cb)(void));+void BK_window_wake(void);+void BK_window_set_keep_alive(int on);/* Evaluate Blender-style number input ("2*pi", "1/3 + 2^2"). */int BK_eval_number(const char *expr, double *r_value);diff --git a/kit/intern/kit_window.c b/kit/intern/kit_window.cindex 02a28ad..c73eac5 100644--- a/kit/intern/kit_window.c+++ b/kit/intern/kit_window.c@@ -55,7 +55,54 @@ static void wake_loop(void)PostThreadMessageW(GetCurrentThreadId(), WM_NULL, 0, 0);}static int g_quit = 0;+static int g_keep_alive = 0;static int (*g_stop)(void) = NULL;++/* -- cross-thread wake: a message-only window on the loop's thread ------------------- */+# define WM_BK_WAKE (WM_APP + 7)+static HWND g_wake_hwnd = NULL;+static void (*g_wake_cb)(void) = NULL;+static volatile LONG g_wake_pending = 0;++static LRESULT CALLBACK wake_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)+{+ if (msg == WM_BK_WAKE) {+ InterlockedExchange(&g_wake_pending, 0); /* wakes after this point post again */+ if (g_wake_cb) {+ g_wake_cb();+ }+ return 0;+ }+ return DefWindowProcW(hwnd, msg, wp, lp);+}++int BK_window_wake_init(void (*cb)(void))+{+ g_wake_cb = cb;+ if (g_wake_hwnd) {+ return 1;+ }+ WNDCLASSW wc = {0};+ wc.lpfnWndProc = wake_proc;+ wc.hInstance = GetModuleHandleW(NULL);+ wc.lpszClassName = L"BUIKitWake";+ RegisterClassW(&wc); /* fails harmlessly when already registered */+ g_wake_hwnd = CreateWindowExW(0, L"BUIKitWake", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL,+ wc.hInstance, NULL);+ return g_wake_hwnd != NULL;+}++void BK_window_wake(void)+{+ if (g_wake_hwnd && InterlockedExchange(&g_wake_pending, 1) == 0) {+ PostMessageW(g_wake_hwnd, WM_BK_WAKE, 0, 0);+ }+}++void BK_window_set_keep_alive(int on)+{+ g_keep_alive = on;+}static const wchar_t *k_class = L"BUIKitWindow";int BK_window_supported(void)@@ -874,7 +921,7 @@ void BK_window_run(void){g_quit = 0;MSG msg;- while (g_open > 0 && !g_quit && GetMessageW(&msg, NULL, 0, 0) > 0) {+ while ((g_open > 0 || g_keep_alive) && !g_quit && GetMessageW(&msg, NULL, 0, 0) > 0) {TranslateMessage(&msg);DispatchMessageW(&msg);if (g_stop && g_stop()) {@@ -960,5 +1007,15 @@ int BK_window_pump(void)}void BK_window_quit(void) {}void BK_window_set_stop_check(int (*stop)(void)) {}+int BK_window_wake_init(void (*cb)(void))+{+ (void)cb;+ return 0;+}+void BK_window_wake(void) {}+void BK_window_set_keep_alive(int on)+{+ (void)on;+}#endif