Selkie::UI
NAME
Selkie::UI
TITLE
UI Builder Abstractions for Selkie
NOTE
This module is under active development. API may change.
SYNOPSIS
use Selkie::UI;
App {
Screen :name<main>, {
VBox {
Button.label: "Click me"
}
}
}DESCRIPTION
Selkie::UI provides a Raku-native DSL for building terminal user interfaces using the Selkie framework. Unlike traditional imperative UI code where you manually manage rendering and event loops, this module offers a declarative approach ā your code describes what the UI should look like and do, not how to achieve it step-by-step.
Widgets are declared hierarchically using block syntax, with properties and handlers specified via chained method calls. This makes UI definitions intuitive, compositional, and easy to reason about ā whether you are building simple tools or complex applications.
The DSL handles the glue between your declarative definitions and Selkie's imperative runtime, including state management with automatic UI updates when reactive variables change.
Dynamic Variables
Builder context flows through dynamic variables. These are set by App, Screen, and layout containers, and are only available within their blocks:
$*UI-APPā The running application object (store, rendering, event loop)$*UI-PARENTā The parent builder for tree hierarchy@*UI-PATHSā Tracks state paths read during block evaluation (for auto-subscribe)@*UI-NODESā Stack of child nodes being constructed$*UI-IDā Unique string per auto-subscribe chain for event deduplication
State Management
new-state
new-state($default, :$name, :$event) creates a reactive scalar state variable that automatically dispatches updates and re-renders affected UI elements. Returns a Proxy where reads track the state path in @*UI-PATHS and writes dispatch events through the store. Use for scalar values (Str, Int, Bool).
my $counter := new-state 0;
$counter = 42;new-array-state
new-array-state(@default, :$name, :$event) returns a ReactiveArray object that implements Positional and Iterable. Bind with := to an @-sigiled variable. Mutation methods (ASSIGN-POS, push, pop, shift, unshift, splice) dispatch fresh values to the store.
For nested mutations, use the extract-modify-reassign pattern:
my @tasks := new-array-state [{:title<A>,:!done},{:title<B>,:!done}];
my %task = @tasks[0];
%task<done> = True;
@tasks[0] = %task; # ASSIGN-POS dispatches fresh Arraynew-hash-state
new-hash-state(%default, :$name, :$event) returns a ReactiveHash object that implements Associative and Iterable. Bind with := to a %-sigiled variable. Mutation methods (ASSIGN-KEY, DELETE-KEY) dispatch fresh values to the store.
my %config := new-hash-state {:theme<dark>, :refresh(30)};
%config<theme> = 'light'; # ASSIGN-KEY dispatches fresh HashBlock-Based Setters
Many builder methods accept a block instead of a literal value. When a block is provided, the builder:
Evaluates the block once to get the initial value
Tracks any
new-statevariables read inside the block via@*UI-PATHSSubscribes to those state paths so the setter re-runs when states change
Updates the widget with the new value automatically
Example:
my $counter := new-state 0;
Text.text: { "Count: $counter" };These reactive setters require an active App because auto-subscribe uses $*UI-APP and the store.
Builder Lifecycle
TWEAKfires on construction, pushing the builder onto@*UI-NODESfor parent captureParent iterates
@*UI-NODESafter the block to collect childrenChained method calls configure the underlying
.objwidgetBlock-valued setters trigger auto-subscribe for reactive updates
When building outside an App (e.g., in tests), use Detached to set up @*UI-NODES:
my $stream = Detached { TextStream };Builders
The module exports builder functions for Selkie primitives. Each builder returns a chainable builder object that wraps the underlying widget.
Layout and Containers
Appā Application entry point that initializes the UI and starts the event loopScreenā Named screens that can be switched betweenTabā Named screen for use insideTabBar(creates a Screen)VBox,HBox,Splitā Layout containers for stacking or splitting widgetsBorder,Modal,ScrollViewā Container and decorator widgetsCardListā Scrollable list of variable-height widgets
Inputs and Selection
Buttonā Clickable button with label and press handlerTextInput,MultiLineInputā Text input fields with submit handlingCheckbox,RadioGroup,Selectā Selection controlsProgressBarā Progress indicator
Text and Lists
Text,TextStream,RichTextā Text display widgetsListView,Table,TabBarā List and table widgetsImage,Spinner,Toastā Media and status widgets
Overlays and Helpers
ConfirmModalā Confirmation modal builderCommandPaletteā Fuzzy command launcherFileBrowserā File picker modalHelpOverlayā Contextual keybind helpPasswordStrengthā Password strength meter
Charts
Plot,BarChart,LineChart,ScatterPlotā Chart widgetsSparkline,Heatmap,Histogramā Inline and grid chartsAxis,Legendā Chart adornments
Helpers
App helpers that interact with the runtime:
Handlerā Register a store event handlerDetachedā Create isolated UI nodes without parent attachmentOnKeyā Register global key handlersOnFrameā Register a per-frame callbackDispatchā Dispatch events to the storeTickā Tick the store immediatelyShowModalā Open a modal dialogCloseModalā Close the currently open modalFocusā Focus a specific widget (returns the widget for chaining)FocusNextā Move focus to the next widgetFocusPreviousā Move focus to the previous widgetSwitchScreenā Switch to a named screenQuitā Quit the applicationToastā Show a transient toast message
Playground
There is a built-in playground to live-edit/test Selkie::UI code:
raku -I lib bin/selkie-ui-playground.rakuExamples
Text input with reactive display
This example creates a text input field that echoes user input to a text stream above it.
The program creates a reactive string variable with new-state, places a vertical box layout on screen, adds a text stream widget to display messages, and adds a text input widget. When the user types and presses Enter, the input text is stored in the reactive variable, which automatically updates the text stream, and the input field is cleared for the next entry.
use Selkie::UI;
App {
my $next-msg := new-state Str;
VBox {
TextStream.append: { $next-msg };
TextInput(:placeholder('Type here...')).size(1).on-submit: -> $input, $text {
$next-msg = $text;
$input.clear
}
}
}The App block is the entry point that initializes the application. The new-state function creates a reactive state variable bound with :=, initialized as an empty string. The VBox widget arranges its children vertically from top to bottom. TextStream.append with a block argument reactively displays the value of $next-msg and updates whenever it changes. TextInput creates a single-line text input with a placeholder hint. .size(1) constrains the input to a fixed height of one row. .on-submit registers a handler that runs when the user presses Enter. The handler receives the input widget and the submitted text, stores the text in the reactive variable, and clears the input for the next entry.
Button with reactive state
This example shows a button whose label changes based on a numeric state variable.
The program creates a reactive integer counter, places it in a vertical box, and displays a button. The button label is computed from the counter value using a block ā when the counter changes, the label automatically re-renders. Each button press increments the counter, updating both the counter value and the button label.
use Selkie::UI;
App {
my UInt $val := new-state 0;
VBox {
Button.label({ $val ?? "BLE $val" !! "BLA $val" })
.on-press: { ++$val }
}
}ListView with reactive items
This example binds a list view to a reactive array. When the array changes, the list updates automatically.
use Selkie::UI;
App {
my $items := new-state <One Two Three>;
VBox {
ListView.set-items: { $items };
Button.label('Refresh').on-press: {
$items = <One Two Three Four>
}
}
}TabBar with tabs
This example shows a TabBar with two tabs, each containing different content.
use Selkie::UI;
App {
Screen :name<main>, {
TabBar {
Tab { Text(:text('Dashboard')) }: :name<dash>, :label('Dashboard');
Tab { Text(:text('Settings')) }: :name<set>, :label('Settings');
Border # content area ā TabBar fills it with the active tab
}
}
}EXPORTS
App and Screen
App(&block, |c)
Application entry point that initializes the UI and starts the event loop.
The block receives the builder as $_ and runs inside the application context. All builder functions must be called inside an App block.
App {
Screen :name<main>, { VBox { Button.label: 'Hello' } }
}Screen(&block, Str :$name = "main", |c)
Named screens that can be switched between with SwitchScreen.
Screen :name<settings>, { VBox { Text(:text('Settings')) } }Screen(name = "main", |c)
Screen variant that accepts an existing widget node instead of a block.
my $node = Detached { VBox { Button.label: 'Ok' } };
Screen($node): :name<main>;Tab(&block, Str :label!, |c)
Named screen for use inside a TabBar. Returns a ScreenBuilder. The block receives the screen builder as $_.
Tab { Text(:text('Dashboard')) }: :name<dash>, :label('Dashboard');Layout Containers
VBox(&block, :style, |c)
Vertical box layout. Stacks children top-to-bottom.
VBox {
Button.label: 'Top';
Button.label: 'Bottom'
}HBox(&block, :style, |c)
Horizontal box layout. Stacks children left-to-right.
HBox {
Button.label: 'Left';
Button.label: 'Right'
}Split(&block?, :size, :$style, |c)
Split container. Divides space between children. Optional :$ratio sets the split proportion.
Split :ratio(0.3), {
Text(:text('Left'));
Text(:text('Right'))
}Inputs and Selection
Button(:size, :$style, |c)
Pressable button with label. Supports .on-press handler (idempotent).
Button.label('Click').on-press: { say 'clicked' }Methods:
.label(Str)/.label(&block)ā Set or reactively bind label text.on-press(&block)ā Register click handler (idempotent)
TextInput(:size, :$style, |c)
Single-line text input field.
TextInput(:placeholder('Name')).on-submit: -> $_, $text { say $text }Methods:
.text(Str)/.text(&block)ā Get/set text.text-silent(Str)ā Set text without triggering events.on-submit(&block)ā Submit handler (idempotent).on-change(&block)ā Change handler (idempotent).clear/.clear(&block)ā Clear input.mask(:$char!)ā Set mask character for password input
MultiLineInput(:max-lines, :style, |c)
Multi-line text input area.
MultiLineInput(:max-lines(5)).on-submit: -> $_, $text { say $text.lines }Checkbox(:size, :$style, |c)
Toggleable checkbox with label.
Checkbox(:label('Accept terms')).check(True).on-change: -> $, $checked { say $checked }Methods:
.label(Str)/.label(&block)ā Set or reactively bind label.check(Bool)/.check(&block)ā Set checked state.on-change(&block)ā Change handler (idempotent)
RadioGroup(:style, |c)
Group of radio buttons for exclusive selection.
RadioGroup.set-items: ['Option A', 'Option B']Select(:style, |c)
Dropdown-style selection widget.
Select.set-items: ['option-1', 'Option 2']PasswordStrength(:show-label, :style, |c)
Password input with strength meter visualization.
PasswordStrength(:input($input-builder), :show-label)Text and Rich Content
Text(&block?, :size, :$style, |c)
Static text display widget. The optional block variant supports reactive subscriptions when used inside App.
Text(:text('Hello world'));
Text.text: { "Count: $counter" } # reactive ā reruns when $counter changesMethods:
.text(Str)/.text(&block)ā Set or reactively bind text.text-silent(Str)ā Set text without triggering events
TextStream(:size, :$style, |c)
Scrollable text stream for streaming log-like content.
TextStream.append: 'log line';
TextStream.append: { $message } # reactive ā appends when $message changesMethods:
.append(Str)/.append(&block)ā Append text (block = reactive).clear(Bool)/.clear(&block)ā Clear the stream.max-lines(UInt)ā Limit visible lines
RichText(:truncated-bottom, :style, |c)
Rich text widget with styled spans.
RichText.content: ['plain', %(:text<styled>, :style{ :sgr<bold> })]Lists and Tables
ListView(&block?, :style, |c)
Scrollable list of items. Supports .set-items for reactive data.
ListView.set-items: ['A', 'B', 'C'];
ListView.set-items: { @items };Methods:
.set-items(@items)/.set-items(&block)ā Set list items.on-select(&block)ā Selection handler (idempotent).on-activate(&block)ā Activation handler (idempotent).on-key(Str $key, &block)ā Key handler (idempotent).cursorā Current cursor position
Table(&block?, :size, :$style, |c)
Tabular data display with column headers. Accepts columns as array of hashes with :name, :label, :sizing/:flex/:fixed, :sortable, :render, and :sort-key. The optional block sets row data reactively.
Table :columns[
%(:name<id>, :label('ID')),
%(:name<name>, :label('Name')),
], {
[{:id(1), :name('Alice')}, {:id(2), :name('Bob')}]
}Methods:
.add-column(:$name!, :$label!, ...)ā Add a column.rows(@rows)/.rows(&block)ā Set or reactively bind rows.clear-columnsā Remove all columns.on-select(&block)ā Selection handler (idempotent).on-activate(&block)ā Activation handler (idempotent).on-key(Str $key, &block)ā Key handler
CardList(&block?, :select-last, :style, |c)
Scrollable list of variable-height widget cards. Each item is a widget with a required height. Supports reactive data via block setters.
CardList { $.add-item(Text(:text('card')), :height(3)) }Methods:
.add-item($widget, :$height!, :$root, :$border)ā Add a card.set-items(@items)/.set-items(&block)ā Replace all items.clear-itemsā Remove all items.set-item-height(Int $idx, Int $height)ā Change item height.select-index(Int $idx)ā Select item by index.select-first(Bool)/.select-last(Bool)ā Select first/last.scroll-up/.scroll-downā Scroll by one item.on-select(&block)ā Selection handler (idempotent)
TabBar(&block?, :size, :$style, |c)
Tabbed navigation bar. Uses a declarative block-based API. The block must return a content container (e.g., Border) that provides .title and .content methods. Use Tab inside the block to define screens.
TabBar {
Tab { Text(:text('Dashboard')) }: :name<dash>, :label('Dashboard');
Tab { Text(:text('Settings')) }: :name<set>, :label('Settings');
Border # returned as the content area
}Methods:
.add-tab(:$name!, :$label!)ā Register a tab.remove-tab(Str $name)ā Remove a tab.clear-tabsā Remove all tabs.select-by-name(Str $name)ā Select tab by name.select-index(UInt $idx)ā Select tab by index.on-tab-selected(&block)ā Tab change handler (idempotent)
Overlays and Helpers
Border(&block?, :hide-top-border, :size, :$style, |c)
Bordered container with optional title. Supports reactive title via block.
Border :title('Section'), { Text(:text('Content')) }Modal(Selkie::UI::Base $widget)
Extracts the .modal widget from an existing builder. Useful with ShowModal.
ShowModal(Modal($my-builder)); # $my-builder.modalModal(&block?, :height-ratio, :size, :$style, |c)
Modal overlay dialog with configurable size and backdrop dimming.
Modal :width-ratio(0.6), :height-ratio(0.5), { Text(:text('Overlay')) }ConfirmModal(:message, :no-label, :height-ratio, :on-result, |c)
Confirmation dialog with accept/cancel buttons.
ConfirmModal :title('Confirm'), :message('Proceed?'), :on-result(-> $, $result { say $result })Toast(Str duration = 3e0)
Temporary toast notification dispatched via the app.
Toast('Saved!', :duration(2));HelpOverlay(:focused-widget, :style, |c)
Keyboard shortcut help overlay.
HelpOverlay # auto-generates from app keybindingsCommandPalette(&block?, :style, |c)
Command palette for fuzzy-searchable actions. The optional block registers commands.
CommandPalette { $.add-command({ say 'new' }, :label<New>) }Methods:
.add-command(&action, :$label!)ā Register a command.commands(@pairs)ā Set commands from pairs.show-modalā Show the palette modal.on-command(&block)ā Command handler (idempotent).buildā Build the underlying modal widget
FileBrowser(&block?, Bool :focus, :&on-select, :style, |c)
File system browser widget that opens as a modal.
FileBrowser :show-modal, :on-select(-> $, $path { say $path })Miscellaneous
ScrollView(&block?, :size, :$style, |c)
Scrollable viewport container for overflowing content.
ScrollView { VBox { ... } }Spinner(:@frames, :style, :$size, |c)
Animated spinner with configurable frames and interval.
Spinner(:frames(['/', '-', '\\', '|']), :interval(0.1))Methods:
.tickā Advance to next frame.resetā Reset to first frame
Image(&block?, :size, :$style, |c)
Image display widget. Supports reactive file binding via block.
Image(:file('logo.png'))ProgressBar(:style, |c)
Progress bar with configurable value.
ProgressBar.progress(0.75).show-percentageMethods:
.progress(Numeric)/.progress(&block)ā Set progress value.indeterminate(Bool)ā Toggle indeterminate mode.show-percentage(Bool)ā Toggle percentage display.tickā Advance animation frame
Charts
Plot(:min-y, :title, :rangex, :@store-path, :size, :$style, |c)
General-purpose plot widget.
Plot :type<bar>, :data([{:x(0),:y(1)},{:x(1),:y(3)}]), :title('Sales')BarChart(:@data, :@store-path, :palette, :show-labels, :max, :empty-message, :style, |c)
Bar chart with configurable orientation and styling.
BarChart(:data([{:label<A>,:value(10)},{:label<B>,:value(20)}]))LineChart(:@series, :&store-path-fn, :show-axis, :fill-below, :y-min, :tick-count, :size, :$style, |c)
Line chart with multiple series support.
LineChart(:series([{:name<A>,:values[1,2,3]}]))ScatterPlot(:@series, :@store-path, :x-min, :y-min, :overlap, :size, :$style, |c)
Scatter plot for point data visualization.
ScatterPlot(:series([{:name<pts>,:x[1,2,3],:y[4,5,6]}]))Sparkline(:@data, :@store-path, :max, :size, :$style, |c)
Compact inline sparkline chart.
Sparkline(:data([1, 3, 2, 5, 4]))Heatmap(:@data, :@store-path, :min, :empty-message, :style, |c)
Heatmap for matrix data visualization.
Heatmap(:data([[1,2],[3,4]]))Histogram(:@values, :orientation, :show-axis, :min, :tick-count, :size, :$style, |c)
Histogram for distribution visualization.
Histogram(:values([1,1,2,2,2,3]), :bins(3))Axis(:max!, :tick-count, :size, :$style, |c)
Chart axis with configurable range and ticks.
Axis(:min(0), :max(100), :tick-count(5))Legend(:@series, :swatch, :style, |c)
Chart legend for multi-series plots.
Legend(:series([{:name<A>,:swatch<red>}]))State and Helpers
new-state(name, :$event)
Creates a reactive state variable. Returns a Proxy that auto-tracks reads and dispatches events on writes. Use for scalar values (Str, Int, Bool). Requires an active App context.
new-array-state(@default, :event)
Creates a reactive array state. Returns a ReactiveArray that implements Positional and Iterable. Bind with := to an @-sigiled variable. Mutations dispatch fresh values: push, pop, shift, unshift, splice, ASSIGN-POS.
new-hash-state(%default, :event)
Creates a reactive hash state. Returns a ReactiveHash that implements Associative and Iterable. Bind with := to a %-sigiled variable. Mutations dispatch fresh values: ASSIGN-KEY, DELETE-KEY.
Handler(Str $name, &block)
Registers a store event handler for the given event name.
Detached(&block)
Creates isolated UI node contexts without parent attachment. Sets up @*UI-NODES for the block. Returns the block's result if defined, otherwise the first child node from @*UI-NODES.
my $stream = Detached { TextStream };OnKey(Str:D screen)
Registers a keypress handler. $spec is a key specification string (e.g., "ctrl+p", "q", "tab").
OnFrame(&block)
Registers a per-frame callback for animation or polling.
Dispatch($event, *%payload)
Dispatches a named event through the store with optional payload.
Tick
Triggers an immediate store tick (re-render cycle).
ShowModal($modal)
Opens a modal dialog from a builder or widget. Returns the modal widget.
CloseModal
Closes the currently open modal dialog.
Focus($widget)
Focuses a specific widget. Returns the widget for chaining. Handles .focusable-widget delegation automatically.
FocusNext
Moves focus to the next focusable widget.
FocusPrevious
Moves focus to the previous focusable widget.
SwitchScreen(Str $name)
Switches to a named screen.
Quit
Exits the TUI application gracefully.
Toast(Str duration = 3.0)
Dispatches a transient toast notification via the app.
AUTHOR
Fernando Correa de Oliveira
LICENSE
Artistic-2.0