All 42 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 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 current() returns 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. Original SugarCraft component.

Install

composer require sugarcraft/sugar-focus

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

Wire it into a sugar-core model's update(), then let each region style itself in view():

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

// …in update():
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];
}

// …and in view():
$style = $ring->isFocused('sidebar') && $ring->isEnabled('sidebar')
    ? $accentBorder : $plainBorder;

On the wire, Shift+Tab arrives as Tab with shift: true — sugar-core's InputReader decodes ESC [ Z (CSI-Z, the literal "Backtab" sequence) 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 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 and moves the ring like a plain Tab would. The isEnabled() conjunct in the paint matters: focus can legally park on a disabled region, so isFocused() alone can accent a dimmed panel.

Behavior

Exactly one focused regionA non-empty ring always has exactly one focused region; an empty ring focuses nothing (current() is null, index() is -1).
register() appendsAdds to the traversal order and focuses the region only when the ring was empty; re-registering an existing id is a no-op.
unregister() lands enabledKeeps 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 is disabled. With nothing enabled left, focus parks on the clamped slot itself; emptying the ring clears focus.
Wrap-around traversalnext() / previous() wrap past the ends 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() in one stepReplaces the traversal order: ids are deduped (first wins), focus stays on the current region if it survives — otherwise it lands on the first enabled survivor, index 0 only when every survivor is disabled. New ids are added and missing ids dropped; reordering an empty ring to an empty set is a no-op (replacing a non-empty ring with an empty set empties it rather than no-opping).
Disabled regionsdisable() keeps a region registered but makes traversal skip it; enable() puts it back. Disabling the focused region does not move focus — the next next() / previous() carries it to the nearest enabled region in that direction, even a sole enabled survivor. focus() refuses a disabled id (no-op) so it cannot teleport past that wall — snapshot restore focuses the id before re-applying its disabled flag. A region dropped while disabled comes back enabled.
Iterable, countable, serializableImplements IteratorAggregate, Countable and JsonSerializable: foreach walks every registered id, count($ring) counts them, json_encode($ring) gives {"ids":[…],"focused":…,"index":n,"disabled":[…]}, and FocusRing::restore() rebuilds the ring — preferring the focused id over the positional leg, an unknown focused id landing on the first region, clamping stale indices on legacy positional-only snapshots, and dropping unknown disabled entries. Legacy positional-only snapshots carry no disabled key, so everything comes back enabled.
Pure queriesnextOf() / previousOf() answer where traversal would land from an id without moving focus; focusFirst() / focusLast() jump to the first / last enabled region; enabledIndex() is the focused region's ordinal among enabled ids (null while parked or empty).
Modals and focus trapsNo layer concept: a dialog is just another region and the trap is the disabled set — register it, disable the background, and on close re-enable the background before dropping the dialog and restoring the saved region. The README carries the full recipe and its edges.
ImmutableEvery mutator returns a new FocusRing and leaves the receiver untouched, so it slots into the immutable Model–Update–View pattern. No-op calls return the same instance, so $new === $old cheaply detects "nothing changed".
Dependency-freeNo rendering or key decoding of its own — the owning model wires keys to it and reads isFocused() when drawing. Composes with any sugar-core model.

Use it for

  • Full-window TUI layouts — track which panel (sidebar, content grid, filter bar) currently owns keyboard focus.
  • Tab / Shift-Tab traversal — wrap-around movement across an ordered set of regions, decoupled from key decoding.
  • Accent-border styling — read isFocused() together with isEnabled() in view() to highlight the focused region.
  • Immutable models — drop the ring into your Model state; every mutator returns a fresh instance.

Source & demos

sugar-focus demo

Try the quickstart →

API

ClassMethodDescription
FocusRingnew(): selfAn empty ring with nothing registered or focused
FocusRingof(string ...$ids): selfA ring of regions (duplicates dropped), focusing the first
FocusRingofStrict(string ...$ids): selfLike of(), but throws InvalidArgumentException on a duplicate id
FocusRingrestore(array $snapshot): selfInverse of jsonSerialize() — clamps stale indices on legacy positional-only snapshots, unknown focused ids land on the first region, drops unknown disabled entries, and legacy positional-only snapshots carry no disabled key so everything comes back enabled; takes a decoded array (guard json_decode with is_array)
FocusRingregister(string $id): selfAdd an enabled region to the end of the traversal order
FocusRingunregister(string $id): selfRemove a region, preserving focus where possible
FocusRingreorder(string ...$ids): selfReplace the traversal order, keeping focus on the current id when it survives
FocusRingfocus(string $id): selfFocus a specific registered, enabled region (no-op for unknown, disabled or already-focused ids)
FocusRingnext(): selfTab traversal — move to the next enabled region (wrapping)
FocusRingprevious(): selfShift-Tab traversal — move to the previous enabled region (wrapping)
FocusRingnextOf(string $id): ?string / previousOf(string $id): ?stringPure query: the id traversal would land on if focus sat on $id (focus not moved; null for unregistered ids)
FocusRingfocusFirst(): self / focusLast(): selfJump to the first / last enabled region (no-op when none is enabled)
FocusRingdisable(string $id): self / enable(string $id): selfExclude a region from / restore it to traversal; no-ops for unknown ids or ids already in that state
FocusRingisEnabled(string $id): boolWhether $id is registered and not disabled (false conflates unregistered with disabled — use has() to tell them apart)
FocusRingenabledIds(): list<string> / disabledIds(): list<string>Enabled / disabled ids in traversal order
FocusRingenabledCount(): int / disabledCount(): intEnabled / disabled region counts
FocusRingcurrent(): ?stringThe focused region id, or null when empty
FocusRingisFocused(string $id): boolWhether $id is the focused region (paint with && isEnabled($id))
FocusRinghas(string $id): boolWhether $id is registered
FocusRingindex(): intFocused position into all registered ids, or -1 when empty (enabledIndex() for the "k of n" enabled ordinal)
FocusRingenabledIndex(): ?intFocused region's 0-based ordinal into enabledIds(), or null when the ring is empty or focus is parked on a disabled region
FocusRingids(): list<string>Registered region ids in traversal order
FocusRingcount(): intNumber of registered regions (Countable, so count($ring) works too)
FocusRingisEmpty(): boolWhether the ring has no regions
FocusRinggetIterator(): Traversable<int, string>foreach support — every registered id (disabled ones included) in traversal order
FocusRingjsonSerialize(): array['ids' => …, 'focused' => …, 'index' => …, 'disabled' => …] snapshot for json_encode(); restore() reads it back