Repository navigation
Game UI
Menus, HUDs, lobbies and world-space panels are Svelte 5 components (*.svelte) mounted by a UIView (ADR 0423): HTML tags, a <style>, props and runes, rendered by the engine's renderer onto the UI core. UI lays out with flexbox, draws inside the game canvas with crisp text at any size, and takes the pointer before the game does. It lays out with Taffy, a CSS layout engine checked against Chrome (ADR 0434), and draws with Babylon GUI (ADR 0076).
A view's render is the only way to make game UI (ADR 0421, amended by 0423). The elements it renders are UI components (UICanvas, UIPanel, UIText, UIImage, UIButton, UIInputField and the form, SVG and media elements, ADR 0069), and scripts read and write their fields, but nothing else creates them: addComponent(UIPanel) throws, and a scene or prefab that saves a UI component on a node fails to load, naming the file and the node. UI documents (*.ui.xml markup with *.ui.css stylesheets and the UIDocument component, ADR 0077) were retired by 0423's wave D: a scene that still saves a UIDocument fails to load, naming 0423. There's no automatic migration; the samples are Svelte.
<!-- ui/Menu.svelte -->
<script lang="ts">
import { t } from "myco";
let { score = 0, onplay }: { score?: number; onplay?: (name: string) => void } = $props();
let name = $state("");
</script>
<div id="menu">
<h1 id="title">{t("menu.title")}</h1>
<button id="play" class="primary" onclick={() => onplay?.(name)}>Play</button>
<input id="name" bind:value={name} placeholder="Your name" />
<p id="score">Score: {score}</p>
</div>
<style>
:global(:root) { --fg: #ffffff; }
#menu { width: 100%; height: 100%; flex-direction: column; justify-content: center; align-items: center; gap: 12px; color: var(--fg); }
#title { font-size: 48px; text-outline-color: #000000; text-outline-width: 3px; }
.primary { width: 240px; height: 56px; background-color: #336699; }
.primary:hover { background-color: #4477aa; }
</style>-
Tags are HTML names:
div,section,ul… are panels,p,span,h1… text,imgan image,buttona button,inputand the other form elements controls (more below). -
Attributes set the element's fields, in kebab case (
font-size="20",background-color="#336699",width={w}) and beat style rules. A text element's content is its text; a button's text is its label. -
Styles are a CSS subset (and growing toward the web's, ADR 0422): type,
.class,#id, descendant and child selectors, pseudo-classes (:hover,:pressed,:focus,:disabled,:lang()…), and variables (--name,var(--name)). Properties are the elements' fields in kebab case. Text properties inherit from parent to child, as on the web:color,font-size,font-weight,text-align,text-outline-colorandtext-outline-width. A component's<style>is scoped to it;:global(…)rules and imported.cssfiles reach every view. -
Localised text:
{t("menu.start")}is that key's message in the current language, and follows a language switch (ADR 0356).
To show a component, put a node with a UIView in the scene and set its component (asset:ui/Menu.svelte). The view makes the canvas and renders the component's elements as children of its node; they aren't saved in the scene, and they render again when the component changes. In the editor, Create > UI > UI View adds a node with a view on a new component (the Assets panel's New Svelte Component makes one too); its static parts are selected and edited in the scene view and the Inspector (below).
- A disabled element or an inactive node takes no space.
display: nonedoes the same while the node stays active, like CSS'sdisplay: none.visible: falsehides an element and its children but keeps its space. Hidden elements, and elements inside them, don't take the pointer.
| Field | Meaning |
|---|---|
mode |
screen: drawn over the game, after the cameras and their post-processing, never tone mapped or fogged. world: a panel in the scene at the node's transform, drawn with the scene. |
referenceResolution |
The UI's design size in UI pixels (default 1280×720). |
matchHeight |
Screen mode. 1 (the default) scales the UI with the canvas height, 0 with its width, in between a blend, like Unity's Canvas Scaler. At 1, a 1280×720 design on a 2560×1440 canvas draws twice as big, and on a wider canvas gets more room at the sides. |
sortOrder |
Screen canvases draw in ascending order: higher is on top, and gets the pointer first. |
pixelSize |
World mode: world units per UI pixel (default 0.01, so a 1280×720 canvas is 12.8×7.2 units). |
modal, autoFocus, firstSelected, player
|
Keyboard and gamepad navigation: see below. |
A screen canvas covers the game canvas. Its children lay out in a row by default (flexbox's default); for a full-screen layout, give the component one root element with width: 100%; height: 100%.
These are the UIView's fields, set in the Inspector or by a script (view.sortOrder = 10): a component never writes a canvas tag.
Every element has flexbox fields (CSS flexbox, laid out as a browser does), written in kebab case in attributes and styles (flex-direction, justify-content). Lengths are UI pixels.
| Field | Values |
|---|---|
flexDirection |
row (default), column, row-reverse, column-reverse: how this element lays out its children |
justifyContent |
along that direction: flex-start, center, flex-end, space-between, space-around, space-evenly
|
alignItems |
across it: stretch (default), flex-start, center, flex-end, baseline
|
gap, padding, margin
|
pixels, on every side |
width, height
|
pixels (240 or "240"), a percentage of the parent ("50%") or "auto" (sized by the content) |
positionType |
relative, or absolute to take it out of the flow and place it by top, right, bottom, left (position: absolute in a stylesheet) |
flexGrow |
how much of the parent's free space it takes |
opacity |
0–1, multiplied into its children's |
visible |
false hides it and its children, keeping its space |
display |
flex (default), or none to take it and its children out of layout, drawing and the pointer |
raycastTarget |
true (default): the pointer stops at it, if it's a graphic (below); false: it passes through |
When children don't fit, text shrinks and wraps to what's left; other elements keep their size unless their flexShrink says otherwise (below).
ADR 0422 wave 1 adds these fields to every element, each settable by attribute, style rule or script:
| Field | Values |
|---|---|
paddingTop, paddingRight, paddingBottom, paddingLeft; the same for margin…
|
pixels on one side; null (the default) takes padding / margin, the all-sides value |
borderTopWidth, borderRightWidth, borderBottomWidth, borderLeftWidth
|
panels, buttons and input fields: one side's border; null takes borderWidth. Unequal sides draw each side as its own edge |
minWidth, minHeight
|
pixels or a percentage; auto (default): no minimum |
maxWidth, maxHeight
|
pixels or a percentage; none (default): no maximum |
flexWrap |
nowrap (default), wrap, wrap-reverse: children that don't fit go onto more lines |
alignSelf |
auto (default: the parent's alignItems), or one of alignItems' values for this element |
alignContent |
how wrapped lines share the space across: stretch (default), flex-start, center, flex-end, space-between, space-around, space-evenly
|
flexShrink |
how much it shrinks, relative to its siblings, when they don't fit; null (default): its kind's (text 1, others 0) |
flexBasis |
its size along the parent's direction before growing and shrinking: pixels, a percentage, or auto (default: its width or height) |
aspectRatio |
width ÷ height, kept when only one side is set (aspect-ratio: 16 / 9); 0 (default): none |
overflow |
visible (default), hidden, auto or scroll: other than visible, its children are drawn and take the pointer only inside its padding box (inside its border, with rounded inner corners); auto and scroll also scroll them (see Scrolling below). overflowX and overflowY (overflow-x, overflow-y) set one axis; null takes overflow
|
direction |
ltr or rtl (HTML's dir); null (default) takes the parent's, and a canvas is ltr. In rtl a row lays out from the right and scrolls from there (see Scrolling); text keeps the language's direction (ADR 0432) |
zIndex |
draw and pointer order among siblings: higher on top, then document order |
Shorthands work as in CSS, in styles and in attributes, and expand to the fields above where they're written, so the later declaration wins for each side:
.card { padding: 8px 16px; margin: 0 0 12px; border: 2px solid #fff; border-width: 2px 0; }
.grow { flex: 1; } /* grow 1, shrink 1, basis 0; also flex: none | auto | 2 0 50% | 120px */-
padding,marginandborder-widthtake one to four values (top, right, bottom, left, as in CSS). One value sets the all-sides field and clears the sides; two to four set the sides. A script writingpaddingchanges the sides that have no value of their own. -
bordertakes a width,solid(ornone, no border) and a colour, in any order. Only solid borders are drawn. - An
overflowother thanvisibleand a non-zerozIndexeach draw the element's descendants together, right after it, ordered among themselves by their ownzIndex: a child can't rise above its parent's later siblings by itszIndex(a CSS stacking context). Tab andnext/previouskeep document order; only drawing and the pointer followzIndex. -
overflow: hiddendoesn't scroll for the player (a script can still setscrollX/scrollY). An element it clips away entirely is skipped by keyboard and gamepad navigation, and the editor outlines only the part that's drawn.
An element with overflow: auto or scroll scrolls its children (ADR 0427):
.log { height: 240px; overflow-y: auto; flex-direction: column; overscroll-behavior: contain; scrollbar-color: #8af #0004; }-
Layout. Its content lays out unconstrained along the axis it scrolls (children keep their size instead of shrinking to fit), and its extent is the union of the children's margin boxes plus its end padding.
scrollX/scrollY(UI pixels,scrollLeft/scrollTopon the web) say how far it's scrolled; scripts write them, and they're kept between 0 and how far the content reaches past the padding box. A list whose content starts at its far end,flex-direction: column-reverseorrow-reverse, or a row indirection: rtl(HTML'sdir="rtl", which also lays the row out from the right), starts scrolled to that end, where its offset is 0, and goes negative toward the other, as browsers'scrollTop/scrollLeftdo (ADR 0432). The children are drawn, take the pointer, are found by navigation and are outlined by the editor where the scroll puts them. -
The player scrolls it with the wheel (Shift turns it sideways) over it, a touch or pen drag (past 10 pixels the press stops being a press, and a fast drag keeps going with momentum; the mouse doesn't drag-scroll), a draggable scrollbar (a press on the track pages), and keys: Page Up/Down and Home/End scroll the list the focused element is in, and with nothing focused, after a press in the list, the arrow keys do too. The wheel and drags go to the innermost list under the pointer that can still move that way, then to the lists it's in (
overscroll-behavior: containornonestops that). A wheel a UI list took isn't the game's:Input.mouseScrollDeltareads zero that frame. A scrolling panel stops the pointer over its whole box, between its children too. - Navigation scrolls the element it focuses into view.
-
Scrollbars show for
scrollalways and forautowhen the content overflows, over the content at the end edge (the vertical one on the left inrtl):scrollbar-width: auto | thin | none(10, 6 or no pixels) andscrollbar-color: <thumb> <track>.scrollbar-gutter: stablekeeps the vertical bar's room beside the content, shown or not, so the content doesn't move when the bar appears (clientWidthis that much smaller);stable both-edgeskeeps the same room on the other side too. -
Snapping (CSS Scroll Snap, ADR 0432):
scroll-snap-type: x | y | both | block | inline [mandatory | proximity]on the list, andscroll-snap-align: <block> [<inline>](start,center,end) on the elements it should rest on, withscroll-padding(the list's inset) andscroll-margin(the element's outset), andscroll-snap-stop: alwayson one a swipe mustn't pass over. The wheel snaps once it stops turning (on to the next position in the direction it went), a swipe eases to the position nearest where its momentum would end, the arrow and page keys andscrollBystep to the next position,scrollTo, Home/End and a released scrollbar thumb to the nearest, andscrollIntoViewand navigation to one that keeps the element in view.mandatoryalways rests on a position;proximityonly within 30% of the list's size of one. When the layout changes (rows added, resized or removed), the list snaps again to the element it rested on, or (mandatory) to the nearest position.
.carousel { flex-direction: row; overflow-x: auto; scroll-snap-type: x mandatory; scroll-padding: 0 16px; }
.carousel > .card { scroll-snap-align: start; }-
Scripts: an element's
scrollTo(x, y)/scrollTo({ top, left, behavior }),scrollBy,scrollIntoView({ block, inline, behavior })(start,center,end,nearest),scrollTop/scrollLeftandscrollWidth/scrollHeight/clientWidth/clientHeight(from the last layout), on Svelte nodes (bind:this) andview.query's elements.behavior: "smooth", orscroll-behavior: smoothon the list, eases there;instantjumps. -
Events:
scroll(it doesn't bubble) in the frame after the offsets changed, andscrollendonce they stop.
-
UIPanel: a box.backgroundColor(none by default),borderRadius,borderWidth,borderColor, and the paint above: a shadow, a background image or gradient, and per-corner radii. -
UIText:text,font(a font file in the project, or a generic family such asmonospace; empty is the bundled Inter),fontSize,color,fontWeight(light,normal,medium,semi-bold,bold, or a number),fontStyle,textDecoration,backgroundColorand a border (borderWidth, sides,borderColor,borderRadius; its box),whiteSpaceCollapseandtextWrapMode(CSSwhite-space),verticalAlignandcontentEditablefor inline runs and editable text,textAlign(startandendfollow the language's direction),wordBreak(break-word,break-all,keep-allfor no wrapping), and an outline:textOutlineColor(none by default) andtextOutlineWidth(UI pixels, 0 by default). The outline shows outside the glyphs, scales with the canvas like the font, and doesn't change the layout. A HUD label over a busy game takestext-outline-color: #000; text-outline-width: 3px;. -
UIImage:image(a texture asset) andfit:fillstretches it to the element,coverfills it and crops,containkeeps the texture's aspect ratio when the element's size comes from it (leavewidthorheightat"auto"). -
UIButton: a panel that takes the pointer, withhoverColor,pressedColorandinteractable. Its children are its label. -
UIInputField: a one-line text field:value,placeholder,maxLength(0: no limit),fontSize,color,placeholderColor, and the panel's style. - Buttons and input fields also take focus:
focusable,focusColor,navigationandnavUp,navDown,navLeft,navRight(below). - The form elements of the next section: checkboxes, radio buttons, sliders, text areas, drop-downs, progress bars, meters, labels and forms.
-
UIControlMapper: a ready-made controls screen that lists a player's actions and rebinds them (see Input). It draws with a built-in Svelte component on aUIViewit makes as its node's child.
HTML's form elements work as in a browser (ADR 0428). Each is an element kind of its own, styled like a panel (its box is the element: size, background, border, radius), with its marks drawn in accent-color:
| HTML | Component | Fields |
|---|---|---|
<input type="checkbox"> |
UIToggle |
checked, indeterminate (a dash until the player toggles it), name, value, accentColor
|
<input type="radio"> |
UIRadio |
checked, name, value, accentColor: one checked per name in a form (outside forms, in the canvas) |
<input type="range"> |
UISlider |
min, max, step (0: any value), value, accentColor
|
<input type="text|password|number"> (and search, email, tel, url) |
UIInputField |
type (password draws dots; number's arrow keys step it), min, max, step
|
<textarea> |
UITextArea |
an input field with rows (its height in lines) and wrap (soft or off); Enter starts a line, and it scrolls |
<select> with <option>s |
UISelect/UIOption
|
value, multiple, open; options' value, selected, label
|
<progress> |
UIProgress |
value out of max; no value: indeterminate, a moving bar |
<meter> |
UIMeter |
value, min, max, low, high, optimum: green, yellow or red by HTML's regions |
<label> |
UILabel |
for (an element id), else the control inside it |
<form> |
UIForm |
requestSubmit(), reset(), submitted
|
<form id="settings" gap="8" onsubmit={save}>
<label><input type="checkbox" id="music" bind:checked={music} />Music</label>
<label for="volume">Volume</label><input type="range" id="volume" bind:value={volume} />
<select id="quality" bind:value={quality}><option value="low">Low</option><option value="high">High</option></select>
<button>Save</button>
</form>- What the player does: a click (or Space, Enter or the south button with focus) toggles a checkbox, checks a radio and opens a drop-down. A drop-down's list is drawn above everything else in its canvas, outside its parents' clips, below it (above where it wouldn't fit); a click on an option chooses it, a press elsewhere closes it. A press on a slider jumps its thumb there and drags it. A click on a label toggles or clicks its control, or focuses a field (typing), slider or drop-down.
- Keys and the gamepad: left and right step a focused slider (Page Up/Down a tenth, Home/End its ends) and move a radio group's check; up and down leave them, as they do any control. An open drop-down's list takes up and down; Enter chooses, Escape closes. A typing number field's arrow keys step it.
-
Events:
inputthenchangewhen the player changes a control (a slider sendsinputas it moves andchangewhen it's let go); a script writing a field sends none. Each control'schangedis true for that frame. A form sendssubmit(cancelable; nothing else happens) for asubmitbutton's click (a button'stype:submit, the default,resetorbutton) or Enter in one of its fields, andreset, after which its controls go back to how they were built unless a handler prevented it. Every default action can be prevented: a checkbox'sclickhandler callinge.preventDefault()keeps it as it was. -
interactableis HTML'sdisabled(the attribute sets it): every control has it. Disabled controls draw their marks faded. -
Pseudo-classes:
:checked(checkboxes, radios, chosen options),:indeterminate(checkboxes, progress bars without a value),:disabledand:placeholder-shown(fields showing their placeholder). -
Parts (ADR 0432):
accent-coloris the simple route; part pseudo-elements style each part, by the names browsers use:::-webkit-slider-thumb(width,height,background-color,border,border-radius,box-shadow,opacity),::-webkit-slider-runnable-track(heightis its thickness, and the same paint),::-webkit-progress-bar(the bar's track, drawn over the element's own box) and::-webkit-progress-value,::-webkit-meter-optimum-value,::-webkit-meter-suboptimum-valueand::-webkit-meter-even-less-good-value(the meter's value in each of HTML's regions),::checkmark(a checkbox's mark or a radio's dot:color) and::picker-icon(a select's arrow:color). Properties a part doesn't take are ignored; a slider's fill keeps the accent colour.
input[type="range"]::-webkit-slider-thumb { width: 12px; height: 24px; border-radius: 3px; background-color: #fff; box-shadow: 0 1px 3px #0008; }
input[type="range"]::-webkit-slider-runnable-track { height: 4px; background-color: #333; }
progress::-webkit-progress-value { background-color: gold; }
input[type="checkbox"]::checkmark { color: black; }-
::placeholderstyles a field's placeholder:color,opacity(which fades its colour) andfont-style; without a rule it'splaceholderColor's grey.::selectioncolours a typing field's selected text and its highlight (color,background-color), as it does an editable text's (contenteditable). They set the fieldsplaceholderColor,placeholderFontStyle,selectionColorandselectionBackgroundColor, so transitions animate them and scripts can write them. -
Svelte bindings:
bind:checkedandbind:indeterminateon checkboxes,bind:groupon radios (the bound value is the checked one'svalue) and checkboxes (an array of the checked ones' values), andbind:valueon inputs (a number, or null when empty, fortype="number"and"range"), text areas and selects (the chosen option'svalueas given,value={2}binding the number 2; an array withmultiple). After a form's reset, the bindings read the controls again. Nodes havechecked,indeterminate,selected,options,selectedIndex,valueAsNumber,form, and on formsrequestSubmit()andreset(). An<input>whosetypechanges is made again in place as the new kind.
Panels, buttons and input fields take a shadow, a gradient or image background and a radius per corner; text takes a shadow (ADR 0422 wave 2). Write them as CSS, in a style or as attributes:
.card {
background-color: #1d2230;
border-radius: 12px 12px 0 0; /* top-left, top-right, bottom-right, bottom-left */
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5); /* offset-x offset-y blur colour */
}
.banner { background-image: linear-gradient(90deg, #336699, #66aacc 70%); }
.glow { background-image: radial-gradient(#ffffffcc, transparent); }
.wood { background-image: url(../images/wood.png); }
.title { text-shadow: 0 2px 4px black; }| Property | Takes | Fields it sets |
|---|---|---|
box-shadow |
one shadow: offset-x offset-y [blur] [colour] (black when the colour is left out), or none
|
boxShadowOffsetX, boxShadowOffsetY, boxShadowBlur, boxShadowColor (null: none) |
text-shadow |
the same, on text; inherited like color
|
textShadowOffsetX, textShadowOffsetY, textShadowBlur, textShadowColor
|
background-image |
url(path), linear-gradient([angle | to side,] stops…), radial-gradient([circle [at center],] stops…) or none
|
backgroundImage (the CSS text) |
border-radius |
one to four lengths, in CSS order | one value: borderRadius; two to four: borderTopLeftRadius, borderTopRightRadius, borderBottomRightRadius, borderBottomLeftRadius
|
-
Shadows are one shadow each:
inset, a spread and several shadows aren't supported. Offsets and blur are UI pixels and scale with the canvas. A panel's shadow is cast by its background, so a panel without abackgroundColoror gradient has none. -
Gradients: a stop is a colour and an optional position in
%; positions left out are spread evenly, as in CSS. A linear gradient's angle is indeg(alsoturn,rad,grad; default180deg, top to bottom) orto top,to right,to bottom,to left. A radial gradient is a circle at the centre reaching the farthest corner. A gradient replacesbackgroundColor, so a button with one doesn't change colour on hover. -
url()stretches the texture over the box inside the border, under the element's children; a relative path is relative to the component or.cssfile. -
Corners: a corner's field at
-1(its default) takesborderRadius, so scripts writingborderRadiuskeep working. One value inborder-radiussetsborderRadiusand puts every corner back on it;border-top-left-radius: 0after it squares just that corner. Elliptical corners (/) aren't supported. - A value that can't be read is left out and warned about once, saying why.
- Every field is also its own property (
box-shadow-blur: 8px,background-imageby attribute), and scripts write them like any field.
Performance. Babylon GUI draws the UI with Canvas2D and redraws only what changed. A shadow or gradient redraws its whole region, blur included, each time it changes, so animating one (a pulsing glow, a moving gradient) costs more CPU than animating a position, and more on large screens. Animate opacity or position where you can.
Any element can be drawn moved, turned and scaled (ADR 0422 wave 3). As on the web, layout ignores transforms: the element keeps its place in the layout and its siblings don't move. A transform applies to the element and its children, and the pointer, editor picking, the scene view's outline and handles, and keyboard navigation all follow what's drawn.
.badge { transform: translate(-50%, -50%) rotate(-8deg) scale(1.2); }
.tilted { rotate: 12deg; transform-origin: left top; }
.pressed { scale: 0.95; }
.slid { translate: 40px 0; }| Property | Takes | Fields it sets |
|---|---|---|
transform |
none, or a list of translate(x[, y]), translateX(), translateY(), scale(s[, sy]), scaleX(), scaleY(), rotate(angle), skew(ax[, ay]), skewX(), skewY(), matrix(a, b, c, d, e, f), composed left to right |
all six: translateX, translateY, scaleX, scaleY, rotate, transformMatrix
|
translate |
x [y]: px, or % of the element's own width (x) and height (y); none
|
translateX, translateY (strings like "12" or "50%"; default "0") |
scale |
one number for both axes or two (2, 1.5 1, 150%); none
|
scaleX, scaleY (default 1) |
rotate |
an angle: deg, turn, rad, grad, or a bare number of degrees; none
|
rotate (degrees, clockwise) |
transform-origin |
one or two positions: left, center, right, top, bottom, px or %
|
transformOriginX, transformOriginY (default "50%", the middle) |
-
The fields keep one translate, one rotation, one scale and a full matrix, applied the way CSS applies its
translate,rotateandscaleproperties and thentransform: the matrix, then scale, then rotate, about the origin, then translate. Atransformlist is folded into the first three when it can be, sorotate(90deg) translate(10px)becomesrotate: 90deg; translate: 0 10px. -
Skew and matrices (ADR 0430): a list that doesn't fold (one with
skew(),skewX(),skewY()ormatrix(), or a rotation after an unequal scale, which skews) is held intransformMatrixasmatrix(a, b, c, d, e, f), after its leading translates, which keep their%(translate(-50%, -50%) skewX(10deg)works). A%translate later in such a list is refused with a warning (a matrix holds pixels): write it first, or in px. Skewed elements are drawn, hit and picked exactly. -
transformand the individual properties set the same fields, so the later declaration wins for each field (CSS would apply both).transformsets all six, sotransform: scale(2)putsrotateback to 0 and clears the matrix. -
As attributes,
transform="…",rotate="45",scale="2",translate-x="10"andtransform-origin="left top"work as attributes. Thetranslateattribute stays HTML's "don't localise this" marker (ADR 0356), so writetransform="translate(…)"ortranslate-x/translate-yinstead. -
Scripts write the fields:
(view.query("#play")!.component as UIButton).rotate = 15,.scaleX = 1.1,.translateY = "-4",.transformMatrix = "matrix(1, 0, 0.2, 1, 0, 0)". -
Animating a transform tweens each field; the matrix interpolates as CSS interpolates matrices (decomposed into translation, rotation, shear and scales, each mixed, then put back together), so
skewX(0)→skewX(30deg)shears smoothly and a turn doesn't take the long way round. -
Clipping: an
overflow: hiddenelement clips its children where it's drawn, so a turned clipper clips at its turned edges, and a transformed child is clipped where the transform puts it. - Paint turns with the element: gradients, borders and rounded corners are drawn in its frame, and a shadow's offset turns and scales with it (its blur scales). 3D transforms aren't supported.
-
The scene view outlines the box as drawn and puts the handles on its turned corners. Resizing works in the element's own frame (dragging a turned edge changes its width by the distance in its own UI pixels). On an element with a transform of its own, the west and north handles change only the size, never
left/top(those are in its parent's frame). Moving an absolutely positioned element works in its parent's frame, from where layout put it. -
Input fields: the hidden DOM
<input>that takes typing (and IME composition) stays off-screen as before, so an IME's candidate window shows where the browser puts it, not next to the transformed field.
Performance. Changing a transform needs no new layout: Babylon GUI redraws only the regions the element leaves and enters. Its shadow and gradient are redrawn with it, so a transformed element with a large blur still costs what a moving shadow costs.
filter (ADR 0430) draws an element and its children through CSS filter functions: blur(), brightness(), contrast(), grayscale(), hue-rotate(), invert(), opacity(), saturate(), sepia() and drop-shadow().
.locked { filter: grayscale(1) brightness(0.7); }
.frosted { filter: blur(4px); transition: filter 0.3s; }
.icon { filter: drop-shadow(0 2px 3px #0008); }-
Each function is a field (
filterBlur,filterBrightness,filterContrast,filterGrayscale,filterHueRotate,filterInvert,filterOpacity,filterSaturate,filterSepia, andfilterDropShadowColor/OffsetX/OffsetY/Blur), so transitions and keyframes animate them and scripts write them.filtersets them all (the ones it doesn't list back to no effect). -
They apply in one fixed order, the order above, whatever order
filterlists them in. A function listed twice folds where it can (brightness, contrast, saturate and opacity factors multiply, hue-rotate angles add, blurs combine as Gaussians);grayscale,sepiaorinverttwice and several drop shadows are refused with a warning, as isurl(). - A filter applies to the subtree: its children are drawn through it too (theirs first, then their parent's). Each drawn piece is filtered as it's drawn, so a blur blurs each piece, and translucent pieces overlapping each other are filtered one by one rather than flattened first.
- Lengths (a blur, a drop shadow's offset) scale and turn with the element's transform, as shadows do. A
drop-shadowwithout a colour is black. -
Cost: a filter redraws the region it covers, grown by how far a blur or shadow reaches. Browsers with
CanvasRenderingContext2D.filter(Chromium, Firefox, Safari 18) apply it while drawing; elsewhere the element is drawn to an offscreen canvas and filtered there (blurs approximated by box blurs), which costs more for big elements.
backdrop-filter (ADR 0432) takes the same functions and applies them to what's drawn behind the element, within its box and rounded corners, under its own background: frosted glass.
.glass { background-color: #ffffff22; border-radius: 12px; backdrop-filter: blur(8px) saturate(1.4); transition: backdrop-filter 0.3s; }-
Fields:
backdropBlur,backdropBrightness,backdropContrast,backdropGrayscale,backdropHueRotate,backdropInvert,backdropOpacity,backdropSaturate,backdropSepiaandbackdropDropShadowColor/OffsetX/OffsetY/Blur, applied in the same fixed order; transitions and keyframes animate them. It's the element's own (its children don't get one), lengths through its transform; the element'sopacityfades it, itsfilterdoesn't apply to it. - What's behind is the UI drawn under it on the same texture (lower elements and canvases): the 3D scene behind the UI isn't part of it.
-
Cost: each time the element is redrawn, the texture under its box (grown by a blur's reach) is copied into an offscreen canvas, filtered (with
ctx.filter, or by reading the pixels back and filtering them on the CPU where it's missing,filterPixels) and drawn back. Anything redrawn under it redraws the whole element and the area it samples, so an animated element behind a large backdrop redraws that area every frame. Keep backdrop elements small, or few, over UI that moves.
ADR 0430. In a Svelte component:
<svg class="icon" width="24" height="24" viewBox="0 0 24 24" onclick={pick}>
<path d="M4 12 l5 5 l11 -11" fill="none" stroke="currentColor" stroke-width="2" in:draw={{ duration: 400 }} />
</svg>
<video src="asset:videos/intro.webm" autoplay muted bind:currentTime={t} bind:paused onended={next}></video>
<audio src="asset:sounds/theme.ogg" loop bind:this={music}></audio>-
<svg>is an element (UISvg); its shapes (path,rect,circle,ellipse,line,polyline,polygon,g,text,use,defs, gradients andstop…) stay an SVG document, drawn as an image of it, rasterised again only when something in it changes. Its size comes from itswidth/heightattributes or the stylesheet (300 × 150 without either, as in HTML). The stylesheet styles the<svg>itself, and itscoloriscurrentColorinside; shapes take their paint from attributes and inlinestyle. A pointer event on it goes to the shape under the pointer (by the shape's geometry and itspointer-events: by default its fill where it's filled and its stroke where it's stroked), then through its groups to the<svg>. Shapes havegetTotalLength()andgetPointAtLength(), andsvelte/transition'sdrawworks. SMIL animation (<animate>) isn't supported. -
<video>is an image whose picture is the video's current frame (UIVideo;fitworks), drawn each frame while it plays.srcis a project file (asset:videos/…) or a URL, or a<source src>inside it. A script can hand it any media element instead:(el.component as UIVideo).media = myVideoElement. There are no built-in controls. -
<audio>isn't drawn (UIAudio,display: none); it plays through the audio plugin, anAudioSourceon its node made when it first plays (on the Master bus).durationis NaN there (engine sounds don't report their length),playbackRatechanges the pitch too, and seeking (currentTime = …) jumps on the core audio backend only. -
Both have the media API on the node and the component:
play(),pause(),currentTime,duration,paused,ended,volume,muted,playbackRate,loop; media events (onplay,onpause,onended,ontimeupdate,onvolumechange,ondurationchange…;on("ended", …)on the component); and Svelte's media bindings:bind:currentTime,bind:paused,bind:volume,bind:muted,bind:playbackRate, and read-onlybind:duration,bind:ended,bind:readyState,bind:seeking,bind:videoWidth,bind:videoHeight.autoplay,loopandmutedare attributes (fields). Browsers let only muted video start without a gesture. - Headless Worlds (servers, tests) make no media element from
src; one handed tomediaworks anywhere.
A text element holds inline runs: the phrasing elements inside it, each in its own style, laid out and drawn together as one paragraph (ADR 0429).
<p class="note">You have <b>{coins}</b> coins. <a href="#shop" onclick={openShop}>Visit the <em>shop</em></a><br />H<sub>2</sub>O <code>x = 1</code> <mark>new</mark> <img src="images/coin.png" width="16" height="16" alt="" /></p>-
Runs:
span,b/strong,i/em,u,s/del,a,code/kbd,small,sub/sup,markand the other phrasing tags inside a text element (p,span,h1…) are runs;brbreaks the line;imgis an inline image, sized by itswidth/height(one em square without them) and sitting on the baseline. HTML's own defaults apply under your styles:bbold,iitalic,uandaunderlined (a link keeps the text's colour: style it),sstruck through,codemonospace,small/sub/supsmaller,markblack on yellow. -
Run styles:
color,font-size,font-weight,font-style,font-family(a font file, ormonospace,serif,sans-serif,system-ui),text-decoration(underline,line-through,overline; a run's reach the runs inside it),background-color(behind the run's glyphs; on the text element itself, its whole box) andvertical-align(sub,super,middle,top,bottom,text-top,text-bottom). Selectors match runs as elements (.note b,a:first-child). -
One paragraph: lines wrap across runs (a word split between runs stays whole), with the language's line breaking (CJK, Thai); each line is as tall as its tallest run. Its base direction is the text's
direction(its own or an ancestor's, HTML'sdir) when set, else the language's. In a right-to-left paragraph a line's runs are placed from the right; the browser orders mixed text within each run (a run that mixes directions with its neighbours is approximate). -
White space (ADR 0432):
white-space: normal | nowrap | pre | pre-wrap | pre-line | break-spaces(or its longhands,white-space-collapse: collapse | preserve | preserve-breaks | break-spacesandtext-wrap-mode: wrap | nowrap;text-wrap: nowraptoo) on plain texts and runs, inherited as in CSS.normalcollapses spaces, tabs and line breaks across runs as HTML does;prekeeps them and doesn't wrap;pre-wrapkeeps them and wraps (trailing spaces hang);pre-linekeeps only line breaks;break-spaceskeeps spaces that take room at a line's end;nowrapon a run keeps it whole on one line. Tabs stop every 8 columns. A component's text reaches the engine as written (UIText.textholds it raw) and the UI core applies the rule; an editable text keepspre-wrap. -
:hoverand:activeon runs: the run under the pointer, its inline parents and its text are:hover; the ones pressed in are:active(the engine's:pressed) while the button is held, soa:hover { color: … }restyles just that link (a colour or background change redraws without laying out again). -
Inline boxes:
padding,border(width,solid/none, colour),border-radiusand horizontalmarginon a run take room on its line before its first character and after its last; vertical padding and borders are drawn around its glyphs without making the line taller, as in CSS. A run broken across lines is sliced: its start side on its first line, its end side on its last. Itsbackground-colorfills the box. A text element itself takes a border too. -
Inline blocks:
display: inline-block(orinline-flex) on an element inside a text, and every element there that isn't phrasing text or a plain image (a<button>, an<input>, a<select>or other form control, an<svg>,<video>,<audio>, a<div>), is an atomic inline box: laid out by itself at its content's size (its own layout root), placed on the line like a word, its baseline its last line of text (else its bottom margin edge) unlessvertical-alignsays otherwise, and drawn and hit-tested as its own element. A<button>in a<p>clicks as any button, and its events bubble through the text. An<img>withdisplay: inline-blockbecomes such a box too (padding, margins,fit); without it, it's an inline image as above. -
Links and the pointer: a press on a run goes to the run's element (
e.targetis the<em>inside the<a>), and bubbles through its inline parents and the text, soonclickon an<a>hears clicks on any part of it.hrefstays on the node (e.currentTarget.getAttribute("href")): a game decides what a link does. -
{@html value}parses inline HTML into nodes: inside a text element its phrasing tags are runs; block elements (div,p,ul) become panels as anywhere else.<script>,<style>,<iframe>and the like are dropped with their content, and so are event attributes (onclick="…") andjavascript:URLs. A node'sinnerHTMLcan be set the same way. Only games that use{@html}orbind:innerHTMLload the parser. -
Messages with tags: a string table message may carry the inline subset (
You have <b>{count}</b> coins); translators keep the tags.{@html tHtml("hud.coins", { count })}draws it as runs:tHtmlescapes every string argument, so a player's name can't add markup. -
Editable text:
contenteditableon a text element lets the player edit it: a press puts the caret (drag or Shift+press selects), typing and the IME go through the hidden text area as for input fields, Enter starts a line, Escape or a press elsewhere leaves it, and each edit sendsinput(andfocus/bluras it starts and ends). Runs keep their styles; text typed between runs takes the style of the run before it. Whitespace is kept as typed.bind:textContent,bind:innerTextandbind:innerHTMLread and write it. There are no formatting commands (bold, lists);contenteditableworks on text elements only (<p>,<span>), not on a<div>.
Styles animate as CSS does (ADR 0422 wave 4): a transition eases a field from its old value to its new one when a class, a pseudo-class (:hover, :focus…) or an attribute changes it, and an animation plays @keyframes while an element has it, starting when the element appears or when its animation-name changes.
.button { background-color: #335; transform: scale(1); transition: background-color 150ms ease-out, transform 150ms; }
.button:hover { background-color: #558; scale: 1.05; }
.toast { animation: slide-in 300ms ease-out, fade 300ms ease-in 3s forwards; }
@keyframes slide-in { from { translate: 0 -40px; opacity: 0; } }
@keyframes fade { to { opacity: 0; } }
.spinner { animation: spin 1s linear infinite; }
@keyframes spin { to { rotate: 360deg; } }| Property | Takes |
|---|---|
transition |
comma-separated property duration timing-function delay behavior in any order (the first time is the duration, the second the delay); none
|
transition-property |
all, none, or property names; a shorthand covers its longhands (padding its sides, transform the transform fields, box-shadow the shadow's fields, border-radius the corners) |
transition-duration, transition-delay
|
times: 0.3s, 300ms (a negative delay starts part-way) |
transition-timing-function |
linear, ease, ease-in, ease-out, ease-in-out, cubic-bezier(x1, y1, x2, y2), steps(n[, jump-start | jump-end | jump-none | jump-both | start | end]), step-start, step-end, linear(0, 0.25 75%, 1) (stops of an output and up to two input percentages, ADR 0432); the same list for animation-timing-function
|
transition-behavior |
normal (values that don't interpolate change at once) or allow-discrete (they transition too, flipping half way; ADR 0432) |
animation |
comma-separated name duration timing-function delay iteration-count direction fill-mode play-state in any order |
animation-name |
@keyframes names, or none
|
animation-iteration-count |
a number (2.5 ends half way through the third) or infinite
|
animation-direction |
normal, reverse, alternate, alternate-reverse
|
animation-fill-mode |
none, forwards (hold the last value), backwards (show the first keyframe during the delay), both
|
animation-play-state |
running, paused (toggle it with a class to pause and resume) |
-
What animates: numbers (opacity, sizes in px,
font-size,gap,z-indexrounded…), lengths (width,left,translate…: px with px,%with%; a mixed pair orautojumps half way), colours (in linear RGB), the transform fields, shadow fields, per-side padding, margins and borders, and corner radii. A side left unset animates from its all-sides value, and a shadow fromnoneanimates from a transparent one. Other fields (choices likeflex-direction, text, images) change at once in a transition, unless it'sallow-discrete(ADR 0432), and jump half way between keyframes.displayto or fromnonekeeps the value that isn'tnonefor the whole of it, sotransition: opacity 0.3s, display 0.3s allow-discretewithdisplay: nonefades an element out before it's gone. -
@keyframestakefrom,toand percentages (0%, 50% { … }lists several). A keyframe can setanimation-timing-functionfor the segment that starts at it. A missingfromortouses the element's own value, so@keyframes fade { from { opacity: 0 } }fades in to whatever opacity the element has. The last@keyframeswith a name wins. -
These are styles, not fields: set them in rules, as attributes (
<div class="x" transition="opacity 0.2s">) or in astyle. A script starts and stops them by changing classes or attributes. -
A script writing a field that's transitioning or animating takes it over at once, as an inline style would:
(el.component as UIPanel).opacity = 1stops that field's transition (notransitionend) or that field of the animation. -
Time: animations run on the World's unscaled clock, so UI still animates with
Time.timeScale = 0(a pause menu). They start in the frame of the change. - Interrupting: a transition interrupted by another change starts again from the value showing, towards the new value. Changed back to where it started part-way (a hover that ends half way), it runs back over the share of its duration it had covered, as CSS's reversing shortening does (ADR 0432): half way through a 1 s transition, the way back takes 0.5 s.
-
Inherited values (
color,font-sizeand the other text properties) pass through to children frame by frame while a parent's transition or animation runs (ADR 0432), on any element: a panel or button that has no colour of its own still transitions the colour its text inherits. A child that sets the property itself, or transitions it itself, keeps its own. -
Events:
el.on("transitionend", e => …)withe.propertyName(kebab-case) ande.elapsedTime;animationstart,animationiterationandanimationendwithe.animationName. Like other UI events they arrive in the frame after they happened. Listen on the element fromview.query(UIViewElement.on). - The Inspector shows a field that's animating as Transition or Animation, over the rule or attribute it animates to.
- Scenes being edited don't animate: the editor shows each element's styled values.
-
Not supported:
animation-composition,animation-timeline,@starting-styleandtransitioncancel. Changing an animation's duration or timing while it runs takes effect when it next starts (its play state applies at once). Lengths inemfollow a transitioningfont-sizewhen the element is next restyled, not frame by frame.
How it runs. Transitions and keyframe segments run as tweens on the engine's tween core (ADR 0424): the animation core's when the animation plugin is on, otherwise a small standalone tween module that loads the first time a view's styles animate. Timing functions become engine curves (a cubic Bézier is exactly one Bézier segment). Measured headless (no drawing): 500 elements each transitioning a colour and a number cost about 1 ms a frame, and the frame that starts all 1,000 transitions about 17 ms (9 without transitions). Animating paint (shadows, gradients, colours of large boxes) also redraws regions each frame (see Paint above); opacity and transforms are the cheap things to animate.
ADR 0422 wave 5 brings the selectors, math and media queries web stylesheets use, and ADR 0432 adds :has() and relative lengths. They work in components' styles and in queries (view.query(…), a node's querySelector).
.row:nth-child(odd) { background-color: #ffffff10; }
.row:not(:last-child) { border-bottom-width: 1px; }
.tab + .tab { margin-left: 4px; }
h2 ~ p { color: #aab; }
input[type="checkbox"] { width: 24px; }
[data-state="open" i] .chevron { rotate: 90deg; }
.slot:empty { opacity: 0.4; }
.card:has(> .badge) { border-color: gold; }
.field:has(input:focus) { background-color: #ffffff18; }
label:has(+ input:disabled) { opacity: 0.5; }
.title { font-size: 1.5rem; margin-bottom: 0.5em; } .hud { width: min(90vw, 1200px); height: 10vh; }
.sidebar { width: calc(30% - 2 * var(--gutter)); min-width: max(160px, 20%); padding: calc(var(--gutter) / 2); }
@media (max-width: 900px) { .sidebar { display: none; } }
@media (orientation: portrait) and (min-aspect-ratio: 9/20) { .hud { flex-direction: column; } }-
Selectors:
:not(list)(with complex arguments::not(.a .b)),:first-child,:last-child,:only-child,:nth-child(an+b [of S]),:nth-last-child(),:first-of-type,:last-of-type,:only-of-type,:nth-of-type(),:nth-last-of-type(),:empty,:root, attribute selectors[a],[a=v],[a~=v],[a|=v],[a^=v],[a$=v],[a*=v](each with aniflag for case-insensitive values), and the sibling combinators+and~. Specificity is CSS's: attribute selectors and pseudo-classes count like classes,:not(),:has()and:nth-child(… of S)add their most specific argument. -
:has()(ADR 0432) takes relative selectors::has(.x)(a descendant),:has(> .x)(a child),:has(+ .x)(the next sibling),:has(~ .x)(a later sibling), each with more compounds after it (:has(> .a .b)), in a list.:has()inside:has()isn't supported. With:has()in the styles, an element appearing, going or moving, or changing class, attribute, text or state (:has(:hover),:has(input:focus)), restyles the ancestors (and with+/~, the earlier siblings) that could match it: only those whose tag, id and classes fit a:has()compound, each alone, and its subtree only when what it passes on changed. With no:has()in any stylesheet this costs nothing. -
Pseudo-elements (ADR 0432) end a selector:
::before,::after(also:before,:after),::placeholder,::selectionand the form parts. The rest of the selector matches the element they belong to, sobutton:hover::beforeworks; a pseudo-element counts as a type selector in specificity. Nothing may follow one (::before:hoveris refused), and they can't be inside:is(),:not()or:has(). Queries never return them (view.query("p::before")is null, asquerySelectoris). -
::beforeand::afterwithcontent(strings,attr(name)of the element, both concatenated:content: "(" attr(data-count) ")") generate an element first or last inside theirs, styled by their rules and inheriting from it;content: noneornormal(or nocontent) generates nothing. Inside a text element (<p>,<span>…) it's an inline run before or after the text; elsewhere a box (a panel, its text a label inside), laid out as a first or last child:content: ""with a size and background is a decoration. It's not an element of the component: queries, children, structural selectors and:emptydon't count it, and its pointer events go to its element (a click on a::beforeclicks the button). It restyles with its element (its classes, attributes, state, the rules), and transitions like any element. Counters, quotes and images incontentaren't supported; nor are::beforeon replaced elements and controls (inputs, images, media, selects), as in browsers. -
Positions count elements, not text: a button's label text doesn't make the
<span>after it a second child.:emptyis an element with no child elements and no text.:rootis the tree's root: a view's canvas (where:global(:root) { --accent: … }declares a theme's variables). -
Attributes are matched as written: an element's attributes as the component writes them,
data-*,aria-*,typeand other HTML-only ones included. Names match in any case. -
Restyling: adding, removing and reordering elements (Svelte's
{#each}and{#if}) restyles their siblings when the styles use structural selectors or+/~; a class or attribute change restyles the element, and its siblings with them. New elements start no transitions from their first styles when their later siblings arrive; a class you add after a view has rendered transitions as usual. -
calc()takes+ - * /, parentheses, nestedcalc()andvar(), over numbers, lengths and angles;min(),max()andclamp()take values of one unit. A result in pixels only (or a number) is worked out in the cascade (calc(2 * 8px)is16px). A length mixing%and px (calc(100% - 24px)) is kept for layout (the field holdscalc(100% + -24px)), onwidth,height,top/right/bottom/left, the min/max sizes andflex-basis: the UI core resolves it against the parent's content box from the last layout, and lays out once more in the same frame when that size changed. Padding, margin and borders take pixels only, so they refuse a mixedcalc(). An expression that can't work out (10px * 2px,10px + 2, a division by zero) is left out and warned about once. -
Relative lengths (ADR 0432) work anywhere a length does,
calc()included:emis the element's font size (insidefont-size, its parent's),remthe root's (a:root { font-size: … }rule, else 16px), andvw,vh,vmin,vmaxa hundredth of the canvas's width, height, smaller or larger side, in UI pixels after the canvas scaler, as@mediasees it (before the first layout, and in headless Worlds, its reference resolution). They become pixels in the cascade (calc(50% + 1em)is kept for layout ascalc(50% + 16px)), so a font size or canvas size change restyles them: the tree restyles when the canvas changes size if a stylesheet or an inline style uses viewport lengths.:rootrules now also give the text properties every element inherits (:root { color: #eee; font-size: 18px }), as on the web. -
@mediamatches the canvas, not the browser window:width,height,aspect-ratio(each withmin-/max-and in range form,(600px <= width < 1200px)) andorientation, in UI pixels after the canvas scaler, so a 1280×720-reference canvas matching height on an 800×600 window is 960×720.and,or,not, nested@media, media types (screenandallmatch,printnever) and query lists work. Rules match again when the canvas changes size (the frame after, from the last layout); a view's first size isn't a change, so it starts no transitions. Before the first layout (headless Worlds) only size-free queries match.@keyframesinside@mediaisn't supported. -
Svelte:
MediaQueryfromsvelte/reactivityfollows the same canvas (new MediaQuery("min-width: 1000px").current), and so doesmatchMediaon<svelte:window>'s window.
@media (prefers-reduced-motion: reduce) and @media (prefers-color-scheme: dark) (and their boolean forms, (prefers-reduced-motion)) match the player's preferences (ADR 0431), as do Svelte's prefersReducedMotion and new MediaQuery("prefers-color-scheme: dark"). They come from UIPreferences:
import { UIPreferences } from "myco";
UIPreferences.reducedMotion = true; // an options menu's switch; null follows the system again
UIPreferences.colorScheme = "dark"; // "light" | "dark" | null
UIPreferences.onChange(() => console.log(UIPreferences.reducedMotion, UIPreferences.colorScheme));
UIPreferences.reset(); // follow the system for bothUntil the player chooses, each follows the system's setting (the browser's or desktop window's, live); outside a browser it's no reduced motion and light. A choice is saved in player storage (settings, myco.ui) and comes back the next time the game starts, before its first scene. Rules restyle when a preference changes.
-
Not supported:
:has()inside:has(),::first-line/::first-letter, namespaces in attribute selectors, and!important(specificity and:where()cover it).
A component handles its own events (onclick, bind:value) and takes data as props. A script reaches a view on its node: it passes props, which are reactive, and finds rendered elements with selectors. Element fields are plain values: change them at runtime and the UI follows that frame.
import { GameBehavior, UIButton, UIText, UIView, behavior } from "myco";
@behavior("game.MainMenu")
export class MainMenu extends GameBehavior {
private view!: UIView;
start() {
this.view = this.node.getBehavior(UIView)!;
this.view.props = { score: 0, onplay: (name: string) => startGame(name) };
void this.view.ready.then(() => {
this.view.query("#name")!.on("submit", (e) => startGame(e.element.value ?? ""));
});
}
update() {
const play = this.view.query("#play")?.component as UIButton | undefined;
const title = this.view.query("#title")?.component as UIText | undefined;
if (play && title) title.text = play.hovered ? "Ready?" : "King of Pirates";
}
}-
view.propsis what the component's$props()sees:view.props.score = 10shows that frame.view.readyresolves once it's mounted;view.exportsholds the root component's exports. -
view.query(selector)andview.queryAll(selector)find rendered elements (the canvas isview.root); an element has its ownquery,id,classes,node,component(the UI component:as UIButton),value,click(),focus(),rect()and scrolling. Its classes and attributes belong to the component: change them there (class:on={lit}), not from a script. -
on(type, handler, { capture, once })on an element (offremoves it):click,input,change,submit,focus,blur,transitionend,animationstart,animationiterationandanimationend(see Animation above), and the pointer, key, focus and drag events below. In a component, the same events are attributes (onclick,onkeydown…). -
Events travel through the element's ancestors as DOM events do (ADR 0426): handlers added with
{ capture: true }(onclickcapture) hear an event on its way down, from the root, before its target; then the target's; then, for the types that bubble, the parents' on the way back up, and out of the view to<svelte:body>,<svelte:document>and<svelte:window>. So one handler on a list hears clicks on all its rows (e.targetis the row,e.currentTargetthe list, in a component).e.stopPropagation()ends the trip after the current element,e.stopImmediatePropagation()at once.click,input,change,submit, the pointer and key events,wheel,focusin/focusoutand drags bubble;focus,blur,pointerenter/pointerleave,scrolland the animation events don't. -
Pointer events go to the element under the pointer that stops it (its raycast target, below):
pointerover/pointerout,pointerenter/pointerleave,pointermove,pointerdown/pointerup(any button),clickon the element the press and the release share (any element, not only buttons; not in a button that isn'tinteractable),dblclick,contextmenu(a right press),wheel, andpointercancelwhen a touch drag starts scrolling.e.clientX/e.clientYare canvas UI pixels (asgetBoundingClientRectboxes),e.offsetX/e.offsetYthe target's own pixels,e.canvasX/e.canvasYthe drawing canvas's CSS pixels;e.button,e.buttons,e.pointerType,e.detail,e.deltaX/e.deltaYand the modifier keys are there too. -
Keys:
keydownandkeyupon the focused element (withe.keyande.codeas the DOM names them), bubbling. Focus:focusin/focusoutbubble afterfocus/blur, withe.relatedTarget. -
Drags between UI elements: an element with
draggable(draggable="true") pressed and moved past 4 pixels sendsdragstart(put data one.dataTransfer.setData("text", …)),dragwhile it moves,dragenter/dragover/dragleaveon the elements under the pointer,dropwhere it's released if adragoverthere was prevented (e.preventDefault()says "drop here"), thendragend. A drag isn't a click. -
Default actions run after an event's handlers unless one calls
e.preventDefault(): apointerdownfocuses what it pressed (and starts a field typing), awheelor a touch drag scrolls, akeydownscrolls (Page Up/Down, Home/End, arrows),dragstartstarts the drag, and Enter'skeydownin a field submits it. Typing itself can't be prevented: it reaches the field through the browser before the frame's handlers run. -
Rows made at runtime (a list of rooms, a crew, markers) are an
{#each}over a prop or shared state.
A button's state, read any time:
-
hovered: the pointer is over it (and it's interactable). -
pressed: from a press on it until the pointer button is released. -
clicked: true for the one frame a click finished: pressed and released over the same button, likeInput.getMouseButtonUp.
A button's or field's focused is true while it has focus; set it to focus or unfocus it from a script (one element has focus at a time). A field's typing is true while it takes the keyboard: setting focused = true on a field, or clicking it, also starts typing. changed is true for the frame after the player changed its value and submitted for the frame after Enter was pressed in it. A script writing value is never a change.
clicked, changed, submitted, focusedChanged and the focus and blur events all happen in the frame after the player acted (with the pointer; in the same frame with keyboard and gamepad navigation, before any script runs), and every script phase of that frame sees them, fixedUpdate included. A script's own focus changes are never events. Focus a press gives is its pointerdown's default action, so it's taken in that frame's event step, after the handlers (before behaviors' update).
Each frame, before any script runs, the pointer is tested against the UI's raycast targets (below): screen canvases from the highest sortOrder, the topmost element first (later siblings draw over earlier ones), then world canvases, nearest first. When it's over one:
-
Input.pointerOverUIis true. - That frame's mouse presses go to the UI:
Input.getMouseButtonDownreports false for them. A press that began on UI stays the UI's until it's released:getMouseButtonandgetMouseButtonUpreport false for it too. - A press that began in the game stays the game's, even when it's released over a button (which then isn't clicked).
Raycast targets (ADR 0385). Every element has raycastTarget, like Unity's Graphic.raycastTarget, on by default. Text, images, buttons and input fields stop the pointer, and so does a panel with a backgroundColor (a transparent one too: an invisible click blocker) or a border; a panel with neither is a layout box and the pointer passes it. A press on text, an image or a panel goes to the UI and does nothing; inside a button, it presses the button (a button's label passes its clicks to the button). Turn raycastTarget off for decoration over the game, such as a HUD's markers or a hint line, so clicks reach the game through it (raycast-target="false" as an attribute, or raycast-target: false in a style). It's per element: children keep their own. A button with raycastTarget off is pressed only through a child that stops the pointer.
A button with interactable off still blocks the pointer from the game, but isn't hovered, pressed or clicked.
Pressing a button or an input field focuses it (a field starts typing); pressing anywhere else unfocuses it. Escape stops typing, keeping the field focused. Typing goes through a hidden DOM <input>, so IME, paste and the OS's text tools work. While a field is typing, Input.keyboardOverUI is true and Input.getKey, getKeyDown, getKeyUp and anyKeyDown report false for keys, so typing a name doesn't move the ship.
Only a World that takes local input routes the pointer. The editor's scene view shows a scene's UI but doesn't route clicks to it (they select); in play mode the game World routes as usual.
Menus work with the arrow keys, Tab, Enter and Escape, and with a gamepad's d-pad, left stick, A and B, with no game code (ADR 0340). It's Unity's selectable navigation and Godot's focus neighbours.
Focus. A World's UI has at most one focused element: a UIButton or UIInputField that is active, visible, focusable (default true) and, for a button, interactable. A press focuses what it hit, a script sets focused, and navigation moves it. Losing what made it focusable (hidden, disabled, made non-interactable) loses focus.
The UI actions. Navigation is driven by an engine action set, engine.UIActions, bound in the engine's ui context:
| Action | Defaults | Does |
|---|---|---|
navigate |
arrow keys, d-pad, left stick | moves focus up, down, left or right |
submit |
Enter, Space, south button (A) | clicks the focused button; on an input field, starts typing |
cancel |
Escape, east button (B) | records a cancel on the focused element's canvas |
next, previous
|
Tab, Shift+Tab | move focus in tree order, wrapping within the canvas |
navigate, next and previous repeat while held: at once, then after 0.4 s every 0.1 s. Turning navigate to another direction while it's held (rolling from one arrow key to the next, sweeping the stick round) moves at once too. The ui context is on for a player only while their World's UI has focus, at priority 1000, so a focused menu's arrows, d-pad, Enter, Space and Escape don't also move or pause the game; with nothing focused, the game gets every control. Players rebind it like any other context (Input).
Pressing a button focuses it, so Space and Enter then press it until focus moves on (as in Unity). Give HUD buttons that shouldn't take the keyboard focusable = false.
Where navigate goes. From the focused element's box, to the nearest focusable element of the same canvas in that direction: candidates whose centre lies in a 90° cone opening from the box's edge (or that line up with it across the direction), scored by distance with a penalty for being off-axis. Per element:
-
navUp,navDown,navLeft,navRight(nodes in the same canvas) override the search in their direction. -
navigation:auto(default) takes the neighbours, else the search;explicitonly the neighbours;nonedoesn't leave the element withnavigate(nextandpreviousstill do).
Submit and cancel. submit on a button is a click: clicked and onclick handlers see it like a pointer click. cancel sets UICanvas.canceled for that frame ((view.root!.component as UICanvas).canceled), so Escape or B backs out of a menu; Escape is also a keydown on the focused element, bubbling out of the view to <svelte:window onkeydown>. Navigation's events (clicked, focusedChanged, focus, blur, cancel) happen in the same frame, before any script runs, and every script phase of the frame sees them.
Canvases.
| Field | Meaning |
|---|---|
autoFocus |
When the canvas becomes active, focus firstSelected, else its first focusable element: a pause menu gets focus without script. |
firstSelected |
The element autoFocus, modal and navigate with nothing focused start on. On a UIView, the id of an element its component renders (options or #options), which follows the element that has the id as the view renders; empty: the first focusable element. |
modal |
While it has a focusable element, focus can't leave it: focus elsewhere moves in, and presses outside don't take it (they still press what they hit). |
player |
The local player whose UI actions drive it (-1, the default: any local player), for split-screen menus. The ui context is on only for that player. |
With nothing focused, navigation acts on the highest sortOrder screen canvas that has a focusable element (but the ui context is off then, so only your own bindings of engine.UIActions reach it).
Input fields. Navigation focuses a field without typing in it; submit starts typing. While it's typing, the keyboard types (arrows move the caret); only Tab and Shift+Tab (to the next or previous element), Escape (stops typing, keeping focus) and the gamepad leave it.
Showing focus. focusColor is a button's fill (under hover and pressed) and an input field's border, drawn while it has focus and the last UI input was navigation. Moving or pressing the pointer hides it, so mouse users don't see a stray highlight.
In a component. The same rules, as attributes: focusable="false", focus-color, navigation="explicit", nav-up, nav-down, nav-left and nav-right (element ids in the same view, which follow the element that has the id as the view renders). The canvas's autoFocus, modal, firstSelected and player are the UIView's fields (firstSelected an element id: firstSelected: "resume").
<div flex-direction="column" gap="12">
<button id="resume" nav-up="quit" onclick={close}>Resume</button>
<button id="options">Options</button>
<button id="quit" nav-down="resume">Quit</button>
</div>
<svelte:window onkeydown={(e) => e.key === "Escape" && close()} />Make a component with the Assets panel's Create > UI > New Svelte Component (it goes in ui/), add a UIView to a node and set its component to the .svelte asset.
The view makes the canvas itself (its fields are the canvas settings: mode, referenceResolution, matchHeight, sortOrder, pixelSize, modal, autoFocus, player), so a component never writes a canvas tag:
<script lang="ts">
let { title, coins = 0 }: { title: string; coins?: number } = $props();
let name = $state("");
</script>
<section class="panel" flex-direction="column" gap="4">
<h1>{title} ({coins})</h1>
<input bind:value={name} placeholder="Your name" onsubmit={() => console.log(name)} />
<button onclick={() => coins++}>Add</button>
</section>
<style>
.panel { background-color: #112233; padding: 8px; }
h1 { color: var(--accent); }
:global(:root) { --accent: #ffcc00; }
</style>-
Tags are HTML names.
div,section,nav,ul,li… are panels;span,p,h1–h6,b,em… are text;imgis an image;buttona button;input(by itstype),textarea,select,option,progress,meter,labelandformare the form elements. Other tags warn once and are panels. -
Attributes are fields in kebab-case (
flex-direction="column",font-size={24}).class,id,style,class:andstyle:feed the cascade. HTML-only attributes (type,alt,aria-*,data-*…) stay on the node. -
Text inside a text tag is its text; tags inside it are inline runs (
<p>Hi <b>you</b></p>draws "you" bold, in one paragraph). Text anywhere else becomes its own text element (a button's label). -
Events:
onclick,oninput,onchange,onsubmit,onfocus,onblur,onpointerenter,onpointerleave, and the pointer, key, focus, drag and scroll events of Scripting (onpointerdown,onmousedown,onwheel,onkeydown,onfocusin,ondragstart,onscroll…), or the olderon:clickform with its modifiers (|once,|preventDefault,|stopPropagation,|capture,|passive). They come from the UI core, so the mouse, touch, keyboard and gamepad all reach them, and their changes show in the same frame. They travel through the nodes as DOM events do:onclickcapture(oraddEventListener(type, fn, { capture: true })) hears an event on its way down, and one that bubbles out of the view goes on to<svelte:body>,<svelte:document>and<svelte:window>(so<svelte:window onclick>hears clicks on the UI).e.targetis the node it happened on,e.currentTargetthe one listening;e.currentTarget.valuereads an input field.node.dispatchEvent(event)propagates the same way (byevent.bubbles). -
Bindings:
bind:value,bind:checked,bind:indeterminateandbind:groupon the form elements, andbind:this, which gives a node with an Element subset for actions and attachments:setAttribute/getAttribute,classList,style(node.style.color = "red"),dataset,addEventListener/dispatchEvent,focus/blur(the UI's focus),getBoundingClientRect(in canvas UI pixels, through transforms),closest/matches/querySelector,contains,parentElement/children/nextElementSibling…,value,textContent, and scrolling (scrollTop,scrollHeight,scrollTo,scrollIntoView…). -
The window:
<svelte:window>,<svelte:document>and<svelte:body>work.onkeydown/onkeyupget the keys the game gets (none while a text field is typing) and the ones that bubble out of the focused node,onpointerdown/onpointerup/onpointermove/onwheelthe pointer outside UI and what bubbles out of the view, andonresizefires when the view's canvas changes size. The window is the canvas in UI pixels, the units ofgetBoundingClientRectand@media:bind:innerWidth/bind:innerHeight(andouterWidth/outerHeight) are the canvas's size after the canvas scaler (960×720 for a 1280×720-reference canvas matching height on an 800×600 window),bind:devicePixelRatiois device pixels per UI pixel, andwindow.matchMedia(query)(andsvelte/reactivity'sMediaQuery) answers against it, withchangeevents. With several views, that's the first view's canvas.bind:onlineand<svelte:document bind:activeElement>(the focused element) work too. -
<svelte:head>: its<title>sets the browser tab's or the desktop window's title; anything else in it is ignored with a warning. -
Localised text:
import { t } from "myco"and write{t("menu.start")}or{t("hud.coins", { count })}: the message in the current language, asLocale.t, which followsLocale.setLanguage(and string table edits) in the same frame. A message with inline tags (You have <b>{count}</b> coins) draws as runs through{@html tHtml("hud.coins", { count })}(below). In the editor, select an element with literal text and use the Inspector's Localisation section: Localise… picks a key, Extract to string table… adds the text to a table under a new key; either writes{t("key")}(orplaceholder={t("key")}) into the source and importst(Ctrl+Z undoes it), and Unlink writes the text back. The Localisation panel's Report lists literal text that isn't localised yet (Dismiss leaves one out;translate="no"on an element leaves out its text) and Check text fit lays each language out in the boxes the open scene's views render. -
Styles are Svelte's: a component's
<style>is scoped to it (<svelte:options css="injected" />works too);:global(...)rules apply to everyUIViewin the World (one theme for the HUD and the pause menu). Selectors match the tag as written (button,div), in any case, and:is()/:where()work (:where()adds no specificity), as do the wave 5 selectors,calc()and@media, and:has()and relative lengths. -
Scripts pass data through
view.props, which is reactive (view.props.coins = 10shows that frame), wait forawait view.ready, and find elements withview.query("#play")/view.queryAll(".row"). Disabling or removing the view unmounts the component; enabling it mounts it again with fresh state and the same props. -
The component's exports:
view.exportsholds what the root component exports (export function reset() {…}in its<script>isview.exports.reset()), null until it's mounted and a new object each time it mounts again. -
Errors in boundaries: set
view.transformError = (error) => …to turn an error a<svelte:boundary>catches into what itsfailedsnippet andonerrorget (a message safe to show, an error id), as Svelte'smountoption of that name; it's read when the error is caught. -
inert(HTML's attribute) takes an element and everything inside it out of the pointer (presses pass to what's behind), focus and navigation, while it's still drawn. Svelte's outros set it on outroing elements. -
Shared state goes in rune modules (
ui/score.svelte.ts:export const score = $state({ value: 0 })), which components and scripts both import (import { score } from "../ui/score.svelte"). -
Plain
.cssfiles a component imports (import "./theme.css") apply to everyUIViewin the World, like:globalrules. A.cssfile nothing imports isn't loaded. -
addComponent(UIPanel)and the other UI components stay refused: a view's render makes them.
Compiling. Components (.svelte), rune modules (.svelte.ts, anywhere in the project) and the .css files they import compile with the project's scripts, in the editor and when you export:
- In the editor they compile when the project opens and again whenever you save one (in the Code panel or outside the editor), or create one. A mounted
UIViewshows the new version in its next frame and keeps itsprops(hot reload); its own state starts over. A compile error is reported like a script's (the status line, with the file and line), and the view keeps showing the last version that compiled. - Play's type check covers rune modules (Svelte's runes and modules are known to the Code panel's TypeScript service). Inside
.sveltefiles, the Svelte compiler's errors are reported, but types aren't checked yet (no svelte-check). -
Built-in components: the engine's own UI (
UIControlMapper's screen,SubtitleDisplay's rows) is Svelte too, served at@myco/ui/paths. The editor has them always; a game build compiles the ones the project uses (a scene, prefab or script namingUIControlMapperorSubtitleDisplay) into the game's code with its own components. -
Spaces and line breaks: text collapses runs of whitespace and line breaks, as in HTML (
white-space: normal), whether it's written as content or given in thetextattribute. To keep them (a readout of several lines, columns padded with spaces), style the element withwhite-space: pre-wrap(orpre,pre-line), as the samples' HUDs do (ADR 0432). - A game build compiles them without the editor's debugging information. The
.svelteand.svelte.tsfiles don't ship: their compiled code does, with Svelte's runtime and the engine's renderer from the player, never the compiler. Styles are parsed when they compile, so a game that uses only Svelte UI doesn't load the CSS parser.
Editing in the editor (ADR 0423 wave C). A UIView in the scene being edited shows its component as it renders, and the editor edits its static parts by writing back to the .svelte source:
Inline SVG, <video> and <audio> work (above), and svelte/transition's blur and draw too.
Motion. svelte/transition, svelte/animate and svelte/motion (Tween, Spring, tweened, spring) run on the engine's frames and the game's unscaled clock (a paused game's menus still move), headless too, so engine.step drives them in tests. A value a tween or a tick transition computes shows in the frame it's computed. To honour a player who prefers less motion, read prefersReducedMotion.current from svelte/motion (or write @media (prefers-reduced-motion: reduce) rules): it follows UIPreferences (above).
- Selecting. The Hierarchy lists the view's rendered elements under its node (muted, with a ◇), and clicking UI in the scene view selects the element under the pointer (a button's label selects the button; the view's canvas selects its node). A selection is the element's place in the file (its line and column), so it stays selected across re-renders and hot reload.
-
The Inspector shows its fields and where each value comes from: a literal attribute or the literal
style(with the file and line), an expression (width={w},style:color={c}, text with{…}: shown as written, view-only), a scoped or:globalrule (the selector as written, in the component's<style>or an imported.cssfile), inherited from an ancestor, the text, the default, or a transition or animation running over it. Clicking a source opens that file in the Code panel at the line. -
Editing a field writes a literal attribute in kebab-case (or changes the literal
stylewhere it declares the property), overriding rules and inheritance; ✕ removes it. The id, the staticclassattribute and literal text edit in place, and Move to class moves the element's literal attributes and style declarations into a class rule in the component's<style>(made at the end of the file if it has none). -
Scene-view handles resize and move static elements (
width/height,left/top, or reordering among flex siblings), each drag one undo step; Escape puts the file back. Sizes in%stay percentages; Shift keeps the aspect ratio. -
The Create menu inserts tags (
div,span,p,h1,button,img,input, and the form elements) into the selected element's component, as its last child (after it, when it isn't a container); with the view's node selected, at the end of the component's top level. Rows also rename (the id), duplicate, delete and drag to reorder within the file. -
View-only: expressions, the rows of an
{#each}and a{#snippet}'s elements (one place in the file renders them many times), and a child component's insides (written in its own file: edit a view of that component). They select and show their sources; edits are refused with the reason in the status bar. - Every edit changes only its own text (comments and formatting stay), is one step on the scene's undo history (Ctrl+Z, the History panel), and recompiles the project's code, so the view hot-reloads. Samples are read-only, and nothing edits while playing.
Not yet: npm packages that import Svelte, and type checking inside .svelte files.
How much of Svelte works is measured by npm run test:svelte-conformance, which runs Svelte's own runtime tests against the engine's renderer (see the 0423 row of the implementation status).
A view renders its elements in any World. Only a World with a render backend lays them out and draws them, so a server or a test can build UI without WebGL; there the pointer and typing do nothing and navigation has no layout to move focus through (a script's focus still takes submit and cancel). Tests click, hover, type and navigate through a UI core and Input, as a player does (engine/tests/uiPointer.ts, engine/tests/uiNavigation.test.ts).
- Form controls' part pseudo-elements take the properties listed above only (no
::-webkit-meter-bar,::-moz-*or a slider's fill); there's no<datalist>,<optgroup>labels,<input type="date|color|file">(drawn as text fields) or on-screen number spinners; a text area's caret ignores soft-wrapped lines.flex-wrap: wrap-reversedoesn't move where scrolling starts; snap areas ignore transforms. - Events from the pointer go only to elements that stop it (raycast targets): a click on a bare layout panel's gap goes to the game, not to the panel's handlers. Touch events (
touchstart…) aren't sent; touches arrive as pointer events. -
::placeholdertakes colour, opacity and slant (not a font size, weight or family);::selectionis per element (a parent's rule doesn't reach its children's text), and a text area's selection, like its caret, follows line breaks, not soft wraps. Abackdrop-filterdoesn't sample the 3D scene behind the UI. - No 3D transforms, SVG filters (
filter: url(…)) or SMIL animation in inline SVG. Stylesheet rules don't reach the shapes inside an<svg>(only the<svg>itself). - No on-screen keyboard: a gamepad can focus an input field but not type in it.
- Inline text (ADR 0429, 0432): no floats; a block element inside a text (
<div>in a<p>) is an inline block rather than breaking the paragraph; an inline block sizes to its content (CSS's shrink-to-fit without the available width: a percentage width inside it has nothing to resolve against); an empty run with padding takes no room;tab-sizeis fixed at 8. Bidi reordering across runs is simplified; editable text has no undo history beyond the hidden text area's, and its caret doesn't blink. - In a Svelte component,
ontransitionend={…}and the other animation event attributes aren't wired yet; listen withon("transitionend", …)on the element fromUIView.query. - No styling of focus beyond
focusColor(a:focusrule styles input fields and the form controls, not buttons). A slider shows navigation's focus only through its border, which it has none of by default. -
fit: containin a box with both sides fixed stretches likefill. - The Localisation panel's text fit check measures only elements whose whole text is one keyed message (
<p>{t("menu.start")}</p>), rendered by a view in the open scene, in a direction theirwidthorheightfixes; its unkeyed-text list doesn't see text written at a component's top level, outside any element.
This wiki is generated from docs/wiki/ and the myco module's source on every push to master. Change pages there in a pull request: edits made here are not kept.
Basics
Gameplay
Rendering
Audio
- Playing sound
- Why is there no sound?
- Playlists
- Interactive music
- Sound generators
- Spatial audio
- Audio mixer
- Live mixing
- Loudness
- Audio profiler
- Audio takes
Reference