All 48 libraries

SugarFocus

Focus-ring state machine — ordered focusable regions with Tab/Shift-Tab traversal, accent paint gated on isEnabled()

original — no 1:1 Go counterpart focus keyboard navigation

SugarFocus code coverage

A dependency-free focus ring for full-window terminal UIs: an ordered set of focusable regions with exactly one focused member and wrap-around Tab and Shift-Tab traversal. It answers "which panel has focus?" for a TUI layout. The ring carries no rendering and no key decoding, so it composes with any sugar-core model. It is an original SugarCraft design with no Go counterpart; see Upstream mapping.

Install

composer require sugarcraft/sugar-focus

Requires PHP 8.3 or newer. The package has no runtime dependencies. The wiring example below uses sugar-core's key message, which your model already has.

Quickstart

use SugarCraft\Focus\FocusRing;

$ring = FocusRing::of('sidebar', 'grid', 'filter'); // 'sidebar' is focused

$ring = $ring->next();        // 'grid'
$ring = $ring->next();        // 'filter'
$ring = $ring->next();        // 'sidebar' (wraps)
$ring = $ring->previous();    // 'filter' (wraps the other way)
$ring = $ring->focus('grid'); // jump straight to a region

$ring->current();             // 'grid'
$ring->isFocused('grid');     // true

Every mutator returns a new FocusRing. Store the result, because the receiver is never changed.

The recorded demo is a committed artifact. It is rendered from .vhs/focus-ring.tape by CI, not by hand. The demo repaints the whole frame on each loop, so it can flicker on some displays.

sugar-focus demo

Concepts

A non-empty ring always has exactly one focused region. An empty ring focuses nothing: current() is null and index() is -1. Traversal wraps at both ends and skips disabled regions.

A region can be disabled without being removed. A disabled region stays registered, so it keeps its place in the order, but Tab skips it. Focus can legally sit on a disabled region, which the ring calls parked. The paint and the key routing must therefore check both isFocused() and isEnabled().

Every no-op returns the same instance. Registering an existing id, focusing an unknown or disabled id, and traversing with nowhere to go all return the receiver, so $new === $old detects "nothing changed" cheaply. When a caller needs to branch on that, canFocus() and tryFocus() answer explicitly.

Tasks

Use it for

  • Tab cycling between panels. candy-code's Tui\Pane cycles its tabs through a ring.
  • Dashboard focus. SugarDashboard's Layout\FocusManager wraps a ring and persists it.
  • Modal dialogs. A dialog takes focus with FocusTrap and gives it back on release.

Wire Tab and Shift-Tab into update()

use SugarCraft\Core\KeyType;
use SugarCraft\Core\Msg\KeyMsg;

if ($msg instanceof KeyMsg && $msg->type === KeyType::Tab
    && !$msg->ctrl && !$msg->alt) {
    $ring = $msg->shift ? $this->ring->previous() : $this->ring->next();
    return [$this->withRing($ring), null];
}

On the wire, Shift+Tab arrives as Tab with shift set, because sugar-core decodes the ESC [ Z sequence into that shape. The guard leaves Ctrl+Tab and Ctrl+Shift+Tab free for other bindings, but only on terminals that report modifiers. On a legacy terminal Ctrl+Tab is byte-identical to Tab, so it moves the ring.

Paint the focused region

$style = $ring->isFocused('sidebar') && $ring->isEnabled('sidebar')
    ? $accentBorder
    : $plainBorder;

The isEnabled() conjunct matters. Without it, a parked focus paints an accent border on a dimmed panel. isParked() reports that whole-ring state in one call.

Trap focus in a dialog

FocusTrap owns the save-and-restore ritual. It holds the saved id and the list of background regions, so releasing the trap takes no argument.

$trap = $ring->trap()->guarding('dialog-ok', 'dialog-cancel'); // background unreachable
$trap = $trap->withRing($trap->ring()->next());                // Tab inside the dialog
$ring = $trap->release();                                      // background back, focus restored

release() re-enables the background, unregisters the dialog ids, and restores focus to the saved region when it is still enabled. Otherwise it restores focus to the first enabled region. guarding() throws when an id is already registered.

Save and restore focus

$json = json_encode($ring);   // {"ids":[…],"focused":…,"index":n,"disabled":[…]}

$ring = FocusRing::fromJson($json)
    ?? FocusRing::of('sidebar', 'grid', 'filter');   // unreadable file: rebuild defaults

fromJson() returns null when the text does not parse to an array, so a corrupt file falls back to the defaults. A structurally broken id list still throws from restore(), because that is a producer bug and not disk rot.

Keys

The ring handles no keys itself. The runnable example maps these keys to ring operations, and a model can use the same map.

Keys used by examples/focus-ring.php
KeyRing operation
Tabnext()
Shift-Tabprevious()
xToggle whether the focused region takes part in traversal (disable() and enable())
dRe-enable the first disabled region, focus not required
s / rSnapshot the ring with json_encode(), then restore it with fromJson()
qQuit

Theme and styling

The ring has no colors. The consumer paints the focused region with an accent border in view(), and the paint must follow isFocused() && isEnabled(). Pair the accent with a non-color cue, because a border is invisible to a user who cannot tell the hue apart. The example prints a text status per panel (> FOCUS, > parked, idle, off) and a footer that names the focused region. This follows WCAG 1.4.1 (Use of Color). Border strength falls under 1.4.11 (Non-text Contrast).

Screen readers never see the paint. Announce current() by name whenever it changes. For a "region k of n" position, use enabledIndex() + 1 over enabledCount(), because it counts what Tab can reach. When enabledIndex() is null, announce the region name alone.

Configuration

The ring has no runtime options. Its behavior is set by the constructor you choose and by the snapshot you restore.

Construction and restore options
Entry pointDuplicate idsFocus on buildUse when
FocusRing::new()n/aEmpty ring, no focusRegions are registered later with register()
FocusRing::of(...$ids)Dropped; first winsFirst idThe usual case: known regions at startup
FocusRing::ofStrict(...$ids)Throws InvalidArgumentExceptionFirst idA duplicate id is a programmer error that should fail loudly
FocusRing::fromJson($json)Per restore()From the snapshot's focused idRestoring a file that may be corrupt; returns null when unreadable
FocusRing::restore(array $snapshot)Structurally broken ids throwFrom focused, else the clamped indexA snapshot already decoded to an array

The snapshot holds four keys: ids in traversal order, focused by id, index for readers of older snapshots, and disabled as a list of strings. Legacy positional-only snapshots have no disabled key, so every region comes back enabled. Ids in disabled must be JSON strings, because a numeric 1 never matches the id "1".

Examples

examples/focus-ring.php draws four labeled panels and handles the keys listed above. The example hand-rolls its ANSI, so the library stays dependency-free. With no terminal attached, it draws one frame and exits 0.

php examples/focus-ring.php

Testing

cd sugar-focus && composer install && vendor/bin/phpunit

The suite has two test classes: FocusRingTest covers the ring's transitions, disabled-region rules and snapshots, and FocusTrapTest covers the dialog recipe.

Troubleshooting and FAQ

A disabled panel shows the accent border

Focus can park on a disabled region. Paint with isFocused($id) && isEnabled($id), or check isParked() once for the whole ring.

next() does nothing

Traversal needs at least two enabled regions. With one enabled region the ring has nowhere to move, so the call returns the receiver unchanged. The exception is focus parked on a disabled region, which moves to the nearest enabled one.

current() is null

The ring is empty, or a dialog opened over an empty ring. focusFirst() does nothing on an empty ring, so register a region before focus can land: register() focuses the new region when the ring is empty, and of() takes the ids up front. Use focusFirst() only when regions exist and none is focused, and never pass null to focus().

Ctrl+Tab moves focus like Tab

That is a terminal limit, not a ring bug. Ctrl+Tab is identical to Tab on terminals that do not report modifiers. The guard can only tell the two apart where the terminal reports them.

A restored id contains terminal control bytes

A snapshot is untrusted input, and the ring never sanitizes ids. Pass every id you paint through sugar-core's Sanitize::untrusted(). Use untrustedForMarkedFrames() when the frame carries sugar-mouse zones.

use SugarCraft\Core\Util\Sanitize;

$label = Sanitize::untrusted((string) $ring->current());

Upstream mapping

No Charmbracelet source maps to this library. The ring is an original SugarCraft design. By analogy, the Charmbracelet component stack handles focus inside each component, while this library holds focus state for a whole layout. The analogy is for orientation only.

SugarCraft classes and their origin
ClassOrigin
FocusRingOriginal SugarCraft design
FocusTrapOriginal SugarCraft design, built on FocusRing
examples/focus-ring.phpHand-rolled ANSI demo of the ring; no upstream

Architecture

FocusRing is an immutable value object. It holds an ordered id list, a focused id and a set of disabled ids, and it implements Countable, IteratorAggregate and JsonSerializable. FocusTrap wraps a ring and records the saved focus and the background regions it disabled. Neither class performs IO or rendering.

API

FocusRing

FocusRing public methods
MethodDescription
new(), of(...$ids), ofStrict(...$ids)Empty ring, ring with the first id focused, or the same with duplicates rejected
restore(array $snapshot), fromJson(string $json): ?selfRebuild from a decoded snapshot, or from JSON text (null when unreadable)
register(string $id), unregister(string $id), reorder(...$ids)Add an enabled region, remove one while keeping focus where possible, or replace the order
focus(string $id), focusFirst(), focusLast()Focus a registered, enabled region, or the first or last enabled region
canFocus(string $id): bool, tryFocus(string $id): ?selfAsk first: would focus() move? tryFocus() returns the moved ring or null
next(), previous()Tab and Shift-Tab traversal, wrapping and skipping disabled regions
nextOf(string $id), previousOf(string $id), peekNext(), peekPrevious()Pure queries: where traversal would land, without moving focus
disable(string $id), enable(string $id)Exclude a region from traversal, or restore it
isEnabled(string $id), has(string $id), isFocused(string $id)Enabled and registered checks, and the focus check to pair with isEnabled() when painting
current(): ?string, isParked(): boolThe focused id, or null; whether focus sits on a disabled region
index(): int, enabledIndex(): ?intPosition among all registered ids, or the 0-based ordinal among enabled ids
ids(), enabledIds(), disabledIds()Registered, enabled and disabled ids in traversal order
count(), enabledCount(), disabledCount(), isEmpty()Region counts and the empty check
jsonSerialize(): array, getIterator()The snapshot shape, and foreach support over every registered id

FocusTrap

FocusTrap public methods
MethodDescription
new(FocusRing $base), FocusRing::trap()Start a trap over a ring
guarding(...$ids)Register the dialog ids and disable the background
withRing(FocusRing $ring), ring()Replace the working ring, or read it
saved(), background(), dialog()The focus to restore, and the background and dialog id lists
release()Return the ring with the background enabled, the dialog removed and focus restored

Only methods declared in sugar-focus/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Focus

FocusRing final class

An immutable focus ring: an ordered set of focusable region ids with a single focused member, plus Tab/Shift-Tab traversal that wraps around.

MethodSummary
static new(): selfAn empty ring with nothing registered or focused.
static of(string ...$ids): selfA ring of the given region ids in traversal order (duplicates dropped, first occurrence wins), focusing the first one.
static ofStrict(string ...$ids): selfA strict variant of of() that throws on duplicate ids instead of silently dropping them. Useful when callers want to enforce uniqueness.
register(string $id): selfRegister a region at the end of the traversal order. A no-op (returns the same ring) if it is already registered. Registering into an empty ring focuses the new region. A newly registered region is always enabled.
unregister(string $id): selfRemove a region. A no-op if it was not registered. If the removed region was focused, focus lands on the nearest ENABLED survivor at or after the vacated slot (wrapping to the first enabled region at the end) — the wall that next() skips must not strand the next keystroke. Only when EVERY survivor is disabled does focus keep the slot (clamped to the new end): the parked state, which the next traversal carries off. Focus otherwise stays on the same region. The disabled flag for the removed id is cleared.
trap(): FocusTrapOpen a modal FocusTrap over this ring; call guarding() then release().
focus(string $id): selfFocus a specific registered, ENABLED region. A no-op if it is not registered, is disabled, or is already focused.
canFocus(string $id): boolWhether focus() would actually MOVE focus to $id: registered, enabled, and not already focused. One bool for all three refusal causes — the same wall focus() respects; pair with has()/isEnabled() when the caller must know WHICH refusal happened.
tryFocus(string $id): ?selfAsk-and-refuse form of focus(): the moved ring when focus relocates, null when it would not (unknown id, disabled id, already focused — an empty ring refuses everything, so it answers null too). focus()'s identity-return and this null are the same fact in two grammars; the shared call keeps them from drifting apart.
focusFirst(): selfFocus the first ENABLED region in traversal order — disabled heads are skipped. A no-op when nothing is enabled, or when focus already sits there.
focusLast(): selfFocus the last ENABLED region in traversal order — disabled tails are skipped. A no-op when nothing is enabled, or when focus already sits there.
reorder(string ...$ids): selfReplace the traversal order while keeping focus on the current region id when it survives the dedupe. Acts as a batch set-replace — ids not previously registered are added; ids missing from the new list are dropped.
next(): selfMove focus to the next enabled region (Tab), wrapping past the end. Disabled regions are skipped. Disabling the focused region does not move focus; it is left in place and the next traversal carries it off — onto the nearest enabled region after it, even when that is the only enabled region left. A no-op (returns the same ring) when focus already sits on the only enabled region, or when no region is enabled.
previous(): selfMove focus to the previous enabled region (Shift-Tab), wrapping past the start. Disabled regions are skipped. Disabling the focused region does not move focus; it is left in place and the next traversal carries it off — onto the nearest enabled region before it, even when that is the only enabled region left. A no-op (returns the same ring) when focus already sits on the only enabled region, or when no region is enabled.
nextOf(string $id): ?stringPure query: the id focus would land on stepping forward from $id, without moving focus. Mirrors next() including its no-op shape — an id with nowhere enabled to go answers with itself: when every region is disabled, or when $id is the sole enabled survivor. A parked, disabled query id with any enabled survivor moves to the nearest one in that direction. null when the id is not registered.
previousOf(string $id): ?stringPure query: the id focus would land on stepping backward from $id, without moving focus. Mirrors previous(); see nextOf().
peekNext(): ?stringWhere next() WOULD land if it were called now, without moving focus: the ring-level sibling of nextOf(), answering about the CURRENT focus. null on an empty ring; a parked focus answers via the nearest enabled region, and a nowhere-to-move focus answers with its own id (next()'s no-op shape — callers compare ===current() to detect "Tab would do nothing").
peekPrevious(): ?stringWhere previous() WOULD land if it were called now. See peekNext() for the shared grammar (empty ring null, parked focus carried to the nearest enabled region, no-op answers the current id).
disable(string $id): selfDisable a region so next()/previous() skip over it. Disabling the currently focused region does not move focus — it is a pure metadata change so disable() never causes surprising focus jumps.
enable(string $id): selfRe-enable a previously disabled region. A no-op if the id is not registered or is already enabled.
isEnabled(string $id): boolTrue when the region is registered and not disabled. False conflates unregistered with disabled — use has() to tell them apart.
enabledIds(): array
disabledIds(): array
enabledCount(): intZero-cost enabled region count (avoids array allocation of enabledIds()).
disabledCount(): intZero-cost disabled region count.
getIterator(): \Traversable
jsonSerialize(): arraySnapshot for session persistence: the ids in traversal order, the focused region (as both an id and a position), and the disabled ids in traversal order. Disabled ids are read from $ids rather than from the keys of the disabled set, because PHP coerces a numeric-string key such as "1" to int(1) — the snapshot must stay a list of strings so restore() can consume it verbatim.
static restore(array $snapshot): selfRebuild a ring from a jsonSerialize() snapshot — the inverse of the persistence format.
static fromJson(string $json): ?selfDecode a JSON snapshot string and rebuild through restore() — the file-reading convenience that keeps callers from hand-assembling the json_decode/is_array guard.
current(): ?stringThe focused region id, or null when the ring is empty.
isFocused(string $id): boolWhether $id is the focused member. CAUTION for painters: focus can legally PARK on a disabled region — disable() never moves an existing focus, and unregister() lands on the vacated slot when every survivor is disabled — so draw a focus accent only when isFocused($id) && isEnabled($id) both hold.
has(string $id): bool
index(): intThe focused position into the REGISTERED ids (disabled regions count too), or -1 when the ring is empty. For "region k of n" among the focusable ones use enabledIndex() with enabledCount(). Answers -1 ONLY when empty: a parked focus still reports its raw slot — the two no-answer grammars differ, enabledIndex() nulls on empty AND parked.
enabledIndex(): ?intThe focused region's 0-based ordinal into enabledIds() — the "k" of "region k of n" for a status line. null when the ring is empty or focus is parked on a disabled region, cases where index() counts every registered region and cannot answer; unlike index()'s -1 (empty only), this null also covers the parked state.
ids(): array
count(): intNumber of registered regions (enabled and disabled); backs count($ring).
isEmpty(): bool
isParked(): boolWhether focus currently sits on a DISABLED region — the ring is non-empty and enabledIndex() has no answer. Focus parks ONLY through disable() on the focused id, or unregister()/restore landing it on an all-disabled survivor. The paint rule and the key-routing guard are one question about the whole ring; naming it here stops every call site from recombining the two accessors and getting the empty case wrong. Per-region paint still pairs isFocused()/isEnabled() — this answers about the FOCUSED region.

FocusTrap final class

An immutable modal focus trap over a FocusRing: opening it captures what the dialog interrupts (the focused id and every enabled id) and disables the background; release() undoes it in the one correct order with no argument, because the trap holds its own base state.

MethodSummary
static new(FocusRing $base): selfOpen a trap over $base: every currently enabled region becomes unreachable.
guarding(string ...$ids): selfRegister the dialog's focusable regions and focus the first.
withRing(FocusRing $ring): selfReplace the trapped ring, e.g. after Tab / Shift-Tab inside the dialog.
ring(): FocusRingThe ring as it stands while trapped (background disabled, dialog ids live).
saved(): ?stringThe id focused when the trap opened, or null on an empty ring.
background(): array
dialog(): array
release(): FocusRingClose the dialog: re-enable background, drop dialog ids, restore focus.

Changelog and versioning

This page does not record a release history. The commit history on GitHub is the change record.

Source and demos

Try the quickstart →