Log inGet started

ui

Updated November 24, 2026

UI system — screens, styles, themes, widget responses, focus, custom-widget builders, per-widget state.

require("@builtin::modules.api.engine.ui") -- ui (also available as global 'ui')

The ui namespace: 196 functions.

globals/ui/blur

ui.blur()

Surrender keyboard focus from whichever widget currently holds it, in the editor's UI and the game's alike.

globals/ui/bringAreaToFront

ui.bringAreaToFront(id: string)

Raise a movable area to the top of the window stacking order — the programmatic equivalent of clicking it. Areas sharing a stacking band order by interaction, so this is the call that brings one forward from code: use it when a taskbar button, focus change, or app launch should raise a window. Moving a screen to a higher layer band raises it over the bands below.

Parameters

  • id string — Area widget id.

globals/ui/canvas

ui.canvas(space: ("camera" | "window")?) -> Canvas

The canvas one of the two surfaces a screen lays out on spans (see ui.setScreenSpace), with everything a layout is computed from, in one reading: width / height in logical points (ui.screenSize(space)), aspect (width over height), orientation ("portrait" while taller than wide, "landscape" otherwise: the canvas's own shape, which in the editor is the Scene panel's picture rather than the window), pixelRatio (ui.pixelRatio(space)), safeArea (ui.safeArea(space): the insets, the rect they leave, the cutouts and the on-screen controls) and revision.

revision advances every time any of those changes: a window resized, a phone rotated, a Scene panel dragged to a new size, a preview size set with renderer.setPictureSize, the system bars or the keyboard shown or hidden, an on-screen control shown or moved, the window carried to a display of another density. Compare it with the revision a layout was computed against to tell whether to compute it again, or subscribe with ui.onCanvasChange.

"camera" (the default) is the camera's picture, where a HUD or any camera-space screen lays out; "window" is the window, where the editor's chrome lays out. A layout stated in anchors, % sizes and flex follows the canvas on its own; one computed in Luau from these numbers is computed again when the canvas changes.

Parameters

  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns Canvas — { space, width, height, aspect, orientation, pixelRatio, safeArea, revision }.

local c = ui.canvas(); if c.orientation == "portrait" then print("stack the HUD down the side") end
local c = ui.canvas(); ui.setAreaPos("hud", c.safeArea.x + 8, c.safeArea.y + 8)

globals/ui/captureWindow

ui.captureWindow(screen: string, window: string, opts: CaptureOpts?) -> CaptureResult?

Render a single Window widget to its own offscreen texture and write the result as PNG at /runtime/render_surfaces/<rtHandle>.png. The screen does NOT need to be visible. Returns { rtHandle, texturePath } or nil on invalid inputs (width/height clamped to [1, 8192], defaults 600x400).

Parameters

  • screen string — Screen id containing the target Window.
  • window string — Widget id of the Window.
  • opts CaptureOpts (optional) — { width, height } (optional).

Returns CaptureResult? — { rtHandle, texturePath } or nil.

globals/ui/clearMotion

ui.clearMotion(id: string)

Drop the widget id's motion: it is drawn where layout puts it again, unscaled and at its own opacity, at once. Unregistering a screen drops the motions of the widgets drawn on it the same way.

Parameters

  • id string — The widget's id.

globals/ui/click

ui.click(callbackId: string, value: any?) -> boolean

Simulate a widget click / interaction by its callback id. The call carries no screen, so an id that names widgets on several screens reaches every component that declared it, once each. The callback id is the one a widget emits: the string its onClick / onChange / other on* prop names, or its element id where it leaves that prop unnamed (a button clicked without an onClick, a slider changed without an onChange). Given the element id of a widget whose interactions emit other ids, it raises an error naming those ids, and clicks nothing.

Parameters

  • callbackId string — Callback id the widget emits (its onClick / onChange / on* prop).
  • value any (optional) — Optional value the callback receives as data.value: a number, a string, a boolean, or a table with the fields a structured interaction delivers (a code editor's { token, line, col }, a canvas drag's deltas).

Returns boolean — true when a widget on a registered screen emits the id and the click reaches a handler: an onCallback of a component instance owning the id (its own top-level one, or one of an env its own code registered with ui.registerCallbackEnv), or the broadcast set for an id no component owns. false otherwise: when no widget emits the id (the click then still reaches every ui.registerCallbackEnv env and every component and scene entrypoint that receives callbacks no screen claims), and when the component instances owning the id hold no onCallback to run, which the dispatch logs as a warning naming those instances.

globals/ui/copyText

ui.copyText(text: string)

Put text on the host clipboard — the operating system's clipboard on a native build, the browser's in a web build. What a "Copy path" or "Copy reference" action calls.

Parameters

  • text string — The text to copy.
ui.copyText("/zero/source/scenes/main.scene")

globals/ui/defineStyle

ui.defineStyle(name: string, style: StyleProps)

Define a named style. Style keys follow <widgetType>.<className> (e.g. "label.h1", "button.primary") or bare <className> to apply across widget types. Widgets reference styles via the classes (or class) prop.

Parameters

  • name string — Style name.
  • style StyleProps — Style properties table.

globals/ui/defineStyles

ui.defineStyles(styles: { [string]: StyleProps })

Define multiple named styles at once.

Parameters

  • styles { [string]: StyleProps } — Map of style name to style properties.

globals/ui/defineWidget

ui.defineWidget(name: string, builderFn: (WidgetTree, { WidgetTree }) -> WidgetTree)

Register a custom widget kind. When a tree contains { type = name, props = ..., children = ... }, the decoder calls builderFn(props, children) at register / update time and substitutes the returned widget table in place. Errors surface through ui.lastValidation() with codes widget-builder-error / widget-builder-bad-return / decode-recursion-depth-exceeded.

Parameters

  • name string — Custom widget kind name.
  • builderFn (WidgetTree, { WidgetTree }) -> WidgetTree — Builder closure (props, children) -> widgetTable.

globals/ui/diagnose

ui.diagnose(widgetId: string) -> WidgetPaint?

Why one widget did or did not reach the last frame. Returns that widget's row from ui.observe() — the same fields, resolved against the same reading. An id no registered screen carries reads noSuchWidget, which is how a misspelling separates from a widget whose screen is hidden and from one the frame laid out no box for.

Parameters

  • widgetId string — The id the widget records layout under.

Returns WidgetPaint? — The widget's row, or nil before the UI has published a frame.

local row = ui.diagnose("hud-healthbar")

globals/ui/displayScale

ui.displayScale() -> DisplayScale

The physical scale the UI is sized at. density is the physical pixels one density-independent point covers on a handheld display (a phone, a tablet, a page in a touch browser): a point of the UI covers at least that many pixels whatever the screen's width or orientation, so text and buttons keep their physical size. It is nil on a desktop window, whose UI is sized by its width alone. textScale is the user's text size setting, which multiplies every font size the UI typesets (labels, buttons, inputs, editor chrome; canvas text is drawn at the size it names). touchTarget is the smallest target, in points, a touch reaches an interactive widget within: 48 on a handheld display, 0 on a desktop. pixelRatio is ui.pixelRatio() of the same frame. ui.simulateDisplayScale previews a phone's on any engine.

Returns DisplayScale — { density?, textScale, touchTarget, pixelRatio }.

local scale = ui.displayScale()
local buttonHeight = math.max(32, scale.touchTarget)

globals/ui/dragState

ui.dragState() -> { payload: string, x: number, y: number, label: string?, ghost: boolean }?

The in-flight drag-and-drop payload while a dragPayload widget is being dragged, else nil. x/y are the pointer's position in the logical space ui.getLayoutInfo rects live in, so the reading resolves directly against widget rects. label is the text the drag ghost beside the pointer reads (dragLabel, else the source's text; nil for an outline ghost), and ghost whether the engine draws one (dragGhost) — a capture never shows the ghost, so this is how a drag's name-at-cursor is checked. Poll during a drag to drive live feedback; the drop itself still lands through the target's onDrop. Snapshotted each frame.

Returns { payload: string, x: number, y: number, label: string?, ghost: boolean }? — { payload, x, y, label?, ghost } during a drag, nil otherwise.

globals/ui/elementTree

ui.elementTree(screenName: string) -> ElementNode?

Introspect a screen's rendered widget hierarchy with each element's layout rect. Every node the renderer draws appears, nested exactly as the widgets nest, under the id it records layout against: the id set on the node when the author gave it one, otherwise <screen>/<type>@<path>. bounds is that element's rect — the same table ui.getLayoutInfo(id) returns — and appears once the element has been measured. Kinds registered through ui.defineWidget appear expanded into the primitives they build. Feeds the gui.captureElement tool: list the tree, pick the ids to frame, capture their region.

Parameters

  • screenName string — Screen id passed to ui.registerScreen.

Returns ElementNode? — An ElementNode tree, or nil when no screen is registered under that name.

globals/ui/fling

ui.fling(id: string, velocity: MotionValues, options: FlingOptions?)

Throw the widget id with velocity ({ x, y }, points per second): it coasts from where it is and slows until it rests, stepped by the engine each frame. A widget carrying onDrag = "<callback id>" calls its screen's onCallback every frame of a press-drag with data.value = { dx, dy, vx, vy, dragStarted, dragStopped, shift, ctrl, alt }: dx, dy the frame's movement, vx, vy the pointer's speed, which on the frame dragStopped is true is the release velocity to fling with. Move the widget under the finger meanwhile with ui.setMotion. Options: decay (seconds for the speed to fall to about a third, default 0.35; it travels about velocity * decay), bounds ({ minX, maxX, minY, maxY }: offsets it stays inside; reaching one, or starting beyond it, it springs onto it), stiffness, damping, mass (that spring, default 300, 1, 1) and onSettle (as ui.spring). Under reduced motion it moves at once to where the throw would have brought it to rest, inside its bounds.

Parameters

  • id string — The widget's id.
  • velocity MotionValues — { x?, y? } in points per second.
  • options FlingOptions (optional) — { decay?, bounds?, stiffness?, damping?, mass?, onSettle? }.
ui.fling("card", { x = 900, y = 0 }, { bounds = { minX = -200, maxX = 200 } })

globals/ui/focus

ui.focus(widgetId: string)

Programmatically request keyboard focus on a widget. Queued as a one-shot; the next render of the matching widget calls response.request_focus(). A field, a button and any keyed widget carrying onClick hold it, and Enter or Space on a focused clickable widget clicks it.

Parameters

  • widgetId string — Widget id to focus.

globals/ui/focusedTextField

ui.focusedTextField() -> FocusedTextField?

The text field that holds the keys: the field the person last put the caret in, in the window (place "window"), in the game view's picture ("camera"), or on a panel standing in a headset's world ("panel", with panel its xr.panels id). widget is the id the field records layout under when its screen gave it one; kind is "text", "password", "code" or "number" (an input with a number prop), and for a number number ("whole" or "decimal") and signed say which numbers it takes; multiline says whether Enter starts a new line (in a single-line field Enter submits); text and caret (in characters) are what it holds; bounds is the field's box as shares of the picture it is drawn in, 0 at the top left and 1 at the bottom right. Nil while no field holds the keys. Snapshotted each frame. ui.typeText and ui.typeKey type into this field.

Returns FocusedTextField? — The field, or nil.

local field = ui.focusedTextField()

globals/ui/focusedWidget

ui.focusedWidget() -> (string?, string?)

Return the widget id of whichever widget currently holds keyboard focus, or nil, and the space it draws in: "window" for the editor's UI around the game view, "camera" for the game's own UI in the game view. Snapshotted post-render each frame.

Returns (string?, string?) — Focused widget id or nil, and its space.

local id, space = ui.focusedWidget()

globals/ui/fromViewport

ui.fromViewport(x: number, y: number, space: ("camera" | "window")?) -> { x: number, y: number }

Carry a point from the scene viewport's physical pixels into the UI's logical points. The scene viewport's pixels are what input.snapshot().mouse_position, a touch, every input.events() position, worldToScreen and capture answer in, measured from the top-left of the rect the scene is drawn into.

space names the surface the answer is on (see ui.setScreenSpace): "camera" (the default) is the canvas a camera-space screen (a HUD, a game menu) states its pos and anchors on, so a widget placed at the answer sits over the point; "window" is the window, the space ui.getLayoutInfo, gui.bounds, ui.hitTest and ui.pointerWidget use, so the answer can be tested against a widget's recorded rect. The two differ while a Scene panel presents the scene inside the window.

Parameters

  • x number — X in the scene viewport's physical pixels.
  • y number — Y in the scene viewport's physical pixels.
  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns { x: number, y: number } — { x, y } in that surface's logical points.

local m = input.snapshot().mouse_position; local p = ui.fromViewport(m[1], m[2], "window"); local over = ui.hitTest(p.x, p.y)
local s = worldToScreen(0, 2, 0); local at = ui.fromViewport(s.x, s.y); ui.updateScreen("nameTag", { type = "area", id = "nameTag", pos = { at.x, at.y }, children = { { type = "label", props = { text = "NPC" } } } })

globals/ui/getAreaPos

ui.getAreaPos(id: string) -> AreaPos?

Read the current pivot position of an area widget, including any user drag deltas. Returns { x, y } or nil if the area didn't render this frame.

Parameters

  • id string — Area widget id.

Returns AreaPos? — { x, y } or nil.

globals/ui/getAreaSize

ui.getAreaSize(id: string) -> AreaSize?

Read the measured size of an area widget, including any user resize-grip drags if the area is resizable. Returns { w, h } or nil if the area didn't render this frame.

Parameters

  • id string — Area widget id.

Returns AreaSize? — { w, h } or nil.

globals/ui/getDockLayout

ui.getDockLayout(id: string) -> string?

Read the current serialized layout (split/tab arrangement) of a dockArea widget as a JSON string. Returns nil if the dockArea didn't render this frame. Persist the string and pass it back via the dockArea's layout prop to restore the arrangement.

Parameters

  • id string — DockArea widget id.

Returns string? — Serialized DockState JSON string, or nil.

globals/ui/getLayoutInfo

ui.getLayoutInfo(widgetId: string?) -> LayoutInfo?

Get layout info (position, size, content bounds) for UI containers: the box each is drawn in, which is where layout put it moved through any CSS transform it is drawn under (the upright box a rotated one covers). If widgetId is given, returns info for that widget only; otherwise returns all.

Parameters

  • widgetId string (optional) — Optional widget id to query.

Returns LayoutInfo? — Layout info table or nil.

globals/ui/getPersistentDockLayout

ui.getPersistentDockLayout(id: string) -> string?

Read a dockArea's arrangement as a JSON string with every tab whose dockPanel is transient left out — the form to save and restore across sessions. Returns nil if the dockArea didn't render this frame.

Parameters

  • id string — DockArea widget id.

Returns string? — Serialized DockState JSON string without transient tabs, or nil.

globals/ui/getScreenTree

ui.getScreenTree(screenName: string) -> WidgetTree?

Return the last widget tree table passed to registerScreen / updateScreen for screenName.

Parameters

  • screenName string — Screen name to query.

Returns WidgetTree? — Widget tree or nil.

globals/ui/getTheme

ui.getTheme() -> string

Get the name of the currently active theme.

Returns string — Active theme name.

globals/ui/getToken

ui.getToken(name: string) -> string?

Look up a single design token value from the active theme.

Parameters

  • name string — Token name (without $ prefix).

Returns string? — Token value or nil.

