@solidrt/core 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,4 +24,10 @@ for the element/prop model see `@solidrt/core/AGENTS.md`.
24
24
 
25
25
  ## Images and GPU
26
26
  - `image.tsx` - `createImage` (async value: fetch + decode + upload) read inside a `<Loading>` boundary and shown with `<texture>`.
27
- - `gpu-shader.tsx` - a GLSL fragment shader rendered to a texture, animated via `setShaderParams`.
27
+ - `gpu-shader.tsx` - a GLSL fragment shader rendered to a texture, animated via `setShaderParams`.
28
+
29
+ ## Vector graphics
30
+ - `svg.tsx` - `<svg src={...}>` draws a whole SVG *document string* (not HTML/JSX children); multi-color fills vs a `currentColor` icon recolored by the `color` prop. This is how to use existing icon libraries (Lucide, Heroicons, etc.) - hand their SVG source to `src`.
31
+
32
+ ## Bundling assets
33
+ - `binary-import.tsx` - `import bytes from "./file" with { type: "binary" }` inlines a file's bytes into the bundle as a `Uint8Array` (combine with `image.tsx` to display an inlined image). `with { type: "text" }` works the same way for a string.
@@ -0,0 +1,26 @@
1
+ // Importing a file with `with { type: "binary" }` inlines its bytes into the
2
+ // bundle as a Uint8Array. The data travels inside the compiled bytecode, so it
3
+ // is available synchronously - no runtime fetch, works offline. Reach for this
4
+ // with small assets you want baked in; for large or many assets prefer a string
5
+ // URL source loaded at runtime instead.
6
+ //
7
+ // This example shows only the binary import itself: it reports the imported
8
+ // file's length and leading bytes. What you do with the bytes afterwards is a
9
+ // separate concern - e.g. hand them to createImage to decode and display an
10
+ // image (see image.tsx), or to decodeImage/createTexture for manual control.
11
+ import { render } from "@solidrt/core"
12
+ import bytes from "./logo.png" with { type: "binary" }
13
+
14
+ // The PNG magic number: 89 50 4e 47 ... - proof the real bytes are inlined.
15
+ let head = Array.from(bytes.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join(" ")
16
+
17
+ function App() {
18
+ return (
19
+ <window alignItems="center" justifyContent="center" gap={8}>
20
+ <text fontSize={18} color="#e6e6e6">{bytes.length} bytes inlined</text>
21
+ <text color="#888">starts with {head}</text>
22
+ </window>
23
+ )
24
+ }
25
+
26
+ render(() => <App />)
Binary file
@@ -0,0 +1,45 @@
1
+ // <svg> draws a whole SVG *document* passed as a STRING in the `src` prop. This
2
+ // is not HTML: there are no per-element <rect>/<circle>/<path> JSX children to
3
+ // nest. You hand it the SVG source text and usvg parses it (CSS, transforms,
4
+ // defs/use, gradients, clips) into a flat path tree the element renders. So an
5
+ // SVG is a value (a string you import, fetch, or inline), not markup you author
6
+ // inline with JSX.
7
+ //
8
+ // width/height set the drawn box (percentages work too); a multi-color document
9
+ // keeps each shape's own fill, while a monochrome icon using stroke/fill
10
+ // "currentColor" is recolored by the host `color` prop. For per-shape authored
11
+ // or animated vector art, compose <d-path> instead of this document layer.
12
+ //
13
+ // This is how you use an existing icon library (Lucide, Heroicons, Feather,
14
+ // Material, etc.): those ship SVG source, so import/inline the icon string and
15
+ // hand it to `src`. The `currentColor` convention they follow means the `color`
16
+ // prop recolors them, exactly as `currentColor` would in a browser.
17
+ import { render } from "@solidrt/core"
18
+
19
+ // Multi-color document: each shape carries its own fill, no host color needed.
20
+ const HOUSE = `
21
+ <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
22
+ <rect x="20" y="45" width="60" height="45" fill="#457b9d"/>
23
+ <path d="M10 50 L50 15 L90 50 Z" fill="#e63946"/>
24
+ <rect x="42" y="62" width="16" height="28" fill="#f1faee"/>
25
+ <circle cx="50" cy="35" r="6" fill="#ffd166"/>
26
+ </svg>`
27
+
28
+ // Monochrome icon (Lucide arrow-right) drawn with currentColor, recolored below.
29
+ const ARROW = `
30
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
31
+ stroke-linecap="round" stroke-linejoin="round">
32
+ <path d="M5 12h14"/>
33
+ <path d="M12 5l7 7-7 7"/>
34
+ </svg>`
35
+
36
+ function App() {
37
+ return (
38
+ <window justifyContent="center" alignItems="center" flexDirection="row" gap={32}>
39
+ <svg width={120} height={120} src={HOUSE} />
40
+ <svg width={120} height={120} src={ARROW} color="#4f8cff" />
41
+ </window>
42
+ )
43
+ }
44
+
45
+ render(() => <App />)
package/jsx-runtime.d.ts CHANGED
@@ -8,13 +8,14 @@ import type {
8
8
  TextProps,
9
9
  TextureProps,
10
10
  AudioProps,
11
- LayoutProps
11
+ LayoutProps,
12
+ Element as CoreElement,
13
+ ElementChildrenAttribute as CoreElementChildrenAttribute
12
14
  } from "./src/types"
13
- import type { JSX as SolidJSX } from "@solidjs/signals"
14
15
 
15
16
  export namespace JSX {
16
- type Element = SolidJSX.Element
17
- type ElementChildrenAttribute = SolidJSX.ElementChildrenAttribute
17
+ type Element = CoreElement
18
+ type ElementChildrenAttribute = CoreElementChildrenAttribute
18
19
 
19
20
  // Return type is unconstrained: a ref callback's return value is ignored, so
20
21
  // an arrow like `ref={n => (this.node = n)}` (which returns the assignment)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidrt/core",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "license": "MIT",
5
5
  "author": "Antoine van Wel",
6
6
  "type": "module",
@@ -0,0 +1,48 @@
1
+ import { env } from "./environment"
2
+
3
+ // Capabilities: what interactions are possible in the current environment.
4
+ // Derived from Environment State on every read - computed, never stored - so
5
+ // they are reactive wherever env is. Capabilities describe what is possible,
6
+ // not how the UI should behave; behavior lives in the policy layer on top.
7
+ //
8
+ // Device presence wins when the runtime reports it (so unplugging the mouse
9
+ // drops hover); the traffic-inferred seen-flags are the fallback for runtimes
10
+ // without device enumeration.
11
+
12
+ export type WindowSizeClass = "compact" | "medium" | "expanded"
13
+
14
+ export type Capabilities = {
15
+ /** A pointer can rest over content without pressing (mouse/trackpad). */
16
+ hover: boolean
17
+ /** Pixel-precise pointing (mouse/trackpad), as opposed to a finger. */
18
+ precisePointer: boolean
19
+ /** Direct touch input. */
20
+ touch: boolean
21
+ /** Hardware-key navigation (tab/arrow traversal, shortcuts). */
22
+ keyboardNav: boolean
23
+ /** How much horizontal room the window offers (Material breakpoints). */
24
+ windowSizeClass: WindowSizeClass
25
+ }
26
+
27
+ // Material 3 width breakpoints, in logical pixels.
28
+ const MEDIUM_MIN_WIDTH = 600
29
+ const EXPANDED_MIN_WIDTH = 840
30
+
31
+ export let capabilities: Capabilities = {
32
+ get hover() {
33
+ return env.inputDevices?.mouse ?? env.mouseSeen
34
+ },
35
+ get precisePointer() {
36
+ return env.inputDevices?.mouse ?? env.mouseSeen
37
+ },
38
+ get touch() {
39
+ return env.inputDevices?.touch ?? env.touchSeen
40
+ },
41
+ get keyboardNav() {
42
+ return env.inputDevices?.keyboard ?? env.keyboardSeen
43
+ },
44
+ get windowSizeClass(): WindowSizeClass {
45
+ let w = env.windowSize.width
46
+ return w >= EXPANDED_MIN_WIDTH ? "expanded" : w >= MEDIUM_MIN_WIDTH ? "medium" : "compact"
47
+ },
48
+ }
@@ -0,0 +1,155 @@
1
+ import { createSignal } from "@solidjs/signals"
2
+ import { on } from "srt:events"
3
+ import { windowSize, safeArea, displayScale, windowFocused, keyboardHeight } from "./window"
4
+
5
+ // Environment State: reactive facts about the current execution environment.
6
+ //
7
+ // Device presence comes from the runtime's sticky "inputDevices" event (init +
8
+ // hotplug). Runtimes that do not emit it leave `inputDevices` undefined, and
9
+ // the seen-flags below act as the fallback: a pointer type or key press has
10
+ // been seen this session. Seen-flags only ever go from false to true, so a
11
+ // capability derived from them can appear mid-session (e.g. the first mouse
12
+ // move) but never flickers away.
13
+
14
+ /** Connected input device classes, as reported by the runtime. */
15
+ export interface InputDevices {
16
+ keyboard: boolean
17
+ mouse: boolean
18
+ touch: boolean
19
+ }
20
+
21
+ export type SystemTheme = "dark" | "light" | "unknown"
22
+
23
+ export type Orientation = "portrait" | "portraitFlipped" | "landscape" | "landscapeFlipped" | "unknown"
24
+
25
+ let devicesAccessor: (() => InputDevices | undefined) | undefined
26
+
27
+ function ensureDevicesState() {
28
+ if (devicesAccessor) return
29
+ let [devices, setDevices] = createSignal<InputDevices | undefined>(undefined)
30
+ // Sticky: the current state replays on subscribe, so the first read already
31
+ // sees it on runtimes that report devices.
32
+ on("inputDevices", (d: InputDevices) => {
33
+ setDevices({ keyboard: !!d.keyboard, mouse: !!d.mouse, touch: !!d.touch })
34
+ })
35
+ devicesAccessor = devices
36
+ }
37
+
38
+ let systemThemeAccessor: (() => SystemTheme) | undefined
39
+
40
+ function ensureSystemThemeState() {
41
+ if (systemThemeAccessor) return
42
+ let [theme, setTheme] = createSignal<SystemTheme>("unknown")
43
+ on("systemTheme", (e: { theme?: SystemTheme }) => setTheme(e.theme ?? "unknown"))
44
+ systemThemeAccessor = theme
45
+ }
46
+
47
+ let orientationAccessor: (() => Orientation) | undefined
48
+
49
+ function ensureOrientationState() {
50
+ if (orientationAccessor) return
51
+ let [orientation, setOrientation] = createSignal<Orientation>("unknown")
52
+ on("displayOrientation", (e: { orientation?: Orientation }) => {
53
+ setOrientation(e.orientation ?? "unknown")
54
+ })
55
+ orientationAccessor = orientation
56
+ }
57
+
58
+ let mouseSeenAccessor: (() => boolean) | undefined
59
+ let touchSeenAccessor: (() => boolean) | undefined
60
+
61
+ function ensurePointerState() {
62
+ if (mouseSeenAccessor) return
63
+ let [mouse, setMouse] = createSignal(false)
64
+ let [touch, setTouch] = createSignal(false)
65
+ let sawMouse = false
66
+ let sawTouch = false
67
+ let unsubs: (() => void)[] = []
68
+ let note = (e: { pointerType?: string }) => {
69
+ if (e.pointerType === "mouse" && !sawMouse) {
70
+ sawMouse = true
71
+ setMouse(true)
72
+ } else if (e.pointerType === "touch" && !sawTouch) {
73
+ sawTouch = true
74
+ setTouch(true)
75
+ }
76
+ // Both types observed: nothing left to learn, stop listening.
77
+ if (sawMouse && sawTouch) for (let u of unsubs) u()
78
+ }
79
+ unsubs.push(on("pointerMove", note), on("pointerDown", note))
80
+ mouseSeenAccessor = mouse
81
+ touchSeenAccessor = touch
82
+ }
83
+
84
+ let keyboardSeenAccessor: (() => boolean) | undefined
85
+
86
+ function ensureKeyboardState() {
87
+ if (keyboardSeenAccessor) return
88
+ let [keyboard, setKeyboard] = createSignal(false)
89
+ // Soft keyboards also deliver some keydowns (Backspace, Return), so this can
90
+ // read true on a touch-only device once the user types in a field. Only a
91
+ // fallback: capabilities prefer runtime-reported device presence.
92
+ let unsub = on("keydown", () => {
93
+ setKeyboard(true)
94
+ unsub()
95
+ })
96
+ keyboardSeenAccessor = keyboard
97
+ }
98
+
99
+ /**
100
+ * Reactive Environment State: what the framework observes about where it is
101
+ * running. Read properties inside a tracked scope (JSX, memo, effect) to re-run
102
+ * when they change. Behavior decisions should go through `capabilities` and the
103
+ * policy layer; read `env` directly only when the raw fact itself is needed.
104
+ */
105
+ export let env = {
106
+ get windowSize() {
107
+ return windowSize()
108
+ },
109
+ get safeArea() {
110
+ return safeArea()
111
+ },
112
+ get displayScale() {
113
+ return displayScale()
114
+ },
115
+ get windowFocused() {
116
+ return windowFocused()
117
+ },
118
+ get keyboardHeight() {
119
+ return keyboardHeight()
120
+ },
121
+ /**
122
+ * Connected input device classes, or undefined until the runtime reports
123
+ * them (it does so at startup, so undefined normally means the runtime has
124
+ * no device enumeration).
125
+ */
126
+ get inputDevices(): InputDevices | undefined {
127
+ ensureDevicesState()
128
+ return devicesAccessor!()
129
+ },
130
+ /** The OS-level dark/light preference. */
131
+ get systemTheme(): SystemTheme {
132
+ ensureSystemThemeState()
133
+ return systemThemeAccessor!()
134
+ },
135
+ /** Orientation of the display the window is on. */
136
+ get orientation(): Orientation {
137
+ ensureOrientationState()
138
+ return orientationAccessor!()
139
+ },
140
+ /** A mouse (or trackpad) pointer has produced events this session. */
141
+ get mouseSeen(): boolean {
142
+ ensurePointerState()
143
+ return mouseSeenAccessor!()
144
+ },
145
+ /** A touch pointer has produced events this session. */
146
+ get touchSeen(): boolean {
147
+ ensurePointerState()
148
+ return touchSeenAccessor!()
149
+ },
150
+ /** A key press has been delivered this session. */
151
+ get keyboardSeen(): boolean {
152
+ ensureKeyboardState()
153
+ return keyboardSeenAccessor!()
154
+ },
155
+ }
package/src/image.ts CHANGED
@@ -56,7 +56,7 @@ export function createImage(src: ImageSource | (() => ImageSource)): () => numbe
56
56
  // If the source changed while we were loading, this run is superseded. Skip
57
57
  // the GPU upload and stay pending: a texture created here would leak, since
58
58
  // superseded async runs are not otherwise cleaned up. The newer run wins.
59
- if (mine !== generation) throw new NotReadyError()
59
+ if (mine !== generation) throw new NotReadyError(source)
60
60
 
61
61
  let { data, width, height } = decodeImage(bytes)
62
62
  holder.id = createTexture(data, width, height)
package/src/index.ts CHANGED
@@ -4,7 +4,12 @@ export type { BoundingBox } from "./core"
4
4
  export { parseColor, createLinearGradient, createRadialGradient } from "./color"
5
5
  export type { Gradient, GradientStop } from "./color"
6
6
  export { onFrame, onLayout, onResize, onWindowFocus, onWindowBlur } from "./window"
7
+ export { setPointerCapture, releasePointerCapture } from "./window"
7
8
  export { windowSize, safeArea, displayScale, windowFocused, keyboardHeight } from "./window"
9
+ export { env } from "./environment"
10
+ export type { InputDevices, SystemTheme, Orientation } from "./environment"
11
+ export { capabilities } from "./capabilities"
12
+ export type { Capabilities, WindowSizeClass } from "./capabilities"
8
13
  export { createTexture } from "./gpu"
9
14
  export { createImage, decodeImage } from "./image"
10
15
  export type { DecodedImage, ImageSource } from "./image"
package/src/renderer.ts CHANGED
@@ -30,9 +30,42 @@ function createProxyNode(elementType: ElementType): ProxyNode {
30
30
  return node
31
31
  }
32
32
 
33
- // Detaches `node` from `parent` and destroys it (and all descendants) on both
34
- // the JS and native sides. Hoisted out of the renderer config so createPortal
35
- // can reuse it (createRenderer does not return its removeNode hook).
33
+ // Nodes detached this tick and awaiting the destroy sweep, keyed by id so a
34
+ // re-insert can cancel one. See removeNode / flushDestroy.
35
+ let pendingDestroy = new Map<number, ProxyNode>()
36
+ let destroyScheduled = false
37
+
38
+ // Frees a detached node and its subtree on both sides. Descendants that were
39
+ // moved out (their parent no longer points here) are left alone. Clear focus
40
+ // before dropping handlers so onBlur still fires for a focused descendant.
41
+ function destroyNode(node: ProxyNode): void {
42
+ tree.destroyNode(node.id)
43
+ let cleanup = (n: ProxyNode) => {
44
+ for (let child of n.children) if (child.parent === n) cleanup(child)
45
+ if (n.id === getFocusedNodeId()) setFocus(null)
46
+ nodes.delete(n.id)
47
+ cleanupNodeHandlers(n.id)
48
+ }
49
+ cleanup(node)
50
+ }
51
+
52
+ // End-of-tick sweep: destroy every still-detached pending node. A node that was
53
+ // re-inserted this tick had its entry removed by insertNode (it moved, not
54
+ // died); one still parentless here is genuinely gone.
55
+ function flushDestroy(): void {
56
+ destroyScheduled = false
57
+ let batch = pendingDestroy
58
+ pendingDestroy = new Map()
59
+ for (let node of batch.values()) {
60
+ if (node.parent === undefined) destroyNode(node)
61
+ }
62
+ }
63
+
64
+ // Detaches `node` from `parent`, keeping the subtree alive so it can be
65
+ // re-inserted elsewhere (a move) - matching DOM removeChild. Destruction is
66
+ // deferred to an end-of-tick sweep; if nothing re-attaches the node by then it
67
+ // is freed. Hoisted out of the renderer config so createPortal can reuse it
68
+ // (createRenderer does not return its removeNode hook).
36
69
  function removeNode(parent: ProxyNode, node: ProxyNode): void {
37
70
  if (!node || !parent) return
38
71
 
@@ -45,17 +78,13 @@ function removeNode(parent: ProxyNode, node: ProxyNode): void {
45
78
  }
46
79
  node.parent = undefined
47
80
 
48
- tree.deleteNode(parent.id, node.id)
81
+ tree.detachNode(parent.id, node.id)
49
82
 
50
- // Recursively clean up node and all descendants. Clear focus before
51
- // dropping handlers so onBlur still fires for a focused descendant.
52
- let cleanup = (n: ProxyNode) => {
53
- for (let child of n.children) cleanup(child)
54
- if (n.id === getFocusedNodeId()) setFocus(null)
55
- nodes.delete(n.id)
56
- cleanupNodeHandlers(n.id)
83
+ pendingDestroy.set(node.id, node)
84
+ if (!destroyScheduled) {
85
+ destroyScheduled = true
86
+ Promise.resolve().then(flushDestroy)
57
87
  }
58
- cleanup(node)
59
88
  }
60
89
 
61
90
  export let {
@@ -123,6 +152,10 @@ export let {
123
152
  insertNode: (parent: ProxyNode, node: ProxyNode, anchor?: ProxyNode): void => {
124
153
  if (!node) return
125
154
 
155
+ // A re-inserted node is being moved, not destroyed: cancel its pending
156
+ // destroy so the end-of-tick sweep leaves it (and its subtree) alone.
157
+ pendingDestroy.delete(node.id)
158
+
126
159
  if (parent) {
127
160
  node.parent = parent
128
161
 
@@ -0,0 +1,52 @@
1
+ // Lattice runner builtin modules (the "srt:*" surface). These are ambient
2
+ // module declarations, so they live in this global-script .d.ts (no top-level
3
+ // import/export) rather than in types.d.ts: an ambient `declare module` only
4
+ // becomes globally visible to consumers from a non-module declaration file.
5
+
6
+ declare module "*.svg" {
7
+ const content: string
8
+ export default content
9
+ }
10
+
11
+ // Binary asset imports: `import data from "./pic.png" with { type: "binary" }`.
12
+ // The bundler inlines the file's bytes as a Uint8Array (see packages/cli
13
+ // bundler `binaryImport`); feed it straight into createImage/decodeImage.
14
+ declare module "*.png" {
15
+ const bytes: Uint8Array
16
+ export default bytes
17
+ }
18
+ declare module "*.jpg" {
19
+ const bytes: Uint8Array
20
+ export default bytes
21
+ }
22
+ declare module "*.jpeg" {
23
+ const bytes: Uint8Array
24
+ export default bytes
25
+ }
26
+
27
+ // UI event bus (lattice), provided by the runtime as a builtin module.
28
+ // on/once return an unsubscribe function.
29
+ declare module "srt:events" {
30
+ export function on(event: string, callback: (data: any) => void): () => void
31
+ export function once(event: string, callback: (data: any) => void): () => void
32
+ }
33
+
34
+ // Dev-server control surface (lattice). Present only in dev/go builds; in other
35
+ // builds `available` is false and the functions are no-ops.
36
+ declare module "srt:dev" {
37
+ export const available: boolean
38
+ export const canDiscover: boolean
39
+ export const recents: string[]
40
+ export function connect(address: string): void
41
+ export function discover(): void
42
+ export function stop(): void
43
+ }
44
+
45
+ // Frame draw (lattice runner). renderFrame() synchronously renders the current
46
+ // frame: layout, the postLayout hook, paint and hover refresh, then builds and
47
+ // submits the display list. To schedule a future frame instead, use
48
+ // requestFrame() from "flux:rendertree". The tree-building surface itself is
49
+ // "flux:rendertree" (from @solidrt/flux-types).
50
+ declare module "srt:render" {
51
+ export function renderFrame(): void
52
+ }
package/src/types.d.ts CHANGED
@@ -1,34 +1,12 @@
1
1
  /// <reference types="@solidrt/flux-types" />
2
+ /// <reference path="./runtime-modules.d.ts" />
2
3
 
3
- import type { JSX as SolidJSX } from "@solidjs/signals"
4
4
  import type { Gradient } from "./color"
5
+ import type { Element } from "solid-js"
5
6
 
6
- // UI event bus (lattice), provided by the runtime as a builtin module.
7
- // on/once return an unsubscribe function.
8
- declare module "srt:events" {
9
- export function on(event: string, callback: (data: any) => void): () => void
10
- export function once(event: string, callback: (data: any) => void): () => void
11
- }
12
-
13
- // Dev-server control surface (lattice). Present only in dev/go builds; in other
14
- // builds `available` is false and the functions are no-ops.
15
- declare module "srt:dev" {
16
- export const available: boolean
17
- export const canDiscover: boolean
18
- export const recents: string[]
19
- export function connect(address: string): void
20
- export function discover(): void
21
- export function stop(): void
22
- }
23
-
24
- // Frame draw (lattice runner). renderFrame() synchronously renders the current
25
- // frame: layout, the postLayout hook, paint and hover refresh, then builds and
26
- // submits the display list. To schedule a future frame instead, use
27
- // requestFrame() from "flux:rendertree". The tree-building surface itself is
28
- // "flux:rendertree" (from @solidrt/flux-types).
29
- declare module "srt:render" {
30
- export function renderFrame(): void
31
- }
7
+ // The "srt:*" lattice runner modules are declared in ./runtime-modules.d.ts
8
+ // (referenced above) - ambient `declare module` only reaches consumers from a
9
+ // non-module declaration file, and this file is a module.
32
10
 
33
11
  declare global {
34
12
  let image: {
@@ -48,7 +26,16 @@ declare global {
48
26
  }
49
27
  }
50
28
 
51
- type Children = SolidJSX.Element
29
+ // JSX value model. The element type is solid-js's (its control-flow components
30
+ // like <For> return it, so JSX.Element must match). @solidjs/signals ships no
31
+ // JSX namespace and solid-js defines no ElementChildrenAttribute, so we supply
32
+ // that here - its single key tells TS which prop receives JSX children.
33
+ export type { Element }
34
+ export interface ElementChildrenAttribute {
35
+ children: {}
36
+ }
37
+
38
+ type Children = Element
52
39
 
53
40
  interface FlexboxProps {
54
41
  gap?: number
@@ -166,6 +153,10 @@ export interface PointerEvent {
166
153
  ctrlKey: boolean
167
154
  altKey: boolean
168
155
  metaKey: boolean
156
+ // Stops the event from reaching ancestor handlers. Events dispatch leaf->root
157
+ // (bubbling), so calling this in a child prevents the enclosing node from
158
+ // seeing it (e.g. a slider claiming a drag so an ancestor scroller ignores it).
159
+ stopPropagation: () => void
169
160
  }
170
161
 
171
162
  export interface WheelEvent extends PointerEvent {
package/src/window.ts CHANGED
@@ -4,6 +4,28 @@ import { renderFrame } from "srt:render"
4
4
  import { on, once } from "srt:events"
5
5
  import { getEventHandler, getFocusedNodeId, setFocus } from "./core"
6
6
 
7
+ // ------ Pointer capture -----------------
8
+
9
+ // Active pointer captures, pointerId -> nodeId. While a pointer is captured, its
10
+ // move/up events dispatch straight to the captured node (bypassing hit testing),
11
+ // so a drag keeps working when the pointer drifts off the element. Modeled on the
12
+ // web setPointerCapture; capture auto-releases on pointerUp.
13
+ let pointerCaptures = new Map<number, number>()
14
+
15
+ /**
16
+ * Routes all further move/up events for `pointerId` to `nodeId` until release,
17
+ * regardless of what is under the pointer. Call from a pointerdown handler to own
18
+ * a drag (e.g. a slider). Auto-releases on the matching pointerup.
19
+ */
20
+ export function setPointerCapture(nodeId: number, pointerId: number) {
21
+ pointerCaptures.set(pointerId, nodeId)
22
+ }
23
+
24
+ /** Ends a capture early. Not needed for the common case (pointerup releases it). */
25
+ export function releasePointerCapture(pointerId: number) {
26
+ pointerCaptures.delete(pointerId)
27
+ }
28
+
7
29
  // ------ Animation frames ----------------
8
30
 
9
31
  let nextFrameId = 1
@@ -201,12 +223,24 @@ export function attachWindow(_nodeId: number) {
201
223
  runFrame(time * 1000, frame)
202
224
  })
203
225
 
226
+ // Dispatch an event to every node on the hit path, leaf->root (bubbling), so
227
+ // a child handler can call e.stopPropagation() to keep the event from
228
+ // reaching its ancestors. `targets` arrives root->leaf, hence the reverse.
229
+ let bubble = (targets: number[], handler: string, e: any) => {
230
+ let stopped = false
231
+ e.stopPropagation = () => {
232
+ stopped = true
233
+ }
234
+ for (let i = targets.length - 1; i >= 0; i--) {
235
+ getEventHandler(targets[i]!, handler)?.(e)
236
+ if (stopped) break
237
+ }
238
+ }
239
+
204
240
  unsubDown = on(
205
241
  "pointerDown",
206
242
  ({ targets, ...e }: { targets: number[]; [k: string]: any }) => {
207
- for (let nodeId of targets) {
208
- getEventHandler(nodeId, "onPointerDown")?.(e)
209
- }
243
+ bubble(targets, "onPointerDown", e)
210
244
  // Outside-tap blur. Read focus AFTER per-node handlers so a tap that
211
245
  // moves focus to a new node is not immediately blurred again.
212
246
  let focused = getFocusedNodeId()
@@ -217,42 +251,61 @@ export function attachWindow(_nodeId: number) {
217
251
  )
218
252
 
219
253
  unsubUp = on("pointerUp", ({ targets, ...e }: { targets: number[]; [k: string]: any }) => {
220
- for (let nodeId of targets) {
221
- getEventHandler(nodeId, "onPointerUp")?.(e)
254
+ let captured = pointerCaptures.get(e.pointerId)
255
+ if (captured != null) {
256
+ // Deliver to the captured node, then release (web auto-release on up).
257
+ e.stopPropagation = () => {}
258
+ getEventHandler(captured, "onPointerUp")?.(e)
259
+ pointerCaptures.delete(e.pointerId)
260
+ return
222
261
  }
262
+ bubble(targets, "onPointerUp", e)
223
263
  })
224
264
 
225
265
  unsubMove = on(
226
266
  "pointerMove",
227
267
  ({ targets, ...e }: { targets: number[]; [k: string]: any }) => {
228
- for (let nodeId of targets) {
229
- getEventHandler(nodeId, "onPointerMove")?.(e)
268
+ let captured = pointerCaptures.get(e.pointerId)
269
+ if (captured != null) {
270
+ // Captured drags get moves anywhere over the window, bypassing hit test.
271
+ e.stopPropagation = () => {}
272
+ getEventHandler(captured, "onPointerMove")?.(e)
273
+ return
230
274
  }
275
+ bubble(targets, "onPointerMove", e)
231
276
  },
232
277
  )
233
278
 
279
+ // Enter/leave keep their hover-diff order (already leaf->root for leave,
280
+ // root->leaf for enter), but still honor stopPropagation for a consistent
281
+ // event shape.
282
+ let dispatchOrdered = (targets: number[], handler: string, e: any) => {
283
+ let stopped = false
284
+ e.stopPropagation = () => {
285
+ stopped = true
286
+ }
287
+ for (let nodeId of targets) {
288
+ getEventHandler(nodeId, handler)?.(e)
289
+ if (stopped) break
290
+ }
291
+ }
292
+
234
293
  unsubEnter = on(
235
294
  "pointerEnter",
236
295
  ({ targets, ...e }: { targets: number[]; [k: string]: any }) => {
237
- for (let nodeId of targets) {
238
- getEventHandler(nodeId, "onPointerEnter")?.(e)
239
- }
296
+ dispatchOrdered(targets, "onPointerEnter", e)
240
297
  },
241
298
  )
242
299
 
243
300
  unsubLeave = on(
244
301
  "pointerLeave",
245
302
  ({ targets, ...e }: { targets: number[]; [k: string]: any }) => {
246
- for (let nodeId of targets) {
247
- getEventHandler(nodeId, "onPointerLeave")?.(e)
248
- }
303
+ dispatchOrdered(targets, "onPointerLeave", e)
249
304
  },
250
305
  )
251
306
 
252
307
  unsubWheel = on("wheel", ({ targets, ...e }: { targets: number[]; [k: string]: any }) => {
253
- for (let nodeId of targets) {
254
- getEventHandler(nodeId, "onWheel")?.(e)
255
- }
308
+ bubble(targets, "onWheel", e)
256
309
  })
257
310
 
258
311
  unsubKeyDown = on("keydown", (e: any) => {