radlang — Native GUI (syn)

syn is radlang’s native desktop GUI. You describe a tree of nodes — panels, labels, buttons, form fields — and syn resolves its layout and redraws it every frame on a native sokol surface (Metal on macOS and iOS; OpenGL on request, see Rendering backends). Layout is intrinsic: nodes size themselves from their content and font, so you rarely hardcode pixels.

For language fundamentals see the Overview. For the system-webview surface (syn.webview) see gui.md.

iOS. radlang build --target ios runs the same tree full-screen inside the safe area (status bar, notch and home indicator excluded). A one-finger touch drives the pointer path, so taps press and focus as clicks do, and a swipe scrolls the region under it, with momentum after a flick (a drag that starts on a slider, scrollbar thumb or split divider still drags that control). Focusing a text field brings up the on-screen keyboard and the layout shrinks above it (see On-screen keyboard). syn.run never returns on iOS. Long press, double tap, pan, pinch and edge swipes are handlers on any node (see Gestures). Hover-only affordances (tooltips) have no touch equivalent yet. See the README’s iOS section.

Touch targets (iOS, Android). The window is cleared with the app’s full-screen background (the outermost full-size panel’s fill), so the status bar and home-indicator strips match it. A number field’s steppers become − and + buttons side by side, each at least 44pt wide; padY on a toggle, checkbox or radio adds height to its row (per option for radio), so padY: syn.px(9)–syn.px(12) gives 44pt tap rows.


Overview

syn is a compiler-intrinsic namespace — no import needed for the core primitives. You open a window, hang a tree of nodes off it, and run the loop:

fn main(): void {
    NativeWindow win = syn.window("Hello", 480, 320)
    SynNode root = win.panel({dir: "column", pad: syn.px(20), gap: syn.px(10)})

    root.label("What's your name?")
    SynNode name = root.input({placeholder: "type here"})
    root.button("Greet", fn() {
        sys.output("Hello, " + name.value())
    })

    syn.run(win)
}

Two things are always true:

  1. Every node attaches to a parent when it’s built. A node has to know where it lives in the tree the moment you create it, because syn draws the whole retained tree each frame — there are no detached/orphan nodes.
  2. The parent comes first. For built-in primitives that means calling the builder on the parent (root.button(...)); for the layout components it means passing the parent as the first argument (layout.table(root, ...)). See Primitives vs. components.

Showcase

projects/syn/src/showcase-demo.rad is a single radlang file (no assets beyond one image) that tours everything below. Build and run it from the projects/syn project:

cd projects/syn
radlang build src/showcase-demo.rad -o output/showcase && ./output/showcase

It is a sidebar app: the nav buttons show and hide eight page panels, the header clock is a syn.every(1000, ...) timer, and every color comes from a small palette of syn.rgb helpers. The screenshots are the real window on a Retina Mac.

Overview page: live layout

Overview page: stat cards, live bar chart, traffic mix bars and wrapping feature chips

Four stat cards sit in a wrap: true row with basis: syn.px(180) and grow: 1, so they share a line and reflow onto two lines in a narrow window. The throughput bars are 24 panels in a row with align: "end"; an 80ms syn.every timer resizes each one with bar.style({h: syn.pct(v)}), and the traffic-mix bars do the same with w. The counters update with setText. Nothing redraws between timer ticks (see redraw on demand).

Layout page: flexbox

Layout page: every justify mode, align modes, grow weights and shrink limits

Each justify mode (start, center, end, spaceBetween, spaceAround, spaceEvenly) applied to the same three boxes, the four align modes on children of different heights, grow weights 1:2:3, and shrink with basis and minW. See Flex sizing.

Layout page scrolled: three independently scrolling lists and a two-axis canvas

Further down: three lists that scroll on their own (the wheel passes to the page at their ends), and a 24×16 grid of cells in a 260px viewport with overflowX: "auto" and align: "start", scrolling in both directions with a scrollbar for the most recently used axis. See Scrolling.

Typography page

Typography page: type scale, Menlo code, Unicode scripts, wrapping, ellipsis and alignment

A type scale set with .font({size, weight, italic, family}); Unicode from fallback fonts (accents, CJK, Korean, Greek, Cyrillic, Vietnamese, symbols); a wrap: true label inside a bordered, padded box; ellipsis: true; textAlign; and hard newlines. Right-to-left scripts (Hebrew, Arabic) are not shaped yet.

Surfaces page

Surfaces page: corner radii, border widths, opacity steps and interactive button states

radius from square to circle, border widths with borderColor, opacity from 20% to 100% (it applies to a node and its children), and buttons with hoverColor / pressColor; the last tile is a plain panel made clickable with .onClick.

Components page

Components page: a live style editor with sliders, toggles and a radio group restyling a preview card

A live style editor: two sliders, two toggles and a radio group restyle the preview card through preview.style({...}) in their handlers. The chips carry .tooltip(...). Below (not shown): progress bars (one driven by a timer, one indeterminate), tabs switching three panes, image with each fit, and a button with .menu([...], handler). See Components.

Themes card: the same widgets under the light, dark and a custom rose theme

The same widget set three times with no colors of its own, under .theme("light"), .theme("dark") and .theme({base: "dark", accent: ..., field: ..., ...}). See Themes.

Data views page

Data page: a live area chart, a grouped bar chart, a sortable table and a file tree

An area chart whose two series a timer replaces every second (hover shows the values), a grouped bar chart, a 300-row table (click a header to sort; numbers sort numerically and right-align) and a tree of project files.

Data page scrolled: the table, a 100,000-row virtualized list and a colored log

A 100,000-row list whose builder runs only for the rows on screen, and a log fed by a timer with per-line colors. See Data views.

Live page: timers, async, tree edits

Live page: an event stream, an async job and an editable list

An event stream appended every 450ms into a stickToBottom panel (pause and clear are onClick / clear()), an async fn button handler that awaits sys.sleepAsync while a spinner and progress bar animate, and a list edited with add, insert(0, ...), remove() and clear().

Forms page

Forms page: floating-label inputs, a number stepper, a select, a textarea and a checkbox

Inputs with floating labels, a number stepper, a select, a textarea and a checkbox, all restyled with color / radius / border. Submitting reads every field back (value(), checked()) into the preview and shows a toast built with .overlay() and .ttl(2.5).


The window

NativeWindow win = syn.window(title, width, height, {config}?)

config is an optional struct of window flags (all default on):

Flag Meaning
resizable window can be resized
minimizable window has a minimize control
closable window has a close control
titled window has a title bar
NativeWindow win = syn.window("Fixed", 400, 300, {resizable: false})
syn.run(win)   // enters the app loop; returns when the window closes

win behaves as the root node: you build the top container with win.panel(...), and everything else nests under that.


The layout model

Each node measures its intrinsic size from its content, then the layout engine places it. You override sizing only where you need to.

Units

Inside a layout spec, sizes are written with unit markers:

Form Meaning
syn.px(n) n pixels (absolute)
syn.pct(n) n percent of the parent along that axis
bare number fraction of the parent (0.5 = half); prefer syn.pct for clarity

Omit a size entirely and the node hugs its content (the default, and the recommended path — it adapts to the font automatically).

Container options

Any builder that takes a {...} spec accepts these:

Key Values Notes
dir / direction "column", "row" how children stack; default absolute/overlap
gap syn.px(n) space between children
pad / padding syn.px(n) inset for this node’s children
margin syn.px(n) inset of this node inside its own slot
x y w h syn.px / syn.pct explicit position/size (else intrinsic)
anchor "center", "top", "bottomRight", … 9-grid placement within the parent
color / background syn.rgb(r,g,b) / syn.rgba(r,g,b,a) fill color (translucent with rgba)
overflow "auto", "scroll", "hidden", "visible" main-axis overflow (default auto)
overflowX / overflowY same values overflow per axis; the cross axis defaults to hidden
smooth / antiAliasing true / false anti-aliased text; inherited by the subtree
justify "start", "center", "end", "spaceBetween", "spaceAround", "spaceEvenly" where unused main-axis space goes
align "stretch" (default), "start", "center", "end" children’s cross-axis size and position
alignSelf same values, or "auto" override the parent’s align for this child
wrap true / false rows/columns flow onto new lines when full
rowGap syn.px(n) space between wrapped lines (defaults to gap)
padTop padRight padBottom padLeft padX padY syn.px(n) per-side padding (padding… spellings work too)
marginTop … marginX marginY syn.px(n) per-side margin
minW maxW minH maxH syn.px / syn.pct size limits, applied after flex sizing
grow number flex weight (same as .grow(n))
shrink number share of an overflow this child gives up (default 0: never shrinks)
basis syn.px / syn.pct / "auto" starting main size before grow/shrink (default: content size)
id string tag for lookup (same as .id(name))
stickToBottom true / false while scrolled to the end, follow new content (logs, feeds)
radius syn.px(n) rounded corners (panels, buttons, fields, labels with a border); buttons and fields default to the controlRadius / fieldRadius tokens
border / borderColor syn.px(n) / syn.rgb(...) / syn.rgba(...) border width and color, following radius
opacity 0–1 translucency of the node and everything inside it (for a see-through fill that leaves children alone, use syn.rgba)
backgroundImage path string ("" clears) picture drawn over the fill and under the children, clipped to radius and sized by fit (default "cover"); relative paths also resolve inside the app bundle, like image
shadow syn.rgba(...) soft drop shadow behind the node: the color’s alpha is its strength at the node’s edge
shadowBlur syn.px(n) blur radius, like CSS box-shadow (Gaussian, sigma = blur / 2; default: the shadowBlur token, 16)
shadowY syn.px(n) how far the shadow box sits below the node (default: the shadowY token, 4), so the top edge gets a weaker halo
backdropBlur syn.px(r) blur what is drawn behind the node, clipped to its radius (CSS backdrop-filter: blur(r): a Gaussian with standard deviation r); pair it with a translucent color for frosted glass
gradient gradient string, syn.linear(...), syn.radial(...) one or more gradient layers over color (and backgroundImage), under the children, clipped to the corners; see Gradients and effects
borderGradient gradient string the border painted with a gradient, at border width (1 when unset)
textGradient gradient string a label’s glyphs filled with a gradient across the label box
radiusTL radiusTR radiusBR radiusBL syn.px(n) one corner’s radius (unset corners keep radius); honoured by fill, gradient, border, backgroundImage, shadow and backdropBlur
shadowX / shadowSpread syn.px(n) shadow offset to the right, and how far the shadow box grows (negative shrinks), like CSS box-shadow
fadeEdges "x", "y", "both", "none" fade the node’s content (its children) to transparent at its edges; fadeStart / fadeEnd (fractions, default 0.05 / 0.95) bound the opaque middle
kind / strokeWidth "ring" / syn.px(n) on progress: a circular indicator and its stroke width
textColor syn.rgb(...) text color of buttons, labels and fields (color is a label’s text color, a panel’s fill)
hoverColor / pressColor syn.rgb(...) fill while hovered / pressed (any clickable node)
textAlign "left", "center", "right" label text alignment (labels default left); button text (buttons default center)
ellipsis true / false cut an overflowing single-line label with …
fillRole a theme role ("surface", "field", "accent", …) fill with the theme’s color for that role (see Themes)
selectable true / false label text can be selected and copied
trackColor syn.rgb(...) unfilled track of progress, slider and toggle
fit "contain", "cover", "fill" how an image (or a panel’s backgroundImage) fills its box
any theme token number / syn.px(n) this node’s value for that token (controlPadX, fieldWidth, switchW, …; see Engine and style)
<role>Color syn.rgb(...) this node’s colour for a component-part role (thumbColor, indicatorColor, caretColor, scrollbarColor, …)
tint syn.rgb(...) / syn.rgba(...) ("" clears) recolour an image (or a panel’s backgroundImage) that is an alpha mask, such as a monochrome PNG icon: its own colours are ignored and every pixel takes the tint, keeping its alpha (see Fonts and icons)
translateX translateY scale scaleX scaleY rotate originX originY see Animation render-only transform: moves, scales or turns the node as drawn, never its layout
transitionMs transitionCurve transitionProps see Animation later style() changes to the listed properties tween instead of jumping
panAxis zoomable minScale maxScale dismissKeyboardOnDrag see Gestures which drags onPan claims; built-in pinch zoom; blur the focused field on a drag

