@kama/ui
One set of HTML-like documents for a kama program's UI. It has two backends behind one contract:
- In a browser, the browser's own DOM. The documents become real elements over the canvas, painted by the
browser. No JavaScript library is used: only the DOM and CSS, through about 700 lines of emcc
--js-libraryglue. - Natively, RmlUi through
@kama/rmlui. It records draw commands for the program's own renderer.
The program writes ui::UiContext and never knows which backend it has. Each build has exactly one: native.kama and
web.kama declare UiContext under complementary @compileFor gates, and both are checked against the UiHost
contract where they are written.
Status: published (registry.kama-lang.org, 0.6.0 on 2026-10-29): the
Commitevent. Needs kama ≥ 0.9.758; tested with 0.9.765. Tested natively on Linux x86_64 (debug, release and AddressSanitizer) and in headless Firefox 157 (emcc 6.0.9).
The plan. RmlUi is today's native engine. Matt's own HTML/CSS engine replaces @kama/rmlui later, behind this
same contract. Only native.kama changes. The documents, the web leg and every program using UiContext stay as they
are. What a replacement must provide is exactly UiHost in src/host.kama:
- documents from a file and from text, on a scaled stage or as a page that fills the window;
- bindings by id that survive rewrites, and let go of what a rewrite replaced;
- markup appended and children removed in place;
- events, polled, each naming where it happened: clicks, changes, commits, double clicks, keys, focus and blur, drops;
- a focus ring driven by TAB, the arrows and ENTER;
- tooltips from
title, and drag and drop fromdraggable, onto zones markeddroppable, saying where it landed; - files into and out of the page: chosen, dropped from outside, pasted, read in slices, offered to save;
- a
<video>or<audio>element's playback: its time, length and pause, a seek, play and pause, and an event when any of it changes (on the web only today: RmlUi decodes no media, so natively every answer is None or false); - quiet writes into controls, classes, attributes, inline properties and plain text;
- a clipboard the program bridges;
- recorded draw commands and textures.
The contract
src/host.kama is the authority. Every method there carries its reasons. In short:
| group | methods |
|---|---|
| documents | loadDocument(path), loadDocumentText(rml), closeDocument(), setInnerRml(handle, rml) (releases what it replaces), appendInnerRml(handle, rml) (keeps it), childCount(h), removeChildren(h, from, count) |
| assets | loadFont(path, fallback), provideImage(name, rgba: ConstView<uint8>, w, h), setImageRewrite(nativeExt, webExt) |
| frame | setSize, setViewport(offsetX, offsetY, scale, visible), setDpRatio, update(), updateAt(seconds), render() |
| drawing (native) | commandCount, command(i) → UiCommand (kind, vertices, indices, texture, translation, scissor, transform), textureCount, texture(h), textureGeneration(h) |
| pointer (native) | mouseMove, mouseButton(button, down, mods), mouseWheel |
| keyboard | key(code, down, mods) with UI_KEY_* (GLFW's numbers) and UI_MOD_*, claimKey(key, mods), typeChar(codepoint), focusHeld(), focusDocument(), focusElement(h), focusedElement(), textFocused() (any control a person types into) |
| clipboard | copyText(text), provideClipboard(text) / takeClipboardWrite() (native; no-op / None on the web) |
| files | chooseFiles(accept, multiple) → a file list, fileCount / fileName / fileSize / fileType / filePath(files, i), releaseFiles, readFile(files, i, offset, count) → a read, readBytes(read, into), readError(read), saveFile(name, bytes); uiFileType(name) |
| media (web; None / false natively) | mediaTime(h) / mediaDuration(h) → Optional<float64> seconds, mediaPaused(h) → Optional<bool>, seekMedia(h, seconds), playMedia(h), pauseMedia(h) → bool (asked) |
| files (native, the program's half) | takeFileRequest(), fileRequestAccept / fileRequestMultiple, provideFiles(files, paths), dropFiles(paths, x, y), pasteFiles(paths), takeSaveRequest(), saveRequestName, saveRequestBytes (0 and no-ops on the web) |
| elements | bindElement(id) → handle, findElement(id) → a handle that hears nothing, elementId(h) → its id, elementRect, elementValue / setElementValue (a float), elementText / setElementText (no length cap), elementChecked(h), setElementClass, setElementProperty, setElementAttribute(h, name, value) / removeElementAttribute(h, name), elementContent(h) / setElementContent(h, text) (plain text), scrollToEnd(h), isScrolledToEnd(h), scrollIntoView(h) |
| events | pollEvent() → UiEvent { kind: Click | Change | DoubleClick | Key | Focus | Blur | Drop | Files | Paste | Read | Media | Commit, element, target, source, key, mods, files, atX, atY } |
| lifetime | UiContext.open(width, height, fontPath) (a stage), UiContext.openPage(width, height, fontPath) (a page), isOpen(), close() |
ui::UiNav turns a pad's d-pad and stick into arrow presses (hysteresis, one direction at a time, delay then repeat).
ui::uidoc holds the RML → HTML rewriter (rmlToHtml) and escapeText, the escaping both parsers agree on.
The rules that matter most:
A
UiContextis a value. Its state lives on the other side of the seam, so a program may keep copies in module statics;close()is explicit.A stage or a page.
openis a fixed virtual resolution the program letterboxes and scales (setViewport): a game's menus.openPageis a document that fills the window and reflows like a web page: a tool, an editor. On the web a page's stage is pinned to the window, shown at once, never scaled, and resized by CSS alone; natively the program passes its window's size tosetSizeon every resize and draws the commands at the origin, unscaled. Both scroll anoverflow: autoelement in place.Handles are integers. Binding an id again gives the same handle, and repairs it after
setInnerRmlreplaced the element. Re-bind what you wrote, after the write.A rewrite releases what it replaced. A handle into the old content lets go of its element and its listeners, and every call on it is a no-op until an element carries its id again; then the same handle names the new one.
Events bubble on both legs. A bound container also hears its children's clicks.
An event names its target: the nearest element with an id, from where it happened up to the bound element. One binding on a list tells its rows apart. The target is a handle (the one
bindElementgives for that id), soelementIdturns it into the row's id. Poll before you rewrite: a target the rewrite destroyed reads as 0.Name what you only write to with
findElement. It gives the handlebindElementwould, without listening: a list rewritten withsetInnerRml, a row given a class, a box measured. Nothing is queued for it, and it does not hear its children. It is 0 when no element has the id now, even one named before (0.5.1), so it also answers whether an element is there.One change per edit, the same count on both legs: each character typed into a text field or a textarea, each step of a range (live, as a slider previews), each toggle of a checkbox, each choice of a radio or an option. A commit is no edit: ENTER in a text field, a field losing focus, a slider let go. Neither is the radio a choice unchecks, nor a movement that changes nothing: a range stepped past its end, or dragged within one step.
A
Commitwhen the person is done with a value (0.6.0), after the Changes on the way, for a program that wants only the value settled on (a field saved as it is left, one undo step per drag). It names the control as itstarget, reaches the same bindings in the same order, and carries no value: read it, as the last Change left it. A range commits as it is let go (a drag of its bar, a press on its track) and at each step of a key; a text field at ENTER and as it loses the focus (before that Blur); a textarea as it loses the focus; a checkbox, a radio and a select with each Change. Only when the value changed since the control's last Commit: a drag back to where it began, or a character typed and erased, then left, is none. A program's write is what the next Commit is measured against, unless the person has an edit pending, which then still commits.Writes into controls raise no event on either leg, attributes included (
checked,value), neither a Change nor a Commit. Only a person's edit is queued.scrollToEndfollows a log: write the new line, ask in the same frame, and the next frame drawn shows the end on both legs. The web scrolls at once; natively the request waits for the nextupdate, whose layout pass measures what was written. To follow only while the reader is at the bottom (scrolling up to read is not yanked back), ask first and append withappendInnerRml, which rewrites nothing:bool follow = ui.isScrolledToEnd(handle: log); ui.appendInnerRml(handle: log, rml: line); if (follow) { ui.scrollToEnd(handle: log); }isScrolledToEndis true within a pixel of the end, for a box that cannot scroll, and while ascrollToEndwaits for the next update. On the web an append touches no existing node, so a person's text selection survives it. The cost is the new markup's on both legs.childCountandremoveChildren(h, 0, n)trim the oldest lines without a rewrite.The same events, in the same order, on both legs.
- Two presses within half a second are Click, DoubleClick, Click.
- Focus moving is Blur on what had it, then Focus on what has it, for a button, a form control or an element with a tab index. A bound container hears them before the element: RmlUi's focus does not bubble, so both legs listen on the way down.
- A Click, a DoubleClick and a Drop carry the
modsheld (UI_MOD_*, Cmd folded into Ctrl).
Keys are events too. A
Key(element 0,targetthe focused element) arrives for every key of the table that types no character: Enter, Escape, Tab, the arrows, Delete, Backspace, Home/End, PageUp/PageDown and F1–F12. A–Z and 0–9 arrive only with Ctrl or Alt held.claimKey(UI_KEY_S, UI_MOD_CTRL)keeps a shortcut from the browser (no save dialog) as the key goes down; natively there is nothing to keep it from.The program gets every key first. On the web the browser hears its own keys, and the program forwards the ring's (TAB, the arrows, ENTER) to
keyfor a page that swallows them. Natively it forwards every key it does not keep, with its modifiers. ENTER clicks the focused element, so it arrives as an ordinary click.Drag and drop:
draggable="true". Natively the package makes it RCSSdrag: drag-drop; on the web it is HTML5's. A drop raisesDropwhere it lands, withtargetthe element dropped on andsourcethe one dragged. During the drag the dragged element has the classui-draggingand the element under the pointer hasui-drop-target.Drop zones:
droppable="true"with an id (0.4.0). A drop anywhere inside a zone names the zone as itstarget, and the zone, not whatever inner element is under the pointer, hasui-drop-target; with no zone there, both are the nearest element with an id, as before.atXandatYsay where in the target it landed, 0 to 1 across its border box, so a list can put what was dropped before or after a row.Files (0.4.0). A file list is a handle the package holds files under until
releaseFiles:chooseFilesreturns the list its answer fills, and aFilesevent says it is filled (empty: cancelled). One at a time; on the web only within a person's gesture, so call it while handling the Click or Change that asked.- files dropped from outside are a
Dropwithsource0 andfilestheir list (the same list on every event of one drop); files pasted are aPaste, the document's, naming the focused element; - each file has a name, a size, a media type from its name (the package's own table,
uiFileType, the same on both legs) and, natively, its path; readFilereads a slice without blocking: aReadevent says it is done, andreadBytesmoves the bytes out;saveFileoffers bytes to save under a name: a download on the web, a save request for the program natively. On the web a file stays the browser'sFileuntil a read asks, and another library takes it whole fromModule.kamaUiFile(files, index)(a fetch's body: an upload never copies the file into wasm memory).
Media (0.5.0): a
<video>or<audio>by handle.mediaTimeandmediaDurationare seconds (float64; the length None until the metadata has loaded),mediaPausedwhether it is paused; each None for what is not a media element.seekMedia(h, seconds)reads back at once and is followed by aMediaevent once the frame there is decoded;playMediaandpauseMediasay whether they were asked (a browser may refuse to play a clip with sound without a person's gesture:mediaPausedsays). AMediaevent says only that something changed — the metadata loaded, a play, a pause, a seek finished, the time moved while playing — so read the state. Media events do not bubble in the DOM, so they are heard in the capture phase, as Focus: a bound container hears its clips', ancestors first. One waits at a time per binding and clip. A frame picker:// A step button's Click: one frame on, for a clip of 24 frames a second. ui.pauseMedia(handle: clip); Optional<float64> at = ui.mediaTime(handle: clip); match (at) { case Some(value: t): { ui.seekMedia(handle: clip, seconds: t + 1.0 / 24.0); } case None: { } }; // A Media event naming `clip` (the seek finished, or it played on): show `mediaTime` as the frame picked.On the web only, today. RmlUi decodes no media, so natively every answer is None or false whatever the handle names, and a
Mediaevent never arrives; the same document still loads there, the clip an empty box.textFocused()is any control a person types into (0.5.0): a<textarea>, and an<input>whose type is absent,text,password,number,search,email,urlortel, in any case. A page checks it before a shortcut (Ctrl+Z, Ctrl+A, a bare letter) so the field's own keys stay the field's.Tooltips:
title. After half a second of hover, on the program's clock (so callupdateorupdateAtevery frame on the web too), the package shows the title in#kama-ui-tooltip. The document styles.ui-tooltip. It hides on leaving, on a press and on a scroll. On the web the attribute is held asdata-kama-ui-title, so the browser's own popup never shows; a[title]rule matches natively only.The clipboard is the program's to bridge, natively. Hand the OS clipboard's text to
provideClipboardbefore forwarding a paste, and put everytakeClipboardWriteon the OS clipboard; RmlUi's fields then copy, cut and paste with Ctrl+C/X/V.copyTextworks on both legs. The web needs none of this.The native renderer must apply
UiCommands in order and skip (or implement) every one whosekindis notDraw. AClipSetcarries a mask's geometry, not a picture.
Using it
Natively
@kama/rmlui and @kama/freetype vendor RmlUi and FreeType, and kama compiles them into the program. There is
nothing to fetch or build first, and no -L path to set. Once the packages are on the registry, depend on this one
alone:
"dependencies": { "@kama/ui": { "version": "^0.4.0" } }
@kama/rmlui and @kama/freetype come with it. To build against a checkout instead (working on the package itself),
override it in your gitignored kama.local.json, never in kama.json:
{ "overrides": { "@kama/ui": { "path": "../kama-ui" } } }
@kama/rmlui's README covers the rest: build times, "debug": { "optimize": ["rmlui", "freetype"] } to keep
the layout engine at release speed in a debug build, and Windows' static libstdc++.
import { ui::UiContext, ui::UiEvent, ui::UiCommand, ui::UI_KEY_DOWN };
fn void frame(ref UiContext ui, int32 play) {
ui.updateAt(seconds: 12.5); // a monotonic clock: hover transitions, the caret
ui.render();
int32 i = 0;
while (i < ui.commandCount()) {
UiCommand c = ui.command(index: i);
bool draw = match (c.kind) { case Draw: true; case _: false; };
// if (draw) { upload c.vertices (8 floats a vertex, premultiplied), c.indices; texture c.texture,
// keyed on ui.textureGeneration(handle: c.texture) }
i = i + 1;
}
bool more = true;
while (more) {
Optional<UiEvent> e = ui.pollEvent();
match (e) {
case None: { more = false; }
case Some(value: ev): { if (ev.element == play) { /* start */ } }
};
}
}
fn void open() {
UiContext ui = UiContext.open(width: 1920, height: 1080, fontPath: "assets/fonts/Inter-Regular.ttf");
ui.setDpRatio(ratio: 1.0);
ui.loadDocument(path: "assets/ui/menu.rml");
int32 play = ui.bindElement(elementId: "play");
frame(ui: ui, play: play);
}
A page — a tool's window, say — opens with openPage, follows the window with setSize, and needs one binding for a
whole list:
fn void openTool(int32 width, int32 height) {
UiContext ui = UiContext.openPage(width: width, height: height, fontPath: "assets/fonts/Inter-Regular.ttf");
ui.loadDocument(path: "assets/ui/items.rml"); // <div id="items"><div id="item-17">…</div>…</div>
int32 items = ui.bindElement(elementId: "items");
// every window resize: ui.setSize(width: w, height: h); (a no-op on the web, where CSS follows the window)
Optional<UiEvent> e = ui.pollEvent();
match (e) {
case None: { }
case Some(value: ev): {
if (ev.element == items) { string row = ui.elementId(handle: ev.target); /* "item-17" */ }
}
};
}
The program owns the window natively, so five things are its part. The browser does all five by itself.
Every key it does not keep goes to
key(code, down, mods), with Cmd asUI_MOD_CTRL, and every character goes totypeChar. That is how shortcuts reach the document asKeyevents, and how a field's Ctrl+A/C/X/V works.The modifiers held go to
mouseButton(button, down, mods).updateAt(seconds)every frame, on a monotonic clock. Double clicks and the tooltip's delay are measured on it.The clipboard:
ui.provideClipboard(text: osClipboardText); // before forwarding a paste, or every frame bool more = true; while (more) { Optional<string> w = ui.takeClipboardWrite(); // each copy, cut or copyText, oldest first match (w) { case None: { more = false; } case Some(value: s): { /* put s on the OS clipboard */ } }; }Files (0.4.0): the package owns no window, so it opens no dialog. The program's platform layer (or a dialog package) does:
int32 asked = ui.takeFileRequest(); // a chooseFiles waiting: 0 for none if (asked != 0) { // show the OS's open dialog, filtered by ui.fileRequestAccept(files: asked), one or several by // ui.fileRequestMultiple(files: asked); then answer with what was chosen (none: cancelled) ui.provideFiles(files: asked, paths: chosen); } int32 save = ui.takeSaveRequest(); // a saveFile waiting: 0 for none if (save != 0) { string name = ui.saveRequestName(save: save); // the save dialog's suggestion bool took = ui.saveRequestBytes(save: save, into: bytes); // then write them where the person chose } ui.dropFiles(paths: dropped, x: cursorX, y: cursorY); // the window's file drop, as it happens ui.pasteFiles(paths: copied); // a paste while the OS clipboard holds files
In a browser
Build the program with --target WASM. This package's jsLibraries and emSettings reach the build on their own.
- The page: the shell may provide
#ui-stageand#ui-root; if it does not,opencreates them. The stage is the virtual resolution given toopen.setViewport(…, visible: true)positions it over#canvasand shows it.openPagepins the stage to the window's four edges instead: it is shown at once, never scaled, and CSS resizes it;setViewportthen only shows and hides it. - Documents are read from the program's virtual filesystem (
--embed-filethem) and rewritten to HTML byui::uidoc::rmlToHtml.loadDocumentTextneeds no file. - Fonts come from the page's own
@font-face. Images are served beside the page. If native and web read different files for one picture,setImageRewrite(nativeExt: ".pam", webExt: ".webp")rewrites every<img src>as it is inserted. - Keys.
Keyevents come from the browser's own keydown, heard on the window in the capture phase, whereclaimKeyprevents a claimed shortcut's default. For a page that swallows the keys (a game's platform layer preventDefaults them, so SPACE and the arrows do not scroll the page), the program forwards the navigation subset throughkey(), and the JS moves the focus in document order and clicks on ENTER. The browser types into its own<input>s. - The clock.
updateandupdateAtkeep the program's clock, which the tooltip's delay is measured on. Call one every frame here too. - Files.
chooseFilesclicks a hidden<input type=file>at once, so it must be called while the browser still counts a person's gesture (a few seconds after the click or the key); otherwise it answers 0. Dropped and pasted files come from the browser's own events, and a file dropped anywhere in the window is never opened as a page while a document is up.saveFileis a download.Module.kamaUiFile(files, index)hands another library theFile. - Media is the element's own:
currentTime,durationandpausedread,currentTimewritten for a seek, andplay()(its refusal swallowed) andpause(). A clip'ssrcis fetched by the browser, so it is served beside the page, as an image is. mouseMove,mouseButton,mouseWheel,render,typeChar,setDpRatio,loadFont,provideImageandprovideClipboardare no-ops here, andtakeClipboardWriteis always None: the browser does those itself. So are the files' native half (takeFileRequestandtakeSaveRequestalways 0).
Writing documents for both legs
ui::uidoc repairs the five places RCSS and CSS disagree: borders have no style in RCSS, RmlUi has no default
stylesheet, the browser's UA sheet, inheritance, and form-control accents. It also turns dp into px and scopes
every selector under #ui-root, mapping body and RmlUi's scrollbar elements. Beyond that, the document's own job:
- Declare
display: blockfor the tags you use. RmlUi defaults everything to inline, and the web leg reproduces that on purpose. - Make controls focusable with
tab-index: auto; nav: auto;. To wrap the ring at its ends, writenav-upon the first control andnav-downon the last. The web wraps by itself and walks document order, so lay out one column, or spell everynav-*. - To take a form control out of the ring, write it inline:
style="tab-index: none". RmlUi gives every form control an inlinetab-index: autothat no stylesheet rule beats, and the web leg reads the same inline style (tabindex="-1"also works there). autofocusputs the ring on a control when the document loads, on both legs.- An
<input>carries its type as a class on both legs (range,checkbox,text…), as RmlUi gives it one, soinput.rangestyles a slider on both. A class toggled on an input keeps it (0.4.0; natively a toggle used to drop it, and the web gave none). - Inline properties set with
setElementPropertymay usedp. The web leg rewrites it topx. - Text another person typed goes through
ui::uidoc::escapeTextbeforesetInnerRml. On the web an unescaped<is script injection. - Close a
<video>or<audio>with its own end tag,<video id='clip' src='clip.webm'></video>, never/>. RML is XML, where both mean the same; HTML ignores the/on an element that is not void, so the rest of the document would end up inside the clip. - Not drawn natively yet:
box-shadow,filterand gradients (@kama/rmlui's README, "Not here yet").
Tests
KAMA=/path/to/kama tools/test.sh # native: debug, release, and AddressSanitizer (Linux), through @kama/rmlui
KAMA=/path/to/kama tools/test-web.sh # emcc (EMSDK, default ~/emsdk), served locally, run in headless Firefox
The two scripts build one program, tests/. Shared on both legs:
ui::uidoc: the rewriter suite.ui::UiNav: the focus-navigation suite.- the seam suite, run against whichever
UiContextthe build has:- a document from a file and one from text;
- every id bound, an unknown one 0, a re-bind giving the same handle;
- laid-out boxes;
- the focus ring starting on
autofocus, walked down and up with wrapping, and TAB; - ENTER clicking the focused button, with the bubble to its container;
- a real click, injected, arriving as a polled event, bubbling to the container, each naming its target;
- quiet writes of text and of a range, read back, raising nothing;
- a class and an inline
dpproperty changing a box; - a rewrite with a new id bound and an old handle kept;
- a rewrite releasing what it replaced: every call on a stale handle a no-op (under ASan natively), its id kept, and the same handle naming the element once its id is back;
- one binding on a list: a click on each row naming the row (or the row's text, by its own id), a target being the
handle
bindElementgives, and naming one adding no listener; findElement: a found element's click raising nothing, a found container not hearing its children, a found handle taking a write and a rewrite, and binding it later giving the same handle, which then hears; 0 for an id named before whose element a rewrite removed, and the same handle once it is back (0.5.1);- one change per edit, counted per control: three characters typed into a text field, two into a textarea, a range step, a range step past its end (none), a checkbox toggle, a radio choice (one, though RmlUi also unchecks the neighbour), an option picked, and ENTER in a text field (none);
- a commit when a person is done with a value (0.6.0), each as the Changes and Commits one handle heard, or one string per leg: a range's key step (Change, Commit), two before one poll, one past the end (neither), its bar dragged two steps and let go (two Changes, a Commit), dragged down and back (four Changes, none), a press on its track (Change, Commit) and on its bar (neither), and a key step with a drag before one poll; a text field typed in and left (its Changes, the field's then the panel's Commit, then the Blurs), typed in and ENTER (the Changes, the Key, the Commits), ENTER again and leaving it unedited (none), a character typed and erased then left (none), the program's write then leaving (none) and its write over a pending edit (still committed); a textarea's ENTER (no commit) and its blur (the Commit, then the Blur); a checkbox (Change, Commit); a radio bound inside a bound container (both Changes, then both Commits, the unchecked radio neither), two radios before one poll, and an option picked;
- attributes:
hiddenagainst the document's[hidden]rule,checkedset and removed quietly, a person's click toggling it, a write after that still taking, and avalueattribute written quietly; - a 3,400-byte value with three-byte characters read back whole;
- keys: Escape, F2, PageDown, Ctrl+S and Alt+1 each one
Keynaming the focused element; a letter alone or with Shift none; - focus and blur as one string per leg (
Blur:panel>first,Blur:first>first,Focus:panel>second,…), and a press on what cannot hold the focus taking it away with no Focus; - Click, DoubleClick, Click for two presses within half a second, two spaced clicks giving none, and a Ctrl and a Shift+Alt click carrying their modifiers;
- a drag and drop: the two classes mid-drag, one Drop heard by the list with its target and source, the classes
gone after, and an appended
draggablerow dragged onto a bound row's text; - a drop zone: the class on the zone, not on its row with an id, a drop naming the zone and saying where it landed (top left, bottom right, read from the drop even after the pointer moved on), and a range the drag passed over keeping its own class and size;
- files, as ticks of the program's frame loop (a read finishes on its own time on the web):
uiFileType; two files dropped on a zone's row — one Drop naming the zone, with their names, sizes and types; two reads, a slice and one past the end, each a Read event, their bytes moved out and gone once taken; the chooser one at a time, answered with two files and then cancelled; a file pasted into a focused field; a save offered asout.json, 8 bytes,application/json; no chooser without a document; - plain text written and read, ignored by a form control; a select's options rebuilt, appended to and trimmed with its value settled and no change;
- what counts as typing (0.5.0): the ring on an
<input>with no type, an empty one,text,password,number,search,EMAIL(in capitals),urlandtel, and a textarea, eachtextFocused; on a checkbox, a radio, a range, a submit, adate(a text field natively) and a button, each not; - media (0.5.0), as ticks of the frame loop after the files': a paragraph, handle 0 and an unknown handle
answering nothing; then on the web a two-second VP8 clip (
tests/fixtures/clip.webm, made bytools/make-test-clip.py) with its metadata heard and its length known, at its start and paused; a seek to a negative time refused, one to 1.25 s reading back at once and heard when it finishes; a play heard with the time moving on, and a pause taking at once; every poll's Media events being the player's then the clip's, one each (capture order, one waiting at a time), and nothing else; and a handle into the closed document answering nothing. Natively the clip answers nothing and raises no event; - closing the document;
close();- a page (
openPage): shown withoutsetViewportat the window's corner, and anoverflow: autobox scrolled by the wheel while the page stays put; scrollToEndasked right after a rewrite, before any update, showing the newest line at the log's bottom with no event, and doing nothing for an unknown handle or a box that does not scroll;- a log appended to with
appendInnerRml: followed while at its end (isScrolledToEndtrue even before the update), the line before the new one kept in order with its handle, its class and its listener (clicked before its handle is used again); scrolled up, an append leaving the reader where they were, unfollowed; a pendingscrollToEndreading as at the end; - a line scrolled to the top of the log, and the oldest five lines removed (a handle into them stale, one to a kept line valid, a range past the end removing nothing);
- a tooltip: nothing a sixth of a second in, the title past half a second at 12 and 16 px from the pointer, hidden on leaving, on a press (and staying hidden while hovered) and on the wheel;
- a stage opened after the page, shown by
setViewportat its own virtual width.
On the native leg the input is RmlUi's own: the pointer, the buttons (a click half a second of the clock apart from the
last, so it never pairs into a double click), the wheel and keys. On the web it is the browser's own hit test
(document.elementFromPoint) and the events a browser fires, in its order. A synthetic event performs no default
action, so the helpers perform the ones that matter: a press focuses what it hits; typing focuses the field and sends
an input per character (a change only as a browser does, when the field is let go); an option is selected, then
input and change; a drag is mousedown, dragstart, dragenter, dragover, drop, dragend; a range's thumb dragged is
the press, an input per step, the release with its change, and the click (a press on its track the same, with one
input for the jump); a key is a keydown at the focused element, then the same key forwarded to key. Natively a
range is dragged by RmlUi's pointer at its bar, and an option is chosen by a click in the box laid out below its
select. Each leg adds its own checks:
- Natively: draws with vertices and a glyph-atlas texture, the provided picture at its own size, typing with
Backspace, Home and Delete, change events from typing, "a navigation key with nothing focused lands on the first
control", Ctrl+A/C/V against the clipboard the program bridges, and a page reflowing to
setSize; a file's absolute path, a one-file chooser keeping the first path, and a read of a file gone from the disk failing with its name. The wheel is RmlUi's own input, with a second of updates for its smooth scroll. - On the web: a claimed Ctrl+S prevented (and Cmd+S folded into it) while Ctrl+P is not,
copyTextreachingnavigator.clipboard, a title held asdata-kama-ui-title, a text selection surviving an append, a slider dragged two steps and let go giving two changes and a commit, no commands and no textures, the image rewrite done before the browser fetched (and on ansrcattribute), real elements, a row a rewrite released and a field from a closed document hearing nothing (click, input and change fired at the detached element), and a page's stage pinned to the window, filling it, hidden and shown again bysetViewportwithout moving. The wheel is the browser's own scroll, applied to the box under the point (a syntheticWheelEventscrolls nothing); no path for a file, the zone highlighted while files are dragged over and not once they leave,Module.kamaUiFilehanding over theFile, and text dragged in from outside reaching nothing.
Results: native 285 checks, passing in debug, in release and under AddressSanitizer with leak checking. The ASan
leg wraps cc/c++, so RmlUi, FreeType and both shims are instrumented. Web 305 checks, passing in headless
Firefox. The web leg serves the media suite's clip beside the page (tools/test-web.sh copies it there). The native
leg's font is Lato (SIL OFL 1.1), committed under tests/fonts/ with its licence and never published; nor is the clip,
which the package's own code made (tools/make-test-clip.py, with PyAV).
The web verdict comes back over HTTP. The page POSTs {run, failed, output} to tools/web-test-server.py, so nothing
reads a screenshot or a DOM dump. The page then closes its own window, which ends the browser. A failing check makes
the script exit 1 with the check's name.
⚠️ Brave 144 hangs in --headless on this machine, even for a one-line page. Firefox is the default; set BROWSER to
override.
Where it came from
Extracted from the UI layer of earlier kama games. Two copies were reconciled: the older had no lines the newer
lacked, and its document-rewriter test suite (tests/src/uidoc_test.kama) came across with it. Prefixes became
kama_ui_ / KamaUi. The changes made on the way:
| decision | why |
|---|---|
The native backend is native.kama over @kama/rmlui. The original C++ shim is gone from this package. |
The binding is general now. This file holds only the seam's policy: one document, bind by id, the GLFW key subset, first-press focus, the 1/60 step, quiet writes. |
UiCommand gained kind (clip masks), transformed and transform. Its pointers are UnsafeConstPtr. |
RmlUi 6's clip masks and transforms are recorded now, not dropped. The const pointers were owed (the original headers said so). |
provideImage takes ConstView<uint8>, not UnsafeConstPtr<uint8>. |
Safe and length-checked; the web leg ignores it either way. |
Added loadDocumentText(rml). |
Generated documents, and tests that need no files. |
uidoc's .pam" → .webp" rule became setImageRewrite(nativeExt:, webExt:), applied by the web JS before parsing. |
One game's convention no longer sits inside a general rewriter. It now reaches setInnerRml content too, and it runs before the browser fetches the wrong file. |
uidoc is a module, ui::uidoc, not its own package. |
One package to depend on and publish. |
The web ring includes input, select and textarea, and excludes tabindex="-1" and inline tab-index: none. |
The legs agree. RmlUi rings every form control. Form fields with no tabindex attribute were skipped on the web and stopped on natively. |
The web leg focuses [autofocus] when a document is set. |
autofocus does nothing in innerHTML. RmlUi's show focuses it, so the rings start in the same place. |
The web leg's setElementProperty turns dp into px and reports whether the browser took the value. |
"150dp" was invalid CSS there, and was dropped without a word. |
| The contract's comments are generalised (nothing game-specific); the measured warnings stay. | It is a package now. |
Publishing
kama publish ships exactly what git tracks, minus publish.exclude (tools/, tests/, the agent notes). The three
packages published in order on 2026-10-13: @kama/freetype, then @kama/rmlui, then @kama/ui, each once the
one before it was live, because a published package cannot carry a path dependency. Publish from kama-registry with
./ops publish ../kama-ui/kama.json.
License
@kama/ui is licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option. It vendors nothing. Its native leg builds @kama/rmlui and @kama/freetype, and their READMEs say
what a program that ships them must carry:
- RmlUi's MIT notice, and the containers' (robin_hood and itlib).
- FreeType's FTL, with its credit line.
- The MIT notice of FreeType's hashing code.
The web leg ships only this package's own code. A wasm build compiles FreeType (kama cannot gate a dependency by
target, @kama/rmlui's KAMA_GAPS.md #4), but nothing calls it, and the link drops it.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in @kama/ui by you, as
defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.