import type {
AppMsg,
BoxProps,
KuiMsg,
Msg,
EnterProp,
GeneratedSpecProps,
KuiNode,
MenuItemInput,
MenuItemRole,
TextProps,
} from './jsx-runtime.js';
export type { KuiNode, KuiElement, Msg, KuiMsg, AppMsg } from './jsx-runtime.js';
// The menu inputs live beside the other prop types, because ` `
// takes one; they are re-exported here because `Ctx.openMenu` takes one
// too, and an app should not have to know which file a type sits in.
export type { MenuItemInput, MenuItemRole, MenuInput, MenuBarInput } from './jsx-runtime.js';
export type { ColorToken, FamilyToken, LengthToken } from './jsx-runtime.js';
// -- events ------------------------------------------------------------------
// An event arrives as the message its handler declared
// (docs/adr/0047-an-event-arrives-as-the-message-its-handler-declared.md):
// a node that declares `onDrag={{ kind: 'pan' }}` hears a drag as
// `{ kind: 'pan', drag: { phase, x, y, dx, dy, parent } }` — the message
// as declared plus one field, named for the event, holding its data. The
// envelope's `event` (`UiEvent.event`) says which event it was; the
// payload no longer does. A `null` handler declares the behaviour and
// names no message, so its events arrive as the field alone
// (`{ drag: { … } }`), and `{}` for an event with no data. A message
// that is not a map — a string, a number, a boolean, a list — is kept
// under `tag`, even when the event has no data: `onClick: 'save'` is
// heard as `{ tag: 'save' }` (decision 3), so every payload a node sends
// is a map (`Arrived`). The shapes are `EVENTS` in
// crates/kui-core/src/schema.rs, the table docs/props.md is generated from.
//
// Each event has three types: its data (`DragEvent`), the field that
// carries it (`WithDrag`, an interface, so `extends` works), and a helper
// that adds the field to the app's own message (`DragMsg`). Register
// the messages as they arrive — `DragMsg<{ kind: 'pan' }>` — and the
// handler prop (`onDrag`) takes them as declared, without the field:
// `HandlerMsg`. A message registered without the field does not
// fit the prop, so pairing a message with the wrong handler fails at the
// node. A bare message with a field is registered as it arrives —
// `DragMsg<{ tag: 'pan' }>` — and the prop takes `'pan'` back
// (`Declared`).
//
// What has no node of its own — a resize, the window's keyboard, a
// modifier change, the OS's documents — is declared where the window is
// (ADR 0048): the root box's `windowEvents` group (`WindowEvents`), a
// `windows` entry's `onWindow` / `onDismiss` (`WindowDecl`), and
// ``. They arrive as the app's own messages too, so
// `update` takes the registered messages and nothing else.
/** The registered messages that carry the event field `W`, as a node
* declares them: without the field, which the core writes in. Every
* handler prop is typed as this — `onDrag` as `HandlerMsg`,
* `onKey` as `HandlerMsg` — so only a registered message
* with that field fits it. `W` may be a union, for a handler that
* delivers several events; the `keyof` and the `Omit` distribute, so
* each message keeps its own fields. Left un-augmented (no `KuiMsg`),
* it is `Msg`, any plain data, as every prop is. */
export type HandlerMsg = KuiMsg extends { msg: infer M }
? Extract extends infer E
? E extends unknown
? Declared>
: never
: never
: Msg;
/** A message that is not a map — a string, a number, a boolean, a list. A
* node may declare one; it arrives under `tag` (`Arrived`). */
export type BareMsg = string | number | boolean | readonly unknown[];
/** The message `M` a node declared, as the app hears it (ADR 0047,
* decision 3): every node payload is a map. A map arrives as it is (with
* the event's field added where the event has data); a bare message —
* `onClick: 'save'`, a number, a list — arrives under `tag` beside that
* field, `{ tag: 'save' }`, even when the event has no data; `null`
* arrives as the field alone, or `{}`. This is what `update` is handed
* and what `UiEvent.payload` is: an app registers the messages it
* declares (`'save'`) and reads them as they arrive (`msg.tag`). It
* leaves a map alone, so it is a no-op on an all-map union and on a
* union already mapped through it. */
export type Arrived = M extends null | undefined
? { [field: string]: Msg }
: M extends BareMsg
? { tag: M }
: M;
/** The other way round, for a handler prop: a registered message that is
* `{ tag }` and nothing else once the event's field is left out may be
* declared bare — `DragMsg<{ tag: 'pan' }>` registered, `onDrag="pan"`
* declared — as well as spelled out. Anything else is declared as it is. */
export type Declared = M extends { tag: infer T extends BareMsg }
? [Exclude] extends [never]
? T | M
: M
: M;
/** A rect in logical viewport px: a container's, the node's own. */
export interface EventRect {
x: number;
y: number;
w: number;
h: number;
}
/** What a click on a `cells` grid, or inside an `onKey` sink that draws
* `role="line"` rows, can say beyond "it was clicked" — and, on a map
* message, what it was made with. A plain click arrives as declared (a
* bare message under `tag`), with no `click` field; this is there only
* where the click can say more. */
export interface ClickEvent {
/** On a `cells` grid: the cell under the pointer, clamped to the grid. */
cell?: { row: number; col: number };
/** Inside an `onKey` sink that draws `role="line"` rows: the line and
* the byte in its text, as a drag carries them, whether the point is
* within that line's own box, and the press's click count. */
line?: number;
byte?: number;
inside?: boolean;
clicks?: number;
/** On a map message: the modifiers held for a ⌘-click or a
* Shift-click (backlog C101's facts). */
mods?: { shift: boolean; ctrl: boolean; alt: boolean; super: boolean };
/** On a map message: the key that made the click, Enter or Space. */
key?: 'enter' | 'space';
}
/** A pointer-captured drag on an `onDrag` node. `x`/`y` are where the
* pointer is; `dx`/`dy` are its displacement **from the press point**, in
* every phase — `start` carries zero, a `move` how far the pointer is from
* where it pressed, `end` the whole distance — so a handler sets
* `value = start + dx` rather than summing deltas, and can commit from
* `end` alone. Nothing is dropped under the click slop (3 px, measured
* from the press): the first `move` already carries the whole distance.
* `parent` is the container rect, so fractions need no geometry query. */
export interface DragEvent {
phase: 'start' | 'move' | 'end';
x: number;
y: number;
dx: number;
dy: number;
parent: EventRect;
/** On a `cells` grid: the cell under the pointer, clamped to the grid. */
cell?: { row: number; col: number };
/** Inside an `onKey` sink that draws `role="line"` rows: the line, the
* byte in its text, whether the point is within that line's own box,
* and the press's click count. */
line?: number;
byte?: number;
inside?: boolean;
clicks?: number;
}
/** A key press on the focused `onKey` sink — and its release too, as
* `phase: 'up'`, when the sink also declares `keyUp`; without that flag a
* sink hears presses only, so a keymap runs each binding once. `code` is a
* character or a name ("left", "f5"), `text` what the press would insert
* (null for a chord — but for a Mac's Option while it composes, ⌥- typing
* "–" — and on every release), `repeat` set when the OS
* auto-repeated the press. A key only comes up where it went down: a release
* whose press the sink never got is dropped, and focus leaving while a key is
* held delivers the `up` first — so a held-key binding cannot be left stuck
* down. */
export interface KeyEvent {
phase: 'down' | 'up';
code: string;
/** The US-QWERTY key at that *position*, spelled as `code` is — bind
* it when you want the finger rather than the label (WASD stays a
* square on every layout). A shifted letter arrives as the upper-case
* letter in `code` with `shift` set, as the OS spells it, and as the
* lower-case one here. */
physical: string;
shift: boolean;
ctrl: boolean;
alt: boolean;
super: boolean;
text: string | null;
repeat: boolean;
/** Which of a key's twins it was (backlog F108): the left or right
* modifier, the keypad's digit, operator or Enter (`code` is still
* "1", "enter"), else "standard". */
location: KeyLocationName;
/** Caps Lock and Num Lock as the press left them: a lock key's own
* press reports the state it made (backlog RG96). */
caps_lock: boolean;
num_lock: boolean;
}
/** Where a key sits, for the keys that have twins (`KeyEvent.location`). */
export type KeyLocationName = 'standard' | 'left' | 'right' | 'numpad';
/** Text an IME committed at the end of a composition, on the focused
* `onKey` sink (or the nearest one above the focused control) — the one
* committed text the platform never reports as a key press carrying
* `text`, so insert it as you would a key's `text`. Plain typing does not
* arrive this way: the `key` event already carries it, and a sink hearing
* both would type every character twice. A focused `` takes the
* commit itself and reports its `change`. Assistive technology replacing
* a custom editor's selection arrives this way too: text to insert over
* the selection.
*
* The answer to a `requestPaste()` arrives the same way, with `pasted`
* set (backlog DX14) — an IME's commit never has it — and with what the
* pasteboard marked it (backlog F84): `concealed` for a secret a password
* manager copied — show it to no one, keep it nowhere — and `transient`
* for text not to keep in a history. A marker that is not set is absent,
* never `false`. */
export interface TextEvent {
text: string;
pasted?: true;
concealed?: true;
transient?: true;
}
/** An in-progress IME composition on the focused `onKey` sink: `text` is
* the uncommitted string to show inline at the caret, `cursor` the byte
* range inside it the IME's own caret covers (null when it does not say),
* and an empty `text` means the composition ended without a commit. The
* OS candidate window is anchored for you: the `line` carrying `caret`
* says where (`imeRect()` headless). */
export interface PreeditEvent {
text: string;
cursor: [number, number] | null;
}
/** Assistive technology set the selection of a custom editor — an `onKey`
* sink that draws its own `role="line"` rows (ADR 0047): line ordinals
* among the drawn lines and byte offsets into their text, the end that
* stays (`anchor`) and the caret (`focus`). */
export interface SelectEvent {
anchor: { line: number; offset: number };
focus: { line: number; offset: number };
}
/** A copy reached rows of a `selectable` virtual list that no frame built
* (ADR 0017, tier 3): the core cannot read text it never laid out, so it
* asks the app, on the scope, for the range — `from`/`to` are row indices
* (`index`, the row's data index) and byte offsets into each row's text —
* and the app answers with `answerSelectionRange(text)`, which is what
* reaches the clipboard. Only while `requestCopy()` answered `asked`; a
* late answer changes nothing. A Select All over a list that declared
* `rowCount` asks for `0..rowCount - 1` with `to.byte` past the last
* row's length (the row was never built) — cut it to the row. */
export interface SelectionRangeEvent {
from: { index: number; byte: number };
to: { index: number; byte: number };
}
/** A secondary-button (right) press on an `onContextMenu` node — on the
* press, not the release. `x`/`y` are logical viewport coordinates: where
* the menu goes. The core opens nothing; declare the menu as a `modal`
* float and stop declaring it on `dismiss`, or `openMenu`. */
export interface ContextMenuEvent {
x: number;
y: number;
}
/** A menu row was chosen, from a menu opened for an `onMenu` node — a
* ``'s, or one `Ctx.openMenu` named it the target of — or from
* the application menu bar (`docs/adr/0018-a-menu-bar-the-app-declares.md`),
* as ``'s message. `item` is the row's `id`, or its label
* when it declared none. `role` says whether the core already carried
* the row out: a standard role is performed (and its clipboard work
* queued for the host) *and* posted. The stock right-click menu, whose
* roles the core performs itself, sends nothing. */
export interface MenuEvent {
role: MenuItemRole;
item: Msg;
}
/** A press that deepened past the second stage of a Force Touch trackpad,
* on an `onForceClick` node, at the logical viewport point it happened
* at. Routed as a secondary press is — no focus moved, no click — and the
* ordinary click the press is still producing arrives afterwards. Text
* needs none of this: over an `edit` or a `selectable` scope the core
* selects the word and asks the host for its Look Up panel instead. */
export interface ForceClickEvent {
x: number;
y: number;
}
/** A non-primary button on an `onButton` node that claims it (`buttons`),
* backlog F105: `press` where it went down, with the click count, then
* `move` for every pointer move while it is held and `release` where it
* came up — on the same node wherever the pointer went, since the press
* captured the button. `button` is its name, or for one past the middle
* button its number (`3 + n`). On a `cells` grid each also carries
* `cell: { row, col }` under the pointer, clamped to the grid, and inside
* an `onKey` sink that draws `role="line"` rows `line` and `byte`, as a
* drag does. A claimed secondary press is this instead of a
* `contextmenu`. */
export interface ButtonEvent {
phase: 'press' | 'move' | 'release';
button: 'secondary' | 'middle' | number;
x: number;
y: number;
/** On the press only: the driver's count; the native runner counts
* the primary button alone, so 1. */
clicks?: number;
/** On a `cells` grid: the cell under the pointer, clamped to the grid. */
cell?: { row: number; col: number };
/** Inside an `onKey` sink that draws `role="line"` rows: the line and
* the byte in its text, as a drag carries them, and whether the point
* is within that line's own box (false in the margin beside it). */
line?: number;
byte?: number;
inside?: boolean;
}
/** The wheel over an `onScroll` node, or a drag-select held past a
* `cells` grid's top or bottom edge
* (`docs/adr/0029-a-selection-follows-the-pointer-past-the-edge.md`).
* `dx`/`dy` are the delta in logical px as the driver reported it
* (positive `dy` is the wheel rolling up, toward earlier content),
* `x`/`y` the pointer, and `lines` the whole lines a `cells` grid's `dy`
* covers — positive is later history, the sign `originLine` grows in,
* the fraction carried to the next notch — and null on any other node.
* The core scrolls nothing for it: re-declare the grid's `originLine`,
* or zoom the canvas. From the edge drag it comes once a frame while the
* pointer is held past the edge. A trackpad's pinch comes as one too
* (backlog F256), with `zoom` and `dx`/`dy` 0. */
export interface ScrollEvent {
x: number;
y: number;
dx: number;
dy: number;
lines: number | null;
/** On a node that names `scrollMods`: the modifiers held when the
* gesture began. */
mods?: { shift: boolean; ctrl: boolean; alt: boolean; super: boolean };
/** A trackpad's pinch (backlog F256): the magnification since the last
* event, positive zooming in. Only a pinch carries it. */
zoom?: number;
}
/** Keyboard focus entered or left an `onFocus` node's subtree, and what
* moved it (backlog DX18). */
export interface FocusEvent {
phase: 'in' | 'out';
by: 'pointer' | 'keyboard' | 'assistive' | 'program';
/** A move the keyboard or the pointer made with a modifier held. */
mods?: { shift: boolean; ctrl: boolean; alt: boolean; super: boolean };
}
/** The pointer entered or left an `onHover` node — also when a new frame
* moved it under a still cursor, which `by` tells apart. */
export interface HoverEvent {
phase: 'enter' | 'leave';
/** What moved: the pointer, or what is under a still one — a list the
* keys scrolled, a row that grew (backlog DX20). */
by: 'pointer' | 'content';
}
/** Files dragged in from the OS over an `onDrop` node
* (`docs/adr/0031-a-drop-zone-is-a-row-and-the-files-are-an-event.md`):
* `enter` when they come over the zone, `move` while they move over it
* (never twice for one point), `leave` when they go to another zone, to
* no zone or out of the window, `drop` when they land — and no `leave`
* after a `drop`. `paths` are the OS paths; `x`/`y` the pointer in
* logical viewport coordinates, absent on `leave`. The zone is the
* topmost one under the pointer by paint order: a node inside it is its,
* and a node that is no zone is looked past, so an overlay shown on
* `enter` does not end the hover. */
export interface DropEvent {
phase: 'enter' | 'move' | 'leave' | 'drop';
paths: string[];
x?: number;
y?: number;
}
/** A file dialog's answer (backlog C51): the paths an Open, Save or folder
* dialog asked for with `requestFiles` picked, as a `drop` carries them —
* none when the user cancelled. It arrives on the root, in the dialog's
* own `tag` message. */
export interface FilesEvent {
paths: string[];
}
/** The data rows in an `onRange` node's view (docs/adr/0065): the least
* and greatest data index among its children inside its box. */
export interface RangeEvent {
first: number;
last: number;
}
/** A node's matched `when` entries over its own size and the window's
* (ADR 0069): the 0-based indices of every entry that matches, and the
* node's size; on a ``, its decision — `[0]` while `render` is
* built — and the room its parent offers. */
export interface QueryEvent {
matched: number[];
width: number;
height: number;
}
/** The rect layout gave an `onLayout` node — logical px, viewport
* coordinates, after scrolling and position easing — on its first frame
* and whenever it changes, never on a frame that left it alone (a
* transition that moves the node reports every frame it moves). `parent`
* is the container rect, as on drags. Layout's numbers, so the view never
* re-derives them by hand. */
export interface LayoutEvent {
x: number;
y: number;
w: number;
h: number;
parent: EventRect;
/** Physical px per logical px at the node — `w × scale` by `h × scale`
* is how many pixels to render for it before `updateImage`. */
scale: number;
}
/** An editor's text changed, on an `` (or a custom editor — a node
* with an editor role that draws its own text) that declared `onChange`:
* typing, a paste, a composition's commit, assistive technology setting
* the value. `text` is the whole text after the change, so storing it and
* declaring it back as `value` keeps the editor and the model one text
* (ADR 0047, decision 8). An editor without `onChange` sends nothing. */
export interface EditChangeEvent {
text: string;
}
/** A stock slider's proposal (docs/adr/0034-stock-controls-over-the-roles.md):
* the core turned a press, a drag, an arrow, a Page key, Home / End or an
* assistive-technology increment into `value` — clamped to the range and
* snapped to `valueStep` — on a `` (or a `role="slider"` box) that
* declared `onChange`. `phase` is `'move'` while the pointer holds it and
* `'end'` when it lets go or a key moved it. Nothing moves until the view
* declares `value` as `valueNow`; a slider without `onChange` does not
* move at all (`slider-without-handler`). */
export interface SliderChangeEvent {
value: number;
phase: 'move' | 'end';
}
/** An editing key that met the edge of an editor's text and did nothing
* (backlog F145): ↑ on the first line, ← or Backspace at the start, ↓ on
* the last line, → or Delete at the end — from a caret with no selection
* and without Shift, on an editor that declared `onBoundary`. `word` and
* `doc` are the editing modifiers the key carried. */
export interface BoundaryEvent {
key: 'up' | 'down' | 'left' | 'right' | 'backspace' | 'delete';
edge: 'start' | 'end';
word: boolean;
doc: boolean;
/** Control itself (backlog C94): on macOS not the primary `doc`. */
ctrl: boolean;
}
/** A playback with a message (`play(id, { tag })` or ``)
* finished on its own — never when something stopped it. On an
* `` node's key, or the root for `play`. `'refused'` is the
* device declining to start it at all (its 128 voices are all held, or
* the sound did not decode): that playback never starts and so never
* ends, so this arrives in place of the `'ended'` a view would otherwise
* wait forever for. */
export interface SoundEvent {
phase: 'ended' | 'refused';
playback: number;
}
/** A still or a recording the app asked for with `captureTo` /
* `recordTo` was written to `path`, or could not be (ADR 0055). `width`
* and `height` are physical px; `frames` is 1 for a still and the frames
* drawn while recording for a recording, `seconds` its length (0 for a
* still); `error` says why a `failed` one failed — a directory that is
* not there, no GPU, an extension that names no format. */
export interface CaptureEvent {
phase: 'saved' | 'failed';
path: string;
width: number;
height: number;
frames: number;
seconds: number;
error?: string;
}
/** A surface was asked to go away: Escape, or a press that landed
* outside it. The core closes nothing — stop declaring the surface (or
* ask first). On a `modal` node only the modal in effect hears it; a
* `kind: 'popup'` window hears it as its `windows` entry's `onDismiss`,
* with the window's `id` — the driver reports it, because a press outside
* a window and a key sent to a non-activating one are facts only the OS
* has. */
export interface DismissEvent {
reason: 'escape' | 'outside' | 'accelerator';
/** A popup window's: the id its own events carry in `window`. */
id?: number;
}
/** The viewport changed size or DPI (logical px), as the root's
* `windowEvents.onResize`: the window's, or what the devtools' dock
* leaves of it while the panel is docked, so a dock coming, moving or
* being dragged is one too; `win.size()` queries the same numbers. */
export interface ResizeEvent {
width: number;
height: number;
scale: number;
}
/** A window's lifecycle or its keyboard. `opened` / `closed` arrive as a
* `windows` entry's `onWindow`, with the window's `id` — on whichever
* window's frame noticed; a closed window's is the last `onWindow` its
* entry declared. A window the user closed stays closed while it is
* still declared (a declaration reopens a window only when it *starts*):
* stop declaring it, then declare it again. `focused` / `blurred` arrive
* as the root's `windowEvents.onFocus`: this window gained or lost the
* keyboard (backlog DX18), and carry no id. */
export interface WindowEvent {
phase: 'opened' | 'closed' | 'focused' | 'blurred';
/** `opened` / `closed` only: what that window's events carry in
* `window`. */
id?: number;
}
/** The physical modifier state changed, as the root's
* `windowEvents.onModifiers`. */
export interface ModifiersEvent {
shift: boolean;
ctrl: boolean;
alt: boolean;
super: boolean;
}
/** The OS asked the app to open these documents (backlog F124), as the
* main window's `windowEvents.onOpen`: the Finder's Open With, a file
* dropped on the Dock icon, `open -a`, a double-click on a document type
* the app's Info.plist declares (`CFBundleDocumentTypes`) — whether or
* not the app asked, at launch once the window is open, and while it
* runs. `paths` are file-system paths. macOS only: Windows and Linux
* hand documents over in `process.argv`. `ctx.openDocuments(paths)` is
* the headless drive. */
export interface OpenEvent {
paths: string[];
}
/** The `click` field: a click on a node that can say more than "it was
* clicked" (`ClickEvent`). */
export interface WithClick {
click: ClickEvent;
}
/** The `drag` field, on an `onDrag` message. */
export interface WithDrag {
drag: DragEvent;
}
/** The `key` field, on an `onKey` message. */
export interface WithKey {
key: KeyEvent;
}
/** The `text` field, on an `onKey` message. */
export interface WithText {
text: TextEvent;
}
/** The `preedit` field, on an `onKey` message. */
export interface WithPreedit {
preedit: PreeditEvent;
}
/** The `select` field, on an `onKey` message. */
export interface WithSelect {
select: SelectEvent;
}
/** What an `onKey` sink hears: a key, committed text, a composition or a
* selection set by assistive technology — one message for all four, told
* apart with `'key' in msg`. */
export type WithKeySink = WithKey | WithText | WithPreedit | WithSelect;
/** The `selectionrange` field, on an `onSelectionRange` message. */
export interface WithSelectionRange {
selectionrange: SelectionRangeEvent;
}
/** The `contextmenu` field, on an `onContextMenu` message. */
export interface WithContextMenu {
contextmenu: ContextMenuEvent;
}
/** The `menu` field, on an `onMenu` message. */
export interface WithMenu {
menu: MenuEvent;
}
/** The `forceclick` field, on an `onForceClick` message. */
export interface WithForceClick {
forceclick: ForceClickEvent;
}
/** The `button` field, on an `onButton` message. */
export interface WithButton {
button: ButtonEvent;
}
/** The `scroll` field, on an `onScroll` message. */
export interface WithScroll {
scroll: ScrollEvent;
}
/** The `focus` field, on an `onFocus` message. */
export interface WithFocus {
focus: FocusEvent;
}
/** The `hover` field, on an `onHover` message. */
export interface WithHover {
hover: HoverEvent;
}
/** The `drop` field, on an `onDrop` message. */
export interface WithDrop {
drop: DropEvent;
}
/** The `files` field, on the message `requestFiles` was given. */
export interface WithFiles {
files: FilesEvent;
}
/** The `layout` field, on an `onLayout` message. */
export interface WithLayout {
layout: LayoutEvent;
}
/** The `range` field, on an `onRange` message. */
export interface WithRange {
range: RangeEvent;
}
/** The `query` field, on an `onQuery` message. */
export interface WithQuery {
query: QueryEvent;
}
/** A type-ahead search a `list` or `table` composite's built rows did not
* answer (docs/adr/0070): the whole search so far, lower-cased. Answer
* with `answerTypeahead(key, index)`. */
export interface TypeaheadEvent {
text: string;
}
/** The `typeahead` field, on an `onTypeahead` message. */
export interface WithTypeahead {
typeahead: TypeaheadEvent;
}
/** A key a composite's focused item did not claim (backlog C120), on the
* composite's `onItemKey`: Delete on a checklist's row. The press is a
* `key` event's (always `down`); `item` is the focused item's key,
* `index` its data `index` (else its place among the items), `column` a
* table cell's column. */
export interface ItemKeyEvent {
phase: 'down';
code: string;
physical: string;
shift: boolean;
ctrl: boolean;
alt: boolean;
super: boolean;
text: string | null;
repeat: boolean;
location: KeyLocationName;
caps_lock: boolean;
num_lock: boolean;
item: number;
index: number;
column?: number;
}
/** The `itemkey` field, on an `onItemKey` message. */
export interface WithItemKey {
itemkey: ItemKeyEvent;
}
/** The `change` field of an editor's `onChange` message. */
export interface WithEditChange {
change: EditChangeEvent;
}
/** The `change` field of a slider's `onChange` message. */
export interface WithSliderChange {
change: SliderChangeEvent;
}
/** The `boundary` field, on an `onBoundary` message. */
export interface WithBoundary {
boundary: BoundaryEvent;
}
/** The `sound` field, on a playback's message. */
export interface WithSound {
sound: SoundEvent;
}
/** The `capture` field, on the message `captureTo` or `recordTo` named. */
export interface WithCapture {
capture: CaptureEvent;
}
/** The `dismiss` field, on a `modal` message or a popup's `onDismiss`. */
export interface WithDismiss {
dismiss: DismissEvent;
}
/** The `resize` field, on `windowEvents.onResize`. */
export interface WithResize {
resize: ResizeEvent;
}
/** The `window` field, on a `windows` entry's `onWindow` or
* `windowEvents.onFocus`. */
export interface WithWindow {
window: WindowEvent;
}
/** The `system` field, on `windowEvents.onSystemSettingsChange`: an OS
* setting changed while the app was open — the appearance, the accent
* colour, reduced motion or the UI language — or assistive technology
* started listening (one per window that noticed). It is `env().system`
* as it now reads.
*
* A window's view runs when a message changes the model, so without it a
* palette picked from `env().system.appearance` is the one the first
* frame read and stays it: the driver's redraw re-lowers the tree it was
* handed, it does not re-run `view`. The first frame establishes the
* reading rather than reporting it, the way a resize does. */
export interface WithSystem {
system: SystemEnv;
}
/** The `modifiers` field, on `windowEvents.onModifiers`. */
export interface WithModifiers {
modifiers: ModifiersEvent;
}
/** The `open` field, on `windowEvents.onOpen`. */
export interface WithOpen {
open: OpenEvent;
}
/** The app's message `T` as a click with data arrives (`WithClick`). */
export type ClickMsg = T & WithClick;
/** The app's message `T` as an `onDrag` drag arrives. */
export type DragMsg = T & WithDrag;
/** The app's message `T` as an `onKey` key press arrives. */
export type KeyMsg = T & WithKey;
/** The app's message `T` as committed text on an `onKey` sink arrives. */
export type TextMsg = T & WithText;
/** The app's message `T` as a composition on an `onKey` sink arrives. */
export type PreeditMsg = T & WithPreedit;
/** The app's message `T` as a selection set on an `onKey` sink arrives. */
export type SelectMsg = T & WithSelect;
/** The app's message `T` as everything an `onKey` sink hears arrives:
* one of four, told apart with `'key' in msg`, `'text' in msg`, … */
export type KeySinkMsg = T & WithKeySink;
/** The app's message `T` as an `onSelectionRange` ask arrives. */
export type SelectionRangeMsg = T & WithSelectionRange;
/** The app's message `T` as an `onContextMenu` press arrives. */
export type ContextMenuMsg = T & WithContextMenu;
/** The app's message `T` as an `onMenu` choice arrives. */
export type MenuMsg = T & WithMenu;
/** The app's message `T` as an `onForceClick` press arrives. */
export type ForceClickMsg = T & WithForceClick;
/** The app's message `T` as an `onButton` press, move or release arrives. */
export type ButtonMsg = T & WithButton;
/** The app's message `T` as an `onScroll` gesture arrives. */
export type ScrollMsg = T & WithScroll;
/** The app's message `T` as an `onFocus` move arrives. */
export type FocusMsg = T & WithFocus;
/** The app's message `T` as an `onHover` enter or leave arrives. */
export type HoverMsg = T & WithHover;
/** The app's message `T` as an `onDrop` event arrives. */
export type DropMsg = T & WithDrop;
/** The app's message `T` (a file dialog's `tag`) as its answer arrives. */
export type FilesMsg = T & WithFiles;
/** The app's message `T` as an `onLayout` rect arrives. */
export type LayoutMsg = T & WithLayout;
/** The app's message `T` as an `onRange` node's rows in view arrive. */
export type RangeMsg = T & WithRange;
/** The app's message `T` as a composite's unanswered type-ahead arrives. */
export type TypeaheadMsg = T & WithTypeahead;
/** The app's message `T` as a key a composite's item left arrives. */
export type ItemKeyMsg = T & WithItemKey;
/** The app's message `T` as an `onQuery` node's matched entries arrive. */
export type QueryMsg = T & WithQuery;
/** The app's message `T` as an editor's `onChange` arrives. */
export type EditChangeMsg = T & WithEditChange;
/** The app's message `T` as a slider's `onChange` arrives. */
export type SliderChangeMsg = T & WithSliderChange;
/** The app's message `T` as an editor's `onBoundary` arrives. */
export type BoundaryMsg = T & WithBoundary;
/** The app's message `T` (a playback's `tag`) as its end arrives. */
export type SoundMsg = T & WithSound;
/** The app's message `T` (a `modal`, a popup's `onDismiss`) as its
* dismissal arrives. */
export type DismissMsg = T & WithDismiss;
/** The app's message `T` as `windowEvents.onResize` arrives. */
export type ResizeMsg = T & WithResize;
/** The app's message `T` as a `windows` entry's `onWindow` or
* `windowEvents.onFocus` arrives. */
export type WindowMsg = T & WithWindow;
/** The app's message `T` as `windowEvents.onSystemSettingsChange` arrives. */
export type SystemMsg = T & WithSystem;
/** The app's message `T` as `windowEvents.onModifiers` arrives. */
export type ModifiersMsg = T & WithModifiers;
/** The app's message `T` as `windowEvents.onOpen` arrives. */
export type OpenMsg = T & WithOpen;
/** A file dialog to ask for with `requestFiles`, and what
* `takeFileRequests` hands a host that shows it itself. Every field is
* optional: an Open dialog for one file, any type, is `{}`. */
export interface FileDialogOptions {
/** `'open'` (the default), `'save'` or `'folder'`. */
mode?: 'open' | 'save' | 'folder';
/** More than one file or folder may be picked (open and folder). */
multiple?: boolean;
title?: string;
/** The file types offered, the first chosen; extensions without the dot. */
filters?: { name: string; extensions: string[] }[];
/** The folder it opens in. */
directory?: string;
/** A save dialog's suggested name. */
fileName?: string;
/** The message the answer arrives as, `files: { paths }` in it (a
* `FilesMsg`); without one it arrives as `{ files }` alone. */
tag?: HandlerMsg;
}
// -- a window's own events (ADR 0048) ---------------------------------------
/** The root box's `windowEvents` group: the messages the window's own
* events arrive as, each with its data in the field named for the event
* (`onResize: { kind: 'resized' }` is heard as `{ kind: 'resized',
* resize: { width, height, scale } }`). A key left out is an event the
* window does not hear; `env()` reads every fact they report either way.
* Root only — on any other node it is ignored and warned about
* (`window-events-off-root`). `onOpen` is read on the main window alone,
* since the OS opens documents to the app; `onFonts` carries no data, so
* it takes any message `A` and arrives as declared. A host that retains
* its tree re-runs the view only for a message, so a view that follows
* the OS's appearance declares `onSystemSettingsChange`. */
export interface WindowEvents {
onResize?: HandlerMsg | null;
/** This window's keyboard, `window: { phase: 'focused' | 'blurred' }`;
* not the node row `onFocus`. */
onFocus?: HandlerMsg | null;
onSystemSettingsChange?: HandlerMsg | null;
/** The system's installed fonts changed (a rescan found a face
* installed or removed). Re-read `systemFonts()` here if the model
* holds the list; a `family` named in the view needs nothing. A font
* the app loads itself raises none. */
onFonts?: A | null;
onModifiers?: HandlerMsg | null;
onOpen?: HandlerMsg | null;
}
/** One entry of `windows(model)` (or of the root box's `windows` prop): a
* window that should exist, by stable name. `width`/`height` are the
* initial inner size in logical px (640x480 when left out) and are read on
* the frame the window opens and never again — the user owns its geometry
* once it exists. `activates` is whether opening it takes OS focus
* (default true for a normal window, false for a popup). A bare string is
* a name at the defaults.
*
* `kind: 'popup'` makes it a menu surface instead: borderless, off the
* taskbar, owned by the window that declared it and closed with it, placed
* in screen coordinates against `anchor` — the `{x, y, w, h}` a
* `LayoutEvent` already reports for the field or button the menu belongs to
* — and non-activating, so the field keeps its focus ring while the arrows
* walk the list. A press outside it or Escape arrives as its `onDismiss`
* message (a `DismissMsg`) and closes nothing: stop declaring the window, the way you stop
* declaring a `modal` node. Reach for one only where an in-window float
* cannot go — a list taller than the window, a menu with nowhere in-window
* to sit, a panel beside the app; everything else is cheaper as a `float`
* with `fit`. See `docs/adr/0004-multi-window.md`, decision 9. */
export type WindowDecl =
| string
| {
name: string;
kind?: 'normal' | 'popup';
width?: number;
height?: number;
activates?: boolean;
/** `kind: 'popup'` only: what to place it against, in the declaring
* window's own logical coordinates — a `LayoutEvent`'s rect. */
anchor?: { x?: number; y?: number; w?: number; h?: number };
/** The message its opening and closing arrive as, with `window:
* { phase: 'opened' | 'closed', id }` in it (ADR 0048). */
onWindow?: HandlerMsg | null;
/** A popup's: the message a press outside it or Escape arrives as,
* with `dismiss: { reason, id }` in it. */
onDismiss?: HandlerMsg | null;
};
/** What `Ctx.windowCommands()` drains: what chrome nodes asked for
* (`startDrag` / `close` / `minimize` / `toggleMaximize`, about `window`)
* and what the declared window set decided (`open` with the new window's
* id and the config from its declaration, `close`). A `KuiWindow` applies
* these itself. */
export type WindowCommand =
| { kind: 'startDrag' | 'close' | 'minimize' | 'toggleMaximize'; window: number }
| { kind: 'setSize'; window: number; width: number; height: number }
| { kind: 'focus'; window: number }
| { kind: 'redraw'; window: number }
| { kind: 'setFullscreen'; window: number; enabled: boolean; display: number | null }
| { kind: 'setVisible'; window: number; visible: boolean }
| { kind: 'setCloseHides'; window: number; enabled: boolean }
| {
kind: 'open';
window: number;
/** The window whose frame declared this one: a popup's owner, whose
* position its `anchor` is measured against and whose closing closes
* it. */
owner: number;
/** Whose declaration won: 0 is your app, 1+ an extension. */
origin: number;
config: {
kind: 'normal' | 'popup' | 'surface';
width: number;
height: number;
activates: boolean;
anchor: { x: number; y: number; w: number; h: number };
};
};
// -- generated from the core's event table; edit EVENTS in crates/kui-core/src/schema.rs, then `npm run gen` --
/** Which event it was, as `UiEvent.event` spells it: every row of the
* events table in docs/props.md. */
export type EventName =
| 'click' | 'drag' | 'key' | 'text' | 'preedit' | 'select'
| 'selectionrange' | 'contextmenu' | 'menu' | 'forceclick' | 'button'
| 'scroll' | 'focus' | 'hover' | 'drop' | 'files' | 'open' | 'layout'
| 'resize' | 'window' | 'system' | 'fonts' | 'modifiers' | 'change'
| 'submit' | 'cancel' | 'boundary' | 'sound' | 'capture' | 'dismiss'
| 'component' | 'range' | 'query' | 'typeahead' | 'itemkey';
// -- end generated --
/** A position in an editor's text: one of its `runs` and a character
* index into it (the run's character count is its end). */
export interface TextPos {
run: string;
character: number;
}
/** One laid-out line (or a piece of one) of an editor's text, with every
* character placed — what a screen reader reads by character and word.
* A line that continues ends with its `"\n"`, a character of no width. */
export interface AccessRun {
key: string;
/** The line it belongs to and its byte range in that line's text. */
line: number;
start: number;
end: number;
text: string;
rect: { x: number; y: number; w: number; h: number };
charLengths: number[];
/** Each character's x relative to `rect.x`, and its width. */
charPositions: number[];
charWidths: number[];
/** Character indices where words start. */
wordStarts: number[];
rtl: boolean;
}
/** The argument of `access(key, 'setTextSelection', …)`: the end that
* stays (`anchor`) and the caret (`focus`); `text` rides along for the
* text actions when given as an object. */
export interface AccessArg {
anchor?: TextPos;
focus?: TextPos;
text?: string;
}
// -- generated from the core's access lists; edit Role::ALL / AccessAction::ALL in crates/kui-core/src/access.rs, then `npm run gen` --
/** Every role a node of the tree can report: the ones a view declares
* (`role`), the ones the core derives (a `cells` grid is a `terminal`,
* an editor a text input, a scrolling box a scroll view, the root the
* window). */
export type AccessRole =
| 'none' | 'button' | 'checkbox' | 'radio' | 'switch' | 'slider' | 'tab'
| 'tabList' | 'link' | 'heading' | 'list' | 'listItem' | 'image' | 'dialog'
| 'group' | 'window' | 'titleBar' | 'staticText' | 'textInput'
| 'multilineTextInput' | 'scrollView' | 'line' | 'radioGroup' | 'menu'
| 'menuItem' | 'terminal' | 'passwordInput' | 'table' | 'row' | 'cell'
| 'columnHeader' | 'rowHeader' | 'progress' | 'meter';
/** What assistive technology can ask of a node (`access(key, action)`). */
export type AccessAction =
| 'click' | 'focus' | 'blur' | 'setValue' | 'increment' | 'decrement'
| 'scrollIntoView' | 'scrollUp' | 'scrollDown' | 'scrollLeft'
| 'scrollRight' | 'setTextSelection' | 'replaceSelectedText';
// -- end generated --
/** One semantic node of a frame. Plain boxes are elided, so `parent` is
* the nearest semantic ancestor. */
export interface AccessNode {
key: string;
parent: string | null;
origin: number;
role: AccessRole;
/** `label`, else the node's own text, else (for buttons, links, tabs,
* headings) the text inside it, else the window title for the root. */
name: string | null;
/** What the `description` prop sets, or the `tooltip` shorthand: both
* write this one slot, and the later declaration wins. */
description: string | null;
/** Logical px, viewport coordinates, cut to the clip the node is drawn
* under: a node wholly clipped away is a zero-size rect on the clip's
* edge, still in the tree and actionable. */
rect: { x: number; y: number; w: number; h: number };
/** The node's one string value: an editor's text, with its caret and
* non-empty selection as byte offsets, or a slider's `valueText` — a
* slider that named its reading reads as that instead of its number. */
value: string | null;
caret: number | null;
selection: [number, number] | null;
/** An editor's laid-out text, run by run; empty for anything else. */
runs: AccessRun[];
/** The caret (`focus`) and the selection's other end (`anchor`, equal
* to `focus` without a selection) as run positions. */
anchor: TextPos | null;
focus: TextPos | null;
/** `checked` for checkbox / radio / switch roles. */
checked: boolean | null;
/** A checkbox that is neither on nor off (`mixed`, ADR 0034). */
mixed: boolean;
/** The current one of a set. Every `tab` carries it; a `listItem` or a
* `link` only where the view set `selected`. */
selected: boolean | null;
/** A disclosure's state, as declared. `null` = it does not expand. */
expanded: boolean | null;
/** "3 of 7", derived from the composite container holding this node: the
* zero-based ordinal on each item, the count on the container. */
posInSet: number | null;
setSize: number | null;
/** Where the node sits in a table, zero-based (ADR 0070): a cell's and a
* row's row (a windowed table's or list's row its data `index`), a
* cell's column (which links it to the `columnHeader` above it), and on
* the table its row count (a windowed one's `rowCount`) and its longest
* row. A `list`'s items carry `rowIndex` and the list `rowCount`. */
rowIndex: number | null;
columnIndex: number | null;
rowCount: number | null;
columnCount: number | null;
/** A table one of whose cells takes focus, and its rows and cells: a
* composite, which a reader is told is a grid. */
cellsFocus: boolean;
/** How a composite container (`radioGroup`, `tabList`, `menu`, `list`)
* arranges its items, from its own `dir`. `null` for anything else. */
orientation: 'horizontal' | 'vertical' | null;
/** `valueNow` / `valueMin` / `valueMax` for a slider, a progress bar or
* a meter (a busy progress bar has no `valueNow`). What the position
* reads as is `valueText`, which arrives in `value` above. */
valueNow: number | null;
valueMin: number | null;
valueMax: number | null;
/** A slider's `valueStep`, where it declared one (ADR 0034). */
valueStep: number | null;
/** Holds keyboard focus (`focused()` names the same node). */
focused: boolean;
/** Declared `disabled`: inert, and not a Tab stop. */
disabled: boolean;
/** The frame's `modal` surface (`aria-modal`): focus and input are
* confined to its subtree, everything else is inert. Only the modal in
* effect — the last one declared — carries it. */
modal: boolean;
scroll: { x: number; y: number; maxX: number; maxY: number } | null;
/** The requests this node accepts. */
actions: AccessAction[];
/** Declared `live`: when the text inside this node changes, a reader
* reads the change without being asked. `'off'` for every other node
* (`docs/adr/0008-live-regions-and-announcements.md`). */
live: Live;
}
/** The semantic nodes of a frame in tree order (root first) — what a
* screen reader sees, as data. Assert on it in tests. */
export interface AccessTree {
nodes: AccessNode[];
/** The node holding keyboard focus. */
focus: string | null;
/** Changes when anything above does. */
hash: string;
}
/** What `cursorShape()` reports: the `cursor` prop's own vocabulary, so a
* test compares against `'text'` and the two cannot drift. */
export type CursorShape = NonNullable;
/** Where a point landed in the text a keyed node drew (`textHit`): a byte
* offset into that text — across the node's text runs in order, the way
* the access tree reads a `line` — and the visual (wrapped) line, 0-based.
* `byte` is a caret position: between two characters, past the last one
* at the end. */
export interface TextHit {
byte: number;
line: number;
}
/** The application menu as the core holds it (`Ctx.menuBar()`): what a
* host with a menu bar of its own reads after `setNativeMenuBar(true)`.
* `revision` changes only when the declaration does, so a host keeps the
* last one it built and rebuilds nothing until the number moves. */
export interface MenuBarState {
revision: number;
/** The platform's standard menus are kept around these
* (``, ADR 0052). */
standardMenus: boolean;
menus: {
label: string;
enabled: boolean;
items: OpenMenuItem[];
}[];
}
/** One row of a menu, as `Ctx.menu()` and `Ctx.menuBar()` both report it
* (`docs/adr/0017-selection-as-a-scope.md`): what the drawn menu would
* show. `label` is the row's own text or, for a standard role that
* declared none, the role's wording; a host rendering natively uses `role`
* to pick the platform's own wording instead, and draws `accel` beside
* it. */
export interface OpenMenuItem {
label: string;
role: MenuItemRole;
/** Drawn with a checkmark: a setting the row *is* rather than a command
* it runs. Present on every row; a context menu's rows can carry it as
* a bar's can. */
checked: boolean;
/** A disabled row is drawn dimmed and cannot be chosen — Paste with an
* empty clipboard, Copy with no selection. Present rather than absent,
* so a menu's rows do not move under the pointer. */
enabled: boolean;
/** Display only: the shortcut is the app's or the platform's. The row's
* own, or its role's default (`⌘C` on a `copy` row that declared none);
* null where there is neither. */
accel: string | null;
/** The rows of the submenu this row opens, read the same way; absent on
* a row that opens none. A row with them is never chosen itself: report
* a row inside with `activateMenuPath`. */
items?: OpenMenuItem[];
}
/** The menu a window has open (`Ctx.menu()`): where it opened, the node it
* is about, and its rows. Read it after `setNativeMenus(true)`, show it
* however the platform does, and answer with `activateMenuItem(i)` or
* `closeMenu()`. */
export interface OpenMenu {
/** The node the menu is about; chosen rows post their event on it. */
target: string;
x: number;
y: number;
items: OpenMenuItem[];
}
/** What choosing a menu row left for the host (`Ctx.takeMenuActions()`).
* The clipboard is the host's in this library: the core works out *what*
* to copy, which is the half only it can do, and hands over the text.
*
* `setClipboard` carries `text` (and `html` where the selection had
* formatting to carry — beside the text, never instead of it);
* `setClipboardSecret` carries a secret to write marked concealed and
* transient; `paste` asks for what is on the clipboard, delivered back
* with `Ctx.paste(text, marks)` (or `Ctx.commit(...)`, a paste nothing
* marked) — a focused editor takes it as typing, a focused
* `onKey` sink hears it as a `text` event; `lookUp` asks for the
* platform's definition panel for `text`, anchored at the baseline
* origin `x`, `y`. A view queues the first two itself with
* `setClipboard` / `requestPaste`. */
export type MenuAction =
| { kind: 'setClipboard'; text: string; html: string | null }
/** A secret to write marked concealed and transient, the way a password
* manager does (`setClipboardSecret`, backlog F84). */
| { kind: 'setClipboardSecret'; text: string }
/** A picture for the clipboard (`setClipboardImage`,
* `captureToClipboard`), by its size: a window writes it itself, and a
* headless host holds the pixels it asked with or `capture()`s them. */
| { kind: 'setClipboardImage'; width: number; height: number }
| { kind: 'paste' }
| { kind: 'lookUp'; text: string; x: number; y: number }
/** A file to show in the system's file manager: the devtools' "open
* folder" (backlog F203). Apply it with `showInFolder(path)`. */
| { kind: 'showInFolder'; path: string }
/** Files for the clipboard, as a file manager's Copy puts them there
* (`setClipboardFiles`, backlog F247): a window writes them itself. */
| { kind: 'setClipboardFiles'; paths: string[] }
/** A recording to open in kui-perf, the trace inspector — the devtools'
* "open in kui-perf" once the Perf tab saved it (backlog F253). Apply it
* with `openRecording(path)`, and `showInFolder(path)` should that throw. */
| { kind: 'openRecording'; path: string };
/** What text measures (`measureText`): logical px at the scale of the
* current or last frame; `lines` after wrapping. The same numbers layout
* gives a `` with that content and style. */
export interface TextMetrics {
width: number;
height: number;
lines: number;
}
// -- generated from the core's warning codes; edit crates/kui-core/src/diag.rs, then `npm run gen` --
export type WarningCode =
/** A grow weight other than 1 on the only grow child of its parent (the
* weight splits space between grow siblings, so alone it changes nothing) or
* across the parent's main axis (cross-axis grow fills the parent whatever
* its weight). */
| 'grow-weight-ignored'
/** The child count of a node changed while one of its children carries a
* transition under an auto-assigned key. Auto keys are sibling positions, so
* the children that shifted became new nodes and snapped instead of easing.
* Give list items a key. */
| 'transition-auto-key'
/** Two nodes in one frame share a key: everything retained per key
* (transitions, scroll offsets, editors, layout events, hover state) is
* mixed between them. Siblings need distinct keys. */
| 'duplicate-key'
/** A label resolved by name (`focus("beta")` in Node, `env.set_focus("beta")`
* in Lua, `kui_key_of` in C) is declared by more than one node in the frame,
* under different parents, so they have distinct keys and the name picked
* the first in tree order. Labels are unique among siblings, not across a
* tree. An extension asking from inside a fill is answered from the nodes
* that fill opened and no one else's — not even its own other instances' —
* and the host from its own first; so this is a clash among the asker's own.
* Give the node meant a label nothing else declares, or pass the hex key an
* event carried. Two nodes with the *same* key are `duplicate-key`. */
| 'ambiguous-key'
/** A lookup by accessible name (`Core::key_named`, `ctx.keyNamed`,
* `kui_key_named`) found more than one node with that name in the last frame
* — two buttons both read as "Delete" — and used the first in tree order. A
* reader hears the same name twice too: give each a `label` that says which,
* or look the one meant up by its key label. When one of them is static text
* and another is not — a caption under the button it repeats — the message
* says so: a caption a reader need not hear is decorative, and `role="none"`
* on the box around it takes it out of the tree (backlog F140). */
| 'ambiguous-name'
/** A `focusRegion(name)` (`Core::focus_region`, `env.focus_region`,
* `kui_focus_region`) named a node the frame after it did not declare as a
* `focusRegion` — no node under the label, or a node without the row — so
* nothing was entered and focus stayed where it was. The call is resolved
* against the frame it lands on, so an `update` that toggles a dock on and
* enters it in one go is fine; this is that call with the view half missing,
* with a name the view spells differently, or naming a node that is not a
* region. */
| 'focus-region-without-node'
/** A `reveal` or `setScroll` by label (`env.reveal("rows")`,
* `win.reveal("rows")`, `Core::reveal_label`) named a label the frame it
* resolved against did not declare, so nothing moved. A label is resolved
* when the frame finishes, so a view may name a node it is declaring right
* now, or one the next frame declares; this is the name spelled differently
* from the `key` that declares it, or the node not declared at all. */
| 'label-without-node'
/** A text's `family` named a family no installed or loaded font has, so it
* shaped as sans; or a family token's fallback list matched nothing, so a
* text naming the token shapes as sans and the message names the token (ADR
* 0049). `sans`, `serif` and `mono` are kui's own; any other name is matched
* as `addSystemFont` matches it, and `systemFonts()` lists the names a
* machine has. */
| 'unknown-family'
/** A `selectable` node inside another `selectable` node. Selection scopes do
* not nest: the innermost one owns every run under it, so the outer scope
* selects only the text outside the inner one — and a drag that crosses the
* boundary stops there, which reads as a selection that will not extend.
* Declare the scope once, on the container whose text should select as one. */
| 'nested-selection-scope'
/** An image with no `label`: assistive technology has nothing to say for it.
* Decorative images take `role="none"`. */
| 'image-without-label'
/** A `slider` (or a `progress` or `meter`, which read the same rows) whose
* `valueNow` lies outside its own `valueMin` / `valueMax`, or whose
* `valueMin` is above its `valueMax`. The row is advertised verbatim, so a
* screen reader reads a value the range says is impossible; the app that
* clamps in its own `update` keeps the range in two places with nothing
* tying them, and this is the tie. Declare the range the value is really
* held to, or clamp where the view declares it. */
| 'slider-value-out-of-range'
/** `Core::add_fragment` was given WGSL that does not compile, so no handle
* was minted and nothing will draw. The message carries naga's own error
* with the line numbers moved into the app's source. The source is rejected
* here rather than at the first frame that shows it, so a headless test sees
* it too. */
| 'fragment-rejected'
/** A `fragment` node declared more than sixteen `params`. The shader takes
* four `vec4` and no more, so the extra numbers were dropped; pass
* fewer, or pack what the fragment needs into the sixteen it has. */
| 'fragment-params-truncated'
/** A `polygon` declared more than eight points: the stock fragment takes
* eight vertices in the sixteen params it has, so the rest were dropped. Two
* polygons, or a `path`, which takes any outline. */
| 'polygon-points-truncated'
/** A `path`'s `d` did not parse: the message names the byte and what was
* expected there (a number, a command letter, an arc flag). Or the path
* holds a number that is not finite - a NaN or an infinity, which `1e99` in
* `d` is - among its coordinates or in its turn. The node draws nothing.
* Raised once per key. */
| 'path-malformed'
/** A `path`'s mask is wider or taller than a texture the device can hold, so
* it draws nothing: the message names the size and the limit. Draw it
* smaller, or as several paths. */
| 'path-too-large'
/** The frame's modal surface is not in a float, and content painted after it
* is drawn on top of it: everything the user can see over the modal is
* inert, which looks like inert-behind is broken. A modal that has to cover
* the app is a float (`float="viewport"`). Also raised for a modal that *is*
* a float when another float from outside its scope stacks over it: a HUD
* opened after the dialog is the same inert surface over it. */
| 'modal-behind-content'
/** A control (a button, link, tab, checkbox, slider, editor) with no
* computable name: no `label`, and no text inside it. Icon buttons and
* editors need a `label`. */
| 'control-without-name'
/** A focusable node inside a composite's *item* — a button inside a list row,
* a link inside a tab. The item is one roving stop of a composite, so the
* Tab ring stops at the item and nothing reaches what is inside it:
* declared, and impossible, which is what `modal-behind-content` set the
* precedent for. A focusable node inside the *container* but outside every
* item — a "+" at the end of a tab bar — is reachable and is not reported. */
| 'focusable-inside-item'
/** A control — anything focusable or with a click — inside a `live` region. A
* live region reads as one message, its subtree presentational (that is what
* makes every platform announce it), so assistive technology cannot reach
* the control at all: a notice's Retry, a toast's close button. Put `live`
* on the node holding the message alone, beside the controls. */
| 'control-inside-live'
/** A `radio` with no `radioGroup` above it, or a `tab` with no `tabList` —
* the stock `` included. Outside its container an item is no
* composite's: each one is a Tab stop of its own, the arrows, Home and End
* do not move the choice, and a screen reader announces no "2 of 3". Wrap
* the set in the container, labelled with what the choice is. A `menuItem`
* or `listItem` on its own is not reported: the menus build their own
* container, and a row outside a list is only a looser reading. */
| 'item-outside-container'
/** A `modal` surface with no `label`. A dialog is not named by the text
* inside it (it is not one of ARIA's name-from-content roles), so a screen
* reader announces it as an unnamed dialog — the same silent defect
* `control-without-name` catches, on the node that just took the user's
* focus. Only the derived dialog role is checked: a modal that says what it
* is with an explicit `role` says it with a `label` too, or means something
* naming works differently for. */
| 'modal-without-name'
/** A node declares `live` but carries no `label` and holds no text, so
* nothing it ever does can be announced: every platform derives the spoken
* string from a name, and there is none to derive. The same silent defect
* `image-without-label` catches, on the node that was meant to speak. */
| 'live-region-without-name'
/** The same announcement text was queued on two consecutive frames. That is
* what an unguarded `announce` in a frame builder looks like — a view runs
* every frame, so the message is said every frame — and it is never what an
* app means: a message genuinely repeated is repeated across frames the user
* did something in between. The announcement still goes through; this names
* the builder that is shouting. */
| 'announcement-repeated'
/** `wrapChildren` on a container that cannot break lines: a column, a row
* whose main axis scrolls, or a row of a table, whose children are the
* table's columns. All lay out exactly as if the flag were absent, which
* reads as "wrapping is broken"; see `LayoutSpec::wrap` for why a column
* cannot have it. */
| 'wrap-ignored'
/** An alignment declared where it means nothing: a spread (`spaceBetween` /
* `spaceAround` / `spaceEvenly`) on `crossAlign`, `baseline` on `mainAlign`
* or on a column's `crossAlign`, or either as a float's attach point. Each
* lays out as `start` — the two centring spreads as `center` — which reads
* as "the value is broken" when it is the axis that is wrong. */
| 'align-ignored'
/** An `aspectRatio` with nothing it can set: both axes are declared, or the
* width is `fit` under a `grow` or percent height, which is resolved only
* after every width is. The ratio sizes a fit height from the width, or a
* fit width from a fixed height. */
| 'aspect-ignored'
/** A `backdropBlur` under an opaque `bg` of the node's own: the background
* paints over the whole blur, so nothing of it shows and the copy and the
* passes are spent for nothing. Give the `bg` some transparency
* (`#ffffff40`) — frosted glass is a translucent fill over a blur (backlog
* F129). */
| 'backdrop-blur-hidden'
/** A `revealOnHover` node with no ancestor that tracks the pointer — no
* `onClick`, `hoverBg`, `hoverable` or other hit region above it — so
* nothing's hover can show it, and it is drawn always rather than hidden for
* good. Put `hoverable` on the row or group whose hover should show it (ADR
* 0051). */
| 'reveal-without-anchor'
/** A text node sits more than four levels below the `line` row above it,
* which is as far as a text's place remembers its ancestors — so `textHit` /
* `caretRect` asked by that row's key cannot find the run, and a press
* inside it reports `byte: 0`. Flatten the wrappers between the row and its
* text, or ask by a nearer key. */
| 'text-beyond-line'
/** One frame removed more nodes declaring `exit` than the exit store will
* hold (4096, `depart::MAX_NODES`), so none of that frame's removal
* animated: every departing node of it vanished at once, as a node with no
* `exit` does, rather than some sliding out and the rest blinking. Correct,
* and invisible from the outside, which is the whole reason it is a line
* here: a list that drops a thousand rows wants `exit` on the list, not on
* every row. A removal that fits the budget but finds earlier exits still in
* flight evicts those, oldest first, and is not this warning. */
| 'exit-budget'
/** A prop name nothing claims: not a schema row, not a composite, not one of
* the element's own props (see `schema::known_prop`). The binding threw the
* declaration away — `hoverBg` in a Lua table, `onclick` in JSX — so unlike
* every other code here this one is raised by the frontend that saw it,
* through `Core::warn`: by the time a frame is a tree the name is gone. The
* message names the likely spelling. Also raised for a key a menu row map
* carried that no row reads — `disabled` on a select's option, where the key
* is `enabled` — by the binding that read the row. */
| 'unknown-prop'
/** The process has spelled 65 536 distinct size expressions — the most the
* table every window shares keeps, and never lets go of — and one more was
* declared: that prop is left at its default (a `width` is fit, a clamp
* none) instead of failing the frame, and so is every new expression after
* it; the ones kept still resolve. A view that makes a new expression per
* frame reaches it — a `{ max: [dragX, { percent: 30 }] }` fed a splitter's
* fractional drag, a `format!` of the pointer — where one expression per
* layout, with the moving part a px size beside it, would not. Raised once
* per core; the message names the last expression refused. */
| 'size-expressions-full'
/** One name declared with two different window configs on the frame it
* opened. The config is read on the opening edge only, and on that edge the
* lowest declaring window wins (the first declaration within one frame), so
* the pick is deterministic — but two places in the app disagree about what
* `"palette"` is, and only one of them is right. */
| 'duplicate-window-config'
/** A window the user closed is still declared, so it stays closed: a
* declaration reopens a window only when it *starts*, and this one never
* stopped. The first version of every multi-window app does this — it
* declares the window unconditionally — and from outside it looks like
* `windows` being ignored. Handle the entry's `onWindow` message (its
* `window: {phase: "closed", id}`), stop declaring the name, and declare it
* again to reopen. */
| 'window-declared-while-closed'
/** A window declared with a `KUI_WINDOW_KIND_*` this build does not have —
* `KUI_WINDOW_KIND_NORMAL`, `KUI_WINDOW_KIND_POPUP` and
* `KUI_WINDOW_KIND_SURFACE` are the three there are. Only a C host can reach
* this: JSX and Lua name a kind by string, so an unknown one is refused
* where it is written rather than reported a frame later. The window still
* opens, as a normal one, so a host built against a later header degrades to
* a window rather than to nothing; this line is what keeps that from being
* silent. */
| 'unknown-window-kind'
/** A window declared as a surface — an island a host draws into its own world
* (`docs/adr/0076-an-island-is-a-window-the-host-draws.md`) — under the
* windowed runner, which has no world to draw it into: it opens nothing, and
* the rest of the app runs. A surface is for a host that drives kui itself
* (a game on its own window and GPU device); under the runner, a float or a
* normal window is what shows the subtree. */
| 'surface-without-host'
/** The system has no font the shaper can read — a container with no fonts
* installed, a minimal Linux image — so every text is drawn in kui's
* last-resort face, each character a box half an em wide: it measures and
* lays out, and reads as nothing. Install a font (`fonts-dejavu-core` on
* Debian and Ubuntu), or register one with `add_font` / `load_fonts_dir` and
* name its family. */
| 'no-system-fonts'
/** A `setEditText` (`Core::set_edit_text`, `kui_edit_set_text`) named a key
* or a label, the text was held for the frame that would declare it, and the
* frame after the call declared no editor under that name — so nothing was
* ever seeded and the text is dropped. The call is meant to run from an
* `update` that also opens the editor, one frame ahead of the view that
* declares it; this is the same call with the view half missing, or with a
* name the view spells differently. Pass the label the editor's `key` prop
* declares — the spelling that needs nothing to exist yet — or the hex key
* an event carried. `keyOf`/`kui_key_of` turns a label into that key, but
* only for an editor some frame declared (Lua's verbs take the label
* itself). An editor that already exists takes the text where the call is
* made and never reaches this. */
| 'edit-text-without-editor'
/** The keyboard or assistive technology asked a `slider` that declares no
* `onChange` to move. A slider proposes its value in the `onChange` message
* and moves when the view declares it back as `valueNow`; without the row
* there is no message to propose it in, so the slider stays where it is (ADR
* 0047, decision 5). */
| 'slider-without-handler'
/** An editor declares a `value` and no `onChange`. The value always wins, so
* every keystroke is undone on the next frame and the field looks frozen:
* declare `onChange` and store the `change`'s text in the model the value is
* read from (ADR 0047, decision 8). */
| 'edit-value-without-handler'
/** A `cells` grid declared more cells than one grid takes —
* `cells::MAX_CELLS`, 4,194,304, a 2048 x 2048 screen — so it draws the rows
* that fit and no more: `rows * cols` from a driver's arithmetic (a `u32`
* each in C) overflowed or asked for gigabytes. */
| 'cells-too-large'
/** A handler's message has a field named for the event it arrives as —
* `{kind: "k", key: "a"}` declared as an `onKey` message — and the event's
* data replaced it, so the app's own value never reaches it (ADR 0047,
* decision 4). Rename the field: the event's name is the core's in a message
* that event arrives as. */
| 'message-field-taken'
/** A node other than the root declares `windowEvents`. The group is the
* window's, read on its root alone, so this one is ignored and its events
* arrive as nothing (ADR 0048): move it to the root. */
| 'window-events-off-root'
/** An editor declares both `initial` and `value`. The value wins, and the
* seed is never read (ADR 0047, decision 8). Raised by the bindings whose
* editor takes the two as separate props. */
| 'edit-value-and-initial'
/** A one-shot `audio` node went away — or changed its `src` — while the sound
* it started was still playing, so the user heard it cut off. Almost always
* a duration guessed short: the view keeps the node declared for a constant
* it picked, and the asset is longer. Ask for the sound instead of the guess
* — `finish` (`AudioSpec::finish`, `finish` in JSX and Lua) releases the
* playback on removal so it plays itself out, and a `tag` arrives with
* `sound: {phase: "ended"}` in it when it gets there. A view that means to
* cut the sound off says so by stopping what it started (`Core::stop`),
* which is not reported, and a `looped` playback never is: it has no end to
* be short of. Only a driver with a real device raises it, because only a
* device knows the sound was still running: the core queues the `stop` and
* the driver answers `Core::audio_truncated` for the ones its handle found
* still playing. A headless `Ctx` therefore never raises it — nothing plays
* — and the assertion point there is the other end of the same fact:
* `audioCommands()` holding a `stop` for the node, where the suite expected
* none. */
| 'truncated-playback'
/** A `FontId` / `ImageId` / `SoundId` registered in one `Session` and used
* through a core of another. Handles are unique to the process, so it cannot
* resolve to somebody else's resource; it behaves as a removed handle does
* (draws nothing, shapes as sans-serif, plays nothing), which from outside
* looks like the resource never registered. Two `Core::new()`s are two
* sessions; windows that share resources are built with `Core::new_in`
* against one `Session`. */
| 'foreign-resource'
/** A colour, length or family prop named a token — `bg = "$peach"` — that
* nothing declared and that is no theme, metrics or number role, or named
* one of another kind (a length in a colour slot). The slot is left at the
* row's default, as if the prop had not been written — no `bg`, a fit width,
* the theme's foreground for a text's `color` — never an explicit
* transparent or zero, which would hide the node a typo was on; the same in
* every binding and in every place a `$name` can go, a keyframe stop and an
* entrance included, and what `ui.token_color` / `token_length` /
* `token_family` answer `None` for in Rust. Raised by the binding that
* lowered the reference, through `Core::warn_unknown_token`, once per name,
* since the name is gone by the time the frame is a tree. Also raised at the
* declaration for a derived token whose source — the `from`, or the colour a
* `mix` or `readable` names — is no colour token declared before it and no
* theme role: that token is dropped, the message names both, and the rest of
* the table lands. */
| 'unknown-token'
/** A declared token took a theme, metrics or number role's name (`surface`,
* `radius`, `disabledOpacity`) under either spelling, or a family token took
* a stock family's (`sans`, `serif`, `mono`), and was dropped: the roles are
* the corpus's contract and `$surface` always means the theme's, so an app
* cannot shadow one. Rename the token. */
| 'reserved-token'
/** A token in a DTCG file (ADR 0062) was skipped or changed on its way into
* the table: a type kui has no kind for (a shadow, a typography, a font
* weight), a colour clamped into sRGB, an alias to nothing, two paths that
* make one name. The message names the token's DTCG path; the rest of the
* file landed. */
| 'dtcg-skipped'
/** A host placed a component (ADR 0060) that no loaded extension provides: no
* extension under its namespace, or one that does not list the name in its
* `components`. Nothing is drawn where it was placed. Raised once per name
* and key. */
| 'unknown-component'
/** A fill asked for its host's children (`children()`) where they cannot be:
* outside a fill, in one placed with none (an extension's root, a devtools
* tab), or a second time for one group. Nothing is built. */
| 'children-misplaced'
/** An `svg` element's document did not parse (ADR 0063): the message carries
* the parser's reason. The element draws an empty box of the size its spec
* gives. Raised once per key. */
| 'svg-malformed'
/** An `svg` element's `src` file could not be read: the message names the
* path and the reason. The element draws an empty box, and draws the picture
* once the file can be read. Raised once per key. */
| 'svg-unreadable'
/** An `svg` element forced to `mode="paths"` holds what a kui path cannot
* draw exactly — a gradient, a clip, a mask, a filter, a butt cap — so it
* was approximated or left out; the message lists what. `auto` would have
* drawn it as an image. */
| 'svg-approximated'
/** An `svg` element drawn as an image holds a shape that reaches past 30,000
* px at its drawn size — a coordinate like `8e8` — which the rasterizer
* cannot hold, so the image draws nothing. Raised once per key. */
| 'svg-too-large'
/** An extension returned from `view` with nodes still open. The core closed
* them at the depth the fill began, so the host's tree is what the host
* declared; outside the guard, the rest of the host's view would have landed
* inside the extension's last open node. The extension has an `open` without
* its `close`. */
| 'unbalanced-extension'
/** The view returned with nodes still open: an `open` without its `close` —
* in Odin, a bare `kui.box(ui, spec)` where `if kui.box(ui, spec) { }` was
* meant. Layout closes them, but every node declared after the forgotten
* close, the core's own menu and devtools panel included, landed inside the
* open one. Raised once per innermost open node. */
| 'unclosed-node'
/** `layout_of` was asked for a node that declares no `on_layout`, and
* answered nothing: it keeps the rects of those nodes alone. Declare
* `on_layout` on it, or read every node's rect from the inspection snapshot
* (`set_inspect` and `nodes`). Raised once per key. */
| 'layout-of-without-handler'
/** An extension's `view` returned an error. The message is drawn in red where
* the fill would have been, and reported here once per extension and
* component rather than once per frame. */
| 'extension-view-error'
/** An extension placed one of its *own* components while it was drawing, with
* no spare handle to draw it (`Extension::reentry`), so drawing it would
* have meant calling the extension inside itself. The instance is left
* empty. An extension may host extensions (`Fill::add`) and place theirs —
* what it cannot do is be its own guest. */
| 'recursive-component'
/** `request_frame_for` was given more distinct names than a session keeps
* (256): the rest are recorded as `request_frame`. A name per call — a
* counter, an id — rather than per reason is the usual cause. Raised once
* (ADR 0058, decision 8). */
| 'perf-names-exhausted'
/** `KUI_PERF_TRACE` (or `perf_trace_to`) named a file that could not be
* created: nothing is recorded to it. The message names the path and the
* OS's reason (ADR 0058, decision 11). */
| 'perf-trace-failed'
/** The device refused a play: its voices are all held, or the sound did not
* decode. A released playback (`finish`) holds one of the device's 128
* voices until its file ends, so a view that releases faster than its sounds
* finish reaches the limit and the 129th play is refused. The refusal is not
* left silent because the playback never starts and so never ends: a
* `tag`ged node waiting for `ended` would wait forever. It gets its message
* with `sound: {phase: "refused"}` in it instead, and this line says why.
* Stop what the view no longer needs rather than releasing it, or release
* shorter sounds. */
| 'playback-refused'
/** A devtools tab name declared twice in one frame: two `devtools_tab` /
* `devtools_tab_with` calls, a host form and an extension form of one name,
* or an extension declaring from its fill under a name the host took. The
* first declaration stands and the second is ignored; give the second tab
* its own name. */
| 'duplicate-tab'
/** A `devtoolsTab` declaration a binding could not read as either form: a
* child that is not a function, both a `component` and a child, or a `view`
* that is not a function in Lua. The tab was not declared. A tab names a
* component an extension provides, or carries a function the binding calls
* only when the tab is shown. */
| 'bad-devtools-tab'
/** A select's `current` names no option the field can show: an index past its
* options, or a separator's. The field is drawn as if none were in force —
* an empty description, no row checked — rather than blank with a check on a
* divider; the options are drawn as declared. A `current` the view computes
* from a list it also filters is how this happens; the index is into the
* options as passed, separators counted. Raised once per field. */
| 'select-current-ignored'
/** A `when` entry names a prop it may not set (ADR 0069, decision 7): an
* entry over the node's own size sets the layout of its children only —
* direction, gaps, padding, wrap, alignment, `minColumn` and which children
* are `hidden` — and no entry sets a handler, an access prop, a key or its
* children. The prop is left out and the rest of the entry applies. Also
* raised for an entry past the sixty-fourth, which is dropped. */
| 'rule-prop-refused'
/** A node reads its own size in an axis whose size comes from its content — a
* `fit` width under a `when` entry over `width`, or the parent of a lazy
* branch that needs width — which would loop (ADR 0069, decision 8). The
* `fit` is refused: the node takes the room its parent offers in that axis,
* as a `grow` would, and the condition reads that. */
| 'query-on-fit'
/** A lazy branch's `query` names a state condition (`hovered`, `pressed`,
* `focused`, ...): a hover must not build or drop a subtree. The state
* conditions are left out of the query; a `when` entry is how a node looks
* different while hovered. */
| 'query-state'
/** A lazy branch's decision disagreed with the layout twice in one frame: the
* view was run again once on the first disagreement, as the core does, and
* the branch it built still did not fit what that layout gave it — a branch
* whose room depends on itself. The frame is drawn as it was laid out and
* the next frame decides again. */
| 'query-unsettled'
/** With the paint audit on (`Core::set_paint_audit`, `KUI_PAINT_AUDIT=1` for
* a kui-native driver), a node drew a quad, a glyph or a mask outside the
* clip of the nearest box above it that clips or scrolls (ADR 0074): what
* the rule forbids, raised once per node. A node that means to leave
* declares it — a viewport float, or `escape` on a float anchored to its
* parent (a menu, a popover, a tooltip) — and is not audited past the box it
* leaves. A test aid, off unless asked for. */
| 'paint-escape';
// -- end generated --
/** A silent misconfiguration the core noticed while finishing a frame —
* the kind that otherwise looks like "the feature is broken". Each
* distinct (code, node) pair is raised once. */
export interface Warning {
/** Stable: match on it. Every code, with what it means, is `WarningCode`
* (and the Warnings table in docs/props.md); the `string` arm keeps a
* newer addon's codes from being a type error. */
code: WarningCode | (string & {});
/** The node it is about (hex, like event keys). */
key: string;
message: string;
}
/** Options for `play`. Volumes are linear amplitude (0..1), durations ms. */
export interface PlayOptions {
volume?: number;
loop?: boolean;
fadeIn?: number;
/** The message the playback's end arrives as, `sound: { phase,
* playback }` in it (a `SoundMsg`), when it ends on its own. */
tag?: HandlerMsg;
}
/** What a driver plays; `Ctx.audioCommands()` drains them (headless), a
* `KuiWindow` plays them itself. */
export type AudioCommand =
| { kind: 'play'; playback: number; sound: string; volume: number; loop: boolean; fadeIn: number }
| { kind: 'stop'; playback: number; fade: number }
| { kind: 'setVolume'; playback: number; volume: number; tween: number }
| { kind: 'pause'; playback: number; fade: number }
| { kind: 'resume'; playback: number; fade: number }
| { kind: 'masterVolume'; volume: number; tween: number }
| { kind: 'unload'; sound: string };
/** How urgently a screen reader should read a change it was not asked to
* read (the `live` prop, and `announce`'s politeness). */
export type Live = 'off' | 'polite' | 'assertive';
/** One thing to say once, with no node behind it. `Ctx.announcements()`
* drains them (headless); a `KuiWindow` delivers them itself. See
* docs/adr/0008-live-regions-and-announcements.md. */
export interface Announcement {
text: string;
/** Never `'off'` — `announce` drops those. */
live: Live;
}
// --------------------------------------------------------------------------
/** One event out of the loop. `A` is the app's message union; it defaults to
* the registered `AppMsg`. */
export interface UiEvent {
/** Which frontend drew the node: 0 is your app, 1+ an extension. Not the
* window — an extension draws into every one of them. */
origin: number;
/** Which window it happened in, matching `env().window.id`. 0 while an
* app has one window, which is every app today. */
window: number;
/** Node key as a hex string; pass back to editText()/isFocused()/... */
key: string;
/** Which event it was (ADR 0047, decision 14). The payload does not
* say: a node's is the message its handler declared, with this event's
* data in the field of the same name (`drag`, `change`, …) where it
* has any, so a plain click and a submit on one map message both
* arrive as that map. `'tick'` is the loop's own clock (`tick` in the
* loop config), and `'dispatch'` a message the app handed the loop
* itself (`app.dispatch`, an effect handler's `dispatch`): no node
* declared either, and `key` is `''`. */
event: EventName | 'tick' | 'dispatch';
/** The message as it arrives: always a map — a bare declared message
* under `tag` (`Arrived `). A window's own events are messages its
* root, its `windows` entry or its `` declared (ADR 0048). */
payload: Arrived;
/** The component instance whose fill drew the node, as its key (`keyOf`
* of the `key` prop it was placed with answers the same), or null for a
* node your app drew. One extension is placed many times, so `origin`
* cannot say which; this is what routes an event by the instance it
* came from (ADR 0067). */
instance: string | null;
/** The namespace of the extension that raised a component's event — what
* tells a slot's contributors apart, since each raises the view's one
* message (ADR 0067) — or null for any other event. */
from: string | null;
}
/** Window inner size in logical px plus the device pixel ratio. */
export interface WindowSize {
width: number;
height: number;
scale: number;
}
export interface FrameStats {
quadCount: number;
viewportW: number;
viewportH: number;
scale: number;
atlasSize: number;
}
/** One frame's cost in ms, split by phase (what the latency HUD draws). */
export interface FrameSample {
/** Input routing and edits since the previous frame. */
inputMs: number;
/** The view (tree lowering). */
viewMs: number;
/** Layout, text measurement and display-list emission. */
layoutMs: number;
/** GPU encode and present. */
renderMs: number;
/** CPU cache housekeeping after submission (may overlap GPU execution). */
maintenanceMs: number;
/** Blocked on a swapchain image (vsync pacing, not work). */
waitMs: number;
totalMs: number;
/** Everything but `waitMs`. */
workMs: number;
}
/** What the last frame left owed, by kind: `animating()` taken apart. The
* window redraws for any of them; a test reads `cycle` apart from the
* rest, since a keyframe `repeat` cycle never ends (backlog F64). */
export interface Owed {
/** A finite transition — a leg or a spring — still mid-flight. */
transition: boolean;
/** A keyframe cycle running; it always is, while its node is drawn. */
cycle: boolean;
/** An exit animation (a ghost) still departing. */
depart: boolean;
/** A frame asked for: a door that moves something the next frame
* draws (`reveal`, `setScroll`, `focusRegion`, `requestFiles`), or an
* `animate` node. Node has no bare `requestFrame` (backlog RG82). */
requested: boolean;
/** A held drag scrolling its container. */
autoscroll: boolean;
/** A scroll container easing to where a `reveal` or a `setScroll`
* took it (a `transition` on the container). */
scroll: boolean;
}
/** A reason a frame runs, as `frameCause()` names it (backlog F111): the
* input it answers, what a window's runner saw, or `owed` — the frame
* before left one owed, and `owedBy()` says who. */
export type FrameCauseName =
| 'pointerMove' | 'pointerLeave' | 'button' | 'wheel' | 'key' | 'modifiers'
| 'text' | 'preedit' | 'access' | 'fileDrag' | 'files'
| 'first' | 'wake' | 'host' | 'resize' | 'scale' | 'focus' | 'occlusion'
| 'appearance' | 'caret' | 'retry' | 'overdue' | 'device' | 'afterFrame'
| 'elsewhere' | 'menu' | 'audio' | 'smoke'
| 'owed';
/** One thing holding an owed frame (backlog F111). */
export interface FrameHolder {
/** The node's key, as `keyOf` spells it. */
key: string;
/** The labels from the root, `/`-joined; an unlabelled node ends in its
* accessible name in quotes, or `#` and eight hex digits of its key. */
name: string;
/** A transition's slots still mid-flight (`width`, `bg`, `position`,
* …); empty for every other holder. */
slots: string[];
}
/** Who held the frame the last one left owed: `owed()` with names
* (backlog F111). Empty unless `setFrameTrace(true)`. */
export interface OwedBy {
transitions: FrameHolder[];
cycles: FrameHolder[];
departures: FrameHolder[];
scrolls: FrameHolder[];
autoscroll: FrameHolder | null;
animate: FrameHolder[];
/** Each line that asked for the frame: `why` is the Rust door a call
* that asks for the frame landing it went through — `reveal`,
* `reveal_label`, `set_scroll`, `set_scroll_label`, `focus_region`,
* `request_focus_step`, `request_files` (backlog RG82) — or what kui
* asked for itself (`scrollbar fade`, `resliced`, `list first frame`,
* …); `file` and `line` are the Rust source line that asked, the
* addon's own for a call made from JS. */
requests: { why: string; file: string; line: number }[];
}
/** The window's frame timing: the averages and maxima over the last 120
* frames, and two monotonic counts. */
export interface FrameTiming {
/** How many frames the ring holds: its fill, one per painted frame up
* to 120, so a window that paints only when something changes stays
* below it for as long as it idles. Not a count of frames — that is
* `framesTotal`. */
frames: number;
/** Every frame the window has painted, since it opened (backlog F62).
* Two readings a second apart are that second's frame rate. */
framesTotal: number;
/** Every `pump()` the window has taken, the one that opened it
* included — what the driver's backoff is measured in: a stopped app
* with a once-a-second tick takes ~30 pumps a second at the default
* `idlePumpMs`, ~60 in the half-second after a click. Which of them
* something outside the app caused is `wokenPumps`. */
pumps: number;
/** The pumps among `pumps` that found an OS event or a wake: any window
* event but a redraw — a key, the pointer crossing the window, a focus
* change, a resize, the window moved or occluded — or a reader or a
* file dialog answering (backlog F94). Monotonic, never more than
* `pumps`. Two readings a second apart with this one unmoved are a
* second the desktop left the window alone: every frame in it was the
* app's own (a tick, a caret blink, a transition). A moved one is the
* desktop or a person reaching in, which resets the driver's backoff
* exactly as a regression would, so an idle-window test that sees it
* move measures that second again rather than failing it. */
wokenPumps: number;
/** Null before the first frame. */
last: FrameSample | null;
avgTotalMs: number;
maxTotalMs: number;
avgWorkMs: number;
maxWorkMs: number;
}
/** Host facts the frame driver pushed into the core, as `env()` reads them
* back: what the display and the window are doing right now. A window's
* runner refreshes all of it every frame; a headless `Ctx` shows the
* defaults until `setEnv` says otherwise. */
export interface Env {
/** Display refresh rate in Hz, or null when the host cannot tell (which
* is when `frameBudgetMs` falls back to 120 Hz). */
refreshHz: number | null;
/** One vsync interval at `refreshHz` — the per-frame time budget, and
* what the latency HUD draws its line at. */
frameBudgetMs: number;
/** Whether the *window* has the keyboard at all. Not to be confused with
* `focused()`, which is the focused *node*'s key. */
focused: boolean;
/** What the user set in the OS. */
system: SystemEnv;
/**
* The current or last frame's viewport: the window less the devtools'
* dock while the panel is docked — what `KuiWindow.size()` answers and a
* `resize` reports. 0×0 before the first frame.
*/
viewport: WindowSize;
window: WindowEnv;
/** What the driver's audio output is doing. */
audio: AudioEnv;
/** The platform the app runs on (every other Unix reads as Linux): what
* a `when` entry's `platform` condition reads, so code following a
* platform's convention and a rule following it agree. */
platform: 'macos' | 'windows' | 'linux' | 'other';
}
/** One node of the last finished frame, as `nodes()` reads it back (after
* `setInspect(true)`): what it is, the label it was opened under, where
* layout put it in logical viewport px, and the declarations that make
* it interactive or special. What a tree view and a node inspector are
* built from. */
export interface NodeInfo {
key: string;
parent: string | null;
/** Nesting depth; the root is 0. */
depth: number;
kind: 'box' | 'text' | 'edit' | 'image' | 'line' | 'cells' | 'fragment' | 'polygon' | 'path';
label: string | null;
rect: Rect;
dir: 'row' | 'column';
/** A table (ADR 0033): a column whose rows' cells line up in columns. */
table: boolean;
/** `fit`, `grow(n)`, `px` or `%`, as the spec spelled it. */
width: string;
height: string;
/** `0xRRGGBBAA`; 0 alpha is none. */
bg: number;
float: boolean;
role: string | null;
/** A text node's content, cut to a line's worth. */
text: string | null;
/** `click`, `drag`, `key`, `hover`, `hoverable`, `context-menu`, `modal`,
* `selectable`, `focusable`, `disabled`, `scroll`, `clip`, `transition`. */
flags: string[];
/** The paint layer: 0 in flow, else the float layer's rank from the
* bottom (1 is the first layer over the flow). */
layer: number;
/** Who declared it: 0 the app, 1+ an extension, 65535 the devtools. */
origin: number;
children: number;
padding: { t: number; r: number; b: number; l: number };
gap: number;
mainAlign: 'start' | 'center' | 'end';
crossAlign: 'start' | 'center' | 'end';
wrap: boolean;
/** Size floors and ceilings in px; a floor is `null` for the fit floor,
* a ceiling `null` when unbounded. */
minWidth: number | null;
minHeight: number | null;
maxWidth: number | null;
maxHeight: number | null;
/** Per corner: top-left, top-right, bottom-right, bottom-left. */
radius: [number, number, number, number];
borderWidth: number;
/** `0xRRGGBBAA`. */
borderColor: number;
opacity: number;
/** Its `backdropBlur` radius in px, 0 for none (backlog F129). */
backdropBlur: number;
/** Its turn in turns and its scale as drawn this frame, eased (ADR
* 0043): 0 and 1 for a node that declares none. */
rotate: number;
scale: number;
/** Its stretch across and down as drawn this frame (`scaleX` /
* `scaleY`, backlog C149): 1 each for a node that declares none. */
scaleX: number;
scaleY: number;
/** A scroller's offset; `null` for a node that does not scroll. */
scroll: { x: number; y: number } | null;
/** Every handler it declared with the message it would post: `click`,
* `drag`, `key` (the sink's message), `hover`, `context-menu`,
* `force-click`, `layout`, `modal`, …. */
events: Record;
}
/** Where the core's devtools panel sits (`setDevtoolsDock`): beside the
* app's tree in the main window (a docked pane's inner edge is a handle
* that resizes it), in a window of its own named `kui-devtools`, or
* hidden with its chords still live. `'side'` is accepted as `'right'`. */
export type DevtoolsDock = 'left' | 'right' | 'bottom' | 'window' | 'off';
/** The devtools panel's own tabs (`setDevtoolsTab`, `devtoolsCurrentTab`):
* the runtime's facts, the event stream, the node tree, the frames. A ``
* the app declares is named by its `name` beside these. */
export type DevtoolsTab = 'facts' | 'events' | 'tree' | 'perf';
/** The name of the core's devtools window while the panel is popped out
* (`setDevtoolsDock('window')`): what `windows()` lists it as, and what
* `runWindowed` never asks the app's `view` to draw. */
export declare const DEVTOOLS_WINDOW: 'kui-devtools';
/** The output device's state and how many playbacks are live, as the
* driver reports them each frame. A fact and not a verb — nothing closes
* the device from here; the runner does that itself once it has been idle
* a while. Worth reading because an open stream is a real-time thread
* whether or not anything plays, which is the whole of an idle app's CPU
* once it has held a sound: `device: 'open'` with `live: 0` long after the
* last sound is a bug that otherwise only `top` can see. A headless `Ctx`
* reads `'closed'` and 0. */
export interface AudioEnv {
/** `'closed'` (the default), `'opening'` (the ~90 ms open, off-thread),
* `'open'`, or `'failed'` (it refused; commands are dropped). */
device: 'closed' | 'opening' | 'open' | 'failed';
/** Playbacks started and not yet ended, plus any waiting on the open. A
* play that arrives while the device is `'opening'` counts here from
* the frame it was asked until the open answers; if the device
* refuses, the play is refused on the next apply — a `SoundMsg` with
* `phase: 'refused'` for a tagged one — and leaves the count with it,
* so a machine with no output device shows `opening`/1, then
* `failed`/0 with the refusal between (backlog F63). */
live: number;
}
/** The palette a frame paints with: one `0xRRGGBBAA` number per role,
* derived from `env().system` — the OS's light/dark picks the base and the
* OS's accent recolours it — unless the app called `setAccent` or
* `setTheme`. Pass a role straight to a prop: ``.
*
* The stock widgets already read it, so an app built out of ``,
* `` and the context menu follows the OS's appearance without
* touching this. Read it when painting something of your own. */
export interface Theme {
/** Which base this came from. `'unknown'` is the dark base, without
* claiming the user chose it — what kui painted before themes. */
appearance: 'unknown' | 'light' | 'dark';
// -- generated from the core's theme roles; edit THEME_ROLES in crates/kui-core/src/schema.rs, then `npm run gen` --
/** The window behind everything. */
bg: number;
/** A card, panel or list sitting on `bg`. */
surface: number;
/** A surface floating above content: a menu, a tooltip, a popover. Under a
* light theme it is no lighter than `surface` — a float on a white page
* separates by its border. */
raised: number;
/** A well cut into a surface: a text field, a code block, a track. */
sunken: number;
/** The hairline between two surfaces. */
border: number;
/** A border that has to be seen — a float's edge, a focused field. */
borderStrong: number;
/** Body text, and what a `color`-less text run resolves to. */
fg: number;
/** Secondary text: captions, hints, an accelerator beside a label. */
muted: number;
/** Text that is barely there: a placeholder, a gutter number. */
faint: number;
/** The one saturated colour: the OS accent where the host reports one, the
* app's where it pinned one, kui's blue otherwise. The `accent` prop
* paints from this. */
accent: number;
/** `accent` under a pointer. */
accentHover: number;
/** `accent` under a press. */
accentPressed: number;
/** Black or white — whichever a reader can see on `accent`. What a button's
* label is. */
onAccent: number;
/** The accent as a translucent wash rather than a fill: a selected menu
* row, a chosen tab, a highlighted list item. Keeps `fg` readable over it
* on both bases, which a fill does not. */
accentSoft: number;
/** What a text selection is painted under, in an editor and over a
* `selectable` scope alike. */
selection: number;
/** The default keyboard focus ring (ADR 0002). */
focusRing: number;
/** A translucent wash over a hovered neutral control. An overlay, not a
* fill, so one value works on every surface. */
hover: number;
/** The same over a pressed one, and the firmer of the two on both bases. */
pressed: number;
/** A good outcome. Readable on `surface` on both bases, which is why it is
* not one colour for both. */
success: number;
/** Something that wants attention. */
warning: number;
/** A destructive action or a failure. The close button's hover, too. */
danger: number;
/** The scrollbar thumb at rest. */
scrollbar: number;
/** The thumb while hovered or dragged. */
scrollbarActive: number;
// -- end generated --
/** What a disabled control's opacity is multiplied by. */
disabledOpacity: number;
}
/** `setTheme`'s argument: a base, then the roles to change on top of it.
* Every colour takes the two spellings a prop takes — `0xRRGGBBAA` or
* `'#rrggbb'`.
*
* `accent` is not just one role: naming it also recomputes `accentHover`,
* `accentPressed`, `onAccent`, `accentSoft`, `selection` and `focusRing`
* from it, and any of those named explicitly then wins. An unknown key
* throws rather than doing nothing. */
/** One palette for each appearance (ADR 0061): each half is overrides on
* that base, and the core picks the half the OS's appearance asks for
* every frame. A half left out is the stock base for it. */
export interface ThemePairOverrides {
light?: Omit;
dark?: Omit;
}
export interface ThemeOverrides {
/** Which base to start from; the OS's when absent. */
appearance?: 'unknown' | 'light' | 'dark';
// -- generated from the core's theme roles (overrides); edit THEME_ROLES in crates/kui-core/src/schema.rs, then `npm run gen` --
bg?: number | string;
surface?: number | string;
raised?: number | string;
sunken?: number | string;
border?: number | string;
borderStrong?: number | string;
fg?: number | string;
muted?: number | string;
faint?: number | string;
accent?: number | string;
accentHover?: number | string;
accentPressed?: number | string;
onAccent?: number | string;
accentSoft?: number | string;
selection?: number | string;
focusRing?: number | string;
hover?: number | string;
pressed?: number | string;
success?: number | string;
warning?: number | string;
danger?: number | string;
scrollbar?: number | string;
scrollbarActive?: number | string;
// -- end generated --
disabledOpacity?: number;
}
/** The sizes the stock widgets are built from — the palette's other axis
* (backlog T2). Logical px, before the scale factor the renderer applies.
* Read it so a control of your own agrees with ``, the field and
* the menus on a radius and a padding: ``.
* The stock set is the constants the widgets always had; `setMetrics`
* changes it, and nothing in the OS is followed. */
export interface Metrics {
// -- generated from the core's metric roles; edit METRIC_ROLES in crates/kui-core/src/schema.rs, then `npm run gen` --
/** A stock control's label: the button's text size. */
controlText: number;
/** The chrome's text: a menu row, a menu-bar title, the titlebar's title. */
chromeText: number;
/** A tooltip's text. */
hintText: number;
/** The corner of every stock surface: a button, a field, a menu, a tooltip. */
radius: number;
/** The corner of a row inside one: a menu row, a menu-bar title. */
radiusInner: number;
/** A button's horizontal padding. */
controlPadX: number;
/** A button's vertical padding. */
controlPadY: number;
/** A text field's horizontal padding. */
fieldPadX: number;
/** A text field's vertical padding. */
fieldPadY: number;
/** A tooltip's horizontal padding. */
hintPadX: number;
/** A tooltip's vertical padding. */
hintPadY: number;
/** A menu row's horizontal padding, and a menu-bar title's. */
menuPadX: number;
/** A menu row's vertical padding; a menu-bar title's is two px less. */
menuPadY: number;
/** A menu panel's width. */
menuWidth: number;
/** The drawn menu bar's height. */
menuBarH: number;
/** The titlebar strip's height: the platform's caption height, 32 on
* Windows and 34 elsewhere, or the window's own where the runner knows it
* (backlog W22) — 40 and 52 off macOS for a launcher's `medium` or `tall`
* titlebar under custom chrome, and under macOS custom chrome the OS's own
* titlebar as `window.native_controls` measures it (32, 40 or 52 on macOS
* 27). The stock number stands for that window's height, so a set of the
* app's keeps it unless it names a number of its own. Under macOS custom
* chrome the strip is drawn at the measured height whatever this row says
* (`widgets::titlebar_height`). */
titlebarH: number;
// -- end generated --
}
/** `setMetrics`'s argument: overrides on top of the set in effect, or on
* top of `base` — `'comfortable'` is the stock set, `'compact'` a dense
* tool's (smaller text, shallower padding, sharper corners, the titlebar
* unchanged) — then `scale` multiplying every length: a density slider.
* An unknown key throws rather than doing nothing. */
export interface MetricsOverrides extends Partial {
base?: 'comfortable' | 'compact';
scale?: number;
}
/** The OS settings on `Env` — appearance, accent, motion, locale — as the
* host reported them, and beside them whether assistive technology is
* listening. Every one of them can be "the host cannot tell", and that is
* the default: a `KuiWindow` asks the OS for all four on macOS and
* Windows (and for the locale from `LANG` elsewhere) and hears from its
* accessibility bridge for the fifth, a headless `Ctx` knows only what
* `setEnv` told it. Treat an unknown as "use my own default" rather than
* as an answer. Nothing in kui acts on these; a view that honours them
* does so where it picks a colour, declares an animation or decides
* whether an alert announces. */
export interface SystemEnv {
/** The OS light/dark setting. `'unknown'` where the platform has no
* answer (X11, Wayland without an override) or nobody pushed one. */
appearance: 'unknown' | 'light' | 'dark';
/** The OS accent colour as `0xRRGGBBAA` — pass it straight back as a
* `bg` or `color` — or null when the host cannot tell. */
accent: number | null;
/** Whether the user asked for reduced motion. `'reduced'` is the
* request, `'full'` is its absence, `'unknown'` is nobody having asked
* the OS — so test for `=== 'reduced'`, not for truthiness. */
motion: 'unknown' | 'full' | 'reduced';
/** The UI language as a BCP-47 tag (`'en-US'`), unparsed, or null when
* the host cannot tell. */
locale: string | null;
/** Whether assistive technology is listening: `'listening'` once an
* accessibility client asked this window for its tree, `'none'` while
* the bridge is up and nobody has, `'unknown'` where there is no bridge
* (a headless `Ctx`). The reading that changes what a view *says*
* rather than what it draws — an alert that announces when something
* is listening and blinks when nothing is — so test for
* `=== 'listening'`. Any client counts (a probe, an inspector, a screen
* reader alike), and on macOS and Windows nothing reports a client
* leaving, so once risen it stays for the window's life; only AT-SPI
* reports deactivation. Arrives as a `SystemMsg` when it changes. */
assistive: 'unknown' | 'none' | 'listening';
/** Whether the user asked for more contrast (ADR 0069): `'more'` under
* macOS's Increase Contrast or a Windows high contrast theme,
* `'normal'` when the OS says not, `'unknown'` where nobody asked. What
* a `when` entry's `contrast: 'more'` reads. */
contrast: 'unknown' | 'normal' | 'more';
}
/** The window chrome facts on `Env`. A view that draws its own titlebar
* reads these the way `` does: inset past `nativeControls`, pick
* the maximize or restore glyph from `maximized`, draw nothing at all
* unless `customChrome`. */
export interface WindowEnv {
/** Which window this frame is drawing, assigned by the driver — the same
* number every `UiEvent` from it carries. 0 is the window the app starts
* in, and the only one there is today. */
id: number;
/** The host asked the app to draw its own chrome, so there is no native
* titlebar to sit under. `` and `` build
* nothing when this is false. */
customChrome: boolean;
maximized: boolean;
fullscreen: boolean;
/** The window is above every other app's: what the runner applied after
* the frame asked (a root ``), not what was asked — a
* platform can refuse or drop the level, and on Wayland winit has no
* call for it, so it reads false there however often the app asks. A
* pin button draws its state from this. */
alwaysOnTop: boolean;
/** Area (logical px, window coordinates) covered by controls the OS still
* draws over our content — the macOS traffic lights under custom chrome.
* Keep out of it. Null means the OS draws nothing over us. */
nativeControls: Rect | null;
/** What is behind the window's transparent pixels, as the runner got it:
* `'opaque'` (the default), `'transparent'` (the desktop as it is),
* `'blur'` (a live blur of what is behind the window) or `'tinted'`
* (the desktop's colour, steady). Less where the platform has less — a
* blur asked of GNOME reads `'tinted'`, the wallpaper kui draws, or
* `'opaque'` — so a view paints its translucent regions opaque when
* this is `'opaque'`. */
backdrop: Backdrop;
}
/** What is behind a window's transparent pixels (`WindowEnv.backdrop`). */
export type Backdrop = 'opaque' | 'transparent' | 'blur' | 'tinted';
/** A box in logical px: position and size. */
export interface Rect {
x: number;
y: number;
w: number;
h: number;
}
/** What `Ctx.setEnv` takes: the writable half of `Env`, every key optional.
* Keys you leave out keep their current values, so a test declares just the
* fact it is about. */
export interface EnvInput {
/** Null for "the host cannot tell"; a rate at or below zero means the
* same. */
refreshHz?: number | null;
focused?: boolean;
/** What the user set in the OS, as a real host would have pushed it.
* `'unknown'`, and null for the two values, are the readings a host that
* cannot tell reports — they are settings, not absences, so a test can
* declare them. `accent` also takes the `'#rrggbb'` spelling a prop
* takes; a `locale` that is not an ASCII tag of at most 31 bytes throws
* rather than being stored truncated. */
system?: {
appearance?: 'unknown' | 'light' | 'dark';
accent?: number | string | null;
motion?: 'unknown' | 'full' | 'reduced';
locale?: string | null;
assistive?: 'unknown' | 'none' | 'listening';
};
window?: {
/** Which window a headless `Ctx` is standing in for; every `UiEvent` it
* hands out carries it. Real windows get theirs from their runner. */
id?: number;
customChrome?: boolean;
maximized?: boolean;
fullscreen?: boolean;
alwaysOnTop?: boolean;
/** `x` and `y` default to the window origin; a zero-sized rect and null
* both mean "nothing is drawn over us". */
nativeControls?: Partial | null;
/** What a runner would report behind the window's transparent pixels. */
backdrop?: Backdrop;
};
/** What a driver with a device would report; see `AudioEnv`. */
audio?: {
device?: 'closed' | 'opening' | 'open' | 'failed';
live?: number;
};
}
export interface KeyMods {
shift?: boolean;
/** Word-wise motion (alt). */
word?: boolean;
/** Document-wise motion (cmd/ctrl). */
doc?: boolean;
/** Control itself, which on macOS is not `doc` (backlog C94). */
ctrl?: boolean;
}
export interface KeySinkMods {
shift?: boolean;
ctrl?: boolean;
alt?: boolean;
/** Command / Windows key. */
super?: boolean;
/** Which of a key's twins the press was (backlog F108); "standard" when
* omitted. The key doors only — `modifiers` ignores it. */
location?: KeyLocationName;
/** The lock state the press was made under; the key doors only. */
capsLock?: boolean;
numLock?: boolean;
/** The same, as a `key` event spells it, so a press heard can be handed
* back as it came (backlog RG86). */
caps_lock?: boolean;
num_lock?: boolean;
/** The script of the layout the press was typed on (backlog F115); the
* key doors only, with `physical`. "nonLatin" reads every key as
* US-QWERTY prints it at `physical`, the layout's ASCII too — macOS
* Russian's "]" on the key printed "`" is "`"; "latin" when omitted,
* each key judged by itself. */
layout?: 'latin' | 'nonLatin';
}
// -- generated from the core's input lists; edit EditKey::ALL / MouseButton::NAMED in crates/kui-core/src/input.rs, then `npm run gen` --
/** The buttons `ctx.mouse` takes by name; anything else is a code. */
export type MouseButtonName =
| 'primary' | 'secondary' | 'middle';
/** The editing keys `ctx.key` takes, the spelling the corpus steps use. */
export type EditKeyName =
| 'left' | 'right' | 'up' | 'down' | 'home' | 'end' | 'pageup' | 'pagedown'
| 'backspace' | 'delete' | 'enter' | 'tab' | 'selectall' | 'undo' | 'redo'
| 'escape';
// -- end generated --
/** One end of the text selection as `selectionEnds()` reads it: the data
* index of the virtualised row it is in (null outside every virtualised
* row) and the byte inside that row's own text. */
export interface SelectionEnd {
index: number | null;
byte: number;
}
/** The text selection's two ends as the drag made them — the anchor where
* the press landed, the focus where the pointer is — so a Shift-click
* that kept the anchor reads as one (ADR 0029). */
export interface SelectionEnds {
anchor: SelectionEnd;
focus: SelectionEnd;
}
/** One end of a `cells` grid's selection: an absolute line (`originLine`
* plus the row, so a scroll does not move it) and a column. */
export interface CellEnd {
line: number;
col: number;
}
/** A `cells` grid's selection as `cellSelection()` reads it: the grid's
* key, the two ends as the drag made them, and whether it is a block
* (rectangular) rather than linewise (ADR 0017, decision 4). */
export interface CellSelection {
node: string;
anchor: CellEnd;
focus: CellEnd;
block: boolean;
}
/** A scroll container's retained offset, in logical px: positive means the
* content has moved up / left inside it. */
export interface ScrollOffset {
x: number;
y: number;
}
/** One font family the core can see, installed or loaded, with what the
* font database read off its faces (`systemFonts()`, backlog F97). */
export interface SystemFont {
/** The name `addSystemFont` takes. */
family: string;
/** Every face says it is fixed-pitch (the `post` table's
* `isFixedPitch`). */
monospaced: boolean;
/** The weights its faces come in — 400 regular, 700 bold — sorted,
* each once. */
weights: number[];
/** It has an italic or an oblique face. */
italic: boolean;
}
/** What the last layout resolved for a scroll container: its own box
* (`x`/`y`/`w`/`h`, logical px in viewport coordinates), its laid-out
* content size (padding included) and the offset it clamped. */
export interface ScrollGeometry {
x: number;
y: number;
w: number;
h: number;
contentW: number;
contentH: number;
/** Where it is scrolled to — the retained offset clamped to `maxOffset`,
* so it is always a position within the content even right after a
* `setScroll` of "a huge number" meaning "the end". */
offset: ScrollOffset;
/** How far `offset` can travel; zero on an axis that does not scroll.
* `offset.y === maxOffset.y` is "at the bottom". */
maxOffset: ScrollOffset;
}
/** An extension a window or a headless app loads before its first frame:
* a `.lua` script, a folder holding `init.lua`, or a C library (ADR 0059),
* under `namespace` (its own name when left out). */
export type ExtensionEntry = string | { path: string; namespace?: string };
export interface WindowOptions {
/** Extensions loaded before the window opens, in order: their origins
* are their places in this list. `@qxuken/kui/kit`'s `extension` is
* one entry. */
extensions?: ExtensionEntry[];
width?: number;
height?: number;
/** Smallest inner size the user may resize the window to (logical px).
* The OS enforces it; `width`/`height` are clamped up into it. Either
* axis may stand alone — the other stays unbounded. */
minWidth?: number;
minHeight?: number;
/** Largest inner size the user may resize the window to (logical px).
* A bound below the matching minimum loses to it. */
maxWidth?: number;
maxHeight?: number;
chrome?: 'native' | 'custom' | 'borderless';
/** How tall the titlebar strip is under `chrome: 'custom'` (the
* launcher's `titlebar`, backlog W22): `'standard'` (the default),
* `'medium'` or `'tall'`. On macOS it is AppKit's own titlebar, made
* with an empty toolbar, and so where the traffic lights sit: 32 px
* with them at 9,9 on macOS 27, 40 at 12,13, or 52 about them at
* 19,19; what the window got is `env().window.nativeControls`, and
* the window's `titlebarH` metric is that height. On Windows and Linux
* the strip is the app's: `'medium'` and `'tall'` make the window's
* `titlebarH` metric 40 and 52 in place of the caption's 32 or 34.
* Either way a `setMetrics` keeps it unless it names a `titlebarH` of
* its own, and `titlebar` lays out against it. */
titlebar?: 'standard' | 'medium' | 'tall';
/** What shows through the window where a frame paints nothing or paints
* with alpha (the launcher's `backdrop`), by effect: `'opaque'` (the
* default), `'transparent'` (the desktop as it is), `'blur'` (macOS
* vibrancy, Windows 11 Acrylic, KDE's compositor blur) or `'tinted'`
* (Windows 11 Mica, macOS's window-background material, the wallpaper
* kui draws where the OS has neither). Paint the regions that should
* show it with alpha and the rest opaque; `env().window.backdrop` says
* what the platform gave, which is less where it has less. */
backdrop?: Backdrop;
/** How outline glyphs are antialiased: `'auto'` (the default) is LCD
* subpixel coverage where the GPU blends per channel and grayscale
* otherwise. `KUI_TEXT_AA=gray|subpixel` in the environment still
* overrides, for an A/B by hand. */
textAa?: 'auto' | 'gray' | 'subpixel';
/** Frames queued ahead of the one on screen (backlog C47). 2 by default:
* every vsync gets a frame at light load. 1 on Windows, where one
* already gets every vsync (backlog RG46). A Node window turns its loop
* from a timer, where the display cannot start its frames (the Rust and
* C runners' pacing), so a frame drawn while frames run back to back (an
* animation, a drag, a scroll) reaches the screen a vsync later than
* with 1 — the lowest latency during those, at the cost of an occasional
* missed vsync when little is drawn. `KUI_FRAME_LATENCY` in the
* environment still overrides. */
frameLatency?: number;
/** Pins part of `env.system` for the life of the window, over whatever
* the OS says: `{ motion: 'reduced' }` opens the window as a user who
* asked for less motion sees it, on a machine whose owner did not. The
* same partial `Ctx.setEnv` takes, and the same readings — but a field
* left out, `'unknown'` or null here is *not pinned* and keeps
* following the OS, whose changes to it still arrive as the `system`
* message, carrying the pinned fields with them. A window has no
* `setEnv` because its runner writes the real reading before every
* frame; this is merged inside that write, which is what makes it
* hold. It is an option rather than an environment variable so that a
* shipped app's motion is its own code's decision. */
system?: EnvInput['system'];
/** The icon every window of the app is created with (the launcher's
* `icon`): `rgba` is `width` × `height` pixels, four bytes each, row
* by row from the top left, alpha not premultiplied — a `Buffer` is a
* `Uint8Array` — and 64 to 256 px is what a taskbar shrinks cleanly.
* Windows shows it in the title bar, Alt-Tab and the taskbar, X11 in
* the window manager's. macOS has no window icon, so there it is the
* app's, in the Dock and ⌘Tab while it runs — the icon a CLI run with
* `node` shows instead of Node's — unless the app is a bundle whose
* `Info.plist` names an icon, which wins (backlog F181); Wayland's is
* the `.desktop` file's (`appId`). `resource` is an icon
* resource in the executable, on Windows, and wins there — only a
* packaged app has one of its own: under `node.exe` it is Node's.
* Pixels that are not the size are refused, as the constructor
* refuses every other option. */
icon?: { rgba: Uint8Array; width: number; height: number; resource?: number } | { resource: number };
/** The name the Linux desktop knows the app's windows by (the launcher's
* `app_id`, backlog F172): the Wayland `app_id` and both halves of the
* X11 `WM_CLASS`. A compositor matches it to `.desktop` — an X11
* window manager to the file whose `StartupWMClass` it is — and shows
* the window with that file's `Icon=`; without it a Wayland window has
* no `app_id` and the generic icon. Nothing on Windows or macOS. */
appId?: string;
/** `false` stops the loop printing the core's warnings (see `Warning`);
* `win.warnings()` still drains them. */
warnings?: boolean;
/** Whether the core runs the checks at all. Default: on unless
* `NODE_ENV` is `production`, so a shipped app pays and prints nothing. */
diagnostics?: boolean;
/** `false` makes a mouse wheel's notch jump on the next frame instead of
* gliding toward its place (ADR 0050), in every window of the app.
* Default on; the system's reduced motion jumps either way. A trackpad
* is unaffected. */
smoothWheel?: boolean;
/** Accelerate rapid wheel notches on scroll containers. Off by default. */
wheelAcceleration?: boolean;
/** How a mouse wheel's notch scrolls, in every window of the app: a
* preset's name (`'brisk'` is a touch faster than the default) or the
* numbers to change from the standard feel. Taken as the window opens,
* so `KUI_WHEEL` in the environment overrides it, as `KUI_TEXT_AA`
* overrides `textAa`; `win.setWheelFeel` afterwards wins over both. */
wheelFeel?: WheelPreset | Partial;
/** How a held drag scrolls a container at its edge, in every window of
* the app: a preset's name (`'brisk'`) or the numbers to change from the
* standard feel. Taken as the window opens, so `KUI_EDGE_SCROLL` in the
* environment overrides it; `win.setEdgeScrollFeel` afterwards wins over
* both. */
edgeScrollFeel?: EdgeScrollPreset | Partial;
}
/** An edge scroll feel by name, slow to fast; `'standard'` is the default. */
export type EdgeScrollPreset = 'gentle' | 'standard' | 'brisk';
/** How a held drag scrolls a container at its edge (ADR 0029): kui's own
* caret drag and drag-select, and an app's through `edgeScroll`. */
export interface EdgeScrollFeel {
/** How deep the edge zone inside a container is, logical px (60). */
zonePx: number;
/** The speed at full depth before the ramp, px/s (500): at the
* container's edge, or pinned against the window's. */
speedPxS: number;
/** The curve's exponent from the zone's inner edge (2, quadratic). */
curve: number;
/** Seconds held in the zone to reach the ramp's top (1.5). */
rampSecs: number;
/** What the ramp multiplies the speed by at its top (6). */
rampMax: number;
/** The most it scrolls, px/s, after depth and ramp (3000). */
capPxS: number;
/** How far back toward the content restarts the ramp, px (8). */
pullBackPx: number;
}
/** A wheel feel by name, slow to fast; `'standard'` is the default. */
export type WheelPreset = 'gentle' | 'relaxed' | 'standard' | 'brisk' | 'swift';
/** How a mouse wheel's notch scrolls (ADR 0050). */
export interface WheelFeel {
/** How far one line of a wheel goes, in logical px (40). A plain mouse's
* notch is one line; a fraction of a line goes its share. */
linePx: number;
/** The glide's response in seconds (0.30): shorter lands sooner. */
response: number;
/** How much of a pure ease-out's speed each notch gives the glide, 0 to
* 1 (0.6): more starts each notch harder and stops it sooner, less
* starts it softer. */
kick: number;
}
/** The binary-frame protocol tables the addon exports: the stream's version,
* its opcodes and its prop ids, which is everything `createEncoder` needs.
* (`protocol()` also carries the schema tables `npm run gen` reads; those
* are generator input, not app surface, so they are not typed here.) */
/** One binding's cell in the verb table: its spelling of the verb, the
* same thing in another form (a prop, a reading, a callback, a
* constructor option), or the reason there is none. */
export type DoorCell = { is: string } | { as: string } | { no: string };
/** One row of the verb table (`schema::DOORS`, backlog B1a): a verb by its
* Rust spelling and what each binding has for it. The suite pins `Ctx`
* and `KuiWindow` to the Node column both ways. */
export interface Door {
rust: string;
c: DoorCell;
/** The Odin binding's (packages/odin), pinned by its generator. */
odin: DoorCell;
node: DoorCell;
lua: DoorCell;
doc: string;
}
export interface Protocol {
version: number;
op: Record;
prop: Record;
doors: Door[];
}
/** The `KuiWindow` constructor's options, picked out of `runWindowed`'s
* (which carry the loop's own beside them): for an app opening its window
* itself with the same set. */
export declare function windowOptions(opts?: WindowOptions & Record): WindowOptions;
/** A reusable frame encoder for the binary IR path (drivers make their own). */
export declare function createEncoder(p: Protocol): {
encode(tree: KuiNode, tokens?: Map): {
stream: Float64Array;
strings: Uint8Array;
unknown: [string, string][];
unknownTokens: [string, string][];
};
};
// -- tokens (docs/adr/0027-tokens-beside-the-theme.md) ---------------------
/** One step of a derived colour token's recipe (ADR 0028), a tuple: the
* verb, then its operands — a colour token or role by name for `mix` and
* `readable`, then the number. `lift` / `darken` move toward white /
* black by `t`; `raise` toward the front of whichever base is in effect;
* `alpha` sets the alpha; `mix` moves toward the named colour by `t`;
* `readable` moves toward black or white — whichever reads on the named
* colour — until it clears the ratio on it. */
export type ColorOp =
| readonly ['lift', number]
| readonly ['darken', number]
| readonly ['raise', number]
| readonly ['alpha', number]
| readonly ['mix', string, number]
| readonly ['readable', string, number];
/** A colour token computed from another (ADR 0028): `from` names a colour
* token declared *before* this one, or a theme role (`'accent'`), and
* `ops` is the chain folded over it in order — a list of tuples, or one
* bare tuple, or nothing for an alias. Resolved by the core on read, so a
* themed source's recipe runs on the half in effect. A source that is
* not there is dropped with `unknown-token` at the declaration. */
export interface DerivedColor {
from: string;
ops?: ColorOp | readonly ColorOp[];
}
/** A colour token's value: one colour for both bases, a light and a dark
* half the core picks by the appearance in effect — each the way a colour
* prop spells one, `0xRRGGBBAA` or `'#hex'` — or a recipe over an earlier
* token (`DerivedColor`). */
export type ColorTokenValue =
| number
| string
| { light: number | string; dark: number | string }
| DerivedColor;
/** A family token's value: a family name — `sans`, `serif`, `mono`, an
* installed or loaded family's — or a fallback list of them, the first
* that resolves picked by the core when the table is declared and again
* when the fonts change (ADR 0049). A list nothing matches is sans, with
* `unknown-family`, and so is an empty one: a token that is always sans. */
export type FamilyTokenValue = string | readonly string[];
/** What `setTokens` / `defineTokens` take: the app's named colours,
* lengths and font families, apart by kind — a colour and a length are
* both a number, so the kind cannot be read off the value. Declaration
* order is the wire index. A length is any number: logical px where the
* slot is a length, the number itself where it is not (`opacity`). A name
* a theme, metrics or number role owns (`surface`, `radius`,
* `disabledOpacity`) is dropped by the core with a `reserved-token`
* warning: `$surface` always means the role's; so is a family token
* named `sans`, `serif` or `mono`. */
export interface TokenDeclaration<
C extends Record = Record,
L extends Record = Record,
F extends Record = Record,
> {
colors?: C;
lengths?: L;
families?: F;
}
/** The references a declaration's names become: `{ peach: '$peach',
* sideW: '$sideW', code: '$code' }`, each a literal type branded by kind. */
export type TokenRefs = {
readonly [K in keyof D['colors'] & string]: `$${K}` & { readonly __kuiToken?: 'color' };
} & {
readonly [K in keyof D['lengths'] & string]: `$${K}` & { readonly __kuiToken?: 'length' };
} & {
readonly [K in keyof D['families'] & string]: `$${K}` & { readonly __kuiToken?: 'family' };
};
/**
* Types a token declaration's names as the references a prop takes
* (ADR 0027, decision 5): given `{ colors: { peach: '#ffcc99' }, lengths:
* { sideW: 132 } }` it returns `{ peach: '$peach', sideW: '$sideW' }`, so
* `bg={T.peach}` and `width={T.sideW}` type-check, `width={T.peach}` does
* not, and `T.peech` does not exist. Zero runtime: the object *is* the
* references. Hand the same declaration to `setTokens`.
*/
export declare function defineTokens(decl: D): TokenRefs;
/** How `loadTokens` reads a DTCG file (ADR 0062). */
export interface DtcgOptions {
/** Put in front of every name: `'brand'` makes `color.ink` `brandColorInk`. */
prefix?: string;
/** The resolver modifier whose contexts are the two halves; found by its
* contexts when it is not `'theme'`. */
modifier?: string;
/** Its context for the light half (`'light'`). */
light?: string;
/** Its context for the dark half (`'dark'`). */
dark?: string;
/** Px in one `rem` (16). */
rem?: number;
/** A context for each other modifier, by name; one left out takes its default. */
inputs?: Record;
}
/** What `loadTokens` gives back: `tokens` goes to `setTokens` as it is. */
export interface LoadedTokens {
tokens: TokenDeclaration;
/** Which DTCG path each name came from, in file order. */
names: { name: string; path: string; kind: 'color' | 'length' | 'family' }[];
/** Every token skipped or changed, as `path: why`. */
warnings: string[];
/** Whether the source was a resolver (two halves) or a token file. */
resolver: boolean;
}
/** The theme's and metrics' roles as references — `roles.surface` is
* `'$surface'`, `roles.radius` is `'$radius'` — the same spelling an app
* token takes, resolved to the role's value whatever the app declared.
* `roles.disabledOpacity` is the theme's number (ADR 0049), for
* `opacity={roles.disabledOpacity}`. */
export declare const roles: {
readonly [K in Exclude & string]: `$${K}` & { readonly __kuiToken?: 'color' };
} & {
readonly [K in (keyof Metrics | 'disabledOpacity') & string]: `$${K}` & { readonly __kuiToken?: 'length' };
};
/** `tokens()`: the tokens a view here sees this frame, resolved — colours
* as `0xRRGGBBAA` for the appearance in effect, lengths in px, families
* as the name each list picked (`'sans'` for one nothing matched). Roles
* are not listed; read them off `theme()` and `metrics()`. */
export interface ResolvedTokens {
colors: Record;
lengths: Record;
families: Record;
}
// -- generated from the addon's `#[napi]` surface; edit crates/kui-node/src/lib.rs, then `npm run gen` --
/**
* One revision of a channel, held. Columns are numbers (a `Float64Array`
* or an array of numbers), booleans or strings, all of one length.
*/
export declare class Channel {
/**
* A channel of `columns`: each key a column's name, each value its
* rows. Throws for columns of two lengths or of mixed kinds.
*/
constructor(columns: object)
/**
* The channel a handle names, if someone still holds it: what an
* event's payload or a worker's message carries.
*/
static resolve(handle: any): Channel
/** How many rows. */
get length(): number
/** Its revision: 1, and one more for each `publish`. */
get rev(): number
/** The column names, in order. */
get names(): Array
/**
* Row `row`'s value of column `col` (a name, or a 0-based index);
* `null` past the end.
*/
get(row: number, col: string | number): any
/** One column whole: a `Float64Array` for numbers, an array otherwise. */
column(col: string | number): Float64Array | Array
/**
* Column `col` over rows `from` up to `to` in `buckets` buckets of
* near one size — one a row when the range has fewer — each one's
* least, greatest, first and last value and the rows they were read
* from: a chart's pixel columns of a hundred thousand rows without the
* rows crossing into JavaScript. `to` past the end stops at it; an
* empty range answers empty arrays. Throws for a column that is not
* numbers.
*/
reduce(col: string | number, from: number, to: number, buckets: number): ChannelReduction
/**
* The next revision under the same identity, holding `columns`: a
* handle to this channel names that revision from now on.
*/
publish(columns: object): Channel
/**
* The next revision under the same identity: this one's rows and
* `columns`' after them, each column of this channel named, of its
* kind and all of one length (backlog C147). With `cap`, the oldest
* rows go past it. This revision's rows are shared with the next, not
* copied, so a growing log costs its new lines.
*/
append(columns: object, cap?: number | undefined | null): Channel
/**
* The rows — all, or those of `rows` in its order — whose cell in
* column `col` matches, 0-based (backlog C148). Throws for a match of
* the wrong kind for the column, or a row past the end.
*/
filter(col: string | number, matching: ChannelMatch, rows?: Uint32Array | Array | undefined | null): Uint32Array
/**
* The rows — all, or `rows` — ordered by column `col`, least first or
* greatest with `descending`; ties keep their order, NaN goes last
* (backlog C148).
*/
sort(col: string | number, descending?: boolean | undefined | null, rows?: Uint32Array | Array | undefined | null): Uint32Array
/**
* A new channel of `rows`, in that order (backlog C148): a filtered
* or sorted view, made in Rust.
*/
take(rows: Uint32Array | Array): Channel
/**
* The intervals `start .. start + len` (`len` left out: points) on
* the lanes column `lane` names (one lane without it), built once in
* Rust for `ChannelLanes.window` (ADR 0075): what a waterfall draws a
* million spans as, a window at a level of detail.
*/
lanes(start: string | number, len?: string | number | undefined | null, lane?: string | number | undefined | null): ChannelLanes
/**
* The handle: `{ $channel, rev }`, a value that rides in props, in
* messages and to a worker.
*/
handle(): any
/**
* What `JSON.stringify` writes: the handle, so a channel in a
* component's props crosses as one.
*/
toJSON(): any
}
/**
* What `channel.reduce` answers (backlog C95): a typed array per field,
* one entry a bucket. NaN is skipped; a bucket of only NaN is NaN at its
* first row. Rows are the channel's, 0-based.
*/
export interface ChannelReduction {
min: Float64Array
max: Float64Array
first: Float64Array
last: Float64Array
minRow: Uint32Array
maxRow: Uint32Array
firstRow: Uint32Array
lastRow: Uint32Array
}
/** A channel's intervals on lanes (`channel.lanes`, ADR 0075). */
export declare class ChannelLanes {
/** How many lanes. */
get count(): number
/** How many intervals. */
get length(): number
/** The earliest start. */
get lo(): number
/** The latest end. */
get hi(): number
/**
* Lane `lane`'s runs reaching into `v0 .. v1`, at the detail where
* an interval at least `min` long is a run of its own and shorter
* ones a gap under it apart merge into a strip: about a run a pixel
* with `min` a pixel's width.
*/
window(lane: number, v0: number, v1: number, min: number): ChannelRuns
}
/**
* What `lanes.window` answers: a typed array per field, a run per index —
* its start, end, row (0-based; -1 for a strip of several) and how many
* intervals it holds.
*/
export interface ChannelRuns {
s: Float64Array
e: Float64Array
row: Int32Array
n: Uint32Array
}
/**
* What `channel.filter` keeps a row for (backlog C148): `eq`, a cell
* equal to it; `contains`, a string cell holding it (`caseSensitive` to
* match its letters' case); `min` / `max`, a number cell in that range,
* either end left open.
*/
export interface ChannelMatch {
eq?: any
contains?: string
caseSensitive?: boolean
min?: number
max?: number
}
/**
* The heights a `list()` slices by: a measured number per row where one is
* known, the mean of those for every other row, and the prefix sums over
* both. The app owns it and hands the same one back every frame; rebuild it
* (or `clear()` it) when the rows change under the same indices, and
* `setLen` it when rows are appended.
*/
export declare class RowHeights {
/**
* `rows` rows, none measured, each standing at `estimate` logical px
* until it is. The estimate only has to be the right order of
* magnitude: it decides how wrong the scrollbar is before the list has
* been scrolled through, and nothing else.
*/
constructor(rows: number, estimate: number)
/** How many rows. */
get length(): number
/**
* Grows or shrinks to `rows`, keeping what is still in range — rows
* appended to a log keep every height already measured.
*/
setLen(rows: number): void
/**
* Forgets every measurement, keeping the length and the estimate —
* for a list whose rows changed under the same indices.
*/
clear(): void
/**
* Records row `i`'s height; the estimate for the others is the mean of
* the rows recorded this way.
*/
set(i: number, h: number): void
/** Row `i`'s height as measured, or null for one at the estimate. */
measured(i: number): number | null
/** Row `i`'s height: measured, or the estimate. */
get(i: number): number
/** What an unmeasured row stands at. */
estimate(): number
/** The whole list's height, measured and estimated together. */
total(): number
/**
* The top of row `i` in content coordinates. `ctx.setScroll(key, 0,
* heights.offsetOf(i))` puts row `i` at the top — exactly for a
* measured row, within a frame or two for one at the estimate.
*/
offsetOf(i: number): number
/** The row content-coordinate `y` lands in. */
rowAt(y: number): number
/**
* `list()`'s first step: the reading, and back the rows to measure
* (`{ width, rows }`). Not for an app to call; `list()` is the loop.
*/
sliceBegin(reading: ListReading): { width: number, rows: number[] }
/**
* `list()`'s middle step: the heights of the rows the last step asked
* for, in its order, and back the next rows to measure — empty once
* the window has settled.
*/
sliceMeasured(heights: Array): Array
/**
* `list()`'s last step: the rows to build (`first`..`last`) with each
* one's height, the spacers, and the scroll correction for
* `ctx.shiftScroll` (null when nothing moved).
*/
sliceFinish(): ListPlan
}
/**
* The binary-frame protocol tables (`{version, op, prop}`). The JS encoder
* reads its opcodes and prop ids from here at module init, so the two sides
* cannot drift.
*/
export declare function protocol(): Protocol
/**
* A headless kui core: build frames from JSX trees, feed input, poll events.
* Everything a window does except open one, so an app's behaviour is
* testable without a display.
*/
export declare class Ctx {
constructor()
/**
* A new context in this one's session (backlog F237): the same
* registered fonts, images and sounds and the same shaping caches,
* so a second HUD loads and shapes nothing twice. Its tree, focus,
* events and glyph atlas are its own.
*/
sibling(): Ctx
/**
* `frame` from an already-encoded binary instruction stream, for
* callers that own their encoder (`createEncoder(protocol())`) — the
* fastest path, and what the JS drivers use. Buffers are read
* zero-copy.
*/
frameBinary(width: number, height: number, scale: number, stream: Float64Array, strings: Uint8Array): void
/**
* Starts the next frame's record before its view runs: from here
* until the frame after it begins, `frameCause()` and `owedBy()`
* answer the frame the next `frame` call builds. A
* view runs before its frame — it returns the tree `frame` is handed
* — so without this it reads the frame before; `createApp`'s loop
* calls it ahead of every view. Twice before one frame is once.
*/
beginFrameCause(): void
/**
* Loads an extension: a Lua script (a `.lua` file, or a folder
* holding `init.lua`), or a C shared library exporting the seven
* `kui_ext_*` entry points `crates/kui-ffi/include/kui.h` describes
* (ADR 0059). `namespace` is the word that fronts every component it
* provides — ` ` for `addExtension('todos', …)`
* — and an empty one takes the extension's own name. Throws with the
* reason if the script fails to load or run, or the library will not
* load, declares no `kui_ext_abi` or one this build does not
* implement, has no `kui_ext_view`, or wants a namespace another
* extension has.
*
* Load before the first frame: origins are positions in the list, so
* one added later renumbers the ones after it. The context owns it and
* unloads it when the context goes.
*
* **An extension runs in this process**, on this thread, on this
* app's frame — loading one is trusting it as much as linking it would
* be, a script included: it may load C plugins of its own.
*/
addExtension(namespace: string, path: string): void
/**
* The namespaces of the loaded extensions, in origin order: index `i`
* is origin `i + 1`, and origin 0 is the app's own nodes. What turns
* the `origin` on an event into the name this app gave the plugin.
*/
extensionNamespaces(): Array
/**
* The frame clock for `transition` props: monotonic seconds, any
* origin. Set before each frame; never setting it makes transitions
* snap. A bare `Ctx` is the only place to call it: `createApp`'s loop
* owns the clock, stamps it before every frame it draws, and replaces
* this method on its surface with one that throws — `app.advance(ms)`
* is what moves time there.
*/
setTime(nowSecs: number): void
/**
* Declares host facts a real window would have pushed — what C spells
* `kui_env_set` + `kui_env_set_window`, in one call shaped like what
* `env()` reads back. Only the keys you pass move; the rest keep their
* values, so `setEnv({window: {customChrome: true}})` is the whole of
* "pretend this app draws its own titlebar" and ``,
* `` and `widgets::window_buttons` start building
* something. `refreshHz: null` means "the host cannot tell" (the
* default), and `nativeControls: null` means the OS draws nothing over
* our content. `window.id` is the one fact here an app never chooses —
* a driver assigns it — and setting it is how a headless test says
* "these events came from that window"; it is 0 otherwise.
*
* Headless only, and on purpose: a `KuiWindow` has no such call because
* its runner reports the real window every frame, and anything set here
* would be overwritten before the next view ran.
*/
setEnv(env: EnvInput): void
cursor(x: number, y: number): void
cursorLeft(): void
/**
* Files dragged in from the OS are over the window at (`x`, `y`) —
* entering and moving alike: the `onDrop` zone under the
* point hears its message with `drop: {phase: "enter"|"move", paths,
* x, y}` in it, a zone it left hears `leave`, a repeat at the same
* point is nothing. `dropTarget()` afterwards is what a driver answers the OS
* with.
*/
dragFiles(paths: Array, x: number, y: number): void
/**
* A file dialog's answer, as a host that showed it reports it: the
* paths picked, none for a cancelled dialog. Whoever asked with
* `requestFiles` hears the message it gave with `files: {paths}` in
* it; with nothing asked it is dropped.
*/
answerFiles(paths: Array): void
/**
* The OS asked the app to open these documents (backlog F124) — the
* Finder's Open With, a file dropped on the Dock icon, `open -a`: the
* app hears its root's `windowEvents.onOpen` message with `open:
* {paths}` in it, whether or not it asked (ADR 0048); none is nothing,
* and so is a root that declares no `onOpen`. A `KuiWindow` on macOS hears it from the
* runner; this is the headless drive.
*/
openDocuments(paths: Array): void
/**
* The dragged files released at (`x`, `y`): the zone there hears
* its message with `drop: {phase: "drop", paths, x, y}` and no
* `leave` after it; with no zone there, nothing but the lit zone's `leave`.
*/
dropFiles(paths: Array, x: number, y: number): void
/**
* The dragged files left the window, or the OS ended the drag
* elsewhere: the lit zone hears its `leave`.
*/
dragCancel(): void
/**
* A button press or release. `clicks`: 1 single, 2 double (word
* select), 3 triple (line select) — the grain everywhere text can be
* selected: an editor, a `selectable` scope, and a `cells` grid,
* where it counts in cells. `button` defaults to "primary", and
* only that one presses, drags, places the caret and clicks;
* "secondary" asks the node under the pointer for a context menu and
* moves nothing else, and every button but the primary reaches a node
* that claims it with `onButton`, press to release.
* A button past the middle one is its number, `3 + n` — the code a
* `button` event carries for it.
*/
mouse(down: boolean, clicks?: number, button?: MouseButtonName | number): void
scroll(dx: number, dy: number): void
/**
* One event of a scroll gesture: `begins`
* on its first, then the rest go to the target it picked, wherever
* the pointer or the content has gone since — the latching a native
* swipe gets, for a headless test. `scroll` is a gesture of its own.
*/
scrollGesture(dx: number, dy: number, begins: boolean): void
/**
* A wheel's notches, in lines (+y = scroll up), as part of a scroll
* gesture: latched as `scrollGesture` is, at 48 px a line by default, and on a
* scroll container a whole notch glides toward a target further
* notches move (ADR 0050) — `advance` the clock to see it land. A
* fraction of a line is applied as it comes.
*/
wheel(lx: number, ly: number, begins: boolean): void
/**
* A trackpad's pinch, as part of a pinch gesture (backlog F256):
* `delta` the magnification since the last event (positive = zoom
* in), `begins` on its first. The first picks the innermost
* `onScroll` node around the pointer — whatever its `scrollAxes`,
* passing by one that names `scrollMods` — and the rest go to it
* wherever the pointer goes, as its message with `scroll: {x, y, dx:
* 0, dy: 0, lines: null, zoom}` in it. Nothing scrolls for it.
*/
pinch(delta: number, begins: boolean): void
/** Committed text input (typing, paste); routed to the focused editor. */
text(text: string): void
/**
* Text an IME committed at the end of a composition: a focused
* `` takes it, otherwise the focused `onKey` sink hears it as
* its message with `text: {text}` in it — the one committed text a
* `key` event never carries. `type`/`press` stay the way to type.
*/
commit(text: string): void
/**
* The clipboard's answer to a paste (`requestPaste()`), with what
* the pasteboard marked it: routed as `commit` is, and
* a focused `onKey` sink hears its message with `text: {text}` in
* it, `concealed: true` / `transient: true` there for the markers
* set. No
* marks is a paste nothing marked, the same answer `commit` gives.
*/
paste(text: string, marks?: { concealed?: boolean; transient?: boolean } | null): void
/**
* An in-progress IME composition: `text` is the uncommitted string
* (empty ends the composition without a commit), `cursor` the byte
* range inside it the IME's caret covers, or null. A focused ``
* shows it inline; otherwise the focused `onKey` sink hears its
* message with `preedit: {text, cursor}` in it.
*/
preedit(text: string, cursor?: [number, number] | null): void
/**
* Editing key by name ("left", "backspace", "enter", ...) with optional
* modifiers `{shift, word, doc, ctrl}` (`ctrl` is Control itself,
* which on macOS is not the primary `doc`).
*/
key(name: EditKeyName, mods?: KeyMods): void
/**
* Raw key press for `onKey` sinks (modal keymaps): a single character
* (layout-resolved, e.g. "W" or "$"), a name ("left", "enter", "escape",
* "f5", ...), with mods `{shift, ctrl, alt, super}`. Editing keys for
* focused editors still go through `key()`. `repeat` marks a press the
* OS auto-repeated. The sink hears its message with `key: {phase:
* "down", ...}` in it.
*
* `physical` is the US-QWERTY key at that *position*, spelled the same
* way; omit it and it is the position's US key: the lower-case letter
* for a letter, `code` for everything else — the pair a window
* reports for ⇧Z is `code: "Z", physical: "z"`, and so is this door's.
* Passing both is how a driver reports a non-US
* layout, and it is what makes the reported `code` portable: a
* layout producing something outside ASCII would leave a Latin
* keymap matching nothing, so the position's US key stands in, as
* Shift prints it (`"J"`, `":"`; unshifted under Alt). What the press
* types is still `code` as passed — the layout's own character.
*/
keyDown(code: string, mods?: KeySinkMods, repeat?: boolean, physical?: string): void
/**
* The release of a key, spelled the way `keyDown` spells it (`physical`
* included): a sink that declared `keyUp` hears `key: {phase: "up",
* ...}` with `text` null; one that did not hears nothing,
* since presses only is the keymap default. A release whose press the
* sink never got resolves nothing, and moving focus while a key is
* held delivers the `up` first.
*/
keyUp(code: string, mods?: KeySinkMods, physical?: string): void
/**
* A whole key going down, the way a window sends it: the raw press
* to an `onKey` sink, and then what the core is asked to do with that
* key — Escape dismisses a modal, Tab walks the focus ring, an arrow
* nudges a focused slider, Space presses a focused control, a
* printable character reaches the focused editor.
*
* **This is the one to reach for.** `keyDown` and `key` are its two
* halves, kept for a test that means to drive one channel and not the
* other; a test that means "the user pressed this key" wants both,
* and `keyDown("escape")` leaving a modal open is what having to
* choose used to cost.
*
* Spelled exactly as `keyDown`: a single character (layout-resolved,
* e.g. "W" or "$") or a name ("left", "enter", "escape", "f5", ...),
* with mods `{shift, ctrl, alt, super}`, `repeat` for an OS
* auto-repeat, and `physical` for the US-QWERTY key at that position.
* `release()` is the other end of the same key.
*
* Spell it the way the OS does, because nothing here re-spells it: a
* shifted letter is the upper-case letter with `shift` set —
* `press("Z", { shift: true, super: true })` is ⇧⌘Z — and
* `press("z", { shift: true })` is a chord no keyboard produces, which
* a handler switching on `"z"` hears headless and never from a user.
* Fold a one-character `code` to lower case under a chord if a keymap
* binds letters.
*/
press(code: string, mods?: KeySinkMods, repeat?: boolean, physical?: string): void
/**
* The same key coming up, spelled the way `press` spells it. One
* channel, because only one has a second half: the editing keys act
* on the way down, so this is `keyUp` under the name that pairs with
* `press`. A sink that declared `keyUp` hears it; one that did not
* hears nothing.
*/
release(code: string, mods?: KeySinkMods, physical?: string): void
/**
* Physical modifier state changed: `{shift, ctrl, alt, super}`. When
* it differs from the last report, the root's
* `windowEvents.onModifiers` message arrives with `modifiers: {…}` in
* it (ADR 0048).
*/
modifiers(mods?: KeySinkMods): void
/**
* Drains the audio commands the core queued, as plain objects
* (`{kind:"play", playback, sound, volume, loop, fadeIn}`, ...) — what a
* windowed driver would play. For tests and custom drivers.
*/
audioCommands(): AudioCommand[]
/**
* Drains the announcements queued since the last drain, as plain
* objects (`{text, live}`). `runWindowed` drains and delivers them
* itself; a bare `Ctx` hands them back so a driver or a test can see
* what a frame asked to say.
*/
announcements(): Announcement[]
/**
* Serves what `captureTo`, `recordTo` and `stopRecording` asked,
* against the last `frame` (ADR 0055), as a window's runner does after
* each frame it draws: the files written, and a `capture` event in
* `pollEvents` for each ask that named a message. On a machine with no
* GPU adapter each answers `phase: 'failed'`, its `error` starting
* "no GPU".
*/
serveCaptures(): void
/**
* A custom driver reports a playback finished on its own; a tagged
* one becomes a `sound` event in `pollEvents`.
*/
audioEnded(playback: number): void
/**
* The same driver reports that a `stop` it drained landed on a
* playback still running, `at` seconds in: a one-shot `` that
* went away without `finish` is named in a `truncated-playback`
* warning (`warnings()`); any other stop reports nothing.
*/
audioTruncated(playback: number, at: number): void
/**
* The same driver reports that its device refused a `play` it
* drained: a tagged playback becomes a `sound` event with phase
* `refused` in `pollEvents`, and the node that asked is named in a
* `playback-refused` warning either way.
*/
audioRefused(playback: number): void
/**
* Drains the window commands the core queued, as plain objects: what
* chrome nodes asked for (`{kind:"startDrag"|"close"|"minimize"|
* "toggleMaximize", window}`) and what the declared window set decided
* (`{kind:"open", window, owner, origin, config:{kind, width, height,
* activates, anchor}}` / `{kind:"close", window}`).
*/
windowCommands(): WindowCommand[]
/**
* A custom driver reports that the OS closed window `id`: it stays
* closed while still declared, whatever only it declared closes with
* it, and its `windows` entry's `onWindow` message lands in
* `pollEvents` with `window: {phase: "closed", id}` in it (ADR 0048). Nothing happens for the main window (0) or for a
* window the diff already closed.
*/
windowClosed(id: number): void
/**
* A custom driver reports that window `id` was asked to go away: a
* press landed outside it (`"outside"`) or Escape reached it
* (`"escape"`). Its `windows` entry's `onDismiss` message lands in
* `pollEvents` with `dismiss: {reason, id}` in it (ADR 0048), and
* **nothing closes** — the app stops declaring the
* window on the frame it decides to, exactly as it answers a `modal`
* node's dismissal. Nothing happens for a window that is not open.
*/
windowDismissed(id: number, reason: string): void
/**
* The topmost node at (`x`, `y`) (logical px) that blocks a host's
* world, as its key, as of the last finished frame; null for the
* world (backlog F233). A node kui takes the pointer on blocks, and
* so does a box that paints — a background, a border, an image —
* unless it says `hostHit="pass"`; any box that says
* `hostHit="block"` does. For a host that draws the UI over a world
* of its own: a game, a map, a 3D view.
*/
hit(x: number, y: number): string | null
/**
* Whether the pointer is the UI's now: over a node `hit` answers
* for, held by a press, a drag or a selection kui started, or
* anywhere while a menu is open or a `modal` is in effect (backlog
* F233). Ask before handing a press, a drag or a wheel to the world.
*/
pointerWants(): boolean
/**
* Whether the keyboard is the UI's now: an editor has focus, the
* focused node is a key sink (`onKey`), or a menu is open (backlog
* F233). Keep movement and hotkeys while it is false.
*/
keyboardWants(): boolean
/**
* The window title the last frame declared (a root ``), or
* null when it declared none. `runWindowed` applies it to the real
* window; a bare `Ctx` hands it back so a test can assert on it.
*/
windowTitle(): string | null
/**
* Whether the last frame asked for the window above every other
* app's (a root ``); false when it did
* not. `runWindowed` applies it to the real window on change and
* reports what the platform did as `env().window.alwaysOnTop`; a
* bare `Ctx` hands the ask back so a test can assert on it.
*/
alwaysOnTop(): boolean
/**
* Whether the last frame asked for secure keyboard entry (a root
* ``); false when it did not.
* `runWindowed` turns it on while that window has the keyboard and
* keeps the platform's count balanced; a bare `Ctx` hands the ask
* back so a test can assert on it.
*/
secureInput(): boolean
/**
* Which Option keys the last frame asked to act as Alt on macOS (a
* root ``): `"none"`, `"left"`,
* `"right"` or `"both"`, `"none"` when it did not ask. `runWindowed`
* applies it to the window on change; a bare `Ctx` hands the ask back
* so a test can assert on it.
*/
optionAsAlt(): 'none' | 'left' | 'right' | 'both'
/**
* Whether the last frame asked for the platform's input method off
* in its window (a root ``) — no composition, and on a
* Mac no dead keys and no press-and-hold; false when it did not.
* `runWindowed` applies it to the window on change; a bare `Ctx`
* hands the ask back so a test can assert on it.
*/
imeOff(): boolean
/**
* A headless context is one window, the main: this answers whether
* `window` names it (`"main"`, `0`, or left out) and addresses
* nothing else — the same door `KuiWindow` has, so a loop or a test
* can call it on either surface.
*/
useWindow(window?: string | number): boolean
/**
* Registers a w×h RGBA image (pixels copied); returns its id for
* ``. Stable until `removeImage`.
*/
addImage(width: number, height: number, rgba: Buffer): string
removeImage(id: string): void
/**
* Replaces an image's pixels in place (copied): the id is
* unchanged, so every `` shows the new pixels
* next frame with no view change; `width`/`height` may differ
* from the registration. From the first update on the image
* is drawn from a texture of its own — a video frame, a
* camera, a plot the app rasterised itself. A dead id warns
* `foreign-resource` and changes nothing.
*/
updateImage(id: string, width: number, height: number, rgba: Buffer): void
/**
* Registers a WGSL fragment function; returns its id for
* ``. Throws when the source does not
* compile, with the compiler's message in the app's own line
* numbers. Idempotent by source, so the same text gets the
* same id without being validated twice.
*/
addFragment(wgsl: string): string
removeFragment(id: string): void
/**
* Registers a font from file bytes (TTF/OTF/TTC); returns its id
* for the `font` prop on `` / ``. Throws when the
* data holds no usable face.
*/
addFont(data: Buffer): string
/**
* Registers an installed font by family name; null when none
* matches (see `systemFontFamilies`). Also finds families loaded
* with `loadFontsDir` / `loadFontFile`; the same family gets the
* same id.
*/
addSystemFont(name: string): string | null
/**
* Registers a font file by path (memory-mapped); throws when it
* cannot be read or holds no usable face.
*/
loadFontFile(path: string): string
/**
* Loads every font file under a folder (recursively) so its
* families can be picked by name with `addSystemFont`; returns
* the face count.
*/
loadFontsDir(dir: string): number
/**
* Scans the system's fonts again, so a font installed while the
* app runs is found (kui scans them once a process); returns how
* many faces came and went, 0 when nothing did. Tens of
* milliseconds: call it when the set may have changed, not
* every frame.
*/
reloadSystemFonts(): number
/**
* The fonts asked, in order, for a character the text's own
* family has no glyph for, before the platform's fallback list
* — whose first choice on macOS is the system's proportional
* face. Ids from `addFont` / `addSystemFont` / `loadFontFile`;
* one that names no font is left out, and `[]` is the
* platform's list alone. `mono` text asks them straight after
* its own face, ahead of the machine's other monospaced faces.
* A new list shapes every text again; the same list twice is
* nothing.
*/
setFallbackFonts(ids: Array): void
removeFont(id: string): void
/**
* Family names of every font the core can see, installed or
* loaded (sorted).
*/
systemFontFamilies(): Array
/**
* The families `systemFontFamilies` names, in its order, each
* with what its faces say they are: `monospaced` (every face
* fixed-pitch), `weights` (sorted, each once) and `italic`.
* Read from what the font database recorded
* when it scanned each face, so a font picker can put the
* monospaced ones first without loading a file or shaping a
* glyph.
*/
systemFonts(): Array
/**
* Registers a sound from its encoded bytes (wav/ogg/mp3/flac);
* returns its id for ``, the `clickSound` /
* `hoverSound` props and `play`. Stable until `removeSound`.
*/
addSound(data: Buffer): string
removeSound(id: string): void
/**
* Starts a playback: `{volume, loop, fadeIn, tag}`; returns its
* id for `stop` / `setVolume` / `pause` / `resume`. A `tag` is
* the playback's message: it comes back with `sound: {phase,
* playback}` in it (a `SoundMsg`) when the playback finishes on
* its own.
* Says something once, with no node behind it: `announce("Saved")`,
* `announce("3 results", "assertive")`. `"off"` and an empty string
* are both no-ops. A region whose message is on screen is the `live`
* prop instead.
*
* Call it from an event handler. Called while building a frame it
* fires every frame, which the core reports as
* `announcement-repeated`.
*/
announce(text: string, live?: Live): void
/**
* A window plays it on its own device at once; headless nothing
* sounds and the command queues for `audioCommands()`.
*/
play(sound: string, opts?: PlayOptions): number
stop(playback: number, fadeMs?: number): void
setVolume(playback: number, volume: number, tweenMs?: number): void
pause(playback: number, fadeMs?: number): void
resume(playback: number, fadeMs?: number): void
setMasterVolume(volume: number, tweenMs?: number): void
/**
* Events since the last poll: `[{origin, window, key, event,
* payload, slot}]`, payloads as plain data — the message the
* node's handler declared, with the event's data in the field
* `event` names (`drag`, `change`, …); a window's own events
* as its root's `windowEvents` messages and its lifecycle as
* its `windows` entry's (ADR 0047, ADR 0048). A payload is
* always a map: a message that is not one (`onClick: 'save'`)
* arrives under
* `tag` (`{tag: 'save'}`), a `null` one as the field alone or
* `{}` (`Arrived`). `A` types them — the app's own union,
* or one message type when only that is being watched.
*/
pollEvents (): UiEvent []
/**
* Whether a `` branch's decision disagreed with the frame
* just laid out (ADR 0069): the view runs once more and the
* frame is built again — at once on a headless `Ctx`, on the
* next turn on a window. `createApp`'s loop does it itself; a
* test driving `frame` by hand asks.
*/
rerunOwed(): boolean
/**
* What the last layout decided for each `` of the last
* view, in the order the view held them: `true` builds
* `render`, `false` `fallback`, `null` neither yet. The encoder
* reads the next view's choices from it by position.
*/
lazyChoices(): Array
/**
* True when the last frame left a transition mid-flight. A window
* schedules its own redraws for that; this is for tests and
* drivers that want to know when motion has settled.
*/
animating(): boolean
/**
* What the last frame left owed, by kind — `animating()`
* taken apart: `{transition, cycle, depart, requested,
* autoscroll, scroll}`. To the window they are one, and it redraws
* for any of them; to a test they differ, since a keyframe
* `repeat` cycle never ends and `settled()` never resolves
* under one. `quiet()` on the loop waits on everything but
* `cycle`.
*/
owed(): Owed
/**
* Turns on the trace of why frames run: who
* holds each owed frame (`owedBy()`) and whether each frame
* changed what is drawn (`frameUnchanged()`). Off by default,
* where neither costs anything; `frameCause()` is kept either
* way.
*/
setFrameTrace(on: boolean): void
/**
* Why a frame runs, as the names of its reasons: the input it
* answers (`key`, `pointerMove`, `wheel`, …), what a window's
* runner saw (`wake`, `resize`, `caret`, `retry`, …) and
* `owed` when the frame before left one owed.
* Empty for a frame nothing here asked for.
*
* Which frame: on a `Ctx`, from inside a `createApp` view,
* the one that view is for (the loop calls
* `beginFrameCause()` first), and between frames the last one
* built. On a `KuiWindow`, always the last frame drawn: a
* window's view runs when the model changes, ahead of the
* frame that shows it, and the frames a transition or a
* blink runs call no view at all.
*/
frameCause(): FrameCauseName[]
/**
* Who held the frame the last one left owed — `owed()` with
* names: the nodes mid-transition (with their slots), the
* cycles, the departures, the easing scrollers, the held
* drag's scroller, the `animate` nodes, and each line that
* asked for a frame. Read from inside a `createApp` view on a
* `Ctx`, the reason that view's frame exists; between frames,
* the last frame built's; on a `KuiWindow`, the last frame
* drawn's, as `frameCause()` says. Empty
* unless `setFrameTrace(true)`.
*/
owedBy(): OwedBy
/**
* Whether the last finished frame drew exactly what the one
* before drew; `null` untraced and on the first traced frame.
*/
frameUnchanged(): boolean | null
/**
* Whether anything is recorded (ADR 0058): the devtools' Perf
* tab recording or on show, `KUI_PERF_TRACE`,
* `setPerfRecording(true)`. Off, every perf door is a no-op;
* read it to skip reading clocks of your own for
* `perfMeasure`.
*/
perfMeasuring(): boolean
/**
* Begins a span named `name` inside the one open now,
* recording the node the builder has open; end it with
* `spanEnd`. Its id, 0 while nothing is recorded. A span
* crosses a callback by its id; `span(name, fn)` is the
* closure form. One left open when its frame ends is closed
* there and marked cut.
*/
spanBegin(name: string): number
/**
* Ends the span `id` names, and any opened inside it and left
* open; 0, or an id with no begin, is nothing.
*/
spanEnd(id: number): void
/**
* A span timed elsewhere — a parse in a worker, a job — `ms`
* long, ending now, on the track named `name`.
*/
perfMeasure(name: string, ms: number): void
/** Adds `n` to this frame's counter `name`. */
perfCount(name: string, n: number): void
/**
* Sets the reading `name` — a footprint, a buffer's bytes —
* held until set again.
*/
perfGauge(name: string, value: number): void
/**
* Puts an instant on the timeline: a file opened, a command
* run.
*/
perfMark(name: string): void
/**
* Puts a line on the timeline — what the numbers beside it
* cannot say — shown in its frame's detail: at most 64 a
* frame and its gap, of 512 bytes each.
*/
perfNote(text: string): void
/**
* Asks for a frame after this one and names why: `owedBy()`
* lists it under `why`, and a recording's causes read
* `request: why`.
*/
requestFrameFor(why: string): void
/**
* A wake named `name` reached the window: the next frame's
* causes read `wake: name`. Call it where a completion lands —
* a socket's data, a worker's message — before the model
* change it brings.
*/
noteWake(name: string): void
/**
* Starts a recording, dropping what was kept, or stops one and
* keeps it for `perfTrace()` — the Perf tab's record button.
*/
setPerfRecording(on: boolean): void
/** Whether a recording runs. */
perfRecording(): boolean
/**
* What is kept — the last recording, or the frames the Perf
* tab shows — as `kui-trace` bytes, a `.kuitrace` file's.
*/
perfTrace(): Buffer
/**
* Writes out what the file `KUI_PERF_TRACE` names holds so
* far; throws when the write fails.
*/
perfFlush(): void
/**
* Byte budget for the shaped-text cache: every text a frame
* draws is shaped once and kept, and past this many
* (estimated) bytes the least recently drawn entries go at
* the start of the next frame — never what the last frame
* drew. Default 64 MB; a terminal streaming new lines lowers
* it, a viewer that wants every page it showed kept warm
* raises it.
*/
setTextCacheBudget(bytes: number): void
/**
* What the shaped-text cache holds, in the estimated bytes
* the budget is charged against.
*/
textCacheBytes(): number
/** Summary of the last frame's display list. */
stats(): FrameStats
/**
* Asks for the next frame this window draws, written to `path`
* as a picture (ADR 0055): `.png`, `.jpg` / `.jpeg` (quality 90,
* alpha dropped), `.webp` (lossless) or `.gif`, by the
* extension. `message` is what the `capture` event arrives as,
* `capture: {phase: 'saved' | 'failed', path, width, height,
* frames, seconds, error?}` in it; without one the file is
* written and nothing is heard. A window's runner serves it after
* the next frame it draws; a headless `Ctx` after
* `serveCaptures()`.
*/
captureTo(path: string, message?: unknown): void
/**
* Asks for the next frame this window draws, put on the
* clipboard as a picture — "Copy screenshot" (ADR 0055) —
* served and answered as `captureTo` is, the `capture` event's
* `path` empty. A headless `Ctx` queues the picture for
* `takeMenuActions()` after `serveCaptures()`.
*/
captureToClipboard(message?: unknown): void
/**
* Asks for every frame this window draws from the next one on,
* written to `path` as an animation when `stopRecording()` ends
* it (ADR 0055): `.png` / `.apng` (an animated PNG) or `.gif`.
* Each frame shows from when it was drawn until the next, on the
* frame clock. `message` as `captureTo`'s, heard once the file is
* written, with the frames drawn and the `seconds` it lasts. One
* asked for while one runs fails, naming that one.
*/
recordTo(path: string, message?: unknown): void
/**
* Ends the recording with the next frame drawn, which it leaves
* out, and has its file written. Nothing, with none running.
*/
stopRecording(): void
/**
* The last finished frame as pixels (backlog C55): drawn again
* from its draw list on a GPU device of the process's own, with
* no window, and read back over the theme's `bg`. A window
* answers with what its last pump drew — what it shows, less
* what the OS draws behind a translucent one — so a smoke test
* can check the pixels the shipping driver painted; a headless
* `Ctx` with its last `frame`. The first call opens the device
* (tens of ms). Throws, naming why, before any frame or on a
* machine with no GPU adapter.
*/
capture(): Capture
/**
* Raw quads for the finished frame, `quadStride()` bytes each,
* laid out as kui-ffi's KuiQuad (see include/kui.h) and decoded
* by `decodeQuads`. Copied into the Buffer. A window answers
* with what its last pump drew, so a smoke test can read the
* frame the shipping driver painted and not only a headless
* one's. Drive that window with `access(key,
* action)` — `click`, `type` and `key` are refused there,
* because the OS is what drives a real window.
*/
quads(): Buffer
/**
* The clips this frame's quads name through their `clip`
* index, `clipStride()` bytes each, laid out as kui-ffi's
* KuiClip (see include/kui.h) and decoded by `decodeClips`.
* Entry zero clips nothing, so a quad always has one; the
* list is empty only on a frame that drew nothing.
*/
clips(): Buffer
/**
* This frame's fragment draws, in the order their quads index
* them by `uv[0]`: twenty-four doubles each — the handle as
* two 32-bit halves, the sixteen parameters, then where the
* draw's `image` is (0 none, 1 the atlas, 2 a texture of its
* own), the `textureDraws` index when it is 2, and the texel
* rect `x, y, w, h`. The parameters ride a side
* list rather than the quad, so `quads()` alone cannot show
* them and a corpus adapter needs this to compare them.
* Empty on a frame that draws no fragment.
*/
fragmentDraws(): Array
/**
* This frame's texture draws, in the order their quads index
* them by `uv[0]`: nine doubles each — the image handle as two
* 32-bit halves, the pixels' revision, width and height, and
* the texel rect `x, y, w, h` in the image's own texels (the
* whole image, or the crop a `fit="cover"` made). The side
* list a `quads()` texture quad points at.
* Empty on a frame that draws no texture-backed image.
*/
textureDraws(): Array
/**
* Host facts the frame driver pushed in: what the window and the
* display are doing, as of now (see `Env`). This is the same
* surface Lua's `view(env)` reads and C's `kui_env_set*` writes —
* a JSX app needs it to build its own titlebar (inset past the
* macOS traffic lights, pick the maximize glyph), to dim its
* chrome when the window loses focus, or to pace itself against
* the real refresh rate.
*
* Note `env().focused` is the *window*'s keyboard focus, not the
* focused node's key — that is `focused()`, one call up.
*/
env(): Env
/**
* The palette this window paints with: one `0xRRGGBBAA` number
* per role, derived from `env().system` unless this app said
* otherwise (`setAccent` / `setTheme`). A view reads it and
* paints with it — `` — and the stock
* widgets already do, so a JSX app that only uses ``,
* the context menu and `` follows the OS's light and
* dark without reading this at all.
*/
theme(): Theme
/**
* Keep following the OS's light/dark, but paint this accent
* instead of the OS's — an app with a brand colour. A
* `0xRRGGBBAA` number or a `"#hex"` string, as any colour
* prop takes; `null` goes back to the OS's own.
*/
setAccent(accent: number | string | null): void
/**
* Pin the palette: an object of role overrides on top of the
* base named by `appearance` (`"light"`, `"dark"`, or absent
* for the OS's), each value a colour the way a prop takes
* one. Follows nothing afterwards — `setAccent(null)` is how
* an app goes back to following the OS.
*
* `{ appearance: "dark", accent: "#d2691e" }` is a dark app
* with one colour changed; every role the object does not
* name keeps the base's, and the ones derived from the accent
* (its hover, its pressed shade, the label on it, the ring,
* the selection tint) are recomputed unless named too.
*
* `{ light: {…}, dark: {…} }` is one palette for each
* appearance (ADR 0061): each half is overrides on that base,
* and the core picks the half the OS's appearance asks for
* every frame, so a skin follows light and dark with no
* listener. A half left out is the stock base for it.
*/
setTheme(theme: ThemeOverrides | ThemePairOverrides): void
/**
* The sizes the stock widgets are built from — the palette's
* other axis: one number per metric, logical px before the
* scale factor. Read it so a control of your own agrees with
* `` on a radius and a padding: ``.
*/
metrics(): Metrics
/**
* Makes these the frame's metrics: overrides on top of the
* set in effect, or on top of `base: "comfortable"` (the
* stock set) / `"compact"` (a dense tool's), then `scale`
* multiplying every length — a density slider. `null`
* restores the stock set. Density is the app's to choose;
* nothing in the OS is followed.
*/
setMetrics(metrics: MetricsOverrides | null): void
/**
* Declare the app's named colours, lengths and families:
* `{ colors: { peach: '#ffcc99', ink: { light, dark } },
* lengths: { sideW: 132 }, families: { code: ['JetBrains
* Mono', 'mono'] } }`. Replaces the table whole, so an app
* whose lengths change with a viewport tier declares again
* on `resize`. A name a theme, metrics or number role owns,
* or a family token named for a stock family, is dropped
* with a `reserved-token` warning. A colour may be a
* recipe over an earlier one: `{ from: 'peach',
* ops: [['lift', 0.3]] }`, dropped with `unknown-token` when
* its source is not there. Reference one in a prop
* as `'$peach'` — `defineTokens` types the names. The raw
* addon door; `index.js` wraps it to keep the encoder's map
* in step, so call `setTokens` and not this.
*/
setTokensRaw(tokens: { colors: [string, unknown][], lengths: [string, number][], families?: [string, string | string[]][] }): void
/**
* The tokens a view here sees this frame, resolved: colours as
* `0xRRGGBBAA` for the appearance in effect, lengths in px,
* families as the name each list picked, under `colors`,
* `lengths` and `families`. Roles are not listed — read them
* off `theme()` and `metrics()`.
*/
tokens(): ResolvedTokens
/**
* `frame` / `setView` report the `$name` references the
* encoder could not resolve — nothing declared, or the other
* kind — through here, as `unknown-token`, once per name.
*/
warnUnknownTokens(names: [string, string][]): void
/**
* `measureText`'s door (index.js adds `measureText` itself):
* one `` element as `encoder.encodeText` writes it, and
* the answer is what that text lays out to — `{width, height,
* lines}` in logical px at the context's scale, capped to
* `maxWidth` when given. The metrics do not scale linearly:
* `measured × zoom` is not `measure(size × zoom)`, because
* shaping rounds per size, so anything that zooms measures at
* the size it draws.
*/
measureTextBinary(stream: Float64Array, strings: Uint8Array, maxWidth?: number | undefined | null): TextMetrics
/**
* `caretInText`'s door (index.js adds `caretInText` itself):
* one `` element as `measureTextBinary` takes it, and
* the answer is where byte `byte` of that text lands once laid
* out at `maxWidth` (unwrapped without one) — the rect
* `caretRect` gives when a node draws the text at that width,
* from the text's own top-left rather than the viewport's.
*/
caretInTextBinary(stream: Float64Array, strings: Uint8Array, maxWidth: number | undefined | null, byte: number): Rect | null
/**
* Drains the warnings the core raised since the last call
* (see `Warning`), each distinct (code, node) pair once.
* `createApp` collects them on `app.warnings` for you, and
* `runWindowed` prints them, unless either was told not to.
*/
warnings(): Warning[]
/**
* Turns the per-frame diagnostic checks behind `warnings` on or
* off. A bare `Ctx` has them on; `createApp` / `runWindowed`
* turn them off under `NODE_ENV=production`.
*/
setDiagnostics(on: boolean): void
/**
* Whether a wheel's notch glides on a scroll container (ADR
* 0050): on by default; off, a notch jumps on the next frame.
* The system's reduced motion jumps either way. `runWindowed`
* takes it for the whole app as `smoothWheel`.
*/
setSmoothWheel(on: boolean): void
/** That switch, read back. */
smoothWheel(): boolean
/** Enables acceleration for rapid wheel notches on scroll containers. */
setWheelAcceleration(on: boolean): void
/** Whether wheel acceleration is enabled. Off by default. */
wheelAcceleration(): boolean
/**
* How a wheel's notch scrolls: a preset's name, slow to
* fast `'gentle'`, `'relaxed'`, `'standard'` (the default), `'brisk'` (an
* alias of standard), `'swift'`; or `{ linePx, response, kick }`,
* any left out kept as they are — the base travel per line in
* logical px (48), the glide's response in seconds (0.27)
* and its kick, 0 to 1 (0.6). Clamped into what the glide
* can use.
* `runWindowed` takes it for the whole app as `wheelFeel`.
*/
setWheelFeel(feel: WheelPreset | Partial): void
/** That feel, read back as clamped. */
wheelFeel(): WheelFeel
/**
* How a held drag scrolls a container at its edge — kui's own
* caret drag and drag-select, and `edgeScroll`: a preset's
* name, slow to fast `'gentle'`, `'standard'` (the default),
* `'brisk'`; or `{ zonePx, speedPxS, curve, rampSecs,
* rampMax, capPxS, pullBackPx }`, any left out kept as they
* are — the edge zone's depth (60 px), the speed at its edge
* (500 px/s) along a curve (its exponent, 2), the ramp while
* held (to 6 times over 1.5 s), the cap (3000 px/s) and how
* far a pull back restarts the ramp (8 px). Clamped.
* `runWindowed` takes it for the whole app as
* `edgeScrollFeel`.
*/
setEdgeScrollFeel(feel: EdgeScrollPreset | Partial): void
/** That feel, read back as clamped. */
edgeScrollFeel(): EdgeScrollFeel
/**
* Draws a faded subtree as one picture, faded once (ADR
* 0056): a node whose own `opacity` is under 1 has its
* subtree's quads between a group's begin and end markers
* (kinds 10 and 11), unfaded by it, the end carrying the
* fade, so a label on its own fill no longer washes into it.
* A window has it on; a headless `Ctx` has it off, every
* quad of a faded subtree carrying its fade, and turns it on
* for `capture()` to show what a window shows.
*/
setOpacityGroups(on: boolean): void
/**
* Every warning the core has raised so far, drained or not,
* oldest first — the log `warnings()` leaves behind, for a
* reader that is not the driver (a devtools stream).
*/
warningsRaised(): Warning[]
/**
* Turns the per-frame node snapshot behind `nodes()` on or off
* (off unless a devtool asked: the copy is O(nodes) a frame).
*/
setInspect(on: boolean): void
/**
* Turns the core's devtools panel on or off: the event stream, the runtime's facts and
* the tree, drawn by the core beside the app's own tree in the
* main window — or where `setDevtoolsDock` says — with its
* controls and its `Ctrl+Shift+` chords handled inside
* the core, so nothing of it reaches `update`. `KUI_DEVTOOLS=1`
* in the environment is the same call made by nobody, for a
* `KuiWindow`; a headless `Ctx` never reads it.
*/
setDevtools(on: boolean): void
/** Whether the devtools panel is on. */
devtools(): boolean
/**
* Where the devtools panel sits: `"left"`, `"right"`,
* `"bottom"`, `"window"` (one of its own, named
* `kui-devtools`) or `"off"` (hidden, the chords still live);
* `"side"` is the right. Throws on any other word.
*/
setDevtoolsDock(dock: DevtoolsDock): void
/** Where the devtools panel sits (see `setDevtoolsDock`). */
devtoolsDock(): DevtoolsDock
/**
* Where the last frame laid the app out in its window, in
* logical px: `{x, y, w, h}`, the viewport `env().viewport`
* sizes with its origin — `x` is the pane's width under a
* left dock, and the rect is the whole window with the panel
* off, in its own window, or anywhere but the main window.
* `quads()` are in physical px, so multiply by the scale
* (`env().viewport.scale`) to filter them: a quad inside is
* the app's, one outside is the dock's — but for the root's
* `bg`, which is the window's too and under a dock also fills
* the whole window beneath the pane. All zeros before the
* first frame, like `env().viewport`; a window's `size()` is
* the reading from before it.
*/
hostArea(): Rect
/**
* Seeds the panel's theme override, what its `T` and `A`
* chords cycle from: `base` is `"light"`, `"dark"` or `null`
* for the app's own; `accent` an `#rrggbb` string or `null`.
*/
setDevtoolsTheme(base: 'light' | 'dark' | null, accent: string | null): void
/**
* Respells the chord that moves the keyboard into the panel
* and back out — and brings a hidden panel back — from its
* default `"ctrl+shift+i"`: `"f12"`, `"mod+shift+d"` (`mod`
* is Command on macOS, Control elsewhere), `"⌥⌘I"`, any
* spelling a menu item's `accel` takes. The panel's other
* chords stay `Ctrl+Shift+`. With another chord set,
* `Ctrl+Shift+I` reaches the app like any other press. Throws
* on a spelling kui cannot name.
*/
setDevtoolsKey(key: string): void
/**
* The chord `setDevtoolsKey` set, or the default, in its
* portable spelling: `"ctrl+shift+i"`, `"f12"`,
* `"super+alt+d"`.
*/
devtoolsKey(): string
/**
* The declared devtools tab on show, by name, or `null` for
* one of the panel's own, the panel off or popped out.
* What `frame` / `setView` read once before encoding,
* so a ``'s function child is called only for
* that tab.
*/
devtoolsShownTab(): string | null
/**
* The node the panel's tree tab has selected, as a hex key,
* or `null` — what an inspector in a
* declared tab reads to say which node it is about.
*/
devtoolsSelected(): string | null
/** The tree row under the pointer, as a hex key, or `null`. */
devtoolsHovered(): string | null
/** The node the picker is over while picking, or `null`. */
devtoolsPicked(): string | null
/**
* Raises the panel's picker from outside it — an inspector in
* a `` asking "which node?" — or puts it away.
* Picking happens over the app in
* the main window: `devtoolsPicked()` is the node under the
* pointer while it is up, and the press lands it in
* `devtoolsSelected()`. Raised while a declared tab is on
* show, the pick leaves that tab up; raised otherwise — a
* tab named but not declared yet included — it is the
* `Ctrl+Shift+P` pick and shows the tree tab. A hidden
* panel comes back docked.
*/
setDevtoolsPick(on: boolean): void
/** Whether the panel's picker is up. */
devtoolsPicking(): boolean
/**
* Shows the panel's tab named `name` from the app's side —
* what the strip's click and `Ctrl+Shift+N` do, for a command
* that jumps to the app's own tab. `name` is one
* of the panel's own (`facts`, `events`, `tree`, `perf`, in any case)
* or a ``'s, exactly as declared. A declared
* name the panel does not list
* yet is kept and shows once a frame declares it; the return
* says whether the panel lists it now. A hidden panel comes
* back docked; `setDevtools(true)` is still the app's to
* call. Call it once, not every frame: it would pin the strip
* against the user's own clicks.
*/
setDevtoolsTab(name: DevtoolsTab | (string & {})): boolean
/**
* The tab the panel is on, by name: one of its own or a
* ``'s — the selection itself, panel on or off,
* unlike `devtoolsShownTab()`, which is the encoder's reading
* of a declared tab on show.
*/
devtoolsCurrentTab(): DevtoolsTab | (string & {})
/**
* Selects a node in the panel's tree tab from outside it and
* reveals it there, as the picker does; `null` clears. `key`
* is a hex key an event carried or `keyOf` answered.
*/
setDevtoolsSelected(key?: string | undefined | null): void
/**
* The key legend the panel's facts tab shows: `[keys, what]`
* pairs.
*/
setDevtoolsLegend(legend: [string, string][]): void
/**
* The last finished frame's nodes in tree order, each with what
* it is, the label it was opened under, where layout put it
* (in the app's viewport, like `layoutOf`), and
* the declarations that explain the rest — what a tree view
* and a node inspector are built from. Empty until
* `setInspect(true)` and a frame after it.
*/
nodes(): NodeInfo[]
/**
* The prop names the encoder threw away while lowering a tree,
* as `[element, name]` pairs, raised as `unknown-prop` warnings
* (see `Warning`). A name outside the schema never reaches the
* binary stream, so the encoder is the only side that sees it;
* `frame` / `setView` report what they dropped through here.
* Behind the same `setDiagnostics` gate, and once per name. A
* pair under `protocol().menuItem.name` is a key a ``
* option object carried that no menu row reads.
*/
warnUnknownProps(props: [string, string][]): void
/**
* What assistive technology sees of the last frame (see
* `AccessTree`). A window hands it to the platform by itself
* (AccessKit); this is for tests and tooling.
*/
accessTree(): AccessTree
/**
* A request from assistive technology on a node: an `AccessAction`
* name the node advertises, with `value` the new text for
* `setValue`. It arrives as the event a user doing the same
* would cause (ADR 0047): a click, a slider's or an editor's
* `change`, an `onKey` sink's `text` or `select`. `key` is either spelling of the node — the hex key
* an event carried (16 digits), or the label its `key` prop
* declared, resolved through the last frame (see `focus`).
* Resolved like its pointer/keyboard equivalent, so the resulting
* events come out of `pollEvents`. A real screen reader's
* requests arrive through a window on their own.
*/
access(key: string, action: AccessAction, value?: string | AccessArg): void
/**
* Hover state as of the last frame. `key` is either spelling,
* as for `focus`: the label a `key` prop declared, or the hex
* key an event carried. For plain hover styling prefer the
* `hoverBg` / `pressedBg` props — the core resolves those without
* a round trip.
*/
isHovered(key: string): boolean
/**
* Press state as of the last frame; `key` is either spelling,
* as for `isHovered`.
*/
isPressed(key: string): boolean
/**
* Whether any member of the hover group `group` (the
* `hoverGroup` name) is hovered, as of the last frame.
*/
isGroupHovered(group: string): boolean
/**
* Whether any member of the hover group `group` holds a
* press, as of the last frame (backlog C92).
*/
isGroupPressed(group: string): boolean
/**
* Whether files dragged in from the OS are over `key` — for
* drop-dependent layout; the colour swap is the
* `dropBg` prop. `key` is either spelling, as for `isHovered`.
*/
isDropTarget(key: string): boolean
/**
* The `onDrop` zone the dragged files are over, as the hex key
* an event carries, or null — what a driver answers the OS
* with after each `dragFiles`, and what a test reads to say a
* zone was found.
*/
dropTarget(): string | null
/**
* The pointer shape for where the pointer is now, in the `cursor`
* prop's own vocabulary: whatever the topmost node under it
* declared with `cursor`, and when it declared nothing,
* `'text'` over an editor or a `selectable` scope and
* `'default'` over everything else — an `onClick`, `focusable`
* or `onDrag` node included, as a native button is, so a hand
* or a grab is the view's to declare (the stock `button`
* declares `'pointer'` itself). A captured drag keeps the
* dragged node's shape wherever the pointer goes; no pointer at
* all is `'default'`. A window applies it to the real cursor by
* itself and only touches it when the answer changes; this is
* for tests and drivers.
*/
cursorShape(): CursorShape
/**
* Whether a node holds keyboard focus — any node: an editor, an
* `onKey` sink, a button Tab landed on (see `focused`). `key` is
* a hex key or a declared label, as for `focus`.
*/
isFocused(key: string): boolean
/**
* The node holding keyboard focus (hex key), or null. Tab /
* Shift-Tab walk every control in tree order, Enter and Space
* press the focused one, and the arrows nudge a focused
* slider — `press("tab")`, `press(" ")`, `press("right")`,
* which is what a keyboard sends. (`key("tab")` is the half
* of that press the core acts on, for a test that means to
* drive one channel; `keyDown` is the other half, the one an
* `onKey` sink hears.)
*/
focused(): string | null
/**
* Whether focus got where it is by keyboard or assistive
* technology rather than a click — when it shows (the ring, or
* `focusBg`).
*/
focusVisible(): boolean
/**
* Whether the window's "Tab moves focus" toggle is on
* (backlog C99): a multiline editor whose Tab would type
* walks the focus ring instead. Ctrl+M flips it in such an
* editor (Ctrl+Shift+M on macOS); what a status label reads.
*/
tabMovesFocus(): boolean
/**
* Sets the appearance the host's `dark` / `light`
* conditions read in place of the palette's (backlog C113):
* `'light'`, `'dark'`, or null for the palette's again.
*/
setRulesAppearance(appearance?: string | undefined | null): void
/**
* The caret's blink phase — `true` draws it. A
* custom editor reads it in `view` and skips its caret node
* on the off phase, keeping the `caret` row on its `line`
* either way; the window's clock sets it while a focused
* `` or such a line has a caret, and parks it hidden
* while the window has no keyboard. Always `true` headless.
*/
caretVisible(): boolean
/**
* The frame clock in seconds (backlog F134): the one the
* tweens and cycles read, `setTime` or the loop's own, 0
* before either. Read a deadline off it rather than off
* `Date.now()`, so `advance` moves both.
*/
now(): number
/**
* Asks for a frame at `at` on the frame clock (backlog F135),
* in seconds: a toast's expiry, a sequence's next beat. Nothing
* is owed until then, so `animating()` stays false; a window
* sleeps to it and draws, and the earliest time asked for wins.
* A headless loop's `advance` past it draws the frame it ends
* on, as it does for a `tick`.
*/
requestFrameAt(at: number): void
/**
* The exit the node `key` leaves by if it leaves in the frame
* that finishes next (backlog F136), over the `exit` it
* declared: `{dx: 400, opacity: 0}`, the same fields as
* `exit`. A card a button throws aside is removed in the same
* handler, with no frame drawn first to aim it. It aims a node
* that declares an `exit`, with that node's transition, and is
* forgotten when that frame finishes.
*/
exitWith(key: string, exit: EnterProp): void
/**
* The frame-clock time the next asked-for frame is due at, in
* seconds; `null` when none was asked for.
*/
nextFrameAt(): number | null
/**
* Whether there is a caret to blink: a focused ``'s, or
* the `caret` a `line` under the focused sink declares — unless
* the line declares it `caretSolid`, which
* anchors and reads but arms no clock. What the window's
* clock is armed on; headless, what a test reads to see that
* an idle view asks for no frame.
*/
hasCaret(): boolean
/**
* The driver's half of the blink: sets the phase. A window
* runs its own clock; headless, a test drives it to see the
* off phase drawn.
*/
setCaretVisible(visible: boolean): void
/**
* Moves keyboard focus to a node now (an editor, an `onKey` sink,
* a control, a `focusable` box); `keyFocus` on a box is the
* declarative, edge-triggered form.
*
* `key` is either spelling of the node: the 16-digit hex key an
* event carried, or the label its `key` prop declared —
* `focus('note')` — resolved through the last frame, so a node
* the user has never touched can be named. Labels are unique
* among siblings, not across the tree: when two nodes declare
* the same one, the first in tree order wins and an
* `ambiguous-key` warning says so. A label no node declared
* throws.
*/
focus(key: string): void
/**
* The hex key of the node a key label names — the label a `key`
* prop declared, not the accessible name a reader hears
* (`keyNamed`), resolved through the frame being built so
* far and then the last finished one — or null when no node
* declared it. The door for holding a key across frames;
* every call that takes a key takes the label too, so this
* is for caching one, or for checking that a name reached
* the view. Two nodes on one label under different parents
* resolve to the first in tree order and raise
* `ambiguous-key` — among the host's own first, and a
* plugin's component is answered from its own nodes only.
*/
keyOf(label: string): string | null
/**
* The reverse of `keyOf`: the label the node with this hex key
* (as an event carries it) was opened under, in the frame
* being built so far and then the last finished one — or null
* for an auto-keyed node, a key no frame declared, or a string
* that is not a key. What a key from `focused()`, an event or
* a log turns back into; the label is the local one, so two
* rows of a list under different parents answer the same.
*/
labelOf(key: string): string | null
/**
* The hex key of the first node in the last finished frame
* whose accessible name is `name` (backlog F137) — its
* `label` prop, else its own text, else a control's derived
* name — so a test clicks "the button named Like" as a reader
* would: `ctx.access(ctx.keyNamed('Like')!, 'click')`, or
* `app.access(…)` on a headless app, which settles what
* follows through `update`. (`click` is the pointer's, at
* coordinates, on an app.) Not `keyOf`'s key label, which a
* reader never hears. Null when no node has the name; two
* raise `ambiguous-name`.
*/
keyNamed(name: string): string | null
blur(): void
/**
* What Tab does, as a call — for an `onKey` sink that binds Tab
* itself and wants to hand the keyboard on: the next focusable
* node in tree order, wrapping.
*/
focusNext(): void
/** What Shift-Tab does. */
focusPrev(): void
/**
* Enters a focus region — a box declared `focusRegion`, named by
* the label its `key` prop declares or by the hex key an event
* carried — or the main ring for `null`. Focus lands on what that
* ring last held if the node is still there, else its
* `initialFocus`, else its first stop, and shows.
*
* Resolved when the next frame finishes, like `focusNext`, so
* the `update` that toggles a dock on may enter it in the same
* turn — which is why a label is taken as a name to hold rather
* than resolved now: the node need not exist yet. A frame that
* then declares no `focusRegion` under the name raises
* `focus-region-without-node` and moves nothing.
*/
focusRegion(key?: string | undefined | null): void
/**
* Focuses item `index` of a list, table or other composite —
* named by the label its `key` prop declares or the hex key an
* event carried — when the next frame finishes (backlog C125):
* the item opened with that data `index`, a row a windowed list
* did not build being scrolled to and landed on the frame that
* builds it (an index past `rowCount` is the last row), else,
* where items carry no index, the item at that place. A focused
* item that vanishes hands focus to the item now at its place on
* its own; this names one.
*/
focusItem(key: string, index: number): void
/**
* The focus region in effect — the hex key of the `focusRegion`
* node whose ring Tab walks — or `null` for the main ring. What
* a chord that toggles between a dock and the app reads to know
* which way it is going.
*/
region(): string | null
/**
* Scrolls whatever contains a node so it shows — "scroll to the
* selected row", which needs the container geometry only the core
* has. The request resolves against the *next* frame's layout (one
* is requested), so a row the view is about to declare for the
* first time reveals fine. If that frame does not declare the key,
* or nothing above it scrolls, it is a no-op and is not kept for a
* later frame; two reveals before one frame are contradictory, so
* the last wins. `key` is a hex key or a declared label, as for
* `focus`. A label the last frame did not declare is resolved
* when the coming frame finishes, so a row that frame declares
* for the first time is reachable by name too; one it does not
* declare either is a `label-without-node` warning.
*/
reveal(key: string): void
/**
* A scroll container's retained offset `{x, y}` as the last layout
* clamped it (positive = content moved up / left) — the number to
* keep in a model and hand back to `setScroll`. Zero for a node
* that never scrolled.
*/
scrollOffset(key: string): ScrollOffset
/**
* Everything the last layout resolved for the scroll container
* `key`: its box `{x, y, w, h}`, its content size `{contentW,
* contentH}` and the clamped `offset` — `null` for a key no layout
* has resolved as a container.
*
* This is what makes a long list affordable. The core builds every
* child a view declares, so ten thousand rows cost ten thousand
* rows; knowing `h` and `offset.y`, a view renders the rows that
* fit plus two spacers holding the space of the rest. Read while
* building, it describes the previous frame, so a resize slices one
* frame late — render a row or two extra at each end.
*/
scrollGeometry(key: string): ScrollGeometry | null
/**
* The rect the last frame laid `key` out at, `{x, y, w, h}`
* in logical viewport px, for a node that declared `onLayout`
* — the `layout` event's numbers, read back during the next
* build with no event and no model field; `null` for any
* other key. Read while building, it
* describes the previous frame, like `scrollGeometry`.
*/
layoutOf(key: string): { x: number, y: number, w: number, h: number } | null
/**
* Where the pointer is over `key`, `{x, y, w, h}`: its place
* from the node's top-left and the node's size, as of the
* last frame (backlog C119) — over it while `0 <= x < w` and
* `0 <= y < h`. `null` while the pointer is outside the
* window, and for a node the last frame gave neither a hit
* region (`hoverable`, `onHover`, anything that takes the
* pointer) nor an `onLayout` rect. A pointer move is a frame,
* so a view that follows the pointer reads it each frame.
*/
pointerIn(key: string): { x: number, y: number, w: number, h: number } | null
/**
* Where a point lands in the text a keyed node drew: a byte
* offset into its text and the visual row within that node —
* counted across every run the key covers, so a `line` row of
* inline runs is one row and a wrapped run as many as it
* wrapped to; not the ordinal `line` node a pointer event's
* `line` names — or null for a key that drew no
* text. A `role="none"` subtree under the key (a gutter) is
* not its text, as the access tree reads it. `x`/`y` are the logical viewport px a
* `click` or `drag` event carries, so a custom editor turns the
* event into a caret position with one call — no prefix
* measuring, no cell-width arithmetic. A node holding several
* text runs (a `line` row of token runs) answers across them
* in order, the way the access tree reads the line. Answered
* from the frame that finished: the layout the pointer was
* over.
*/
textHit(key: string, x: number, y: number): TextHit | null
/**
* Opens a context menu at `(x, y)` over the node `key`, with
* `items` as plain objects: `{label, role, enabled, id,
* accel}`, all but `label` optional. `role` is one of
* `custom` (the default), `separator`, `cut`, `copy`,
* `paste`, `selectAll` or `lookUp`; the standard ones take
* their own wording when `label` is empty, and the core
* performs the ones it can.
*
* Choosing a row posts `key`'s `onMenu` message with `menu:
* {role, item}` in it, or nothing where `key` declares none,
* and closes the menu; a press outside it or Escape closes it
* with nothing posted. What an app answering its own
* `onContextMenu` calls — and what the core calls itself for
* a right-click nobody claimed, so the two menus are one
* implementation.
*
* `options.maxWidth` / `options.maxHeight` hold the menu and
* its submenus to a size, logical px: a row wider is
* ellipsized, a menu taller scrolls (backlog F210). One left
* out, or not above 0, is the room the menu is drawn in.
* `options.inWindow` keeps the menu drawn in the window where
* the runner would show one that does not fit in a popup
* window of its own.
*/
openMenu(key: string, x: number, y: number, items: MenuItemInput[], options?: { maxWidth?: number; maxHeight?: number; inWindow?: boolean } | null): boolean
/**
* Drains what choosing a menu row left for the host: the
* clipboard, which is the host's in this library. Each entry
* is `{kind}` — `"setClipboard"` with `text` (and `html`
* where there is formatting to carry), `"paste"` asking for
* what is on the clipboard (deliver it back with `commit()`,
* which a focused editor takes as typing and a focused
* `onKey` sink hears as a `text` event),
* or `"lookUp"` with the `text` to show a definition panel
* for at `x`, `y`.
*
* A windowed app never needs this — the driver drains it —
* but a headless one does: nothing else empties the queue,
* and a Copy nobody drains is a copy that never happened.
* Asks for the platform's Open, Save or folder dialog:
* `{mode, multiple, title, filters: [{name, extensions}],
* directory, fileName, tag}`, every field optional. The answer
* is a `files` event, the dialog's `tag` with `files: {paths}`
* in it — `paths` empty when the user cancelled. A window's runner shows the dialog; a
* headless context queues it for `takeFileRequests`. False when
* one is already out: one dialog at a time.
*/
requestFiles(dialog?: FileDialogOptions): boolean
/** Whether a file dialog asked for is still unanswered. */
awaitingFiles(): boolean
/**
* The file dialog asked for and not yet taken — at most one —
* as `requestFiles` took it, for a host that shows it itself.
* A window never needs this: its runner drains and shows it.
* Answer with `answerFiles`.
*/
takeFileRequests(): FileDialogOptions[]
takeMenuActions(): MenuAction[]
/**
* Puts `text` on the system clipboard — the action a menu's
* Copy queues, with a door on it for an `onKey` sink that
* hears the raw `Ctrl-c` and had nowhere to bind it.
* `html` is a second flavour beside the text for the
* host to offer, never in place of it. A window applies it
* at its next drain (after every input and every frame); a
* headless `Ctx` hands it out through `takeMenuActions()`.
*/
setClipboard(text: string, html?: string | undefined | null): void
/**
* Puts a secret on the system clipboard the way a password
* manager does: a window writes it marked
* concealed and transient — `org.nspasteboard.ConcealedType`
* and `TransientType` on macOS, the exclusion formats on
* Windows — so no clipboard manager shows or keeps it. A
* headless `Ctx` hands it out through `takeMenuActions()` as
* `{kind:"setClipboardSecret", text}`.
*/
setClipboardSecret(text: string): void
/**
* Puts files on the system clipboard, as a file manager's
* Copy does — "Copy file" on an attachment: a window writes
* them as the platform's file list (`CF_HDROP` on Windows,
* file URLs on macOS, `text/uri-list` on Linux), so they paste
* into a file manager or a mail as the files. The paths as the
* app names them; the window makes them absolute. False, and
* nothing queued, for none. A headless `Ctx` hands it out
* through `takeMenuActions()` as
* `{kind:"setClipboardFiles", paths}` (backlog F247).
*/
setClipboardFiles(paths: Array): boolean
/**
* Puts a picture on the system clipboard — `width` by `height`
* straight RGBA, what `capture()` and `decodeImage` hand out,
* copied — as the platform's image type: "Copy image". A
* window writes it at its next drain; a headless `Ctx` hands it
* out through `takeMenuActions()` as `{kind:"setClipboardImage",
* width, height}`. False, and nothing queued, when `rgba` is
* not `width * height * 4` bytes or the size is zero.
*/
setClipboardImage(width: number, height: number, rgba: Uint8Array): boolean
/**
* Asks for what is on the clipboard — the action a menu's
* Paste queues. A window reads the clipboard and hands the
* text back as a paste: a focused `` takes it as
* typing, and a focused `onKey` sink hears it as its message
* with `text: {text}` in it — with `concealed: true` /
* `transient: true` there where the pasteboard marked it so
* — so an app that owns its text inserts a
* paste the way it inserts a committed IME string and never
* reads the clipboard itself. Headless, the request comes out
* of `takeMenuActions()` as `{kind:"paste"}` and the test
* answers it with `paste(text, marks)` or `commit(...)`.
*/
requestPaste(): void
/**
* Whether a paste asked for is still unanswered: one ask at a
* time — a second `requestPaste` while one is out is dropped,
* and the `commit` that answers it (an empty one for an empty
* clipboard) lets the next through.
*/
awaitingPaste(): boolean
/**
* The menu this window has open, or null:
* `{target, x, y, items}`. What a host rendering menus itself
* reads after `setNativeMenus(true)` — the core then keeps
* the menu as state and draws none of it — and answers with
* `activateMenuItem` or `closeMenu`. A row reads exactly as a
* `menuBar()` row does (`menu_item_json`).
*/
menu(): OpenMenu | null
/**
* Tells the core this host shows menus itself. It then keeps
* the open menu as state and draws none of it: read it with
* `menu()`, show it, and report back with `activateMenuItem`
* or `closeMenu`. Off by default, which is the menu this
* library draws.
*/
setNativeMenus(on: boolean): void
/**
* The application menu the frame declared, or null:
* `{revision, menus: [{label, enabled, items}]}`. What a
* host with a menu bar of its own reads after
* `setNativeMenuBar(true)`; `revision` changes only when the
* declaration does, so a host rebuilds nothing until it moves.
*/
menuBar(): MenuBarState | null
/**
* Tells the core the platform owns the menu bar, so
* ` ` draws nothing and this host is the one handing
* the declaration over (`menuBar()`) and reporting what was
* chosen (`activateMenuBarItem`). Off by default, which is
* the bar this library draws.
*/
setNativeMenuBar(on: boolean): void
/**
* Reports that the platform's menu bar chose row `item` of
* menu `menu` — the same path a press on the drawn bar's row
* takes. False when the app hears nothing: a row that is not
* there, or a `` that declares no `onMenu` (ADR 0048).
*/
activateMenuBarItem(menu: number, item: number): boolean
/**
* `activateMenuBarItem` for a row inside a submenu of menu
* `menu`, by its path through the rows' `items`. False for a
* row that is not there or that opens a submenu.
*/
activateMenuBarPath(menu: number, path: Array): boolean
/**
* Tells the core this host can show the platform's definition
* panel. The standard Look Up row is then offered where it
* means something, and a force click over text asks for one.
*/
setLookupAvailable(on: boolean): void
/**
* Reports that the host's own menu chose row `index` — the
* same path a press on the drawn menu's row takes. An index
* past the end closes the menu and posts nothing. False when
* nothing was taken: no menu was open, or the row cannot be
* chosen — disabled, or a separator — in which case the menu
* stays open and nothing is posted.
*/
activateMenuItem(index: number): boolean
/**
* `activateMenuItem` for a row inside a submenu, by its path
* through the rows' `items`: `[2, 0]` is the first row of the
* third row's submenu. False where `activateMenuItem` is, and
* for a row that opens a submenu, which is never chosen.
*/
activateMenuPath(path: Array): boolean
/** Closes whatever menu is open; true when there was one. */
closeMenu(): boolean
/**
* Asks for the selection as text: `{ text, asked }`.
*
* `text` is the selection when the core has all of it. When
* the selection reaches rows a virtual list never built,
* `asked` is true instead and a `selectionrange` event —
* the scope's `onSelectionRange` message with `selectionrange:
* {from: {index, byte}, to: {index, byte}}` in it — is posted
* on the scope — the rows behind that gap are the app's, so the
* app answers with `answerSelectionRange`, and the answer is
* what reaches the clipboard.
*/
requestCopy(): { text: string | null, asked: boolean }
/**
* Answers a `typeahead` event (ADR 0070) with the data index of
* the row the search names, in the composite `key` (either
* spelling) that asked: the core goes there, scrolling to a
* row the frame did not build. False when that composite asked
* nothing, or focus has left it.
*/
answerTypeahead(key: string, index: number): boolean
/**
* Answers a `selectionrange` ask with the text for the range
* it named, whole. False when nothing asked — a late answer
* cannot overwrite what has been copied since.
*/
answerSelectionRange(text: string): boolean
/**
* The window's selected text: what a `selectable` scope has
* selected, or the focused ``'s selection, whichever
* the window holds — starting either clears the other, so
* there is never a choice to make. Null with no selection,
* `""` when a selection exists but covers nothing (a press
* that placed both ends together).
*/
selectionText(): string | null
/**
* The text selection's two ends as the drag made them:
* `{anchor: {index, byte}, focus: {index, byte}}`, `index` the
* data index of the virtualised row the end is in (null
* outside every virtualised row — the `index` a
* `selectionrange` ask would name) and `byte` the offset in
* that row's own text. Directed, so a Shift-click that kept
* the anchor reads as one. Null with no text
* selection; a grid's is `cellSelection()`.
*/
selectionEnds(): SelectionEnds | null
/**
* A `cells` grid's selection, the window's when it lives in
* one: the grid's key, `anchor` and `focus` as the drag made
* them — each an absolute `line` (`originLine` plus the row,
* so a scroll does not move it) and a `col` — and `block`
* for a rectangular one. Null when the
* window's selection is not a grid's; a text selection's ends
* are `selectionEnds()`.
*/
cellSelection(): CellSelection | null
/**
* The selection as HTML, carrying the formatting the text
* declared — bold, italic, a span's own colour — and *not*
* the node's colour, which is the app's theme rather than
* the text's.
* Null with no text selection. Meant as a second clipboard
* flavour beside the plain text, never instead of it.
*/
selectionHtml(): string | null
/**
* Selects every run inside the selection scope a keyed node
* declared (`selectable`), first byte to last — Select All,
* scoped. False when that node drew no text, or is not a
* scope. Text the frame built but never drew is included:
* the selection is over the scope's text, not over what fits
* on screen.
*/
selectAllIn(key: string): boolean
/**
* Drops the window's selection, whichever it is. True when
* there was one to drop.
*/
clearSelection(): boolean
/**
* The caret rect for a byte offset in the text a keyed node
* drew: logical viewport px, zero wide, one line tall — where
* a caret, a selection edge or an IME candidate window goes.
* A byte past the text is the end; null for a key that drew
* no text.
*/
caretRect(key: string, byte: number): Rect | null
/**
* Where the OS candidate window goes while a composition is
* under way: the focused ``'s caret, or a custom editor's
* `line` carrying `caret`; null when nothing with a caret is
* focused. The windowed driver applies it itself; headless,
* it is what a test reads to see the anchor moved.
*/
imeRect(): Rect | null
/**
* Sets that offset the way the wheel would; the next frame's
* layout clamps it, so `(0, 0)` jumps to the top and a huge `y` to
* the end without knowing the content height.
*/
setScroll(key: string, x: number, y: number): void
/**
* Moves the scroll container `key` by the content that moved
* under it — `drawn` for where the content is drawn (and an
* eased leg's start), `target` for the retained offset — with
* no ease asked or ended and no frame asked for: a correction to
* the frame the view is building. What `list()` calls when the
* rows it measured came out another height than the estimate
* they stood at, so the row under the pointer stays put.
* A label nothing declared yet is the first
* frame, which has nothing to correct.
*/
shiftScroll(key: string, drawn: number, target: number): void
/**
* Scrolls the container `key` for a drag the app holds with
* the pointer at `x`, `y`, when the pointer is in the edge
* zone inside `rect` — usually the container's own
* `scrollGeometry` — or past it, by `edgeScrollFeel`: at
* once, faster the deeper and the longer it is held, fully
* deep when pinned against the window's edge. Returns what it
* moved, `{ x, y }` positive toward later content, and asks
* for the next frame so a pointer held still goes on
* scrolling; `null` out of the zones, at the end that way, or
* for a key that is no scroll container. Call it once a frame
* while the drag is held — from the view — and place the
* drag's live end under the pointer after; not before the
* drag has left its press's click slop. kui's own caret drag
* and drag-select scroll by the same feel on their own.
*/
edgeScroll(key: string, x: number, y: number, rect: Rect): { x: number, y: number } | null
/**
* The names of every window open right now, `"main"` first,
* then in the order they opened — what a view's root
* `windows` declared and the diff has opened. `view(model,
* window)` is called once per name.
*/
windows(): Array
/**
* The name of the window this core draws: `"main"`, or the
* name the declaration that opened `env().window.id` used.
*/
windowName(): string
/**
* Asks the driver to resize a window to `width`×`height` logical
* px. A request and not a declaration: a window's `size` config
* is read on the frame it opens and never again, because the user
* owns a window's size once it exists, so this is the only way an
* app moves a live one. Queued the way `reveal` is — a `KuiWindow`
* applies it on its next pump, and the window answers with the
* ordinary `resize` event carrying the size it actually became,
* while a headless `Ctx` has no window and simply keeps the
* request. `window` is the id events carry (`env().window.id`),
* 0 for the main window.
*/
setWindowSize(window: number, width: number, height: number): void
/**
* Asks the driver to give a window keyboard focus; queued the same
* way. Advisory: whether the window manager agreed shows up as
* `env().focused` on the frames that follow, not as a reply.
*/
focusWindow(window: number): void
/** Display names, indexed by setWindowFullscreen's display. */
displayNames(): Array
/** Request borderless fullscreen on the current or chosen display. */
setWindowFullscreen(window: number, enabled: boolean, display?: number | undefined | null): void
/** Show or hide a window without losing its context. */
setWindowVisible(window: number, visible: boolean): void
/** Have OS close hide a window while another stays visible. */
setWindowCloseHides(window: number, enabled: boolean): void
editText(key: string): string | null
/**
* Replaces an editor's text, leaving the caret at the end.
*
* It reaches an editor that does not exist yet: the `update`
* that opens a rename field runs a frame ahead of the view
* that declares it, so the text is held for the frame that
* declares this name and seeds the editor there, over
* `initial`. Name it by the label its `key` prop declares —
* the spelling that needs nothing to exist yet, since the
* hex key comes from an event the editor has not fired.
* Either spelling works, as for `focus`; a label the last
* frame declared lands at once, and one it did not is held.
* Held for that one frame — a name nothing declares on it
* drops its text with an `edit-text-without-editor` warning,
* so a name the view spells differently is a line rather
* than a field that opens with the wrong text.
*
* A redraw is asked for only when the text reached an editor.
* A held seed changed nothing on screen, and the frame that
* will — the view that declares the editor — is the app's:
* a redraw here re-lowered the *retained* tree, which declares
* no editor, and that was the frame the hold expired on when
* the call came from a `dispatch` outside the loop
* (`runWindowed` draws that model before it pumps).
*/
setEditText(key: string, text: string): void
}
/**
* Decoded pixels (`decodeImage`): `width` by `height`, four bytes each
* (RGBA), row by row from the top left, alpha not premultiplied — what
* `addImage`, `updateImage` and a window's `icon` take.
*/
export interface DecodedImage {
width: number
height: number
rgba: Buffer
}
/**
* A finished frame as pixels (`capture`): `width` by `height` physical
* pixels, four bytes each (RGBA), row by row from the top left, alpha not
* premultiplied — what `addImage` takes — and the scale it was drawn at.
*/
export interface Capture {
width: number
height: number
scale: number
rgba: Buffer
}
/**
* Every frame of an animated image (`decodeAnimation`), each the whole
* canvas, with the seconds each shows and how many times the sequence
* plays (absent: for ever).
*/
export interface DecodedAnimation {
width: number
height: number
frames: Array
delays: Array
loops?: number
}
/**
* Which frame shows at a moment (`animationAt`), and the seconds after
* the start the next is due — `Infinity` once a finite animation has
* played out.
*/
export interface AnimationShowing {
index: number
next: number
}
/**
* Decodes PNG, JPEG, WebP or GIF bytes (an animated file's first frame)
* with the runner's decoder (backlog F138), so an app that ships a photo
* needs no image package: `ctx.addImage(d.width, d.height, d.rgba)`.
* Throws, naming why, for bytes that are not an image or do not decode.
* Loads a DTCG token file, or a Resolver Module document composing
* several (ADR 0062), into kui's token shape: `tokens` is what
* `setTokens` takes (`ctx.setTokens(loadTokens('brand.resolver.json').tokens)`),
* colours with a light and a dark half; `names` says which DTCG path each
* name came from; `warnings` names every token skipped or changed (a
* shadow kui has no kind for, a colour clamped into sRGB). `source` is a
* path, or a token document already parsed. Throws when the file will not
* read or parse or the resolver cannot be resolved.
*/
export declare function loadTokens(source: string | object, options?: DtcgOptions): LoadedTokens
export declare function decodeImage(bytes: Buffer): DecodedImage
/**
* What `encodeImage` takes beside the pixels: `quality` for a JPEG, 1 to
* 100 (absent: 90).
*/
export interface EncodeOptions {
quality?: number
}
/**
* Encodes straight RGBA — `width` by `height` pixels, four bytes each,
* what `capture()` and `decodeImage` hand out — as a file's bytes with
* the runner's encoders (ADR 0054), so a test or a probe keeps a capture
* with no image package: `writeFileSync('shot.png', encodeImage('png',
* s.width, s.height, s.rgba))`. `png` is lossless at the fast setting,
* `jpeg` lossy at `quality` with alpha dropped, `webp` lossless, `gif` 256
* colours. Throws, naming why, for another format, a size of zero or
* pixels that are not that size.
*/
export declare function encodeImage(format: 'png' | 'jpeg' | 'webp' | 'gif', width: number, height: number, rgba: Buffer, options?: EncodeOptions): Buffer
/**
* Shows the file or folder at `path` in the system's file manager —
* selected in Finder or Explorer, its folder opened elsewhere — and
* returns once it has started (backlog F203): "Show in folder" beside a
* file the app saved. Throws, naming why, for a path that does not exist
* or a file manager that would not start.
*/
export declare function showInFolder(path: string): void
/**
* Opens the recording at `path` in kui-perf, the trace inspector — `kui
* perf `, the `kui` on `PATH` — and returns once that has started
* (backlog F253): what applies the devtools' `openRecording` action.
* Throws, naming why, for a file that does not exist or no `kui` that
* would start.
*/
export declare function openRecording(path: string): void
/**
* Opens `target` with what the system opens it with — a file in its
* app, a folder in the file manager, a URL (`https:`, `mailto:`, …) in
* the browser or mail client — and returns once that has started
* (backlog F203). Throws, naming why, for a path that does not exist or
* a tool that would not start.
*/
export declare function openExternal(target: string): void
/**
* Begins a span named `name` where the window is not at hand — a
* library deep in a stack — on the recording of the window whose span is
* open now on this thread (an `update` the loop times, a span of the
* app's), nested in the span open now (backlog F215). 0 while none is,
* which `threadSpanEnd` ignores.
*/
export declare function threadSpanBegin(name: string): number
/**
* Ends the span `threadSpanBegin` began, and any opened inside it and
* left open; 0, or an id with no begin, is nothing.
*/
export declare function threadSpanEnd(id: number): void
/**
* What an `AnimationEncoder` takes beside its size: `loops`, how many
* times it plays (absent or 0: for ever).
*/
export interface AnimationEncoderOptions {
loops?: number
}
/**
* An animated PNG or GIF written a frame at a time (ADR 0054): `add`
* each frame — the whole canvas, straight RGBA, a `capture()`'s `rgba` —
* with the seconds it shows, then `finish` for the file's bytes. It keeps
* only the rectangle each frame changed, folds a frame that changed
* nothing into the time of the one before, and gives a frame too short
* for the format (1 ms for `png`, 20 ms for `gif`) to the next, so a
* recording at retina size holds two whole frames and the changes.
*/
export declare class AnimationEncoder {
/**
* An encoder for `width` by `height` frames as `png` (an animated PNG,
* every colour exact) or `gif` (256 colours). Throws, naming why, for
* another format or a size it cannot hold.
*/
constructor(format: 'png' | 'gif', width: number, height: number, options?: AnimationEncoderOptions)
/**
* Adds a frame that shows for `seconds`. Throws, naming why, for
* pixels that are not a frame's size, a time that is negative or not
* finite, or an encoder already finished.
*/
add(rgba: Buffer, seconds: number): void
/**
* The file's bytes; the encoder is spent. Throws, naming why, with no
* frame added or when it was finished already.
*/
finish(): Buffer
}
/**
* Decodes every frame of an animated GIF, PNG (APNG) or WebP, each the
* whole canvas, and the seconds each shows; a GIF frame asking for 10 ms
* or less shows for 100, as browsers show it. A still image is one frame
* shown for ever. Play it on the frame clock with `animationAt`,
* `updateImage` and `requestFrameAt`.
*/
export declare function decodeAnimation(bytes: Buffer): DecodedAnimation
/**
* Which of the frames with these `delays` shows `elapsed` seconds after
* the animation started, playing `loops` times (null or 0 for ever), and when
* the next is due: `animationAt(gif.delays, gif.loops, ctx.now() -
* started)`, then `updateImage` when the index moved and
* `requestFrameAt(started + next)`.
*/
export declare function animationAt(delays: Array, loops: number | undefined | null, elapsed: number): AnimationShowing
/** Byte stride of one quad in the `quads()` buffer. */
export declare function quadStride(): number
/** Byte stride of one clip in the `clips()` buffer. */
export declare function clipStride(): number
/**
* A real kui window (winit + wgpu) driven from Node. The event loop is
* pumped, not run: call `pump()` between libuv turns so winit and libuv share
* the main thread — or prefer `runWindowed`, which does that for you, unless
* you are building your own loop. One event loop per process (winit event
* loops are not recreatable on every platform), any number of windows on
* it: a view whose root declares `windows` opens more, `windows()` lists
* them, and `setView` takes the name of the one a tree is for.
*/
export declare class KuiWindow {
/**
* Options: `{width, height, minWidth, minHeight, maxWidth, maxHeight,
* chrome: "native" | "custom" | "borderless", textAa: "auto" | "gray"
* | "subpixel", frameLatency, system, icon, appId, backdrop, titlebar:
* "standard" | "medium" | "tall"}`. The min/max pairs bound what the user can
* resize the window to; either half may stand alone. `system` pins part of `env.system` over what the OS
* says, for the life of the window — `{motion: 'reduced'}` is what a
* user who asked for less motion would get, on a machine whose owner
* did not; `icon: {rgba, width, height, resource}` is every window's
* icon; see `WindowOptions`.
*/
constructor(title: string, options?: WindowOptions)
/**
* Which window the per-window doors — `focus`, `editText`,
* `setEditText`, `isHovered`, `scrollGeometry`, `openMenu`,
* `selectionText`, `setTheme`, `setMetrics`, `setTokens`, the
* devtools setters, input injection — address from here on: a name
* from `windows()`, or the id an event carries in `window`; left out,
* the main window. Returns whether that window is open now; until it
* is, the doors address the main window. `runWindowed` aims the
* surface at the window whose view it is calling and at the window
* an event came from before handing the surface to `update`, so an
* app that never calls this reads and writes the window it is being
* asked about. Resources, `windows()`, `pump` and
* `pollEvents` are the session's and unaffected.
*/
useWindow(window?: string | number): boolean
/**
* `setView` with a flat binary instruction stream (see `Ctx::frame_binary`).
* Copied once so redraws (resize, hover) can re-lower it between pumps.
* `window` names which window the tree is for — `"main"` when left
* out; the names `windows()` lists otherwise.
*/
setViewBinary(stream: Float64Array, strings: Uint8Array, window?: string | undefined | null): void
/**
* Processes pending OS events without blocking. Returns false once the
* window has closed.
*/
pump(): boolean
/**
* Registers what the window calls as it goes for good — its close
* button, `close()`, Quit from the menu or the dock — once, from
* inside the `pump()` that saw it and before that pump returns.
* On macOS a Quit ends the process inside that pump:
* `pump()` never returns, `runWindowed` never resolves and nothing
* after it runs, not even `process.on('exit')` — so this is the only
* thing an app runs on ⌘Q. `runWindowed` registers its config's
* `teardown(model)` here; a driver of its own does the same. The
* window is gone by then: the callback saves and returns. A window
* door it calls anyway throws, and a shared one (`editText`,
* `pollEvents`, …) reads a blank core instead of the closing window's,
* which the pump in flight still holds. The last registration wins.
*/
onTeardown(callback: () => void): void
/**
* `pump`, but parked for up to `timeoutMs` — returning the moment an
* OS event or a `Waker` wake arrives, and otherwise when the time is
* up. Returns false once the window has closed. `timeoutMs` is clamped
* to an hour; anything not finite and positive parks not at all.
*
* **What this buys is latency, and it is not what `runWindowed` idles
* on.** The wake is the event itself rather than the next tick after
* it, so the period stops setting the response time — but two measured
* things make it the wrong default, and both surprise:
*
* - **It does not save CPU; it costs.** winit 0.30's macOS pump stops
* on the *first* wake of any kind, so a park does not hold: a 200 ms
* park runs 101 ms on average. Against polling at the same period, a
* 32 ms period is 49 pumps a second and 4.59% of a core parked,
* against 30 pumps and 1.80% polled.
* - **A blocked main thread is a blocked libuv**, and Node cannot be
* asked whether that is safe — `process.getActiveResourcesInfo()`
* reports nothing for an in-flight `fs.readFile`. Behind a 50 ms
* park, 200 sequential `await readFile` went from 6 ms to 4 s.
*
* So reach for it only in a loop that owns its whole process and does
* no async I/O, and wants the latency. Otherwise `pump()` on a timer
* is both cheaper and safer — which is what `runWindowed` does.
*/
pumpUntil(timeoutMs: number): boolean
/**
* How long until the window next needs a pump, in ms — `null` when
* nothing the runner knows about is due.
*
* A driver on a fixed interval hits every deadline the shell has
* already worked out a whole interval late: the caret blink, a
* transition's next frame, the audio poll, a window's first-frame
* retry. Ask after each pump and sleep to the answer instead, which is
* what `runWindowed` does. It only ever asks for *sooner* — whether an
* OS event is waiting is not something it can say, so a driver still
* needs a ceiling of its own.
*/
nextDeadlineMs(): number | null
/**
* The viewport the app lays out into, in logical px, plus the scale
* factor: `{width, height, scale}` — the window's inner size, less
* the devtools' dock while the panel is docked.
* Readable before the first frame (in `setup` and `init`, where
* `env().viewport` is still 0×0), and re-reported as a
* `resize: {width, height, scale}` in the root's
* `windowEvents.onResize` message (a `ResizeMsg`) whenever the window changes size, moves to a
* display with another DPI, or the dock comes, goes or is dragged.
* It used to be the window's inner size, so an app that seeded
* its tiers from it under `KUI_DEVTOOLS=1` drew for the whole window.
*/
size(): WindowSize
/**
* Frame timing measured by the runner — what the latency HUD draws,
* as data: `{frames, framesTotal, pumps, wokenPumps, last: {inputMs,
* viewMs, layoutMs, renderMs, waitMs, totalMs, workMs} | null,
* avgTotalMs, maxTotalMs, avgWorkMs, maxWorkMs}`. The averages and
* maxima are over the last 120 frames and `frames` is how many of
* those the ring holds — its fill, one per painted frame up to 120, so
* a window that paints only when something changes stays below it for
* as long as it idles. `framesTotal` and `pumps` are the monotonic
* counts of every frame painted and every `pump()` taken, so two
* readings a second apart are that second's frame and
* pump rates. `wokenPumps` counts the pumps that found an OS event or
* a wake — a key, the pointer crossing, a focus change, a resize, a
* reader asking — so two readings a second apart with it
* unmoved are a second the desktop left the window alone, and every
* frame in it was the app's own. `waitMs` is vsync backpressure;
* `workMs` is everything else.
*/
frameStats(): FrameTiming
/** Asks the window to close; the next pump returns false. */
close(): void
/**
* Registers a w×h RGBA image (pixels copied); returns its id for
* ``. Stable until `removeImage`.
*/
addImage(width: number, height: number, rgba: Buffer): string
removeImage(id: string): void
/**
* Replaces an image's pixels in place (copied): the id is
* unchanged, so every `` shows the new pixels
* next frame with no view change; `width`/`height` may differ
* from the registration. From the first update on the image
* is drawn from a texture of its own — a video frame, a
* camera, a plot the app rasterised itself. A dead id warns
* `foreign-resource` and changes nothing.
*/
updateImage(id: string, width: number, height: number, rgba: Buffer): void
/**
* Registers a WGSL fragment function; returns its id for
* ``. Throws when the source does not
* compile, with the compiler's message in the app's own line
* numbers. Idempotent by source, so the same text gets the
* same id without being validated twice.
*/
addFragment(wgsl: string): string
removeFragment(id: string): void
/**
* Registers a font from file bytes (TTF/OTF/TTC); returns its id
* for the `font` prop on `` / ``. Throws when the
* data holds no usable face.
*/
addFont(data: Buffer): string
/**
* Registers an installed font by family name; null when none
* matches (see `systemFontFamilies`). Also finds families loaded
* with `loadFontsDir` / `loadFontFile`; the same family gets the
* same id.
*/
addSystemFont(name: string): string | null
/**
* Registers a font file by path (memory-mapped); throws when it
* cannot be read or holds no usable face.
*/
loadFontFile(path: string): string
/**
* Loads every font file under a folder (recursively) so its
* families can be picked by name with `addSystemFont`; returns
* the face count.
*/
loadFontsDir(dir: string): number
/**
* Scans the system's fonts again, so a font installed while the
* app runs is found (kui scans them once a process); returns how
* many faces came and went, 0 when nothing did. Tens of
* milliseconds: call it when the set may have changed, not
* every frame.
*/
reloadSystemFonts(): number
/**
* The fonts asked, in order, for a character the text's own
* family has no glyph for, before the platform's fallback list
* — whose first choice on macOS is the system's proportional
* face. Ids from `addFont` / `addSystemFont` / `loadFontFile`;
* one that names no font is left out, and `[]` is the
* platform's list alone. `mono` text asks them straight after
* its own face, ahead of the machine's other monospaced faces.
* A new list shapes every text again; the same list twice is
* nothing.
*/
setFallbackFonts(ids: Array): void
removeFont(id: string): void
/**
* Family names of every font the core can see, installed or
* loaded (sorted).
*/
systemFontFamilies(): Array
/**
* The families `systemFontFamilies` names, in its order, each
* with what its faces say they are: `monospaced` (every face
* fixed-pitch), `weights` (sorted, each once) and `italic`.
* Read from what the font database recorded
* when it scanned each face, so a font picker can put the
* monospaced ones first without loading a file or shaping a
* glyph.
*/
systemFonts(): Array
/**
* Registers a sound from its encoded bytes (wav/ogg/mp3/flac);
* returns its id for ``, the `clickSound` /
* `hoverSound` props and `play`. Stable until `removeSound`.
*/
addSound(data: Buffer): string
removeSound(id: string): void
/**
* Starts a playback: `{volume, loop, fadeIn, tag}`; returns its
* id for `stop` / `setVolume` / `pause` / `resume`. A `tag` is
* the playback's message: it comes back with `sound: {phase,
* playback}` in it (a `SoundMsg`) when the playback finishes on
* its own.
* Says something once, with no node behind it: `announce("Saved")`,
* `announce("3 results", "assertive")`. `"off"` and an empty string
* are both no-ops. A region whose message is on screen is the `live`
* prop instead.
*
* Call it from an event handler. Called while building a frame it
* fires every frame, which the core reports as
* `announcement-repeated`.
*/
announce(text: string, live?: Live): void
/**
* A window plays it on its own device at once; headless nothing
* sounds and the command queues for `audioCommands()`.
*/
play(sound: string, opts?: PlayOptions): number
stop(playback: number, fadeMs?: number): void
setVolume(playback: number, volume: number, tweenMs?: number): void
pause(playback: number, fadeMs?: number): void
resume(playback: number, fadeMs?: number): void
setMasterVolume(volume: number, tweenMs?: number): void
/**
* Events since the last poll: `[{origin, window, key, event,
* payload, slot}]`, payloads as plain data — the message the
* node's handler declared, with the event's data in the field
* `event` names (`drag`, `change`, …); a window's own events
* as its root's `windowEvents` messages and its lifecycle as
* its `windows` entry's (ADR 0047, ADR 0048). A payload is
* always a map: a message that is not one (`onClick: 'save'`)
* arrives under
* `tag` (`{tag: 'save'}`), a `null` one as the field alone or
* `{}` (`Arrived`). `A` types them — the app's own union,
* or one message type when only that is being watched.
*/
pollEvents (): UiEvent []
/**
* Whether a `` branch's decision disagreed with the frame
* just laid out (ADR 0069): the view runs once more and the
* frame is built again — at once on a headless `Ctx`, on the
* next turn on a window. `createApp`'s loop does it itself; a
* test driving `frame` by hand asks.
*/
rerunOwed(): boolean
/**
* What the last layout decided for each `` of the last
* view, in the order the view held them: `true` builds
* `render`, `false` `fallback`, `null` neither yet. The encoder
* reads the next view's choices from it by position.
*/
lazyChoices(): Array
/**
* True when the last frame left a transition mid-flight. A window
* schedules its own redraws for that; this is for tests and
* drivers that want to know when motion has settled.
*/
animating(): boolean
/**
* What the last frame left owed, by kind — `animating()`
* taken apart: `{transition, cycle, depart, requested,
* autoscroll, scroll}`. To the window they are one, and it redraws
* for any of them; to a test they differ, since a keyframe
* `repeat` cycle never ends and `settled()` never resolves
* under one. `quiet()` on the loop waits on everything but
* `cycle`.
*/
owed(): Owed
/**
* Turns on the trace of why frames run: who
* holds each owed frame (`owedBy()`) and whether each frame
* changed what is drawn (`frameUnchanged()`). Off by default,
* where neither costs anything; `frameCause()` is kept either
* way.
*/
setFrameTrace(on: boolean): void
/**
* Why a frame runs, as the names of its reasons: the input it
* answers (`key`, `pointerMove`, `wheel`, …), what a window's
* runner saw (`wake`, `resize`, `caret`, `retry`, …) and
* `owed` when the frame before left one owed.
* Empty for a frame nothing here asked for.
*
* Which frame: on a `Ctx`, from inside a `createApp` view,
* the one that view is for (the loop calls
* `beginFrameCause()` first), and between frames the last one
* built. On a `KuiWindow`, always the last frame drawn: a
* window's view runs when the model changes, ahead of the
* frame that shows it, and the frames a transition or a
* blink runs call no view at all.
*/
frameCause(): FrameCauseName[]
/**
* Who held the frame the last one left owed — `owed()` with
* names: the nodes mid-transition (with their slots), the
* cycles, the departures, the easing scrollers, the held
* drag's scroller, the `animate` nodes, and each line that
* asked for a frame. Read from inside a `createApp` view on a
* `Ctx`, the reason that view's frame exists; between frames,
* the last frame built's; on a `KuiWindow`, the last frame
* drawn's, as `frameCause()` says. Empty
* unless `setFrameTrace(true)`.
*/
owedBy(): OwedBy
/**
* Whether the last finished frame drew exactly what the one
* before drew; `null` untraced and on the first traced frame.
*/
frameUnchanged(): boolean | null
/**
* Whether anything is recorded (ADR 0058): the devtools' Perf
* tab recording or on show, `KUI_PERF_TRACE`,
* `setPerfRecording(true)`. Off, every perf door is a no-op;
* read it to skip reading clocks of your own for
* `perfMeasure`.
*/
perfMeasuring(): boolean
/**
* Begins a span named `name` inside the one open now,
* recording the node the builder has open; end it with
* `spanEnd`. Its id, 0 while nothing is recorded. A span
* crosses a callback by its id; `span(name, fn)` is the
* closure form. One left open when its frame ends is closed
* there and marked cut.
*/
spanBegin(name: string): number
/**
* Ends the span `id` names, and any opened inside it and left
* open; 0, or an id with no begin, is nothing.
*/
spanEnd(id: number): void
/**
* A span timed elsewhere — a parse in a worker, a job — `ms`
* long, ending now, on the track named `name`.
*/
perfMeasure(name: string, ms: number): void
/** Adds `n` to this frame's counter `name`. */
perfCount(name: string, n: number): void
/**
* Sets the reading `name` — a footprint, a buffer's bytes —
* held until set again.
*/
perfGauge(name: string, value: number): void
/**
* Puts an instant on the timeline: a file opened, a command
* run.
*/
perfMark(name: string): void
/**
* Puts a line on the timeline — what the numbers beside it
* cannot say — shown in its frame's detail: at most 64 a
* frame and its gap, of 512 bytes each.
*/
perfNote(text: string): void
/**
* Asks for a frame after this one and names why: `owedBy()`
* lists it under `why`, and a recording's causes read
* `request: why`.
*/
requestFrameFor(why: string): void
/**
* A wake named `name` reached the window: the next frame's
* causes read `wake: name`. Call it where a completion lands —
* a socket's data, a worker's message — before the model
* change it brings.
*/
noteWake(name: string): void
/**
* Starts a recording, dropping what was kept, or stops one and
* keeps it for `perfTrace()` — the Perf tab's record button.
*/
setPerfRecording(on: boolean): void
/** Whether a recording runs. */
perfRecording(): boolean
/**
* What is kept — the last recording, or the frames the Perf
* tab shows — as `kui-trace` bytes, a `.kuitrace` file's.
*/
perfTrace(): Buffer
/**
* Writes out what the file `KUI_PERF_TRACE` names holds so
* far; throws when the write fails.
*/
perfFlush(): void
/**
* Byte budget for the shaped-text cache: every text a frame
* draws is shaped once and kept, and past this many
* (estimated) bytes the least recently drawn entries go at
* the start of the next frame — never what the last frame
* drew. Default 64 MB; a terminal streaming new lines lowers
* it, a viewer that wants every page it showed kept warm
* raises it.
*/
setTextCacheBudget(bytes: number): void
/**
* What the shaped-text cache holds, in the estimated bytes
* the budget is charged against.
*/
textCacheBytes(): number
/** Summary of the last frame's display list. */
stats(): FrameStats
/**
* Asks for the next frame this window draws, written to `path`
* as a picture (ADR 0055): `.png`, `.jpg` / `.jpeg` (quality 90,
* alpha dropped), `.webp` (lossless) or `.gif`, by the
* extension. `message` is what the `capture` event arrives as,
* `capture: {phase: 'saved' | 'failed', path, width, height,
* frames, seconds, error?}` in it; without one the file is
* written and nothing is heard. A window's runner serves it after
* the next frame it draws; a headless `Ctx` after
* `serveCaptures()`.
*/
captureTo(path: string, message?: unknown): void
/**
* Asks for the next frame this window draws, put on the
* clipboard as a picture — "Copy screenshot" (ADR 0055) —
* served and answered as `captureTo` is, the `capture` event's
* `path` empty. A headless `Ctx` queues the picture for
* `takeMenuActions()` after `serveCaptures()`.
*/
captureToClipboard(message?: unknown): void
/**
* Asks for every frame this window draws from the next one on,
* written to `path` as an animation when `stopRecording()` ends
* it (ADR 0055): `.png` / `.apng` (an animated PNG) or `.gif`.
* Each frame shows from when it was drawn until the next, on the
* frame clock. `message` as `captureTo`'s, heard once the file is
* written, with the frames drawn and the `seconds` it lasts. One
* asked for while one runs fails, naming that one.
*/
recordTo(path: string, message?: unknown): void
/**
* Ends the recording with the next frame drawn, which it leaves
* out, and has its file written. Nothing, with none running.
*/
stopRecording(): void
/**
* The last finished frame as pixels (backlog C55): drawn again
* from its draw list on a GPU device of the process's own, with
* no window, and read back over the theme's `bg`. A window
* answers with what its last pump drew — what it shows, less
* what the OS draws behind a translucent one — so a smoke test
* can check the pixels the shipping driver painted; a headless
* `Ctx` with its last `frame`. The first call opens the device
* (tens of ms). Throws, naming why, before any frame or on a
* machine with no GPU adapter.
*/
capture(): Capture
/**
* Raw quads for the finished frame, `quadStride()` bytes each,
* laid out as kui-ffi's KuiQuad (see include/kui.h) and decoded
* by `decodeQuads`. Copied into the Buffer. A window answers
* with what its last pump drew, so a smoke test can read the
* frame the shipping driver painted and not only a headless
* one's. Drive that window with `access(key,
* action)` — `click`, `type` and `key` are refused there,
* because the OS is what drives a real window.
*/
quads(): Buffer
/**
* The clips this frame's quads name through their `clip`
* index, `clipStride()` bytes each, laid out as kui-ffi's
* KuiClip (see include/kui.h) and decoded by `decodeClips`.
* Entry zero clips nothing, so a quad always has one; the
* list is empty only on a frame that drew nothing.
*/
clips(): Buffer
/**
* This frame's fragment draws, in the order their quads index
* them by `uv[0]`: twenty-four doubles each — the handle as
* two 32-bit halves, the sixteen parameters, then where the
* draw's `image` is (0 none, 1 the atlas, 2 a texture of its
* own), the `textureDraws` index when it is 2, and the texel
* rect `x, y, w, h`. The parameters ride a side
* list rather than the quad, so `quads()` alone cannot show
* them and a corpus adapter needs this to compare them.
* Empty on a frame that draws no fragment.
*/
fragmentDraws(): Array
/**
* This frame's texture draws, in the order their quads index
* them by `uv[0]`: nine doubles each — the image handle as two
* 32-bit halves, the pixels' revision, width and height, and
* the texel rect `x, y, w, h` in the image's own texels (the
* whole image, or the crop a `fit="cover"` made). The side
* list a `quads()` texture quad points at.
* Empty on a frame that draws no texture-backed image.
*/
textureDraws(): Array
/**
* Host facts the frame driver pushed in: what the window and the
* display are doing, as of now (see `Env`). This is the same
* surface Lua's `view(env)` reads and C's `kui_env_set*` writes —
* a JSX app needs it to build its own titlebar (inset past the
* macOS traffic lights, pick the maximize glyph), to dim its
* chrome when the window loses focus, or to pace itself against
* the real refresh rate.
*
* Note `env().focused` is the *window*'s keyboard focus, not the
* focused node's key — that is `focused()`, one call up.
*/
env(): Env
/**
* The palette this window paints with: one `0xRRGGBBAA` number
* per role, derived from `env().system` unless this app said
* otherwise (`setAccent` / `setTheme`). A view reads it and
* paints with it — `` — and the stock
* widgets already do, so a JSX app that only uses ``,
* the context menu and `` follows the OS's light and
* dark without reading this at all.
*/
theme(): Theme
/**
* Keep following the OS's light/dark, but paint this accent
* instead of the OS's — an app with a brand colour. A
* `0xRRGGBBAA` number or a `"#hex"` string, as any colour
* prop takes; `null` goes back to the OS's own.
*/
setAccent(accent: number | string | null): void
/**
* Pin the palette: an object of role overrides on top of the
* base named by `appearance` (`"light"`, `"dark"`, or absent
* for the OS's), each value a colour the way a prop takes
* one. Follows nothing afterwards — `setAccent(null)` is how
* an app goes back to following the OS.
*
* `{ appearance: "dark", accent: "#d2691e" }` is a dark app
* with one colour changed; every role the object does not
* name keeps the base's, and the ones derived from the accent
* (its hover, its pressed shade, the label on it, the ring,
* the selection tint) are recomputed unless named too.
*
* `{ light: {…}, dark: {…} }` is one palette for each
* appearance (ADR 0061): each half is overrides on that base,
* and the core picks the half the OS's appearance asks for
* every frame, so a skin follows light and dark with no
* listener. A half left out is the stock base for it.
*/
setTheme(theme: ThemeOverrides | ThemePairOverrides): void
/**
* The sizes the stock widgets are built from — the palette's
* other axis: one number per metric, logical px before the
* scale factor. Read it so a control of your own agrees with
* `` on a radius and a padding: ``.
*/
metrics(): Metrics
/**
* Makes these the frame's metrics: overrides on top of the
* set in effect, or on top of `base: "comfortable"` (the
* stock set) / `"compact"` (a dense tool's), then `scale`
* multiplying every length — a density slider. `null`
* restores the stock set. Density is the app's to choose;
* nothing in the OS is followed.
*/
setMetrics(metrics: MetricsOverrides | null): void
/**
* Declare the app's named colours, lengths and families:
* `{ colors: { peach: '#ffcc99', ink: { light, dark } },
* lengths: { sideW: 132 }, families: { code: ['JetBrains
* Mono', 'mono'] } }`. Replaces the table whole, so an app
* whose lengths change with a viewport tier declares again
* on `resize`. A name a theme, metrics or number role owns,
* or a family token named for a stock family, is dropped
* with a `reserved-token` warning. A colour may be a
* recipe over an earlier one: `{ from: 'peach',
* ops: [['lift', 0.3]] }`, dropped with `unknown-token` when
* its source is not there. Reference one in a prop
* as `'$peach'` — `defineTokens` types the names. The raw
* addon door; `index.js` wraps it to keep the encoder's map
* in step, so call `setTokens` and not this.
*/
setTokensRaw(tokens: { colors: [string, unknown][], lengths: [string, number][], families?: [string, string | string[]][] }): void
/**
* The tokens a view here sees this frame, resolved: colours as
* `0xRRGGBBAA` for the appearance in effect, lengths in px,
* families as the name each list picked, under `colors`,
* `lengths` and `families`. Roles are not listed — read them
* off `theme()` and `metrics()`.
*/
tokens(): ResolvedTokens
/**
* `frame` / `setView` report the `$name` references the
* encoder could not resolve — nothing declared, or the other
* kind — through here, as `unknown-token`, once per name.
*/
warnUnknownTokens(names: [string, string][]): void
/**
* `measureText`'s door (index.js adds `measureText` itself):
* one `` element as `encoder.encodeText` writes it, and
* the answer is what that text lays out to — `{width, height,
* lines}` in logical px at the context's scale, capped to
* `maxWidth` when given. The metrics do not scale linearly:
* `measured × zoom` is not `measure(size × zoom)`, because
* shaping rounds per size, so anything that zooms measures at
* the size it draws.
*/
measureTextBinary(stream: Float64Array, strings: Uint8Array, maxWidth?: number | undefined | null): TextMetrics
/**
* `caretInText`'s door (index.js adds `caretInText` itself):
* one `` element as `measureTextBinary` takes it, and
* the answer is where byte `byte` of that text lands once laid
* out at `maxWidth` (unwrapped without one) — the rect
* `caretRect` gives when a node draws the text at that width,
* from the text's own top-left rather than the viewport's.
*/
caretInTextBinary(stream: Float64Array, strings: Uint8Array, maxWidth: number | undefined | null, byte: number): Rect | null
/**
* Drains the warnings the core raised since the last call
* (see `Warning`), each distinct (code, node) pair once.
* `createApp` collects them on `app.warnings` for you, and
* `runWindowed` prints them, unless either was told not to.
*/
warnings(): Warning[]
/**
* Turns the per-frame diagnostic checks behind `warnings` on or
* off. A bare `Ctx` has them on; `createApp` / `runWindowed`
* turn them off under `NODE_ENV=production`.
*/
setDiagnostics(on: boolean): void
/**
* Whether a wheel's notch glides on a scroll container (ADR
* 0050): on by default; off, a notch jumps on the next frame.
* The system's reduced motion jumps either way. `runWindowed`
* takes it for the whole app as `smoothWheel`.
*/
setSmoothWheel(on: boolean): void
/** That switch, read back. */
smoothWheel(): boolean
/** Enables acceleration for rapid wheel notches on scroll containers. */
setWheelAcceleration(on: boolean): void
/** Whether wheel acceleration is enabled. Off by default. */
wheelAcceleration(): boolean
/**
* How a wheel's notch scrolls: a preset's name, slow to
* fast `'gentle'`, `'relaxed'`, `'standard'` (the default), `'brisk'` (an
* alias of standard), `'swift'`; or `{ linePx, response, kick }`,
* any left out kept as they are — the base travel per line in
* logical px (48), the glide's response in seconds (0.27)
* and its kick, 0 to 1 (0.6). Clamped into what the glide
* can use.
* `runWindowed` takes it for the whole app as `wheelFeel`.
*/
setWheelFeel(feel: WheelPreset | Partial): void
/** That feel, read back as clamped. */
wheelFeel(): WheelFeel
/**
* How a held drag scrolls a container at its edge — kui's own
* caret drag and drag-select, and `edgeScroll`: a preset's
* name, slow to fast `'gentle'`, `'standard'` (the default),
* `'brisk'`; or `{ zonePx, speedPxS, curve, rampSecs,
* rampMax, capPxS, pullBackPx }`, any left out kept as they
* are — the edge zone's depth (60 px), the speed at its edge
* (500 px/s) along a curve (its exponent, 2), the ramp while
* held (to 6 times over 1.5 s), the cap (3000 px/s) and how
* far a pull back restarts the ramp (8 px). Clamped.
* `runWindowed` takes it for the whole app as
* `edgeScrollFeel`.
*/
setEdgeScrollFeel(feel: EdgeScrollPreset | Partial): void
/** That feel, read back as clamped. */
edgeScrollFeel(): EdgeScrollFeel
/**
* Draws a faded subtree as one picture, faded once (ADR
* 0056): a node whose own `opacity` is under 1 has its
* subtree's quads between a group's begin and end markers
* (kinds 10 and 11), unfaded by it, the end carrying the
* fade, so a label on its own fill no longer washes into it.
* A window has it on; a headless `Ctx` has it off, every
* quad of a faded subtree carrying its fade, and turns it on
* for `capture()` to show what a window shows.
*/
setOpacityGroups(on: boolean): void
/**
* Every warning the core has raised so far, drained or not,
* oldest first — the log `warnings()` leaves behind, for a
* reader that is not the driver (a devtools stream).
*/
warningsRaised(): Warning[]
/**
* Turns the per-frame node snapshot behind `nodes()` on or off
* (off unless a devtool asked: the copy is O(nodes) a frame).
*/
setInspect(on: boolean): void
/**
* Turns the core's devtools panel on or off: the event stream, the runtime's facts and
* the tree, drawn by the core beside the app's own tree in the
* main window — or where `setDevtoolsDock` says — with its
* controls and its `Ctrl+Shift+` chords handled inside
* the core, so nothing of it reaches `update`. `KUI_DEVTOOLS=1`
* in the environment is the same call made by nobody, for a
* `KuiWindow`; a headless `Ctx` never reads it.
*/
setDevtools(on: boolean): void
/** Whether the devtools panel is on. */
devtools(): boolean
/**
* Where the devtools panel sits: `"left"`, `"right"`,
* `"bottom"`, `"window"` (one of its own, named
* `kui-devtools`) or `"off"` (hidden, the chords still live);
* `"side"` is the right. Throws on any other word.
*/
setDevtoolsDock(dock: DevtoolsDock): void
/** Where the devtools panel sits (see `setDevtoolsDock`). */
devtoolsDock(): DevtoolsDock
/**
* Where the last frame laid the app out in its window, in
* logical px: `{x, y, w, h}`, the viewport `env().viewport`
* sizes with its origin — `x` is the pane's width under a
* left dock, and the rect is the whole window with the panel
* off, in its own window, or anywhere but the main window.
* `quads()` are in physical px, so multiply by the scale
* (`env().viewport.scale`) to filter them: a quad inside is
* the app's, one outside is the dock's — but for the root's
* `bg`, which is the window's too and under a dock also fills
* the whole window beneath the pane. All zeros before the
* first frame, like `env().viewport`; a window's `size()` is
* the reading from before it.
*/
hostArea(): Rect
/**
* Seeds the panel's theme override, what its `T` and `A`
* chords cycle from: `base` is `"light"`, `"dark"` or `null`
* for the app's own; `accent` an `#rrggbb` string or `null`.
*/
setDevtoolsTheme(base: 'light' | 'dark' | null, accent: string | null): void
/**
* Respells the chord that moves the keyboard into the panel
* and back out — and brings a hidden panel back — from its
* default `"ctrl+shift+i"`: `"f12"`, `"mod+shift+d"` (`mod`
* is Command on macOS, Control elsewhere), `"⌥⌘I"`, any
* spelling a menu item's `accel` takes. The panel's other
* chords stay `Ctrl+Shift+`. With another chord set,
* `Ctrl+Shift+I` reaches the app like any other press. Throws
* on a spelling kui cannot name.
*/
setDevtoolsKey(key: string): void
/**
* The chord `setDevtoolsKey` set, or the default, in its
* portable spelling: `"ctrl+shift+i"`, `"f12"`,
* `"super+alt+d"`.
*/
devtoolsKey(): string
/**
* The declared devtools tab on show, by name, or `null` for
* one of the panel's own, the panel off or popped out.
* What `frame` / `setView` read once before encoding,
* so a ``'s function child is called only for
* that tab.
*/
devtoolsShownTab(): string | null
/**
* The node the panel's tree tab has selected, as a hex key,
* or `null` — what an inspector in a
* declared tab reads to say which node it is about.
*/
devtoolsSelected(): string | null
/** The tree row under the pointer, as a hex key, or `null`. */
devtoolsHovered(): string | null
/** The node the picker is over while picking, or `null`. */
devtoolsPicked(): string | null
/**
* Raises the panel's picker from outside it — an inspector in
* a `` asking "which node?" — or puts it away.
* Picking happens over the app in
* the main window: `devtoolsPicked()` is the node under the
* pointer while it is up, and the press lands it in
* `devtoolsSelected()`. Raised while a declared tab is on
* show, the pick leaves that tab up; raised otherwise — a
* tab named but not declared yet included — it is the
* `Ctrl+Shift+P` pick and shows the tree tab. A hidden
* panel comes back docked.
*/
setDevtoolsPick(on: boolean): void
/** Whether the panel's picker is up. */
devtoolsPicking(): boolean
/**
* Shows the panel's tab named `name` from the app's side —
* what the strip's click and `Ctrl+Shift+N` do, for a command
* that jumps to the app's own tab. `name` is one
* of the panel's own (`facts`, `events`, `tree`, `perf`, in any case)
* or a ``'s, exactly as declared. A declared
* name the panel does not list
* yet is kept and shows once a frame declares it; the return
* says whether the panel lists it now. A hidden panel comes
* back docked; `setDevtools(true)` is still the app's to
* call. Call it once, not every frame: it would pin the strip
* against the user's own clicks.
*/
setDevtoolsTab(name: DevtoolsTab | (string & {})): boolean
/**
* The tab the panel is on, by name: one of its own or a
* ``'s — the selection itself, panel on or off,
* unlike `devtoolsShownTab()`, which is the encoder's reading
* of a declared tab on show.
*/
devtoolsCurrentTab(): DevtoolsTab | (string & {})
/**
* Selects a node in the panel's tree tab from outside it and
* reveals it there, as the picker does; `null` clears. `key`
* is a hex key an event carried or `keyOf` answered.
*/
setDevtoolsSelected(key?: string | undefined | null): void
/**
* The key legend the panel's facts tab shows: `[keys, what]`
* pairs.
*/
setDevtoolsLegend(legend: [string, string][]): void
/**
* The last finished frame's nodes in tree order, each with what
* it is, the label it was opened under, where layout put it
* (in the app's viewport, like `layoutOf`), and
* the declarations that explain the rest — what a tree view
* and a node inspector are built from. Empty until
* `setInspect(true)` and a frame after it.
*/
nodes(): NodeInfo[]
/**
* The prop names the encoder threw away while lowering a tree,
* as `[element, name]` pairs, raised as `unknown-prop` warnings
* (see `Warning`). A name outside the schema never reaches the
* binary stream, so the encoder is the only side that sees it;
* `frame` / `setView` report what they dropped through here.
* Behind the same `setDiagnostics` gate, and once per name. A
* pair under `protocol().menuItem.name` is a key a ``
* option object carried that no menu row reads.
*/
warnUnknownProps(props: [string, string][]): void
/**
* What assistive technology sees of the last frame (see
* `AccessTree`). A window hands it to the platform by itself
* (AccessKit); this is for tests and tooling.
*/
accessTree(): AccessTree
/**
* A request from assistive technology on a node: an `AccessAction`
* name the node advertises, with `value` the new text for
* `setValue`. It arrives as the event a user doing the same
* would cause (ADR 0047): a click, a slider's or an editor's
* `change`, an `onKey` sink's `text` or `select`. `key` is either spelling of the node — the hex key
* an event carried (16 digits), or the label its `key` prop
* declared, resolved through the last frame (see `focus`).
* Resolved like its pointer/keyboard equivalent, so the resulting
* events come out of `pollEvents`. A real screen reader's
* requests arrive through a window on their own.
*/
access(key: string, action: AccessAction, value?: string | AccessArg): void
/**
* Hover state as of the last frame. `key` is either spelling,
* as for `focus`: the label a `key` prop declared, or the hex
* key an event carried. For plain hover styling prefer the
* `hoverBg` / `pressedBg` props — the core resolves those without
* a round trip.
*/
isHovered(key: string): boolean
/**
* Press state as of the last frame; `key` is either spelling,
* as for `isHovered`.
*/
isPressed(key: string): boolean
/**
* Whether any member of the hover group `group` (the
* `hoverGroup` name) is hovered, as of the last frame.
*/
isGroupHovered(group: string): boolean
/**
* Whether any member of the hover group `group` holds a
* press, as of the last frame (backlog C92).
*/
isGroupPressed(group: string): boolean
/**
* Whether files dragged in from the OS are over `key` — for
* drop-dependent layout; the colour swap is the
* `dropBg` prop. `key` is either spelling, as for `isHovered`.
*/
isDropTarget(key: string): boolean
/**
* The `onDrop` zone the dragged files are over, as the hex key
* an event carries, or null — what a driver answers the OS
* with after each `dragFiles`, and what a test reads to say a
* zone was found.
*/
dropTarget(): string | null
/**
* The pointer shape for where the pointer is now, in the `cursor`
* prop's own vocabulary: whatever the topmost node under it
* declared with `cursor`, and when it declared nothing,
* `'text'` over an editor or a `selectable` scope and
* `'default'` over everything else — an `onClick`, `focusable`
* or `onDrag` node included, as a native button is, so a hand
* or a grab is the view's to declare (the stock `button`
* declares `'pointer'` itself). A captured drag keeps the
* dragged node's shape wherever the pointer goes; no pointer at
* all is `'default'`. A window applies it to the real cursor by
* itself and only touches it when the answer changes; this is
* for tests and drivers.
*/
cursorShape(): CursorShape
/**
* Whether a node holds keyboard focus — any node: an editor, an
* `onKey` sink, a button Tab landed on (see `focused`). `key` is
* a hex key or a declared label, as for `focus`.
*/
isFocused(key: string): boolean
/**
* The node holding keyboard focus (hex key), or null. Tab /
* Shift-Tab walk every control in tree order, Enter and Space
* press the focused one, and the arrows nudge a focused
* slider — `press("tab")`, `press(" ")`, `press("right")`,
* which is what a keyboard sends. (`key("tab")` is the half
* of that press the core acts on, for a test that means to
* drive one channel; `keyDown` is the other half, the one an
* `onKey` sink hears.)
*/
focused(): string | null
/**
* Whether focus got where it is by keyboard or assistive
* technology rather than a click — when it shows (the ring, or
* `focusBg`).
*/
focusVisible(): boolean
/**
* Whether the window's "Tab moves focus" toggle is on
* (backlog C99): a multiline editor whose Tab would type
* walks the focus ring instead. Ctrl+M flips it in such an
* editor (Ctrl+Shift+M on macOS); what a status label reads.
*/
tabMovesFocus(): boolean
/**
* Sets the appearance the host's `dark` / `light`
* conditions read in place of the palette's (backlog C113):
* `'light'`, `'dark'`, or null for the palette's again.
*/
setRulesAppearance(appearance?: string | undefined | null): void
/**
* The caret's blink phase — `true` draws it. A
* custom editor reads it in `view` and skips its caret node
* on the off phase, keeping the `caret` row on its `line`
* either way; the window's clock sets it while a focused
* `` or such a line has a caret, and parks it hidden
* while the window has no keyboard. Always `true` headless.
*/
caretVisible(): boolean
/**
* The frame clock in seconds (backlog F134): the one the
* tweens and cycles read, `setTime` or the loop's own, 0
* before either. Read a deadline off it rather than off
* `Date.now()`, so `advance` moves both.
*/
now(): number
/**
* Asks for a frame at `at` on the frame clock (backlog F135),
* in seconds: a toast's expiry, a sequence's next beat. Nothing
* is owed until then, so `animating()` stays false; a window
* sleeps to it and draws, and the earliest time asked for wins.
* A headless loop's `advance` past it draws the frame it ends
* on, as it does for a `tick`.
*/
requestFrameAt(at: number): void
/**
* The exit the node `key` leaves by if it leaves in the frame
* that finishes next (backlog F136), over the `exit` it
* declared: `{dx: 400, opacity: 0}`, the same fields as
* `exit`. A card a button throws aside is removed in the same
* handler, with no frame drawn first to aim it. It aims a node
* that declares an `exit`, with that node's transition, and is
* forgotten when that frame finishes.
*/
exitWith(key: string, exit: EnterProp): void
/**
* The frame-clock time the next asked-for frame is due at, in
* seconds; `null` when none was asked for.
*/
nextFrameAt(): number | null
/**
* Whether there is a caret to blink: a focused ``'s, or
* the `caret` a `line` under the focused sink declares — unless
* the line declares it `caretSolid`, which
* anchors and reads but arms no clock. What the window's
* clock is armed on; headless, what a test reads to see that
* an idle view asks for no frame.
*/
hasCaret(): boolean
/**
* The driver's half of the blink: sets the phase. A window
* runs its own clock; headless, a test drives it to see the
* off phase drawn.
*/
setCaretVisible(visible: boolean): void
/**
* Moves keyboard focus to a node now (an editor, an `onKey` sink,
* a control, a `focusable` box); `keyFocus` on a box is the
* declarative, edge-triggered form.
*
* `key` is either spelling of the node: the 16-digit hex key an
* event carried, or the label its `key` prop declared —
* `focus('note')` — resolved through the last frame, so a node
* the user has never touched can be named. Labels are unique
* among siblings, not across the tree: when two nodes declare
* the same one, the first in tree order wins and an
* `ambiguous-key` warning says so. A label no node declared
* throws.
*/
focus(key: string): void
/**
* The hex key of the node a key label names — the label a `key`
* prop declared, not the accessible name a reader hears
* (`keyNamed`), resolved through the frame being built so
* far and then the last finished one — or null when no node
* declared it. The door for holding a key across frames;
* every call that takes a key takes the label too, so this
* is for caching one, or for checking that a name reached
* the view. Two nodes on one label under different parents
* resolve to the first in tree order and raise
* `ambiguous-key` — among the host's own first, and a
* plugin's component is answered from its own nodes only.
*/
keyOf(label: string): string | null
/**
* The reverse of `keyOf`: the label the node with this hex key
* (as an event carries it) was opened under, in the frame
* being built so far and then the last finished one — or null
* for an auto-keyed node, a key no frame declared, or a string
* that is not a key. What a key from `focused()`, an event or
* a log turns back into; the label is the local one, so two
* rows of a list under different parents answer the same.
*/
labelOf(key: string): string | null
/**
* The hex key of the first node in the last finished frame
* whose accessible name is `name` (backlog F137) — its
* `label` prop, else its own text, else a control's derived
* name — so a test clicks "the button named Like" as a reader
* would: `ctx.access(ctx.keyNamed('Like')!, 'click')`, or
* `app.access(…)` on a headless app, which settles what
* follows through `update`. (`click` is the pointer's, at
* coordinates, on an app.) Not `keyOf`'s key label, which a
* reader never hears. Null when no node has the name; two
* raise `ambiguous-name`.
*/
keyNamed(name: string): string | null
blur(): void
/**
* What Tab does, as a call — for an `onKey` sink that binds Tab
* itself and wants to hand the keyboard on: the next focusable
* node in tree order, wrapping.
*/
focusNext(): void
/** What Shift-Tab does. */
focusPrev(): void
/**
* Enters a focus region — a box declared `focusRegion`, named by
* the label its `key` prop declares or by the hex key an event
* carried — or the main ring for `null`. Focus lands on what that
* ring last held if the node is still there, else its
* `initialFocus`, else its first stop, and shows.
*
* Resolved when the next frame finishes, like `focusNext`, so
* the `update` that toggles a dock on may enter it in the same
* turn — which is why a label is taken as a name to hold rather
* than resolved now: the node need not exist yet. A frame that
* then declares no `focusRegion` under the name raises
* `focus-region-without-node` and moves nothing.
*/
focusRegion(key?: string | undefined | null): void
/**
* Focuses item `index` of a list, table or other composite —
* named by the label its `key` prop declares or the hex key an
* event carried — when the next frame finishes (backlog C125):
* the item opened with that data `index`, a row a windowed list
* did not build being scrolled to and landed on the frame that
* builds it (an index past `rowCount` is the last row), else,
* where items carry no index, the item at that place. A focused
* item that vanishes hands focus to the item now at its place on
* its own; this names one.
*/
focusItem(key: string, index: number): void
/**
* The focus region in effect — the hex key of the `focusRegion`
* node whose ring Tab walks — or `null` for the main ring. What
* a chord that toggles between a dock and the app reads to know
* which way it is going.
*/
region(): string | null
/**
* Scrolls whatever contains a node so it shows — "scroll to the
* selected row", which needs the container geometry only the core
* has. The request resolves against the *next* frame's layout (one
* is requested), so a row the view is about to declare for the
* first time reveals fine. If that frame does not declare the key,
* or nothing above it scrolls, it is a no-op and is not kept for a
* later frame; two reveals before one frame are contradictory, so
* the last wins. `key` is a hex key or a declared label, as for
* `focus`. A label the last frame did not declare is resolved
* when the coming frame finishes, so a row that frame declares
* for the first time is reachable by name too; one it does not
* declare either is a `label-without-node` warning.
*/
reveal(key: string): void
/**
* A scroll container's retained offset `{x, y}` as the last layout
* clamped it (positive = content moved up / left) — the number to
* keep in a model and hand back to `setScroll`. Zero for a node
* that never scrolled.
*/
scrollOffset(key: string): ScrollOffset
/**
* Everything the last layout resolved for the scroll container
* `key`: its box `{x, y, w, h}`, its content size `{contentW,
* contentH}` and the clamped `offset` — `null` for a key no layout
* has resolved as a container.
*
* This is what makes a long list affordable. The core builds every
* child a view declares, so ten thousand rows cost ten thousand
* rows; knowing `h` and `offset.y`, a view renders the rows that
* fit plus two spacers holding the space of the rest. Read while
* building, it describes the previous frame, so a resize slices one
* frame late — render a row or two extra at each end.
*/
scrollGeometry(key: string): ScrollGeometry | null
/**
* The rect the last frame laid `key` out at, `{x, y, w, h}`
* in logical viewport px, for a node that declared `onLayout`
* — the `layout` event's numbers, read back during the next
* build with no event and no model field; `null` for any
* other key. Read while building, it
* describes the previous frame, like `scrollGeometry`.
*/
layoutOf(key: string): { x: number, y: number, w: number, h: number } | null
/**
* Where the pointer is over `key`, `{x, y, w, h}`: its place
* from the node's top-left and the node's size, as of the
* last frame (backlog C119) — over it while `0 <= x < w` and
* `0 <= y < h`. `null` while the pointer is outside the
* window, and for a node the last frame gave neither a hit
* region (`hoverable`, `onHover`, anything that takes the
* pointer) nor an `onLayout` rect. A pointer move is a frame,
* so a view that follows the pointer reads it each frame.
*/
pointerIn(key: string): { x: number, y: number, w: number, h: number } | null
/**
* Where a point lands in the text a keyed node drew: a byte
* offset into its text and the visual row within that node —
* counted across every run the key covers, so a `line` row of
* inline runs is one row and a wrapped run as many as it
* wrapped to; not the ordinal `line` node a pointer event's
* `line` names — or null for a key that drew no
* text. A `role="none"` subtree under the key (a gutter) is
* not its text, as the access tree reads it. `x`/`y` are the logical viewport px a
* `click` or `drag` event carries, so a custom editor turns the
* event into a caret position with one call — no prefix
* measuring, no cell-width arithmetic. A node holding several
* text runs (a `line` row of token runs) answers across them
* in order, the way the access tree reads the line. Answered
* from the frame that finished: the layout the pointer was
* over.
*/
textHit(key: string, x: number, y: number): TextHit | null
/**
* Opens a context menu at `(x, y)` over the node `key`, with
* `items` as plain objects: `{label, role, enabled, id,
* accel}`, all but `label` optional. `role` is one of
* `custom` (the default), `separator`, `cut`, `copy`,
* `paste`, `selectAll` or `lookUp`; the standard ones take
* their own wording when `label` is empty, and the core
* performs the ones it can.
*
* Choosing a row posts `key`'s `onMenu` message with `menu:
* {role, item}` in it, or nothing where `key` declares none,
* and closes the menu; a press outside it or Escape closes it
* with nothing posted. What an app answering its own
* `onContextMenu` calls — and what the core calls itself for
* a right-click nobody claimed, so the two menus are one
* implementation.
*
* `options.maxWidth` / `options.maxHeight` hold the menu and
* its submenus to a size, logical px: a row wider is
* ellipsized, a menu taller scrolls (backlog F210). One left
* out, or not above 0, is the room the menu is drawn in.
* `options.inWindow` keeps the menu drawn in the window where
* the runner would show one that does not fit in a popup
* window of its own.
*/
openMenu(key: string, x: number, y: number, items: MenuItemInput[], options?: { maxWidth?: number; maxHeight?: number; inWindow?: boolean } | null): boolean
/**
* Drains what choosing a menu row left for the host: the
* clipboard, which is the host's in this library. Each entry
* is `{kind}` — `"setClipboard"` with `text` (and `html`
* where there is formatting to carry), `"paste"` asking for
* what is on the clipboard (deliver it back with `commit()`,
* which a focused editor takes as typing and a focused
* `onKey` sink hears as a `text` event),
* or `"lookUp"` with the `text` to show a definition panel
* for at `x`, `y`.
*
* A windowed app never needs this — the driver drains it —
* but a headless one does: nothing else empties the queue,
* and a Copy nobody drains is a copy that never happened.
* Asks for the platform's Open, Save or folder dialog:
* `{mode, multiple, title, filters: [{name, extensions}],
* directory, fileName, tag}`, every field optional. The answer
* is a `files` event, the dialog's `tag` with `files: {paths}`
* in it — `paths` empty when the user cancelled. A window's runner shows the dialog; a
* headless context queues it for `takeFileRequests`. False when
* one is already out: one dialog at a time.
*/
requestFiles(dialog?: FileDialogOptions): boolean
/** Whether a file dialog asked for is still unanswered. */
awaitingFiles(): boolean
/**
* The file dialog asked for and not yet taken — at most one —
* as `requestFiles` took it, for a host that shows it itself.
* A window never needs this: its runner drains and shows it.
* Answer with `answerFiles`.
*/
takeFileRequests(): FileDialogOptions[]
takeMenuActions(): MenuAction[]
/**
* Puts `text` on the system clipboard — the action a menu's
* Copy queues, with a door on it for an `onKey` sink that
* hears the raw `Ctrl-c` and had nowhere to bind it.
* `html` is a second flavour beside the text for the
* host to offer, never in place of it. A window applies it
* at its next drain (after every input and every frame); a
* headless `Ctx` hands it out through `takeMenuActions()`.
*/
setClipboard(text: string, html?: string | undefined | null): void
/**
* Puts a secret on the system clipboard the way a password
* manager does: a window writes it marked
* concealed and transient — `org.nspasteboard.ConcealedType`
* and `TransientType` on macOS, the exclusion formats on
* Windows — so no clipboard manager shows or keeps it. A
* headless `Ctx` hands it out through `takeMenuActions()` as
* `{kind:"setClipboardSecret", text}`.
*/
setClipboardSecret(text: string): void
/**
* Puts files on the system clipboard, as a file manager's
* Copy does — "Copy file" on an attachment: a window writes
* them as the platform's file list (`CF_HDROP` on Windows,
* file URLs on macOS, `text/uri-list` on Linux), so they paste
* into a file manager or a mail as the files. The paths as the
* app names them; the window makes them absolute. False, and
* nothing queued, for none. A headless `Ctx` hands it out
* through `takeMenuActions()` as
* `{kind:"setClipboardFiles", paths}` (backlog F247).
*/
setClipboardFiles(paths: Array): boolean
/**
* Puts a picture on the system clipboard — `width` by `height`
* straight RGBA, what `capture()` and `decodeImage` hand out,
* copied — as the platform's image type: "Copy image". A
* window writes it at its next drain; a headless `Ctx` hands it
* out through `takeMenuActions()` as `{kind:"setClipboardImage",
* width, height}`. False, and nothing queued, when `rgba` is
* not `width * height * 4` bytes or the size is zero.
*/
setClipboardImage(width: number, height: number, rgba: Uint8Array): boolean
/**
* Asks for what is on the clipboard — the action a menu's
* Paste queues. A window reads the clipboard and hands the
* text back as a paste: a focused `` takes it as
* typing, and a focused `onKey` sink hears it as its message
* with `text: {text}` in it — with `concealed: true` /
* `transient: true` there where the pasteboard marked it so
* — so an app that owns its text inserts a
* paste the way it inserts a committed IME string and never
* reads the clipboard itself. Headless, the request comes out
* of `takeMenuActions()` as `{kind:"paste"}` and the test
* answers it with `paste(text, marks)` or `commit(...)`.
*/
requestPaste(): void
/**
* Whether a paste asked for is still unanswered: one ask at a
* time — a second `requestPaste` while one is out is dropped,
* and the `commit` that answers it (an empty one for an empty
* clipboard) lets the next through.
*/
awaitingPaste(): boolean
/**
* The menu this window has open, or null:
* `{target, x, y, items}`. What a host rendering menus itself
* reads after `setNativeMenus(true)` — the core then keeps
* the menu as state and draws none of it — and answers with
* `activateMenuItem` or `closeMenu`. A row reads exactly as a
* `menuBar()` row does (`menu_item_json`).
*/
menu(): OpenMenu | null
/**
* Tells the core this host shows menus itself. It then keeps
* the open menu as state and draws none of it: read it with
* `menu()`, show it, and report back with `activateMenuItem`
* or `closeMenu`. Off by default, which is the menu this
* library draws.
*/
setNativeMenus(on: boolean): void
/**
* The application menu the frame declared, or null:
* `{revision, menus: [{label, enabled, items}]}`. What a
* host with a menu bar of its own reads after
* `setNativeMenuBar(true)`; `revision` changes only when the
* declaration does, so a host rebuilds nothing until it moves.
*/
menuBar(): MenuBarState | null
/**
* Tells the core the platform owns the menu bar, so
* ` ` draws nothing and this host is the one handing
* the declaration over (`menuBar()`) and reporting what was
* chosen (`activateMenuBarItem`). Off by default, which is
* the bar this library draws.
*/
setNativeMenuBar(on: boolean): void
/**
* Reports that the platform's menu bar chose row `item` of
* menu `menu` — the same path a press on the drawn bar's row
* takes. False when the app hears nothing: a row that is not
* there, or a `` that declares no `onMenu` (ADR 0048).
*/
activateMenuBarItem(menu: number, item: number): boolean
/**
* `activateMenuBarItem` for a row inside a submenu of menu
* `menu`, by its path through the rows' `items`. False for a
* row that is not there or that opens a submenu.
*/
activateMenuBarPath(menu: number, path: Array): boolean
/**
* Tells the core this host can show the platform's definition
* panel. The standard Look Up row is then offered where it
* means something, and a force click over text asks for one.
*/
setLookupAvailable(on: boolean): void
/**
* Reports that the host's own menu chose row `index` — the
* same path a press on the drawn menu's row takes. An index
* past the end closes the menu and posts nothing. False when
* nothing was taken: no menu was open, or the row cannot be
* chosen — disabled, or a separator — in which case the menu
* stays open and nothing is posted.
*/
activateMenuItem(index: number): boolean
/**
* `activateMenuItem` for a row inside a submenu, by its path
* through the rows' `items`: `[2, 0]` is the first row of the
* third row's submenu. False where `activateMenuItem` is, and
* for a row that opens a submenu, which is never chosen.
*/
activateMenuPath(path: Array): boolean
/** Closes whatever menu is open; true when there was one. */
closeMenu(): boolean
/**
* Asks for the selection as text: `{ text, asked }`.
*
* `text` is the selection when the core has all of it. When
* the selection reaches rows a virtual list never built,
* `asked` is true instead and a `selectionrange` event —
* the scope's `onSelectionRange` message with `selectionrange:
* {from: {index, byte}, to: {index, byte}}` in it — is posted
* on the scope — the rows behind that gap are the app's, so the
* app answers with `answerSelectionRange`, and the answer is
* what reaches the clipboard.
*/
requestCopy(): { text: string | null, asked: boolean }
/**
* Answers a `typeahead` event (ADR 0070) with the data index of
* the row the search names, in the composite `key` (either
* spelling) that asked: the core goes there, scrolling to a
* row the frame did not build. False when that composite asked
* nothing, or focus has left it.
*/
answerTypeahead(key: string, index: number): boolean
/**
* Answers a `selectionrange` ask with the text for the range
* it named, whole. False when nothing asked — a late answer
* cannot overwrite what has been copied since.
*/
answerSelectionRange(text: string): boolean
/**
* The window's selected text: what a `selectable` scope has
* selected, or the focused ``'s selection, whichever
* the window holds — starting either clears the other, so
* there is never a choice to make. Null with no selection,
* `""` when a selection exists but covers nothing (a press
* that placed both ends together).
*/
selectionText(): string | null
/**
* The text selection's two ends as the drag made them:
* `{anchor: {index, byte}, focus: {index, byte}}`, `index` the
* data index of the virtualised row the end is in (null
* outside every virtualised row — the `index` a
* `selectionrange` ask would name) and `byte` the offset in
* that row's own text. Directed, so a Shift-click that kept
* the anchor reads as one. Null with no text
* selection; a grid's is `cellSelection()`.
*/
selectionEnds(): SelectionEnds | null
/**
* A `cells` grid's selection, the window's when it lives in
* one: the grid's key, `anchor` and `focus` as the drag made
* them — each an absolute `line` (`originLine` plus the row,
* so a scroll does not move it) and a `col` — and `block`
* for a rectangular one. Null when the
* window's selection is not a grid's; a text selection's ends
* are `selectionEnds()`.
*/
cellSelection(): CellSelection | null
/**
* The selection as HTML, carrying the formatting the text
* declared — bold, italic, a span's own colour — and *not*
* the node's colour, which is the app's theme rather than
* the text's.
* Null with no text selection. Meant as a second clipboard
* flavour beside the plain text, never instead of it.
*/
selectionHtml(): string | null
/**
* Selects every run inside the selection scope a keyed node
* declared (`selectable`), first byte to last — Select All,
* scoped. False when that node drew no text, or is not a
* scope. Text the frame built but never drew is included:
* the selection is over the scope's text, not over what fits
* on screen.
*/
selectAllIn(key: string): boolean
/**
* Drops the window's selection, whichever it is. True when
* there was one to drop.
*/
clearSelection(): boolean
/**
* The caret rect for a byte offset in the text a keyed node
* drew: logical viewport px, zero wide, one line tall — where
* a caret, a selection edge or an IME candidate window goes.
* A byte past the text is the end; null for a key that drew
* no text.
*/
caretRect(key: string, byte: number): Rect | null
/**
* Where the OS candidate window goes while a composition is
* under way: the focused ``'s caret, or a custom editor's
* `line` carrying `caret`; null when nothing with a caret is
* focused. The windowed driver applies it itself; headless,
* it is what a test reads to see the anchor moved.
*/
imeRect(): Rect | null
/**
* Sets that offset the way the wheel would; the next frame's
* layout clamps it, so `(0, 0)` jumps to the top and a huge `y` to
* the end without knowing the content height.
*/
setScroll(key: string, x: number, y: number): void
/**
* Moves the scroll container `key` by the content that moved
* under it — `drawn` for where the content is drawn (and an
* eased leg's start), `target` for the retained offset — with
* no ease asked or ended and no frame asked for: a correction to
* the frame the view is building. What `list()` calls when the
* rows it measured came out another height than the estimate
* they stood at, so the row under the pointer stays put.
* A label nothing declared yet is the first
* frame, which has nothing to correct.
*/
shiftScroll(key: string, drawn: number, target: number): void
/**
* Scrolls the container `key` for a drag the app holds with
* the pointer at `x`, `y`, when the pointer is in the edge
* zone inside `rect` — usually the container's own
* `scrollGeometry` — or past it, by `edgeScrollFeel`: at
* once, faster the deeper and the longer it is held, fully
* deep when pinned against the window's edge. Returns what it
* moved, `{ x, y }` positive toward later content, and asks
* for the next frame so a pointer held still goes on
* scrolling; `null` out of the zones, at the end that way, or
* for a key that is no scroll container. Call it once a frame
* while the drag is held — from the view — and place the
* drag's live end under the pointer after; not before the
* drag has left its press's click slop. kui's own caret drag
* and drag-select scroll by the same feel on their own.
*/
edgeScroll(key: string, x: number, y: number, rect: Rect): { x: number, y: number } | null
/**
* The names of every window open right now, `"main"` first,
* then in the order they opened — what a view's root
* `windows` declared and the diff has opened. `view(model,
* window)` is called once per name.
*/
windows(): Array
/**
* The name of the window this core draws: `"main"`, or the
* name the declaration that opened `env().window.id` used.
*/
windowName(): string
/**
* Asks the driver to resize a window to `width`×`height` logical
* px. A request and not a declaration: a window's `size` config
* is read on the frame it opens and never again, because the user
* owns a window's size once it exists, so this is the only way an
* app moves a live one. Queued the way `reveal` is — a `KuiWindow`
* applies it on its next pump, and the window answers with the
* ordinary `resize` event carrying the size it actually became,
* while a headless `Ctx` has no window and simply keeps the
* request. `window` is the id events carry (`env().window.id`),
* 0 for the main window.
*/
setWindowSize(window: number, width: number, height: number): void
/**
* Asks the driver to give a window keyboard focus; queued the same
* way. Advisory: whether the window manager agreed shows up as
* `env().focused` on the frames that follow, not as a reply.
*/
focusWindow(window: number): void
/** Display names, indexed by setWindowFullscreen's display. */
displayNames(): Array
/** Request borderless fullscreen on the current or chosen display. */
setWindowFullscreen(window: number, enabled: boolean, display?: number | undefined | null): void
/** Show or hide a window without losing its context. */
setWindowVisible(window: number, visible: boolean): void
/** Have OS close hide a window while another stays visible. */
setWindowCloseHides(window: number, enabled: boolean): void
editText(key: string): string | null
/**
* Replaces an editor's text, leaving the caret at the end.
*
* It reaches an editor that does not exist yet: the `update`
* that opens a rename field runs a frame ahead of the view
* that declares it, so the text is held for the frame that
* declares this name and seeds the editor there, over
* `initial`. Name it by the label its `key` prop declares —
* the spelling that needs nothing to exist yet, since the
* hex key comes from an event the editor has not fired.
* Either spelling works, as for `focus`; a label the last
* frame declared lands at once, and one it did not is held.
* Held for that one frame — a name nothing declares on it
* drops its text with an `edit-text-without-editor` warning,
* so a name the view spells differently is a line rather
* than a field that opens with the wrong text.
*
* A redraw is asked for only when the text reached an editor.
* A held seed changed nothing on screen, and the frame that
* will — the view that declares the editor — is the app's:
* a redraw here re-lowered the *retained* tree, which declares
* no editor, and that was the frame the hold expired on when
* the call came from a `dispatch` outside the loop
* (`runWindowed` draws that model before it pumps).
*/
setEditText(key: string, text: string): void
}
// -- end generated --
// The calls the JS package adds to those classes: a frame crosses the
// boundary already encoded, and `encoder.js` is the only thing that encodes
// one, so `frame` / `setView` live on the prototypes (see index.js) rather
// than in the addon — and so does a headless `Ctx`'s `size()`, which is the
// size those frames are given and, before the first, the one only
// `createApp` knows. Declaration merging puts them on the classes above.
export interface Ctx {
/** Lowers a JSX tree into one frame: encodes it to the flat binary IR
* stream, then one zero-copy boundary crossing lowers it. */
frame(width: number, height: number, scale: number, tree: KuiNode): void;
/** The viewport the app lays out into: `{width, height, scale}`, the
* `WindowSize` `KuiWindow.size()` answers, so `S` reads the same under
* either driver. A headless context has no window; its size is what
* its caller frames at. After a frame this is `env().viewport`, the
* last `frame()`'s size less a docked devtools pane. Before the first
* it is the `width` / `height` / `scale` `createApp` will frame at
* (800×600 at 1 unless its options say otherwise), with nothing taken
* off for a dock, or 0×0 at scale 1 for a bare `Ctx` nothing has
* framed. A `frame()` at another size raises no `resize`: the caller
* chose it. Backlog F91: `Ctx` had no `size()`, and `env().viewport` is
* 0×0 until the first frame, so a headless `init` had nothing to build
* from. */
size(): WindowSize;
/** Declare the app's named colours, lengths and families (ADR 0027,
* ADR 0049): `{ colors: { peach: '#ffcc99', ink: { light, dark } },
* lengths: { sideW: 132 }, families: { code: ['JetBrains Mono', 'mono'] } }`
* — the object `defineTokens` typed. Replaces the table whole, so an
* app whose lengths change with a viewport tier declares again on
* `resize`. Reference one in any colour or number prop as `T.peach`,
* a family in a text's `family` as `T.code`; a name nothing declared
* raises `unknown-token` and the slot keeps its default. */
setTokens(tokens: TokenDeclaration): void;
/** What `content` measures under `style` as one `` would lay out —
* logical px, and the line count — capped to `maxWidth` when given. The
* text crosses encoded like a frame's, so measuring and drawing shape
* the same runs. A headless context answers at scale 1 before its first
* frame; a window at its own scale once a frame has run. */
measureText(content: KuiNode, style?: TextProps, maxWidth?: number): TextMetrics;
/** Where byte `byte` of `content` under `style` lands once laid out at
* `maxWidth` (unwrapped without one), with no node drawing it: the rect
* `caretRect` gives when a `` with that content is laid out at
* that width, but from the text's own top-left rather than the
* viewport's — zero wide, one line tall. A byte past the text is the
* end. For a caret on the frame its text is new, while `caretRect`
* still answers for the text the node drew last frame (backlog F171). */
caretInText(content: KuiNode, style: TextProps | undefined, maxWidth: number | undefined, byte: number): Rect | null;
/** Runs `fn` inside a span named `name` on the recording's timeline
* (ADR 0058) and returns what it returned: `spanBegin` / `spanEnd`
* around it, timed in the core so it nests with the core's spans, and
* ended however `fn` leaves. While nothing is recorded it only calls
* `fn`. */
span(name: string, fn: () => R): R;
}
export interface KuiWindow {
/** Stores the tree future redraws lower, and schedules one. Encodes it to
* the binary IR stream first. */
/** Shows `tree` in one window: `'main'` when `window` is left out, else
* a name `windows()` lists. */
setView(tree: KuiNode, window?: string): void;
/** See `Ctx.measureText`. */
measureText(content: KuiNode, style?: TextProps, maxWidth?: number): TextMetrics;
/** See `Ctx.caretInText`. */
caretInText(content: KuiNode, style: TextProps | undefined, maxWidth: number | undefined, byte: number): Rect | null;
/** See `Ctx.setTokens`. */
setTokens(tokens: TokenDeclaration): void;
/** See `Ctx.span`. */
span(name: string, fn: () => R): R;
}
/** What both drivers take. `S` is the surface the loop drives, and the
* fourth argument `update` gets: the headless `Ctx` under `createApp`, the
* `KuiWindow` under `runWindowed`. `M` is the model, `A` every message
* `update` can see. */
/** What `update` (or a function `init`) returns to hand the loop effects
* beside the model — built by `withEffects`, never by hand: the brand is
* what tells it from a model that happens to be an array or to have a
* `model` key. `docs/adr/0013-effects-as-data.md`. */
export interface WithEffects {
readonly [EFFECTS]: true;
/** The next model, or `undefined` to keep the current one. */
model: M | undefined;
effects: E[];
}
declare const EFFECTS: unique symbol;
/** `withEffects(model, ...effects)`: the next model — or `undefined` to
* keep the current one, as a bare `undefined` return does — and the
* effects `update` wants performed. An effect is the app's own value (`E`
* on `createApp` / `runWindowed`); kui defines no vocabulary for them,
* and its own effects stay where they are — a sound is `surface.play` or
* an `` node, a window is `windows`. The loop sets the model,
* queues the effects, and after the next frame hands each to the
* `effects` handler; headless, `app.effects()` drains them for a test
* whether or not a handler ran. */
export declare function withEffects(model: M | undefined, ...effects: E[]): WithEffects;
/** The one place an app's effects are performed: `createApp` /
* `runWindowed`'s `effects` option. Runs after the frame that followed
* the `update` which returned the effect, with `dispatch` for whatever
* the effect has to say back (a "done", a "failed", a result) — which
* goes through `update` on the next turn, not inside this one — and the
* surface, which shows the frame the effect's cause produced. A
* promise-shaped effect is the handler's business. */
export type EffectHandler = (effect: E, dispatch: (msg: A | Arrived) => void, surface: S) => void;
export interface LoopConfig {
/** The first model, or a function that builds it. The function form is
* handed the surface — after `setup` has run, so the fonts and images it
* registered are there to measure against — which is how a first model
* gets the real `size()` and its own `measureText` numbers instead of
* constants: the first frame establishes the viewport rather than
* reporting it, so no `resize` follows it to correct them. Under
* `runWindowed` `size()` is the window's viewport; under `createApp` it
* is the `width` / `height` / `scale` every frame will be drawn at (see
* `Ctx.size`). It may return `withEffects` too, for the effect an app
* starts with. */
init: M | ((surface: S) => M | WithEffects);
/** Returns the next model; returning undefined keeps the current one.
* `withEffects(model, ...effects)` returns it with the effects the loop
* should perform after the frame (see `EffectHandler`). `surface` is the
* thing being driven — for `editText`, `focus`, `play`,
* `scrollGeometry` and the rest. `msg` is the message as it arrives:
* an event's payload is always a map (`Arrived`), so a node's
* `onClick: 'save'` is `{ tag: 'save' }` here (ADR 0047, decision 3);
* a message the app hands the loop itself — `dispatch`, a tick, an
* effect handler's — arrives as it was written. */
update: (model: M, msg: A | Arrived , event: UiEvent , surface: S) => M | WithEffects | undefined | void;
/** The tree for one window. Called once per open window per frame with
* its name — `'main'` for the one the app starts in, else a name
* `windows` declared — so a single-window app ignores the argument. The
* surface comes third, for the measurement a tree needs while it is being
* built: `surface.measureText(...)` to size a column to its widest label,
* `size()` to pick the tier that fits — the window's viewport, or
* headless the size this frame is drawn at. Measure, do not mutate — a
* view runs every frame. */
view: (model: M, window: string, surface: S) => KuiNode;
/** Which windows exist besides `main`, by name (see `WindowDecl`). A
* window opens on the first frame that lists it and closes on the first
* that does not; the `WindowMsg` says when. Leave it out for one window. */
windows?: (model: M) => WindowDecl[];
/** A clock: every `every` ms the loop feeds `msg` (or `msg(now, every)`,
* with the clock's own reading — `Date.now()` under a window, the loop's
* own milliseconds headless — and the cadence this tick fired on, so a
* model can tell a 16 ms reading from a 1000 ms one and know how stale
* `now` may be by the next press) to `update`, as written. Ticks are frequent, so unlike UI
* events they re-render only when `update` returns a new model — a
* countdown that returns undefined until the displayed second changes
* costs nothing in between. Read backwards, that is the trap: a tick
* handler that mutates the model in place and returns undefined never
* reaches the screen. Return the model (any non-undefined return renders)
* on the ticks that should draw.
*
* A window fires these off its own timer; headless, `app.advance(ms)`
* fires every tick inside the span, so a ticking app is testable.
*
* `every` may be a function of the model, for an app whose cadence
* depends on its state: `every: (m) => m.endsAt ? 16 : 1000` ticks at
* frame rate while a countdown runs and once a second while it is
* stopped — and since the windowed driver's idle gap is capped by the
* next tick, a stopped app then costs a pump a second rather than
* sixty. It is read after `init` and after every `update` (a tick's
* own included); when the answer changes the next tick moves to the
* last tick plus the new value, keeping the beat, rather than letting
* a tick already queued a second out stand — or, when that is already
* past, to the new value from the change, as a fresh loop counts from
* its start: a cadence that shortens after a long quiet owes one tick
* `every` from now, not a burst. `0` or less means no tick, as the
* number does. */
tick?: { every: number | ((model: M) => number); msg: A | Arrived | ((now: number, every: number) => A | Arrived ) };
/** Runs once as the main window goes for good — its close button,
* `win.close()`, Quit from the menu or the dock — with the model as it
* stands, from inside the pump that saw it and before `runWindowed`
* resolves. On a Mac, ⌘Q ends the process inside that pump: the promise
* never resolves and nothing after `await runWindowed(...)` runs, not
* even `process.on('exit')` — so this is the only thing an app runs on
* ⌘Q, and the place to save a session, a draft, a position (backlog
* RG1). Nothing draws by then, and the window's doors are not for it.
* Headless, `app.teardown()` runs it, so a drive can assert on what
* the app would have kept. */
teardown?: (model: M) => void;
}
/** `runWindowed`'s config: `update` also gets the window. */
export type WindowedConfig = LoopConfig;
/** Opens the main window and runs the Elm loop; resolves with the final
* model when that window closes. `config.windows` opens more. */
export declare function runWindowed(
config: WindowedConfig,
opts?: WindowOptions & {
title?: string;
/** The gap between pumps while the app is being used, in ms
* (default 8) — and the floor the backoff never goes under. */
pumpMs?: number;
/** The longest gap between pumps, in ms (default 32), reached by
* doubling once the window has been quiet for `quietMs`. This is what
* an idle window costs: a pump is ~1.2 ms of CPU whether or not
* anything happened, so the bill is linear in the rate — 8 ms is
* 8-15% of a core, 32 ms is ~3%, 250 ms is under 1%. What it buys back
* is the wait an OS event arriving into a deep idle sits through, up
* to this long: clicked with a posted `CGEvent`, a window answers in
* 34 ms at 8 and ~55 ms at 32. Only the first event after `quietMs` of
* silence pays it. Floored at `pumpMs`. */
idlePumpMs?: number;
/** How long a window must have been quiet before the gap starts
* growing, in ms (default 500). Anything the user does — an event, a
* transition, a `dispatch` from outside the loop, an OS event the app
* never sees — resets both the gap and this. A tick does not, nor the
* frame it draws: the loop's own clock says nothing about whether
* anyone is there, and the next tick is a deadline the pump sleeps to
* regardless, so a stopped app drawing a clock digit once a second
* idles between digits. */
quietMs?: number;
/** The loop's time source, in milliseconds. A window fills it with
* `Date.now`: ticks fire off it and `tick.msg(now)` reads it (the
* frame clock behind `transition` is the runner's own and does not
* follow it). A test hands in `() => Date.now() + ahead` to move a
* real window's clock — its ticks run ahead of the wall by that much,
* which is how a countdown is watched in seconds rather than minutes.
* `createApp`'s `startTime` has no counterpart here: under a clock it
* is dead. */
clock?: () => number;
/** Runs after the window opens, before `init` and the first frame —
* register images, fonts and other resources here. `app` is the loop
* itself, so a test can hold on to it and drive a real window with the
* same helpers `createApp` gives (`settle`, `access`, ...). */
setup?: (win: KuiWindow, app: WindowLoop) => void;
/** Performs the effects `update` returns with `withEffects`, after each
* frame. The same handler a headless `createApp` takes, so an effect
* a test asserted on is the effect the window performs. */
effects?: EffectHandler;
/** The window to drive. Default: a new `KuiWindow` opened with the
* options above. A test fills it with a stand-in — what a surface
* answers plus `pump`, `animating` and `nextDeadlineMs` — to run
* this driver, pump order and all, without a display; the mirror of
* `createApp`'s `surface`. */
surface?: KuiWindow;
},
): Promise;
export interface Quad {
x: number; y: number; w: number; h: number;
color: [number, number, number, number];
borderColor: [number, number, number, number];
/** Corner radii (physical px) clockwise from the top-left: tl, tr, br, bl. */
radii: [number, number, number, number];
/** The top-left radius — the uniform value for boxes rounded with `radius`. */
radius: number;
borderW: number;
/** Shadow quads (kind 5) only: the blur radius, which is also how far
* the rect is inflated past the shape being blurred. 0 otherwise. */
blur: number;
/** 0 solid, 1 mask glyph, 2 color glyph, 3 image, 4 subpixel glyph,
* 5 shadow, 6 segment, 7 fragment, 8 texture, 9 backdrop, 10 and 11 a
* group's begin and end (`setOpacityGroups`, ADR 0056) — `QuadKind` in
* the core and `KUI_QUAD_*` in `include/kui.h`, in the same order. A
* group's markers carry its bounds and its fade in `color[3]`, and
* `uv[0]` the other marker's index. A fragment
* quad's `uv[0]` indexes `fragmentDraws()`, a texture quad's
* `textureDraws()`; on both image kinds `borderW` is the `sampling`
* flag (1 = nearest). */
kind: number;
uv: [number, number, number, number];
/** Segment quads (kind 6) only: the stroke's endpoints `x0, y0, x1, y1`
* in physical px, with `borderW` the stroke width and `color` the
* stroke. A `` is one of these per piece — a curve is flattened
* in the core, so a display list carries many. `null` on every other
* kind. */
ends: [number, number, number, number] | null;
/** Which entry of `decodeClips(ctx.clips())` clips this quad. An index
* rather than the clip itself since ABI 11: a clip is 32 bytes and a
* frame has a handful of them, so carrying one per quad was paid by
* every quad of every frame for a value nearly all of them share.
* Entry 0 clips nothing, so there is no null case. */
clip: number;
}
/** One clip a frame's quads name, from `decodeClips`. Physical px. */
export interface Clip {
rect: [number, number, number, number];
/** Corner radii, clockwise from the top-left: a clipping node with a
* radius rounds what it clips. All zero = a plain rect clip. */
radii: [number, number, number, number];
/** The turn every quad naming this entry is drawn through (ADR 0043):
* angle in radians, scale, tx, ty. `[0, 1, 0, 0]` when nothing turns. */
transform: [number, number, number, number];
/** The stretch before the turn (`scaleX` / `scaleY`, backlog C149): sx,
* sy, shear. `[1, 1, 0]` when nothing stretches. */
stretch: [number, number, number];
/** A second clip in the quad's own space, before the turn, and its
* radii: from clipping nodes inside a turned subtree. */
inner: [number, number, number, number];
innerRadii: [number, number, number, number];
}
/** The container `uniformList` declares: every `` prop, plus what it
* needs to slice by. `scrollY` and `gap` are the widget's own. */
export interface UniformListProps extends Omit {
/** Names the container. Required: its geometry is read back by this name,
* so two lists cannot share one (`ambiguous-key`). */
key: string;
/** How many rows the list has, built or not. */
rows: number;
/** One row's height in logical px — the whole stride. Put a row's
* spacing inside it (a row that pads itself) rather than in a `gap`. */
rowH: number;
/** Rows built past each edge of the window, covering the frame of lag on
* a resize or a wheel jump. Two by default. */
overscan?: number;
/** Each row's own node's props — its `onClick`, stripe, hover — where
* the row's contents would otherwise nest a node to carry them. Its
* `index` and `height` stay the list's (backlog DX22). */
rowProps?: (i: number) => BoxProps;
}
/**
* A vertically scrolling column of `rows` uniform rows that declares only
* the visible ones, and the two spacers that hold the height of the rest —
* so the frame costs a screenful however long the list is.
*
* uniformList(ctx, { key: 'log', rows: lines.length, rowH: 28 }, (i) => (
*
* {lines[i]}
*
* ))
*
* `row(i)` returns row `i`'s *contents*; the widget owns the row's own node,
* `rowH` tall and keyed by the row's data `index`, so a row keeps its hover,
* focus, edit buffer and tweens as the built range slides over it — and a
* virtualised list and a full one agree on identity. A clickable row puts
* its `onClick` on a `width="grow" height="grow"` child, as above.
*
* It also declares the zero-height node that makes the *loop* re-run `view`
* when the container scrolls: the wheel raises no event and a window redraws
* by re-lowering the tree it was handed, so nothing else would. That node's
* events never reach `update`.
*
* `ctx.setScroll(key, 0, i * rowH)` puts row `i` at the top — the way to
* reach a row that is not built, since `reveal` of an unbuilt row finds
* nothing.
*/
/** A branch built only when it can be shown (ADR 0069): `render()` when
* the parent offers the room `needs` names — laid out at exactly that
* size — or while `query` holds; `fallback()` otherwise, and neither
* before the first layout. The frame is built again when this one's
* layout disagrees with the choice. */
export declare function Lazy(props: import('./jsx-runtime.js').LazyProps): import('./jsx-runtime.js').KuiElement;
export declare function uniformList(
ctx: Pick,
opts: UniformListProps,
row: (i: number) => KuiNode,
): KuiNode;
/**
* Scrolls the `uniformList` keyed `key` so row `i` shows, when it does not:
* to the middle (backlog DX22). Call it before the list is built, so the
* frame that scrolls builds the rows it scrolled to — `reveal` finds
* nothing for a row the list has not built. True when it scrolled; before
* the list has laid out it scrolls nothing.
*/
export declare function revealRow(
ctx: Pick,
key: string,
i: number,
rowH: number,
): boolean;
/** How many whole rows of `rowH` the list keyed `key` shows as of the last
* layout — a page's stride; 0 before it has laid out. */
export declare function rowsInView(
ctx: Pick,
key: string,
rowH: number,
): number;
/** What `splitter` draws: the parent's direction, the bar's thickness and
* the message its drag arrives as (a `DragMsg`). */
export interface SplitterProps {
key?: string;
/** The parent's direction: `'row'` (the default) for panes side by side. */
dir?: 'row' | 'column';
/** Across the bar, in logical px; 4 by default. */
thickness?: number;
onDrag?: HandlerMsg | null;
}
/**
* A divider between two panes that the pointer drags (backlog DX22): the
* theme's border colour, its accent while hovered or held, the resize
* arrows, and `keepFocus`. The drag's `x` against its `parent` rect is the
* new fraction.
*/
export declare function splitter(ctx: Pick, opts?: SplitterProps): KuiNode;
/** What `list` reads before it slices, handed to `RowHeights.sliceBegin`:
* the container's last layout (null on the first frame), where its scroll
* is going, the window, and the padding its rows sit inside. */
export interface ListReading {
geometry: ScrollGeometry | null;
scrollY: number;
viewportW: number;
viewportH: number;
padT: number;
padX: number;
overscan?: number;
}
/** What a frame's slicing comes to, from `RowHeights.sliceFinish`: the rows
* to build (`first` up to, not including, `last`) with each one's height,
* the two spacers, and the correction `ctx.shiftScroll` makes. */
export interface ListPlan {
first: number;
last: number;
heights: number[];
lead: number;
tail: number;
shift: { drawn: number; target: number } | null;
firstFrame: boolean;
}
/** The container `list` declares: every `` prop, plus what it slices
* by. `scrollY` and `gap` are the widget's own. */
export interface ListProps extends Omit {
/** Names the container. Required: its geometry is read back by this name. */
key: string;
/** The heights the list slices by: a `new RowHeights(rows, estimate)` the
* app makes once and keeps between views. */
heights: RowHeights;
/** Rows built past each edge of the window. Two by default. */
overscan?: number;
}
/**
* A vertically scrolling column of rows of *different* heights that declares
* only the visible ones — `uniformList` where no single stride describes the
* list.
*
* const heights = new RowHeights(messages.length, 40); // kept in the model
* list(ctx, { key: 'chat', heights },
* (i, width) => ctx.measureText(messages[i], style, width - 16).height + 12,
* (i) =>