widgets
@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.Scrollable | ui.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, Both | ui.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_h | the 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_MAX | ui.clamp_scroll, … (widgets.WHEEL_STEP stays) |
It draws the same scrollbar and scrolls the same way.
Layout
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"; } }
}
}
}
}| Widget | Props | |
|---|---|---|
Top, Bottom | h | The first (last) child h high, the other the rest |
Left, Right | w | The first (last) child w wide, the other the rest |
Inset | all, top, left, right, bottom | Margins around its children |
Rows, Cols | gap | Equal shares |
Stack | gap, pad, each | Top to bottom at their own heights (each for one that has none) |
Sized | h, w | A child of a fixed size |
Overlay | Children on top of each other: content with a Dialog over it | |
Space | Room 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
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; }| Widget | Props | Events |
|---|---|---|
Label | text, font (BODY, SMALL, LABEL, CAPTION, TITLE, DISPLAY, MONO, VALUE, DETAIL), size (pixels, instead of font), fg, alpha, align (LEFT, CENTER, RIGHT_ALIGN), pad (8) | |
Caps | text, alpha, pad | |
Paragraph | text, font, size, fg, alpha, align, line_h | |
Badge | text, tone (widgets.Tone.Plain, Ok, Warn, Err), accent | |
TextInput | value, controlled, placeholder, initial, password, disabled, error, label, bg, fg, border_color, text_size, radius, paste_other; states hovered, focused | on_change(value: []const u8), on_submit(value: []const u8), on_paste_other(ev: ui.Paste) |
Editor | text, titled, line_h, placeholder, editable, label, paste_other; state focused | on_change(value: []const u8), on_paste_other(ev: ui.Paste) |
- Over a
TextInputor anEditorthe pointer shows the text cursor (the arrow over a disabled field and anEditor’s scrollbar):ui.cursored. - A
TextInputtakes 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 fireson_submit, Escape gives the focus up. The text scrolls sideways to keep the caret in view; apasswordfield is never copied. radiusrounds aTextInput’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’splaceholdershows while the field is empty, in a soft version of the text colour: the theme’s ink whilefgis unset,fgwhen 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
valueprop is the text to show. Bound to avarwhose generated setteron_changecalls, the field is controlled:widgets.TextInput { value: query; on_change: set_query; }keepsqueryand the field in step. Whenvaluechanges from outside (code assignsquery), 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_changegets"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
valueonly 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 settingvalueto 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: truemakes the field always show the value you hold. After each edit it callson_changewith the edited text, then shows whatevervalueis 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 (inon_changeoron_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:
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
valuemust be something the view reads again afteron_change: avarof the component whose view holds the field (asdraftabove), or a module variable your handler follows withui.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. Leavevalueout and the field keeps its own text (starting frominitial), andon_changeonly reports. - An
Editordraws thetextyou give it, so it always shows what you hold: ifon_changekeeps the old text, its caret and selection go back too. - An
Editorholds 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_othertakes theui.ClipKindbits your program handles (Picture,Files). Then, when the clipboard holds one of those kinds, Ctrl+V fireson_paste_otherwith theui.Pasteand 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: thePaste’s text, picture and paths are valid only during the call.
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
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]; }| Widget | Props | Events |
|---|---|---|
Button | label, variant (Default, Accent, Destructive, Ghost), enabled, bg (set: a colored button in that color), fg, border, text_size; states hovered, active, disabled | on_click() |
IconButton | icon (an SVG path in a 14-unit box), label, disabled, accent, filled; states hovered, active | on_click() |
Checkbox | checked, label, disabled, text_color, check_color, text_size; states hovered, active | on_toggle(new_checked: bool) |
Toggle | checked, label, disabled; states hovered, active | on_change(checked: bool) |
RadioGroup | items: []const string, selected, vertical, disabled | on_change(index: i64) |
Slider | min_val, max_val, value, step, disabled, label, bg, track_color, thumb_color; states hovered, active | on_change(new_value: i64) |
ProgressBar | value, max_value (default 100), label, bg, fill_color | |
Tabs, Segmented | items ("a|b"), selected | on_select(index: i64) |
Toolbar | items ("-" a separator), active, disabled, search | on_item(index: i64) |
Statusbar | cells: []const widgets.Status (text, tone) |
- A
Buttonfireson_clickwhen pressed and released inside it, and on Return or Space once it has the focus. An item ofTabs,Segmented, aToolbaror a list is clicked when it is pressed and released on. Checkbox,Toggle,RadioGroupandSliderreport 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 (bystep, a twentieth of the range when 0), Home and End to the ends.
Lists
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; }| Widget | Props | Events |
|---|---|---|
List | items ("title\tdetail|..."), selected, lead | on_select(index: i64) |
Sidebar | items: []const widgets.SideItem (label, icon, meta, badge, header, tint, disabled), selected | on_select(index: i64) |
Breadcrumb | segments: []const string, icon, boxed | on_select(index: i64) |
ItemGrid | items: []const widgets.GridItem (name, detail, icon, accent, picture), current, selected: []const bool, mode (Icons, Photos), tile | on_select(index, toggle, range), on_open(index: i64) |
Table | columns: []const widgets.TableColumn, cells: []const widgets.Cell, selected, sort, desc | on_select(index: i64), on_sort(column: i64) |
Metric | name, 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
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
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; }
}
}| Widget | Props | Events |
|---|---|---|
Pane | bg (the theme’s surface while unset), bordered | |
Panel | bg (transparent while unset), border | |
Divider | ||
Section | title, number, description | |
SettingRow | title, description, control (the width at the right for its child) | |
Empty | icon, title, message, action, variant | on_action() |
Dialog | title, message, buttons ("Cancel|OK"), accent, danger, cancel | on_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.
| Widget | State props |
|---|---|
Button | hovered_bg, hovered_fg, hovered_border, active_bg, active_fg, active_border (the ring while pressed), disabled_bg, disabled_fg, disabled_border |
TextInput | hovered_bg, hovered_fg, hovered_border_color, focused_bg, focused_fg, focused_border_color |
Checkbox | hovered_text_color, hovered_check_color, active_text_color, active_check_color |
Slider | hovered_bg, hovered_track_color, hovered_thumb_color, active_bg, active_track_color, active_thumb_color |
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):
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)addsstate hovered,state active, the eventname(with oneboolparameter namedargwhen 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 writefn off() -> bool.widgets.item_strip()addsvar hover,var pressed(an item’s index, -1 for none) andstrip_pointer(ev, here), which tracks them for a pointer event over itemhereand 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"])addsstyled()(any ofbg,fg,active_bg, … set),state_now()(the first of the states that is on, -1 for none) andbg_in(base, k),fg_in(base, k)(state k’s color when set, elsebase), and the<state>_<prop>props themselves (active_bg,hovered_fg, …,#00000000while 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:
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 SemiBolditalic 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: