SugarNavstack
Navigation breadcrumbs for terminal UIs
sugar-navstack is the navigation state behind a breadcrumb trail: a stack of titled items, a renderer that elides the oldest crumbs to fit a width, and click zones that map a terminal cell back to a stack position. It renders nothing by itself beyond plain text and accessible HTML, so a host decides how the trail looks. It mirrors KevM/bubbleo (Go) in shape; the code is native PHP.
Install
composer require sugarcraft/sugar-navstack
Packagist serves this package from dev-master only, with no tagged release yet. Require it with a root minimum-stability: "dev" and prefer-stable: true, the SugarCraft-wide convention, or pin "sugarcraft/sugar-navstack": "dev-master". Requires PHP 8.3 or newer and ext-mbstring. Click zones depend on sugarcraft/sugar-mouse, which Composer installs with it.
Quickstart
push('Home', '/')
->push('Settings', '/settings')
->push('Display', '/settings/display');
echo $nav->view(); // Home › Settings › Display
echo $nav->view(' / '); // Home / Settings / Display
$top = $nav->pop(); // NavigationItem: title 'Display', data '/settings/display'
echo $nav->depth(); // 2
The payload argument is opaque to the library. It travels with the item and comes back on pop(), current() and items(), so a host can store a route, a screen object or an id there.
Concepts
The model has three layers. NavStack owns the ordered items and a generation counter that changes on every mutation. Breadcrumb turns a stack into a painted row, elides the oldest crumbs when a width cap applies, and optionally records a click zone for each visible crumb. Shell pairs a stack with a breadcrumb through immutable operations, for hosts that prefer value semantics.
Titles are untrusted by default. Every title passes through the same display sweep before it reaches output: terminal escapes, control bytes and the library's own zone sentinels are removed, and a title that is empty after that sweep is refused. Payloads are never rendered, so they are safe to carry arbitrary data.
NavStack is the navigation-state model, not a UI. The README records zero in-repo consumers today. sugar-dashboard's navigation components are the intended kind of host, rendering this kind of state.
Tasks
Track a menu path and go back
$nav = NavStack::new()->push('Home', 'home');
$nav->push('Settings', 'settings');
$nav->push('Display', 'display');
$back = $nav->canPop() ? $nav->pop() : null; // removes Display
$nav->popToRoot(); // back to Home only
echo $nav->view(); // Home
pop() returns null only on an empty stack. canPop() is true only when a pop leaves a non-empty stack, so it is false at depth 1 even though pop() still returns the root and empties the stack. To pop whatever is on top, check isEmpty() instead.
Render an accessible HTML trail with links
use SugarCraft\NavStack\{NavStack, Url};
$stack = NavStack::new()->push('Home')->push('My Settings');
echo $stack->viewHtml(
href: static fn ($item, int $i): ?string => Url::deriveTo($stack, $i),
label: 'Breadcrumb',
allowSchemes: ['/', 'https'],
);
viewHtml() emits nav[aria-label] around an ol, with aria-current="page" on the last crumb. Each ancestor becomes an anchor when the callback returns a string, and stays plain text when it returns null. $allowSchemes gates the URLs the callback returns, and rejected ones render as plain text. The '/' entry admits scheme-less paths such as Url::deriveTo() output, so leave it out and every relative link renders as plain text. The first crumb of the example therefore becomes an anchor to /Home.
Make crumbs clickable with mouse zones
use SugarCraft\Mouse\{Scan, Scanner};
use SugarCraft\NavStack\Breadcrumb;
$bc = Breadcrumb::new()->withScanner(Scanner::new())->setMaxWidth(40);
$rendered = $bc->render($stack);
$bc->scan($rendered, viewportWidth: 80, row: 1); // scan the untouched output
echo Scan::strip($rendered), "\n"; // strip before painting
// On a click at ($col, 1):
$item = $bc->hitItem($stack, $col, 1);
if ($item !== null) {
$stack->popTo(array_search($item, $stack->items(), true));
}
The order matters. Scan the output from render() untouched, then strip it for display, or the zone sentinels appear as garbage cells. Zone ids carry the stack index, so a click still resolves after elision has hidden the oldest crumbs. Re-scan after every render. A click on the … marker returns null from hitItem(), and elisionSpan() reports where the marker sits if the host wants to treat it as an expansion gesture.
Keep a deep trail readable in a narrow bar
$bc = Breadcrumb::new()
->setMaxWidth(24)
->setTruncator('[more] ')
->setItemRenderer(static fn ($item, int $i, bool $focused = false): ?string
=> $focused ? '[' . $item->title . ']' : null); // null keeps the default
$bc->setFocusedIndex($selected);
echo $bc->render($stack);
setMaxWidth() elides the oldest crumbs first. setTruncator() replaces the default …, which helps screen readers. A custom item renderer returns null for crumbs it does not style, and its strings are emitted raw, so do not put untrusted text in them. setFocusedIndex() is intent only. Read focusedIndex() afterwards to see whether the selected crumb survived the width math.
Track a directory trail
use SugarCraft\NavStack\Shell;
$shell = Shell::new();
$shell = $shell->withDirectory('/home/user/projects/sugarcraft/src');
echo $shell->renderBreadcrumb();
Shell never watches the filesystem. The host detects a directory change and calls withDirectory(), which appends the path's segments to the current trail rather than replacing it. To start a fresh trail at a new location, build it from Shell::new(), as in Shell::new()->withDirectory($path). pushDirectory() still works as a deprecated forwarder. Every with*() returns a new Shell. All of them except withBreadcrumb() give the derived shell its own copy of the breadcrumb renderer. withBreadcrumb() keeps the instance you pass, so later changes to that renderer show through.
API reference
NavStack
| Method | Description |
|---|---|
new() / new NavStack() | Empty stack. Both forms work, and the class has no explicit constructor |
push(string $title, mixed $data = null): self | Push an item and return the same stack. Refuses titles that are empty after sanitizing, and growth past MAX_STACK_DEPTH (10000) |
pop(): ?NavigationItem / popTo(int $index) / popToRoot() | Remove the top item / truncate so the item at $index is the top / keep only the root. popTo() refuses negative indices |
current() / parent() / depth() / canPop() / isEmpty() | Top item / the item below it / item count / whether a pop leaves a non-empty stack (depth above 1) / whether the stack is empty |
items(): array / updateTop(mixed $data) | All items, bottom first / replace the top item's payload |
setItems(array $items) / clear() | Replace the whole stack / empty it |
generation(): int | Mutation counter. A breadcrumb hit is refused when its stack generation no longer matches |
safeTitle(string $title): string | The display sweep, exposed so a host can sanitize a title before pushing it |
view(string $separator = ' › ') | Plain-text trail. Titles are sanitized. CR, LF and terminal escapes in the separator throw |
viewHtml(?callable $href, string $label = 'Breadcrumb', ?array $allowSchemes) | Accessible HTML landmark. $href receives (NavigationItem, index) |
filtered(string $term): self | New stack whose items match $term by Unicode case-folded substring over the title and scalar payloads. Indices renumber. filter() is a deprecated forwarder |
Breadcrumb
| Method | Description |
|---|---|
new() / render(NavStack $stack): string | Create the renderer / paint the stack as one row |
renderTitles(array $titles): string | Render a pre-filtered title list instead of a stack. Each title is capped the same way a constructed item is |
setSeparator(string) / setTruncator(string) / setEmptyLabel(string) | Between-crumb separator (CR and LF refused) / elision marker (default …) / label painted at depth 0 |
setMaxWidth(int) | Width cap. Oldest crumbs elide first. 0 disables the cap, and a negative value throws |
setItemRenderer(\Closure) | fn(NavigationItem, int $index, bool $focused): ?string. null falls back to the default |
setFocusedIndex(?int) / focusedIndex(): ?int | Mark a crumb as selected / the index the last render actually reflected |
setZonePrefix(string) | Rename the crumb- zone id prefix, so merged dispatch tables stay unambiguous |
withScanner(?Scanner) / scanner(): ?Scanner | Attach a sugar-mouse scanner for click zones / read it back |
scan(string $rendered, int $viewportWidth, int $row = 1): self | Record zones for a rendered row. The viewport width is required, and zones clamp to it |
hit(int $col, int $row): ?Zone / hitItem(NavStack $stack, int $col, int $row): ?NavigationItem | Raw zone lookup / the clicked stack item, or null on a miss. Throws LogicException when the stack is not the generation the breadcrumb rendered |
visibleIndices(): array | Stack indices that survived the last render's truncation |
elisionSpan(): ?array | [start, end, row] of the painted … marker, or null |
Shell, Url, NavigationItem and Escape
| Class | Method | Description |
|---|---|---|
| Shell | new(?Breadcrumb), withPush, withPop, withPopTo, withDirectory, withBreadcrumb, renderBreadcrumb() | Immutable facade. Each with*() returns a new shell. withBreadcrumb() deliberately shares a renderer |
| Url | derive(NavStack): string, deriveTo(NavStack, int $index): string, parse(string $path): NavStack | Percent-encoded path from the trail / the prefix up to and including $index / a stack built from path segments. Titles only; payloads do not travel |
| NavigationItem | __construct(string $title, mixed $data = null), title() | One stack entry. Refuses titles over MAX_TITLE_BYTES (65536 raw bytes) |
| Escape | title(string, separator), unescape(string, separator) | Escape a title for the crumb stream, so a separator inside it cannot split it, and reverse that with unescape(). Use it when a trail is stored as one string |
Only methods declared in sugar-navstack/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\NavStack
Breadcrumb final class
Renders a NavStack as a breadcrumb string.
| Method | Summary |
|---|---|
static new(): self | Adapted from KevM/bubbleo Breadcrumb — the upstream constructor takes the navstack model; this port's renderer is stack-free until render. |
setSeparator(string $s): self | Set the string drawn between crumbs (and folded into each zone's click region except after the last crumb). |
setTruncator(string $s): self | Set the elision marker shown in place of dropped leftmost crumbs. |
setEmptyLabel(string $label): self | Label painted when the stack is empty (NS-15). |
setMaxWidth(int $w): self | Hard cap on rendered cell width; 0 disables the cap. |
setZonePrefix(string $prefix): self | Rename the per-crumb zone id prefix (default crumb, ids crumb-{stackIndex}). Note that withScanner() CLONES the Scanner, so two breadcrumb widgets can never share one scanner instance; the prefix serves the reachable multi-widget shape instead — a host merging the zone enumerations (or one dispatch table) of several breadcrumbs, each with its own scanner, keeps crumb-2 unambiguous across the combined view. |
setItemRenderer(\Closure $fn): self | Custom per-item renderer. The closure MUST return string|null: fn(NavigationItem $item, int $index, bool $focused): ?string. Return null to fall back to the default (sanitized) title rendering. |
withScanner(?Scanner $scanner): self | Attach a Scanner for mouse-click hit-testing. |
scanner(): ?Scanner | The scanner owned by this breadcrumb (as copied in by withScanner()), or null when click tracking is disabled. |
scan(string $rendered, int $viewportWidth, int $row = 1): self | Feed a rendered breadcrumb string to the internal scanner so that subsequent hit-testing can determine which crumb zone contains a given coordinate pair. |
hit(int $col, int $row): ?Zone | Return the zone at the given ABSOLUTE terminal coordinate, or null if no crumb zone contains that cell. |
hitItem(NavStack $stack, int $col, int $row): ?NavigationItem | Resolve an ABSOLUTE terminal coordinate straight to the stack item whose crumb zone contains it — the one-call click dispatcher. |
visibleIndices(): array | Stack indices made visible by the most recent render (empty before the first render, and after a render of an empty stack). When setMaxWidth() elides older crumbs, these are the survivors' true positions — exactly the indices zone ids carry. Positions are meaningful ONLY for the stack that render() consumed — filtered() renumbers, and hitItem() refuses dispatches against a different stack or a since-mutated generation (NS-08). |
setFocusedIndex(?int $index): self | Mark which crumb the item renderer should style as selected (NS-16). |
focusedIndex(): ?int | The focus the most recent render reflected: the raw intent when it survived into the visible set, otherwise null (NS-16). Renders without a stack (renderTitles(), empty renders) never carry focus. |
elisionSpan(): ?array | The terminal cells the left-elision marker occupies on the CURRENT scanned render, as [start, end, row] (1-based, absolute — same coordinate space as hit()), or null when there is nothing to bind (NS-21). |
render(NavStack $stack): string | Render the current navigation stack as a breadcrumb string. |
renderTitles(array $titles): string | Render a custom list of titles (not from a NavStack). |
Closable interface
Interface for navigation items that respond to enter/leave lifecycle events.
| Method | Summary |
|---|---|
onEnter(): void | Called when this item becomes the current/active item. |
onLeave(): void | Called when this item is no longer the current item. |
title(): string | Returns the item's title. |
Escape final class
Separator escaping for navigation item titles.
| Method | Summary |
|---|---|
static title(string $title, string $separator = self::DEFAULT_SEPARATOR): string | Escape a title so it can safely appear in a breadcrumb render. If the title contains $separator, prefix each occurrence with a backslash. |
static unescape(string $title, string $separator = self::DEFAULT_SEPARATOR): string | Reverse title(). Pass the SAME $separator that was used to escape. |
Lang final class
Per-library translation facade for sugar-navstack.
NavStack final class
Navigation stack — last-in, first-out navigation state.
| Method | Summary |
|---|---|
static new(): self | Mirrors KevM/bubbleo NavStack (Go); the upstream constructor takes a window model (research §2.4) — this port's is dependency-free. |
generation(): int | The mutation ledger of this exact stack object. Compare against the value a breadcrumb stamped at render time (see Breadcrumb::hitItem()'s cross-generation refusal); a fresh filtered() copy deliberately carries parent+1 so original/filtered confusion is caught on both axes (identity AND count). |
push(string $title, mixed $data = null): self | Push a new navigation item onto the stack. |
pop(): ?NavigationItem | Pop the topmost item off the stack and return it. Returns null if the stack is empty. |
canPop(): bool | Can the stack pop without going empty? |
popTo(int $index): self | Truncate the stack to the item at $index (inclusive), removing everything newer. The item at position $index becomes the top. |
popToRoot(): self | Keep ONLY the root item (spelled intent for what a negative popTo used to silently do — wipe the stack from a 1-based off-by-one). On an empty stack this is a no-op. |
current(): ?NavigationItem | Peek at the top item without removing it. |
parent(): ?NavigationItem | Peek at the item below the top. |
depth(): int | Current stack depth (number of items). |
isEmpty(): bool | Is the stack empty? |
items(): array | Get all items as a list. |
updateTop(mixed $data): self | Replace the TOP ITEM: a fresh NavigationItem carrying the same title with new data (titles are readonly, so the item object itself is swapped — identity checks on the previous top stop matching). Does nothing if stack is empty. |
clear(): self | Clear the stack completely. |
setItems(array $items): self | Replace all items at once (used by Shell for immutable operations). |
static safeTitle(string $title): string | PUBLIC display facade for a raw title: the byte-identical sweep that view(), viewHtml(), Breadcrumb::render() and Breadcrumb::renderTitles() run every stack-sourced title through before emitting it. Hosts echoing an UNTRUSTED title outside those surfaces (a <title> tag, a log line, a custom renderer closure) call this instead of reaching into the internal sanitizer — or, worse, printing the raw accessor output. |
view(string $separator = self::SEPARATOR): string | Render the navigation stack as a breadcrumb string. e.g. "Home › Settings › Display" |
viewHtml(?callable $href = null, string $label = 'Breadcrumb', ?array $allowSchemes = null): string | Render the stack as semantic HTML breadcrumb. |
filtered(string $term): self | Filter items by title or data matching $term (case-insensitive substring). Data is matched when it is scalar or Stringable, or — for array data such as ['route' => '/dash'] — when ANY scalar/Stringable value inside the array matches, at any depth (bounded: see MAX_PAYLOAD_DEPTH below). Returns a new NavStack with only matching items. |
filter(string $term): self |
NavigationItem final class
A single item on the navigation stack.
| Method | Summary |
|---|---|
__construct(public readonly string $title, public readonly mixed $data = null) | |
onEnter(): void | Contract default from Closable: a no-op. Nothing in this library dispatches it — a consumer that wires enter/leave events calls it, and subclasses are impossible (final); implement Closable on your own type instead. |
onLeave(): void | Contract default from Closable: a no-op. See onEnter() for who dispatches. |
title(): string | Returns the item's title. |
Shell final class
Shell — combines NavStack + Breadcrumb into a single navigation component.
| Method | Summary |
|---|---|
__construct(public readonly NavStack $stack, public readonly Breadcrumb $breadcrumb) | |
static new(?Breadcrumb $breadcrumb = null): self | |
withPush(string $title, mixed $data = null): self | Push a new navigation item and return a new Shell. |
withPop(): self | Pop the top item and return a new Shell. |
withPopTo(int $index): self | Truncate the stack to the item at $index (inclusive), removing newer items, and return a new Shell. A negative $index THROWS (see NavStack::popTo()); NavStack::popToRoot() names the keep-only-the-root intent the old silent clamp used to swallow. |
withBreadcrumb(Breadcrumb $breadcrumb): self | |
renderBreadcrumb(): string | |
withDirectory(string $path): self | Parse a directory path and push each segment as a navigation item. e.g. "/home/user/projects" pushes "home", then "user", then "projects" Each segment's data is the full path up to that segment. |
pushDirectory(string $path): self |
Url final class
URL/path derivation utilities for navigation stacks.
| Method | Summary |
|---|---|
static derive(NavStack $stack): string | Derive a URL path string from the navigation stack. e.g. NavStack with items ["home", "settings", "display"] → "/home/settings/display" |
static deriveTo(NavStack $stack, int $index): string | Derive the ancestor-prefix path up to AND INCLUDING stack index $index: the first $index+1 crumbs of derive()'s output. |
static parse(string $path): NavStack | Parse a URL path back into a NavStack. |
Configuration
sugar-navstack has no config file or environment variables. Its behavior is set by the constants and the renderer setters below.
| Option | Type | Default | Effect |
|---|---|---|---|
NavStack::SEPARATOR | string | ' › ' | Separator used by view() and the breadcrumb default |
NavStack::TRUNCATOR | string | '… ' | Elision marker used by the breadcrumb default |
NavStack::MAX_STACK_DEPTH | int | 10000 | Refuses push() past this depth |
NavigationItem::MAX_TITLE_BYTES | int | 65536 | Refuses titles longer than this in raw bytes |
Breadcrumb::setMaxWidth() | int | 0 | Width cap in cells. 0 means no cap |
Filtering and payload walking refuse payloads nested deeper than 64 levels. Guards throw \InvalidArgumentException rather than truncating silently.
Keys and keybindings
sugar-navstack handles no keys. A host maps its own keys to pop(), popTo() and popToRoot(). A keyboard user reaches the same jumps as a mouse user: select a visible index from visibleIndices() and call popTo() on it. An index past the top of the stack is a no-op in popTo(), but a negative index throws \InvalidArgumentException.
Theme and styling
The library emits no ANSI and no motion. The default output is plain text, so styling belongs to the host. Wrap the item renderer's return value with your own Style to color the current crumb, and keep the separator and truncator plain so they stay legible in monochrome terminals.
The glyphs › and … assume a UTF-8 terminal. Under LANG=C or TERM=dumb, switch to ASCII with setSeparator(' > ')->setTruncator('... ').
Examples
examples/basic.phpdrives a stack throughpush(),depth(),current(),parent()anditems(). It then renders the trail with the default separator, a custom separator and a width-20 cap that elides the oldest crumb. Run it withphp examples/basic.php.examples/navigation.phpwalks a push, pop and back flow, shows the filtered view, adds aShelldirectory trail, and demonstrates the focus callback. Run it withphp examples/navigation.php.examples/mouse.phpis the click-zone reference. It renders a four-deep stack in a width-24 bar, prints the cell range of each crumb, dispatches synthetic clicks topopTo()indices, and checks that the elision marker is not navigation. Run it withphp examples/mouse.php.
The examples read vendor/autoload.php, so run them from the library root after composer install.
Testing
cd sugar-navstack
composer install
vendor/bin/phpunit
The suite covers the stack model, HTML output and escaping, URL derivation and parsing, title forgery, depth guards, zone geometry and the Shell facade. AliasesTest resolves the old sugar-crumbs class names to their canonical classes, and LangCoverageTest checks the localization registry against the published constants.
Troubleshooting
A click lands on the wrong crumb after the bar narrows
Hit-testing must use the same stack that was rendered. Zone ids are positions in the rendered stack, so after filtered() they are positions in the filtered stack. Pass that exact stack to hitItem(), and re-scan after every render. If the stack was pushed, popped, or otherwise mutated after the last render, hitItem() throws LogicException instead of returning null. Re-render and re-scan the stack before dispatching a click.
Stray control characters appear in the terminal
The painted row still carries zone sentinels. Strip the output with Scan::strip() before writing it, and keep the unstripped string only for scan().
push() throws for a title that looks valid
A title that is empty after trimming and sanitizing is refused. Sanitizing removes escapes and control bytes, so a title made only of those is refused too. A title over 65536 raw bytes is refused by NavigationItem. Trim and cap titles before pushing them, or call NavStack::safeTitle() to see what the sweep produces.
The separator throws
view() and Breadcrumb::setSeparator() refuse separators that contain CR or LF, and view() refuses terminal escapes. Use a single-line separator.
The focused crumb does not render as focused
setFocusedIndex() is intent. An index beyond the stack, a negative index, or a crumb elided off the left edge reads back as null. Check focusedIndex() after render(), and compare visibleIndices() to confirm the crumb survived the width cap.
Upstream mapping
| KevM/bubbleo (Go) | sugar-navstack (PHP) |
|---|---|
| Navigation stack of screens | NavStack, with push(), pop() and popTo() |
| Breadcrumb trail | Breadcrumb with width-capped elision and per-item renderers |
| Closable screen lifecycle | Closable vocabulary. The library never dispatches the hooks; the host does |
| Not ported as-is | Click zones (sugar-mouse), accessible HTML, URL derivation and the directory Shell are SugarCraft additions |
The port mapping is in docs/MATCHUPS.md.
Architecture
Every mutation on NavStack bumps the generation counter, so a breadcrumb hit recorded against an older stack is refused. Breadcrumb::scan() records zones against the stack indices it rendered. Those zones persist until the next scan(), so a click resolves against the render the user actually saw.
Titles pass through TitleSanitizer::sanitize() before they reach output. Escape handles the separator inside the crumb stream, so a title that contains the separator text survives a round trip only when it is escaped. Payloads are never rendered.
Changelog and versioning
sugar-navstack has no tagged release yet. It is tracked from dev-master, and its history is the commit log of the sugar-navstack/ directory in the monorepo. Read the commit history for changes. The rename of pushDirectory() to withDirectory() and of filter() to filtered() is recorded as a deprecation, and the old names still forward.
Related
- sugar-mouse: the
Scannerthat records click zones andScan::strip(). - sugar-dashboard: a host whose navigation components render this kind of state.
- sugar-core: the
Modeland runtime a TUI host runs on.
Demos.
VHS-recorded GIFs of the basic and navigation examples. The mouse example, the click-zone reference, has a tape but no recording yet. Regenerated automatically on every push that touches the source.
Push / pop / back
NavStack push / pop / back through nested screens.
Basic crumb trail
Render aHome › Settings › Display crumb trail — default and custom separators, and width-capped left-elision.