Appearance
GUI controls
clientsideClientside scripts build interface — HUDs, windows, shops, message boxes, custom chat bars — out of GUI controls: Graal-style objects such as GuiWindowCtrl, GuiButtonCtrl and GuiTextCtrl, rendered by the client's UI layer on top of everything else. This page covers creating and parenting controls, styling them, listening for mouse and keyboard events, and cleaning them up.
GUI controls are one of two ways to put things on screen. The other is script images (findimg), which are cheaper and can live in the world, but are not interactive and always draw below the GUI. Rule of thumb: anything the player clicks, types into or drags is a GUI control; decoration, floating text and effects are images.
All the declarations on this page are in the GUI controls reference.
Creating a control
Construct a control with a name, then assign properties:
ts
// weapons/hello.client.ts
export function onCreated() {
const win = new GuiWindowCtrl('Hello_Window')
win.text = 'Hello'
win.extent = '240,120' // or win.width = 240; win.height = 120
win.position = `${ScreenWidth / 2 - 120},100`
const btn = new GuiButtonCtrl('Hello_Close')
btn.text = 'Close'
btn.position = '20,50'
btn.width = 80
win.addControl(btn)
btn.on('click', () => win.destroy())
}Things worth knowing about this model:
- Names are global. Every control is registered under its name and also published as a global variable, so after the code above any script can write
Hello_Window.hide()— the classic GS2 style. Because the namespace is shared by every weapon, prefix control names with your weapon's name (Hello_Window,Shop_BuyButton,Messages_Text1). - Re-creating a name replaces the old control.
new GuiWindowCtrl('Hello_Window')a second time destroys the first one (and its children) before creating the new one, so rebuilding a UI from scratch is safe. - Writes are batched. Creation and property writes are collected and sent to the renderer once per flush window: a control costs one create plus at most one update per flush, however many properties you assign. You don't need to batch writes yourself.
- Reads are live once the control exists.
text,x,y,width,heightandvisibleread back from the renderer after the creating tick (so you see e.g. a label's auto-sized width, or a window the player dragged). Before that, reads return what you wrote.
position and extent are write-only "x,y" / "w,h" conveniences for x/y and width/height. show() / hide() toggle visible, and bringtofront() raises a control above its siblings. Style controls with the properties described below, or share a look between controls and weapons with a profile.
The control types
Every control derives from GuiControl, which carries position, size, visibility, skins, parenting and events.
| Class | What it is |
|---|---|
| GuiWindowCtrl | A draggable window with a title bar (text, plus font/fontsize/style for the title) and an optional close button (canclose). Windows always drag by their title bar. |
| GuiButtonCtrl | A push button with a text caption, styled by font, fontsize and style. |
| GuiTextCtrl | A static label with font, fontsize, style and color. Auto-sizes to its text. |
| GuiTextEditCtrl | A single-line text input with placeholder, password, readonly, font, fontsize and style, plus selection methods. |
| GuiPanelCtrl | An invisible grouping container; give it color / border props to draw a box. |
| GuiImageCtrl | Shows (a region of) an image asset, or a gani character via actor. |
| GuiDrawingPanelCtrl | A panel with a pixel canvas you draw on: images, lines, shapes and text that stay until cleared. |
| GuiScrollCtrl | A scrollable viewport; children may be larger than it. |
| GuiStretchCtrl | A container laid out at a fixed virtual resolution and scaled to its real size. |
| GuiCheckboxCtrl | A checkbox with a text label and a checked state. |
| GuiRadioCtrl | A radio button; radios sharing a parent and a group are mutually exclusive. |
| GuiSliderCtrl | A horizontal slider with min, max, value and an optional snapping step. |
| GuiDropDownCtrl | A dropdown list of items with a selected index. |
| GuiTabCtrl | A Graal-style tab bar: a row of tabs with a selected index. |
| GuiMultiLineTextCtrl | A wrapping, scrollable multi-line text area; readonly makes it a display box, and code mode makes it a small code editor. |
Labels
A GuiTextCtrl sizes itself to its text until you set width or height explicitly. The 'c' style centers text within the control's width, so set a width when centering:
ts
const title = new GuiTextCtrl('Shop_Title')
title.text = 'General Store'
title.fontsize = 24 // points, 1-256; re-rasterized, stays crisp. Default 18
title.style = 'bc' // any of b(old), i(talic), c(entered)
title.color = '255,220,120'
title.width = 300 // needed for 'c' to have a box to center infont defaults to 'opensans', which ships with the client. Other families come from the server; see Fonts. To lay out text before creating a label — word-wrapping a long message into pages, right-aligning a hint — use measuretext, which measures exactly the way a label renders.
Fonts
font, fontsize and style work on labels, buttons (the caption), text edits (the text and placeholder) and windows (the title). On controls other than labels, style only takes 'b' and 'i'; they keep their themed alignment. font = '' returns a control to its default font.
Font families are files the server provides in its font folders (assets/fonts/ by default): font = 'Tahoma' loads Tahoma.ttf, and bold/italic use Tahoma-Bold.ttf, Tahoma-Italic.ttf and Tahoma-BoldItalic.ttf when present. Text shows in the default font until the family has downloaded, and stays in it when the server doesn't have the family. The client never uses the player's installed system fonts, so everyone sees the same text. Naming, formats and licensing are covered under Custom fonts.
ts
const ok = new GuiButtonCtrl('Shop_Buy')
ok.text = 'Buy'
ok.font = 'PressStart2P' // assets/fonts/PressStart2P.ttf
ok.fontsize = 10
ok.style = 'b'Text inputs
ts
const edit = new GuiTextEditCtrl('Login_Password')
edit.placeholder = 'Password'
edit.password = true // only takes effect in the creating tick
edit.width = 200
edit.onTextChanged = text => { this.pw = text }password must be set in the same tick the control is created; it has no effect afterwards. The current value is always readable as edit.text.
Submitting with Enter
A text edit fires submit when the player presses Enter in it, with the text as e.text (GuiTextSubmitEvent). It's the event to finish an entry on, such as sending a chat line or confirming a name, and it works the same on every platform: on iOS the on-screen keyboard's done key fires it. The box keeps focus afterwards, so clear it or release focus yourself:
ts
const input = new GuiTextEditCtrl('Chat_Input')
input.on('submit', e => {
if (e.text) sendchat(e.text)
input.text = ''
input.makefirstresponder(false) // on iOS this also closes the keyboard
})submit fires on the text edit itself and doesn't bubble. Multi-line text controls don't have it, because there Enter types a newline.
Typing on iOS
On iOS, focusing a text edit (tapping it, or makefirstresponder()) opens the on-screen keyboard and a text field across the top of the screen that shows what's being typed. Each keystroke goes straight into the control, so text, onTextChanged and change update live as the player types. The keyboard's done key fires submit. The keyboard closes when the control loses focus, for example when the player taps the game or your script calls makefirstresponder(false). Closing the keyboard yourself takes focus away from the control.
Disabled controls
Buttons and text inputs (GuiButtonCtrl, GuiTextEditCtrl, GuiMultiLineTextCtrl) can be disabled with active = false, Graal's name for it. A disabled control draws grayed out. It can't be clicked, typed into, focused or tabbed to, and it fires no click, mousedown, mouseup, doubleclick, mousewheel or touch events. Hover events (mouseenter, mousemove, mouseleave) still fire, so you can show a tooltip explaining why. Disabling a focused input releases its focus. Other control kinds don't take active, and writing it on them throws.
A disabled control still covers the game, so clicks on it don't fall through. For render-only UI that the mouse should pass through, use interactive instead.
A skinned control grays its normal region while disabled. Give it a dedicated region with skinrectdisabled, which profiles can carry too:
ts
const buy = new GuiButtonCtrl('Shop_Buy')
buy.text = 'Buy'
buy.profile = 'Theme_Button' // its skinrectdisabled shows while disabled
buy.active = gold >= price // re-assert whenever gold changesRead-only text and selection
Both text controls, GuiTextEditCtrl and GuiMultiLineTextCtrl, take readonly = true: the player can still focus, select and copy (Ctrl+C) the text but can't change it. Script writes to text still apply.
Scripts select text with setselection(start, end) (characters start up to, not including, end) or selectall(). Indices are clamped to the text, and the caret moves to end. The current selection is a live read through selectionstart, selectionend and selectedtext. When nothing is selected, selectionstart and selectionend are both the caret position. The highlight shows even when the control doesn't have focus.
The caret has its own pair: setcursorpos(pos) moves it to a character index (0 is before the first character, text.length after the last) and clears any selection, and cursorpos reads where it is now. The position is clamped to the text, and the box scrolls to keep the caret in view. Like a selection, it's applied after a same-tick text write, so a script can replace the text and park the caret in one go:
ts
// Insert a tag at the caret and put the caret right after it.
const chat = new GuiTextEditCtrl('Chat_Input')
function insertTag(tag: string) {
const at = chat.cursorpos
chat.text = chat.text.slice(0, at) + tag + chat.text.slice(at)
chat.setcursorpos(at + tag.length)
}The caret (and a multiline box's selection highlight) is as tall as one line of the control's font, so it follows fontsize, font and GUI scaling.
ts
// A copyable invite code: focused and fully selected, ready for Ctrl+C.
const code = new GuiTextEditCtrl('Invite_Code')
code.text = 'MYTH-4F2K-91QZ'
code.readonly = true
code.width = 200
code.makefirstresponder()
code.selectall() // applied after text and focus in the same tick
// Pre-fill a name and select only the editable part.
const name = new GuiTextEditCtrl('Pet_Name')
name.text = 'Sir Fluffington'
name.setselection(4, 15) // "Fluffington"Selection changes made in the same tick apply after any text write and makefirstresponder(). Selection reads come from the client, so they reflect a setselection only after it has been flushed (the next tick).
Form controls
Checkboxes, radios, sliders, dropdowns, tab bars and multi-line text areas all report user changes through one event, change, whose payload depends on the control (see the table below). Script writes to their values (checked, value, selected, items, tabs, text) never fire it, so a handler doesn't loop when it sets another control. Every value is also a live read.
| Control | Value props | change payload |
|---|---|---|
| GuiCheckboxCtrl | checked, text | GuiCheckChangeEvent {checked} |
| GuiRadioCtrl | checked, group, text | GuiCheckChangeEvent, only on the radio that became checked |
| GuiSliderCtrl | min, max, range, value, step | GuiSliderChangeEvent {value}, repeatedly while dragging |
| GuiDropDownCtrl | items, selected, selectedtext | GuiSelectChangeEvent {index, text} |
| GuiTabCtrl | tabs, selected, selectedtext | GuiSelectChangeEvent {index, text} |
| GuiMultiLineTextCtrl | text, placeholder, readonly, selectionstart, selectionend, selectedtext | GuiTextChangeEvent {text} |
ts
const sound = new GuiCheckboxCtrl('Opts_Sound')
sound.text = 'Play sounds'
sound.checked = true
sound.on('change', e => { this.sound = e.checked })
const volume = new GuiSliderCtrl('Opts_Volume')
volume.range = '0,100'
volume.step = 5
volume.value = 80
volume.on('change', e => { Opts_VolumeLabel.text = `Volume ${e.value}` })
// Radios are exclusive per parent + group.
for (const [i, size] of ['Small', 'Large'].entries()) {
const r = new GuiRadioCtrl(`Opts_Size${i}`)
r.text = size
r.group = 'size'
r.position = `8,${80 + i * 24}`
Opts_Window.addControl(r)
r.on('change', () => { this.size = size })
}
Opts_Size0.checked = true
const weapon = new GuiDropDownCtrl('Opts_Weapon')
weapon.items = ['Sword', 'Bow']
weapon.additem('Staff')
weapon.selected = 0
weapon.on('change', e => echo(`picked ${e.text}`))items and tabs read back as copies, so edit them by assigning a new array or with additem/clearitems (addtab/cleartabs). Replacing the list keeps the selected index while it is still in range. The dropdown's list pops up above everything else, so it isn't clipped by a panel or scroll area.
A GuiTabCtrl is just the tab bar; it doesn't own pages. Build one panel per tab and switch them from change:
ts
const tabs = new GuiTabCtrl('Opts_Tabs')
tabs.tabs = ['General', 'Audio']
tabs.width = 300
Opts_Window.addControl(tabs)
const pages = [Opts_GeneralPage, Opts_AudioPage] // GuiPanelCtrls below the bar
function showPage(i: number) { pages.forEach((p, j) => { p.visible = j === i }) }
tabs.selected = 0
showPage(0)
tabs.on('change', e => showPage(e.index))A GuiMultiLineTextCtrl wraps to its width, inserts newlines on Enter and scrolls with the mouse wheel. A scrollbar appears while the text is taller than the box. Set readonly = true to make it a scrollable display for logs or long descriptions.
Code editor mode
A GuiMultiLineTextCtrl can also act as a small code editor, for things like an in-game script pad or a JSON config editor. Setting code to 'js', 'ts' or 'json' turns on everything at once. Each feature is also a separate prop:
| Prop | Default | Effect |
|---|---|---|
syntax | 'none' | Colours tokens for a GuiSyntax: 'js', 'ts' or 'json'. |
syntaxcolors | built-in | Per-token colour overrides, a GuiSyntaxColors object of 'r,g,b[,a]' strings. |
autoindent | false | Enter keeps the line's indentation, and adds a level after { [ (. Enter between brackets puts the closer on its own line. |
softtabs | false | Tab inserts spaces to the next tab stop instead of moving focus. Tab/Shift+Tab indents or dedents selected lines. Backspace in leading spaces deletes a whole level. |
tabsize | 4 | Spaces per indent level. |
wrap | true | false lets long lines run off to the right. The box follows the caret sideways, and a horizontal scrollbar, a sideways swipe or Shift+wheel scrolls it. |
linenumbers | false | A line-number gutter that scrolls with the text. |
code = 'json' is the same as setting syntax = 'json', autoindent, softtabs and linenumbers to true, and wrap = false. code = false resets all five.
ts
const editor = new GuiMultiLineTextCtrl('Cfg_Editor')
editor.extent = '320,200'
editor.code = 'json'
editor.syntaxcolors = { property: '255,200,120' } // other tokens keep the built-in colours
editor.text = JSON.stringify(this.config, null, 4)
Cfg_Window.addControl(editor)
editor.on('change', e => {
try {
this.config = JSON.parse(e.text)
Cfg_Status.text = 'OK'
} catch (err) {
Cfg_Status.text = String(err)
}
})Edits made by the editor features (auto-indent, Tab, smart Backspace) fire change like typing does. In code mode the text stays exactly as typed: Gum's [color=...] text markup isn't parsed, so arr[0] and "[b]" are safe. Colouring stops above 20,000 characters to keep drawing fast. The built-in colours are chosen for the default dark skin, so use syntaxcolors with a light skin.
Images and character previews
GuiImageCtrl displays an image asset. imagerect picks a source region, which is stretched to the control's extent — extent equal to the region size shows it 1:1, double shows it at 2x. image = '' draws a solid rectangle in the tint color (useful as a highlight overlay). scale zooms the whole control while keeping width/height and event coordinates in unscaled units.
Setting actor draws a gani character instead — ideal for an outfit preview in a tailor or character screen. GuiActor fields are ani, head, body, colors, dir, x and y:
ts
const pic = new GuiImageCtrl('Tailor_Preview')
pic.extent = '32,48'
pic.scale = 2 // shows 64x96
pic.actor = { ani: 'idle', dir: 'down', y: 16 }
pic.actor.colors = player.colors // copy the local player's colors
pic.actor.colors[1] = '255,0,0' // then recolor the coat
// pic.actor = null brings the plain image backThe gani's origin sits at the control's top-left (shifted by actor.x/y) and anything outside the extent is cut off; a stock idle character fits in '32,48' with actor.y = 16. Gani sounds don't play and gani scripts don't run.
attr and aniParams feed the gani's ATTR and PARAM sprites, shaped like player.attr and player.aniParams. That makes copying another character's pose a one-liner:
ts
const p = findplayer('someone')
if (p) pic.actor = { ani: p.ani, dir: p.dir, aniParams: p.aniParams, attr: p.attr, y: 16 }
pic.actor.attr = { hat: 'hat1.png' } // an ATTR "hat" sprite now draws hat1.pngA copy is a snapshot. To follow a character live, set actor.player to its handle: player, a players / findplayer() handle, an NPC's this, or a gani script's player. The actor then mirrors that character's look (head, body, colors and attributes) every frame, while the pose (ani, dir, aniParams) stays the actor's own:
ts
pic.actor = { player, y: 16 } // you, updating as you change clothes
fitting.actor = { player, head: 'head5.png', y: 16 } // you, trying on another head
fitting.actor.attr = { hat: 'hat2.png' } // ...and another hat
// fitting.actor.player = null stops mirroringFields you set on the actor override the mirrored ones: head, body and colors replace the character's, and attr entries win name by name, with the rest still coming from the character. Reading head, body or colors gives what's drawn (mirror included), while attr and aniParams read back the actor's own values. If the character isn't loaded on this client (it left, or you're on the Login Server), the actor draws its own fields or the defaults, and picks the character up again once it's back.
Drawing panels
GuiDrawingPanelCtrl is a panel with a canvas you paint on from script, for minimaps, charts, signature boxes, paint tools or any widget the stock controls don't cover. It is still a panel: color, borders, skins and child controls all work, with the canvas drawn above the panel's background and below its children.
Drawing is retained, as in Graal: each call paints onto the canvas once and the result stays until you erase it with clearall() or clearrectangle(). There is no redraw loop, so draw what changed (a new stroke, a moved marker) rather than everything every frame. Coordinates are pixels from the control's top-left, and the canvas is the control's width x height:
| Call | Draws |
|---|---|
drawimage(x, y, img) | a whole image, 1:1 |
drawimagerectangle(x, y, img, sx, sy, sw, sh) | one region of an image (a tile, a sprite-sheet frame), 1:1 |
drawimagestretched(x, y, w, h, img, sx?, sy?, sw?, sh?) | an image or region stretched to w x h |
drawpixel(x, y) | one pixel |
drawline(x, y, endx, endy, width?) | a line between two pixels (both included); thick lines get round ends |
drawrect / fillrect(x, y, endx, endy) | a rectangle outline / fill between two corners (end exclusive) |
drawcircle / fillcircle(x, y, radius) | a circle outline / fill around a center |
drawellipse / fillellipse(x, y, rx, ry) | an ellipse outline / fill |
drawpolygon / fillpolygon([x1, y1, x2, y2, ...]) | a closed polygon outline / even-odd fill |
drawtext(x, y, text) | text in the pen's font |
Everything after a pen call uses it, until you change it again: setcolor ('r,g,b' or 'r,g,b,a' for shapes and text), setlinewidth (outlines and the default line width), setfont (family, pixel size, 'b'/'i'/'c' style), setimagecolor (a tint/alpha for images only, so a red pen never tints your sprites) and setblendmode: 'alpha' paints normally, 'add' brightens (glows), and 'erase' turns any shape or image into an eraser.
A small paint box, using the mouse events for strokes:
ts
const pad = new GuiDrawingPanelCtrl('Paint_Pad')
pad.extent = '200,150'
pad.color = '255,255,255' // the panel's own background
pad.setcolor('20,20,20')
pad.setlinewidth(3)
let last: { x: number, y: number } | null = null
pad.on('mousedown', (e) => {
pad.setblendmode(e.button === 'right' ? 'erase' : 'alpha')
pad.drawline(e.x, e.y, e.x, e.y)
last = { x: e.x, y: e.y }
})
pad.on('mousemove', (e) => {
if (!last) return
pad.drawline(last.x, last.y, e.x, e.y)
last = { x: e.x, y: e.y }
})
pad.on('mouseup', () => { last = null })The erase brush clears the canvas, not the panel, so the white panel color shows through where you erase.
Draw calls run in call order, and in order with property writes made in the same tick, so pad.extent = ... followed by draws works as expected. Resizing keeps what's drawn (anchored to the top-left). An image or font that hasn't downloaded yet holds back the draws after it until it arrives, so a fresh canvas can fill in a moment after the first use of an image; images the server doesn't have are skipped. Inside a GuiStretchCtrl the canvas keeps its virtual resolution and scales with the control.
TIP
Shapes are pixel-crisp, with no anti-aliasing, to match the game's pixel art. For a smooth look, draw a pre-rendered image instead.
Scrolling and stretching containers
Children of a GuiScrollCtrl land in an inner content area; scrollbars appear when the content is larger than the viewport and the mouse wheel scrolls it.
A GuiStretchCtrl lets you design a screen once at a fixed resolution and have it fill any window size. Children are positioned in virtual units, and stretchmode picks 'stretch' (fill, may distort), 'fit' (uniform, letterboxed) or 'fill' (uniform, cropped):
ts
export function onCreated() {
const ui = new GuiStretchCtrl('Battle_Root')
ui.virtualextent = '720,480'
ui.stretchmode = 'fit'
ui.extent = `${ScreenWidth},${ScreenHeight}`
this.lastW = ScreenWidth; this.lastH = ScreenHeight
// ...build children in 720x480 coordinates
}
export function onUpdate() {
// There are no anchors: re-assert the extent when the window resizes.
if (ScreenWidth !== this.lastW || ScreenHeight !== this.lastH) {
this.lastW = ScreenWidth; this.lastH = ScreenHeight
Battle_Root.extent = `${ScreenWidth},${ScreenHeight}`
}
}Positions, sizes, image scale, actors, panel borders and all text scale — labels, buttons, text edits, checkboxes, dropdowns, tabs and window titles, at their fontsize or their default size when none is set. Text and borders use the smaller axis factor so they never distort, and fonts are re-rasterized at the new size so they stay crisp. Themed chrome — window title bars, default button height, scrollbar thickness — keeps its native pixel size, so give scaled buttons an explicit height that fits their text. Inside the container, reads of x/y/width/height and event x/y are in virtual units, while absx/absy stay real screen pixels.
9-slice skin corners stay 1:1 by default. Set scaleskins to scale them (and the default theme's frames) by the same uniform factor, so a skinned button keeps its proportions at any window size. It covers every descendant; a nested stretch control can set it again to override it for its own subtree:
ts
const ui = new GuiStretchCtrl('Battle_Root')
ui.virtualextent = '720,480'
ui.scaleskins = true
const attack = new GuiButtonCtrl('Battle_Attack')
attack.skin = 'gui/button.png'
attack.skinborder = 6 // 6 source px = 12 screen px at 2x
attack.extent = '120,32'
ui.addControl(attack)Parenting and layout
New controls attach to the screen root by default — no window required. Call addControl on a container to parent a child inside it:
- Children are positioned relative to the parent's top-left. For a window that includes the title bar (GS2-style), so start content around
y = 40. - Destroying, hiding or moving a parent takes its children with it;
bringtofront()raises the whole subtree. - To hit-test the mouse against a control wherever it sits (inside a dragged window, a scrolled area, a stretch container), use the live screen-absolute absx/absy, which compare directly with mousescreenx()/mousescreeny().
GameControl
GameControl is a pseudo-control for the game screen itself (a GuiGameScreen). It exposes the live viewport width, height and extent, and GameControl.addControl(ctrl) makes root parenting explicit — or moves a control back out of a window. Use it for HUDs and custom chat bars that sit directly on the game view:
ts
const bar = new GuiTextEditCtrl('Chat_Edit')
bar.width = 400
bar.y = GameControl.height - 30 // bottom-anchored: no anchor API,
GameControl.addControl(bar) // so reposition in onUpdate on resizeGameControl cannot be created, destroyed, styled or listened to ('GameControl' is a reserved name — constructing a control with it throws), and its show/hide/bringtofront are no-ops.
Click-through controls
A full-screen HUD would normally swallow every click under it. Set interactive to false and the control only renders: the mouse and touches pass through it to the controls or the game underneath, mouseonui() ignores it, it can't take keyboard focus (clicking, Tab or makefirstresponder()), and it receives no mouse or touch events, not even ones bubbling up from its children.
Children inherit the setting, so setting it once on the root covers the whole HUD. A child can opt back in with interactive = true. Setting it to null goes back to inheriting, and reading it returns the effective value:
ts
const hud = new GuiStretchCtrl('HUD_Root')
hud.virtualextent = '720,480'
hud.extent = `${ScreenWidth},${ScreenHeight}`
hud.interactive = false // hearts, minimap, labels: render-only
const menu = new GuiButtonCtrl('HUD_Menu')
menu.text = 'Menu'
menu.extent = '80,24'
hud.addControl(menu)
menu.interactive = true // the one clickable piece
menu.on('click', () => showMenu())Draw order
Among siblings, the last one drawn wins: controls created later draw above earlier ones, and bringtofront() moves one to the top of its siblings. A common pattern is a full-screen dimmer panel created before a modal window so it sits underneath it.
Finding controls
Because every control is also a global, most code simply refers to My_Window directly. When the name is dynamic, or the control may not exist:
- findGuiControl(name) returns the control, or
undefined. - findobj(name) is the Graal-style alias. It is typed as never returning
undefinedso chaining stays terse (findobj('Shop_Window').visible = true), but it still returnsundefinedat runtime for unknown names — usefindGuiControlwhen existence is in doubt.
Both return GameControl for the name 'GameControl'.
Styling
Controls use the client's default skin until you style them: a translucent navy window with a glossy blue title bar, glossy blue buttons with hover, pressed and disabled states, dark inset text edits and scroll areas, and slim blue scrollbars. Labels and panels draw nothing of their own. The same skin covers the client's built-in screens, so script UI matches the login screen.
Panels are invisible until given a fill or border:
ts
const box = new GuiPanelCtrl('Hud_Box')
box.extent = '160,40'
box.color = '0,0,0,160' // r,g,b[,a] 0-255
box.bordersize = 2
box.bordercolor = '255,255,255'
box.borderradius = 6 // rounds fill and border (children aren't clipped)Windows take a color tint multiplied into their frame.
A window gets a close button in its title bar with canclose. Clicking it hides the window and fires onCloseQuery. Set closequery to keep the window open and decide in the handler instead:
ts
const win = new GuiWindowCtrl('Shop_Window')
win.text = "Old Mira's Wares"
win.canclose = true
win.closequery = true
win.onCloseQuery = () => {
if (cart.length === 0) win.destroy()
else confirmLeave.show()
}Skins replace the themed look of windows, buttons, panels, text edits and scroll areas with a 9-slice image asset: corners render 1:1 (or scaled, inside a stretch container with scaleskins), edges and center stretch. Labels and image controls ignore skins.
| Property | Meaning |
|---|---|
| skin | Image asset, e.g. 'gui/fancywindow.png'; '' restores the default skin. |
| skinrect | "left,top,width,height" sub-region of the texture (atlas support). |
| skinborder | Border thickness in source pixels; unset = a third of the region, 0 = plain stretch. |
| skinrecthover / skinrectpressed | Button-only per-state regions. Without them a skinned button auto-lightens/darkens on hover/press. |
| skinrectdisabled | Region shown while a button or text input is disabled. Without it the skin is grayed. |
ts
const win = new GuiWindowCtrl('Messages_Window')
win.skin = 'itemui.png'
win.skinrect = '0,0,96,96'
win.skinborder = 16Skins load asynchronously
Skin images go through the asset cache, so the first use of an image may pop in a moment after the control appears; later uses of an already-loaded image apply instantly. If the asset can't be found, the control keeps its default look.
Profiles
A GuiControlProfile is a named set of style props, like Graal's profiles. Define it once, typically in a small theme weapon, and any control in any weapon can use it by name. You don't need a lib script of skinButton()-style helpers.
ts
// weapons/theme.client.ts
export function onCreated() {
new GuiControlProfile('Theme_Button', {
skin: 'gui/theme.png', skinrect: '0,0,24,24', skinborder: 6,
skinrecthover: '24,0,24,24', skinrectpressed: '48,0,24,24',
skinrectdisabled: '72,0,24,24',
fontsize: 12, style: 'b',
})
new GuiControlProfile('Theme_Title', { font: 'opensans', fontsize: 16, color: '255,230,160' })
}ts
// weapons/shop.client.ts
const buy = new GuiButtonCtrl('Shop_Buy')
buy.profile = 'Theme_Button'
buy.fontsize = 10 // set on the control: beats the profile's 12How profiles behave:
- Control props win. A prop you set directly on a control always overrides the profile's, whether you set it before or after assigning profile.
- Late binding. Weapons load in no guaranteed order, so a control can name a profile that doesn't exist yet. It picks the profile up as soon as the profile is defined.
- Live edits. Changing a profile prop (
findGuiProfile('Theme_Button').fontsize = 14) restyles every control using it. Setting a prop tonullordelete-ing it removes it, and those controls go back to their default for that prop. - Detaching.
ctrl.profile = ''puts the profile-supplied props back to the control's defaults. - Ownership. A profile belongs to the weapon that created it. When that weapon is unloaded the profile is removed and its controls revert to defaults, but they keep the profile name, so a hot reload re-applies the new definition. Defining a profile under an existing name replaces the old one.
A profile can carry the style props from GuiProfileProps: font, size and style, colors, panel borders, skins, and image tint/alpha. Each control uses the ones that apply to its kind and ignores the rest, so one profile can serve buttons and windows alike. findGuiProfile looks a profile up by name.
Events
Listen with on(event, listener) and remove with off(event, listener?) (omit the listener to remove all of them for that event). on returns the control, so calls chain. Every control kind supports every mouse and keyboard event, and multiple listeners run in registration order. The form controls add a change event, typed by their own event maps (GuiCheckEventMap, GuiSliderEventMap, GuiSelectEventMap, GuiTextEventMap), and text edits add submit (GuiTextEditEventMap).
The events and their payloads are listed in GuiEventMap:
| Event | Payload | Notes |
|---|---|---|
click, doubleclick | GuiButtonEvent | Press and release on the same control, any button. |
mousedown | GuiButtonEvent | |
mouseup | GuiButtonEvent | Fires on the control(s) the press started on, even if the cursor moved off. |
mousemove, mouseenter, mouseleave | GuiMoveEvent | |
mousewheel | GuiWheelEvent | delta in notches, positive = up. |
keydown, keyup | GuiKeyEvent | While the control or a child has keyboard focus. |
touchstart, touchmove, touchend | GuiTouchEvent | Touchscreens only. One stream per finger; see Touch events. |
change | per control, see Form controls | Form controls only: the user changed the value. Doesn't bubble. |
submit | GuiTextSubmitEvent | Text edits only: Enter (iOS: done) was pressed. Doesn't bubble. See Submitting with Enter. |
Button payloads carry button — a GuiMouseButton: 'left', 'right' or 'middle' — so one click listener can handle right-clicks too. Mouse x/y are relative to the control's top-left (in unscaled/virtual units inside scaled images and stretch containers).
ts
Inventory_Slot3
.on('click', e => {
if (e.button === 'right') dropItem(3)
else useItem(3)
})
.on('mouseenter', () => { Inventory_Tooltip.visible = true })
.on('mouseleave', () => { Inventory_Tooltip.visible = false })Bubbling
Mouse events bubble: a click on a child (an image inside a panel, a button inside a window) fires on the child first and then on each listening ancestor. This lets one listener on a container handle clicks on everything inside it; use the event's coordinates or your own state to tell children apart.
Keyboard events
keydown/keyup are routed by focus, not by the cursor: they fire while the control — or any child of it — has keyboard focus (click a text edit to focus it), then bubble to listening ancestors. The GuiKeyEvent key uses the same names as the global keydown() helper ('a', 'enter', 'escape', '0'…'9'), plus shift and control modifier flags. They are edge-triggered (one event per press, no auto-repeat). Keys still reach the control itself, so typing letters into a listening text edit works as usual.
ts
const edit = new GuiTextEditCtrl('Cmd_Edit')
edit.on('keydown', e => {
if (e.key === 'escape') edit.makefirstresponder(false)
})To act on Enter in a text edit, listen for submit instead of checking for an 'enter' keydown.
To focus a control from code instead of a click (say, a hotkey that opens a custom chat bar), call makefirstresponder() on it; makefirstresponder(false) releases focus again so movement and onKeyPressed resume. See A custom chat bar.
When nothing script-owned has focus (including while the built-in chat bar is focused), no key events fire. For global hotkeys, poll keydown() instead.
Touch events
On a touchscreen (istouchdevice()) controls also get touchstart, touchmove and touchend, with a GuiTouchEvent payload. They differ from the mouse events in two ways:
- Every finger is separate. Each has its own
id, so several controls can be held at once: a joystick and an attack button, say. (The mouse events only follow one finger.) - A finger stays with the control it started on.
touchstartfires on the deepest visible control listening to touch events under the finger (and bubbles to listening ancestors). That control then gets the finger'stouchmoveandtouchenduntil it's lifted, even after the finger slides off it.x/yare relative to the control and can lie outside it;screenx/screenyare screen pixels.
ts
const pad = new GuiPanelCtrl('Pad')
pad.extent = '150,150'
pad.on('touchstart', e => echo('finger ' + e.id + ' down at ' + e.x + ',' + e.y))
.on('touchmove', e => echo('finger ' + e.id + ' at ' + e.x + ',' + e.y))
.on('touchend', e => echo('finger ' + e.id + ' lifted'))Pair them with emulateKey to build on-screen controls that drive the game like a keyboard; Touch controls has a complete joystick weapon.
Checking who has focus
isfirstresponder() tells you whether a control holds keyboard focus right now. On GameControl it's true when no input has focus — neither a script control nor the built-in chat bar — so the game owns the keyboard. That's the check to make before acting on a polled hotkey:
ts
export function onUpdate() {
if (keydown('i') && GameControl.isfirstresponder())
findobj('Inventory_Window').show() // not while the player is typing "i" somewhere
}getfirstresponder() returns the focused control itself: a script control, GameControl when nothing is focused, or null while built-in UI such as the chat bar has focus.
ts
const fr = getfirstresponder()
if (fr !== GameControl && fr !== null)
echo('typing into ' + fr.name)Both are live reads. A makefirstresponder() call takes effect when the tick's GUI batch flushes, so asking straight after it in the same tick still returns the old answer.
Listening makes a control count as UI
A control that listens for any mouse event becomes hit-testable, so hovering it makes mouseonui() return true. That's usually what you want — it stops world clicks from firing through your UI. Keyboard-only listeners don't change this.
Legacy handler properties
The older assignment-style handlers still work but are deprecated in favour of .on(): onAction on buttons (use on('click')) and onClick on images (use on('mousedown')), and onAction on text edits (use on('submit')). onTextChanged on text edits and onCloseQuery on windows have no .on() equivalent and are the way to observe edits and close-button clicks.
Animation
Every control has animate(). It tweens props from their current values to the ones you give, over a duration in seconds, and returns a GuiAnimation you can await:
ts
win.alpha = 0
await win.animate({ alpha: 1, y: '-=20' }, { duration: 0.3, easing: 'outBack' })
label.animate({ color: '255,80,80' }, 0.2) // a number is the duration- What animates (see GuiAnimatableProps):
- Numbers:
x,y,width,height,alpha,scale(images),fontsize,bordersize,borderradius, andvalue(sliders). A string like'+=20'or'-=20'is relative to the value when the animation starts. - Colors (
color,bordercolor,tint) tween per channel, alpha included. A panel with no fill fades in from transparent.
- Numbers:
alphaworks on every control and fades its children with it, so animating a window'salphafades the whole window. While a control is below full opacity it is drawn through an offscreen layer the size of the control, so anything sticking out of its rectangle is clipped until it is back at 1. On images,alphafades only the picture, as before.- Options (GuiAnimationOptions):
duration: seconds, default 0.25.delay: seconds to wait before starting.easing: a GuiEasing name (default'outQuad') or your ownt => tfunction.yoyo: plays back to the start values afterwards.loop:trueto repeat until cancelled, or a total play count.onupdate(progress)andoncomplete()callbacks.
- Easing names are
'linear'orin/out/inOutplusQuad,Cubic,Quart,Sine,Expo,Back,Elastic, orBounce(e.g.'outBack','inOutSine').outcurves suit things appearing.incurves suit things leaving.Backovershoots a little.
The awaited result is true if the animation finished, and false if it was cancelled, taken over, or its control was destroyed. It never rejects. Hold on to the handle to stop it early: cancel() freezes it where it is, and finish() jumps to the end values. stopanimations() does the same for every animation on a control.
One animation per prop. Starting another animation of the same prop takes that prop over from the running one, and so does setting the prop directly (win.x = 10). The old animation keeps its other props, and resolves false once it has none left. Start values are read when an animation actually begins, so a delayed animation continues from wherever the previous one left off:
ts
panel.animate({ x: 200 }, 0.5)
panel.animate({ x: 0 }, { delay: 0.5, duration: 0.5 }) // then backSequences and parallel steps
GuiAnimation.sequence() runs steps one after another, and GuiAnimation.parallel() runs them all at once. A step can be any of these:
{ target, to, ...options }animates a control.- A number pauses for that many seconds.
- A function is called, and the group waits if it returns a promise or animation.
{ sequence: [...] }or{ parallel: [...] }nests a group, with group optionsloopandoncomplete.
Each step starts when it is reached, so it begins from where the previous steps left the control.
ts
GuiAnimation.sequence([
{ target: toast, to: { x: ScreenWidth - 240 }, duration: 0.3, easing: 'outCubic' },
2,
{ parallel: [
{ target: toast, to: { alpha: 0 }, duration: 0.4 },
{ target: toast, to: { y: '-=10' }, duration: 0.4 },
] },
() => toast.destroy(),
])Groups return the same kind of handle. cancel() stops the running steps and skips the rest. finish() runs every remaining step straight to its end values.
Timing and ownership
Animations advance once per frame, just before onUpdate, so a value your onUpdate writes wins that frame (and takes the prop over). Code after await ctrl.animate(...) runs as your script, exactly like code after await sleep(). Animations belong to the script that started them: when it unloads or hot reloads, they stop where they are and never resolve, so nothing after the await runs.
This example weapon pops a menu window open with a fade, pulses its button, and shows toasts that slide in and fade away:
ts
// The `animdemo` weapon: animated GUI with ctrl.animate and GuiAnimation.
// M - pops a menu window open (or fades it away)
// T - shows a toast that slides in, waits, and fades out
// Other clientside weapons can raise toasts too:
// findweapon('animdemo')?.trigger('toast', 'Saved!')
const MENU_W = 260
const MENU_H = 180
let menuOpen = false
function buildMenu() {
const win = new GuiWindowCtrl('AnimDemo_Menu')
win.text = 'Menu'
win.width = MENU_W
win.height = MENU_H
win.x = (ScreenWidth - MENU_W) / 2
win.y = (ScreenHeight - MENU_H) / 2
win.visible = false
const play = new GuiButtonCtrl('AnimDemo_Play')
play.text = 'Play'
play.x = 30
play.y = 60
play.width = 200
play.height = 36
win.addControl(play)
// A gentle pulse until clicked: one play there-and-back, repeated.
const pulse = play.animate({ width: '+=12', x: '-=6' },
{ duration: 0.6, easing: 'inOutSine', yoyo: true, loop: true })
play.on('click', () => { pulse.finish(); toast('Let\'s go!') })
}
// Opening fades the whole window in (children included) while it rises
// into place with a slight overshoot.
async function toggleMenu() {
const win = findGuiControl('AnimDemo_Menu')!
menuOpen = !menuOpen
if (menuOpen) {
win.alpha = 0
win.y = (ScreenHeight - MENU_H) / 2 + 30
win.visible = true
await win.animate({ alpha: 1, y: '-=30' }, { duration: 0.35, easing: 'outBack' })
} else {
// Hide only if nobody re-opened it meanwhile (that takes the
// animation over, so this one resolves false).
const done = await win.animate({ alpha: 0 }, 0.2)
if (done) win.visible = false
}
}
let toastCount = 0
// Slides a toast in from the right, holds it, fades it out, and destroys it.
export function toast(text: string) {
const name = 'AnimDemo_Toast' + (++toastCount)
const panel = new GuiPanelCtrl(name)
panel.color = '20,20,30,220'
panel.borderradius = 6
panel.width = 220
panel.height = 40
panel.x = ScreenWidth
panel.y = 20
const label = new GuiTextCtrl(name + '_Text')
label.text = text
label.x = 12
label.y = 10
label.color = '255,255,255'
panel.addControl(label)
GuiAnimation.sequence([
{ target: panel, to: { x: ScreenWidth - 240 }, duration: 0.3, easing: 'outCubic' },
2,
{ target: panel, to: { alpha: 0, y: '-=10' }, duration: 0.4, easing: 'inQuad' },
() => panel.destroy(),
])
}
export function onCreated() {
buildMenu()
}
export function onKeyPressed(key: string) {
if (key === 'M') toggleMenu()
if (key === 'T') toast('Hello from animdemo')
}Lifecycle and cleanup
- destroy() removes a control and every child added via
addControlfor good. Writing to a destroyed control throws. - Destroying a control ends its running animations, which resolve
false. - Controls are destroyed automatically when the weapon that created them is unloaded or reloaded — including hot reloads — so a weapon never has to clean up after itself on removal.
Build UI in onCreated or event handlers, not timers
Controls created from setTimeout/setInterval callbacks are only swept when the player disconnects, not when the weapon unloads. Create controls in onCreated, onUpdate, GUI event handlers or other script events; timers may freely modify existing controls (animating text, fading a panel's color).
A typical show/hide pattern keeps one set of controls and toggles visible, or destroys the root window and rebuilds it next time (safe, because re-creating a name replaces it). See the HUD & message box tutorial for a complete example.
Naming convention summary
Weapon_Thing— weapon name, underscore, role:Shop_Window,Shop_BuyButton,Messages_Background.- Keep names stable so other scripts (and
findobj) can address them. - Never use
GameControl.