widgets

tape
@profile(t2);
import ui from "ui";
import widgets from "widgets";

var volume: i64 = 50;
fn on_save() { }
fn on_volume(v: i64) { volume = v; }

component Settings {
    view {
        widgets.Pane {
            ui.Column { padding: 12; gap: 8;
                widgets.Label { text: "Volume"; grow: 0; }
                widgets.Slider { min_val: 0; max_val: 100; value: 50; on_change: on_volume; grow: 0; }
                widgets.Button { label: "Save"; variant: widgets.Variant.Accent; on_click: on_save; grow: 0; }
            }
        }
    }
}

The widgets draw themselves with look, in the colors of the active theme and in Noto Sans, which the module carries: the same pixels on Windows, Linux and macOS, in a window or headless.

Every widget follows one rule: props in, events out. You keep the data in your component’s vars and pass it down; a widget reports what the user did (a click, a new value, an index) and keeps nothing of yours. A Checkbox asks for the opposite of checked; you store it and pass it back.

Every prop has a default: leave a color at its zero value (#00000000), or a size at 0, and the widget paints it with the active theme, which theme.set can switch while the program runs. To set props for many widgets at once, write a #style rule. Every widget also takes width, height and grow, its size in a ui.Column or ui.Row (Column and Row); with grow: 0 it takes its own size (a Button its label’s and 30 pixels, a Label its text’s).

A view that scrolls is ui.ScrollArea, the one scroll container: widgets.Scrollable was merged into it. A program that used widgets.Scrollable writes ui.ScrollArea with the same props:

widgets.Scrollableui.ScrollArea
direction: widgets.ScrollDir.Vertical (the default)direction: ui.ScrollDir.Vertical, or nothing: the default Both scrolls sideways only when content_w is wider than the view
direction: widgets.ScrollDir.Horizontal, Bothui.ScrollDir.Horizontal, Both
content_h (used when the child measures nothing)content_h (the content’s height whenever it is set: leave it out for a child that measures itself)
content_w, reveal, reveal_hthe same
event on_scroll(offset), scroll_to(sx, sy)the same
widgets.clamp_scroll, thumb_of, Thumb, THUMB_MIN, drag_scroll, reveal_scroll, wheel_steps, clip_within, MEASURE_MAXui.clamp_scroll, … (widgets.WHEEL_STEP stays)

It draws the same scrollbar and scrolls the same way.

Layout

tape
widgets.Left { w: 200;                     // a pane 200 wide, the rest beside it
    widgets.Sidebar { items: places[0..4]; selected: here; on_select: go; }
    widgets.Top { h: 38;                   // a bar 38 high, the rest under it
        widgets.Toolbar { items: "New|Open|-|Share"; on_item: tool; }
        ui.ScrollArea {
            widgets.Stack { gap: 8; pad: 12;   // children at their own heights
                widgets.Paragraph { text: intro; }
                widgets.Sized { h: 30; widgets.TextInput { placeholder: "Name"; } }
            }
        }
    }
}
WidgetProps
Top, BottomhThe first (last) child h high, the other the rest
Left, RightwThe first (last) child w wide, the other the rest
Insetall, top, left, right, bottomMargins around its children
Rows, ColsgapEqual shares
Stackgap, pad, eachTop to bottom at their own heights (each for one that has none)
Sizedh, wA child of a fixed size
OverlayChildren on top of each other: content with a Dialog over it
SpaceRoom that draws nothing

A Stack, a Paragraph and a Section know their height, so in a ui.ScrollArea they set how far it scrolls. For rows of fixed and flexible parts, ui.Row and ui.Column take sizes.

Text

tape
widgets.Label { text: "Inbox"; font: widgets.TITLE; }
widgets.Caps { text: "Recent"; }
widgets.Paragraph { text: long_text; align: widgets.CENTER; }
widgets.Badge { text: "Beta"; accent: true; }
widgets.TextInput { value: query; placeholder: "Search"; on_change: set_query; on_submit: search; }
widgets.TextInput { placeholder: "Passphrase"; password: true; on_change: set_secret; }
widgets.TextInput { value: msg; placeholder: "Message"; radius: 99; on_change: set_msg; }   // a pill
widgets.Editor { text: note; titled: true; on_change: set_note; }
WidgetPropsEvents
Labeltext, font (BODY, SMALL, LABEL, CAPTION, TITLE, DISPLAY, MONO, VALUE, DETAIL), size (pixels, instead of font), fg, alpha, align (LEFT, CENTER, RIGHT_ALIGN), pad (8)
Capstext, alpha, pad
Paragraphtext, font, size, fg, alpha, align, line_h
Badgetext, tone (widgets.Tone.Plain, Ok, Warn, Err), accent
TextInputvalue, controlled, placeholder, initial, password, disabled, error, label, bg, fg, border_color, text_size, radius, paste_other; states hovered, focusedon_change(value: []const u8), on_submit(value: []const u8), on_paste_other(ev: ui.Paste)
Editortext, titled, line_h, placeholder, editable, label, paste_other; state focusedon_change(value: []const u8), on_paste_other(ev: ui.Paste)
  • Over a TextInput or an Editor the pointer shows the text cursor (the arrow over a disabled field and an Editor’s scrollbar): ui.cursored.
  • A TextInput takes the focus when clicked or tabbed to. Typing inserts at the caret (any character, as UTF-8), replacing a selection; the arrows, Home and End move the caret (Ctrl by words, Shift selects), Backspace and Delete erase (Ctrl a word; an emoji sequence or a letter with its accents is one character to them and to the arrows), Ctrl+A selects all, Ctrl+C, Ctrl+X and Ctrl+V copy, cut and paste (a paste is one line: line breaks become spaces), Return fires on_submit, Escape gives the focus up. The text scrolls sideways to keep the caret in view; a password field is never copied.
  • radius rounds a TextInput’s corners, in pixels (0: square). It is held to half the field’s height, so a large one (radius: 99) makes a pill. The border, the focus ring, the error ring and the text’s clip all follow the rounded shape.
  • A TextInput’s placeholder shows while the field is empty, in a soft version of the text colour: the theme’s ink while fg is unset, fg when it is set. A dark field with light text (bg: #1C1C1E; fg: #FFFFFF;) gets a light grey placeholder, not the theme’s dark one.
  • The text an event hands over is valid during the handler: copy it ("{value}") to keep it.
  • Its value prop is the text to show. Bound to a var whose generated setter on_change calls, the field is controlled: widgets.TextInput { value: query; on_change: set_query; } keeps query and the field in step. When value changes from outside (code assigns query), the field adopts the new text and keeps the caret, clamped to the new length. Inside the component, text() is the text being edited.
  • A handler may store something other than the text it was given: a formatter that puts dashes in a code (on_change gets "48210", you store "4821-0"). The field shows your text with the caret as far from the end as it was in the edited text (moved back to the start of a character if it falls inside one), so typing goes on after what was typed: the next digit makes "4821-03". Any selection collapses to the caret. This holds whether or not the field is controlled; a value that changes at any other time keeps the caret clamped, as above.
  • A field adopts value only when it differs from the value it was last given: otherwise it keeps its own text. So a handler that doesn’t store an edit can’t undo it, and setting value to what the field last got doesn’t reach it. Clearing a field bound to a variable whose binding is never re-read (it was "" when the field last saw it) leaves the typed text there. For those, make the field controlled.
  • controlled: true makes the field always show the value you hold. After each edit it calls on_change with the edited text, then shows whatever value is once the handler returns: the new text if the handler stored it, the old text if it kept the old one, nothing if it cleared it (in on_change or on_submit). So a handler can refuse an edit by not storing it, and the field goes back to the text, caret and selection it had before the edit (a value the handler changes, say to upper case or with dashes, shows instead, the caret as far from the end as in the edited text). A formatter’s field is best controlled: Backspace over a dash the formatter puts back then shows the text and caret as they were (the handler decides the text), where a field that isn’t controlled keeps the edited text, the value having not changed:
tape
fn set_draft(v: []const u8) {
    if (looks_like_recovery_code(v)) { return; }   // refused: the field shows draft again
    draft = "{v}";
}
fn send(v: []const u8) { post(v); draft = ""; }    // the field is emptied

widgets.TextInput { value: draft; controlled: true; on_change: set_draft; on_submit: send; }
  • A controlled field’s value must be something the view reads again after on_change: a var of the component whose view holds the field (as draft above), or a module variable your handler follows with ui.invalidate. A module variable isn’t followed otherwise, so a controlled field bound to one keeps showing the variable’s old value and its edits are undone. Leave value out and the field keeps its own text (starting from initial), and on_change only reports.
  • An Editor draws the text you give it, so it always shows what you hold: if on_change keeps the old text, its caret and selection go back too.
  • An Editor holds lines: Up, Down, Page Up and Page Down move by the wrapped lines, Return breaks a line, the wheel and its scrollbar scroll it and the view follows the caret.
  • A field pastes text only, unless you ask for more: paste_other takes the ui.ClipKind bits your program handles (Picture, Files). Then, when the clipboard holds one of those kinds, Ctrl+V fires on_paste_other with the ui.Paste and inserts no text, even if the clipboard has text too (files copied in a file manager come with their paths as text, and you want the file, not its path typed into the message). A clipboard with only text pastes it as usual. Copy what you keep before the handler returns: the Paste’s text, picture and paths are valid only during the call.
tape
fn attach(ev: ui.Paste) {
    if (ev.has_picture) { add_picture("{ev.picture}"); }   // an image file's bytes: image.decode
    for (p in ev.paths) { add_file("{p}"); }
}

widgets.TextInput { value: msg; on_change: set_msg;
    paste_other: ui.ClipKind.Picture as i64 | ui.ClipKind.Files as i64; on_paste_other: attach; }

Controls

tape
widgets.Button { label: "Save"; variant: widgets.Variant.Accent; on_click: save; }
widgets.Button { label: "Delete"; variant: widgets.Variant.Destructive; enabled: has_selection; on_click: delete; }
widgets.IconButton { icon: "M3 7H11M7 3V11"; label: "Add"; on_click: add; }
widgets.Checkbox { checked: subscribed; label: "Subscribe"; on_toggle: set_subscribed; }
widgets.Toggle { checked: dark; on_change: set_dark; }
widgets.RadioGroup { items: sizes[0..3]; selected: size; on_change: set_size; }
widgets.Slider { min_val: 0; max_val: 100; value: volume; on_change: set_volume; }
widgets.ProgressBar { value: done; max_value: total; label: "Copying"; }
widgets.Tabs { items: "General|Advanced"; selected: tab; on_select: set_tab; }
widgets.Segmented { items: "Day|Week|Month"; selected: range; on_select: set_range; }
widgets.Statusbar { cells: cells[0..2]; }
WidgetPropsEvents
Buttonlabel, variant (Default, Accent, Destructive, Ghost), enabled, bg (set: a colored button in that color), fg, border, text_size; states hovered, active, disabledon_click()
IconButtonicon (an SVG path in a 14-unit box), label, disabled, accent, filled; states hovered, activeon_click()
Checkboxchecked, label, disabled, text_color, check_color, text_size; states hovered, activeon_toggle(new_checked: bool)
Togglechecked, label, disabled; states hovered, activeon_change(checked: bool)
RadioGroupitems: []const string, selected, vertical, disabledon_change(index: i64)
Slidermin_val, max_val, value, step, disabled, label, bg, track_color, thumb_color; states hovered, activeon_change(new_value: i64)
ProgressBarvalue, max_value (default 100), label, bg, fill_color
Tabs, Segmenteditems ("a|b"), selectedon_select(index: i64)
Toolbaritems ("-" a separator), active, disabled, searchon_item(index: i64)
Statusbarcells: []const widgets.Status (text, tone)
  • A Button fires on_click when pressed and released inside it, and on Return or Space once it has the focus. An item of Tabs, Segmented, a Toolbar or a list is clicked when it is pressed and released on.
  • Checkbox, Toggle, RadioGroup and Slider report what the user asked for and leave the value to you: store it and pass it back as the prop. Once focused, Space or Return toggles; the arrows move a radio group and a slider (by step, a twentieth of the range when 0), Home and End to the ends.

Lists

tape
widgets.List { items: "Inbox\t12 unread|Archive\tnothing new"; selected: box; on_select: open_box; }
widgets.Sidebar { items: places[0..5]; selected: place; on_select: go; }
widgets.Breadcrumb { segments: path[0..3]; on_select: up_to; }
widgets.ItemGrid { items: files[0..n]; current: at; on_select: pick; on_open: open; }
widgets.Table { columns: cols[0..3]; cells: cells[0..30]; selected: row; sort: by; on_select: select_row; on_sort: sort_by; }
WidgetPropsEvents
Listitems ("title\tdetail|..."), selected, leadon_select(index: i64)
Sidebaritems: []const widgets.SideItem (label, icon, meta, badge, header, tint, disabled), selectedon_select(index: i64)
Breadcrumbsegments: []const string, icon, boxedon_select(index: i64)
ItemGriditems: []const widgets.GridItem (name, detail, icon, accent, picture), current, selected: []const bool, mode (Icons, Photos), tileon_select(index, toggle, range), on_open(index: i64)
Tablecolumns: []const widgets.TableColumn, cells: []const widgets.Cell, selected, sort, descon_select(index: i64), on_sort(column: i64)
Metricname, card: widgets.Card, rgb

The lists scroll when they don’t fit and keep the selection in view; once focused, the arrows, Home, End and Page Up and Down move it. In an ItemGrid Shift extends a range and Ctrl (Command) toggles, widgets.apply_pick turns its on_select into your flags, and a double click or Return fires on_open.

Pictures

tape
let photo: gfx.Surface = image.decode(bytes) or { return 1; };
widgets.Image { picture: widgets.picture_of(&photo); fit: widgets.Fit.Cover; }
widgets.Image { src: &logo; }                 // a surface at its own size, top-left
widgets.PhotoView { picture: big; prev: at > 0; next: at < last; on_prev: back; on_next: forth; on_close: close; }

A Picture is your pixels (picture_of wraps a gfx.Surface); keep them alive while it is shown. Image scales it once into its bounds (Contain, or Cover to fill) and keeps the result until the picture or the size change. PhotoView shows one large on a dark ground with step buttons at its sides, Left and Right to step, Escape to close.

Pages and dialogs

tape
widgets.Section { number: "A.1"; title: "Appearance"; description: "How the windows look.";
    widgets.SettingRow { title: "Dark theme"; control: 34;
        widgets.Toggle { checked: dark; on_change: set_dark; }
    }
}
widgets.Empty { title: "No notes"; message: "Notes you write appear here."; action: "New note"; on_action: new_note; }
widgets.Overlay {
    content;
    if (asking) {
        widgets.Dialog { title: "Delete note"; message: "This cannot be undone.";
                         buttons: "Cancel|Delete"; danger: 1; cancel: 0; on_choose: answered; }
    }
}
WidgetPropsEvents
Panebg (the theme’s surface while unset), bordered
Panelbg (transparent while unset), border
Divider
Sectiontitle, number, description
SettingRowtitle, description, control (the width at the right for its child)
Emptyicon, title, message, action, varianton_action()
Dialogtitle, message, buttons ("Cancel|OK"), accent, danger, cancelon_choose(index: i64)

A Dialog in an Overlay covers the window: nothing behind it takes a click. It takes the keyboard focus when it appears: Escape chooses cancel, Return the marked button or accent, Left and Right mark one.

The look of a state

Each color prop of a widget with states has a variant per state, named <state>_<prop>: the color while that state is on. Left at zero, the theme’s look for that state is used.

WidgetState props
Buttonhovered_bg, hovered_fg, hovered_border, active_bg, active_fg, active_border (the ring while pressed), disabled_bg, disabled_fg, disabled_border
TextInputhovered_bg, hovered_fg, hovered_border_color, focused_bg, focused_fg, focused_border_color
Checkboxhovered_text_color, hovered_check_color, active_text_color, active_check_color
Sliderhovered_bg, hovered_track_color, hovered_thumb_color, active_bg, active_track_color, active_thumb_color
tape
widgets.Button { label: "Delete"; bg: #B03030; hovered_bg: #C04040; active_bg: #902020; }

A color you give shows exactly as given: the widget paints flat in your colors instead of the theme’s look.

With transition: 150 (milliseconds) a widget fades to a state’s colors instead of switching, along transition_ease (widget transitions). When the user has asked the system for less motion (ui.reduce_motion()), the colors switch at once instead.

When two states are on, the stronger one shows: disabled over active (pressed) over hovered, and focused over hovered. In a #style rule the same is written :hovered { bg: #C04040; }.

Behaviour for your own components

The widgets get their press, hover and state-color code from generators your components can call too (@tape in a component’s body adds members to it, metaprogramming):

tape
import gfx from "gfx";
import ui from "ui";
import widgets from "widgets";

component Chip {
    @tape { ui.drawable(); ui.interactive(); widgets.pressable("on_pick", ""); }
    prop disabled: bool = false;
    fn off() -> bool { return disabled; }      // pressable asks it: no input while true
    fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64) {
        var bg: color = #E0E4EA;
        if (active) { bg = #C0C8D4; } else if (hovered) { bg = #D0D6E0; }
        s.fill_rect(x, y, w, h, bg);
    }
}
  • widgets.pressable(name, arg) adds state hovered, state active, the event name (with one bool parameter named arg when it is not empty, fired with !checked), and the pointer and key handlers: a press and a release on it, or Return or Space once focused, fire the event. You write fn off() -> bool.
  • widgets.item_strip() adds var hover, var pressed (an item’s index, -1 for none) and strip_pointer(ev, here), which tracks them for a pointer event over item here and returns the item clicked, else -1: fn handle_pointer(ev: *ui.PointerEvent) { let i = strip_pointer(ev, item_at(ev.x, ev.y)); if (i >= 0) { fire on_select(i); } }.
  • widgets.state_colors(["active", "hovered"], ["bg", "fg"]) adds styled() (any of bg, fg, active_bg, … set), state_now() (the first of the states that is on, -1 for none) and bg_in(base, k), fg_in(base, k) (state k’s color when set, else base), and the <state>_<prop> props themselves (active_bg, hovered_fg, …, #00000000 while unset).

Fonts

The widgets’ text is Noto Sans (Regular and SemiBold, Latin script) on a type scale: widgets.BODY (13 pixels), SMALL, LABEL, CAPTION, TITLE, DISPLAY, MONO, VALUE, DETAIL, TERM; MONO and TERM are Noto Sans Mono, so a column of digits or a terminal lines up. To draw text on a surface of your own in the same faces, widgets.ctx(widgets.BODY) is a text context, and widgets.face(px, bold, italic, mono) one at any size and style:

tape
let body = widgets.face(14, false);                 // Noto Sans Regular
let em = widgets.face(14, false, true);             // Noto Sans Italic
let strong_em = widgets.face(14, true, true);       // SemiBold Italic
let code = widgets.face(14, false, false, true);    // Noto Sans Mono
let code_bold = widgets.face(14, true, false, true); // Noto Sans Mono SemiBold

italic and mono default to false; mono has no italic, so both give the upright mono. A context face hands out stays that face and size for the program’s life, however many others are asked for later. Each distinct one costs its own glyph cache, about 124 KB (a 64 KB atlas, a 16 KB glyph table, an emoji cache and the contexts), kept until the program ends; a program that animates through many sizes (a zoom) should make a text.Context of its own with text.init and set it to each size instead.

The fonts are about 50 KB each, and a program carries only the ones it can draw with: regular and semibold always; the italics and the mono semibold only when some call of face asks for them (a call that leaves italic false everywhere keeps the italics out of the program); the mono when a call of face asks for it, or when the program uses the widgets’ text or widgets.ctx, which choose a face of the scale at run time.

To use other fonts, hand their bytes to widgets.use_fonts(regular, semibold, mono, italic, semibold_italic, mono_bold) before the first frame; the last three may be left out. Your family is never mixed with Noto: a face you leave empty falls back within it, mono to your regular, italic to your regular, semibold_italic to your semibold, and mono_bold to your mono (your semibold when mono is empty too).

Emoji come from the platform’s colour emoji font, found at the first frame: Segoe UI Emoji on Windows, Apple Color Emoji on macOS, Noto Color Emoji on Linux (where distributions install it, else under the font directories). Every label, paragraph and field shows them without anything from you, in colour, with ZWJ sequences, skin tones, flags and keycaps as one emoji (Segoe UI Emoji has no flags: Windows shows their two letters). Code points Noto Sans lacks that the emoji font has (☺, ↔) come from it too. widgets.has_emoji() says whether a font was found; widgets.use_emoji_font(bytes) (or use_emoji_file(path)) uses another colour font, "" the platform’s again. Emoji look as each platform draws them, so text with emoji is the one thing that differs between platforms.

Test a form without a window with ui.headless; stdlib/examples/widgets.tape drives a settings window that way.

Last modified: