All 48 libraries

SugarNavstack

Navigation breadcrumbs for terminal UIs

inspired by KevM/bubbleo navigationbreadcrumbrouting

SugarNavstack code coverage

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.

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

MethodDescription
new() / new NavStack()Empty stack. Both forms work, and the class has no explicit constructor
push(string $title, mixed $data = null): selfPush 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(): intMutation counter. A breadcrumb hit is refused when its stack generation no longer matches
safeTitle(string $title): stringThe 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): selfNew stack whose items match $term by Unicode case-folded substring over the title and scalar payloads. Indices renumber. filter() is a deprecated forwarder
MethodDescription
new() / render(NavStack $stack): stringCreate the renderer / paint the stack as one row
renderTitles(array $titles): stringRender 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(): ?intMark 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(): ?ScannerAttach a sugar-mouse scanner for click zones / read it back
scan(string $rendered, int $viewportWidth, int $row = 1): selfRecord 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): ?NavigationItemRaw zone lookup / the clicked stack item, or null on a miss. Throws LogicException when the stack is not the generation the breadcrumb rendered
visibleIndices(): arrayStack indices that survived the last render's truncation
elisionSpan(): ?array[start, end, row] of the painted … marker, or null

Shell, Url, NavigationItem and Escape

ClassMethodDescription
Shellnew(?Breadcrumb), withPush, withPop, withPopTo, withDirectory, withBreadcrumb, renderBreadcrumb()Immutable facade. Each with*() returns a new shell. withBreadcrumb() deliberately shares a renderer
Urlderive(NavStack): string, deriveTo(NavStack, int $index): string, parse(string $path): NavStackPercent-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)
Escapetitle(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.

MethodSummary
static new(): selfAdapted from KevM/bubbleo Breadcrumb — the upstream constructor takes the navstack model; this port's renderer is stack-free until render.
setSeparator(string $s): selfSet the string drawn between crumbs (and folded into each zone's click region except after the last crumb).
setTruncator(string $s): selfSet the elision marker shown in place of dropped leftmost crumbs.
setEmptyLabel(string $label): selfLabel painted when the stack is empty (NS-15).
setMaxWidth(int $w): selfHard cap on rendered cell width; 0 disables the cap.
setZonePrefix(string $prefix): selfRename 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): selfCustom 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): selfAttach a Scanner for mouse-click hit-testing.
scanner(): ?ScannerThe 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): selfFeed 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): ?ZoneReturn the zone at the given ABSOLUTE terminal coordinate, or null if no crumb zone contains that cell.
hitItem(NavStack $stack, int $col, int $row): ?NavigationItemResolve an ABSOLUTE terminal coordinate straight to the stack item whose crumb zone contains it — the one-call click dispatcher.
visibleIndices(): arrayStack 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): selfMark which crumb the item renderer should style as selected (NS-16).
focusedIndex(): ?intThe 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(): ?arrayThe 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): stringRender the current navigation stack as a breadcrumb string.
renderTitles(array $titles): stringRender a custom list of titles (not from a NavStack).

Closable interface

Interface for navigation items that respond to enter/leave lifecycle events.

MethodSummary
onEnter(): voidCalled when this item becomes the current/active item.
onLeave(): voidCalled when this item is no longer the current item.
title(): stringReturns the item's title.

Escape final class

Separator escaping for navigation item titles.

MethodSummary
static title(string $title, string $separator = self::DEFAULT_SEPARATOR): stringEscape 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): stringReverse 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.

MethodSummary
static new(): selfMirrors KevM/bubbleo NavStack (Go); the upstream constructor takes a window model (research §2.4) — this port's is dependency-free.
generation(): intThe 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): selfPush a new navigation item onto the stack.
pop(): ?NavigationItemPop the topmost item off the stack and return it. Returns null if the stack is empty.
canPop(): boolCan the stack pop without going empty?
popTo(int $index): selfTruncate the stack to the item at $index (inclusive), removing everything newer. The item at position $index becomes the top.
popToRoot(): selfKeep 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(): ?NavigationItemPeek at the top item without removing it.
parent(): ?NavigationItemPeek at the item below the top.
depth(): intCurrent stack depth (number of items).
isEmpty(): boolIs the stack empty?
items(): arrayGet all items as a list.
updateTop(mixed $data): selfReplace 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(): selfClear the stack completely.
setItems(array $items): selfReplace all items at once (used by Shell for immutable operations).
static safeTitle(string $title): stringPUBLIC 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): stringRender the navigation stack as a breadcrumb string. e.g. "Home › Settings › Display"
viewHtml(?callable $href = null, string $label = 'Breadcrumb', ?array $allowSchemes = null): stringRender the stack as semantic HTML breadcrumb.
filtered(string $term): selfFilter 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.

MethodSummary
__construct(public readonly string $title, public readonly mixed $data = null)
onEnter(): voidContract 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(): voidContract default from Closable: a no-op. See onEnter() for who dispatches.
title(): stringReturns the item's title.

Shell final class

Shell — combines NavStack + Breadcrumb into a single navigation component.

MethodSummary
__construct(public readonly NavStack $stack, public readonly Breadcrumb $breadcrumb)
static new(?Breadcrumb $breadcrumb = null): self
withPush(string $title, mixed $data = null): selfPush a new navigation item and return a new Shell.
withPop(): selfPop the top item and return a new Shell.
withPopTo(int $index): selfTruncate 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): selfParse 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.

MethodSummary
static derive(NavStack $stack): stringDerive 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): stringDerive the ancestor-prefix path up to AND INCLUDING stack index $index: the first $index+1 crumbs of derive()'s output.
static parse(string $path): NavStackParse 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.

OptionTypeDefaultEffect
NavStack::SEPARATORstring' › 'Separator used by view() and the breadcrumb default
NavStack::TRUNCATORstring'… 'Elision marker used by the breadcrumb default
NavStack::MAX_STACK_DEPTHint10000Refuses push() past this depth
NavigationItem::MAX_TITLE_BYTESint65536Refuses titles longer than this in raw bytes
Breadcrumb::setMaxWidth()int0Width 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.php drives a stack through push(), depth(), current(), parent() and items(). It then renders the trail with the default separator, a custom separator and a width-20 cap that elides the oldest crumb. Run it with php examples/basic.php.
  • examples/navigation.php walks a push, pop and back flow, shows the filtered view, adds a Shell directory trail, and demonstrates the focus callback. Run it with php examples/navigation.php.
  • examples/mouse.php is 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 to popTo() indices, and checks that the elision marker is not navigation. Run it with php 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 screensNavStack, with push(), pop() and popTo()
Breadcrumb trailBreadcrumb with width-capped elision and per-item renderers
Closable screen lifecycleClosable vocabulary. The library never dispatches the hooks; the host does
Not ported as-isClick 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.

  • sugar-mouse: the Scanner that records click zones and Scan::strip().
  • sugar-dashboard: a host whose navigation components render this kind of state.
  • sugar-core: the Model and runtime a TUI host runs on.

Try the quickstart →

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.

Terminal recording: a scripted back-navigation walk — Home, Settings, and Display pushed, then popped one by one while the trail shrinks.

Push / pop / back

NavStack push / pop / back through nested screens.
Terminal recording: the Home Settings Display trail rendered plain, with a custom greater-than separator, and elided to a width-20 cap.

Basic crumb trail

Render a Home › Settings › Display crumb trail — default and custom separators, and width-capped left-elision.