globals/ui/getTokens

ui.getTokens() -> { [string]: string }

Get all design tokens from the active theme as a key-value map.

Returns { [string]: string } — Token map.

globals/ui/getWidgetProps

ui.getWidgetProps(typeName: string) -> { WidgetPropDescriptor }?

Get the property definitions for a widget type: its own props, then the ones every widget takes (onClick, dragPayload, onDrop, tooltip, ...) marked common = true, then the style keys the type reads for its own box (pointerEvents) marked style = true, which are set in the widget's style.

Parameters

  • typeName string — Widget type name.

Returns { WidgetPropDescriptor }? — Array of property descriptors, or nil if type not found.

globals/ui/getWidgetTypes

ui.getWidgetTypes() -> { string }

Get all available widget type names that can be used in widget trees.

Returns { string } — Array of widget type names.

globals/ui/hideScreen

ui.hideScreen(name: string) -> boolean

Hide a registered screen, and report whether a screen by that name is registered. The engine applies the hide later in the frame; listScreens reflects it from the next call onwards.

Parameters

  • name string — Screen identifier to hide.

Returns boolean — True when a screen by this name is registered.

globals/ui/hitTest

ui.hitTest(x: number, y: number) -> PaintHitTest?

Which widget a pointer at (x, y) reaches, and the stack beneath it. Coordinates are logical points on the window, the space getLayoutInfo and gui.bounds rects are in wherever a widget's screen draws (a screen in the Scene view's picture included). A widget that takes no pointer is passed over, and the answer is the widget beneath it: one declaring pointerEvents = "none", and a container that only lays out its children, filling nothing and answering no pointer. stack lists the widgets that take the pointer at the point, topmost first, with each container holding one of them after the widgets it holds.

Parameters

  • x number — Logical X.
  • y number — Logical Y.

Returns PaintHitTest? — { widget, screen, stack, x, y } — widget nil when the point is over no UI — or nil before the UI has published a frame.

local hit = ui.hitTest(640, 360)

globals/ui/hitTestRegions

ui.hitTestRegions(regions: { PressRegion }, opts: HitTestRegionsOpts?) -> { RegionHit }?

Which widget answers a press inside each of regions: the region counterpart of ui.hitTest, for a caller that draws something over the UI and needs to know whether a press anywhere on it would do something in the UI beneath. Each region is a rect { x, y, width, height } or a disc { x, y, radius }, in logical points on the window (the space ui.hitTest and ui.getLayoutInfo use). The answer holds one { widget, screen, takesHold } per region, in the order given. Of the widgets the last frame drew that take the pointer and whose visible box meets the region, a press there reaches those of the highest stacking band; of those, the answer names the smallest that answers a press (a click or a drag: a button, a slider, a text field, a scroll area, a box with onClick), the latest paint breaking a tie, so a label inside a button answers through the button. takesHold is true when holding or dragging that press does something on the widget: a slider, a text field, a scroll area, a widget with onDrag, onPointerDown, onPointerUp, onContextMenu or dragPayload, or one stating holdsPointer or keepsTouchDrag. widget is nil where nothing takes the pointer there, and where what the press reaches answers none of it (a label, a filled box, a full-screen tint). opts.space ("camera" or "window") counts only the screens drawn on that surface, and opts.except leaves out the screens it names.

Parameters

  • regions { PressRegion } — The regions, in logical points on the window.
  • opts HitTestRegionsOpts (optional) — { space?, except? }. Optional.

Returns { RegionHit }? — One { widget, screen, takesHold } per region, or nil before the UI has published a frame.

local hits = ui.hitTestRegions({ { x = 1200, y = 640, radius = 56 } }, { space = "camera" })

globals/ui/idCollisions

ui.idCollisions() -> { [string]: { string } }

Element ids more than one screen recorded, each mapped to the screens that recorded it. An id addresses one element: two screens sharing one leave ui.getLayoutInfo and the gui element tools answering for whichever painted last, and the gui tools refuse such an id. Empty while every id is unique.

Returns { [string]: { string } } — Colliding id -> the screens that recorded it.

for id, screens in ui.idCollisions() do print(id, table.concat(screens, ", ")) end

globals/ui/invisibilityReasons

ui.invisibilityReasons() -> { string }

Every verdict ui.diagnose can report, as a closed list.

Returns { string } — The reason names.

globals/ui/lastRegistration

ui.lastRegistration() -> { name: string, layer: number? }?

The name and layer passed to the most recent ui.registerScreen call, recorded synchronously at call time. A host that mounts a nested app reads this immediately after the mount to learn which screen the nested code registered, without intercepting the ui table.

Returns { name: string, layer: number? }? — { name, layer } for the last registration, or nil if none yet.

globals/ui/lastValidation

ui.lastValidation(screenName: string?) -> any