Anchors: topLeft top topRight left center right bottomLeft bottom bottomRight.

Values may be any expression: {dir: direction, w: syn.px(width)} with variables works. Keys syn doesn’t know are compile warnings (unknown syn style key 'justfy' in 'panel') rather than being silently ignored.

Flex sizing

Rows and columns follow CSS flexbox:

  1. Each child starts from its explicit size (w/h on the main axis), else its basis, else its content size, clamped to its min*/max* limits.
  2. Space left over goes to children with grow, by weight.
  3. If the children don’t fit, children with shrink give space back (in proportion to shrink × their size), down to their minimum. A shrinking panel may go down to 0 and scroll its own content; a shrinking label or field keeps its content size.
  4. Whatever is still left over is distributed by justify; if the children still overflow, the container scrolls (overflow: "auto").

The default is “never shrink”: an overflowing column scrolls as a whole.

.fill() means “take exactly the remaining space” (CSS flex: 1 1 0): the child starts from 0, grows into the free space and may shrink. That is how you make a scroll region that sits under fixed content:

SynNode page = win.panel({dir: "column"})
page.label("Inbox").font({size: 22})          // stays put
SynNode list = page.panel({dir: "column"})
list.fill()                                   // takes the rest, scrolls inside
for (Message m in messages) { list.label(m.subject) }

.grow(n) keeps its content size as the starting point and only adds free space; use it when the child should never be squeezed.

Colors

The lexer has no hex literals, so colors are built with syn.rgb:

SynNode card = root.panel({color: syn.rgb(46, 52, 64)})

A panel without color is transparent.

syn.rgba(r, g, b, a) makes a translucent color; a is the opacity from 0 (invisible) to 1 (opaque), clamped, and syn.rgba(r, g, b, 1) equals syn.rgb(r, g, b). It works anywhere a color does: fills, borders, text colors, hover/press fills, theme roles, chart series. Unlike the node opacity, which fades a node and its children, a translucent color is blended over what is behind it only where that color is painted:

root.panel({color: syn.rgb(228, 237, 245), backgroundImage: "public/wall.png", fit: "fill"})
card.style({color: syn.rgba(255, 255, 255, 0.38), border: syn.px(1),
            borderColor: syn.rgba(255, 255, 255, 0.7),
            shadow: syn.rgba(57, 95, 139, 0.09), shadowBlur: syn.px(14), shadowY: syn.px(4)})

Encoding: colors are ints 0xTTRRGGBB. The top byte TT is the transparency in 7 bits (0 = opaque, so every syn.rgb value is unchanged; 0x7F = invisible), so alpha is quantized to 1/127 and a color never equals the internal “unset” marker 0xFFFFFFFF. A translucent window clear colour is composited over the theme background.

Notes: shadow draws outside the node but inside the padding of the nearest clipping container, and never changes layout. A backgroundImage on the full-window panel is also drawn behind the iOS/Android safe-area strips, so a wallpaper has no seams there. A translucent panel shows the wallpaper behind it sharp; set backdropBlur on it for frosted glass (see Rendering backends).

Themes

Widgets that do not set their own colors take them from a theme, which inherits down the tree like fonts. Set a preset, override individual roles, or both:

NativeWindow win = syn.window("App", 900, 600)
SynNode root = win.panel({dir: "column"}).theme("light")           // whole app
settings.theme({accent: syn.rgb(244, 63, 94)})                     // one subtree, rose accent
sidebar.theme({base: "dark", bg: syn.rgb(18, 20, 28)})             // a dark sidebar in a light app

Presets are "dark" (the default) and "light": neutral fallbacks, not a design. Real looks come from a style library such as syn-style or the app’s own kit. The main roles:

Role Used for
bg window background; a panel that sets a theme paints it
surface menus and dropdown lists
field input / select / checkbox / radio fill
border field borders, dividers, the tab rule
text, muted text; placeholders and inactive tabs
accent, onAccent buttons, checked and selected states, sliders; text on them
selection text selection, hovered list options
track progress / slider / toggle tracks, scrollbar track
focus keyboard focus ring, floated field labels
tooltip, tooltipText tooltips

Explicit colors on a node (color, textColor, borderColor, …) always win over the theme.

A theme also carries metric tokens (paddings, radii, sizes, motion timing) and roles for component parts (thumb, indicator, caret, scrollbar, …), listed in Engine and style:

root.theme({controlPadX: syn.px(20), controlRadius: syn.px(8), fieldRadius: 6, thumb: syn.rgb(250, 250, 250)})
root.setTheme("accent", syn.rgb(244, 63, 94))     // one role or token by name, from data

Gradients and effects

Paint keys that work like their CSS counterparts. They never change layout, and a node without them draws exactly as before. They work on the same keys in builder specs and node.style({...}), on Metal, OpenGL and GLES alike.

Gradients

gradient, borderGradient and textGradient take a gradient string, so they can come from data (a theme file, a style library) as well as code:

card.style({gradient: "linear(100deg, #285C99 0, #1769C2 0.42, #0076E8 1)", radius: syn.px(14)})
Form Meaning
linear(angle, stops) colour along a line through the box centre. angle is CSS’s: 0deg points up, 90deg right, 180deg (the default when omitted) down; turn and rad units work too. The line is long enough that the box corners reach the first and last stops.
radial(cx cy rx ry, stops) an elliptical gradient: centre (cx, cy) and radii (rx, ry) as fractions of the box (0.5 0.5 0.5 0.5 when omitted: an ellipse touching the box sides). Past the last stop it keeps the last colour.
layer, layer, ... several layers, like CSS background-image: the first is on top.

A stop is a colour and an optional position: a fraction (0.42) or a percentage (42%). Positions that are left out spread evenly between their neighbours (the first defaults to 0, the last to 1); repeating a position makes a hard edge. Colours are #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(r, g, b), rgba(r, g, b, a), transparent, or the decimal value of a syn.rgb / syn.rgba colour. Between stops colours blend premultiplied, as in CSS, so fading to transparent never darkens. "" or "none" removes a gradient.

The helpers build the same strings from colour values and stop lists:

string sky = syn.linear(100, [syn.rgb(40, 92, 153), syn.rgb(23, 105, 194), syn.rgb(0, 118, 232)], [0.0, 0.42, 1.0])
string wash = syn.radial(0.15, 0.1, 0.7, 0.5, [syn.rgba(91, 140, 255, 0.35), syn.rgba(91, 140, 255, 0.12), syn.rgba(91, 140, 255, 0)], [0.0, 0.45, 1.0])

syn.linear(angle, colors, stops?) and syn.radial(cx, cy, rx, ry, colors, stops?) take an int[] of colours and an optional float[] (or int[]) of positions; without stops the colours spread evenly. (A list literal has one element type, so write [0.0, 0.45, 1.0], not [0, 0.45, 1].)

Where they paint:

  • gradient paints over the node’s color and backgroundImage and under its children and border, clipped to its corners. On a button it shades on hover and press like the fill (hoverShade / pressShade); an explicit hoverColor / pressColor replaces it while it applies. On a progress bar it fills the value part (the gradient spans the whole track), and on a ring the arc.
  • borderGradient strokes the border with the gradient at the border width (1 when border is unset), following the corners.
  • textGradient fills a label’s glyphs with the gradient laid across the label’s box (colour emoji keep their colours).

An invalid gradient is ignored: as a string literal it is a compile warning (invalid syn gradient '...' in 'panel': ...); built at run time it prints one syn: invalid gradient ... note to stderr.

A wallpaper of three radial washes over a background colour, a gradient button, a glowing card and a gradient wordmark:

SynNode page = win.panel({dir: "column", pad: syn.px(24), gap: syn.px(16), color: syn.rgb(238, 242, 248),
    gradient: "radial(0.15 0.1 0.7 0.5, #5b8cff59 0, #5b8cff1f 0.45, #5b8cff00 1), " +
              "radial(0.9 0.3 0.6 0.6, rgba(255, 170, 120, 0.25) 0, rgba(255, 170, 120, 0.1) 0.45, transparent 1), " +
              "radial(0.5 1 0.8 0.5, #8fd3c040 0, #8fd3c018 0.45, #8fd3c000 1)"})
page.label("Rad Chat", {textGradient: "linear(90deg, #285C99, #0076E8)"}).font({size: 28, weight: "bold"})
page.button("Continue", {gradient: "linear(100deg, #285C99 0, #1769C2 0.42, #0076E8 1)", textColor: syn.rgb(255, 255, 255)}, fn() { next() })
page.panel({pad: syn.px(16), radius: syn.px(16), color: syn.rgba(255, 255, 255, 0.6), border: syn.px(1.5),
    borderGradient: "linear(120deg, #7aa7ff, #c084fc 0.5, #7aa7ff00)",
    shadow: syn.rgba(91, 140, 255, 0.35), shadowBlur: syn.px(24), shadowSpread: syn.px(2)})

Corners and shadows

radiusTL, radiusTR, radiusBR and radiusBL set single corners; the others keep radius. When adjacent corners would overlap, all four scale down together (as in CSS). The fill, gradient, border, backgroundImage, shadow and backdropBlur all follow them:

bubble.style({radius: syn.px(18), radiusBR: syn.px(4)})      // a chat bubble's tail corner

shadow, shadowBlur, shadowY gain shadowX (offset to the right) and shadowSpread (the shadow box grows by it on every side; negative shrinks it), as in CSS box-shadow: x y blur spread color. shadowBlur: syn.px(0) gives a hard shadow.

Edge fades

fadeEdges fades a node’s content (its children) to transparent towards its edges, like a CSS mask-image linear gradient: the mask rises from 0 at the edge to 1 at fadeStart, stays 1 until fadeEnd, and falls to 0 at the far edge (fractions of the node’s width for "x", height for "y", both for "both"). The node’s own fill, border and scrollbar are not faded. A horizontally scrolling strip of chips with Flutter’s stops (0, 0.04, 0.9, 1):

SynNode chips = root.panel({dir: "row", gap: syn.px(8), overflowX: "auto",
                            fadeEdges: "x", fadeStart: 0.04, fadeEnd: 0.9})

It renders the content’s backdrop into an offscreen copy (the backdropBlur snapshot path), so each faded node costs one full-window copy per redraw; a frame holds at most 8 snapshots between blurs and fades. A node past that cap is drawn without its fade (or blur), and syn prints a one-time warning to stderr.

Ring progress

kind: "ring" turns a progress into a circular indicator, filling clockwise from the top; a negative value spins a quarter arc (indeterminate). It is a square two text lines across unless w / h say otherwise (it draws in the smaller side, centred). strokeWidth sets the ring’s thickness (default a tenth of the diameter, at least 2); color (or gradient) is the arc, trackColor the track:

root.progress({value: 0.65, kind: "ring", strokeWidth: syn.px(4), alignSelf: "start"})
root.progress({value: -1, kind: "ring", w: syn.px(24), h: syn.px(24)})     // spinner

Engine and style

syn is the engine, like CSS: layout, primitives, style keys, effects, text, input and the theme-token plumbing. It hardcodes no look. Every visual constant it uses is a colour role or a metric token whose default is a neutral fallback, and both can be overridden:

  • For a subtree: node.theme({...}) with role or token names, or node.setTheme(key, value) one at a time (for themes kept as data). Metric values are px numbers or syn.px(n); roles take syn.rgb / syn.rgba. A theme preset name ("dark" / "light") resets the colour roles only; metric tokens keep inheriting.
  • For one node: a style key of the same name (.style({controlPadX: syn.px(20)}), or in the builder’s spec). Roles added with the token table take the key <role>Color (thumbColor, indicatorColor, …). A node’s own value wins over the theme’s, and the specific keys still win over both: pad over controlPadX/controlPadY, radius over controlRadius / fieldRadius, border over borderWidth/dividerW, color / textColor / trackColor over the roles.

Looks belong in a style library written in radlang, like Bootstrap on top of CSS: presets, scales and styled components. The repository ships one, libraries/syn-style (namespace Style). An app’s own look (its palette, tokens and components) lives in the app, built on the style library. A new visual need becomes a general syn capability (a style key, token, primitive or effect) plus its use in the style library or the app, never an app-specific constant in syn.

With every token at its default an app renders exactly as before the split: the defaults are the values syn used to hardcode, and the headless layout dumps are byte-identical.

Using syn-style

Build and export it (radlang lib, radlang rtest test, radlang export in libraries/syn-style), then add the package to an app’s config.yaml:

packages:
  syn-style:
    path: "../radlang/libraries/syn-style/output/package/syn-style.rlp"
import { Style } from "syn-style"

Style.Preset t = Style.apply(root, Style.preset("light"), Style.overrides())
SynNode card = Style.card(root, t)
Style.field(card, t, "Email", "you@example.com")
Style.button(card, t, "Continue", "primary").onClick(fn() { next() })
Function Returns
Style.preset("dark" | "light") a Style.Preset: syn’s fallback value for every role and token, a neutral palette (danger, success, warning and their on… text colours) and the scales
Style.apply(root, preset, overrides) themes root’s subtree; returns the preset in effect, which components take
Style.overrides(), Style.put(o, key, value) a set of role / token changes
Style.followSystem(root, light, dark, overrides) themes root from syn.systemAppearance() now and again on every syn.onAppearance change (dark while the system is dark, else light); returns the preset in effect now
Style.followSystemThen(root, light, dark, overrides, onChange) the same, and calls onChange(preset) after each re-theme so an app can restyle nodes it coloured explicitly from a preset
Style.forAppearance(mode, light, dark) the preset for "light" / "dark"
Style.derive(base, name, overrides), Style.withPalette(p, pal), Style.withScale(p, s) a new preset built from another
Style.value(p, key), Style.color(p, key), Style.space(p, i) a preset’s token, colour, or spacing step (4, 8, 12, 16, 24, 32)
Style.roleNames() the colour roles among a preset’s keys
Style.gradient(p, name), Style.withGradient(p, name, value) a preset’s gradient token (a string for gradient / borderGradient / textGradient), and a preset with one replaced

Scales: space 4 / 8 / 12 / 16 / 24 / 32; radii radiusSm 4, radiusMd 8, radiusLg 12, radiusXl 16, radiusPill 999; type textCaption 12, textBody 15, textSubtitle 17, textTitle 20, textHeadline 28.

Gradient tokens: "accent" (a primary fill), "accentBorder" (a frame fading from the accent), "glow" (a soft accent wash from the top), "wash" (a faint two-layer page wallpaper) and "scrim" (transparent to dark, for text over pictures). Their defaults derive from the preset’s accent, so a new accent recolours them; Style.withGradient replaces one, and derive keeps the replacements.

Components (each takes the parent and the preset, and returns the node to use): button(parent, t, text, variant) with variants "primary", "gradient", "secondary", "ghost", "danger" (attach the action with .onClick); card; glowCard (a card with the "glow" wash, an "accentBorder" frame and an accent glow); chip(…, text, selected); badge(…, text, tone); segmented(…, options, selected, fn(string v)); listRow(…, title, detail); field(…, caption, placeholder) (returns the input); sectionHeader(…, text); toggleRow(…, text, on, fn(bool on)) (returns the toggle); dialog(host, t) (a hidden modal surface; fill it, then .show()). icon(parent, codepoint, size, color) takes no preset: it is a label showing one glyph of the icon font named by Style.setIconFamily(family) (default "Icons"; see Fonts and icons).

Motion: Style.motion() returns the motion tokens (fast 160 ms, normal 250 ms, curve "easeOutCubic"). Style.reveal(node) fades a node in while it slides down from 4% of its height above, over normal, and returns it. Style.pulseDots(row, n) adds n dots to row that rise and brighten in turn (a typing indicator: a 1200 ms cycle each, 200 ms apart, on the muted role) and returns them. Style.blink(node, ms) fades a node out and back, ms each way, until node.stopAnimations(). See Animation.

Motion: Style.motion() returns the motion tokens (fast 160 ms, normal 250 ms, curve "easeOutCubic"). Style.reveal(node) fades a node in while it slides down from 4% of its height above, over normal, and returns it. Style.pulseDots(row, n) adds n dots to row that rise and brighten in turn (a typing indicator: a 1200 ms cycle each, 200 ms apart, on the muted role) and returns them. Style.blink(node, ms) fades a node out and back, ms each way, until node.stopAnimations(). See Animation.

Gesture components (no preset: they take their fills from the theme roles of the subtree they are built in, so a preset applied above skins them; see Gestures):

  • Style.swipeRow(parent, actions) returns a row (fill it) that slides left to reveal actions behind it and snaps open or closed on release. Each Style.SwipeAction is {label, color, confirm} (Style.swipeAction(label, confirm) uses the theme’s accent); confirm runs when the revealed action is tapped or the row is swiped most of the way across (the last action), and returns true to let the row slide away (remove it) or false to spring it back. A tap on the open row closes it.
  • Sheets and drawers are overlays sized to host’s content box: pass a panel that covers the window without padding (usually the root), so the scrim covers everything.
  • Style.sheet(Style.SheetOptions(host, detents, onDismiss)) returns a Style.Sheet (layer, panel, body, open(i), close()): a bottom sheet over host on the surface role with a scrim behind it and a drag handle. detents are its resting heights as fractions of the host (ascending). A drag on the handle moves it; released below 60% of the smallest detent, or flicked down, it closes and calls onDismiss, otherwise it settles at the nearest detent. A tap on the scrim closes it.
  • Style.drawer(Style.DrawerOptions(host, side, width)) returns a Style.Drawer (layer, panel, body, open(), close()): a side drawer from "left" or "right", width a fraction of the host. A swipe in from that edge of the host (host.onEdgeSwipe) drags it open; it opens when pulled out a third of the way (or flicked), a drag on it closes it, and so does a tap on the scrim.
Style.SwipeAction[] acts = [Style.swipeAction("Delete", fn(): bool { remove(msg); return true })]
SynNode row = Style.swipeRow(list, acts)
row.label(msg.subject).fill()

Style.Sheet s = Style.sheet(Style.SheetOptions(root, [0.5, 0.9], fn() {}))
s.body.label("Share")
s.open(0)

Style.Drawer menu = Style.drawer(Style.DrawerOptions(root, "left", 0.8))
menu.body.label("Settings")

Text: a type scale of roles "caption", "body", "subtitle", "title" and "headline", each a size from the scale plus a weight, lineHeight and letterSpacing (Style.typeStyle(t, role) returns them as a Style.TypeStyle). Style.text(parent, t, content, role) is a wrapping label in a role, Style.typeset(node, t, role) applies one to any label, rich text or field, and Style.paragraph(parent, t, spans) is body rich text. Span helpers: Style.code(t, "x = 1") (monospace on a chip in the preset’s field fill and text ink) and Style.link(t, "the docs", "docs") (underlined, in the theme’s link colour).

Writing a preset

A preset is data: start from "dark" or "light" and override what your design changes, so tokens you do not mention keep syn’s values (and pick up new tokens as syn adds them).

fn brand(): Style.Preset {
    Style.Overrides o = Style.overrides()
    Style.put(o, "accent", syn.rgb(16, 122, 87))
    Style.put(o, "surface", syn.rgb(250, 250, 248))
    Style.put(o, "controlRadius", 10)
    Style.put(o, "fieldRadius", 10)
    Style.put(o, "controlPadY", 10)
    return Style.derive(Style.preset("light"), "brand", o)
}

Keep a product’s palette and components in the app (for example a kit.rad next to its theme files), built from Style and these tokens, rather than in syn or syn-style.

Token reference

Every metric token, in compiler/runtime/syn_tokens.inc order (px unless stated). That file is the single source: the runtime, the compiler’s style keys and Style.preset are generated or checked from it.

Constant Token / key Default
Label text inset on each side, inside any padding (was LBL_X / LBL_Y inset) labelInset 4
Selection highlight drawn past the end of a line it continues from selectionEol 6
Thickness of the underline under input-method (marked) text markUnderline 1.5
That underline’s distance above the line bottom markOffset 2
Underline and strike-through thickness in rich text decorationWidth 1
Rich-text underline distance below the baseline underlineOffset 2
Button padding left and right, when pad is unset (was BTN_PX (32 = 16 a side)) controlPadX 16
Button padding top and bottom, when pad is unset (was BTN_PY (16 = 8 a side)) controlPadY 8
Button corner radius, when radius is unset controlRadius 0
Factor a button’s fill is multiplied by while hovered (no hoverColor) hoverShade 1.18
Factor a button’s fill is multiplied by while pressed (no pressColor) pressShade 0.82
Keyboard focus ring on buttons and toggles focusWidth 2
Gap between a toggle and its focus ring focusOffset 2
Field text inset left and right fieldPadX 8
Field text inset top and bottom (height = line + 2 x fieldPadY) fieldPadY 8
Field corner radius, when radius is unset (the select list follows it) fieldRadius 0
Intrinsic width of input, number and select fieldWidth 180
Intrinsic width of a textarea textareaWidth 220
Rows a textarea is at least tall (count) textareaMinRows 3
Rows a textarea grows to at most (count) textareaMaxRows 40
Field border when border is unset; select-list, menu and stepper lines; knob outlines borderWidth 1
Added to a focused field’s border width fieldFocusBorder 1
Floated label size as a fraction of the font (field height grows by it) floatLabelScale 0.72
Floated label’s offset from the field top floatLabelTop 6
Value’s inset from the field bottom under a floating label floatLabelBottom 5
Text caret width caretWidth 2
Space kept between the caret and a field’s right edge while scrolling caretMargin 3
Number field’s +/- column width (desktop) (was SYN_STEPPER_W) stepperW 22
Minimum stepper tap target on touch screens (was SYN_TAP_MIN) tapMin 44
+/- glyph inset in the stepper column (desktop) stepperInset 7
+ glyph top, as a fraction of the upper half (desktop) stepperPlusY 0.25
- glyph top, as a fraction of the lower half (desktop) stepperMinusY 0.1
Select chevron size chevronSize 8
Select chevron centre’s distance from the right edge chevronInset 16
Gap between a select or menu owner and its popup popupGap 4
Select-list highlight inset left and right popupRowInsetX 3
Select-list highlight inset top and bottom popupRowInsetY 2
Select-list highlight radius, as a fraction of the field radius popupRowRadius 0.6
Select-list option text inset popupTextX 10
Menu row height beyond the text line menuRowPad 14
Menu inset around its rows (and the hover highlight’s side inset) menuPad 4
Menu width beyond its widest item menuExtraW 40
Menu minimum width menuMinW 160
Menu corner radius menuRadius 10
Menu hover highlight radius menuItemRadius 6
Menu item text inset menuTextX 14
Menu drop-shadow strength (0..1) menuShadowOpacity 0.35
Menu drop-shadow offset right menuShadowX 2
Menu drop-shadow offset down menuShadowY 4
Space menus and tooltips keep from the window edge viewportMargin 4
Tooltip padding left and right tooltipPadX 10
Tooltip padding top and bottom tooltipPadY 6
Tooltip corner radius tooltipRadius 7
Tooltip offset right of the pointer tooltipOffsetX 12
Tooltip offset below the pointer tooltipOffsetY 20
Tooltip gap above the pointer when it flips up tooltipFlip 8
Checkbox square size (0 = the line height) checkBox 0
Checkbox height beyond the box; width beyond box and label on each side checkPad 8
Gap between the checkbox square and its label checkLabelGap 10
Checkbox corner radius as a fraction of the box, when radius is unset checkRadius 0.25
Unchecked checkbox outline checkBorder 2
Outline factor while a checkbox is hovered or focused checkHoverShade 1.35
Toggle track width switchW 38
Toggle track height (and its minimum row height) switchH 22
Toggle row height beyond the track or text line switchPad 6
Toggle knob inset inside the track knobInset 3
Gap between the toggle track and its label switchLabelGap 10
Toggle focus-ring factor applied to the on colour switchFocusShade 1.3
Slider intrinsic width sliderW 160
Slider intrinsic height sliderH 24
Track inset from the slider’s ends sliderInset 9
Slider track thickness sliderTrackH 4
Slider thumb diameter thumbSize 16
Slider thumb radius growth while hovered, dragged or focused thumbGrow 1
Slider focus halo around the thumb focusHalo 4
Slider focus halo factor applied to the accent focusHaloShade 0.6
Progress intrinsic width progressW 120
Progress intrinsic height progressH 6
Indeterminate segment length, as a fraction of the bar progressSegment 0.3
Radio circle diameter (was SYN_RADIO_DOT) radioDot 16
Gap between the radio circle and its text radioGap 8
Gap between options of a row radio optionGap 20
Radio row height beyond the text line radioRowPad 10
Radio ring thickness radioRing 2
Inset of the selected dot inside the circle radioMark 4.5
Focus ring on the selected radio option or tab optionFocusWidth 1.5
Radius of that ring optionFocusRadius 6
That ring’s factor applied to the accent optionFocusShade 1.2
Radio focus ring outset left and right radioFocusOutset 4
Tab padding left and right tabPadX 16
Tab padding top and bottom tabPadY 11
Tab text raised above centre tabTextLift 1
Selected-tab indicator thickness indicatorH 3
Indicator inset from the tab’s sides indicatorInset 8
Tab focus ring inset tabFocusInset 2
1: the indicator fills the selected tab behind its text (segmented look), inset by indicatorInset; 0: a bar along the bottom indicatorFill 0
Indicator corner radius (0 = half its height: a rounded bar or pill) indicatorRadius 0
Thin rules: tab baseline, table header rule and column lines, chart grid and crosshair, sparkline axis hairline 1
Divider thickness, when border is unset dividerW 1
Split-pane divider thickness (was SYN_DIVIDER_W) splitterW 8
Scrollbar thickness (was SYN_SB_W) scrollbarWidth 6
Scrollbar inset from the edge scrollbarInset 2
Shortest scrollbar thumb scrollbarMinThumb 24
Shadow blur, when the node sets shadow without shadowBlur (was node_new shadow blur) shadowBlur 16
Shadow drop, when the node sets shadow without shadowY (was node_new shadow drop) shadowY 4
Modal backdrop strength (0..1) scrimOpacity 0.45
Intrinsic width of list, table, tree and log dataviewW 300
Intrinsic height of list, table, tree and log dataviewH 300
Data-view row height beyond the text line rowPad 12
List row height beyond a data-view row (when rowHeight is unset) listRowExtra 4
List row padding left and right listRowPadX 12
Gap between a list row’s children listRowGap 8
Table header height beyond a row tableHeaderExtra 4
Table cell text inset tableCellPad 10
Table column width beyond its widest cell tableColExtra 28
Header width reserved for the sort arrow tableSortRoom 22
Sort arrow room in a right-aligned header tableSortW 14
Gap between a header and its sort arrow tableSortGap 4
Column line inset from the header’s top and bottom tableSepInset 6
Strength of the alternate-row tint (0..1) tableZebra 0.35
Width a table gives up for its vertical scrollbar tableBarRoom 10
Tree indent per level treeIndent 18
Tree row content inset treeInset 6
Width of the expand arrow before an item treeTwisty 18
Tree highlight radius treeRowRadius 6
Tree highlight inset top and bottom treeRowInset 1
Log line height beyond the text line logLinePad 2
Log inset above the first and below the last line logPad 4
Log text inset logTextX 8
Log text offset inside its line logTextY 1
Chart intrinsic width chartW 320
Chart intrinsic height chartH 200
Y-label gutter beyond its widest label chartGutter 10
Gap between Y labels and the plot chartLabelGap 8
Legend row height beyond the text line chartLegendPad 8
Plot inset right and bottom chartPad 4
Legend swatch size chartSwatch 10
Legend swatch radius chartSwatchRadius 3
Legend swatch to name chartSwatchGap 14
Legend entry width beyond its name chartLegendGap 26
Share of a slot a bar group fills (0..1) chartBarGroup 0.75
Gap between bars of a group chartBarGap 2
Bar corner radius chartBarRadius 3
Area fill strength (0..1) chartAreaOpacity 0.22
Line series width chartLineW 2
Hover marker diameter chartMarker 8
Hover box offset from the crosshair chartTipOffset 12
Hover box padding left and right chartTipPadX 10
Hover box padding top and bottom chartTipPadY 6
Hover box radius chartTipRadius 6
Hover box swatch size chartTipSwatch 8
Hover box swatch radius chartTipSwatchRadius 2
Hover box text inset (after the swatch) chartTipTextX 24
Sparkline Y-label gutter sparkGutter 26
Sparkline stroke sparkLineW 2
Width of each drawn sparkline column sparkColumnW 1.6
Current-value marker size sparkDot 5
Marker factor applied to the line colour sparkDotShade 1.35
Axis label inset sparkLabelInset 2
Frames the text caret stays on, then off (0 = no blink) caretBlinkFrames 30
Floating-label travel per second, in full rises (0 = jump) floatLabelSpeed 9
Toggle knob travel per second, in full slides (0 = jump) switchSpeed 10
Indeterminate progress sweeps per second progressSweep 0.8
Seconds the pointer rests on a node before its tooltip shows tooltipDelay 0.5
Tooltip fade-in, seconds (0 = no fade) tooltipFade 0.125

Colour roles (the first 13 are the original theme roles; the rest are component parts that used to reuse another role or a literal). “unset” roles fall back as described:

Role Style key (one node) Dark Light Used for
bg — 1A1A1F F4F5F7 window background; a panel that sets a theme paints it
surface — 232836 FFFFFF menus and dropdown lists
field — 3B4252 FFFFFF input, select, checkbox and radio fill; table header and hover rows
border — 4C566A D3D7DE field borders, dividers, rules, knob outlines
text — E5E9F0 1F2328 labels and values
muted — 6B7280 6E7681 placeholders, inactive tabs, axis labels
accent — 5E81AC 4F5BD5 buttons, checked and selected states, slider fill
onAccent — ECEFF4 FFFFFF text on accent fills
selection — 3D5A8A B9D3FB text selection, hovered list options, selected rows
track — 3B4252 E3E6EB progress, slider and toggle tracks
focus — A3BE8C 4F5BD5 keyboard focus ring, floated field labels
tooltip — 0B0D12 2B2F36 tooltip and chart hover-box fill
tooltipText — E5E9F0 F4F5F7 tooltip text
thumb thumbColor FFFFFF FFFFFF slider thumb and toggle knob
indicator indicatorColor unset unset selected-tab indicator (unset: accent)
indicatorText indicatorTextColor unset unset selected-tab text (unset: text)
caret caretColor unset unset text caret (unset: the field’s text colour)
scrollbar scrollbarColor unset unset scrollbar thumb (unset: muted)
scrollbarActive scrollbarActiveColor unset unset scrollbar thumb while dragged (unset: text)
scrollbarTrack scrollbarTrackColor unset unset scrollbar track (unset: track)
splitter splitterColor 434C5E 434C5E split-pane divider
splitterHover splitterHoverColor 5E81AC 5E81AC split-pane divider under the pointer
splitterActive splitterActiveColor 88C0D0 88C0D0 split-pane divider while dragged
scrim scrimColor 000000 000000 modal backdrop (strength: scrimOpacity)
menuShadow menuShadowColor 000000 000000 popup-menu drop shadow (strength: menuShadowOpacity)
chart1 chart1Color 6366F1 6366F1 first chart series without its own colour
chart2 chart2Color 22D3EE 22D3EE second chart series
chart3 chart3Color 34D399 34D399 third chart series
chart4 chart4Color FBBF24 FBBF24 fourth chart series
chart5 chart5Color F43F5E F43F5E fifth chart series
chart6 chart6Color A855F7 A855F7 sixth chart series (then the palette repeats)
sparkBg sparkBgColor 21262E 21262E sparkline plot background
sparkAxis sparkAxisColor 3B4252 3B4252 sparkline Y axis
sparkGrid sparkGridColor 333B49 333B49 sparkline centre gridline
sparkText sparkTextColor 8899AA 8899AA sparkline axis labels
link linkColor unset unset linked spans in rich text, unless the span sets a color (unset: accent)

Not tokens, on purpose: layout and input mechanics (scroll step 30px per wheel unit, page scroll 90% of the view, arrow-key scroll 40px, fling decay and the 10pt touch slop, the split ratio clamp 5–95%), how animation runs (easing, the 30 fps idle frame pacing; its durations and speeds are the motion tokens above), colour math (shades, the backdrop-blur kernel, the shadow’s Gaussian bands), font metrics (the 8px retro glyph cell, the default font Helvetica Neue 15pt, set with .font), and the text colour E6E6EB used only if a caller passes no colour at all. The server.useSyn() dashboard is an application inside the runtime: its DASH_* palette is its own node styling, not engine defaults.


Primitives

Primitives are methods on the parent node. Each appends a child and returns its handle, so trees nest naturally.

Containers

SynNode p    = parent.panel({dir: "column", gap: syn.px(8)})   // generic box
SynNode g    = parent.grid({cols: 3, gap: syn.px(10)})         // wraps into N columns
SynNode s    = parent.split({dir: "row", ratio: 0.3})          // two resizable panes

Text & buttons

parent.label("Some text")
parent.button("Click me", {w: syn.pct(100)}, fn() { sys.output("clicked") })

button(text, {layout}?, onClick) — the click handler is a () => {} / fn(){} closure; the layout spec is optional and sits between text and handler.

Labels show newlines ("line one\nline two") and, with wrap: true, break long text at spaces to fit their width (their height grows to match). In a row, a wrapping label shrinks to the space left beside its siblings, down to its widest word, so {wrap: true, grow: 1} next to an icon wraps instead of overflowing:

card.label(description, {wrap: true})                  // wraps inside the card
row.label(path, {ellipsis: true}).fill()               // one line, cut with …
title.label("Total", {textAlign: "right", w: syn.px(120)})

Styled runs of text (bold, code chips, links) in one wrapping paragraph are rich text; letterSpacing, lineHeight and maxLines are text metrics.

Hovering a clickable node shows a pointing-hand cursor; text fields show an I-beam.

Form fields

SynNode a = parent.input({placeholder: "email", value: "", label: "Email"})
SynNode b = parent.textarea({placeholder: "notes"})
SynNode c = parent.number({value: 30, min: 0, max: 120, step: 1, label: "Age"})
SynNode d = parent.checkbox({label: "Subscribe", checked: true})
SynNode e = parent.select(["Small", "Medium", "Large"], {placeholder: "Size"})

A textarea wraps long lines at its width (breaking at spaces) and grows with its display lines: at least 3 rows, or 1 when it sets minH (which is then the floor), up to 40. With maxH the text scrolls inside to keep the caret in view, so a chat composer is textarea({minH: syn.px(36), maxH: syn.px(140)}). Up/Down move between display lines; Home/End go to the ends of the hard line.

Every handler argument (click, change, row, menu) may be any expression of the right function type: a literal fn(...) { }, a closure held in a variable or parameter (fn wrap(SynNode p, fn(bool): void on) { p.toggle({}, on) }), a named function, or a call returning one.

Field-specific options:

Field Options Change handler
input / textarea placeholder, value, label; input also secure (v) => {} on edit
number value, min, max, step, placeholder, label (v) => {} on edit
checkbox label, checked (b) => {} on toggle
select (options are the first positional arg), placeholder (v) => {} on select

A bare field is just the builder with no options: root.input() gives a plain, unlabeled input attached to root.

label gives a floating label — it rests inside the empty field and animates up to a caption when the field gains focus or content.

secure: true makes a password field. The value is drawn as one bullet per character and is never copied or cut to the clipboard (Cmd+C / Cmd+X and the iOS edit menu do nothing); the change handler and value() still give the real text. The keyboard turns off autocorrect, suggestions and learning: iOS secureTextEntry, Android’s password input type. field.setSecure(bool) switches it at runtime, for a “show password” toggle:

SynNode pw = root.input({placeholder: "API key", secure: true})
root.button("Show", fn() { pw.setSecure(false) })

Headless layout dumps show the bullets and "secure": true, never the text.

Components

Built-in controls beyond the form fields, called on the parent like any primitive (and as syn.slider(...) etc. inside children:[...]). Every one takes the usual layout/style keys.

root.divider()                                            // hairline across the parent
row.spacer()                                              // pushes later siblings to the end
SynNode bar = root.progress({value: 0.4, color: accent})  // 0..1; a negative value animates
root.slider({value: 20, min: 0, max: 100, step: 5}, fn(num v) { bar.setNumber(v / 100.0) })
root.toggle({label: "Dark mode", checked: true}, fn(bool on) { applyTheme(on) })
root.radio(["Small", "Medium", "Large"], {selected: "Medium"}, fn(string v) { size = v })
root.tabs(["Profile", "Billing"], fn(string v) { showPane(v) })
root.image("assets/logo.png", {w: syn.px(120), fit: "cover"})

A relative image path is read from the working directory and, if it is not there, from the app’s bundled resources (the app bundle on iOS, whose working directory is Application Support; Contents/Resources on macOS; the APK’s assets on Android), so public/... images ship with the app unchanged. radius rounds an image’s corners with any fit.

Builder Options Handler Read / write
divider color, border (thickness) — —
spacer — — —
progress value, color, trackColor, kind: "ring", strokeWidth, gradient — numberValue(), setNumber(v)
slider value, min, max, step, color, trackColor fn(num v) numberValue(), setNumber(v)
toggle label, checked, color, trackColor fn(bool on) checked(), setChecked(b)
radio (options first), selected, dir: "row" fn(string v) value(), setSelected(s)
tabs (tab names first), selected (default: the first), color, borderColor fn(string v) value(), setSelected(s)
image (path first), fit: "contain" (default), "cover", "fill" — —

A divider is horizontal in a column and vertical in a row. An image hugs its pixel size; give one explicit px dimension and the other follows the aspect ratio. Image paths are relative to the working directory. Sliders, toggles, radio groups and tabs take Tab focus; arrow keys step a slider or move the selection, Space/Enter flips a toggle.

Two modifiers work on any node:

icon.tooltip("Delete this item")                         // after a short hover
more.menu(["Rename", "Duplicate", "Delete"], fn(string item) { act(item) })

menu opens a popup under the node when it is clicked (it flips above near the window’s bottom); picking an item calls the handler, a click elsewhere or Escape closes it.

Keyboard

Tab / Shift+Tab move focus across fields; Enter/Space activate a focused button/checkbox/select; a modal traps focus while it’s open.

Text fields edit like native macOS fields:

Keys / mouse Effect
Shift + arrows / Home / End extend the selection
Option + Left / Right move by word (Shift to select)
Cmd + Left / Right start / end of the line
Option + Backspace / Delete delete a word; Cmd + Backspace deletes to the line start
Cmd + A / C / X / V select all, copy, cut, paste (the system clipboard)
Up / Down (textarea) previous / next line, keeping the column
drag, double-click, triple-click select a range, a word, everything

Typing or pasting replaces the selection; a number field keeps only the characters it accepts from a paste. Long values scroll sideways to keep the caret in view.

On-screen keyboard (iOS, Android)

On a phone, focusing an input, textarea or number (a tap on it, or Tab from a hardware keyboard) brings up the system keyboard, and losing focus puts it away: a tap outside the field, Return/Done in a single-line field, Escape on a hardware keyboard, or the system’s own dismiss. While the docked keyboard is up, the safe area’s bottom edge sits on top of it, so the layout shrinks into the space above and the focused field is scrolled into view inside its scrolling container (put long forms in an overflowY: "auto" panel).

From code, field.focus() focuses an editable field with the caret at the end of its text and raises the keyboard, as editing a message again does. field.blur() puts the keyboard away. Both are chainable, and they are ignored on nodes that are not editable. Neither fires onChange. A focus set before syn.run applies when the window opens.

On iOS the keyboard edits through the system text input, so autocorrect, predictions, swipe typing, dictation, the emoji keyboard and input-method composition (CJK) all work; composing text is underlined in the field and reaches the change handler when committed. Backspace deletes whole emoji. A long press in the focused field opens the system edit menu (Cut, Copy, Paste, Select All). The keyboard follows the field:

Field Keyboard Return key
input default, sentence capitalization, autocorrect Done (blurs the field)
input in a monospace font no autocorrect, capitalization or smart quotes Done
textarea default newline; a Done bar above the keyboard blurs
number, min >= 0, whole step number pad Done bar
number, min >= 0, fractional step decimal pad (a decimal comma types .) Done bar
number allowing negatives numbers and punctuation Done

The keyboard’s appearance follows the field’s theme (dark or light). Tapping a number field’s −/+ steppers steps it without raising the keyboard. syn has no password field, so there is no secure-entry keyboard. With a hardware keyboard (iPad, simulator) keys type through the same path, and arrows, Home/End, Tab, Escape and Return act as on desktop.

Read-only text can be made selectable, so users can copy it:

root.label(errorDetails, {wrap: true, selectable: true})   // drag or double-click, then Cmd+C

Declarative children

The builder form (parent.method(...)) is imperative: each call mutates the tree and hands back a node. Alongside it, any container accepts a children:[...] option — a declarative form where the code’s nesting mirrors the UI tree. Every entry in the list is attached to the container automatically, in order:

root.panel({dir: "column", gap: syn.px(10), children: [
    syn.label("Title").font({size: 22, weight: "bold"}),
    syn.label("Nesting is the tree — no parent handle needed."),
    syn.panel({dir: "row", gap: syn.px(8), children: [
        syn.button("One", {color: accent}, fn() { sys.output("one") }),
        syn.button("Two", {color: accent}, fn() { sys.output("two") })
    ]})
]})

children entries are built with the syn. builder form — syn.panel, syn.label, syn.button, syn.input, syn.textarea, syn.number, syn.checkbox, syn.select, syn.grid, syn.split, syn.divider, syn.spacer, syn.progress, syn.slider, syn.toggle, syn.radio, syn.tabs, syn.image — which create a detached (parentless) node. The container adopts them; that’s what makes the attachment automatic. (A parent.method(...) call attaches immediately to parent instead, so don’t nest those inside children — the node would end up in two parents.) Containers that adopt: panel, grid, split.

Handles are still recoverable. Build a node into a variable, drop the variable into children[], and mutate it later from a closure — the declarative form doesn’t hide it from you:

SynNode status = syn.label("idle").font({italic: true})
root.panel({dir: "row", gap: syn.px(8), children: [
    status,
    syn.button("Ping", {}, fn() { status.setText("pong") })
]})

Mix freely: use children:[...] for static structure, and parent.method(...) when you’re building nodes in a loop or need the handle inline.


Chainable modifiers

These return the same node, so you chain them onto a builder:

parent.panel({dir: "row"}).grow(1)
parent.label("Title").font({size: 24, weight: "bold"})
Modifier Effect
.grow(n) take a share of leftover main-axis space (flex weight n), starting from the content size
.fill() take exactly the remaining space; may shrink and scroll (see Flex sizing)
.style({...}) set any layout/style key at runtime (same keys as a builder spec)
.id(name) tag the node (used by tests and the headless layout dump)
.font({...}) typography — see Typography
.overlay(modal?) / .modal() float this node above the tree (dialogs/toasts)
.ttl(seconds) auto-hide this node after seconds (toasts)
.hide() / .show() / .setVisible(bool) visibility

Scrolling

A row/column/grid/table whose content is larger than its box scrolls (overflow: "auto", the default):

  • the mouse wheel / trackpad scrolls the innermost region under the pointer; once it reaches its end the rest passes to the next scrolling ancestor;
  • the scrollbar thumb can be dragged, and clicking the track pages;
  • PageUp/PageDown, Home/End and the arrow keys scroll the region under the pointer (or the one holding the focused widget) when no text field or select has focus;
  • Tab scrolls the newly focused field into view.

A container scrolls along its main axis by default. To scroll the other way too (a wide table in a column, a canvas), set overflowX (or overflowY on a row). Children stretch across a column by default, so give a scrolling canvas align: "start" to let its rows keep their content width:

SynNode canvas = card.panel({dir: "column", h: syn.px(300), overflowX: "auto", align: "start"})

A vertical wheel over a region that only scrolls sideways scrolls it sideways; trackpads scroll both axes. A touch drag selects its dominant axis when it passes the drag threshold and keeps that axis through the fling; a new drag may select the other axis. Scroll chaining along the selected axis still passes excess movement to an ancestor at an edge.

scrollbars: false on a node hides its scrollbars and disables their track hit targets without changing scrolling, clipping or scroll offsets. It inherits to descendants; set scrollbars: true on a descendant to show them again. Bars are visible by default. A region that scrolls in both directions shows one bar: vertical initially, then the axis that most recently moved. The other axis remains scrollable and becomes the visible bar when used. Set visibility in a builder or later with .style(...):

SynNode list = root.panel({dir: "column", scrollbars: false})
list.style({scrollbars: true})

From code: node.scrollTo(px), node.scrollToEnd() (both chainable) and node.scrollOffset() (current offset in px). stickToBottom: true keeps a log or feed pinned to its newest content until the user scrolls up, and resumes when they scroll back to the end.

Changing the tree

list.clear()                      // destroy every child
row.remove()                      // detach + destroy this node
list.add(syn.label("new"))        // attach a detached node (or move one)
list.insert(0, syn.label("top"))  // ... at an index
int n = list.childCount()
card.onClick(fn() { open(card) }) // any node can take clicks

A handle to a removed node becomes inert: calls on it are ignored rather than touching freed memory.

Hover, keys and size

card.onHover(fn(bool inside) { card.style({border: syn.px(inside ? 2 : 0)}) })
win.onKey(fn(string key) {
    if (key == "cmd+s") { save() }
    if (key == "escape") { dialog.hide() }
})
chart.onResize(fn(num w, num h) { redraw(w, h) })   // whenever its laid-out size changes

onKey receives key names with modifier prefixes: "a"…"z", "0"…"9", "f1"…"f12", "enter", "escape", "space", "tab", "backspace", "delete", arrows ("left" …), "home", "end", "pageup", "pagedown", prefixed in the order cmd+, ctrl+, alt+, shift+ (e.g. "cmd+shift+z"). While a text field has focus, plain typing and its editing shortcuts stay with the field; other Cmd/Ctrl shortcuts still reach onKey. Handlers on a hidden node do not fire. When the app registers an onKey handler, Escape no longer closes the window.

Back (Android)

win.onBack(fn(): bool {
    if (screen == "home") { return false }   // let Android leave the app
    showHome()
    return true                              // handled: stay
})

Android’s Back button or gesture first closes what syn itself opened: an open menu or dropdown, else the focused text field (and its keyboard) or a text selection. Otherwise the onBack handlers run, newest first, until one returns true; a handler on a hidden or removed node does not run. When none returns true, Android leaves the app. Any node can carry one handler (onBack returns the node, like the other event setters), so a sheet or sub-screen can register its own and remove it with the node.

Without any onBack handler, an app that has onKey handlers receives Back as "escape" and stays open; an app with neither leaves. iOS and desktop platforms have no Back button, so onBack never fires there. The headless script’s back step presses Back (see Testing layouts headlessly).

Platform signals

The system’s appearance, motion preference and app lifecycle, plus keeping the display awake. They belong to the engine, not to a style: an app (or the style library’s Style.followSystem) decides what a dark system means.

syn.systemAppearance(): string      // "light" or "dark"
syn.onAppearance(fn(string mode))   // called when the system appearance changes
syn.reduceMotion(): bool            // the system's reduce-motion setting
syn.onLifecycle(fn(string state))   // "active", "inactive" or "background"
syn.keepAwake(bool on)              // hold the display awake while on
SynNode root = win.panel({dir: "column"}).theme(syn.systemAppearance())
syn.onAppearance(fn(string mode) { root.theme(mode) })
syn.onLifecycle(fn(string state) {
    if (state == "background") { save() }
})
syn.keepAwake(true)      // while a long generation runs

Handlers run on the UI thread, only on a change (registering one does not call it), and any number can be registered. A new appearance is noticed within about a quarter of a second.

Signal iOS Android macOS Linux
systemAppearance the window’s traitCollection.userInterfaceStyle Configuration.uiMode night bit NSApp.effectiveAppearance always "light"
reduceMotion UIAccessibilityIsReduceMotionEnabled ANIMATOR_DURATION_SCALE == 0 (“Remove animations”) accessibilityDisplayShouldReduceMotion false
onLifecycle scene activate / deactivate / enter background / enter foreground pause is "background", resume is "active"; never "inactive" (the frame loop stops when the window loses focus and sokol raises no event for it) application active / resign / hide / unhide window focus: "inactive" and "active"; minimise: "background"
keepAwake idleTimerDisabled FLAG_KEEP_SCREEN_ON an IOPM assertion against idle display sleep no effect

keepAwake(true) is applied by the frame loop, so it can be called before syn.run or from any thread. The reduce-motion setting is exposed for apps and style libraries to consult; syn’s own transitions do not change with it.

Testing: in a headless run RADLANG_SYN_APPEARANCE=dark|light sets what systemAppearance reports and RADLANG_SYN_REDUCE_MOTION=1 sets reduceMotion (a real window ignores both and asks the platform). The headless script verbs appearance:dark and lifecycle:background change them mid-run and fire the handlers, and keepAwake prints SYN-KEEPAWAKE on|off (see Testing layouts headlessly).

Timers and async work

int id = syn.every(1000, fn() { clock.setText(Date.new().format("HH:mm:ss")) })
syn.after(2500, fn() { toast.hide() })
syn.cancel(id)

Timer callbacks run on the UI thread from the frame loop, so they can update nodes directly. Code running on another thread (an HTTP handler, a worker) must not touch nodes; it hands the work over with syn.post:

server.post("/jobs", fn(HttpRequest req): HttpResponse {
    syn.post(fn() { status.setText("job queued") })   // runs on the UI thread
    return HttpResponse(202, "queued")
})

Keep posted closures to state that outlives the request (UI nodes, top-level values); request data may be gone by the time the UI thread runs them.

The window only redraws when something can have changed: input, a timer, a posted closure, finished async work, a resize or a running animation. An idle window uses almost no CPU: after 300 ms with nothing to draw, the frame loop itself slows to 30 frames a second (on macOS, iOS and Android), and the first change brings back the display’s full rate. Timers and async results that land while idle are seen within a frame at that rate (at most ~33 ms later). The frame loop also drives the async scheduler, so event handlers can be async:

root.button("Load", async fn() {
    HttpResponse r = await http.get(url)
    status.setText(r.status.toString())
})

Getters & setters

Read and mutate widget state live:

string v  = field.value()          // input/textarea/number text; select → selected text
num    n  = field.numberValue()    // number field as a num
bool   on = box.checked()          // checkbox
bool   vis = node.visible()

field.setValue("new")
box.setChecked(false)
sel.setSelected("Medium")
label.setText("updated")
node.setColor(syn.rgb(0, 120, 0))
node.setTheme("accent", syn.rgb(244, 63, 94))   // a theme role or token by name
win.title("New window title")
node.close()

syn.layout(win, 800, 600)          // headless layout pass (tests), then:
num w = node.layoutW()             // layoutX / layoutY / layoutW / layoutH
num pad = node.token("controlPadX")
int accent = node.role("accent")

Gestures

photo.onLongPress(fn(num x, num y) { showMenu(x, y) })
photo.onDoubleTap(fn() { like() })
row.style({panAxis: "x"})
row.onPan(fn(string phase, num dx, num dy, num vx, num vy) {
    if (phase == "move") { row.style({translateX: syn.px(dx)}) }
    if (phase == "end" || phase == "cancel") { row.animate({translateX: syn.px(0)}) }
})
canvas.onPinch(fn(string phase, num scale, num cx, num cy) { zoomTo(base * scale) })
viewer.style({zoomable: true, maxScale: 5})          // pinch, pan and double-tap zoom built in
root.onEdgeSwipe("left", fn(string phase, num dx, num dy, num vx, num vy) { drawer(phase, dx, vx) })
feed.onScroll(fn(num offsetY, num offsetX) { header.style({opacity: offsetY > 40 ? 0 : 1}) })
feed.style({dismissKeyboardOnDrag: true})

One recognizer watches touches and the mouse alike, in window points:

Handler Fires
onLongPress(fn(num x, num y)) after a 500 ms hold that stays within 10 points of where it began, with the point in the node’s own box (0, 0 is its top-left). The press then no longer clicks, drag-selects or scrolls. A held mouse button counts. A focused text field keeps the platform’s own long press (the iOS edit menu).
onDoubleTap(fn()) on the second of two taps on the node within 300 ms (after that tap’s own click: each tap still clicks). A mouse double click counts.
onPan(fn(string phase, num dx, num dy, num vx, num vy)) once the pointer leaves the 10-point slop: "begin", then "move"s, then "end" (or "cancel"). dx/dy are the distance from where the press began, vx/vy the velocity in points per second (0 at "end" when the pointer had stopped). The press no longer clicks or scrolls. A mouse drag counts.
onPinch(fn(string phase, num scale, num cx, num cy)) two fingers on the node: "begin" (scale 1), "move"s, "end"/"cancel". scale is relative to the start; (cx, cy) is the centre between the fingers, in the node’s box. macOS trackpads pinch through their magnify gesture, centred on the pointer.
onEdgeSwipe(string edge, fn(phase, dx, dy, vx, vy)) on the root (any node; the newest shown one per edge wins): a press within 20 points of the "left" or "right" window edge that moves inward. Same arguments as onPan; it wins over every onPan.
onScroll(fn(num offsetY, num offsetX)) on a scrolling node, after its offsets change: at most once per frame, after layout (offsets are clamped by then).

The nearest node under the press with a matching handler takes the gesture; an onPan node whose axis does not match passes it to its ancestors. When nothing takes a drag it does what it did before: scroll on a touch screen, select text with a mouse, move a slider, a scrollbar or a split divider (those keep their drags first).

Style key Values Effect
panAxis "both" (default), "x", "y" the node’s onPan claims a drag only when it leaves the slop mostly along that axis, so a "x" row inside a vertical list pans sideways while vertical swipes still scroll the list
zoomable true / false built-in zoom of the node’s children (an image viewer): two-finger pinch (trackpad magnify on macOS) scales about the fingers, a one-finger drag pans while zoomed in (kept inside the node), and a double tap toggles between 1 and 2x (at most maxScale). Children are drawn and hit-tested through the zoom, like a transform; the node clips them unless overflow: "visible"
minScale / maxScale number (defaults 1 / 4) the zoom’s limits; below 1 the content stays centred
dismissKeyboardOnDrag true / false a touch drag that starts inside the node (a scroller, usually) blurs the focused text field, which hides the on-screen keyboard

The headless dump reports a zoomable node’s zoom (scale, x, y), and its children’s drawn boxes as vrect. The headless script has a step for each gesture (see Testing layouts headlessly).

Platforms: iOS and Android deliver every finger (Android by MotionEvent pointer index), so pinch works on both; macOS uses the trackpad’s magnify event for pinch and the mouse for the rest; Linux and the portable GL build use the mouse (no pinch).


Animation

syn animates the way CSS does: a node has render-only transforms, a transition tweens a later style() change, and node.animate runs an animation from one set of values to another. Animations advance from the frame clock, not timers: while one runs the window draws at the display’s full rate, and the idle pace (30 fps after 300 ms with nothing to draw) returns once they all end. The look of an animation (durations, curves, what moves) belongs in the style library or the app; syn-style ships motion tokens and Style.reveal, Style.pulseDots and Style.blink.

Transforms

These style keys move, scale or turn a node and its subtree as drawn. They never change layout: the node keeps its box and its siblings stay put.

Key Value Default
translateX / translateY syn.px(n) (or a plain number, px), or syn.pct(n): percent of the node’s own width / height 0
scale factor for both axes (sets scaleX and scaleY) 1
scaleX / scaleY factor per axis 1
rotate degrees, clockwise 0
originX / originY the point scale and rotation keep fixed, as a fraction of the box (0 left / top, 1 right / bottom) 0.5
badge.style({translateY: syn.px(-2), scale: 1.1})        // lifted and enlarged, layout unchanged
icon.style({rotate: 90})                                  // a chevron turned to point down
thumb.style({scale: 0.5, originX: 0, originY: 0})         // shrunk toward its top-left corner

Clicks, hover, drags and Tab’s scroll-into-view use where the node is drawn (translate and scale exactly; a rotated node is hit inside its bounding box), and a moved node is still clipped by its scrolling ancestors.

Transitions

chip.style({transitionMs: 160, transitionCurve: "easeOut", transitionProps: "color, borderColor, opacity"})
chip.onHover(fn(bool inside) { chip.style({color: inside ? hot : idle}) })   // fades between the two
Key Value
transitionMs duration of each change (0 turns transitions off)
transitionCurve a curve name (see curve below); default "ease"
transitionProps the properties that transition, comma-separated: any animatable property, translate (both axes) or all

A later style() change to a listed property tweens from the current value to the new one; other keys still apply at once. Nothing transitions before the node has been laid out or while it is hidden, so the values a node is built with apply directly.

node.animate

int id = card.animate({opacity: 1, translateY: syn.pct(0)},
                      {ms: 250, curve: "easeOutCubic", from: {opacity: 0, translateY: syn.pct(-4)}},
                      fn() { sys.output("shown") })

node.animate(props, opts?, onDone?) returns an animation id. props maps animatable properties to their target values; opts and the onDone handler are optional. Both specs are {...} literals (the compiler reads their keys, and unknown ones are warnings).

Animatable properties: opacity, color (or background), borderColor, textColor, shadow (its colour), shadowBlur, shadowY, backdropBlur, translateX, translateY, scale, scaleX, scaleY and rotate. Colours blend per channel, translucency included. An unset colour starts from the colour the theme draws (a button’s accent, the text colour, the border role) or, for fills and shadows, from the target made fully transparent.

Option Meaning Default
ms duration of one run 250
curve "linear", "ease", "easeIn", "easeOut", "easeInOut", "easeOutCubic" or "spring" "ease"
delay ms before it starts 0
repeat extra runs after the first; -1 repeats forever 0
alternate every other run plays backwards false
from start values (a {...} of animatable properties); the others start from their current value —
stiffness, damping the "spring" curve’s spring (mass 1), stretched to ms 170, 26

The ease… curves are the CSS timing functions (ease is cubic-bezier(0.25, 0.1, 0.25, 1)), and easeOutCubic is 1 - (1 - t)³. The node takes its from values at once, so it never flashes its end state first. A property in from but not in props animates back to its current value. The end values stay when an animation ends (with alternate and an even number of runs, that is the start). Starting an animation, or a direct style() of a property, takes that property over from any animation already running on the node.

syn.cancelAnimation(id)          // stop it where it is (onDone does not run)
node.stopAnimations()            // stop every animation on the node (chainable)
syn.setAnimationScale(0)         // reduced motion: every animation jumps to its end
syn.setAnimationScale(2)         // everything twice as slow (running ones keep their progress)

syn.setAnimationScale(f) multiplies every duration and delay, transitions included; 0 finishes each animation on the next frame (an endless one stops at the end of its first run) and runs its onDone. Apps use it for the platform’s reduced-motion setting. An animation of a removed node is dropped; one on a hidden node keeps time but does not keep frames coming.

syn’s own small animations (the toggle knob, the floating field label, the caret, indeterminate progress, tooltip fades) are built in and not affected.

Headless runs drive animations from the virtual clock: each wait:MS step advances them in 16 ms frames, so the values in a dump are deterministic (see Testing layouts headlessly).


Typography

Text nodes render from a font that inherits down the tree — a node uses its parent’s font unless it overrides it, and it overrides only the attributes you name. The default is Helvetica Neue 15pt regular.

// A base font on the root; everything under it inherits.
SynNode root = win.panel({dir: "column"}).font({family: "Helvetica Neue", size: 15})

root.label("Heading").font({size: 30, weight: "bold"})   // bigger + bolder
root.label("Body inherits 15pt regular.")                // no override
root.label("Caption").font({size: 13, weight: "light", italic: true})

// A nested container changes the family; its children inherit that…
SynNode code = root.panel({}).font({family: "Menlo"})
code.label("mono, inherited")
code.label("mono, bold").font({weight: "bold"})          // keeps Menlo, only weight changes

.font({...}) options (all optional — unset attributes inherit from the parent):

Key Value
family font family name, e.g. "Helvetica Neue", "Menlo"; the aliases "mono" and "system"; or a family registered with syn.registerFont (see Fonts and icons)
size point size (a number)
weight "thin", "light", "regular", "medium", "semibold", "bold", "heavy", "black"
italic true / false

Layout stays intrinsic at any size — a 30pt heading hugs to 30pt, no clipping.

Each distinct font (family, size, weight, italic, letterSpacing, lineHeight) is built once and shared. A window holds up to 64; past that syn prints one warning on stderr and draws each further font with the nearest one already built (same family first, then italic, weight and size).

Text metrics

Three style keys shape text (labels, rich text, buttons and fields):

Key Value
letterSpacing px between characters, may be negative (-0.5, 0.4). A label’s measured width changes by (characters − 1) × spacing.
lineHeight the line box as a multiple of the font size (1.3, 1.5, like CSS line-height), or syn.px(n) for a fixed height. The extra space is split above and below the text.
maxLines a label shows at most this many lines (wrapped or not); the last is cut with …. On a textarea it caps the rows it grows to (the same as textareaMaxRows).

letterSpacing and lineHeight belong to the font: like .font() attributes they inherit down the tree, so setting them on a panel sets its whole subtree.

root.label("Headline", {letterSpacing: -0.5, lineHeight: 1.25}).font({size: 28, weight: "bold"})
card.label(summary, {wrap: true, maxLines: 2})

Rich text

parent.richText(spans, {layout}?) is a label made of styled spans (syn.richText(...) inside children: [...]); node.setSpans(spans) replaces them. Each span is a SynSpan; a literal names only the fields it sets:

SynNode p = root.richText([
    {text: "Run "},
    {text: "radlang build", family: "mono", background: syn.rgb(40, 44, 52), color: syn.rgb(230, 180, 80), bgRadius: 4, padX: 4},
    {text: " then read "},
    {text: "the docs", link: "docs", underline: true},
    {text: ". It is "},
    {text: "fast", bold: true}
], {wrap: true, selectable: true})
p.onLink(fn(string tag) { sys.output("open " + tag) })
SynSpan field Type Effect
text string the span’s text (newlines break lines)
bold / weight bool / string bold, or any .font() weight name
italic bool italic
family string a font family; "mono" is the platform’s monospace
size num point size (0: the label’s)
color int? text colour (unset: the label’s text colour; a link’s: the link role)
background int? a chip behind the span (unset: none), the height of its font
bgRadius, padX num the chip’s corner radius, and space inside it before and after the text
underline, strike bool underline, strike-through (decorationWidth, underlineOffset tokens)
link string a tag: a tap or click on the span calls node.onLink(fn(string tag))

Unset fields inherit the label’s font and colours (.font(), textColor, the text metrics above). Wrapping flows across spans and may break inside one at a space; ellipsis, maxLines, textAlign and selectable work as for labels, and selection copies the plain text (the spans’ texts joined, which is also what text shows in a dump). setText on a rich label makes it plain.

A SynSpan[] held in a variable works too (SynSpan code = {text: "x", family: "mono"}), and can be built up a span at a time (spans.add({text: "x", bold: true}); fields a literal leaves out keep their defaults). A list literal mixing span literals with SynSpan values is accepted directly by richText and setSpans; elsewhere declare the literals as SynSpan first.


Fonts and icons

syn ships no fonts and no icon table. An app brings its own font files, and a style library (written in radlang, on top of syn) decides which family is which; the engine only loads and draws them.

Registering a font

bool ok = syn.registerFont("Inter", "public/fonts/Inter-Regular.ttf")
if (!ok) { sys.output("Inter is missing; using the system font") }
root.label("Hello").font({family: "Inter", size: 18})

syn.registerFont(family, path) makes a TrueType or OpenType file available as font({family}) and returns true. Call it at the start of main, before syn.run. The path resolves like an image path: relative to the working directory first, then inside the app’s bundled resources (the app bundle on iOS, Contents/Resources on macOS, the APK’s assets/ on Android), so a font kept in public/fonts/ ships with every target unchanged. Nothing else is needed: radlang build --target ios and --target android already copy public/.

syn.registerFont(family, path, icons) takes an optional third argument; true marks the file an icon font outright (see Icon fonts).

Register fonts on the main thread. A font registered after the window is already running (say from a click handler) applies at the start of the next frame: until then text in that family keeps the substitute it had, and no font is rebuilt in the middle of a frame.

A bad path, or a file that is not a font, returns false and prints one warning (syn: registerFont('Inter'): cannot load font '...'); text in that family falls back to the default font. Registering the same family and file again is harmless; a different file for a family already registered returns false. Up to 16 fonts can be registered.

One registration is one face: the family name selects that file whatever weight and italic the node asks for, so register a bold file under its own name ("Inter Bold") and use it directly. Characters the file lacks come from the system’s fallback fonts as usual (a Latin font still shows emoji and CJK), except in icon fonts, below. On Apple platforms the file is also registered with CoreText for the process (CTFontManagerRegisterFontsForURL, process scope); elsewhere the portable loader parses it the way it parses /system/fonts.

Family aliases

Family Resolves to
"mono" the platform’s monospace face: Menlo on macOS and iOS; on Android and Linux the system monospace (Droid Sans Mono, Roboto Mono, DejaVu Sans Mono, Cutive Mono, …)
"system" the platform’s UI font: San Francisco on Apple’s CoreText path; on the portable rasterizer (Android, Linux, RADLANG_SYN_FONT=ttf) it is the sans role (Roboto, Noto Sans, DejaVu Sans, …), the same face as the default font

Any other name that is not registered is looked up by the platform as before ("Helvetica Neue", "Menlo", "DejaVu Sans").

Icon fonts

A registered font is an icon font when it maps private-use codepoints (U+E000 to U+F8FF) and is not a text font, meaning it maps fewer than half of the 52 ASCII letters; icon sets such as Font Awesome are addressed by private-use codepoints and carry no Latin text. A full text font that merely patches in private-use glyphs (a Nerd-Font-style build) maps the Latin letters, so it stays a text font and keeps its fallback for CJK, emoji and symbols. Where the rule guesses wrong (an icon font that also maps the letters, as ligature icon fonts like Material Icons do), pass true as the third argument:

syn.registerFont("Icons", "public/fonts/MaterialIcons.ttf", true)

Label text in an icon font renders with the node’s size, weight and colour like any text, and a glyph the font lacks draws nothing: it never falls through to a fallback font, which would show an unrelated symbol or a box. The first missing glyph of a font prints one warning (syn: icon font 'Icons' has no glyph for U+E0F0 ...). Spaces in an icon font keep a quarter-em advance.

syn.glyph(codepoint) turns a codepoint into the string to show (the lexer has no hex literals, so a codepoint is a decimal int; U+E5D5 is 58837; a string literal can also say "\u{e5d5}"):

syn.registerFont("Icons", "public/fonts/MaterialIcons.ttf", true)
root.label(syn.glyph(58837)).font({family: "Icons", size: 24}).style({color: syn.rgb(120, 130, 140)})

syn keeps no icon names and no default icon family. A style library built on syn wraps this in a helper that owns the family name and the colour (from the app’s theme tokens); the whole of it is a label. syn-style’s Style.icon(parent, codepoint, size, color) is this helper, drawing in the family set by Style.setIconFamily(family) (default "Icons"):

fn icon(SynNode parent, string family, int codepoint, num size, int color): SynNode {
    SynNode glyph = parent.label(syn.glyph(codepoint), {color: color})
    glyph.font({family: family, size: size})
    return glyph
}

Tinted images

Monochrome PNG icons (white or black on transparency) are recoloured with tint, so one asset serves every theme:

row.image("public/icons/search.png", {w: syn.px(20), tint: syn.rgb(120, 130, 140)})
icon.style({tint: syn.rgba(255, 255, 255, 0.6)})    // later changes work
icon.style({tint: ""})                              // draw the picture as it is

The image is treated as an alpha mask: its colours are dropped and each pixel takes the tint, keeping its own alpha (a syn.rgba tint multiplies the alpha). tint also applies to a panel’s backgroundImage.

Testing

Headless runs need no window: layouts reflect the font’s metrics (a label’s w), and RADLANG_SYN_ATLAS_PNG=<file> writes the glyph atlas, which shows every glyph that was drawn (an icon font’s missing glyphs add no ink). Layout dumps list a tinted image’s tint and tintAlpha. See tests/integration/gui/syn-fonts.py and its fixture font in tests/fixtures/syn-fonts/ (four private-use glyphs; make-icon-font.py generates it, Apache-2.0).


Primitives vs. components

There are two layers, distinguished by how you call them:

Built by Call shape
Primitives the compiler parent.method(...) — receiver is the parent
Components the layout library layout.fn(parent, ...) — parent is arg 1

Both attach a child to whatever parent you give them; the tree is always root → containers → widgets. The difference is only who authored the builder: primitives are compiler-emitted node types, components are composed radlang in ns layout, which ships in the standard library (libraries/stdlib/ns/layout.ns.rad): The layout components are in the stdlib package: import { layout } from "stdlib" (it needs the stdlib entry under packages: in config.yaml, which every radlang new project has; a bare import "layout" does not resolve).

Note: grid and split exist in both layers. root.grid({cols: 3}) is the raw primitive; layout.grid(root, 3) is the styled component that wraps it.


Data views

Built-in views for large or structured data. Each draws only what is on screen, scrolls with the wheel, scrollbar and keyboard like any container, and takes the usual layout keys. Give them a height (or .fill()); their default height is 300px (200px for charts).

// 100,000 rows: the builder runs only for rows scrolled into view
root.list(100000, {h: syn.px(400), rowHeight: syn.px(32)}, fn(SynNode row, int i) {
    row.label("Row " + i.toString()).fill()
    row.label(prices[i])
})

// sortable table: click a header (numbers sort numerically), click a row
SynNode people = root.table(["Name", "Age", "City"], {h: syn.px(300)}, fn(int row) { open(row) })
people.addRow(["Ada", "36", "London"])

// tree: parent id "" is the top level; arrows / ← → navigate
SynNode files = root.tree({h: syn.px(300)}, fn(string id) { preview(id) })
files.addItem("", "src", "src")
files.addItem("src", "main", "main.rad")
files.setExpanded("src", true)

// charts: line, bar or area; series are replaced by name;
// cpu.style({kind: "bar"}) switches the kind at runtime
SynNode cpu = root.chart({kind: "area", h: syn.px(200)})
cpu.setSeries("CPU %", samples, syn.rgb(34, 211, 238))   // num[] or int[]

// log: append lines (capped at maxLines), follows the end
SynNode out = root.log({maxLines: 2000, h: syn.px(240)}).font({family: "Menlo"})
out.append("server started")
out.append("disk almost full", syn.rgb(251, 191, 36))
View Data Handler Notes
list(count, {rowHeight}?, builder) setCount(n), refresh() — the builder gets an empty row panel (dir: "row", centered) and the index
table(columns, {..}?, fn(int row)?) addRow(cells) data row index on selection headers sort; numeric columns right-align; wide tables scroll sideways
tree({..}?, fn(string id)?) addItem(parentId, id, label), setExpanded(id, b) id on selection click the arrow (or a selected parent) to expand
chart({kind}?) setSeries(name, values, color?) — kind: "line" (default), "bar", "area"; hover shows values
log({maxLines}?) append(text, color?) — drag selects lines, Cmd+A / Cmd+C copy

clear() empties a view’s data and childCount() returns its rows, items, lines or series.


Layout components

import { layout } from "stdlib" first. Each takes its host container as the first argument and returns the node(s) you fill.

list — a scrollable, fixed-height column

SynNode items = layout.list(root, 240)   // 240px tall, scrolls when it overflows
items.label("Row 1")
items.label("Row 2")

grid / split — styled containers

SynNode g = layout.grid(root, 3)                       // 3 equal columns
SynNode[] panes = layout.split(root, "row", 0.3, 400)  // [left, right], left = 30%, 400px tall
panes[0].label("sidebar")
panes[1].label("content")

accordion — collapsible sections

SynNode acc = layout.accordion(root)
SynNode s1  = layout.section(acc, "Details", true)   // open initially; returns the body
s1.label("shown when expanded")
SynNode s2  = layout.section(acc, "More", false)

tabs — a tab bar over a content stack

SynNode[] panes = layout.tabs(root, ["Overview", "Settings"])
panes[0].label("overview content")
panes[1].label("settings content")
SynNode dlg = layout.modal(root)          // built hidden; add content, then show it
dlg.label("Delete this item?")
dlg.button("Cancel", fn() { dlg.hide() })
root.button("Delete…", fn() { dlg.show() })

toast — a transient message

SynNode t = layout.toast(root, "Saved!")   // built hidden
root.button("Save", fn() { layout.showToast(t, 2.5) })  // flash for 2.5s, auto-hide

table — a fixed-height data table

SynNode t = layout.table(root, ["Name", "Age", "City"], 300)  // 300px tall
layout.tableRow(t, ["Ada", "36", "London"])
layout.tableRow(t, ["Alan", "41", "Bletchley"])

A thin wrapper over the built-in table: sortable headers, row selection, only visible rows drawn.

The layout components use theme colors (fillRole: "surface" for cards, popups and toasts), so they follow node.theme(...).


Quick reference

Namespace calls: syn.window · syn.run · syn.layout · syn.simulate · syn.rgb · syn.rgba · syn.linear · syn.radial · syn.px · syn.pct · syn.webview · syn.cancelAnimation · syn.setAnimationScale

Node builders: panel label richText button input textarea number checkbox select grid split

Components: divider spacer progress slider toggle radio tabs image

Data views: list table tree chart log · addRow addItem setExpanded setSeries append setCount refresh

Modifiers: .grow .fill .style .id .font .theme .setTheme .tooltip .menu .overlay .modal .ttl .hide .show .setVisible

Motion: .animate .stopAnimations · translateX translateY scale scaleX scaleY rotate originX originY · transitionMs transitionCurve transitionProps

Events: .onClick .onLink .onHover .onKey .onResize .onBack · syn.post

Platform signals: syn.systemAppearance syn.onAppearance syn.reduceMotion syn.onLifecycle syn.keepAwake · sys.haptic Gestures: .onLongPress .onDoubleTap .onPan .onPinch .onEdgeSwipe .onScroll · panAxis zoomable minScale maxScale dismissKeyboardOnDrag

Scrolling: .scrollTo .scrollToEnd .scrollOffset · stickToBottom

Tree: .clear .remove .add .insert .childCount .onClick · syn.every syn.after syn.cancel

State: .value .numberValue .checked .selected .visible · .layoutX .layoutY .layoutW .layoutH .token .role · .setValue .setNumber .setChecked .setSelected .setText .setSpans .setColor .title .close

Components (import { layout } from "stdlib"): list grid split accordion+section tabs modal toast+showToast table+tableRow

Styled components (syn-style package, Style): preset apply derive put · button card chip badge segmented listRow field sectionHeader toggleRow dialog · gradient withGradient glowCard · followSystem forAppearance · icon setIconFamily · motion reveal pulseDots blink · swipeRow swipeAction sheet drawer · typeStyle typeset text paragraph code link


Rendering backends

Every backend draws the same tree with the same layout; only the GPU API and, off Apple platforms, the glyph rasterizer change.

Platform Backend Text
macOS (default) Metal CoreText
macOS, RADLANG_SYN_BACKEND=gl at build time OpenGL 4.1 core CoreText (RADLANG_SYN_FONT=ttf at run time: the portable rasterizer)
iOS Metal CoreText
Android (runtime support; the target’s link step wires it) OpenGL ES 3.0 portable TrueType rasterizer over /system/fonts
RADLANG_SYN_BACKEND=gl radlang build app.rad -o app-gl   # links OpenGL instead of Metal
RADLANG_SYN_FONT=ttf ./app-gl                            # portable glyphs on a Mac

The OpenGL build exists to run and compare the Android/Linux render path on a Mac: layouts are identical to Metal (headless and real-window dumps), and pixels match up to macOS colour management (Metal output is colour-matched to the display, OpenGL output is not; up to ~10/255 per channel on saturated fills). On macOS and Linux, GL presents a frame every display refresh (a cached copy of the last drawing when nothing changed; a few percent of a core while idle), where Metal presents nothing while idle; Android skips idle presents like Metal.

The portable rasterizer reads TrueType and CFF/CFF2 outlines (.ttf, .otf, .ttc, including CID-keyed CJK fonts and variable CFF2 at their default instance) without hinting, picks the closest weight/italic face of a family, and synthesizes bold or oblique when a family has none. Family names match font file names ("DejaVu Sans" → DejaVuSans-*.ttf); syn’s macOS defaults map to the platform’s sans (Roboto on Android) and monospace faces. RADLANG_SYN_FONT_DIR adds a font directory and RADLANG_SYN_FONT_FILE forces one file. Compared with CoreText it renders slightly lighter stems and has no font-smoothing. backdropBlur renders on the GPU: the window drawn so far is snapshotted, downscaled and blurred, and glass nodes with the same radius that do not overlap anything drawn after the snapshot (a grid of glass cards, a header and a tab bar) share one snapshot; a modal over them takes a fresh one, so its backdrop includes the cards. Up to 8 snapshots per frame; frames without a blurred node take the direct path. Headless layout runs ignore it.

Emoji come from the system’s colour emoji font in colour: COLRv0/COLRv1 vector glyphs (Noto Color Emoji on Android 13+) or CBDT bitmap strikes (Noto Color Emoji on most Linux distributions); RADLANG_SYN_EMOJI_FONT picks another file (a <name>Flags.ttf beside it is used too, as Android keeps flags in NotoColorEmojiFlags.ttf). Symbols that a monochrome font has (★, ✓, ⚡ where available) draw in the text colour instead. CJK comes from Noto Sans CJK on Android and Linux. On Android, syn.image reads PNG anywhere and JPEG/WebP/GIF/HEIF on Android 11+, from files or the APK’s assets.

Android. The tree runs full-screen inside the system-bar / cutout safe area (the keyboard’s area too while it is up). A tap clicks, a swipe scrolls the region under it (with momentum after a flick), focusing a text field shows the on-screen keyboard (see On-screen keyboard), and Back closes a menu, dropdown or focus, then asks the app’s onBack handlers, then leaves the app. Input methods get the field’s text and type (single-line, multi-line, number), so suggestions, autocorrect, gesture typing, voice input and accented characters commit whole strings into the field (one change event each); text an input method is still composing (CJK and similar) is shown underlined and reported once committed, as on iOS. Code after syn.run never runs on Android.

Testing layouts headlessly

Set RADLANG_SYN_HEADLESS=WxH and syn.run lays the tree out at that size without opening a window, prints it as one SYN-LAYOUT {json} line (type, id, text, rect, widget state, scroll state per node) and returns. Add RADLANG_SYN_SCRIPT to drive input through the real event handling first, as ;-separated steps:

Step Effect
click:ID press and release at the node’s center (where it is drawn, when a transform moves it)
clickat:ID:FX:FY press and release at a fraction of the node’s box (0.5:0.5 = center; the drawn box when transformed)
link:ID:N press and release on the N-th (1-based) linked span of a rich label
scroll:ID:DY wheel over the node; DY px, positive scrolls content down
type:ID:TEXT focus the node and type TEXT
text:TEXT type TEXT into whatever has focus (no click)
key:NAME tab, enter, space, escape, arrows, home, end, backspace, delete, pageup, pagedown, any letter or digit; prefixes shift+ cmd+ alt+ ctrl+
down:X:Y move:X:Y up:X:Y raw pointer events at window coordinates
wheel:X:Y:DY wheel at a point; DY px
touch:X:Y one-finger tap at window coordinates, as a phone delivers it
swipe:X:Y:DX:DY one-finger drag from (X,Y) by (DX,DY), then lifted: scrolls the region under X,Y
touchdown:X:Y touchmove:X:Y touchup:X:Y one finger, step by step (hold with wait:MS between)
longpress:ID one finger held on the node’s center for 600 ms, then lifted
doubletap:ID two taps on the node’s center 100 ms apart
pan:X:Y:DX:DY[:MS] one-finger drag from (X,Y) by (DX,DY) over MS (default 200) in 10 moves on the virtual clock, then lifted (so onPan sees a velocity)
pinch:X:Y:SCALE two fingers 100 px apart around (X,Y) spread (or closed) to 100 × SCALE px, then lifted
edgeswipe:SIDE:DX one finger from 2 px inside the left or right edge, at half height, moved DX px inward over 200 ms
wait:MS advance time by MS in 16 ms frames (timers, animations, transitions and async work run)
back Android’s Back button: prints SYN-BACK handled or SYN-BACK leave
appearance:dark or appearance:light the system appearance changes: fires syn.onAppearance handlers
lifecycle:STATE active, inactive or background: fires syn.onLifecycle handlers
dump print the layout at this point (a final dump always follows)
RADLANG_SYN_HEADLESS=800x600 RADLANG_SYN_SCRIPT="type:name:Ada;click:save" ./app

Headless, syn.keepAwake prints SYN-KEEPAWAKE on|off and sys.haptic prints SYN-HAPTIC <kind>, so an app can be tested for them; RADLANG_SYN_APPEARANCE and RADLANG_SYN_REDUCE_MOTION set the platform signals (headless runs only).

A label laid out with spans, maxLines or letterSpacing always lists its lines (with … where cut); a rich label adds spans (the count), links, each linked span’s tag, drawn color ("RRGGBB") and rects ([x, y, w, h], one per line it is on), and chips, each span background as drawn: rect, color and radius, one per line the span is on.

RADLANG_SYN_DUMP_STYLE=1 adds each node’s resolved visuals to the dump as a style object: fill, border, borderWidth, radius, textColor, a part colour where the widget has one (track, indicator, mark), shadow (with x and spread when set), opacity, every colour role (roles) and every metric token (tokens), plus the paint keys a node sets: gradient, borderGradient and textGradient as parsed layers ({"kind": "linear", "angle": 100, "stops": [["285C99", 0], ...]} or {"kind": "radial", "cx", "cy", "rx", "ry", "stops"}), radii (the four corners as drawn, after scaling), fadeEdges (axis, start, end) and, for a ring, progress (kind, strokeWidth); and transform (translateX / translateY with their unit, "px" or "pct", scaleX, scaleY, rotate, originX, originY) when the node sets one and animations (how many run on it) while any do. Values are the current, interpolated ones. Colours are "RRGGBB", "RRGGBB/a" when translucent, or null. Without the variable the dump is unchanged.

A node drawn somewhere other than its layout box (by its own or an ancestor’s transform) also gets a vrect (x, y, w, h): the box as drawn, its bounding box when rotated. Its x / y / w / h stay the layout box.

From radlang (library tests under rtest), syn.layout(win, w, h) runs one headless layout pass without opening a window; then node.layoutX(), layoutY(), layoutW(), layoutH() give the node’s box, node.token(name) a resolved metric token and node.role(name) a resolved colour role (-1 when unset). syn.simulate(win, w, h, steps) runs script steps (the table above, the same ;-separated string) against the tree at w x h, with a layout pass before each step, and leaves the tree in the state they produce; the virtual clock starts at the first call, so wait:MS and the gesture steps are deterministic. It is for tests: from then on syn runs on that virtual clock, so do not call it in a running app. The syn-style gesture components are tested that way (libraries/syn-style/test/gestures.test.rad).

RADLANG_SYN_DUMP_FRAME=N prints the same SYN-LAYOUT line from a real window at frame N, to compare on-screen layout with a headless run.

RADLANG_SYN_FPS=1 makes a real window print, once a second, SYN-FPS frames=N drawn=M animations=K idle=0|1: frame callbacks, frames actually drawn, animations running and whether the idle pace is on. While an animation runs drawn follows the display rate; after it ends the window drops to the idle pace (frames about 30, drawn about 1 on Metal, macOS GL and Android; Linux GL keeps the display’s rate).

RADLANG_SYN_ATLAS_PNG=path writes the glyph atlas (every character the tree shows, rasterized) to a PNG — after the 30th frame in a window, or at the end of a headless run — to check text rendering without a screenshot.

Text is Unicode: glyphs are rasterized on demand into a shared atlas, and characters the node’s font lacks (CJK, symbols) come from a system fallback font. Emoji sequences are shaped as one glyph on every platform: flags (🇯🇵), keycaps (1️⃣), ZWJ sequences (👨‍👩‍👧, 🏳️‍🌈), skin tones (👍🏽) and tag flags, through CoreText on Apple and the emoji font’s ligatures elsewhere. A sequence, or a letter with combining marks, is one character for editing: the caret steps over it, Backspace and Delete remove all of it, a click never lands inside it and lines never break inside it. A sequence the emoji font has no glyph for draws as its parts (joiners and modifiers invisible). Other text is not shaped: no kerning, ligatures or right-to-left scripts. The atlas PNG shows colour glyphs in colour.

The repository’s syn regression tests (tests/integration/gui/syn-*.py) use this through tests/integration/gui/syn_harness.py; SYN_LAYOUT_LOG=file makes the harness append every raw SYN-LAYOUT line to file, to compare two builds byte for byte. syn-style-tokens.py sets every token and role through the theme and through style keys.