diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7b98c8cf..78b429e4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -96,6 +96,30 @@ All notable changes to **blenderui** (BUI). The format follows
`muted=` and `volume=`) and Lua; the Blender-style controls get a mute button. Videos autoplay with sound now
(they were silent): mute one with `muted`. Tested on Windows; the macOS and Linux outputs are written against
their documented APIs and untried.
+- **Rust: `on_key_press`, `scroll` from any source, and what leaves the tree.** `keypress` follows `keydown` for a key that
+ types. `scroll` fires for every scroll container that moved (also `set_scroll_offset` or a layout change), not only the wheel.
+ When the element that holds the pointer is removed, `pointercancel` and `lostpointercapture` go out and the capture ends;
+ a removed focused element no longer keeps the focus.
+- **JavaScript: the whole set of HTML events.** `addEventListener` now takes `dblclick`, `auxclick`, `contextmenu`, `mouseover`/`mouseout`,
+ every `pointer*` event, `keypress`, `focus`/`blur`/`focusin`/`focusout`, `scroll` and Blender's `pressdrag`, with the capture
+ phase (`{ capture: true }`, `once`, `event.eventPhase`), `buttons`, `pointerId` / `pointerType`, and `el.setPointerCapture()` /
+ `releasePointerCapture()` / `hasPointerCapture()`. The native listener mask is now two words (`LISTEN` carries 62 bits), and the
+ window's own `focus` / `blur` are told from an element's by the target.
+- **Rust: Blender's press-drag.** `on_press_drag` (`PressDragEvent`, `DragDirection`, `DRAG_THRESHOLD`): once per press, from the first
+ move more than 3 pixels from where the button went down, with the direction to the nearest of eight, as Blender's
+ `KM_PRESS_DRAG` and `WM_event_drag_direction` (`wm_event_system.cc`, `wm_event_query.cc`).
+- **Rust: every HTML event, with capture and bubbling.** A listener for each `on*` event: `on_double_click`,
+ `on_aux_click`, `on_context_menu`, `on_mouse_enter` / `leave` / `over` / `out`, the pointer events
+ (`on_pointer_down` / `up` / `move` / `enter` / `leave` / `over` / `out` / `cancel` and the pointer capture pair, with a
+ `PointerEvent`), `on_focus` / `blur` / `focus_in` / `focus_out`, `on_scroll` and `on_wheel`, and a `_capture` twin of
+ each (`onClickCapture` in `rsx!`) for the pass from the root down to the target. `cx.stop_propagation()` ends the pass it
+ is in. `window.set_pointer_capture(cx)` holds the pointer for an element, so a drag keeps hearing the moves and the
+ release outside it; `on_mouse_event` / `on_key_event` / `on_window_event` hear every event of a kind in the window, in
+ both passes, as gpui's `on_mouse_event` does (`DispatchPhase::Capture` / `Bubble`). A press fires `pointerdown` before
+ `mousedown`, and a move `pointermove` before `mousemove`. One listener list per element holds them all (a frame
+ skips the walk for kinds nothing listens for). The touch and trackpad gestures (`on_pan`, `on_pinch`, `on_rotate`) go
+ through both passes too, with their `_capture` twins. Not there yet: the `touch*` events, drag-and-drop, clipboard, media
+ and CSS animation events. `App::simulate_button` clicks with the middle or secondary button in tests.
- **Animation: GSAP and Motion on one engine** (feature `anim`, on by default; `BUI_ANIM` in CMake). One C engine
in the kit (`kit/intern/anim`, `BUI_anim.h`) runs every animation, so Rust, JavaScript, Python, Lua and C animate
the same way and none carries its own. Eases: every name of GSAP, Motion, CSS and Blender, `cubic-bezier()`,
@@ -127,6 +151,11 @@ All notable changes to **blenderui** (BUI). The format follows
### Changed
- **Rust: boxes lay out at fractional positions, as in a browser.** A flex item a quarter of 190px is 47.5px wide (it was rounded to 48), and `element_bounds` reports what `getBoundingClientRect` would. Painting snaps each edge of a box's background, border and image to its nearest device pixel, so edges stay crisp and neighbouring boxes still meet; a canvas's own drawing stays anti-aliased, as a browser canvas.
+- **Rust: pointer events cost less.** The hit test keeps an index of every box's subtree and the rectangle around it
+ (built on the first hit test of a frame, dropped when a redraw or a scroll moves boxes) and skips the subtrees a point is
+ not in; an event kind nothing in the frame listens for skips the walk, window-wide listeners have a list of their own, and
+ a move that ends over the same elements stops after the hit test without allocating. 3000 boxes: a move 46 to 12 µs, a
+ click 130 to 57 µs (`examples/events_bench.rs`, headless, release, against main before the event API).
- **Kit: a layout arranges only the nodes that changed.** A node is arranged again when it or a node under it measured again, or when its place changed; the rest keep their places. A frame where one label changes among 3300 nodes: 0.26 ms instead of 0.31 ms. A change of theme, scale or font still arranges every node.
- **Kit: a layout change redraws only what moved.** A layout used to redraw the whole window. Now each widget's
place on screen is compared with where the last frame drew it, and only widgets that moved, resized, appeared or
@@ -212,6 +241,12 @@ All notable changes to **blenderui** (BUI). The format follows
- `:nth-last-child(An+B of S)` counts the following siblings that match `S` (it saw none, since they aren't built when rules match; `S` may name the element's ancestors).
- `light-dark()`, the system colors (`Canvas`, `LinkText` ...) and `@media (prefers-color-scheme)` follow the theme's mode (they were always dark). Light mode uses a browser's light system colors. Windows re-render when the theme changes, with no `notify_all()` needed.
- **Windows: the system's maximize button maximizes again.** The kit took every press on a maximize button as the app's, so on a window with the system's title bar the press went to the app and Windows never maximized; only a title bar the app draws (`WindowDecorations::Client`) hands its maximize button's presses to the app now.
+- **Rust: an element the layout moved under a pointer that stayed still was never entered** (`mouseenter`, `mouseover`,
+ `pointerenter`, `on_hover` and their leave twins didn't fire; only `:hover` followed): the hover update after each frame fires events now.
+- **Rust: `cx.notify()` in a listener didn't render the window it ran in** (that window is out of the list while it runs):
+ every call that lends a window out renders it again after a `notify`, not only `WindowHandle::update`.
+- **Rust: a `render` that reads `window.is_hovered(..)` or `focused_id()` follows them.** Since a hover or a press over
+ plain content renders nothing, a view that read them kept the old answer; it renders again when what it read changes.
- **Android: the app runs again after Back.** The host's state (`g_quit`, the wake callback, keep-alive, the stop check) starts over on each `BK_android_attach`, so a relaunch in the same process is not a dead window; the activity is `singleTask`, so a second launch brings the running one back instead of attaching a second activity. `BK_android_detach` (new; `android_main` calls it before the glue frees the app) ends wakes from other threads, which used the freed looper. A Lua script that fails after opening its window shows its error (the error window came back NULL and crashed). A second finger joining a one-finger scroll no longer jumps it; `BK_window_timer` returns -1 (not 0) when the window's timers are full, as `BUI_kit.h` says; a failed window allocation returns NULL (the C demo checks it); a frame whose post fails is redrawn. `build.py` aligns the APK with `zipalign 4` (the libraries are deflated: `-P 16` aligned nothing and failed on build-tools 34) and builds a Rust app's crate with `--lib`.
- **WebAssembly: an unstyled canvas keeps its size after a zoom.** At a pixel ratio of 1 its CSS size was not pinned, so after a zoom or a move to a retina screen it grew on every frame; every resize now sizes the backing store and pins it. `build.py --serve` serves `.wasm` and `.js` with their web types on Windows (the override was set on a `functools.partial`, where it did nothing). The wasm workflow runs on changes to the kit, the GPU raster, core and blenderui too, and the smoke test's click check compares against the hovered button, so it can fail.
- **QuickJS (`bui run`, `bui build`, Android `--js`): timers set from promise jobs run.** A `setTimeout` made in a `.then` was missed (a headless app quit with it pending, a windowed one stalled until the next event); timers now run one task at a time with the promise jobs after each, as in HTML's event loop, and the next deadline is read after the last job. A pump that runs out of rounds with work left schedules the next one. `setTimeout(f, Infinity)` (or `NaN`, negative, past 2^31-1 ms) is a 0 ms delay, as in browsers, instead of panicking the runtime.
diff --git a/README.md b/README.md
index 8b427c14..d752f29f 100644
--- a/README.md
+++ b/README.md
@@ -1370,6 +1370,11 @@ run time, and every open window relayouts and redraws:
| Dear ImGui | Its Blender style follows the kit's theme (pick it before the backend starts) |
| Any app, no code change | `BUI_THEME=light` (or `dark`) |
+
+
+ One dashboard, seven themes: Blender's Dark and Light, then five theme files
+
+
**Your own themes.** A theme file is JSON in the shape of gpui-kit's, with Blender's names for the colors
(`user_interface.wcol_regular.inner`, or in plain English `button.background`). It starts from Dark or Light and
lists only what it changes: colors, a few short palette names (`background`, `primary.background`) that fill in
diff --git a/bindings/node/README.md b/bindings/node/README.md
index edd350aa..140e0131 100644
--- a/bindings/node/README.md
+++ b/bindings/node/README.md
@@ -55,14 +55,18 @@ win.body.appendChild(button)
`@blender-ui/native/globals` (`document`, `window` and the node classes as
globals, for DOM-based frameworks), and `bui build` bundling with the Bun
plugin a `@blender-ui/*` package declares (`"bui": { "bunPlugin" }`).
-- **Events:** `addEventListener` for `click`, `mousedown`, `mouseup`,
- `mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input`,
- `change`, and the touch screen / trackpad gestures `pinch` (`delta`: the
- scale change), `rotate` (`delta`: degrees, counter-clockwise) and `pan`
- (`deltaX` / `deltaY`: pixels the content follows the fingers; `phase`:
- `drag`, `fling` or `end`) arrive from the UI thread; other types fire through
- `dispatchEvent`.
- - They bubble through the tree, and `stopPropagation()` works.
+- **Events:** `addEventListener` for `click`, `dblclick`, `auxclick`,
+ `contextmenu`, the `mouse*` and `pointer*` events (`pointerdown`, `pointerup`,
+ `pointermove`, `pointerenter`, `pointerleave`, `pointerover`, `pointerout`,
+ `pointercancel`, `gotpointercapture`, `lostpointercapture`), `wheel`,
+ `keydown`, `keypress`, `keyup`, `focus`, `blur`, `focusin`, `focusout`,
+ `scroll`, `pressdrag` (Blender's press-drag), `input`, `change`, and the touch
+ screen / trackpad gestures `pinch` (`delta`: the scale change), `rotate`
+ (`delta`: degrees, counter-clockwise) and `pan` (`deltaX` / `deltaY`: pixels
+ the content follows the fingers; `phase`: `drag`, `fling` or `end`) arrive
+ from the UI thread; other types fire through `dispatchEvent`.
+ - They capture and bubble through the tree (`addEventListener(type, fn, { capture: true, once: true })`),
+ and `stopPropagation()` works. `el.setPointerCapture()` keeps the pointer for an element.
- An element listening for `pan` takes the drag, as CSS's
`touch-action: none`: nothing under it scrolls by touch.
- They arrive after BUI has handled them, so `preventDefault()` only marks
diff --git a/bindings/node/dom.js b/bindings/node/dom.js
index 22e937af..0b356ec0 100644
--- a/bindings/node/dom.js
+++ b/bindings/node/dom.js
@@ -14,20 +14,27 @@ const { isSignal, effect, unowned, memo } = require('./signals')
const { vars: checkVars } = require('./validate')
// 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, MOTION: 10 }
+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, MOTION: 10, CAPTURE: 11 }
// Motion's props (keep in sync with MotionProp::parse, bindings/rust/blenderui-jsview/src/motion.rs)
const MOTION_PROPS = {
initial: 0, animate: 1, exit: 2, whileHover: 3, whileTap: 4, whileFocus: 5, transition: 6, style: 7, variants: 8,
whileInView: 9, whileDrag: 10, viewport: 11, drag: 12, dragConstraints: 13, dragElastic: 14, dragMomentum: 15,
dragSnapToOrigin: 16, layout: 17
}
+// one bit per native listener (`ev` in blenderui-jsview); more than 31, so they travel as two words
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, pinch: 1024, rotate: 2048, pan: 4096,
+ click: 2 ** 0, mousedown: 2 ** 1, mouseup: 2 ** 2, mousemove: 2 ** 3, mouseenter: 2 ** 4, mouseleave: 2 ** 4,
+ wheel: 2 ** 5, keydown: 2 ** 6, keyup: 2 ** 7, change: 2 ** 8, input: 2 ** 9,
+ pinch: 2 ** 10, rotate: 2 ** 11, pan: 2 ** 12,
+ dblclick: 2 ** 13, auxclick: 2 ** 14, contextmenu: 2 ** 15, mouseover: 2 ** 16, mouseout: 2 ** 17,
+ pointerdown: 2 ** 18, pointerup: 2 ** 19, pointermove: 2 ** 20, pointerenter: 2 ** 21, pointerleave: 2 ** 22,
+ pointerover: 2 ** 23, pointerout: 2 ** 24, pointercancel: 2 ** 25, gotpointercapture: 2 ** 26, lostpointercapture: 2 ** 27,
+ keypress: 2 ** 28, focus: 2 ** 29, blur: 2 ** 30, focusin: 2 ** 31, focusout: 2 ** 32, pressdrag: 2 ** 33, scroll: 2 ** 34,
}
+const WORD = 2 ** 31
const BUTTONS = ['left', 'middle', 'right']
// DOM: these don't bubble
-const NO_BUBBLE = new Set(['mouseenter', 'mouseleave'])
+const NO_BUBBLE = new Set(['mouseenter', 'mouseleave', 'pointerenter', 'pointerleave', 'focus', 'blur', 'scroll'])
const ELEMENT_NODE = 1, TEXT_NODE = 3, COMMENT_NODE = 8, FRAGMENT_NODE = 11
const XHTML = 'http://www.w3.org/1999/xhtml'
@@ -56,6 +63,17 @@ class BuiEvent {
this.clientX = this.x = raw.x
this.clientY = this.y = raw.y
this.button = raw.button
+ this.buttons = raw.buttons
+ this.pointerId = 1
+ this.pointerType = 'mouse'
+ this.isPrimary = true
+ this.pressure = raw.buttons ? 0.5 : 0
+ this.eventPhase = 0 // 1 capturing, 2 at the target, 3 bubbling
+ this.direction = raw.direction ?? undefined // `pressdrag`: 'east' ... 'southeast'
+ this.startX = raw.dx // `pressdrag`: where the press started
+ this.startY = raw.dy
+ this.scrollLeft = raw.dx // `scroll`: the new offsets
+ this.scrollTop = raw.dy
this.detail = raw.clickCount
// wheel: the DOM's, positive scrolls down; pan: pixels the content follows the fingers (x right,
// y down)
@@ -662,27 +680,50 @@ class Element extends Node {
if (t !== '' && t != null) this.appendChild(this._createText(isSignal(t) ? t : String(t)))
}
- /** Any event type; those BUI reports (`EVENT_BITS`) arrive from the UI thread. */
- addEventListener (type, fn) {
- const listeners = (this._listeners ??= new Map())
+ /** Any event type; those BUI reports (`EVENT_BITS`) arrive from the UI thread. `options`: `true` / `{ capture: true }`
+ * listens in the capture phase (ancestors first), `{ once: true }` removes the listener after its first call. */
+ addEventListener (type, fn, options) {
+ const capture = options === true || (options != null && typeof options === 'object' && options.capture === true)
+ const once = options != null && typeof options === 'object' && options.once === true
+ const listeners = (capture ? (this._capture ??= new Map()) : (this._listeners ??= new Map()))
let set = listeners.get(type)
- if (!set) listeners.set(type, (set = new Set()))
- set.add(fn)
+ if (!set) listeners.set(type, (set = new Map()))
+ if (!set.has(fn)) set.set(fn, once)
this._listen()
}
- removeEventListener (type, fn) {
- this._listeners?.get(type)?.delete(fn)
+ removeEventListener (type, fn, options) {
+ const capture = options === true || (options != null && typeof options === 'object' && options.capture === true)
+ ;(capture ? this._capture : this._listeners)?.get(type)?.delete(fn)
this._listen()
}
+ /** HTML `setPointerCapture`: the element keeps the pointer events (also out of it) until the button is released.
+ * Call it from a `pointerdown` / `mousedown` handler. */
+ setPointerCapture (_pointerId) { this._pointerCapture(true) }
+
+ releasePointerCapture (_pointerId) { this._pointerCapture(false) }
+
+ hasPointerCapture (_pointerId) { return (this._x?.captured ?? false) === true }
+
+ _pointerCapture (on) {
+ const w = this.ownerWindow
+ if (w === null || (this._x?.captured ?? false) === on) return
+ ;(this._x ??= {}).captured = on
+ this._listen() // it needs `lostpointercapture` to know when the host lets go
+ w._op(OP.CAPTURE, this.id, on ? 1 : 0)
+ }
+
_listen () {
let bits = 0
- if (this._listeners !== null) for (const [type, set] of this._listeners) if (set.size) bits |= EVENT_BITS[type] ?? 0
+ for (const map of [this._listeners, this._capture]) {
+ if (map != null) for (const [type, set] of map) if (set.size) bits = orBits(bits, EVENT_BITS[type] ?? 0)
+ }
+ if (this._x?.captured) bits = orBits(bits, EVENT_BITS.lostpointercapture)
if (bits !== this._bits) {
this._bits = bits
const w = this.ownerWindow
- if (w !== null) w._op(OP.LISTEN, this.id, bits)
+ if (w !== null) w._op(OP.LISTEN, this.id, bits % WORD, Math.floor(bits / WORD))
}
}
@@ -690,7 +731,7 @@ class Element extends Node {
win._op(OP.CREATE, this.id, win._s(this.localName))
const a = this._attrs
if (a !== null) for (let i = 0; i < a.length; i += 2) win._op(OP.SET_ATTR, this.id, win._s(a[i]), win._s(a[i + 1]))
- if (this._bits !== 0) win._op(OP.LISTEN, this.id, this._bits)
+ if (this._bits !== 0) win._op(OP.LISTEN, this.id, this._bits % WORD, Math.floor(this._bits / WORD))
const m = this._x?.motion
if (m) for (const k in m) win._motionOp(this.id, MOTION_PROPS[k], m[k])
}
@@ -708,6 +749,7 @@ class Element extends Node {
x.checked = raw.checked
x.number = raw.number
}
+ if (raw.kind === 'lostpointercapture' && this._x !== null) this._x.captured = false
this._propagate(new BuiEvent(raw, this))
}
@@ -721,18 +763,30 @@ class Element extends Node {
}
_propagate (e) {
- for (let n = this; n !== null; n = n.parentNode) {
- const set = n._listeners?.get(e.type)
- if (set && set.size) {
- e.currentTarget = n
- for (const fn of [...set]) {
- try { fn.call(n, e) } catch (err) { queueMicrotask(() => { throw err }) }
- if (e.immediatePropagationStopped) break
- }
+ // the target's ancestors, innermost first
+ const up = []
+ for (let n = this.parentNode; n !== null; n = n.parentNode) up.push(n)
+ const stopped = () => e.cancelBubble === true
+ const own = e instanceof BuiEvent // a DOM Event keeps its own phase
+ const run = (n, map, phase) => {
+ const set = map?.get(e.type)
+ if (!set || set.size === 0) return
+ e.currentTarget = n
+ if (own) e.eventPhase = phase
+ for (const [fn, once] of [...set]) {
+ if (once) set.delete(fn)
+ try { fn.call(n, e) } catch (err) { queueMicrotask(() => { throw err }) }
+ if (e.immediatePropagationStopped) break
}
- if (e.cancelBubble || !e.bubbles) break
}
+ // capture: from the root down to the target's parent, then at the target
+ for (let i = up.length - 1; i >= 0 && !stopped(); i--) run(up[i], up[i]._capture, 1)
+ if (!stopped()) run(this, this._capture, 2)
+ if (!stopped() && !e.immediatePropagationStopped) run(this, this._listeners, 2)
+ // bubble
+ if (e.bubbles) for (let i = 0; i < up.length && !stopped(); i++) run(up[i], up[i]._listeners, 3)
e.currentTarget = null
+ if (own) e.eventPhase = 0
}
/** Web Animations: `animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, easing: 'ease-out' })`,
@@ -750,9 +804,16 @@ class Element extends Node {
}
}
+function orBits (a, b) {
+ // a | b for bits above 31
+ const [al, ah, bl, bh] = [a % WORD, Math.floor(a / WORD), b % WORD, Math.floor(b / WORD)]
+ return ((al | bl) >>> 0) + ((ah | bh) >>> 0) * WORD
+}
+
// listeners (a Map), their native bits, and the rarely used extras (form
// state from events, the style object): on the prototype until an element has them
Element.prototype._listeners = null
+Element.prototype._capture = null
Element.prototype._bits = 0
Element.prototype._x = null
diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.ts
index 3c9fec7e..86a37411 100644
--- a/bindings/node/index.d.ts
+++ b/bindings/node/index.d.ts
@@ -43,8 +43,22 @@ export interface LayerShellOptions {
keyboard?: 'none' | 'exclusive' | 'on-demand'
}
-export type EventType = 'click' | 'mousedown' | 'mouseup' | 'mousemove' | 'mouseenter' | 'mouseleave' |
- 'wheel' | 'keydown' | 'keyup' | 'change' | 'input' | 'pinch' | 'rotate' | 'pan'
+export type EventType = 'click' | 'dblclick' | 'auxclick' | 'contextmenu' |
+ 'mousedown' | 'mouseup' | 'mousemove' | 'mouseenter' | 'mouseleave' | 'mouseover' | 'mouseout' |
+ 'pointerdown' | 'pointerup' | 'pointermove' | 'pointerenter' | 'pointerleave' | 'pointerover' | 'pointerout' |
+ 'pointercancel' | 'gotpointercapture' | 'lostpointercapture' |
+ 'wheel' | 'keydown' | 'keypress' | 'keyup' | 'focus' | 'blur' | 'focusin' | 'focusout' |
+ /** Blender's press-drag: a button held and the pointer moved past 3 pixels (once per press). */
+ 'pressdrag' | 'scroll' | 'change' | 'input' |
+ /** Touch screens and trackpads. */
+ 'pinch' | 'rotate' | 'pan'
+
+export interface ListenerOptions {
+ /** Listen while the event travels down to the target (ancestors first). */
+ capture?: boolean
+ /** Remove the listener after its first call. */
+ once?: boolean
+}
export class BuiEvent {
type: EventType
@@ -55,6 +69,22 @@ export class BuiEvent {
x: number
y: number
button: number
+ /** The buttons held (1 left, 2 right, 4 middle). */
+ buttons: number
+ pointerId: number
+ pointerType: 'mouse'
+ isPrimary: boolean
+ pressure: number
+ /** 1 capturing, 2 at the target, 3 bubbling. */
+ eventPhase: number
+ /** `pressdrag`: `'east'`, `'northeast'`, ... `'southeast'`. */
+ direction?: string
+ /** `pressdrag`: where the press started. */
+ startX: number
+ startY: number
+ /** `scroll`: the new offsets. */
+ scrollLeft: number
+ scrollTop: number
detail: number
/** `pan`: pixels the content follows the fingers, right (0 for other events). */
deltaX: number
@@ -294,8 +324,12 @@ export class Element extends Node {
toggleAttribute (name: string, force?: boolean): boolean
getAttributeNames (): string[]
/** Any type; BUI's own (`EventType`) arrive from the UI thread. */
- addEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: unknown): void
- removeEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: unknown): void
+ addEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: boolean | ListenerOptions): void
+ removeEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: boolean | ListenerOptions): void
+ /** Keep the pointer events (also out of the element) until the button is released; call it in `pointerdown`. */
+ setPointerCapture (pointerId?: number): void
+ releasePointerCapture (pointerId?: number): void
+ hasPointerCapture (pointerId?: number): boolean
/** Run the listeners for `event.type` here (and up, if it bubbles). */
dispatchEvent (event: { type: string, bubbles?: boolean }): boolean
/** Web Animations, run by the engine: `animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, easing: 'ease-out' })`.
diff --git a/bindings/node/index.js b/bindings/node/index.js
index cb0f1bb9..22d8430b 100644
--- a/bindings/node/index.js
+++ b/bindings/node/index.js
@@ -418,7 +418,7 @@ class App {
win._frame()
return
}
- if (raw.kind === 'focus' || raw.kind === 'blur') {
+ if ((raw.kind === 'focus' || raw.kind === 'blur') && raw.target === 0xffffffff) { // the window's own
win._emit(raw.kind)
return
}
diff --git a/bindings/node/test/native.test.js b/bindings/node/test/native.test.js
index 12016e55..47176bfd 100644
--- a/bindings/node/test/native.test.js
+++ b/bindings/node/test/native.test.js
@@ -238,3 +238,46 @@ test('touch screen and trackpad gestures: pinch, rotate and pan bubble with thei
assert.strictEqual(got.pan.at(-1).phase, 'end')
assert.ok(bubbled.length === got.pan.length && bubbled.every(Boolean), 'pan bubbles once through the JS tree')
})
+
+test('HTML events: capture phase, pointer events, capture of the pointer, dblclick (headless)', async (t) => {
+ const app = new App({ headless: true })
+ t.after(() => app.quit())
+ const win = app.window({ width: 300, height: 200 })
+ win.body.style = 'margin: 0'
+ const outer = win.createElement('div')
+ outer.style = { width: 200, height: 100, padding: 10 }
+ const inner = win.createElement('div')
+ inner.style = { width: 100, height: 50, backgroundColor: '#00f' }
+ outer.appendChild(inner)
+ win.body.appendChild(outer)
+ await inner.getBoundingClientRect()
+
+ const log = []
+ const tick = () => new Promise(resolve => setTimeout(resolve, 30))
+ outer.addEventListener('pointerdown', e => log.push(`outer capture ${e.eventPhase} ${e.target === inner}`), true)
+ outer.addEventListener('pointerdown', e => log.push(`outer bubble ${e.eventPhase}`))
+ inner.addEventListener('pointerdown', e => {
+ log.push(`inner ${e.eventPhase} ${e.pointerType}`)
+ inner.setPointerCapture(e.pointerId)
+ })
+ inner.addEventListener('pointermove', e => log.push(`inner move ${Math.round(e.x)}`))
+ inner.addEventListener('pointerup', () => log.push('inner up'))
+ inner.addEventListener('dblclick', e => log.push(`dblclick ${e.detail}`))
+ let once = 0
+ inner.addEventListener('click', () => once++, { once: true })
+ inner.addEventListener('pressdrag', e => log.push(`pressdrag ${e.direction}`))
+
+ win.mouseMove(30, 30)
+ win.mouseDown(30, 30)
+ await tick()
+ assert.deepStrictEqual(log.filter(x => !x.startsWith('inner move')).slice(0, 3), ['outer capture 1 true', 'inner 2 mouse', 'outer bubble 3'], 'capture first, then the target, then bubbling')
+ assert.ok(inner.hasPointerCapture(1), 'captured')
+ win.mouseMove(250, 150) // far outside the element
+ await tick()
+ assert.ok(log.includes('inner move 250'), 'a captured pointer is heard outside the element: ' + log)
+ assert.ok(log.includes('pressdrag east') || log.some(x => x.startsWith('pressdrag')), 'press-drag: ' + log)
+ win.mouseUp(250, 150)
+ await tick()
+ assert.ok(log.includes('inner up'), 'the release goes to the element that holds the pointer')
+ assert.ok(!inner.hasPointerCapture(1), 'released with the button')
+})
diff --git a/bindings/rust/blenderui-jsview/src/lib.rs b/bindings/rust/blenderui-jsview/src/lib.rs
index a75cd647..2e65e895 100644
--- a/bindings/rust/blenderui-jsview/src/lib.rs
+++ b/bindings/rust/blenderui-jsview/src/lib.rs
@@ -18,9 +18,9 @@ use blenderui::prelude::*;
pub mod motion;
pub mod shell;
-/// An event from a window (`kind`: click, mousedown, mouseup, mousemove,
-/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, pinch,
-/// rotate, pan, frame, close).
+/// An event from a window (`kind`: the DOM name of an `ev` bit, such as click,
+/// mousedown, pointermove, wheel, keydown, focus, scroll, pressdrag, change,
+/// input, pinch, rotate or pan; or frame, close).
#[derive(Clone, Debug, Default)]
pub struct Event {
pub kind: String,
@@ -32,6 +32,13 @@ pub struct Event {
/// 0 left, 1 middle, 2 right (DOM numbering).
pub button: u32,
pub click_count: u32,
+ /// The DOM `buttons` bits held (1 left, 2 right, 4 middle).
+ pub buttons: u32,
+ /// `pressdrag`: the compass direction; `pointer*`: the pointer type.
+ pub direction: Option,
+ /// `pressdrag`: where the press started; `scroll`: the scroll offsets.
+ pub dx: f64,
+ pub dy: f64,
/// `wheel`: lines (positive scrolls the content up); `pinch`: the scale change (0.1 = 10%
/// larger); `rotate`: degrees, positive counter-clockwise.
pub delta: f64,
@@ -52,6 +59,9 @@ pub struct Event {
pub values: Option>,
}
+/// `Event::target` of the window own `focus` and `blur` (an element gets its node).
+pub const WINDOW: u32 = u32::MAX;
+
/// Where a window's events go (called on the UI thread).
pub type Sink = Arc;
@@ -136,26 +146,49 @@ pub mod op {
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 LISTEN: i32 = 8; // id, event bits low 31, high bits (replaces)
pub const FREE: i32 = 9; // id
- pub const MOTION: i32 = 10; // id, which (motion::MotionProp::parse), index into the commit's motion props
+ pub const MOTION: i32 = 10; // id, which (motion::MotionProp::parse), index into the commit motion props
+ pub const CAPTURE: i32 = 11; // id, 1 hold the pointer for it / 0 let go
}
/// Event bits (`LISTEN`), matching `bindings/node/index.js`.
pub 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;
- pub const PINCH: u32 = 1024;
- pub const ROTATE: u32 = 2048;
- pub const PAN: u32 = 4096;
+ pub const CLICK: u64 = 1 << 0;
+ pub const MOUSE_DOWN: u64 = 1 << 1;
+ pub const MOUSE_UP: u64 = 1 << 2;
+ pub const MOUSE_MOVE: u64 = 1 << 3;
+ pub const HOVER: u64 = 1 << 4;
+ pub const WHEEL: u64 = 1 << 5;
+ pub const KEY_DOWN: u64 = 1 << 6;
+ pub const KEY_UP: u64 = 1 << 7;
+ pub const CHANGE: u64 = 1 << 8;
+ pub const INPUT: u64 = 1 << 9;
+ pub const PINCH: u64 = 1 << 10;
+ pub const ROTATE: u64 = 1 << 11;
+ pub const PAN: u64 = 1 << 12;
+ pub const DOUBLE_CLICK: u64 = 1 << 13;
+ pub const AUX_CLICK: u64 = 1 << 14;
+ pub const CONTEXT_MENU: u64 = 1 << 15;
+ pub const MOUSE_OVER: u64 = 1 << 16;
+ pub const MOUSE_OUT: u64 = 1 << 17;
+ pub const POINTER_DOWN: u64 = 1 << 18;
+ pub const POINTER_UP: u64 = 1 << 19;
+ pub const POINTER_MOVE: u64 = 1 << 20;
+ pub const POINTER_ENTER: u64 = 1 << 21;
+ pub const POINTER_LEAVE: u64 = 1 << 22;
+ pub const POINTER_OVER: u64 = 1 << 23;
+ pub const POINTER_OUT: u64 = 1 << 24;
+ pub const POINTER_CANCEL: u64 = 1 << 25;
+ pub const GOT_CAPTURE: u64 = 1 << 26;
+ pub const LOST_CAPTURE: u64 = 1 << 27;
+ pub const KEY_PRESS: u64 = 1 << 28;
+ pub const FOCUS: u64 = 1 << 29;
+ pub const BLUR: u64 = 1 << 30;
+ pub const FOCUS_IN: u64 = 1 << 31;
+ pub const FOCUS_OUT: u64 = 1 << 32;
+ pub const PRESS_DRAG: u64 = 1 << 33;
+ pub const SCROLL: u64 = 1 << 34;
}
// ==========================================================================
@@ -169,7 +202,7 @@ struct JsNode {
/// The `style` attribute, parsed once when set (renders reuse it).
style: Option>,
children: Vec,
- events: u32,
+ events: u64,
/// Motion's props (`initial`, `animate` ...), when it has any.
motion: Option>,
/// JavaScript removed it, and its `exit` animation runs first: the presence it goes with (0: none).
@@ -240,7 +273,7 @@ impl JsView {
}
fn apply(&mut self, ops: &[i32], strings: &[String], motion: &mut [Option],
- tags: &mut HashMap) {
+ tags: &mut HashMap, capture: &mut Vec<(i32, bool)>) {
let s = |k: i32| strings.get(k as usize).map(String::as_str).unwrap_or("");
let mut i = 0;
while i < ops.len() {
@@ -322,10 +355,14 @@ impl JsView {
i += 3;
}
op::LISTEN => {
- let bits = a(2) as u32;
+ let bits = u64::from(a(2) as u32) | (u64::from(a(3) as u32) << 31);
if let Some(n) = self.node(a(1)) {
n.events = bits;
}
+ i += 4;
+ }
+ op::CAPTURE => {
+ capture.push((a(1), a(2) != 0));
i += 3;
}
op::MOTION => {
@@ -426,7 +463,7 @@ impl JsView {
d.into_any_element()
}
- fn listeners(&self, mut d: Div, id: u32, bits: u32) -> Div {
+ fn listeners(&self, mut d: Div, id: u32, bits: u64) -> Div {
fn at(e: &mut Event, p: Point) {
(e.x, e.y) = (f64::from(p.x.0), f64::from(p.y.0));
}
@@ -468,14 +505,14 @@ impl JsView {
}
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);
+ at(&mut e, c.up.position);
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);
+ at(&mut e, m.position);
e.button = button(&m.button);
e.click_count = m.click_count as u32;
mods(&mut e, &m.modifiers);
@@ -483,14 +520,14 @@ impl JsView {
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);
+ at(&mut e, m.position);
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);
+ at(&mut e, m.position);
mods(&mut e, &m.modifiers);
});
on!(@ false, ev::HOVER, on_hover, |e, h| {
@@ -498,7 +535,7 @@ impl JsView {
});
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);
+ at(&mut e, w.position);
e.delta = w.delta as f64;
mods(&mut e, &w.modifiers);
});
@@ -548,6 +585,96 @@ impl JsView {
e.kind = "input".into();
(e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);
});
+ // the rest of HTML events, as tables: the Rust method, the DOM name
+ macro_rules! pointer {
+ ($($bit:ident, $method:ident, $name:expr;)*) => {$(
+ on!(ev::$bit, $method, |e, p| {
+ e.kind = $name.into();
+ at(&mut e, p.position);
+ e.button = p.button.as_ref().map_or(0, button);
+ e.buttons = u32::from(p.buttons);
+ e.click_count = p.click_count as u32;
+ e.direction = Some("mouse".into());
+ mods(&mut e, &p.modifiers);
+ });
+ )*};
+ }
+ pointer! {
+ POINTER_DOWN, on_pointer_down, "pointerdown";
+ POINTER_UP, on_pointer_up, "pointerup";
+ POINTER_MOVE, on_pointer_move, "pointermove";
+ POINTER_OVER, on_pointer_over, "pointerover";
+ POINTER_OUT, on_pointer_out, "pointerout";
+ POINTER_CANCEL, on_pointer_cancel, "pointercancel";
+ GOT_CAPTURE, on_got_pointer_capture, "gotpointercapture";
+ LOST_CAPTURE, on_lost_pointer_capture, "lostpointercapture";
+ }
+ on!(@ false, ev::POINTER_ENTER, on_pointer_enter, |e, p| {
+ e.kind = "pointerenter".into();
+ at(&mut e, p.position);
+ e.direction = Some("mouse".into());
+ });
+ on!(@ false, ev::POINTER_LEAVE, on_pointer_leave, |e, p| {
+ e.kind = "pointerleave".into();
+ at(&mut e, p.position);
+ e.direction = Some("mouse".into());
+ });
+ macro_rules! hover {
+ ($($bit:ident, $method:ident, $name:expr;)*) => {$(
+ on!(ev::$bit, $method, |e, m| {
+ e.kind = $name.into();
+ at(&mut e, m.position);
+ mods(&mut e, &m.modifiers);
+ });
+ )*};
+ }
+ hover! {
+ MOUSE_OVER, on_mouse_over, "mouseover";
+ MOUSE_OUT, on_mouse_out, "mouseout";
+ }
+ macro_rules! click {
+ ($($bit:ident, $method:ident, $name:expr;)*) => {$(
+ on!(ev::$bit, $method, |e, c| {
+ e.kind = $name.into();
+ at(&mut e, c.up.position);
+ e.button = button(&c.up.button);
+ e.click_count = c.down.click_count as u32;
+ mods(&mut e, &c.up.modifiers);
+ });
+ )*};
+ }
+ click! {
+ DOUBLE_CLICK, on_double_click, "dblclick";
+ AUX_CLICK, on_aux_click, "auxclick";
+ }
+ on!(ev::CONTEXT_MENU, on_context_menu, |e, c| {
+ e.kind = "contextmenu".into();
+ at(&mut e, c.position);
+ e.button = 2;
+ mods(&mut e, &c.modifiers);
+ });
+ on!(ev::KEY_PRESS, on_key_press, |e, k| {
+ e.kind = "keypress".into();
+ e.key = Some(k.keystroke.key.clone());
+ e.key_char = k.keystroke.key_char.clone();
+ mods(&mut e, &k.keystroke.modifiers);
+ });
+ on!(@ false, ev::FOCUS, on_focus, |e, _f| { e.kind = "focus".into(); });
+ on!(@ false, ev::BLUR, on_blur, |e, _f| { e.kind = "blur".into(); });
+ on!(ev::FOCUS_IN, on_focus_in, |e, _f| { e.kind = "focusin".into(); });
+ on!(ev::FOCUS_OUT, on_focus_out, |e, _f| { e.kind = "focusout".into(); });
+ on!(ev::PRESS_DRAG, on_press_drag, |e, p| {
+ e.kind = "pressdrag".into();
+ at(&mut e, p.position);
+ (e.dx, e.dy) = (p.start.x.0 as f64, p.start.y.0 as f64);
+ e.button = button(&p.button);
+ e.direction = Some(format!("{:?}", p.direction).to_lowercase());
+ mods(&mut e, &p.modifiers);
+ });
+ on!(@ false, ev::SCROLL, on_scroll, |e, sc| {
+ e.kind = "scroll".into();
+ (e.dx, e.dy) = (sc.offset.x.0 as f64, sc.offset.y.0 as f64);
+ });
d
}
}
@@ -597,7 +724,7 @@ pub fn init(cx: &mut App, sink: Sink) {
cx.on_window_activation(|id, active, cx| {
let Some(w) = cx.global::().by_native.get(&id.0).copied() else { return };
let kind = if active { "focus" } else { "blur" };
- cx.global::().0(Event { kind: kind.into(), window: w, ..Default::default() });
+ cx.global::().0(Event { kind: kind.into(), window: w, target: WINDOW, ..Default::default() });
});
cx.on_window_closed(|id, cx| {
let Some(w) = cx.global::().by_native.get(&id.0).copied() else { return };
@@ -665,8 +792,15 @@ pub fn commit(cx: &mut App, window: u32, ops: &[i32], strings: &[String], mut pr
}
}
let mut tags = std::mem::take(&mut cx.global_mut::().tags);
- handle.update(cx, |v, w, _| {
- v.apply(ops, strings, &mut props, &mut tags);
+ handle.update(cx, |v, w, app| {
+ let mut capture = Vec::new();
+ v.apply(ops, strings, &mut props, &mut tags, &mut capture);
+ for (id, on) in capture {
+ let Some(n) = v.nodes.get(&(id as u32)) else { continue };
+ // its key: an `id` attribute value, else "n" (as `build` gives it)
+ let key = n.attrs.iter().find(|(k, _)| k == "id").map_or_else(|| n.key.clone(), |(_, v)| v.clone());
+ if on { w.capture_pointer_for(app, &key) } else { w.release_pointer_capture(app) }
+ }
if !animated {
w.refresh(); // this window only
} else if !v.frame_scheduled {
diff --git a/bindings/rust/blenderui-macros/src/component.rs b/bindings/rust/blenderui-macros/src/component.rs
index 169817c9..bbd49b55 100644
--- a/bindings/rust/blenderui-macros/src/component.rs
+++ b/bindings/rust/blenderui-macros/src/component.rs
@@ -4,14 +4,17 @@
//! #[component]
//! fn profile(username: &str, likes: u32) {
//! let (n, set_n) = use_state(likes);
-//! rsx! { {username} " " {n()} }
+//! rsx! { {username.to_string()} " " {n()} }
//! }
//! // used as
//! ```
//!
//! Expands to a props struct named like the function, with an `IntoElement`
//! impl that runs the body in a component scope (hooks, context). `&str`
-//! props are stored as `String`; the body still sees `&str`.
+//! props are stored as `String`; the body still sees `&str`, and an element
+//! owns its text, so `{username}` needs `.to_string()`. For text shown as it
+//! is, take a `SharedString` prop: `` borrows the
+//! literal (no allocation) and `{username}` needs no conversion.
use proc_macro::{Delimiter, Group, TokenStream, TokenTree};
diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rs
index 9132b974..5c1ab101 100644
--- a/bindings/rust/blenderui-node/src/lib.rs
+++ b/bindings/rust/blenderui-node/src/lib.rs
@@ -45,6 +45,10 @@ pub struct BuiEvent {
/// 0 left, 1 middle, 2 right (DOM numbering).
pub button: u32,
pub click_count: u32,
+ pub buttons: u32,
+ pub direction: Option,
+ pub dx: f64,
+ pub dy: f64,
pub delta: f64,
pub delta_x: f64,
pub delta_y: f64,
@@ -66,8 +70,9 @@ impl From for BuiEvent {
fn from(e: view::Event) -> BuiEvent {
BuiEvent {
kind: e.kind, window: e.window, target: e.target, x: e.x, y: e.y, button: e.button,
- click_count: e.click_count, delta: e.delta, delta_x: e.delta_x, delta_y: e.delta_y,
- phase: e.phase.map(str::to_owned), key: e.key, key_char: e.key_char, value: e.value,
+ click_count: e.click_count, buttons: e.buttons, direction: e.direction, dx: e.dx, dy: e.dy, delta: e.delta,
+ delta_x: e.delta_x, delta_y: e.delta_y, phase: e.phase.map(str::to_owned), key: e.key, key_char: e.key_char,
+ value: e.value,
checked: e.checked, number: e.number, shift: e.shift, ctrl: e.ctrl, alt: e.alt, values: e.values,
}
}
diff --git a/bindings/rust/blenderui-qjs/src/lib.rs b/bindings/rust/blenderui-qjs/src/lib.rs
index eddb06c5..f9b86df6 100644
--- a/bindings/rust/blenderui-qjs/src/lib.rs
+++ b/bindings/rust/blenderui-qjs/src/lib.rs
@@ -331,6 +331,10 @@ fn event_object<'js>(ctx: &Ctx<'js>, e: view::Event) -> rquickjs::Result