sparkles:input — Feature Requirements (INP)
Status: partial — the vocabulary, tier ladder, terminal/GPU adapters and input capability declarations are shipped; widget tier declarations and the native pointer grab remain open · Date: 2026-08-05 · Scope: libs/input — the abstract, capability-tiered input vocabulary shared by every sparkles:ui target, and the contracts backend adapters satisfy.
Design & rationale
Interaction is the other half of "one definition, three targets". It previously diverged: the terminal had a private SGR-mouse/key model, the GPU host polled its windowing library directly inside the frame loop, and each interactive backend hand-rolled hit testing. The shared vocabulary and adapters now translate both native sources into the same values; the remaining target differences are declared capabilities, not competing semantic models.
sparkles:input fixes the shape rather than the symptom: events are values, in one vocabulary, in a package both the toolkit and the terminal library can depend on. Value-based notification is also what the architecture catalog prescribes over callback webs.
The native sparkles:wsi boundary is intentionally richer than this toolkit vocabulary: it preserves logical and physical positions, physical/logical keys, IME pre-edit, scroll source/phase, and native output identity. The ui-app adapter converts that lossless WindowEvent once into these cell-space application values. Shared PointerShape, geometry aliases, cell metrics, and conversion helpers live here so WSI, SDL and raylib producers cannot drift, but platform window lifecycle and raw handles do not.
Why a capability ladder
The three targets are not equally capable, and the binding constraint is pure-CSS HTML: static output can express hover, focus and toggling with no script, but cannot express a drag. Rather than let that degrade silently, the model is explicitly tiered, and a widget declares the tier it needs.
| Tier | Interactions | Served by |
|---|---|---|
| 0 | hover, focus, toggle/checked, disclosure | every target, including pure-CSS HTML (:hover, :focus-within, :checked, <details>) |
| 1 | key events, text input, pointer press/release/drag, wheel | interactive targets (GUI, TUI) |
| 2 | sub-cell pointer precision, continuous drag, time-based effects | pixel targets only |
This makes the "prefer pure CSS, add script only when unavoidable" rule checkable — the HTML emitter can refuse to silently drop a tier-1 interaction — instead of aspirational.
Event model (INP1–INP4)
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP1 | Input must be modelled as values in a single vocabulary — key with modifiers, text input, pointer press/release/move/drag, wheel, focus change, resize — not as callbacks registered on widgets. | full (97f931e5) | sparkles.input.events Event (a sum type — no kind + dead fields) |
| INP2 | The vocabulary must live in a package depending on sparkles:base only (plus sparkles:math import-only for the position type), so both sparkles:ui and sparkles:tui can depend on it without a cycle. | full (97f931e5) | libs/input/dub.sdl (incl. the source-included test-runner recipe) |
| INP3 | The position type must be the same type the toolkit's geometry uses, so no conversion is needed at the boundary. | full (97f931e5) | sparkles.input.events Point ≡ ui.geometry.Point; positions are 0-based toolkit cells, converted by producers |
| INP4 | Events must be Regular values — copyable, comparable — so they can be recorded, replayed and asserted in tests without a live terminal or window. | full (97f931e5) | whole-event equality assertions in tui/integration.d |
Capability tiers (INP5–INP6)
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP5 | Every interaction must be classified into tier 0, 1 or 2, and a widget must declare the highest tier it requires. | partial | sparkles.input.tier InteractionTier/tierOf (97f931e5); the widget declaration lands with the M6 widget model |
| INP6 | A target must declare which tiers it serves. Emitting a widget that requires a tier above the target's capability must be a reported degradation, never a silent drop. | partial | InputCapabilities is exposed by the terminal/GPU adapters (IXB10); widget-side tier declaration/reporting remains INP5 |
Adapters (INP7–INP9)
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP7 | The terminal library must decode its wire formats (SGR mouse, key sequences) directly into the shared event vocabulary, retiring its private key/modifier/event types. No separate adapter layer is needed there. | full (b9aeb102) | tui/input.d (decodes 1-based wire → 0-based Point; web-sign wheel deltas incl. horizontal) |
| INP8 | The GPU backend must synthesize events from its windowing library's polled state, since that library has no event queue — including press/release edges, drag tracking and wheel deltas. | full (bbf85c7c, 8837f3e9) | ui_raylib.events RaylibEvents (mouse, touch and hardware-key synthesis) |
| INP9 | The GPU backend must hold a real pointer grab for the duration of a drag, so motion and release are delivered even over window decorations or outside the window. Passive cursor-confinement modes are insufficient; this is a windowing-system concern owned by the adapter, not by application state checks. | not started | UI-O3 |
IMPORTANT
INP9 is a known open bug, not a hypothetical: without a grab, a drag released over a title-bar button activates that button, and a drag leaving the content never sees its release. Application-level mitigations were tried and reverted — the decisive events happen in the window manager. Because this bug class evades in-process tests entirely, its fix must be validated against the end-to-end windowing harness, not unit tests.
Event detail (INP11–INP14)
These four shipped with the vocabulary but were never recorded here; the rows are written from the implementations and their commits, not proposed.
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP11 | A pointer event must carry a pointer identity, so multi-touch is expressible in the shared vocabulary at all. Everything above the gesture layer stays single-pointer by construction: a recognizer owns the ids and hands onward only the primary contact. | full (401cfba4) | sparkles.input.events PointerEvent.pointerId |
| INP12 | Wheel deltas must be cells to scroll, applied by the producer — never a raw notch count a consumer multiplies again. This is what lets a notchless producer (a touch drag, a pixel-precise trackpad) participate in the same event. Beside the whole cells (dx/dy, accumulated) an event may carry the exact distance with its fraction (fdx/fdy), for a target that paints between cells (LAY17); a consumer reads one pair or the other (exactX/exactY fall back to the whole cells). Fractions are opt-in per application (RunConfig.fractionalScroll), because a producer asked for them also emits events whose whole part is 0, which a consumer of dx/dy alone would read as nothing to do. An event also says whether it begins a gesture (begins), for a consumer with nested scrollers that latches one per gesture (SCV12): the touch recogniser sets it on a drag's first scroll and not on the drag's later events or its fling, and the raylib wheel on its first movement after 150 ms without one. A producer that does not set it leaves the consumer's pause rule to start gestures. Violation: a fling that re-picks its scroller mid-flight. | full (d4f531bb) | sparkles.input.events WheelEvent, linesPerNotch, precise, WheelEvent.fdy, WheelEvent.exactY, WheelEvent.begins; RunConfig.fractionalScroll, GestureConfig.fractional, RaylibEvents.fractionalWheel; test input.gesture.aDragBeginsOneGestureItsFlingContinues |
| INP13 | The platform spellings of "go back / dismiss" must be one equivalence in the vocabulary. The framework owns the equivalence; the application owns the chain it triggers. | full (401cfba4) | sparkles.input.events isDismiss (escape ≡ the Android system back key) |
| INP14 | A target must declare its pointer affordances as independent axes — hover, sub-cell precision, simultaneous contacts — separately from the tier ladder, because touch serves a higher tier than a terminal while lacking hover, which no <= test can express. | full (ed198ddf) | sparkles.input.capability InputCapabilities and its four target profiles |
NOTE
The touch recognizer (sparkles.input.gesture, 2ea120fe) cites requirement IDs GST1–GST6 that exist in no specification page. Recording them is a separate reconciliation, not part of this tree; INP23 records the two scroll obligations a consumer that paints between cells depends on.
Key levels and the per-frame fold (INP15–INP17)
Proposed. Required by the application host and by migrating apps/terminal onto it — see P0.3.
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP15 | A key event must carry its action (press, repeat, release), the layout-independent unshifted code point, and the text that keystroke produced — the last stored inline, not borrowed, so an event stays a value that can be recorded now and asserted on later (INP4); modifiers must include the platform "super". A terminal emulator's encoder pairs a key with its text, and a detached text event cannot express that. | full (9f0ca9ad) | sparkles.input.events KeyEvent, Mods, maxKeyText |
| INP16 | A target must declare whether it can report a key release at all — a terminal can only through the kitty keyboard protocol (flag 2, negotiated: D44). A held-key interaction must consult that declaration and offer another route, rather than working on one target and silently failing on another (TGT5). The declaration defaults to absent, unlike the other capability axes. | full (9f0ca9ad) | sparkles.input.capability InputCapabilities.keyRelease; a terminal declares it where TerminalRequest.keyRelease asked and the probe found the kitty keyboard (ui_tui.session, tui.input.kittyEventTypes) |
| INP17 | The per-frame fold — edges versus levels, wheel accumulation, gesture anchors — belongs to this package, not to an application. It must cover every pointer button, modifier level and (where INP16 allows) held keys, and stay unit-agnostic: positions pass through in the producer's own unit. | full (12d17717) | sparkles.input.frame (hue's frame_input.d, deleted) |
| INP18 | The fold must carry a horizontal wheel channel (wheelCellsX): a horizontal axis (WheelEvent.dx, a trackpad's sideways swipe) accumulates directly, and a Shift-modified vertical notch turns sideways instead of scrolling — the universal spelling on mice without a horizontal axis. Consumers scroll sideways by reading one field, exactly like wheelCells. | full | sparkles.input.frame InputFrame.wheelCellsX (hue's per-fence code scrolling is the first consumer) |
IMPORTANT
INP15–INP17 are additive: the new key fields are appended, so every existing construction and helper keeps compiling. The fold already existed as a pure, tested function inside apps/hue, so INP17 was a move plus a generalization, not a new design.
INP16 defaults to absent, not to the desktop answer, which is the one place these rows say something different from the other capability axes. A key release is an extra event, not a refinement of a press: a consumer that switches on the key alone reads a release as a second press. Defaulting the declaration to true would therefore have changed what every existing consumer sees the moment a producer started synthesizing releases. Undeclared means "presses only" — what every producer reported before this existed — and a target opts in by declaring it and emitting them.
The same hazard is why isDismiss ignores releases: an application that dismisses on Escape would otherwise dismiss twice per keystroke, closing a popup and then quitting.
INP15's text is stored inline, not borrowed. A slice into the producer's per-frame buffer would cost the vocabulary INP4 — an event you can record and replay cannot hold a pointer with a shorter life than itself — and it makes the sum type's assignment @system under dip1000, which would strand every @safe consumer. One keystroke is one code point; the cap (maxKeyText) covers a dead-key or IME composition and truncates beyond.
Shared producer primitives (INP19–INP20)
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP19 | Every pixel producer must use one cells-to-device mapping value, including its origin and zero-divisor policy, so SDL, raylib, and native WSI cannot quantize the same pointer differently. | full | sparkles.input.metrics CellMetrics; SDL and raylib adapters |
| INP20 | Pixel gestures must reuse ScreenPosition!float, and consumers must be able to import the shared PointerShape through sparkles:input. The enum remains defined in lower-level sparkles:base so compatibility does not create a dependency cycle. | full | sparkles.input.gesture PointF; sparkles.input.pointer |
Pastes (INP21)
| ID | Requirement | Status | Evidence |
|---|---|---|---|
| INP21 | A paste must reach an application as text, not keys — verbatim, newlines included, so an input can insert it rather than read a newline as "submit" — while Event stays pointer-free: std.sumtype makes assignment @system for any member carrying a pointer, which would take @safe event handling away from every consumer (a string and a reference-counted SharedBuffer were both tried). So a paste is a run of PasteEvent chunks, each an inline buffer of at most pasteChunkBytes (40, keeping Event at 64 bytes) split between code points, the last one marked last — the native window layer's pattern (TextCommittedEvent's inline buffer). A target declares whether it delivers pastes (InputCapabilities.pasteEvents). | full | events.d PasteEvent, pasteChunks; tests input.events.pasteChunks, input.events.pasteEventIsRegular; the terminal decoders (sparkles:tui's blocking reader, ui-app's ring-pump assembler) turn CSI 200~ … CSI 201~ into chunks — integration.pty.bracketedPasteIsOnePaste, ui_app.assembler.bracketedPasteIsTextNotKeys; terminal-view hands a paste to its shell through libghostty's paste encoder (terminal_view.component.pasteIsTextForTheShell) |
Colour scheme (INP22)
| ID | Requirement | Status | Evidence |
|---|---|---|---|
| INP22 | A surface switching between light and dark must reach an application as a value, so it can follow — a ColorSchemeEvent { bool dark; }, pointer-free like every event. A terminal delivers it only with mode 2031 negotiated, and answers a CSI ? 996 n query with the current scheme, so the first one arrives at startup. | full | events.d ColorSchemeEvent; decodeEscape reads CSI ? 997 ; 1|2 n (tui.input.colorSchemeReports, ui_app.assembler.colorSchemeReports); Terminal.enableColorSchemeReports, negotiated by TerminalSession when the terminal answered for 2031 (integration.pty.colorSchemeReportsAreNegotiatedAndDecoded); the consumer, ui-gallery's theme following its sibling (ui_gallery.gallery.themeFollowsTheColorScheme) |
Touch scrolling (INP23)
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP23 | A touch drag must scroll along the axis it set off on and fling at the speed the finger had when it lifted. With fractions asked for (INP12), the recogniser locks the drag's axis once the touch slop is crossed, horizontal when the travel so far is wider than it is tall, and keeps it for the whole drag, so a vertical scroll never wanders sideways and a sideways drag over a wide block scrolls it sideways; every tick that moved emits its exact distance on that axis. The release velocity is the drag's travel over its last 100 ms of ticks, not its last step, so a finger that stopped before lifting does not fling. Without fractions a drag stays vertical and arrives in whole rows. Violation: a drag that starts sideways and scrolls vertically, or a fling after a finger held still. | full | GestureConfig.fractional, GestureConfig.cellW, GestureRecognizer; tests input.gesture.fractionalEmitsTheExactDistanceOnTheLockedAxis, input.gesture.aFingerThatStopsBeforeLiftingDoesNotFling |
Composition (INP24)
| ID | Requirement | Status | Evidence |
|---|---|---|---|
| INP24 | Input-method composition must reach an application as a value, while Event stays pointer-free and 64 bytes (INP21). A CompositionEvent carries the preedit as a TextId naming text in the host's TextPool (sparkles.base.pool), the preedit cursor, and up to four styled segment ranges (none, underline, selected, converted), as sparkles:wsi does. The id resolves until the host's next poll; a consumer that keeps the text copies it. An event whose preedit is TextId.init ends the composition. A recording of events (INP4) records the texts its ids name alongside them. A target declares whether it delivers composition (InputCapabilities.composition). | full | CompositionEvent, CompositionRun, InputTextPool, InputCapabilities.composition; hasInputTexts, withPreedit, RecordingHost.holdTexts, recordedText; tests input.events.compositionIsRegular, ui_app.record.recordingCarriesItsTexts; the editor EDI3, EDI7, EDI8 |
Clipboard reads (INP25)
| ID | Requirement | Status | Evidence |
|---|---|---|---|
| INP25 | Reading the system clipboard must be a request answered by an event, never a blocking call inside a step: the application asks the host (HST8), and the host delivers the text as a run of PasteEvent chunks marked as the answer to that request, carrying the request's number so a late answer can be recognised, or an empty answer when the clipboard holds no text. A target declares whether it can read the clipboard (InputCapabilities.clipboardRead); a terminal declares it absent, because its own paste key arrives as a bracketed paste. | full | PasteEvent.request, pasteChunks, InputCapabilities.clipboardRead; canReadClipboard, GuiHost.readClipboard (raylib), RecordingHost.readClipboard; tests input.events.pasteAnswersCarryTheirRequest, ui_app.record.platformCallsAreCaptured, the editor's editor.clipboard.requestAndAnswer. NativeHost.readClipboard streams the window system's text offer into a bounded sink (ClipboardReads, several reads at once) and answers after the drain the transfer ends in, an offer without text as one empty paste (tests ui_app.nativeClipboard.outOfOrder, ui_app.nativeClipboard.rejectsPartialPayloads, ui_app.nativeClipboard.capacityAndClose); a field host that reads by request serves its fields through RequestClipboard (test editor.field.serveClipboard.byRequest); an application with several inputs routes each answer to the input that asked, while it is still live, through ClipboardRouter (tests ui_app.clipboardRouter.deliversToTheAskingOwner, ui_app.clipboardRouter.staleOwnerIsCancelled, ui_app.clipboardRouter.joinsChunks). |
| INP26 | A trackpad's scroll must coast once, by one model: the fingers are followed exactly, and when they lift the scroll says so (WheelEvent.ends, its deltas possibly zero), so a consumer with momentum of its own flings at the speed the fingers had — the same fling a touch drag releases into (INP23). Inertia the platform synthesizes after the lift (macOS' momentum phase) arrives marked (WheelEvent.momentum): such a consumer ignores it, any other scrolls by it as before. AppKit reports the phases from NSEvent.phase/momentumPhase; Wayland ends a finger scroll at axis_stop, where no compositor sends kinetic scrolling. Violation: a swipe that coasts twice — the platform's inertia and the consumer's fling — or a picker that moves a row per event rather than by the distance swiped. | full | WheelEvent.ends, WheelEvent.momentum, ScrollPhase, AppKitWsi.appKitScrollPhase, ScrollBody.scroll; tests ui.scroll_body.trackpadFlingsOnLift, ui_app.wsi_input.wheelNotchesAndContinuousScrolls, wsi.appkit.scrollPhasesFollowTheGesture |
Hit testing (INP10, INP27, INP28)
| ID | Requirement | Status | Traces to |
|---|---|---|---|
| INP10 | A widget's hit identity must survive the pipeline — from the widget, through layout frames, into the display list — so hit testing is done once by the toolkit and every backend consumes the result, instead of each rebuilding its own map. | partial | state.d hoverTargets/keyTargets (f166e099) are visibility- and clip-aware and consumed by the shared document tree; non-widget pane/chrome routing remains until the container tier owns it (DCK13, whose top-layer rung is specified by anchored overlays LYR5) |
| INP27 | Hit ids must be issued by one registry, never chosen by hand. A component asks for a block under a key — its component tag and an instance key — and gets the same block on every frame the key is asked for again; a key not asked for in a frame frees its block. Two keys can never be issued overlapping blocks. | done | hit_ids.d HitRegistry (HitRegistry.block.disjointKeys, HitRegistry.beginFrame.freesUnasked); every application issues from it — editor.app.hitIdsComeFromTheRegistry, workspace_host.hits.aFramesTargetsNeverShareAnId, viewer_model.claimHits.blocksAreDisjointAndDecode (editor milestone M-a, editor plan) |
| INP28 | A held press or capture must keep its id across frames: a block stays issued while its key is asked for, so the target STM10 armed or STM11 captured on the press frame is the one the release frame tests, even when conditional controls appear or vanish between them. | done | hit_ids.d HitRegistryOf (fixed-stride slots that never move, reused oldest-freed first); HitRegistry.block.pressSurvivesNewControl; STM10, STM11 |
The hit-testing model
Positional hit-testing is a pure query over per-frame derived data: the flat hit list (hoverTargets/keyTargets) scanned in reverse paint order, or equivalently a culled top-down frame-tree descent. The rules:
- Hit geometry is derived, never registered. Hit rects come from the same laid-out frames as the paint, computed as a by-product of display- list emission with visibility and clips applied — one source, so paint and hit cannot drift (the
IXR27invariant). - Hit order is reverse paint order. Stacking is hierarchical and the display list is its ground truth; there is no separate z coordinate. Topmost-wins falls out of iterating the list backwards.
- Targets are indices (hit ids), not pointers — Regular, lifetime-free, assertable in tests.
- Out-of-bounds content is a top layer. Popups and overlays, which escape their parent's bounds, keep explicit rects and are tested before the tree/list, front to back. What that layer is — one ordered, frame-built arena whose index order is paint order is reverse hit order — is specified by anchored overlays
LYR1,LYR5. - Events route against the last painted frame's data — the layout the user saw — never against a mid-rebuild state.
- Positional hits are the last resort in routing precedence: pointer capture (
STM11) first, then the gesture owner, then top layers, then the positional query (see containersDCK13). - Scaling escalation is bounded: if a profile ever shows the query hot (a canvas with ~10⁴+ simultaneously visible targets), the escalation is a bucketed uniform grid built from the same derived list, behind the same pure query function — an implementation detail, not an architecture.
Milestones
| Milestone | Scope | Status | Requirements |
|---|---|---|---|
| N0 | Package + event vocabulary + tier classification | full (97f931e5; widget declaration in M6) | INP1–INP5 |
| N1 | Terminal decoding retargeted to the shared vocabulary | full (b9aeb102) | INP7 |
| N2 | Hit identity plumbed through layout and the display list | partial (f166e099; shared document consumes it, container routing remains) | INP10 |
| N3 | GPU adapter: event synthesis + pointer grab | partial (INP8 full; pointer grab remains UI-O3) | INP8, INP9 |
| N4 | Declared target tiers, with reported degradation | partial (IXB10; widget declaration/reporting remains) | INP6 |
| N5 | Key levels, richer key identity, and the per-frame fold | not started (P0.3) | INP15–INP17 |
| N6 | The hit-id registry: keyed blocks, the hand-picked bases retired | done (editor M-a) | INP27, INP28 |
Module coverage
| Source file | Requirements |
|---|---|
libs/input/src/sparkles/input/ | INP1–INP6, INP11–INP23, INP25 |
libs/tui/src/sparkles/tui/input.d | INP7 |
libs/ui-raylib/src/ | INP8, INP9 |
libs/ui/src/sparkles/ui/hit_ids.d | INP27, INP28 |
libs/ui/src/sparkles/ui/state.d | INP10 (the consumer) |
libs/input/src/sparkles/input/frame.d (planned) | INP17 |
Relationship to existing specs
| Piece | Role in input |
|---|---|
state-machines.md STM | the consumers of events — hover, selection, scroll, focus, disclosure |
backends.md TGT5 | declared per-target capabilities, of which input tiers are half |
widgets.md WGT | where a widget declares its required tier |
ui-app HST | the host that drains these events and folds them per frame (INP17) |
| End-to-end windowing test harness research | the validation route for INP9 / UI-O3 |
→ Overview · State machines · Backends