Key bindings
Navigation, edit, accept and cancel keys are all configurable. A field never asks for a fixed key - it asks for a semantic action (MoveUp, Accept, Toggle - the full set is listed below), and a key map binds each action to one or more keys. Key bindings describe the terminal, not the questionnaire, so you set them on the Tui facade with ->keys(...), mirroring ->theme(...):
$tui = (new Tui($form))->keys('vim'); // built-in vim navigation (h/j/k/l)
3 presets ship: default (every binding it declares is listed below), vim and view. The vim preset adds h/j/k/l alongside the arrow keys - but only where a letter isn't typed input, so text and filter fields keep the arrows. The view preset binds no keyboard keys, for a screen with no fields.
Actions
The actions are the fixed set of intents the fields understand - the bindings behind them are configurable, the intents are not. Every Action case:
| Action | Meaning |
|---|---|
MoveUp / MoveDown / MoveLeft / MoveRight | Move the cursor or caret |
Accept | Commit the editor's value |
Cancel | Close the editor without committing |
Activate | Open the focused field, go into the focused panel, or press a button |
Back | Come back out of the panel you are in |
Quit | Close the dialog that is open, else end the session |
ScrollUp / ScrollDown | Move a scrolling region without moving the cursor |
Help | Show the focused field's help on a page of its own |
DeleteBack | Delete the character before the caret |
InsertSpace | Type a space |
NewLine | Insert a newline (textarea) |
ExternalEdit | Hand off to the external editor (textarea) |
Complete | Accept the ghost-text completion (text, suggest) |
Increment / Decrement | Step a bounded number |
Toggle | Check an option, or flip a two-state switch |
SelectAll / SelectNone | Check or clear every visible option |
Grab | Pick up or drop the held item (reorder) |
Yes / No | Set a confirm directly |
Reveal | Cycle the password display, or show hidden file-picker entries |
The named keys a binding can use - every KeyName case: Up, Down, Left, Right, Enter, Escape, Interrupt (Ctrl-C), Suspend (Ctrl-Z), Space, Backspace, Delete, Tab, Home, End, PageUp, PageDown, MouseWheelUp, MouseWheelDown. Anything printable is bound as the character itself ('q', '?').
The default bindings
What default actually declares, scope by scope. Every field inherits the base layer and overrides only what differs:
| Scope | Keys | Action |
|---|---|---|
| base (every field) | ↑ / ↓ / ← / → | MoveUp / MoveDown / MoveLeft / MoveRight |
| base | Enter | Accept |
| base | Esc | Cancel |
| base | Backspace | DeleteBack |
| base | Space | InsertSpace |
| navigation | Enter | Activate |
| navigation | Esc | Back |
| navigation | q | Quit |
| navigation | ? | Help |
| navigation | mouse wheel | ScrollUp / ScrollDown |
| every field that takes no typed text | ? | Help |
| number | ↑ / ↓ | Increment / Decrement |
| rating | → / ↑ and ← / ↓ | Increment and Decrement |
| text, suggest | Tab | Complete |
| template | Tab / ↓ and ↑ | MoveDown and MoveUp (between slots) |
| textarea | Enter | NewLine |
| textarea | Tab | Accept |
| textarea | Ctrl-E | ExternalEdit |
| confirm | y/Y and n/N | Yes and No |
| confirm, toggle | ← / → / Space / ↑ / ↓ | Toggle |
| password | Tab | Reveal |
| pause | Enter / Space | Accept |
| select (multiple), search (multiple) | Space | Toggle |
| select (multiple), search (multiple) | → / ← | SelectAll / SelectNone |
| file picker (single and multiple) | Tab | Reveal |
| file picker (multiple) | Space | Toggle |
| reorder | Space | Grab |
vim inherits all of it and adds letters where typing can't swallow them: the panel browser gains h/j/k/l for all four directions, the single-choice select k/j for up and down, and the calendar k/j/h/l for week and day movement - each alongside the arrow keys, never replacing them.
The every field that takes no typed text row is why a field's own help stays reachable while it is open. Where the field takes typed characters the key is one of them, so the scope is skipped rather than fought over - which is also what the validation below would insist on.
Not everything on the keyboard routes through the map: a few field keys are fixed. The calendar's month and edge jumps (PageUp/PageDown, Home/End) have no action behind them and always keep their keys. Ctrl-C is fixed the other way round - it is answered above the routing, so it aborts from anywhere, including from inside an open field. Ctrl-Z is answered above the routing too, and hands the terminal back to the shell from anywhere.
ScrollUp and ScrollDown are what the wheel is bound to, and they move what you are looking at rather than where you are: the viewport shifts by a row, the overflow marks follow it, and the cursor stays on the row it was on. A region that was not declared to scroll ignores them, because there is nothing to move through. The next key that could move the cursor puts the region back under it, so looking ahead never costs you your place.
Per-field-type overrides
Bindings are layered by scope: a base layer shared by every field, a navigation layer for the panel browser, and one layer per field type that overrides the base only where it differs (Enter inserts a newline in a textarea, Space toggles a checkbox option). To retune individual bindings, pass overrides on top of a preset - each names a scope, an action and its keys. Later bindings win, so re-declaring a scope-and-action pair replaces the preset's keys for it:
use DrevOps\PhpTui\Block\FieldType;
use DrevOps\PhpTui\Input\Action;
use DrevOps\PhpTui\Input\Binding;
use DrevOps\PhpTui\Input\KeyName;
use DrevOps\PhpTui\Input\Scope;
$tui = (new Tui($form))->keys('default', [
// Quit with x as well as q.
new Binding(Scope::navigation(), Action::Quit, 'x'),
// In the single-choice list, Tab accepts too.
new Binding(Scope::field(FieldType::Select), Action::Accept, KeyName::Tab, KeyName::Enter),
]);
A binding's keys take three forms: a KeyName case for a named key, a single-character string for a printable one, or a Key for anything else - Key::char("\x05") is how the default preset binds Ctrl-E. A scope takes three forms too: Scope::base() (shared by every field), Scope::navigation() (the panel browser), and Scope::field(FieldType::X) - with Scope::field(FieldType::X, multiple: TRUE) targeting the multiple-collecting variant of a choice or file-picker field, which carries its own binding set (that's where Space-to-toggle lives).
The panel and editor hints are drawn from the live bindings, so they always reflect the active keys - remap quit to x and the footer says so.
Letters in a multiple select
A multiple select filters its options as you type. The answer is the options you check, so the multiple select is the one text-taking scope where you can bind a printable character. A bound letter runs its action and skips the filter. To check every option on a and clear them on n:
$tui = (new Tui($form))->keys('default', [
new Binding(Scope::field(FieldType::Select, multiple: TRUE), Action::SelectAll, 'a'),
new Binding(Scope::field(FieldType::Select, multiple: TRUE), Action::SelectNone, 'n'),
]);
The multiple search, Scope::field(FieldType::Search, multiple: TRUE), keeps every letter for its query, because the query can drive a backend source.
Your own commands
A Command binds keys to a handler of your own. Declare it in the same list as your overrides, with the label the hint line shows, the handler and the keys. Its keys take the same 3 forms a Binding takes:
use DrevOps\PhpTui\Answers\Answers;
use DrevOps\PhpTui\Input\Command;
$drafts = [];
$tui = (new Tui($form))->keys('default', [
new Command('save', function (Answers $answers) use (&$drafts): void {
$drafts[] = $answers->toSummary();
}, 's'),
]);
The handler receives the answers as they stand when the key is pressed, and the running Session. Its return value is ignored.
A command runs from the panels: on any row and on the buttons that end the form. While a field is open, its keys go to the field, so an open text field types s as a letter. The hint line follows the same rule. It lists each command after the panel's own keys, in the order you declared them, and drops them while a field is open.
A command needs a free key. Its key can't be one the navigation scope already binds, either directly or through the base scope, such as q, ?, Space or j under vim. It also can't be another command's key. Either conflict throws when the facade is configured. To give a command a built-in's key, rebind the built-in first: new Binding(Scope::navigation(), Action::Quit, 'x') frees q.
Close the screen with a result
A command ends the screen by calling $session->close($result) on the Session it receives. interact() and run() then return the answers as they stand, with your value on their result property. To end the screen on p with the value packed:
use DrevOps\PhpTui\Answers\Answers;
use DrevOps\PhpTui\Input\Command;
use DrevOps\PhpTui\Screen\Session;
$answers = (new Tui($form))->keys('default', [
new Command('pack', function (Answers $answers, Session $session): void {
$session->close('packed');
}, 'p'),
])->interact();
$answers->result; // 'packed'
result is any value you pass, such as an enum case. It's NULL when the screen ends through the quit key or the finish button. A dialog that's open when the command closes the screen gets discarded first, because its edits were never confirmed. Only the first close counts, and the keys after it in the same read are dropped.
Ask before quit
Tui::confirmQuit() runs a closure of yours each time the quit key would end the screen. The closure receives the answers and the Session. Return TRUE to leave, or FALSE to stay. The quit key that closes a dialog never runs it, and Ctrl-C always stops the session without asking.
To ask a question, return FALSE and show the question in a block of your own. Commands then answer it by closing the screen with a result. To ask whether to keep the stall open or close it:
use DrevOps\PhpTui\Answers\Answers;
use DrevOps\PhpTui\Block\Markup;
use DrevOps\PhpTui\Input\Command;
use DrevOps\PhpTui\Screen\Axis;
use DrevOps\PhpTui\Screen\Layout\RegionName;
use DrevOps\PhpTui\Screen\Session;
$asked = FALSE;
$prompt = new Markup('prompt', '');
$answers = (new Tui($form))
->place(RegionName::Header, $prompt, tail: TRUE)
->flow(RegionName::Header, Axis::Columns)
->confirmQuit(function () use (&$asked, $prompt): bool {
$asked = TRUE;
$prompt->body('Leave the market? O keeps the stall open, C closes it.');
return FALSE;
})
->keys('default', [
new Command('keep open', function (Answers $answers, Session $session) use (&$asked): void {
if ($asked) {
$session->close('open');
}
}, 'o'),
new Command('close stall', function (Answers $answers, Session $session) use (&$asked): void {
if ($asked) {
$session->close('closed');
}
}, 'c'),
])
->interact();
The closure can also call $session->close($result) itself, such as to leave at once with a result when there's nothing to confirm.
Display-only screens
A screen with no fields, such as a live dashboard, has nothing to navigate. Select the view preset to leave every keyboard key free for your commands, including the arrow keys, Enter, Space, Esc, q and ?. To step through crates on the arrow keys, weigh 1 on Enter and end the screen on q:
use DrevOps\PhpTui\Input\Action;
use DrevOps\PhpTui\Input\Binding;
use DrevOps\PhpTui\Input\Command;
use DrevOps\PhpTui\Input\KeyName;
use DrevOps\PhpTui\Input\Scope;
$tui = (new Tui($form))->keys('view', [
new Command('previous crate', $previous, KeyName::Up),
new Command('next crate', $next, KeyName::Down),
new Command('weigh', $weigh, KeyName::Enter),
new Binding(Scope::navigation(), Action::Quit, 'q'),
]);
$previous, $next and $weigh are your handlers. The Quit binding ends the screen on q, and the hint line lists it after your commands.
Ctrl-C still stops the session and Ctrl-Z still steps away, because the session answers both keys above the routing. The mouse wheel still scrolls a scrolling region.
Use view only on a screen with no fields, because it binds no key that opens a field or presses a button.
Choose the hints
A screen whose keys change with what it shows can pick its own hint line with ->hints(). Pass a closure that receives the hints the footer would show and returns a list of Hint objects to show in their place. The closure runs on every frame, so the line follows whatever state it reads. Capture that state by reference, because an arrow function copies its value when the closure is created:
use DrevOps\PhpTui\Input\Action;
use DrevOps\PhpTui\Input\Command;
use DrevOps\PhpTui\Input\Hint;
$view = 'basket';
$weigh = new Command('weigh', function () use (&$view): void {
$view = $view === 'basket' ? 'scale' : 'basket';
}, 'w');
$tui = (new Tui($form))
->keys('default', [$weigh])
->hints(function (array $hints) use (&$view, $weigh): array {
if ($view === 'basket') {
return $hints;
}
return [new Hint('go back to the basket', $weigh), new Hint('quit', Action::Quit)];
});
The hints the closure receives are the panel's or the open field's keys, then quit, then show help when the row has help text. Return them filtered or extended to adjust the line, or return your own list to replace it.
A Hint takes a label and the triggers whose keys it shows: actions, keys and commands. A command shows its first key and drops out of the line where the command doesn't run, such as while a field is open. Pass the command itself to its hint, so the hint follows a rebind.
Hint::for() builds a hint from a command's own label, so you write the label once. It takes the label from the first command. Every command you pass shows its key under that label:
$previous = new Command('pick a crate', $up, 'p');
$next = new Command('next crate', $down, 'n');
Hint::for($weigh); // W to weigh
Hint::for($previous, $next); // P/N to pick a crate
Use new Hint() for a label that differs from the command's, such as go back to the basket in the preceding example.
A footer that runs out of room drops whole hints from the end of the line. Call keep() on a hint so the footer drops it only after every hint that isn't kept. The footer shows the hints that fit in the order you listed them:
return [
Hint::for($previous, $next),
Hint::for($weigh)->keep(),
(new Hint('quit', Action::Quit))->keep(),
];
On a narrow terminal this line drops P/N to pick a crate first. When the kept hints still don't fit, the footer drops them from the end too, and it always shows at least 1 hint. The default quit hint is already kept. A quit hint you build yourself needs its own keep() call.
With ->footer(FALSE) the closure never runs. A closure that returns anything other than a list of Hint objects throws a LogicException on the first frame that reads it.
Presets and validation
A preset is a class listing its bindings. Subclass DefaultKeyMap to ship your own, name it directly with ->keys('\App\MyKeyMap'), or register a short alias with KeyMapManager::register('mine', MyKeyMap::class) and then ->keys('mine').
Bindings are validated the moment they're set, so a bad key map is caught at configuration time, not mid-session:
- a key bound to two different actions in the same scope is a conflict;
- a command key already bound in the navigation scope, to an action or to another command, is a conflict;
- a printable character bound in the base scope, or in a scope whose field consumes typed input (text, template, number, rating, password, textarea, search, suggest, toggle and file picker), would be un-typeable and is rejected - control characters like Ctrl-E are exempt, since they're command keys, never typed content;
- an unknown preset name, a character binding that isn't exactly 1 character, a command with no label or no keys, or a command bound to Ctrl-C or Ctrl-Z, is rejected.
See playground/10-key-bindings-* for the default map, the vim preset, a custom override, your own commands and a runtime hint line side by side.