Search by

sugarcraft / sugar-focus

detain

Focus-ring state machine — an ordered set of focusable regions with wrap-around Tab/Shift-Tab traversal for full-window TUI layouts. Dependency-free.

Package info

github.com/sugarcraft/sugar-focus

Documentation

pkg:composer/sugarcraft/sugar-focus

Statistics

Installs: 2 573

Dependents: 5

Suggesters: 0

Stars: 0

Open Issues: 0

dev-master 2026-11-19 05:37 UTC

This package is auto-updated.

Last update: 2026-11-20 01:04:06 UTC


README

Formerly published as sugarcraft/candy-focus (renamed 2026-10).

A tiny, dependency-free focus ring for full-window terminal UIs: an ordered set of focusable regions with a single focused member and wrap-around Tab/Shift-Tab traversal.

It is the "which panel has focus" state for a TUI layout. Register each focusable region (sidebar, content grid, filter bar…), map Tab to next() and Shift-Tab to previous(), and give the region returned by current() an accent border when you render. The ring carries no rendering or key decoding of its own, so it composes with any sugar-core model without pulling in dependencies.

Install

composer require sugarcraft/sugar-focus

Quick start

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

Wire it into a sugar-core model's 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: true — sugar-core's InputReader decodes ESC [ Z (CSI-Z, the literal "Backtab" sequence terminals send for Shift+Tab) into that shape. The ring leg is gated on !$msg->ctrl && !$msg->alt, so Ctrl+Tab and Ctrl+Shift+Tab stay free for other bindings — but that holds only on terminals that report modifiers (kitty keyboard negotiation, or an xterm modifyOtherKeys-style decoder). On legacy/basic terminals Ctrl+Tab is byte-identical to bare Tab: nothing can separate the two there, and those presses move the ring like a plain Tab would.

…and let each region style itself in view():

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

The isEnabled() conjunct matters: focus can legally park on a disabled region, so isFocused() alone can paint an accent border on a dimmed panel — if ($ring->isParked()) names that whole-ring state in one call. The same parked state must stay inert in key routing: a consumer dispatching shortcuts off current() checks isEnabled() there too, not only at paint time.

Pair the paint with a non-color cue. An accent border is invisible to users who cannot distinguish the hue, so examples/focus-ring.php prints a text status row per panel as well — > FOCUS, > parked, idle, off — and a footer naming the focused region (WCAG 1.4.1 Use of Color; border strength itself under 1.4.11 Non-text Contrast).

Behaviour

  • A non-empty ring always has exactly one focused region; an empty ring focuses nothing (current() is null, index() is -1).
  • register() appends to the traversal order and focuses the region only when the ring was empty; re-registering an existing id is a no-op.
  • unregister() keeps focus on the same region where possible; removing the focused region lands focus on the nearest enabled survivor at or after the vacated slot — the slot is first clamped to the new end, so removing the focused tail lands on the new tail rather than wrapping to the head, and the wrap reaches the earliest enabled survivor only when every survivor ahead of the slot is disabled. With nothing enabled left, focus parks on the clamped slot itself; emptying the ring clears focus.
  • next() / previous() wrap around and are no-ops with fewer than two enabled regions — with one exception: focus parked on a disabled region beats the no-op and moves to the nearest enabled survivor in that direction.
  • reorder() replaces the traversal order in one step: ids are deduped (first wins), focus stays on the current region if it survives (otherwise focus lands on the first enabled survivor — index 0 only when every survivor is disabled), new ids are added and missing ids dropped.
  • Immutable — every mutator returns a new FocusRing and leaves the receiver untouched, so it slots into the immutable-model architecture. No-op calls (registering an existing id, focusing an unknown, disabled or already-focused id, traversal with nowhere to go, reordering an empty ring to an empty set…) return the same instance, so $new === $old cheaply detects "nothing changed".

Disabled regions

  • disable() keeps a region registered but makes next() / previous() skip it; enable() puts it back. Both are no-ops for unknown ids or ids already in that state.
  • Disabling the focused region does not move focus — current() still names it. The following next() or previous() call moves focus to the nearest enabled region in that direction — even a sole enabled survivor.
  • focus() refuses a disabled id: it is a no-op, just like focusing an unknown or already-focused region. Restore order relies on this — focus first, then re-apply the disabled flags (see the persistence recipe below).
  • Once focus sits on the only enabled region, next() / previous() are no-ops; with every region disabled they are no-ops too.
  • Paint the accent with isFocused($id) && isEnabled($id). Focus can legally park on a disabled region — disable() never moves it, and unregister() lands on the vacated slot when every survivor is disabled — so isFocused() alone can highlight a dimmed panel. For the ring as a whole the same fact is if ($ring->isParked()); the per-id pair remains the test when painting many regions at once.
  • register() always adds an enabled region (a re-registered id was unregistered first, so it comes back enabled by construction). unregister() clears the removed id's flag, and reorder() keeps flags only for ids that survive — so a region dropped while disabled and later re-added comes back enabled.
  • Three refusal grammars, never mixed. Malformed ids at CONSTRUCTION (ofStrict() duplicates, restore() non-string id lists) throw — a programmer error named loudly. Steady-state mutations answer their own receiver as a silent no-op when there is nothing to move (focus() onto a disabled id, next() with one enabled region). When a caller wants to branch, ask: canFocus() / tryFocus() return the honest false/null for every refusal, so "nothing moved" stops being detected by identity comparison.

Iteration, counting and persistence

  • FocusRing implements IteratorAggregate, Countable and JsonSerializable: foreach ($ring as $id) walks every registered id (disabled ones included) in traversal order, count($ring) is the number of registered regions, and json_encode($ring) produces {"ids":[…],"focused":…,"index":n,"disabled":[…]}.
  • The snapshot's disabled list is in traversal order and always holds strings, numeric ids such as "1" included. focused names the id directly (drift-proof against reordering) while index rides along for readers of older snapshots. Restore from a file with fromJson(), the inverse of json_encode():
$ring = FocusRing::fromJson($json)
    ?? FocusRing::of('sidebar', 'grid', 'filter');  // unreadable file: rebuild defaults

For an array payload, restore() prefers the focused id over the positional leg when both are present, and an unknown focused id lands on the first region — the first enabled one, or index 0 when every region is disabled — the index leg is consulted only when the focus leg is absent or not a string, and then clamped into the surviving ring rather than trusted (a legacy session file from before a layout change cannot crash startup). It drops disabled entries for regions that no longer exist and still loads legacy positional-only snapshots — which carry no disabled key, so everything in them comes back enabled. Malformed ids throw InvalidArgumentException; everything else in the array payload degrades fail-soft. Entry comparison is string-on-string: a hand-edited numeric 1 in disabled never matches the id "1", so that region comes back enabled — ids in the list must be JSON strings. Note the parameter is typed array: a corrupt file whose json_decode() yields null or a string is a caller-side is_array guard away — restore() itself never sees it. That guard is fromJson(): decode-rot answers null, and the demo's s/r keys run the round trip live on the running ring — the disabled set included, so r after s restores exactly what x had parked.

The ring never sanitises ids for you, and snapshot data is the one input you do not control: a restored id is whatever the file said. Ids flow to current() verbatim — the demo prints current() raw in its footer — so any id you paint must first pass through your terminal-sanitisation layer. The sugar-core companion has exactly these helpers: SugarCraft\Core\Util\Sanitize::untrusted() for plain output, and untrustedForMarkedFrames() when frames carry sugar-mouse zones. A restored string holding the U+E000/U+E001 zone sentinels would otherwise forge a mouse zone at paint time.

Modals and focus traps

A modal dialog is just more regions, and the trap is the disabled set. FocusTrap owns that ritual, holding its own saved id and background list, so release 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, dialog gone, focus restored

release() re-enables the background, unregisters the dialog ids, then restores focus to the saved region when it is still enabled, else the first enabled one (empty ring or parked-at-open). guarding() throws on an id that is already registered.

current() is null when nothing was focused — a dialog opened over an empty ring must restore via focusFirst() (or accept where unregister() landed), never by handing null to the string parameter of focus().

Mind the edges: unregister() of the focused region lands on the nearest enabled survivor, so bring the background back before removing the dialog when you want the saved region exactly; and reorder() drops the disabled flags of any id it removes — rebuilding background order through reorder() deliberately clears stale state, re-disable afterwards if the panels were meant to stay out of traversal. FocusTrap encodes the safe order once.

Non-visual access

SGR borders are invisible and inaudible: an Orca-style reader never sees the accent paint, so the ring's state must reach the user as text. Announce current() by name whenever it changes — the demo's footer (● focused: …) is that contract in miniature. For a "region k of n" position, prefer enabledIndex() + 1 over enabledCount() (FocusRing::enabledIndex() / FocusRing::enabledCount()) to the raw index()/count() pair: it reflects what Tab can actually reach. enabledIndex() is null when focus is parked on a disabled region or the ring is empty — announce the region name alone in that case, never position 0. Seen this way the trap recipe above is not a dialog hack but the keyboard-accessibility pattern itself: the disabled set is the focus order (WCAG 2.4.3 Focus Order), and a ring-driven text marker is how focus stays perceivable (2.4.7 Focus Visible).

API

Method Description
FocusRing::new(): self An empty ring.
FocusRing::of(string ...$ids): self A ring of regions (duplicates dropped), focusing the first.
FocusRing::ofStrict(string ...$ids): self Like of(), but throws InvalidArgumentException on a duplicate id.
FocusRing::restore(array $snapshot): self Inverse of jsonSerialize() — clamps stale indices on legacy positional-only snapshots, unknown focused ids land on the first enabled region (index 0 only when every region is disabled), drops unknown disabled entries; a legacy positional-only snapshot has no disabled key, so every region comes back enabled. Takes a decoded array — read JSON strings through fromJson() instead.
FocusRing::fromJson(string $json): ?self json_decode + restore() with the guard built in: text that does not parse to an array answers null (disk rot — ?? a default ring); parsed-but-structurally-broken ids still throw from restore() (producer bug, not rot).
register(string $id): self Add an enabled region to the end of the order.
unregister(string $id): self Remove a region, preserving focus where possible.
reorder(string ...$ids): self Replace the traversal order, keeping focus on the current id when it survives.
focus(string $id): self Focus a specific registered, enabled region (no-op otherwise).
canFocus(string $id): bool / tryFocus(string $id): ?self The ask-first pair over focus(): canFocus() is true exactly when focus() would move (registered, enabled, not already focused — one bool for all three refusals); tryFocus() returns the moved ring or null when focus would not move.
next(): self / previous(): self Tab / Shift-Tab traversal (wrapping, skipping disabled regions).
nextOf(string $id): ?string / previousOf(string $id): ?string Pure query: the id traversal would land on if focus sat on $id (focus not moved; null for unregistered ids).
peekNext(): ?string / peekPrevious(): ?string The ring-level pair: where next() / previous() would land from the CURRENT focus (focus not moved; null on an empty ring; the no-op shape answers the current id, so peekNext() === current() means Tab would do nothing).
focusFirst(): self / focusLast(): self Jump to the first / last enabled region (no-op when none is enabled).
disable(string $id): self / enable(string $id): self Exclude a region from / restore it to traversal.
isEnabled(string $id): bool Whether $id is registered and not disabled (false conflates unregistered with disabled — use has() to tell them apart).
enabledIds(): list<string> / disabledIds(): list<string> Enabled / disabled ids in traversal order.
enabledCount(): int / disabledCount(): int Enabled / disabled region counts.
current(): ?string The focused region id, or null.
isFocused(string $id): bool Whether $id is the focused region (paint with && isEnabled($id)).
has(string $id): bool Whether $id is registered.
index(): int Focused position into all registered ids, or -1 when empty (enabledIndex() for the "k of n" enabled ordinal).
enabledIndex(): ?int Focused region's 0-based ordinal into enabledIds(), or null when the ring is empty or focus is parked on a disabled region.
ids(): list<string> Registered region ids in traversal order.
count(): int Number of registered regions (Countable, so count($ring) works too).
isEmpty(): bool Whether the ring has no regions.
isParked(): bool Whether focus currently sits on a disabled region (non-empty ring with enabledIndex() null) — the paint/key-routing guard for the focused region in one call; parks happen only via disable()/unregister()/restore().
getIterator(): Traversable<int, string> foreach support — every registered id in traversal order.
jsonSerialize(): array ['ids' => …, 'focused' => …, 'index' => …, 'disabled' => …] snapshot for json_encode(); restore() reads it back.

License

MIT © Joe Huss

Credits & inspiration

The focus ring is an original SugarCraft design — no 1:1 Go counterpart. It plays the role that charmbracelet/bubbles' focus handling plays in its stack, but as a standalone, dependency-free ring, so the attribution above is by analogy only (the Go side; the repo consumers below are real users, not analogies).

Used by: sugar-dashboard's Layout\FocusManager (imports SugarCraft\Focus\FocusRing) and candy-code's Tui\Pane tab cycle — the ring is the shared keyboard-focus primitive under both TUIs.

Runnable example: examples/focus-ring.php — run it with php examples/focus-ring.php; with no TTY it draws one frame and exits 0. The shipped demo lays out for roughly 70 columns or wider; narrower terminals wrap the panel rows, and the full repaint means the next keystroke self-heals the frame.

Demo note (2026-11-13): a looping terminal capture — it clears and repaints the frame each loop, so it may flicker on some displays.

sugar-focus demo