Validation diagnostics produced at the most recent registerScreen / updateScreen, plus what the render stage found while painting — unknown-font-family reports a style.fontFamily that named no registered font family, once per family per screen, wrap-label-no-width reports a label with props.wrap whose box came out narrower than its own longest word, once per label per screen, and svg-not-as-declared reports an svg widget whose document declared something the picture does not hold — a <text> whose font-family selected no registered family, a <text> the picture holds no glyph of, or a shape whose url(#id) paint resolved to nothing — once per finding per widget per screen, and layout-unsettled reports a screen whose layout was still changing when a frame ran out of layout passes, so that frame painted it before it settled; widgetId names a tree still moving, and the finding is withdrawn once a frame paints the screen settled. With no args returns a { [screen] = entry } map; with a name returns that screen's entry or nil. Validation gated by world setting ui.validation = "off" | "warn" | "strict" (default "warn").

Parameters

  • screenName string (optional) — Optional screen name.

Returns any — Validation entry, full map, or nil.

globals/ui/listFonts

ui.listFonts() -> { FontFamilyInfo }

Every font family a style.fontFamily can select. Read from the registry the UI text renderer resolves a family token through, so a family this returns is one a label renders in. family and every name in aliases are accepted as a fontFamily, case-insensitively; aliases carries the web-font names, CSS generic families and face names that select the same group. faces names the concrete face in each weight/style slot, so a fontWeight = 700 against a family with no bold face gets a synthesised heavy. more lists the other faces registered in the family's slots, each drawing the codepoints the slot's face lacks: the installed chunks of an on-demand face (font.onDemand() lists them all). system = true marks a family taken from the host OS — present on this machine, absent on one without it, and absent on WASM — so a UI that must look the same everywhere picks a family with system = false. A fontFamily naming nothing in this list is reported as an unknown-font-family warning through ui.lastValidation(screen) once the screen paints, and the text renders in the default proportional face.

Returns { FontFamilyInfo } — Array of { family, aliases, faces, more, system }, by family.

for _, f in ui.listFonts() do print(f.family) end

globals/ui/listScreens

ui.listScreens() -> { ScreenSummary }

List every registered screen with its current visibility, z-order layer, renderLayer (the render-layer membership mask it draws under: the mask setScreenRenderLayer stated, else the one the surface setScreenSpace named implies, else the ui bit), editorChrome (whether the mask setScreenRenderLayer stated carries the EditorUI bit, which makes the screen the editor's own chrome; a screen placed on the window without stating it is not chrome), whether the screen has a populated root widget tree, and the space it draws in ("window" for the editor's UI, "camera" for the game's), including the register / show / hide / unregister calls the running script has already made. Sorted by layer ascending, then name.

Returns { ScreenSummary } — Array of screen summaries.

globals/ui/listThemes

ui.listThemes() -> { string }

List all registered theme names.

Returns { string } — Array of theme names.

globals/ui/lockOrientation

ui.lockOrientation(lock: OrientationLock)

Hold the display to the orientations lock allows: "landscape" (both landscape directions, so turning the device over turns the app with it), "portrait" (both portrait directions) or "any" (the display follows the device). A world states the orientation it plays in as world.orientation, which the engine locks to in play mode and releases in edit mode, so the editor follows the device; call this to change it while the world runs. Android turns the app at once, a browser grants the lock only to a page in fullscreen in most cases (the page asks again each time it enters fullscreen), and a desktop window presents in the shape it is given. ui.orientation() reports the lock and whether the platform holds it from the next frame. Any other value is refused by name.

Parameters

  • lock OrientationLock — "any", "landscape" or "portrait".
ui.lockOrientation("portrait")
ui.lockOrientation("any")

globals/ui/matchMedia

ui.matchMedia(query: string) -> boolean

Whether the CSS media query query matches now, as a browser's matchMedia(query).matches answers. The query takes (prefers-reduced-motion: reduce), (prefers-reduced-motion: no-preference) and the bare (prefers-reduced-motion), joined by and, negated by a leading not, listed as alternatives with ,, with an optional media type (all and screen match, print does not); a leading @media is read past. The same text keys a style's @media block. A query the engine cannot evaluate is refused, naming what it takes.

Parameters

  • query string — A CSS media query.

Returns boolean — Whether it matches.

local calm = ui.matchMedia("(prefers-reduced-motion: reduce)")

globals/ui/maxFileBytes

ui.maxFileBytes() -> number

The most bytes one file may bring into the UI through onFileDrop or onFilePaste. A file past it reaches the handler with error = "tooLarge" and no bytes.

Returns number — The limit, in bytes.

globals/ui/missingGlyphs

ui.missingGlyphs() -> { string }

The characters the UI is showing without a glyph: each appears in text a UI surface (the window, the game view, a camera's UI overlay, a screen drawn into a texture) drew in what it last painted, and no face of the family it was drawn in has a glyph for it, so it shows as the replacement box. Every family falls back glyph by glyph to every face the UI holds, so a character here is one no installed face covers. A character a declared on-demand face covers (font.onDemand()) requests that face the frame it is met, and leaves this list once the face is installed and the next frame draws it.

Returns { string } — Sorted array of single-character strings; empty when every character drawn had a glyph.

if #ui.missingGlyphs() > 0 then print(table.concat(ui.missingGlyphs(), " ")) end

globals/ui/motion

ui.motion(id: string) -> MotionReading

Where the widget id's motion stands, as the last frame left it: each channel's value, velocity and target (where it comes to rest), and whether it is moving. A widget with no motion (never moved, or back at rest where layout puts it) reads at its layout place: x 0, y 0, scale 1, opacity 1, not moving. A motion started this frame reads from the next.

Parameters

  • id string — The widget's id.

Returns MotionReading — { x, y, scale, opacity, velocity, target, moving }.

local m = ui.motion("menu"); if not m.moving then print("rests at", m.y) end

globals/ui/observe

ui.observe(screenName: string?) -> PaintObservation?

What the last UI frame painted. Returns { generation, viewport, pointer, pointerOverUi, pointerWidget, widgets } with one widgets row per widget any registered screen holds — its layout box, the clip chain it painted under, the part of that box which reached the frame (visible), the order it painted in (paintIndex), and its reason from the closed set ui.invisibilityReasons() lists. Every rect, the reading's viewport (the window) and pointer are in logical points on the window; a row's viewport is the region the pass that drew it paints into (the whole window, or the rect a Scene panel presents the camera's picture in), and offViewport is judged against it. generation advances once per re-rendered frame, so two calls reporting the same number describe the same frame.

Parameters

  • screenName string (optional) — Narrow the rows to one screen. Omit for every screen.

Returns PaintObservation? — The reading; nil before the UI has published a frame, and nil for a screenName no registered screen answers to.

local reading = ui.observe("hud")

globals/ui/onCanvasChange

ui.onCanvasChange(callback: (canvas: Canvas, previous: Canvas) -> (), space: ("camera" | "window")?) -> () -> ()

Call callback once for every change of the canvas a screen lays out on, with the new reading and the one before it, as ui.canvas(space) returns them: the canvas resized (a window resized, a Scene panel dragged, a preview size set), turned between portrait and landscape, carried to another pixel ratio, or its safe area or on-screen controls changed. It is how a screen whose layout is computed in Luau from the canvas (a HUD that rearranges between portrait and landscape, boxes placed by pos, a grid sized to the width) lays itself out again: lay it out once from ui.canvas(), then again in the callback.

The callback runs on the frame after the change, once however many of the canvas's values changed together, and never for a frame that changed none. It runs in every mode (edit mode, paused play, a time scale of 0), so a screen follows the canvas wherever it is shown. A listener a component registered ends when that component is removed or reloaded, and every other listener goes on hearing changes until the function it returns is called.

Parameters

  • callback (canvas: Canvas, previous: Canvas) -> () — Receives (canvas, previous): the new reading and the one it replaces.
  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns () -> () — A function that removes this listener.

local function layout(c) ui.updateScreen("hud", buildHud(c.width, c.height, c.orientation)) end; layout(ui.canvas()); local off = ui.onCanvasChange(layout)
local off = ui.onCanvasChange(function(c, was) print(was.width .. "x" .. was.height .. " -> " .. c.width .. "x" .. c.height) end)

globals/ui/onOrientationChange

ui.onOrientationChange(callback: (reading: OrientationReading) -> ()) -> () -> ()

Call callback with the new reading every time ui.orientation() changes: the display turns between landscape and portrait or to another rotation, the lock changes, or the platform starts or stops holding it. It is called in every mode (edit mode, paused play, a time scale of 0), on the frame after the change. A listener a component registered ends when that component is removed or reloaded, and every other listener goes on hearing changes until the function it returns is called.

Parameters

  • callback (reading: OrientationReading) -> () — Receives the reading, as ui.orientation() returns it.

Returns () -> () — A function that removes this listener.

local off = ui.onOrientationChange(function(o) print(o.current, o.rotation) end)

globals/ui/onReducedMotionChange

ui.onReducedMotionChange(callback: (reading: ReducedMotion) -> ()) -> () -> ()

Call callback with the new reading every time ui.reducedMotion() changes: the person changes the OS setting while the engine runs, or an in-app preference is stated or withdrawn. It is called in every mode (edit mode, paused play, a time scale of 0), on the frame after the change. A listener a component registered ends when that component is removed or reloaded.

Parameters

  • callback (reading: ReducedMotion) -> () — Receives the reading, as ui.reducedMotion() returns it.

Returns () -> () — A function that removes this listener.

local off = ui.onReducedMotionChange(function(m) print("reduce motion:", m.reduce) end)

globals/ui/orientation

ui.orientation() -> OrientationReading

The orientation the display presents the app in, and the lock it is held to. current is "landscape" (wider than tall) or "portrait": the shape of the window the app presents in. lock is what ui.lockOrientation last asked, "any" when the display follows the device. enforced is whether the platform holds the display to it: Android always does, a browser does once it grants the Screen Orientation lock, and a desktop window never does, presenting in the shape it is given; reason names why when it does not. rotation is the display's rotation from its natural orientation in degrees (0, 90, 180, 270) where the platform states one, and nil on a desktop window. revision advances every time any of these changes; ui.onOrientationChange calls back on each change.

Returns OrientationReading — { current, lock, enforced, reason?, rotation?, revision }.

if ui.orientation().current == "portrait" then print("lay the HUD out for a tall screen") end

globals/ui/paintGeneration

ui.paintGeneration() -> number

The generation of the last frame's paint reading (ui.observe()), read without building the reading. It advances once per re-rendered frame and stands still otherwise, so something derived from the reading (a ui.hitTest, a ui.hitTestRegions answer) still holds while this reads the number it was derived at.

Returns number — The generation, 0 before the UI has published a frame.

local gen = ui.paintGeneration()

globals/ui/paintOrder

ui.paintOrder(a: string, b: string) -> number?

Which of two widgets paints later: -1 when a paints before b, 1 when after, 0 when level. This is what separates two widgets whose rects are identical.

Parameters

  • a string — First widget id.
  • b string — Second widget id.

Returns number? — -1, 0, 1, or nil when the reading holds no row for one of them.

local order = ui.paintOrder("panel-a", "panel-b")

globals/ui/pixelRatio

ui.pixelRatio(space: ("window" | "camera")?) -> number

Physical pixels per logical point of one of the two surfaces a screen lays out on (see ui.setScreenSpace).

"window" (the default) is the window. ui.getLayoutInfo and gui.bounds rects, ui.hitTest and ui.pointerWidget answer in its points, wherever the widget's screen draws; input.simulateMouse*, the Zin.test pointer primitives and inputSim with target "ui" take its physical pixels. A rect times this ratio is a window pixel.

"camera" is the camera's picture: the canvas a camera-space screen's pos and anchors are stated on, laid over the scene viewport's physical pixels, the space input.snapshot().mouse_position, input.events(), worldToScreen, screenToRay and capture speak.

The two are one number wherever the scene fills the window. While a Scene panel presents the scene in a rect of the window, the picture's canvas is fitted to that rect, so its ratio follows the panel's width (and is at least the density a display states), and the scene viewport's pixels are measured from that rect's top-left (camera.viewData().viewport, whose scaleX / scaleY are its pixels per window pixel while a device screen's size is shown scaled to fit the panel) while the window's are measured from the window's. ui.fromViewport and ui.toViewport carry a point across both steps in one call.

Parameters

  • space ("window" | "camera") (optional) — "window" (default) or "camera".

Returns number — Physical pixels per logical point of that surface (1.0 when unscaled).

local r = ui.pixelRatio(); local b = tools.use("gui", "bounds", "play"); input.simulateMouseMove(b.centerX * r, b.centerY * r)

globals/ui/pointerWidget

ui.pointerWidget() -> PointerRead?

Whether the UI is consuming the pointer, and which widget holds it — the pointer counterpart of ui.focusedWidget(). x, y are in logical points on the window, the space getLayoutInfo rects are in.

Returns PointerRead? — { x, y, overUi, widget, screen }, or nil before the UI has published a frame.

globals/ui/reducedMotion

ui.reducedMotion() -> ReducedMotion

Whether the person asked for less motion, and where that came from. reduce is true while motion is reduced: animate less (drop drift, overshoot and travel; prefer a short cross-fade or an immediate change). platform is the OS setting as the platform states it: Android's Remove animations, a browser's prefers-reduced-motion, or the animation settings of Windows, macOS and the desktop Linux portal, as "reduce" or "no-preference"; "unknown" where the platform states no such setting, which is not the same as off. platformSource names what it was read from, or why the platform states none. setting is the in-app preference ui.setReducedMotion stated, which wins over the platform's while it stands; a world's ends when the world's scripts end, and while a world's and a trusted screen's both stand the one stated last is setting. source says which of them decided ("setting", "platform" or "none"). revision advances on every change; ui.onReducedMotionChange calls back on each. A style follows the same preference with no Luau through an ["@media (prefers-reduced-motion: reduce)"] block (see the styling guide), and ui.matchMedia tests any media query.

Returns ReducedMotion — { reduce, platform, platformSource?, setting?, source, revision }.

if ui.reducedMotion().reduce then print("show the change at once") end

globals/ui/refreshLiveText

ui.refreshLiveText() -> number

Read again the text of every screen this VM registered whose text resolves when it is read: a text, title, header, placeholder, tooltip or dropdown option given as a value with a __tostring metamethod, such as an i18n.text value, rather than as a string. The i18n module calls it whenever the player's language, the pseudo-locale or a catalog changes, so a screen built from i18n.text values follows them without being built again.

Returns number — How many screens were read again.

local tree = { type = "label", props = { text = i18n.text("hud.title") } }

globals/ui/registerBackgroundShader

ui.registerBackgroundShader(shaderHandle: any?, width: number?, height: number?)

Register a screen-domain .shader as a UI background, drawn via the backgroundShader style. Takes the shader's asset handle from asset.resolve. A shader whose compile failed (shaderHandle:compileStatus() reads failed), or whose program the compile gate refuses, is not registered: the call raises an error naming the shader and the compiler's message, the one compileStatus().error reads. A shader whose compileStatus() still reads pending raises too: register it once it reads compiled.

Parameters

  • shaderHandle any (optional) — The screen .shader's asset handle, from asset.resolve.
  • width number (optional) — Render target width (default 1280).
  • height number (optional) — Render target height (default 720).

globals/ui/registerCallbackEnv

ui.registerCallbackEnv(key: string, env: { [string]: any })

Register an environment table to receive widget callbacks: its onCallback(id, value) fires for any widget callback not owned by a specific component instance — the same broadcast a component's onCallback receives. Registered from a component instance's own code (its hooks, methods and the closures they create), the env joins that instance: every callback the instance owns, the ones on the screens it registered, reaches the env as well as the instance's own top-level onCallback. Keyed by key; re-registering the same key replaces the previous env. Reach for this from a context that hosts a UI surface with a handler of its own (a scene entrypoint, a module, a component's local handler). Pair with ui.unregisterCallbackEnv(key) so the ref is released.

Parameters

  • key string — Stable identifier for this registration (re-register replaces).
  • env { [string]: any } — Environment table whose onCallback receives the broadcasts.

globals/ui/registerScreen

ui.registerScreen(name: string, widgetTree: WidgetTree, layer: number?)

Register a named UI screen with a widget tree. Optional layer controls z-ordering (higher = on top), in bands: below 0 behind everything, 0-99 ordinary app depth, 100-999 always-on-top chrome, 1000+ menu and popup depth. A screen in a higher band covers one in a lower band whatever their roots are; inside a band a floating area or window root sits over ordinary content, and a modal root sits over the whole stack. Tag-based grouping lives in Z.tags (Z.tags.set(name, { "editor" }) after register). A screen belongs to the component instance whose own code registers it (its hooks and methods, and any closure they create, such as a listener it subscribes): that instance's onCallback receives its callbacks, and the screen is unregistered when the instance ends. Code that is not an instance's own (a scene entrypoint, a module, a listener either subscribed) registers a screen no instance owns, which stays until it is unregistered, whichever component's hook ran that code. topics/ui has the rule.

Parameters

  • name string — Unique screen identifier.
  • widgetTree WidgetTree — Root widget table.
  • layer number (optional) — Z-order layer (optional).
ui.registerScreen("hud", tree)

globals/ui/registerTheme

ui.registerTheme(name: string, theme: ThemeDefinition)

Register a theme from a flat Luau table. Most callers should use Z.theme.register(name, table) which runs the cascade for them.

Parameters

  • name string — Theme name to register.
  • theme ThemeDefinition — Flat-resolved theme table.

globals/ui/removeScreen

ui.removeScreen(name: string) -> boolean

Alias for ui.unregisterScreen.

Parameters

  • name string — Screen identifier to remove.

Returns boolean — True when a screen by this name was registered.

globals/ui/resetAreaSize

ui.resetAreaSize(id: string)

Clear a resizable area's remembered size (from a grip drag or ui.setAreaSize) so its declared — or content — size takes over again.

Parameters

  • id string — Area widget id.

globals/ui/response

ui.response(widgetId: string) -> WidgetResponse?

Per-widget interaction snapshot for the most recent frame. Returns { clicked, hovered, focused, changed, value } where clicked / changed mark transitions and hovered / focused mark current state.

Parameters

  • widgetId string — The widget id (NOT the onClick / onChange callback id).

Returns WidgetResponse? — WidgetResponse or nil.

globals/ui/safeArea

ui.safeArea(space: ("camera" | "window")?) -> SafeArea

The part of one of the two surfaces a screen lays out on (see ui.setScreenSpace) that no system bar, display cutout or on-screen keyboard covers, in the logical points ui.screenSize(space) reports. "camera" (the default) is the camera's picture, where a HUD or any camera-space screen lays out; "window" is the window, where the editor's chrome lays out. Each is that surface's own area whether or not a screen is shown on it, and the two are one wherever the scene fills the window. top / right / bottom / left are how far in from each edge the covered band reaches; x / y / width / height are the rect they leave; cutouts lists each display cutout (a camera hole or a notch) as { x, y, width, height }. Screens lay out inside this rect, so anchors, top-level % sizes and a window's default position already keep clear of it; read it to place something by absolute pos, or to run a background under the bars while its controls stay inside.

controls lists each rect an on-screen control drawn over the picture covers, as { x, y, width, height, owner }: the engine's touch buttons and its Menu button while the touch controls show (owner "zin_touch_controls"), and every rect a world states with ui.setControlRegions. An anchor of any other screen keeps clear of them on its own; a box placed by pos, padding or flex reads them to stay out from under a control, where a press would reach the control instead of the widget.

revision advances every time the area, the size of its surface or the controls change (a rotation, the system bars shown or hidden, the keyboard opening, a resize, a control shown, hidden or moved): compare it with the one you last laid out against, or subscribe with ui.onCanvasChange, which calls back on each change of the area and of the canvas it is stated on. All zero on a desktop window; ui.simulateSafeArea lays the UI out as a phone would on any engine, on the window and on the picture a Scene panel presents.

Parameters

  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns SafeArea — { top, right, bottom, left, x, y, width, height, cutouts, controls, revision } in that surface's logical points.

local safe = ui.safeArea()
ui.setAreaPos("hud", safe.x + 8, safe.y + 8)
for _, c in ipairs(ui.safeArea().controls) do print(c.owner, c.x, c.y, c.width, c.height) end

globals/ui/screen

ui.screen(name: string) -> { [string]: any }?

Get a screen proxy with methods like setResolution and rasterize.

Parameters

  • name string — Screen name.

Returns { [string]: any }? — Screen proxy table, or nil.

globals/ui/screenRefusal

ui.screenRefusal(screenName: string) -> string?

Why the code calling may not reach the screen screenName, or nil when it may: a private screen (setScreenPrivate) is reached by the account's own code alone. Code that acts on such a screen on its caller's behalf, such as an editor panel's exported functions, raises it before it acts.

Parameters

  • screenName string — The screen name.

Returns string? — The refusal, or nil.

local why = ui.screenRefusal("edui_p_memory"); if why then error(why, 2) end

globals/ui/screenSize

ui.screenSize(space: ("camera" | "window")?) -> { width: number, height: number }

The canvas one of the two surfaces a screen lays out on spans, as { width, height } in logical points: the space that surface's area pos and anchors are stated in (see ui.setScreenSpace).

"camera" (the default) is the camera's picture, where a camera-space screen lays out: a HUD, a game menu, any content UI that states no other space. It is the canvas ui.fromViewport(x, y) answers on, so a HUD clamps a marker to ui.screenSize() and places it at ui.fromViewport of a worldToScreen projection. "window" is the window, where the editor's chrome lays out and ui.getLayoutInfo rects are recorded. Each is that surface's size whether or not a screen is shown on it, and the two are one size wherever the scene fills the window; while a Scene panel presents the scene inside the window, the camera's canvas is fitted to the panel, or laid out as the device screen renderer.setPictureSize draws the panel's picture at. Neither is the pixel size of a capture screenshot, which may be downscaled.

It follows the size the engine draws at, and renderer.setViewportSize changes that size for the task that asks, which is how a layout written against this is checked at a second shape without rebooting the engine, read in the call that set the size before the surface goes back; renderer.setPictureSize does the same for the camera's canvas alone while a Scene panel presents it. The pixel size behind the window's points is renderer.surfaceSize(), the whole drawing surface, which an editor layout makes larger than the rect renderer.viewportSize() draws the scene into. ui.pixelRatio(space) is the factor between a surface's points and its pixels.

The size changes while the engine runs (a window resized, a phone rotated, a Scene panel dragged), and a layout computed from it is computed again when it does: ui.onCanvasChange(fn, space) calls back once for each change, and ui.canvas(space) reads the size with the pixel ratio, the safe area and a revision that advances on each.

Parameters

  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns { width: number, height: number } — { width, height } in that surface's logical points.

local w = worldToScreen(0, 2, 0); local p = ui.fromViewport(w.x, w.y); local s = ui.screenSize(); local onCanvas = p.x >= 0 and p.x <= s.width and p.y >= 0 and p.y <= s.height

globals/ui/scroll

ui.scroll(deltaX: number, deltaY: number)

Simulate a mouse-wheel scroll event on the UI.

Parameters

  • deltaX number — Horizontal scroll delta.
  • deltaY number — Vertical scroll delta.

globals/ui/setAreaPos

ui.setAreaPos(id: string, x: number, y: number)

Programmatically move a movable area widget to (x, y). Applied for one frame; subsequent frames let drag tracking take over.

Parameters

  • id string — Area widget id.
  • x number — Target pivot x (screen coords).
  • y number — Target pivot y (screen coords).

globals/ui/setAreaSize

ui.setAreaSize(id: string, w: number, h: number)

Programmatically set a resizable area's size (the user-size override) — for maximize / restore / tile. Persists until the area's declared width/height changes or ui.resetAreaSize(id) clears it.

Parameters

  • id string — Area widget id.
  • w number — Target width (screen coords).
  • h number — Target height (screen coords).

globals/ui/setControlRegions

ui.setControlRegions(owner: string, rects: { SafeAreaRect }?)

State the rects the on-screen controls owner draws over the camera's picture cover, each { x, y, width, height } in the logical points ui.screenSize() reports. ui.safeArea().controls lists them from this call on, its revision advances, and from the next frame an anchor of any other screen that would land on one moves inward clear of it (a box pinned to the right edge moves left, one pinned to the top moves down, along whichever axis is the shorter move), keeping its margin from the control as it keeps it from the edge. Anchors keep clear of them while the screen keeps the size ui.screenSize() reported at the call, so restate them whenever the controls move and after the screen changes size (a rotation or a window resize advances ui.safeArea().revision), and call with nil or {} to withdraw them. The engine's touch controls state theirs under "zin_touch_controls"; a world drawing on-screen controls of its own states them under the name of the screen it draws them on, so that screen's own anchors stay where it put them. A negative size or a non-number is refused by name.

Parameters

  • owner string — Who draws the controls: the name of the screen they are drawn on.
  • rects { SafeAreaRect } (optional) — { { x, y, width, height } } in logical points; nil or {} withdraws them.
ui.setControlRegions("myTouchPad", { { x = 1100, y = 520, width = 160, height = 160 } })
ui.setControlRegions("myTouchPad", nil)

globals/ui/setDockWindowRect

ui.setDockWindowRect(dockId: string, panelId: string, x: number, y: number, width: number, height: number)

Place the floating window of a dockArea panel at (x, y) with size (width, height). Applies once the panel occupies a window — a request made before then waits for it.

Parameters

  • dockId string — DockArea widget id.
  • panelId string — Id of the panel held by the window to place.
  • x number — Window left edge (screen coords).
  • y number — Window top edge (screen coords).
  • width number — Window width (screen coords).
  • height number — Window height (screen coords).

globals/ui/setMotion

ui.setMotion(id: string, values: MotionValues)

Place the widget id at values ({ x?, y?, scale?, opacity? }, as ui.spring takes them) at once, at rest, ending any motion of the channels it names; a placement that leaves no channel of a spring or fling moving runs its onSettle, as ui.stopMotion does. Nothing is laid out anew and no screen tree is sent: a script running its own simulation states each frame's positions this way, or many widgets' at once with ui.setMotions.

Parameters

  • id string — The widget's id.
  • values MotionValues — { x?, y?, scale?, opacity? }.
ui.setMotion("cursor_ghost", { x = 12, y = -4 })

globals/ui/setMotions

ui.setMotions(values: { [string]: MotionValues })

Place many widgets at once: values maps each widget id to { x?, y?, scale?, opacity? }, as ui.setMotion takes them. One call a frame moves a whole field of widgets a script simulates (bubbles that drift and push each other apart) with no screen tree sent again.

Parameters

  • values { [string]: MotionValues } — { [id]: { x?, y?, scale?, opacity? } }.
ui.setMotions({ a = { x = 10, y = 4 }, b = { x = -3, y = 12, scale = 1.1 } })

globals/ui/setReducedMotion

ui.setReducedMotion(reduce: (boolean | MotionPreference)?) -> boolean

State the in-app reduced-motion preference, which wins over the OS setting while it stands: true (or "reduce") reduces motion, false (or "no-preference") asks for full motion, and nil withdraws it so the OS setting stands again. An app's own "Reduce motion" switch calls this. A world's preference ends when the world's scripts end; a trusted screen's stands for the life of the engine, and while both stand the one stated last decides. ui.reducedMotion(), ui.matchMedia and every style's @media (prefers-reduced-motion) block follow it from the next frame. Any other value is refused by name.

Parameters

  • reduce (boolean | MotionPreference) (optional) — true / "reduce", false / "no-preference", or nil to withdraw it.

Returns boolean — Whether the preference changed.

ui.setReducedMotion(true)
ui.setReducedMotion(nil)

globals/ui/setScreenPrivate

ui.setScreenPrivate(screenName: string)

State that the screen screenName draws what the person keeps for themselves, whether or not it is registered yet, for as long as the engine runs. From then on it is reached by the account's own code alone (the editor, the agent's tools and execute): code a world ships reads nothing it draws (getScreenTree, elementTree, paintSnapshot, getLayoutInfo, widgetState, focusedTextField, /runtime/ui/<name>/), drives none of it (registering, updating, showing, hiding or unregistering it, click on an id its widgets emit, focus, typeText into its field, a widget of another screen emitting an id its widgets emit) and hears none of its callbacks. The account's own code alone states it; code a world ships is refused. An editor panel states it with private = true in its spec.

Parameters

  • screenName string — The screen name.
ui.setScreenPrivate("edui_p_memory")

globals/ui/setScreenRenderLayer

ui.setScreenRenderLayer(name: string, mask: number)

Set a screen's render-layer membership bitmask. A screen draws into a camera or capture only when this mask intersects the camera's include mask, the same rule geometry follows. Content UI carries the ui bit; the editor places its chrome on EditorUI so agent captures can drop it, and a screen carrying that bit is part of the window rather than the camera's picture. Stating a mask here fixes the membership: a screen left to itself takes the one the surface it is placed on implies, EditorUI for the window and ui for the camera's picture. __renderLayers.bit(name) answers with a layer's bit INDEX, so a mask sets the bit at that index and __renderLayers.names(mask) reads it back as the names it holds.

Parameters

  • name string — Screen identifier.
  • mask number — Render-layer membership bitmask — the OR of bit32.lshift(1, __renderLayers.bit(name)) over the layers the screen is on.
ui.setScreenRenderLayer("hud", bit32.lshift(1, __renderLayers.bit("ui")))

globals/ui/setScreenSpace

ui.setScreenSpace(name: string, space: string)

Set which surface a screen is part of. "camera" is the picture the viewport camera produces: the screen lays out over the camera's target and is drawn into it, so it sits inside the Scene panel presenting the scene and appears in every capture of the camera — the default for content UI. "window" is the window itself, whatever presents the scene — where the editor's chrome lives, and the default for a screen on the EditorUI layer. The two are one statement made from either end, so a screen placed on the window takes the EditorUI membership unless setScreenRenderLayer states another: the window goes on drawing it while a capture that drops the authoring layers, which is what an agent takes by default, leaves it out. Where the scene presents on the window, the two surfaces coincide. A name that is neither raises.

Parameters

  • name string — Screen identifier.
  • space string — "camera" | "window".
ui.setScreenSpace("agent-banner", "window")

globals/ui/setScrollPosition

ui.setScrollPosition(widgetId: string, offsetY: number)

Set the scroll offset of a scrollArea widget.

Parameters

  • widgetId string — Scroll area widget id.
  • offsetY number — Vertical scroll offset in pixels.

globals/ui/setShaderUniforms

ui.setShaderUniforms(name: string, uniforms: { [string]: number })

Set uniform values on a registered background shader.

Parameters

  • name string — Shader name identifier.
  • uniforms { [string]: number } — Map of uniform name to number value.

globals/ui/setTheme

ui.setTheme(name: string)

Switch the active global theme by name.

Parameters

  • name string — Theme name to activate.

globals/ui/showScreen

ui.showScreen(name: string) -> boolean

Make a registered screen visible, and report whether a screen by that name is registered. The engine applies the show later in the frame; listScreens reflects it from the next call onwards.

Parameters

  • name string — Screen identifier to show.

Returns boolean — True when a screen by this name is registered.

globals/ui/simulateDisplayScale

ui.simulateDisplayScale(scale: DisplayScaleSpec?)

Size the UI as a display stating scale would, in place of what the platform states. A density sizes it as a handheld display of that many physical pixels per point (omit it for a desktop display sized by its width), and textScale multiplies every font size the UI typesets (1 when omitted). Previews a phone's UI on a desktop or headless engine, and makes a layout test independent of the device it runs on. ui.displayScale(), ui.screenSize() and ui.pixelRatio() report it from the next frame. Call it with no argument (or nil) to return to the platform's own scale. A value that is not a number above 0 and at most 8 is refused by name.

Parameters

  • scale DisplayScaleSpec (optional) — { density?, textScale? }; nil returns to the platform's scale.
ui.simulateDisplayScale({ density = 2.625, textScale = 1.3 })
ui.simulateDisplayScale()

globals/ui/simulateSafeArea

ui.simulateSafeArea(area: SafeAreaSpec?)

Lay the UI out as if the system covered the screen by area (logical points) in place of what the platform states: each inset defaults to 0 and cutouts is a list of { x, y, width, height }. Previews a phone's status bar, camera cutout and navigation bar on a desktop or headless engine, and makes a layout test independent of the device it runs on. It covers the window, and while a Scene panel presents the scene inside the window it covers the camera's picture too, stated in that picture's points, so a game's HUD in the panel lays out inside it in edit and in play as it would on that phone. With renderer.setPictureSize sizing that picture to a phone's pixels, the panel shows what that phone shows. ui.safeArea() reports it from the next frame. Call it with no argument (or nil) to return to the platform's own safe area. A negative or non-number inset is refused by name.

Parameters

  • area SafeAreaSpec (optional) — { top?, right?, bottom?, left?, cutouts? } in logical points; nil returns to the platform's safe area.
ui.simulateSafeArea({ top = 40, bottom = 30, cutouts = { { x = 600, y = 0, width = 80, height = 40 } } })
ui.simulateSafeArea()

globals/ui/spring

ui.spring(id: string, target: MotionValues, options: SpringOptions?)

Move the widget id toward target by a spring the engine steps each frame: no script runs per frame and the screen tree is not sent again. target names any of x, y (an offset in points from where layout puts the widget), scale (about its centre, 1 unscaled) and opacity (multiplying its own, 1 unchanged). The widget is drawn moved and is pressed where it is drawn; its layout box and its neighbours stay put. Calling it again mid-motion retargets from where the widget is, with the speed it has, so it never jumps. Options: stiffness (default 170), damping (the damping ratio, default 0.8: below 1 overshoots and settles, 1 arrives without overshooting), mass (default 1), velocity ({ x, y, scale, opacity } per second: a drag's release speed, or a kick with no target, which springs back to where the channel rests) and onSettle (a callback id: once every channel rests, the screen's onCallback(onSettle, data) runs with data.value = { id, x, y, scale, opacity }). Under reduced motion an opacity change is a 0.15 s cross-fade and the widget moves to its target at once, or, while it fades out, once the fade has ended, so the fade is seen where it was. A key it does not take is refused by name.

Parameters

  • id string — The widget's id.
  • target MotionValues — { x?, y?, scale?, opacity? }: where it springs to.
  • options SpringOptions (optional) — { stiffness?, damping?, mass?, velocity?, onSettle? }.
ui.spring("menu", { y = 0, opacity = 1 }, { stiffness = 400, damping = 0.6 })
ui.spring("card", { scale = 1 }, { velocity = { scale = 4 } }) -- a pop

globals/ui/stopMotion

ui.stopMotion(id: string)

Hold the widget id where it is now, ending its spring or fling (a finger landing on a moving widget). Its onSettle callback runs, as for a motion that came to rest.

Parameters

  • id string — The widget's id.

globals/ui/takeDockTearOffs

ui.takeDockTearOffs(id: string) -> { string }

The panel ids of the tabs dragged out of the dockArea id and released over empty space since the last call. A dock standing in an XR panel hands such a tab to its owner rather than opening a window inside itself, and keeps it out of the dock for as long as the dockArea still lists it; the owner places the panel and stops listing it. Empty for a dock drawn on the desktop window.

Parameters

  • id string — DockArea widget id.

Returns { string } — Array of panel ids.

globals/ui/toViewport

ui.toViewport(x: number, y: number, space: ("camera" | "window")?) -> { x: number, y: number }

Carry a point from the UI's logical points into the scene viewport's physical pixels: the inverse of ui.fromViewport, and the space screenToRay, screenToPlanePoint and Physics.raycastScreen take, so a point read off the UI can be cast into the scene.

space names the surface the point is on: "camera" (the default) for a camera-space screen's pos / anchor coordinates, "window" for a ui.getLayoutInfo / gui.bounds rect.

Parameters

  • x number — X in that surface's logical points.
  • y number — Y in that surface's logical points.
  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns { x: number, y: number } — { x, y } in the scene viewport's physical pixels.

local b = tools.use("gui", "bounds", "target"); local v = ui.toViewport(b.centerX, b.centerY, "window"); local hit = Physics.raycastScreen(v.x, v.y)

globals/ui/typeKey

ui.typeKey(key: string, modifiers: { shift: boolean?, ctrl: boolean?, alt: boolean? }?)

Press and release key on the text field that holds the keys (ui.focusedTextField): Backspace, Delete, Enter (a new line in a multi-line field, a submit in a single-line one), Tab, Escape, the arrows, Home, End, or any other KeyboardEvent.code. modifiers names the modifiers held for it (Shift with an arrow selects). It reaches the UI alone: the game's input reads no key. Raises on a name that is not a key code.

Parameters

  • key string — The key, as a KeyboardEvent.code.
  • modifiers { shift: boolean?, ctrl: boolean?, alt: boolean? } (optional) — { shift?, ctrl?, alt? }.
ui.typeKey("Backspace")

globals/ui/typeText

ui.typeText(text: string)

Type text into the text field that holds the keys (ui.focusedTextField), the way a keyboard's typed characters reach it: inserted at the caret, in place of a selection. Control characters other than a new line and a tab are left out. It reaches the UI alone: the game's input reads no key.

Parameters

  • text string — The characters to type.
ui.typeText("hello")

globals/ui/unregisterCallbackEnv

ui.unregisterCallbackEnv(key: string)

Remove an environment registered with ui.registerCallbackEnv. Its onCallback stops receiving broadcasts. No-op if key isn't registered.

Parameters

  • key string — The key passed to ui.registerCallbackEnv.

globals/ui/unregisterScreen

ui.unregisterScreen(name: string) -> boolean

Remove a screen from the registry entirely. Unlike hideScreen, this deletes the entry so it no longer appears in listScreens or render iteration.

Parameters

  • name string — Screen identifier to unregister.

Returns boolean — True when a screen by this name was registered.

globals/ui/unregisterWidget

ui.unregisterWidget(name: string)

Drop a registered custom widget kind. Subsequent references produce an unknown-widget-type diagnostic.

Parameters

  • name string — Custom widget kind name.

globals/ui/updateScreen

ui.updateScreen(name: string, widgetTree: WidgetTree)

Replace the widget tree of an already-registered screen.

Parameters

  • name string — Screen identifier to update.
  • widgetTree WidgetTree — New root widget table.

globals/ui/useStyles

ui.useStyles(themeName: string)

Apply a registered style file's classes additively without changing the active theme.

Parameters

  • themeName string — Name of the registered style / theme asset.

globals/ui/widgetState

ui.widgetState(widgetId: string, key: string, default: any?) -> any

Read per-widget cross-frame state. Returns the value previously written via widgetStateSet, or default (or nil). State is keyed by widget id and persists across re-renders within a screen's lifetime; cleared automatically when the owning screen is unregistered.

Parameters

  • widgetId string — Widget id whose state to read.
  • key string — State key.
  • default any (optional) — Value to return when nothing has been written.

Returns any — Stored value, default, or nil.

globals/ui/widgetStateClear

ui.widgetStateClear(widgetId: string, key: string)

Remove a per-widget state entry.

Parameters

  • widgetId string — Widget id whose state to clear.
  • key string — State key.

globals/ui/widgetStateSet

ui.widgetStateSet(widgetId: string, key: string, value: any?)

Write per-widget cross-frame state. Replaces any existing value under (widgetId, key). Tables are stored by reference.

Parameters

  • widgetId string — Widget id to scope the state under.
  • key string — State key.
  • value any (optional) — Value to store (must be non-nil).

typed/builtin//modules/api/engine/ui/ui/blur

ui.blur()

Surrender keyboard focus from whichever widget currently holds it, in the editor's UI and the game's alike.

typed/builtin//modules/api/engine/ui/ui/bringAreaToFront

ui.bringAreaToFront(id: string)

Raise a movable area to the top of the window stacking order — the programmatic equivalent of clicking it. Areas sharing a stacking band order by interaction, so this is the call that brings one forward from code: use it when a taskbar button, focus change, or app launch should raise a window. Moving a screen to a higher layer band raises it over the bands below.

Parameters

  • id string — Area widget id.

typed/builtin//modules/api/engine/ui/ui/canvas

ui.canvas(space: ("camera" | "window")?) -> Canvas

The canvas one of the two surfaces a screen lays out on spans (see ui.setScreenSpace), with everything a layout is computed from, in one reading: width / height in logical points (ui.screenSize(space)), aspect (width over height), orientation ("portrait" while taller than wide, "landscape" otherwise: the canvas's own shape, which in the editor is the Scene panel's picture rather than the window), pixelRatio (ui.pixelRatio(space)), safeArea (ui.safeArea(space): the insets, the rect they leave, the cutouts and the on-screen controls) and revision.

revision advances every time any of those changes: a window resized, a phone rotated, a Scene panel dragged to a new size, a preview size set with renderer.setPictureSize, the system bars or the keyboard shown or hidden, an on-screen control shown or moved, the window carried to a display of another density. Compare it with the revision a layout was computed against to tell whether to compute it again, or subscribe with ui.onCanvasChange.

"camera" (the default) is the camera's picture, where a HUD or any camera-space screen lays out; "window" is the window, where the editor's chrome lays out. A layout stated in anchors, % sizes and flex follows the canvas on its own; one computed in Luau from these numbers is computed again when the canvas changes.

Parameters

  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns Canvas — { space, width, height, aspect, orientation, pixelRatio, safeArea, revision }.

local c = ui.canvas(); if c.orientation == "portrait" then print("stack the HUD down the side") end
local c = ui.canvas(); ui.setAreaPos("hud", c.safeArea.x + 8, c.safeArea.y + 8)

typed/builtin//modules/api/engine/ui/ui/captureWindow

ui.captureWindow(screen: string, window: string, opts: CaptureOpts?) -> CaptureResult?

Render a single Window widget to its own offscreen texture and write the result as PNG at /runtime/render_surfaces/<rtHandle>.png. The screen does NOT need to be visible. Returns { rtHandle, texturePath } or nil on invalid inputs (width/height clamped to [1, 8192], defaults 600x400).

Parameters

  • screen string — Screen id containing the target Window.
  • window string — Widget id of the Window.
  • opts CaptureOpts (optional) — { width, height } (optional).

Returns CaptureResult? — { rtHandle, texturePath } or nil.

typed/builtin//modules/api/engine/ui/ui/clearMotion

ui.clearMotion(id: string)

Drop the widget id's motion: it is drawn where layout puts it again, unscaled and at its own opacity, at once. Unregistering a screen drops the motions of the widgets drawn on it the same way.

Parameters

  • id string — The widget's id.

typed/builtin//modules/api/engine/ui/ui/click

ui.click(callbackId: string, value: any?) -> boolean

Simulate a widget click / interaction by its callback id. The call carries no screen, so an id that names widgets on several screens reaches every component that declared it, once each. The callback id is the one a widget emits: the string its onClick / onChange / other on* prop names, or its element id where it leaves that prop unnamed (a button clicked without an onClick, a slider changed without an onChange). Given the element id of a widget whose interactions emit other ids, it raises an error naming those ids, and clicks nothing.

Parameters

  • callbackId string — Callback id the widget emits (its onClick / onChange / on* prop).
  • value any (optional) — Optional value the callback receives as data.value: a number, a string, a boolean, or a table with the fields a structured interaction delivers (a code editor's { token, line, col }, a canvas drag's deltas).

Returns boolean — true when a widget on a registered screen emits the id and the click reaches a handler: an onCallback of a component instance owning the id (its own top-level one, or one of an env its own code registered with ui.registerCallbackEnv), or the broadcast set for an id no component owns. false otherwise: when no widget emits the id (the click then still reaches every ui.registerCallbackEnv env and every component and scene entrypoint that receives callbacks no screen claims), and when the component instances owning the id hold no onCallback to run, which the dispatch logs as a warning naming those instances.

typed/builtin//modules/api/engine/ui/ui/copyText

ui.copyText(text: string)

Put text on the host clipboard — the operating system's clipboard on a native build, the browser's in a web build. What a "Copy path" or "Copy reference" action calls.

Parameters

  • text string — The text to copy.
ui.copyText("/zero/source/scenes/main.scene")

typed/builtin//modules/api/engine/ui/ui/defineStyle

ui.defineStyle(name: string, style: StyleProps)

Define a named style. Style keys follow <widgetType>.<className> (e.g. "label.h1", "button.primary") or bare <className> to apply across widget types. Widgets reference styles via the classes (or class) prop.

Parameters

  • name string — Style name.
  • style StyleProps — Style properties table.

typed/builtin//modules/api/engine/ui/ui/defineStyles

ui.defineStyles(styles: { [string]: StyleProps })

Define multiple named styles at once.

Parameters

  • styles { [string]: StyleProps } — Map of style name to style properties.

typed/builtin//modules/api/engine/ui/ui/defineWidget

ui.defineWidget(name: string, builderFn: (WidgetTree, { WidgetTree }) -> WidgetTree)

Register a custom widget kind. When a tree contains { type = name, props = ..., children = ... }, the decoder calls builderFn(props, children) at register / update time and substitutes the returned widget table in place. Errors surface through ui.lastValidation() with codes widget-builder-error / widget-builder-bad-return / decode-recursion-depth-exceeded.

Parameters

  • name string — Custom widget kind name.
  • builderFn (WidgetTree, { WidgetTree }) -> WidgetTree — Builder closure (props, children) -> widgetTable.

typed/builtin//modules/api/engine/ui/ui/diagnose

ui.diagnose(widgetId: string) -> WidgetPaint?

Why one widget did or did not reach the last frame. Returns that widget's row from ui.observe() — the same fields, resolved against the same reading. An id no registered screen carries reads noSuchWidget, which is how a misspelling separates from a widget whose screen is hidden and from one the frame laid out no box for.

Parameters

  • widgetId string — The id the widget records layout under.

Returns WidgetPaint? — The widget's row, or nil before the UI has published a frame.

local row = ui.diagnose("hud-healthbar")

typed/builtin//modules/api/engine/ui/ui/displayScale

ui.displayScale() -> DisplayScale

The physical scale the UI is sized at. density is the physical pixels one density-independent point covers on a handheld display (a phone, a tablet, a page in a touch browser): a point of the UI covers at least that many pixels whatever the screen's width or orientation, so text and buttons keep their physical size. It is nil on a desktop window, whose UI is sized by its width alone. textScale is the user's text size setting, which multiplies every font size the UI typesets (labels, buttons, inputs, editor chrome; canvas text is drawn at the size it names). touchTarget is the smallest target, in points, a touch reaches an interactive widget within: 48 on a handheld display, 0 on a desktop. pixelRatio is ui.pixelRatio() of the same frame. ui.simulateDisplayScale previews a phone's on any engine.

Returns DisplayScale — { density?, textScale, touchTarget, pixelRatio }.

local scale = ui.displayScale()
local buttonHeight = math.max(32, scale.touchTarget)

typed/builtin//modules/api/engine/ui/ui/dragState

ui.dragState() -> { payload: string, x: number, y: number, label: string?, ghost: boolean }?

The in-flight drag-and-drop payload while a dragPayload widget is being dragged, else nil. x/y are the pointer's position in the logical space ui.getLayoutInfo rects live in, so the reading resolves directly against widget rects. label is the text the drag ghost beside the pointer reads (dragLabel, else the source's text; nil for an outline ghost), and ghost whether the engine draws one (dragGhost) — a capture never shows the ghost, so this is how a drag's name-at-cursor is checked. Poll during a drag to drive live feedback; the drop itself still lands through the target's onDrop. Snapshotted each frame.

Returns { payload: string, x: number, y: number, label: string?, ghost: boolean }? — { payload, x, y, label?, ghost } during a drag, nil otherwise.

typed/builtin//modules/api/engine/ui/ui/elementTree

ui.elementTree(screenName: string) -> ElementNode?

Introspect a screen's rendered widget hierarchy with each element's layout rect. Every node the renderer draws appears, nested exactly as the widgets nest, under the id it records layout against: the id set on the node when the author gave it one, otherwise <screen>/<type>@<path>. bounds is that element's rect — the same table ui.getLayoutInfo(id) returns — and appears once the element has been measured. Kinds registered through ui.defineWidget appear expanded into the primitives they build. Feeds the gui.captureElement tool: list the tree, pick the ids to frame, capture their region.

Parameters

  • screenName string — Screen id passed to ui.registerScreen.

Returns ElementNode? — An ElementNode tree, or nil when no screen is registered under that name.

typed/builtin//modules/api/engine/ui/ui/fling

ui.fling(id: string, velocity: MotionValues, options: FlingOptions?)

Throw the widget id with velocity ({ x, y }, points per second): it coasts from where it is and slows until it rests, stepped by the engine each frame. A widget carrying onDrag = "<callback id>" calls its screen's onCallback every frame of a press-drag with data.value = { dx, dy, vx, vy, dragStarted, dragStopped, shift, ctrl, alt }: dx, dy the frame's movement, vx, vy the pointer's speed, which on the frame dragStopped is true is the release velocity to fling with. Move the widget under the finger meanwhile with ui.setMotion. Options: decay (seconds for the speed to fall to about a third, default 0.35; it travels about velocity * decay), bounds ({ minX, maxX, minY, maxY }: offsets it stays inside; reaching one, or starting beyond it, it springs onto it), stiffness, damping, mass (that spring, default 300, 1, 1) and onSettle (as ui.spring). Under reduced motion it moves at once to where the throw would have brought it to rest, inside its bounds.

Parameters

  • id string — The widget's id.
  • velocity MotionValues — { x?, y? } in points per second.
  • options FlingOptions (optional) — { decay?, bounds?, stiffness?, damping?, mass?, onSettle? }.
ui.fling("card", { x = 900, y = 0 }, { bounds = { minX = -200, maxX = 200 } })

typed/builtin//modules/api/engine/ui/ui/focus

ui.focus(widgetId: string)

Programmatically request keyboard focus on a widget. Queued as a one-shot; the next render of the matching widget calls response.request_focus(). A field, a button and any keyed widget carrying onClick hold it, and Enter or Space on a focused clickable widget clicks it.

Parameters

  • widgetId string — Widget id to focus.

typed/builtin//modules/api/engine/ui/ui/focusedTextField

ui.focusedTextField() -> FocusedTextField?

The text field that holds the keys: the field the person last put the caret in, in the window (place "window"), in the game view's picture ("camera"), or on a panel standing in a headset's world ("panel", with panel its xr.panels id). widget is the id the field records layout under when its screen gave it one; kind is "text", "password", "code" or "number" (an input with a number prop), and for a number number ("whole" or "decimal") and signed say which numbers it takes; multiline says whether Enter starts a new line (in a single-line field Enter submits); text and caret (in characters) are what it holds; bounds is the field's box as shares of the picture it is drawn in, 0 at the top left and 1 at the bottom right. Nil while no field holds the keys. Snapshotted each frame. ui.typeText and ui.typeKey type into this field.

Returns FocusedTextField? — The field, or nil.

local field = ui.focusedTextField()

typed/builtin//modules/api/engine/ui/ui/focusedWidget

ui.focusedWidget() -> (string?, string?)

Return the widget id of whichever widget currently holds keyboard focus, or nil, and the space it draws in: "window" for the editor's UI around the game view, "camera" for the game's own UI in the game view. Snapshotted post-render each frame.

Returns (string?, string?) — Focused widget id or nil, and its space.

local id, space = ui.focusedWidget()

typed/builtin//modules/api/engine/ui/ui/fromViewport

ui.fromViewport(x: number, y: number, space: ("camera" | "window")?) -> { x: number, y: number }

Carry a point from the scene viewport's physical pixels into the UI's logical points. The scene viewport's pixels are what input.snapshot().mouse_position, a touch, every input.events() position, worldToScreen and capture answer in, measured from the top-left of the rect the scene is drawn into.

space names the surface the answer is on (see ui.setScreenSpace): "camera" (the default) is the canvas a camera-space screen (a HUD, a game menu) states its pos and anchors on, so a widget placed at the answer sits over the point; "window" is the window, the space ui.getLayoutInfo, gui.bounds, ui.hitTest and ui.pointerWidget use, so the answer can be tested against a widget's recorded rect. The two differ while a Scene panel presents the scene inside the window.

Parameters

  • x number — X in the scene viewport's physical pixels.
  • y number — Y in the scene viewport's physical pixels.
  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns { x: number, y: number } — { x, y } in that surface's logical points.

local m = input.snapshot().mouse_position; local p = ui.fromViewport(m[1], m[2], "window"); local over = ui.hitTest(p.x, p.y)
local s = worldToScreen(0, 2, 0); local at = ui.fromViewport(s.x, s.y); ui.updateScreen("nameTag", { type = "area", id = "nameTag", pos = { at.x, at.y }, children = { { type = "label", props = { text = "NPC" } } } })

typed/builtin//modules/api/engine/ui/ui/getAreaPos

ui.getAreaPos(id: string) -> AreaPos?

Read the current pivot position of an area widget, including any user drag deltas. Returns { x, y } or nil if the area didn't render this frame.

Parameters

  • id string — Area widget id.

Returns AreaPos? — { x, y } or nil.

typed/builtin//modules/api/engine/ui/ui/getAreaSize

ui.getAreaSize(id: string) -> AreaSize?

Read the measured size of an area widget, including any user resize-grip drags if the area is resizable. Returns { w, h } or nil if the area didn't render this frame.

Parameters

  • id string — Area widget id.

Returns AreaSize? — { w, h } or nil.

typed/builtin//modules/api/engine/ui/ui/getDockLayout

ui.getDockLayout(id: string) -> string?

Read the current serialized layout (split/tab arrangement) of a dockArea widget as a JSON string. Returns nil if the dockArea didn't render this frame. Persist the string and pass it back via the dockArea's layout prop to restore the arrangement.

Parameters

  • id string — DockArea widget id.

Returns string? — Serialized DockState JSON string, or nil.

typed/builtin//modules/api/engine/ui/ui/getLayoutInfo

ui.getLayoutInfo(widgetId: string?) -> LayoutInfo?

Get layout info (position, size, content bounds) for UI containers: the box each is drawn in, which is where layout put it moved through any CSS transform it is drawn under (the upright box a rotated one covers). If widgetId is given, returns info for that widget only; otherwise returns all.

Parameters

  • widgetId string (optional) — Optional widget id to query.

Returns LayoutInfo? — Layout info table or nil.

typed/builtin//modules/api/engine/ui/ui/getPersistentDockLayout

ui.getPersistentDockLayout(id: string) -> string?

Read a dockArea's arrangement as a JSON string with every tab whose dockPanel is transient left out — the form to save and restore across sessions. Returns nil if the dockArea didn't render this frame.

Parameters

  • id string — DockArea widget id.

Returns string? — Serialized DockState JSON string without transient tabs, or nil.

typed/builtin//modules/api/engine/ui/ui/getScreenTree

ui.getScreenTree(screenName: string) -> WidgetTree?

Return the last widget tree table passed to registerScreen / updateScreen for screenName.

Parameters

  • screenName string — Screen name to query.

Returns WidgetTree? — Widget tree or nil.

typed/builtin//modules/api/engine/ui/ui/getTheme

ui.getTheme() -> string

Get the name of the currently active theme.

Returns string — Active theme name.

typed/builtin//modules/api/engine/ui/ui/getToken

ui.getToken(name: string) -> string?

Look up a single design token value from the active theme.

Parameters

  • name string — Token name (without $ prefix).

Returns string? — Token value or nil.

typed/builtin//modules/api/engine/ui/ui/getTokens

ui.getTokens() -> { [string]: string }

Get all design tokens from the active theme as a key-value map.

Returns { [string]: string } — Token map.

typed/builtin//modules/api/engine/ui/ui/getWidgetProps

ui.getWidgetProps(typeName: string) -> { WidgetPropDescriptor }?

Get the property definitions for a widget type: its own props, then the ones every widget takes (onClick, dragPayload, onDrop, tooltip, ...) marked common = true, then the style keys the type reads for its own box (pointerEvents) marked style = true, which are set in the widget's style.

Parameters

  • typeName string — Widget type name.

Returns { WidgetPropDescriptor }? — Array of property descriptors, or nil if type not found.

typed/builtin//modules/api/engine/ui/ui/getWidgetTypes

ui.getWidgetTypes() -> { string }

Get all available widget type names that can be used in widget trees.

Returns { string } — Array of widget type names.

typed/builtin//modules/api/engine/ui/ui/hideScreen

ui.hideScreen(name: string) -> boolean

Hide a registered screen, and report whether a screen by that name is registered. The engine applies the hide later in the frame; listScreens reflects it from the next call onwards.

Parameters

  • name string — Screen identifier to hide.

Returns boolean — True when a screen by this name is registered.

typed/builtin//modules/api/engine/ui/ui/hitTest

ui.hitTest(x: number, y: number) -> PaintHitTest?

Which widget a pointer at (x, y) reaches, and the stack beneath it. Coordinates are logical points on the window, the space getLayoutInfo and gui.bounds rects are in wherever a widget's screen draws (a screen in the Scene view's picture included). A widget that takes no pointer is passed over, and the answer is the widget beneath it: one declaring pointerEvents = "none", and a container that only lays out its children, filling nothing and answering no pointer. stack lists the widgets that take the pointer at the point, topmost first, with each container holding one of them after the widgets it holds.

Parameters

  • x number — Logical X.
  • y number — Logical Y.

Returns PaintHitTest? — { widget, screen, stack, x, y } — widget nil when the point is over no UI — or nil before the UI has published a frame.

local hit = ui.hitTest(640, 360)

typed/builtin//modules/api/engine/ui/ui/hitTestRegions

ui.hitTestRegions(regions: { PressRegion }, opts: HitTestRegionsOpts?) -> { RegionHit }?

Which widget answers a press inside each of regions: the region counterpart of ui.hitTest, for a caller that draws something over the UI and needs to know whether a press anywhere on it would do something in the UI beneath. Each region is a rect { x, y, width, height } or a disc { x, y, radius }, in logical points on the window (the space ui.hitTest and ui.getLayoutInfo use). The answer holds one { widget, screen, takesHold } per region, in the order given. Of the widgets the last frame drew that take the pointer and whose visible box meets the region, a press there reaches those of the highest stacking band; of those, the answer names the smallest that answers a press (a click or a drag: a button, a slider, a text field, a scroll area, a box with onClick), the latest paint breaking a tie, so a label inside a button answers through the button. takesHold is true when holding or dragging that press does something on the widget: a slider, a text field, a scroll area, a widget with onDrag, onPointerDown, onPointerUp, onContextMenu or dragPayload, or one stating holdsPointer or keepsTouchDrag. widget is nil where nothing takes the pointer there, and where what the press reaches answers none of it (a label, a filled box, a full-screen tint). opts.space ("camera" or "window") counts only the screens drawn on that surface, and opts.except leaves out the screens it names.

Parameters

  • regions { PressRegion } — The regions, in logical points on the window.
  • opts HitTestRegionsOpts (optional) — { space?, except? }. Optional.

Returns { RegionHit }? — One { widget, screen, takesHold } per region, or nil before the UI has published a frame.

local hits = ui.hitTestRegions({ { x = 1200, y = 640, radius = 56 } }, { space = "camera" })

typed/builtin//modules/api/engine/ui/ui/idCollisions

ui.idCollisions() -> { [string]: { string } }

Element ids more than one screen recorded, each mapped to the screens that recorded it. An id addresses one element: two screens sharing one leave ui.getLayoutInfo and the gui element tools answering for whichever painted last, and the gui tools refuse such an id. Empty while every id is unique.

Returns { [string]: { string } } — Colliding id -> the screens that recorded it.

for id, screens in ui.idCollisions() do print(id, table.concat(screens, ", ")) end

typed/builtin//modules/api/engine/ui/ui/invisibilityReasons

ui.invisibilityReasons() -> { string }

Every verdict ui.diagnose can report, as a closed list.

Returns { string } — The reason names.

typed/builtin//modules/api/engine/ui/ui/lastRegistration

ui.lastRegistration() -> { name: string, layer: number? }?

The name and layer passed to the most recent ui.registerScreen call, recorded synchronously at call time. A host that mounts a nested app reads this immediately after the mount to learn which screen the nested code registered, without intercepting the ui table.

Returns { name: string, layer: number? }? — { name, layer } for the last registration, or nil if none yet.

typed/builtin//modules/api/engine/ui/ui/lastValidation

ui.lastValidation(screenName: string?) -> any

Validation diagnostics produced at the most recent registerScreen / updateScreen, plus what the render stage found while painting — unknown-font-family reports a style.fontFamily that named no registered font family, once per family per screen, wrap-label-no-width reports a label with props.wrap whose box came out narrower than its own longest word, once per label per screen, and svg-not-as-declared reports an svg widget whose document declared something the picture does not hold — a <text> whose font-family selected no registered family, a <text> the picture holds no glyph of, or a shape whose url(#id) paint resolved to nothing — once per finding per widget per screen, and layout-unsettled reports a screen whose layout was still changing when a frame ran out of layout passes, so that frame painted it before it settled; widgetId names a tree still moving, and the finding is withdrawn once a frame paints the screen settled. With no args returns a { [screen] = entry } map; with a name returns that screen's entry or nil. Validation gated by world setting ui.validation = "off" | "warn" | "strict" (default "warn").

Parameters

  • screenName string (optional) — Optional screen name.

Returns any — Validation entry, full map, or nil.

typed/builtin//modules/api/engine/ui/ui/listFonts

ui.listFonts() -> { FontFamilyInfo }

Every font family a style.fontFamily can select. Read from the registry the UI text renderer resolves a family token through, so a family this returns is one a label renders in. family and every name in aliases are accepted as a fontFamily, case-insensitively; aliases carries the web-font names, CSS generic families and face names that select the same group. faces names the concrete face in each weight/style slot, so a fontWeight = 700 against a family with no bold face gets a synthesised heavy. more lists the other faces registered in the family's slots, each drawing the codepoints the slot's face lacks: the installed chunks of an on-demand face (font.onDemand() lists them all). system = true marks a family taken from the host OS — present on this machine, absent on one without it, and absent on WASM — so a UI that must look the same everywhere picks a family with system = false. A fontFamily naming nothing in this list is reported as an unknown-font-family warning through ui.lastValidation(screen) once the screen paints, and the text renders in the default proportional face.

Returns { FontFamilyInfo } — Array of { family, aliases, faces, more, system }, by family.

for _, f in ui.listFonts() do print(f.family) end

typed/builtin//modules/api/engine/ui/ui/listScreens

ui.listScreens() -> { ScreenSummary }

List every registered screen with its current visibility, z-order layer, renderLayer (the render-layer membership mask it draws under: the mask setScreenRenderLayer stated, else the one the surface setScreenSpace named implies, else the ui bit), editorChrome (whether the mask setScreenRenderLayer stated carries the EditorUI bit, which makes the screen the editor's own chrome; a screen placed on the window without stating it is not chrome), whether the screen has a populated root widget tree, and the space it draws in ("window" for the editor's UI, "camera" for the game's), including the register / show / hide / unregister calls the running script has already made. Sorted by layer ascending, then name.

Returns { ScreenSummary } — Array of screen summaries.

typed/builtin//modules/api/engine/ui/ui/listThemes

ui.listThemes() -> { string }

List all registered theme names.

Returns { string } — Array of theme names.

typed/builtin//modules/api/engine/ui/ui/lockOrientation

ui.lockOrientation(lock: OrientationLock)

Hold the display to the orientations lock allows: "landscape" (both landscape directions, so turning the device over turns the app with it), "portrait" (both portrait directions) or "any" (the display follows the device). A world states the orientation it plays in as world.orientation, which the engine locks to in play mode and releases in edit mode, so the editor follows the device; call this to change it while the world runs. Android turns the app at once, a browser grants the lock only to a page in fullscreen in most cases (the page asks again each time it enters fullscreen), and a desktop window presents in the shape it is given. ui.orientation() reports the lock and whether the platform holds it from the next frame. Any other value is refused by name.

Parameters

  • lock OrientationLock — "any", "landscape" or "portrait".
ui.lockOrientation("portrait")
ui.lockOrientation("any")

typed/builtin//modules/api/engine/ui/ui/matchMedia

ui.matchMedia(query: string) -> boolean

Whether the CSS media query query matches now, as a browser's matchMedia(query).matches answers. The query takes (prefers-reduced-motion: reduce), (prefers-reduced-motion: no-preference) and the bare (prefers-reduced-motion), joined by and, negated by a leading not, listed as alternatives with ,, with an optional media type (all and screen match, print does not); a leading @media is read past. The same text keys a style's @media block. A query the engine cannot evaluate is refused, naming what it takes.

Parameters

  • query string — A CSS media query.

Returns boolean — Whether it matches.

local calm = ui.matchMedia("(prefers-reduced-motion: reduce)")

typed/builtin//modules/api/engine/ui/ui/maxFileBytes

ui.maxFileBytes() -> number

The most bytes one file may bring into the UI through onFileDrop or onFilePaste. A file past it reaches the handler with error = "tooLarge" and no bytes.

Returns number — The limit, in bytes.

typed/builtin//modules/api/engine/ui/ui/missingGlyphs

ui.missingGlyphs() -> { string }

The characters the UI is showing without a glyph: each appears in text a UI surface (the window, the game view, a camera's UI overlay, a screen drawn into a texture) drew in what it last painted, and no face of the family it was drawn in has a glyph for it, so it shows as the replacement box. Every family falls back glyph by glyph to every face the UI holds, so a character here is one no installed face covers. A character a declared on-demand face covers (font.onDemand()) requests that face the frame it is met, and leaves this list once the face is installed and the next frame draws it.

Returns { string } — Sorted array of single-character strings; empty when every character drawn had a glyph.

if #ui.missingGlyphs() > 0 then print(table.concat(ui.missingGlyphs(), " ")) end

typed/builtin//modules/api/engine/ui/ui/motion

ui.motion(id: string) -> MotionReading

Where the widget id's motion stands, as the last frame left it: each channel's value, velocity and target (where it comes to rest), and whether it is moving. A widget with no motion (never moved, or back at rest where layout puts it) reads at its layout place: x 0, y 0, scale 1, opacity 1, not moving. A motion started this frame reads from the next.

Parameters

  • id string — The widget's id.

Returns MotionReading — { x, y, scale, opacity, velocity, target, moving }.

local m = ui.motion("menu"); if not m.moving then print("rests at", m.y) end

typed/builtin//modules/api/engine/ui/ui/observe

ui.observe(screenName: string?) -> PaintObservation?

What the last UI frame painted. Returns { generation, viewport, pointer, pointerOverUi, pointerWidget, widgets } with one widgets row per widget any registered screen holds — its layout box, the clip chain it painted under, the part of that box which reached the frame (visible), the order it painted in (paintIndex), and its reason from the closed set ui.invisibilityReasons() lists. Every rect, the reading's viewport (the window) and pointer are in logical points on the window; a row's viewport is the region the pass that drew it paints into (the whole window, or the rect a Scene panel presents the camera's picture in), and offViewport is judged against it. generation advances once per re-rendered frame, so two calls reporting the same number describe the same frame.

Parameters

  • screenName string (optional) — Narrow the rows to one screen. Omit for every screen.

Returns PaintObservation? — The reading; nil before the UI has published a frame, and nil for a screenName no registered screen answers to.

local reading = ui.observe("hud")

typed/builtin//modules/api/engine/ui/ui/onCanvasChange

ui.onCanvasChange(callback: (canvas: Canvas, previous: Canvas) -> (), space: ("camera" | "window")?) -> () -> ()

Call callback once for every change of the canvas a screen lays out on, with the new reading and the one before it, as ui.canvas(space) returns them: the canvas resized (a window resized, a Scene panel dragged, a preview size set), turned between portrait and landscape, carried to another pixel ratio, or its safe area or on-screen controls changed. It is how a screen whose layout is computed in Luau from the canvas (a HUD that rearranges between portrait and landscape, boxes placed by pos, a grid sized to the width) lays itself out again: lay it out once from ui.canvas(), then again in the callback.

The callback runs on the frame after the change, once however many of the canvas's values changed together, and never for a frame that changed none. It runs in every mode (edit mode, paused play, a time scale of 0), so a screen follows the canvas wherever it is shown. A listener a component registered ends when that component is removed or reloaded, and every other listener goes on hearing changes until the function it returns is called.

Parameters

  • callback (canvas: Canvas, previous: Canvas) -> () — Receives (canvas, previous): the new reading and the one it replaces.
  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns () -> () — A function that removes this listener.

local function layout(c) ui.updateScreen("hud", buildHud(c.width, c.height, c.orientation)) end; layout(ui.canvas()); local off = ui.onCanvasChange(layout)
local off = ui.onCanvasChange(function(c, was) print(was.width .. "x" .. was.height .. " -> " .. c.width .. "x" .. c.height) end)

typed/builtin//modules/api/engine/ui/ui/onOrientationChange

ui.onOrientationChange(callback: (reading: OrientationReading) -> ()) -> () -> ()

Call callback with the new reading every time ui.orientation() changes: the display turns between landscape and portrait or to another rotation, the lock changes, or the platform starts or stops holding it. It is called in every mode (edit mode, paused play, a time scale of 0), on the frame after the change. A listener a component registered ends when that component is removed or reloaded, and every other listener goes on hearing changes until the function it returns is called.

Parameters

  • callback (reading: OrientationReading) -> () — Receives the reading, as ui.orientation() returns it.

Returns () -> () — A function that removes this listener.

local off = ui.onOrientationChange(function(o) print(o.current, o.rotation) end)

typed/builtin//modules/api/engine/ui/ui/onReducedMotionChange

ui.onReducedMotionChange(callback: (reading: ReducedMotion) -> ()) -> () -> ()

Call callback with the new reading every time ui.reducedMotion() changes: the person changes the OS setting while the engine runs, or an in-app preference is stated or withdrawn. It is called in every mode (edit mode, paused play, a time scale of 0), on the frame after the change. A listener a component registered ends when that component is removed or reloaded.

Parameters

  • callback (reading: ReducedMotion) -> () — Receives the reading, as ui.reducedMotion() returns it.

Returns () -> () — A function that removes this listener.

local off = ui.onReducedMotionChange(function(m) print("reduce motion:", m.reduce) end)

typed/builtin//modules/api/engine/ui/ui/orientation

ui.orientation() -> OrientationReading

The orientation the display presents the app in, and the lock it is held to. current is "landscape" (wider than tall) or "portrait": the shape of the window the app presents in. lock is what ui.lockOrientation last asked, "any" when the display follows the device. enforced is whether the platform holds the display to it: Android always does, a browser does once it grants the Screen Orientation lock, and a desktop window never does, presenting in the shape it is given; reason names why when it does not. rotation is the display's rotation from its natural orientation in degrees (0, 90, 180, 270) where the platform states one, and nil on a desktop window. revision advances every time any of these changes; ui.onOrientationChange calls back on each change.

Returns OrientationReading — { current, lock, enforced, reason?, rotation?, revision }.

if ui.orientation().current == "portrait" then print("lay the HUD out for a tall screen") end

typed/builtin//modules/api/engine/ui/ui/paintGeneration

ui.paintGeneration() -> number

The generation of the last frame's paint reading (ui.observe()), read without building the reading. It advances once per re-rendered frame and stands still otherwise, so something derived from the reading (a ui.hitTest, a ui.hitTestRegions answer) still holds while this reads the number it was derived at.

Returns number — The generation, 0 before the UI has published a frame.

local gen = ui.paintGeneration()

typed/builtin//modules/api/engine/ui/ui/paintOrder

ui.paintOrder(a: string, b: string) -> number?

Which of two widgets paints later: -1 when a paints before b, 1 when after, 0 when level. This is what separates two widgets whose rects are identical.

Parameters

  • a string — First widget id.
  • b string — Second widget id.

Returns number? — -1, 0, 1, or nil when the reading holds no row for one of them.

local order = ui.paintOrder("panel-a", "panel-b")

typed/builtin//modules/api/engine/ui/ui/pixelRatio

ui.pixelRatio(space: ("window" | "camera")?) -> number

Physical pixels per logical point of one of the two surfaces a screen lays out on (see ui.setScreenSpace).

"window" (the default) is the window. ui.getLayoutInfo and gui.bounds rects, ui.hitTest and ui.pointerWidget answer in its points, wherever the widget's screen draws; input.simulateMouse*, the Zin.test pointer primitives and inputSim with target "ui" take its physical pixels. A rect times this ratio is a window pixel.

"camera" is the camera's picture: the canvas a camera-space screen's pos and anchors are stated on, laid over the scene viewport's physical pixels, the space input.snapshot().mouse_position, input.events(), worldToScreen, screenToRay and capture speak.

The two are one number wherever the scene fills the window. While a Scene panel presents the scene in a rect of the window, the picture's canvas is fitted to that rect, so its ratio follows the panel's width (and is at least the density a display states), and the scene viewport's pixels are measured from that rect's top-left (camera.viewData().viewport, whose scaleX / scaleY are its pixels per window pixel while a device screen's size is shown scaled to fit the panel) while the window's are measured from the window's. ui.fromViewport and ui.toViewport carry a point across both steps in one call.

Parameters

  • space ("window" | "camera") (optional) — "window" (default) or "camera".

Returns number — Physical pixels per logical point of that surface (1.0 when unscaled).

local r = ui.pixelRatio(); local b = tools.use("gui", "bounds", "play"); input.simulateMouseMove(b.centerX * r, b.centerY * r)

typed/builtin//modules/api/engine/ui/ui/pointerWidget

ui.pointerWidget() -> PointerRead?

Whether the UI is consuming the pointer, and which widget holds it — the pointer counterpart of ui.focusedWidget(). x, y are in logical points on the window, the space getLayoutInfo rects are in.

Returns PointerRead? — { x, y, overUi, widget, screen }, or nil before the UI has published a frame.

typed/builtin//modules/api/engine/ui/ui/reducedMotion

ui.reducedMotion() -> ReducedMotion

Whether the person asked for less motion, and where that came from. reduce is true while motion is reduced: animate less (drop drift, overshoot and travel; prefer a short cross-fade or an immediate change). platform is the OS setting as the platform states it: Android's Remove animations, a browser's prefers-reduced-motion, or the animation settings of Windows, macOS and the desktop Linux portal, as "reduce" or "no-preference"; "unknown" where the platform states no such setting, which is not the same as off. platformSource names what it was read from, or why the platform states none. setting is the in-app preference ui.setReducedMotion stated, which wins over the platform's while it stands; a world's ends when the world's scripts end, and while a world's and a trusted screen's both stand the one stated last is setting. source says which of them decided ("setting", "platform" or "none"). revision advances on every change; ui.onReducedMotionChange calls back on each. A style follows the same preference with no Luau through an ["@media (prefers-reduced-motion: reduce)"] block (see the styling guide), and ui.matchMedia tests any media query.

Returns ReducedMotion — { reduce, platform, platformSource?, setting?, source, revision }.

if ui.reducedMotion().reduce then print("show the change at once") end

typed/builtin//modules/api/engine/ui/ui/refreshLiveText

ui.refreshLiveText() -> number

Read again the text of every screen this VM registered whose text resolves when it is read: a text, title, header, placeholder, tooltip or dropdown option given as a value with a __tostring metamethod, such as an i18n.text value, rather than as a string. The i18n module calls it whenever the player's language, the pseudo-locale or a catalog changes, so a screen built from i18n.text values follows them without being built again.

Returns number — How many screens were read again.

local tree = { type = "label", props = { text = i18n.text("hud.title") } }

typed/builtin//modules/api/engine/ui/ui/registerBackgroundShader

ui.registerBackgroundShader(shaderHandle: any?, width: number?, height: number?)

Register a screen-domain .shader as a UI background, drawn via the backgroundShader style. Takes the shader's asset handle from asset.resolve. A shader whose compile failed (shaderHandle:compileStatus() reads failed), or whose program the compile gate refuses, is not registered: the call raises an error naming the shader and the compiler's message, the one compileStatus().error reads. A shader whose compileStatus() still reads pending raises too: register it once it reads compiled.

Parameters

  • shaderHandle any (optional) — The screen .shader's asset handle, from asset.resolve.
  • width number (optional) — Render target width (default 1280).
  • height number (optional) — Render target height (default 720).

typed/builtin//modules/api/engine/ui/ui/registerCallbackEnv

ui.registerCallbackEnv(key: string, env: { [string]: any })

Register an environment table to receive widget callbacks: its onCallback(id, value) fires for any widget callback not owned by a specific component instance — the same broadcast a component's onCallback receives. Registered from a component instance's own code (its hooks, methods and the closures they create), the env joins that instance: every callback the instance owns, the ones on the screens it registered, reaches the env as well as the instance's own top-level onCallback. Keyed by key; re-registering the same key replaces the previous env. Reach for this from a context that hosts a UI surface with a handler of its own (a scene entrypoint, a module, a component's local handler). Pair with ui.unregisterCallbackEnv(key) so the ref is released.

Parameters

  • key string — Stable identifier for this registration (re-register replaces).
  • env { [string]: any } — Environment table whose onCallback receives the broadcasts.

typed/builtin//modules/api/engine/ui/ui/registerScreen

ui.registerScreen(name: string, widgetTree: WidgetTree, layer: number?)

Register a named UI screen with a widget tree. Optional layer controls z-ordering (higher = on top), in bands: below 0 behind everything, 0-99 ordinary app depth, 100-999 always-on-top chrome, 1000+ menu and popup depth. A screen in a higher band covers one in a lower band whatever their roots are; inside a band a floating area or window root sits over ordinary content, and a modal root sits over the whole stack. Tag-based grouping lives in Z.tags (Z.tags.set(name, { "editor" }) after register). A screen belongs to the component instance whose own code registers it (its hooks and methods, and any closure they create, such as a listener it subscribes): that instance's onCallback receives its callbacks, and the screen is unregistered when the instance ends. Code that is not an instance's own (a scene entrypoint, a module, a listener either subscribed) registers a screen no instance owns, which stays until it is unregistered, whichever component's hook ran that code. topics/ui has the rule.

Parameters

  • name string — Unique screen identifier.
  • widgetTree WidgetTree — Root widget table.
  • layer number (optional) — Z-order layer (optional).
ui.registerScreen("hud", tree)

typed/builtin//modules/api/engine/ui/ui/registerTheme

ui.registerTheme(name: string, theme: ThemeDefinition)

Register a theme from a flat Luau table. Most callers should use Z.theme.register(name, table) which runs the cascade for them.

Parameters

  • name string — Theme name to register.
  • theme ThemeDefinition — Flat-resolved theme table.

typed/builtin//modules/api/engine/ui/ui/removeScreen

ui.removeScreen(name: string) -> boolean

Alias for ui.unregisterScreen.

Parameters

  • name string — Screen identifier to remove.

Returns boolean — True when a screen by this name was registered.

typed/builtin//modules/api/engine/ui/ui/resetAreaSize

ui.resetAreaSize(id: string)

Clear a resizable area's remembered size (from a grip drag or ui.setAreaSize) so its declared — or content — size takes over again.

Parameters

  • id string — Area widget id.

typed/builtin//modules/api/engine/ui/ui/response

ui.response(widgetId: string) -> WidgetResponse?

Per-widget interaction snapshot for the most recent frame. Returns { clicked, hovered, focused, changed, value } where clicked / changed mark transitions and hovered / focused mark current state.

Parameters

  • widgetId string — The widget id (NOT the onClick / onChange callback id).

Returns WidgetResponse? — WidgetResponse or nil.

typed/builtin//modules/api/engine/ui/ui/safeArea

ui.safeArea(space: ("camera" | "window")?) -> SafeArea

The part of one of the two surfaces a screen lays out on (see ui.setScreenSpace) that no system bar, display cutout or on-screen keyboard covers, in the logical points ui.screenSize(space) reports. "camera" (the default) is the camera's picture, where a HUD or any camera-space screen lays out; "window" is the window, where the editor's chrome lays out. Each is that surface's own area whether or not a screen is shown on it, and the two are one wherever the scene fills the window. top / right / bottom / left are how far in from each edge the covered band reaches; x / y / width / height are the rect they leave; cutouts lists each display cutout (a camera hole or a notch) as { x, y, width, height }. Screens lay out inside this rect, so anchors, top-level % sizes and a window's default position already keep clear of it; read it to place something by absolute pos, or to run a background under the bars while its controls stay inside.

controls lists each rect an on-screen control drawn over the picture covers, as { x, y, width, height, owner }: the engine's touch buttons and its Menu button while the touch controls show (owner "zin_touch_controls"), and every rect a world states with ui.setControlRegions. An anchor of any other screen keeps clear of them on its own; a box placed by pos, padding or flex reads them to stay out from under a control, where a press would reach the control instead of the widget.

revision advances every time the area, the size of its surface or the controls change (a rotation, the system bars shown or hidden, the keyboard opening, a resize, a control shown, hidden or moved): compare it with the one you last laid out against, or subscribe with ui.onCanvasChange, which calls back on each change of the area and of the canvas it is stated on. All zero on a desktop window; ui.simulateSafeArea lays the UI out as a phone would on any engine, on the window and on the picture a Scene panel presents.

Parameters

  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns SafeArea — { top, right, bottom, left, x, y, width, height, cutouts, controls, revision } in that surface's logical points.

local safe = ui.safeArea()
ui.setAreaPos("hud", safe.x + 8, safe.y + 8)
for _, c in ipairs(ui.safeArea().controls) do print(c.owner, c.x, c.y, c.width, c.height) end

typed/builtin//modules/api/engine/ui/ui/screen

ui.screen(name: string) -> { [string]: any }?

Get a screen proxy with methods like setResolution and rasterize.

Parameters

  • name string — Screen name.

Returns { [string]: any }? — Screen proxy table, or nil.

typed/builtin//modules/api/engine/ui/ui/screenRefusal

ui.screenRefusal(screenName: string) -> string?

Why the code calling may not reach the screen screenName, or nil when it may: a private screen (setScreenPrivate) is reached by the account's own code alone. Code that acts on such a screen on its caller's behalf, such as an editor panel's exported functions, raises it before it acts.

Parameters

  • screenName string — The screen name.

Returns string? — The refusal, or nil.

local why = ui.screenRefusal("edui_p_memory"); if why then error(why, 2) end

typed/builtin//modules/api/engine/ui/ui/screenSize

ui.screenSize(space: ("camera" | "window")?) -> { width: number, height: number }

The canvas one of the two surfaces a screen lays out on spans, as { width, height } in logical points: the space that surface's area pos and anchors are stated in (see ui.setScreenSpace).

"camera" (the default) is the camera's picture, where a camera-space screen lays out: a HUD, a game menu, any content UI that states no other space. It is the canvas ui.fromViewport(x, y) answers on, so a HUD clamps a marker to ui.screenSize() and places it at ui.fromViewport of a worldToScreen projection. "window" is the window, where the editor's chrome lays out and ui.getLayoutInfo rects are recorded. Each is that surface's size whether or not a screen is shown on it, and the two are one size wherever the scene fills the window; while a Scene panel presents the scene inside the window, the camera's canvas is fitted to the panel, or laid out as the device screen renderer.setPictureSize draws the panel's picture at. Neither is the pixel size of a capture screenshot, which may be downscaled.

It follows the size the engine draws at, and renderer.setViewportSize changes that size for the task that asks, which is how a layout written against this is checked at a second shape without rebooting the engine, read in the call that set the size before the surface goes back; renderer.setPictureSize does the same for the camera's canvas alone while a Scene panel presents it. The pixel size behind the window's points is renderer.surfaceSize(), the whole drawing surface, which an editor layout makes larger than the rect renderer.viewportSize() draws the scene into. ui.pixelRatio(space) is the factor between a surface's points and its pixels.

The size changes while the engine runs (a window resized, a phone rotated, a Scene panel dragged), and a layout computed from it is computed again when it does: ui.onCanvasChange(fn, space) calls back once for each change, and ui.canvas(space) reads the size with the pixel ratio, the safe area and a revision that advances on each.

Parameters

  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns { width: number, height: number } — { width, height } in that surface's logical points.

local w = worldToScreen(0, 2, 0); local p = ui.fromViewport(w.x, w.y); local s = ui.screenSize(); local onCanvas = p.x >= 0 and p.x <= s.width and p.y >= 0 and p.y <= s.height

typed/builtin//modules/api/engine/ui/ui/scroll

ui.scroll(deltaX: number, deltaY: number)

Simulate a mouse-wheel scroll event on the UI.

Parameters

  • deltaX number — Horizontal scroll delta.
  • deltaY number — Vertical scroll delta.

typed/builtin//modules/api/engine/ui/ui/setAreaPos

ui.setAreaPos(id: string, x: number, y: number)

Programmatically move a movable area widget to (x, y). Applied for one frame; subsequent frames let drag tracking take over.

Parameters

  • id string — Area widget id.
  • x number — Target pivot x (screen coords).
  • y number — Target pivot y (screen coords).

typed/builtin//modules/api/engine/ui/ui/setAreaSize

ui.setAreaSize(id: string, w: number, h: number)

Programmatically set a resizable area's size (the user-size override) — for maximize / restore / tile. Persists until the area's declared width/height changes or ui.resetAreaSize(id) clears it.

Parameters

  • id string — Area widget id.
  • w number — Target width (screen coords).
  • h number — Target height (screen coords).

typed/builtin//modules/api/engine/ui/ui/setControlRegions

ui.setControlRegions(owner: string, rects: { SafeAreaRect }?)

State the rects the on-screen controls owner draws over the camera's picture cover, each { x, y, width, height } in the logical points ui.screenSize() reports. ui.safeArea().controls lists them from this call on, its revision advances, and from the next frame an anchor of any other screen that would land on one moves inward clear of it (a box pinned to the right edge moves left, one pinned to the top moves down, along whichever axis is the shorter move), keeping its margin from the control as it keeps it from the edge. Anchors keep clear of them while the screen keeps the size ui.screenSize() reported at the call, so restate them whenever the controls move and after the screen changes size (a rotation or a window resize advances ui.safeArea().revision), and call with nil or {} to withdraw them. The engine's touch controls state theirs under "zin_touch_controls"; a world drawing on-screen controls of its own states them under the name of the screen it draws them on, so that screen's own anchors stay where it put them. A negative size or a non-number is refused by name.

Parameters

  • owner string — Who draws the controls: the name of the screen they are drawn on.
  • rects { SafeAreaRect } (optional) — { { x, y, width, height } } in logical points; nil or {} withdraws them.
ui.setControlRegions("myTouchPad", { { x = 1100, y = 520, width = 160, height = 160 } })
ui.setControlRegions("myTouchPad", nil)

typed/builtin//modules/api/engine/ui/ui/setDockWindowRect

ui.setDockWindowRect(dockId: string, panelId: string, x: number, y: number, width: number, height: number)

Place the floating window of a dockArea panel at (x, y) with size (width, height). Applies once the panel occupies a window — a request made before then waits for it.

Parameters

  • dockId string — DockArea widget id.
  • panelId string — Id of the panel held by the window to place.
  • x number — Window left edge (screen coords).
  • y number — Window top edge (screen coords).
  • width number — Window width (screen coords).
  • height number — Window height (screen coords).

typed/builtin//modules/api/engine/ui/ui/setMotion

ui.setMotion(id: string, values: MotionValues)

Place the widget id at values ({ x?, y?, scale?, opacity? }, as ui.spring takes them) at once, at rest, ending any motion of the channels it names; a placement that leaves no channel of a spring or fling moving runs its onSettle, as ui.stopMotion does. Nothing is laid out anew and no screen tree is sent: a script running its own simulation states each frame's positions this way, or many widgets' at once with ui.setMotions.

Parameters

  • id string — The widget's id.
  • values MotionValues — { x?, y?, scale?, opacity? }.
ui.setMotion("cursor_ghost", { x = 12, y = -4 })

typed/builtin//modules/api/engine/ui/ui/setMotions

ui.setMotions(values: { [string]: MotionValues })

Place many widgets at once: values maps each widget id to { x?, y?, scale?, opacity? }, as ui.setMotion takes them. One call a frame moves a whole field of widgets a script simulates (bubbles that drift and push each other apart) with no screen tree sent again.

Parameters

  • values { [string]: MotionValues } — { [id]: { x?, y?, scale?, opacity? } }.
ui.setMotions({ a = { x = 10, y = 4 }, b = { x = -3, y = 12, scale = 1.1 } })

typed/builtin//modules/api/engine/ui/ui/setReducedMotion

ui.setReducedMotion(reduce: (boolean | MotionPreference)?) -> boolean

State the in-app reduced-motion preference, which wins over the OS setting while it stands: true (or "reduce") reduces motion, false (or "no-preference") asks for full motion, and nil withdraws it so the OS setting stands again. An app's own "Reduce motion" switch calls this. A world's preference ends when the world's scripts end; a trusted screen's stands for the life of the engine, and while both stand the one stated last decides. ui.reducedMotion(), ui.matchMedia and every style's @media (prefers-reduced-motion) block follow it from the next frame. Any other value is refused by name.

Parameters

  • reduce (boolean | MotionPreference) (optional) — true / "reduce", false / "no-preference", or nil to withdraw it.

Returns boolean — Whether the preference changed.

ui.setReducedMotion(true)
ui.setReducedMotion(nil)

typed/builtin//modules/api/engine/ui/ui/setScreenPrivate

ui.setScreenPrivate(screenName: string)

State that the screen screenName draws what the person keeps for themselves, whether or not it is registered yet, for as long as the engine runs. From then on it is reached by the account's own code alone (the editor, the agent's tools and execute): code a world ships reads nothing it draws (getScreenTree, elementTree, paintSnapshot, getLayoutInfo, widgetState, focusedTextField, /runtime/ui/<name>/), drives none of it (registering, updating, showing, hiding or unregistering it, click on an id its widgets emit, focus, typeText into its field, a widget of another screen emitting an id its widgets emit) and hears none of its callbacks. The account's own code alone states it; code a world ships is refused. An editor panel states it with private = true in its spec.

Parameters

  • screenName string — The screen name.
ui.setScreenPrivate("edui_p_memory")

typed/builtin//modules/api/engine/ui/ui/setScreenRenderLayer

ui.setScreenRenderLayer(name: string, mask: number)

Set a screen's render-layer membership bitmask. A screen draws into a camera or capture only when this mask intersects the camera's include mask, the same rule geometry follows. Content UI carries the ui bit; the editor places its chrome on EditorUI so agent captures can drop it, and a screen carrying that bit is part of the window rather than the camera's picture. Stating a mask here fixes the membership: a screen left to itself takes the one the surface it is placed on implies, EditorUI for the window and ui for the camera's picture. __renderLayers.bit(name) answers with a layer's bit INDEX, so a mask sets the bit at that index and __renderLayers.names(mask) reads it back as the names it holds.

Parameters

  • name string — Screen identifier.
  • mask number — Render-layer membership bitmask — the OR of bit32.lshift(1, __renderLayers.bit(name)) over the layers the screen is on.
ui.setScreenRenderLayer("hud", bit32.lshift(1, __renderLayers.bit("ui")))

typed/builtin//modules/api/engine/ui/ui/setScreenSpace

ui.setScreenSpace(name: string, space: string)

Set which surface a screen is part of. "camera" is the picture the viewport camera produces: the screen lays out over the camera's target and is drawn into it, so it sits inside the Scene panel presenting the scene and appears in every capture of the camera — the default for content UI. "window" is the window itself, whatever presents the scene — where the editor's chrome lives, and the default for a screen on the EditorUI layer. The two are one statement made from either end, so a screen placed on the window takes the EditorUI membership unless setScreenRenderLayer states another: the window goes on drawing it while a capture that drops the authoring layers, which is what an agent takes by default, leaves it out. Where the scene presents on the window, the two surfaces coincide. A name that is neither raises.

Parameters

  • name string — Screen identifier.
  • space string — "camera" | "window".
ui.setScreenSpace("agent-banner", "window")

typed/builtin//modules/api/engine/ui/ui/setScrollPosition

ui.setScrollPosition(widgetId: string, offsetY: number)

Set the scroll offset of a scrollArea widget.

Parameters

  • widgetId string — Scroll area widget id.
  • offsetY number — Vertical scroll offset in pixels.

typed/builtin//modules/api/engine/ui/ui/setShaderUniforms

ui.setShaderUniforms(name: string, uniforms: { [string]: number })

Set uniform values on a registered background shader.

Parameters

  • name string — Shader name identifier.
  • uniforms { [string]: number } — Map of uniform name to number value.

typed/builtin//modules/api/engine/ui/ui/setTheme

ui.setTheme(name: string)

Switch the active global theme by name.

Parameters

  • name string — Theme name to activate.

typed/builtin//modules/api/engine/ui/ui/showScreen

ui.showScreen(name: string) -> boolean

Make a registered screen visible, and report whether a screen by that name is registered. The engine applies the show later in the frame; listScreens reflects it from the next call onwards.

Parameters

  • name string — Screen identifier to show.

Returns boolean — True when a screen by this name is registered.

typed/builtin//modules/api/engine/ui/ui/simulateDisplayScale

ui.simulateDisplayScale(scale: DisplayScaleSpec?)

Size the UI as a display stating scale would, in place of what the platform states. A density sizes it as a handheld display of that many physical pixels per point (omit it for a desktop display sized by its width), and textScale multiplies every font size the UI typesets (1 when omitted). Previews a phone's UI on a desktop or headless engine, and makes a layout test independent of the device it runs on. ui.displayScale(), ui.screenSize() and ui.pixelRatio() report it from the next frame. Call it with no argument (or nil) to return to the platform's own scale. A value that is not a number above 0 and at most 8 is refused by name.

Parameters

  • scale DisplayScaleSpec (optional) — { density?, textScale? }; nil returns to the platform's scale.
ui.simulateDisplayScale({ density = 2.625, textScale = 1.3 })
ui.simulateDisplayScale()

typed/builtin//modules/api/engine/ui/ui/simulateSafeArea

ui.simulateSafeArea(area: SafeAreaSpec?)

Lay the UI out as if the system covered the screen by area (logical points) in place of what the platform states: each inset defaults to 0 and cutouts is a list of { x, y, width, height }. Previews a phone's status bar, camera cutout and navigation bar on a desktop or headless engine, and makes a layout test independent of the device it runs on. It covers the window, and while a Scene panel presents the scene inside the window it covers the camera's picture too, stated in that picture's points, so a game's HUD in the panel lays out inside it in edit and in play as it would on that phone. With renderer.setPictureSize sizing that picture to a phone's pixels, the panel shows what that phone shows. ui.safeArea() reports it from the next frame. Call it with no argument (or nil) to return to the platform's own safe area. A negative or non-number inset is refused by name.

Parameters

  • area SafeAreaSpec (optional) — { top?, right?, bottom?, left?, cutouts? } in logical points; nil returns to the platform's safe area.
ui.simulateSafeArea({ top = 40, bottom = 30, cutouts = { { x = 600, y = 0, width = 80, height = 40 } } })
ui.simulateSafeArea()

typed/builtin//modules/api/engine/ui/ui/spring

ui.spring(id: string, target: MotionValues, options: SpringOptions?)

Move the widget id toward target by a spring the engine steps each frame: no script runs per frame and the screen tree is not sent again. target names any of x, y (an offset in points from where layout puts the widget), scale (about its centre, 1 unscaled) and opacity (multiplying its own, 1 unchanged). The widget is drawn moved and is pressed where it is drawn; its layout box and its neighbours stay put. Calling it again mid-motion retargets from where the widget is, with the speed it has, so it never jumps. Options: stiffness (default 170), damping (the damping ratio, default 0.8: below 1 overshoots and settles, 1 arrives without overshooting), mass (default 1), velocity ({ x, y, scale, opacity } per second: a drag's release speed, or a kick with no target, which springs back to where the channel rests) and onSettle (a callback id: once every channel rests, the screen's onCallback(onSettle, data) runs with data.value = { id, x, y, scale, opacity }). Under reduced motion an opacity change is a 0.15 s cross-fade and the widget moves to its target at once, or, while it fades out, once the fade has ended, so the fade is seen where it was. A key it does not take is refused by name.

Parameters

  • id string — The widget's id.
  • target MotionValues — { x?, y?, scale?, opacity? }: where it springs to.
  • options SpringOptions (optional) — { stiffness?, damping?, mass?, velocity?, onSettle? }.
ui.spring("menu", { y = 0, opacity = 1 }, { stiffness = 400, damping = 0.6 })
ui.spring("card", { scale = 1 }, { velocity = { scale = 4 } }) -- a pop

typed/builtin//modules/api/engine/ui/ui/stopMotion

ui.stopMotion(id: string)

Hold the widget id where it is now, ending its spring or fling (a finger landing on a moving widget). Its onSettle callback runs, as for a motion that came to rest.

Parameters

  • id string — The widget's id.

typed/builtin//modules/api/engine/ui/ui/takeDockTearOffs

ui.takeDockTearOffs(id: string) -> { string }

The panel ids of the tabs dragged out of the dockArea id and released over empty space since the last call. A dock standing in an XR panel hands such a tab to its owner rather than opening a window inside itself, and keeps it out of the dock for as long as the dockArea still lists it; the owner places the panel and stops listing it. Empty for a dock drawn on the desktop window.

Parameters

  • id string — DockArea widget id.

Returns { string } — Array of panel ids.

typed/builtin//modules/api/engine/ui/ui/toViewport

ui.toViewport(x: number, y: number, space: ("camera" | "window")?) -> { x: number, y: number }

Carry a point from the UI's logical points into the scene viewport's physical pixels: the inverse of ui.fromViewport, and the space screenToRay, screenToPlanePoint and Physics.raycastScreen take, so a point read off the UI can be cast into the scene.

space names the surface the point is on: "camera" (the default) for a camera-space screen's pos / anchor coordinates, "window" for a ui.getLayoutInfo / gui.bounds rect.

Parameters

  • x number — X in that surface's logical points.
  • y number — Y in that surface's logical points.
  • space ("camera" | "window") (optional) — "camera" (default) or "window".

Returns { x: number, y: number } — { x, y } in the scene viewport's physical pixels.

local b = tools.use("gui", "bounds", "target"); local v = ui.toViewport(b.centerX, b.centerY, "window"); local hit = Physics.raycastScreen(v.x, v.y)

typed/builtin//modules/api/engine/ui/ui/typeKey

ui.typeKey(key: string, modifiers: { shift: boolean?, ctrl: boolean?, alt: boolean? }?)

Press and release key on the text field that holds the keys (ui.focusedTextField): Backspace, Delete, Enter (a new line in a multi-line field, a submit in a single-line one), Tab, Escape, the arrows, Home, End, or any other KeyboardEvent.code. modifiers names the modifiers held for it (Shift with an arrow selects). It reaches the UI alone: the game's input reads no key. Raises on a name that is not a key code.

Parameters

  • key string — The key, as a KeyboardEvent.code.
  • modifiers { shift: boolean?, ctrl: boolean?, alt: boolean? } (optional) — { shift?, ctrl?, alt? }.
ui.typeKey("Backspace")

typed/builtin//modules/api/engine/ui/ui/typeText

ui.typeText(text: string)

Type text into the text field that holds the keys (ui.focusedTextField), the way a keyboard's typed characters reach it: inserted at the caret, in place of a selection. Control characters other than a new line and a tab are left out. It reaches the UI alone: the game's input reads no key.

Parameters

  • text string — The characters to type.
ui.typeText("hello")

typed/builtin//modules/api/engine/ui/ui/unregisterCallbackEnv

ui.unregisterCallbackEnv(key: string)

Remove an environment registered with ui.registerCallbackEnv. Its onCallback stops receiving broadcasts. No-op if key isn't registered.

Parameters

  • key string — The key passed to ui.registerCallbackEnv.

typed/builtin//modules/api/engine/ui/ui/unregisterScreen

ui.unregisterScreen(name: string) -> boolean

Remove a screen from the registry entirely. Unlike hideScreen, this deletes the entry so it no longer appears in listScreens or render iteration.

Parameters

  • name string — Screen identifier to unregister.

Returns boolean — True when a screen by this name was registered.

typed/builtin//modules/api/engine/ui/ui/unregisterWidget

ui.unregisterWidget(name: string)

Drop a registered custom widget kind. Subsequent references produce an unknown-widget-type diagnostic.

Parameters

  • name string — Custom widget kind name.

typed/builtin//modules/api/engine/ui/ui/updateScreen

ui.updateScreen(name: string, widgetTree: WidgetTree)

Replace the widget tree of an already-registered screen.

Parameters

  • name string — Screen identifier to update.
  • widgetTree WidgetTree — New root widget table.

typed/builtin//modules/api/engine/ui/ui/useStyles

ui.useStyles(themeName: string)

Apply a registered style file's classes additively without changing the active theme.

Parameters

  • themeName string — Name of the registered style / theme asset.

typed/builtin//modules/api/engine/ui/ui/widgetState

ui.widgetState(widgetId: string, key: string, default: any?) -> any

Read per-widget cross-frame state. Returns the value previously written via widgetStateSet, or default (or nil). State is keyed by widget id and persists across re-renders within a screen's lifetime; cleared automatically when the owning screen is unregistered.

Parameters

  • widgetId string — Widget id whose state to read.
  • key string — State key.
  • default any (optional) — Value to return when nothing has been written.

Returns any — Stored value, default, or nil.

typed/builtin//modules/api/engine/ui/ui/widgetStateClear

ui.widgetStateClear(widgetId: string, key: string)

Remove a per-widget state entry.

Parameters

  • widgetId string — Widget id whose state to clear.
  • key string — State key.

typed/builtin//modules/api/engine/ui/ui/widgetStateSet

ui.widgetStateSet(widgetId: string, key: string, value: any?)

Write per-widget cross-frame state. Replaces any existing value under (widgetId, key). Tables are stored by reference.

Parameters

  • widgetId string — Widget id to scope the state under.
  • key string — State key.
  • value any (optional) — Value to store (must be non-nil).
  • api
  • reference