Search by

sugarcraft / sugar-quickpick

detain

Fuzzy finder / quick-pick overlay for terminal UIs. Wraps a background view, renders a filterable, rankable list overlay on top with borders and styles, background continues to update underneath. JSONL-backed selection history. Inspired by Genekkion/theHermit (Go); developed as a native PHP project.

Package info

github.com/sugarcraft/sugar-quickpick

Documentation

pkg:composer/sugarcraft/sugar-quickpick

Statistics

Installs: 2 312

Dependents: 3

Suggesters: 0

Stars: 0

Open Issues: 0

dev-master 2026-11-16 17:46 UTC

This package is auto-updated.

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


README

sugar-quickpick

CI codecov Packagist Version License PHP

SugarQuickpick

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

sugar-quickpick — a fuzzy finder / quick-pick overlay for terminal UIs (PHP 8.3+). Renders a filterable list overlay on top of a background view while the background continues to update.

Install

composer require sugarcraft/sugar-quickpick

Stability: this package requires its sugarcraft/ siblings at dev-master. A Composer project left on the default stable minimum-stability cannot resolve them — add "minimum-stability": "dev", "prefer-stable": true to the consuming root (or pin the released sugarcraft/* tags once cut). The monorepo publishes all libs together, so sibling versions always line up.

Requirements

  • PHP 8.3+. No hard extension floor. sugarcraft/sugar-pty is a suggested dependency: it supplies SignalForwarder, the automatic SIGWINCH installer used by attachSigwinch(), and it brings an ext-ffi install floor with it. Skip it entirely if you do not want auto-attached resize signals — everything else in the library is pure string rendering. When sugar-pty is absent attachSigwinch() returns false and you drive resizes yourself (see below).
  • ext-pcntl — only for attachSigwinch(), the opt-in SIGWINCH re-render attach. Without it (or without sugar-pty) attachSigwinch() returns false and everything else keeps working. On a resized terminal the auto width then re-probes only when some width-affecting mutation (withPrompt, withItems, type(), …) drops the memoized computed width — or call invalidateAutoWidth() yourself once per resize (one call invalidates the whole clone family; the width holder is shared).
  • A UTF-8 capable terminal — the built-in chrome draws U+2195 ↕ (overflow marker), U+2500 ─ (separator), U+258F ▏ (filter caret) and U+22EF ⋯ (filter-cap overflow); a legacy non-UTF-8 terminal shows them as mojibake. Host-substitutable vs fixed: the cursor bullet (● ) and the ordinal prefix are your withItemFormatter's bytes — pick any ASCII if you must — while the separator, caret and marker live in the lang catalogue (Lang::t('filter_caret'), 'showing_range', …), measured with Width::of() cell maths, and are not re-flowed for narrower locales by the frame arithmetic. The shipped en catalogue is the default chrome text: adding a locale file changes the chrome rows only, never the geometry.

Quick Start — string items

The simplest use case with plain string items:

use SugarCraft\QuickPick\QuickPick;

// Items to filter
$items = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Create the overlay
$h = QuickPick::new($items)
    ->withPrompt('> ')
    ->withItemFormatter(fn($item, $selected) => ($selected ? '*' : ' ') . " $item");

// Show and type to filter
$h = $h->show();
$h = $h->type('ba');  // filter by 'ba'

echo $h->view("background content\nmore background");

// Navigate
$h = $h->cursorDown();
$h = $h->cursorUp();

// Select
$selected = $h->selected();  // ?Item — null when nothing is selected; string inputs are coerced to FilteredItem, each taking its INPUT POSITION as ordinal (rows counted whole: a mixed [Item, 'a'] list numbers 'a' 2, not 1)

// Hide
$h = $h->hide();

Quick Start — numbered items with history

Use the Item interface + FilteredItem for numbered list items and persistent history:

use SugarCraft\QuickPick\QuickPick;
use SugarCraft\QuickPick\FilteredItem;
use SugarCraft\QuickPick\History\FileHistory;

// Create numbered items
$items = [
    new FilteredItem(1, 'apple'),
    new FilteredItem(2, 'banana'),
    new FilteredItem(3, 'cherry'),
];

// Create the overlay with Item[] and a custom filter function
$h = QuickPick::new($items)
    ->withFilterFn(fn($item): bool => $item->number() > 0)  // filter by custom predicate
    ->withPrompt('> ');

// Persist selections to a JSONL file inside your app's own state directory.
// Pick a path you own — never a predictable world-shared location like /tmp.
// FileHistory creates the file, never its parent directories: make the
// directory first, or the first append() throws RuntimeException.
$historyPath = getenv('HOME') . '/.myapp/history.jsonl';
@mkdir(\dirname($historyPath), 0700, true);
$history = new FileHistory($historyPath);
if ($choice = $h->selected()) {   // selected() is ?Item — null when nothing is selected
    $history->append($choice);    // save selected item
}
$allItems = $history->all();      // load previous items — renumbered 1..N by current position

Fuzzy ranking (sugar-fuzzy)

By default the filter is a contiguous, case-folded substring match with an anchor bias: a candidate is kept only when the first match starts in the first half of the item text. The rule is measured in Unicode codepoints, not bytes, so multibyte values (é, 日, emoji) halve where a user would expect. Worked misses: ry does not match cherry (its first hit starts past the midpoint — the accepted window is positions [0, len/2), so a hit beginning exactly at the halfway point is already rejected), and e does not match apple (its first hit is past halfway). When the bias hides matches that plain substring would have kept, the frame says so: a N hidden by anchor bias row counts what the rule dropped. These are deliberate — deep matches are usually noise — and withRanker() is the escape hatch: plug in a sugar-fuzzy ranker to switch to true subsequence matching, ordering the list by descending fuzzy score and highlighting the scored runes. A ranker alone only REORDERS — emphasis is a separate switch: nothing is painted until you also set withMatchStyle() with an SGR string — the example below ships both switches:

use SugarCraft\QuickPick\QuickPick;
use SugarCraft\Fuzzy\Matcher\SmithWatermanMatcher;

// Self-contained corpus: 'terminal' is a t·m·l subsequence, no other item has all three runes.
$items = ['terminal', 'editor', 'compiler'];

// requireFullQuery: true is what makes "no other item has all three runes"
// the rule that runs: by default the matcher also keeps PARTIAL subsequence
// scores, so 'editor' (t) and 'compiler' (m, l) would survive at 'tml' too.
$h = QuickPick::new($items)
    ->withRanker(new SmithWatermanMatcher(requireFullQuery: true))   // or any FuzzyMatcher
    ->withMatchStyle("\e[1m")
    ->show()
    ->type('tml');   // keeps only "terminal"; the default substring filter would miss it

// withRanker(null) restores the default substring filter.

A custom withFilterFn() predicate still applies on top of the ranker.

Features

Feature Description
Fuzzy filtering Filter list items as you type with anchor-aware substring matching, or plug in a sugar-fuzzy ranker via withRanker() for true subsequence scoring
Overlay compositing Background view renders underneath; overlay chars replace background at specified positions
Background continues updating The QuickPick doesn't block the underlying view
Fully styleable Custom filter prompt, item format, matching highlight, window dimensions
String renderer view() returns strings you manage — it never writes to a stream or moves a cursor. The only terminal I/O lives in the width path and is all read-only or opt-in: an STDIN geometry probe on a width-cache miss, the screen-clamp probe every render applies (see withWindowWidth — a width that fits the screen renders identically everywhere), and the attachSigwinch() resize attach (ioctl + pcntl), which you never have to call
Item interface Work with structured Item objects instead of raw strings
Persistent history FileHistory stores items as JSONL for session persistence
Custom filter predicates withFilterFn() lets you filter items by arbitrary criteria
Border & Style composition withBorder() and withStyle() compose sugar-style Border and Style for window decoration
HelpBar / StatusBar withHelpBar() and withStatusBar() attach keyboard-shortcut and status-line renders below the overlay
SIGWINCH resize withOnResize() + attachSigwinch() forwards terminal resize events via SignalForwarder::attachSigwinchToFd
Colorless by design The frame itself emits no color: selection rides the ● cursor dot and position rides plain ordinals — two cues that need no color at all (withItemFormatter() replaces both wholesale). SGR appears only where the host opts in (withMatchStyle(), the item formatter, withStyle()) — and once opted in, those escapes go out unconditionally: honoring NO_COLOR/CLICOLOR is the host's job (skip the opt-ins on dumb terminals)

Architecture

SugarCraft\QuickPick
├── QuickPick           — Fuzzy finder overlay (main class)
├── Lang                — chrome text catalogue (lang/en.php via the core i18n registry)
├── Item                — Interface for filterable items
├── FilteredItem        — Numbered item implementation of Item
├── HelpBar             — Keyboard shortcut summary line
├── StatusBar           — Status message line with optional segments
├── QuickPickHost       — update()/view() composition contract, state in the return tuple
├── Model               — @deprecated alias of QuickPickHost (soft landing)
├── ItemFactory         — string[]/Item[] coercion (used by new()/withItems(); coerced strings take their input position as ordinal)
├── Concerns
│   └── Visible         — show()/hide()/isVisible() shared by HelpBar/StatusBar
├── Support
│   ├── AnsiWalk        — escape-preserving codepoint walker (highlighting)
│   └── UntrustedText   — trust-boundary guard for rendered strings
└── History
    └── FileHistory     — JSONL-backed persistent history

The examples/ directory in the repository is package-internal: it exists to drive the VHS demo tapes and is not shipped as a runnable template.

API — QuickPick factory

// Create with items (string[] or Item[])
public static function new(array $items = [], ?\Closure $itemFormatter = null): self

The raw constructor additionally accepts a third optional ?\Closure $filterFn predicate — a way to seed a custom filter without a fluent call. new() does not expose it; withFilterFn() (configuration below) is the fluent path.

API — QuickPick configuration (fluent setters)

Every set*()/with*() below returns a clone; the receiver is never mutated. Bind the result ($h = $h->withPrompt('> ');) or the change is lost.

// Replace items (string[] or Item[]). The filter text is KEPT and the new
// list is re-filtered with it; the cursor resets to 0.
public function withItems(array $items): self

// Configure the filter prompt
public function withPrompt(string $prompt): self

// Set ANSI SGR codes for matched character highlighting (e.g. "\e[33m")
public function withMatchStyle(string $ansiStyle): self

// Set overlay window height in rows INCLUDING header+separator, so the
// visible item count is height − 2 (clamped to a minimum of 2) — minus one
// more row when the overflow marker is needed. Two chrome states live in
// the item area and consume an item row: the marker `  ↕ showing %d-%d of
// %d` (1-based visible window, on overflow) and, when a non-empty filter
// matches nothing, `  no matches`. Both are pad-only — never intentionally
// truncated — so on a frame narrower than the text they keep their full
// length: over an empty background they spill past where the right border
// would sit, and over a background-backed row the spill pushes that row's
// surviving tail rightward instead of overwriting it. Truncating them to
// the frame width would be a behavior change and is deliberately not done.
// HelpBar and StatusBar rows append BELOW this height. The value is a
// MAXIMUM: each frame also budgets the live terminal's rows — the windowed
// region shrinks to `min(h, rows − reserved chrome)` (border and visible
// help/status rows come off the screen first; a two-row minimum frame is
// the floor), so a tall frozen window never spills past a short terminal
// (-029, shrink-only: growing back recovers up to h, never past it).
public function withWindowHeight(int $h): self

// Set overlay width. 0 (default) = auto: the computed prompt+items width is
// clamped to min(computed, cols) — an auto frame never exceeds the live
// terminal (-059: the old max(20, cols) ceiling wrapped real sub-20-column
// screens; a degenerate zero-width probe is absorbed by the 80-column
// leg of the throw-net instead). Every width-cache miss on the auto path
// PROBES the terminal through sugar-core's Tty ladder: ioctl(TIOCSWINSZ)
// on STDIN, then the COLUMNS/LINES environment, then /dev/tty, then a
// stty shell-out — and the ladder's LAST answer is Backend::LAST_RESORT_SIZE,
// 200×60. A piped run therefore renders at whatever that ladder reports
// (commonly the 200×60 last resort on a headless runner), NOT at a phantom
// 80×24: QuickPick's own 80×24 is the throw-only net, reached when the
// ladder raises or answers a zero dimension. The cache invalidates on every
// mutation that can change the width (filter edits, item/prompt swaps), so
// chained auto-mode builders re-probe per affected operation. A positive
// value is the OUTER width, negative inputs clamp to 0/auto, and it is
// clamped down to the live columns at render time (-027: an over-cols width
// used to compose wrapping rows); a border consumes two of those cells with
// a border-consumed minimum of 3 so the runes are never sliced. That screen
// clamp is the one geometry probe the explicit-width path still runs.
public function withWindowWidth(int $w): self

// Position the overlay at (x, y). Pure placement: visibility is unchanged
// (use show()/hide()), negative coordinates clamp to 0, and the column is
// clamped at compose time so the overlay never starts past the terminal's
// right edge (-063: withOffset(1000, 0) used to emit 1023-cell rows).
public function withOffset(int $x, int $y): self

// Custom item formatter:
//   Closure(string $value, bool $isSelected, int $number): string
// Replaces the built-in default rendering (a '● ' cursor prefix on the
// selected row, 'N. ' ordinals, indent alignment for the rest) ENTIRELY —
// re-render $isSelected/$number yourself if you still want an indicator.
// It always receives the VALUE STRING (never an Item), even for Item objects,
// plus the selection flag and the item's ordinal. Values arrive already
// guarded (control bytes, escape sequences and forged zone sentinels are
// stripped before you see them); SGR you add survives highlighting.
public function withItemFormatter(\Closure $fn): self

// Printed ordinals on/off (-073). Off means the formatter is handed number
// 0 for every row — the built-in default then renders the cursor dot alone,
// so opting out of numbering no longer requires replacing the formatter
// (and re-deriving the dot yourself). A custom formatter that honors the
// documented "0 = no number" contract opts out the same way.
public function withNumbered(bool $numbered = true): self

// Custom filter predicate: Closure(Item $item): bool
// Applied in addition to the built-in filter (contiguous substring match by
// default; fuzzy scoring only when withRanker() is active); return false to
// exclude the item
public function withFilterFn(\Closure $fn): self

// Plug in a sugar-fuzzy ranker (null restores the default substring filter).
// When set, a non-empty filter ranks items by descending fuzzy score (true
// subsequence matching) and highlighting follows the scored indices.
// Cost note: every keystroke re-scores the WHOLE corpus against the filter —
// on the order of hundreds of ms on 20k-item lists (the substring path is
// low double-digit ms; both figures are machine-dependent). Debounce at the
// host or keep corpora modest.
public function withRanker(?\SugarCraft\Fuzzy\FuzzyMatcher $matcher): self

// Apply a sugar-style Border to the overlay window
public function withBorder(?\SugarCraft\Style\Border $border): self

// Apply a sugar-style Style to the overlay window
public function withStyle(?\SugarCraft\Style\Style $style): self

// Attach a HelpBar (keyboard shortcut summary) below the filter list. Its
// rendered line is hard-clipped to the overlay width (no ellipsis), so a
// wide legend under-reports its own keys at narrow widths — size the
// overlay to fit the legend or keep the legend short.
public function withHelpBar(?HelpBar $helpBar): self

// Attach a StatusBar (status message line) at the bottom of the overlay;
// the same hard clip to the overlay width applies.
public function withStatusBar(?StatusBar $statusBar): self

// Register a callback invoked after SIGWINCH resize events (cols, rows)
public function withOnResize(?\Closure $callback): self

// Attach SIGWINCH handler via SignalForwarder::attachSigwinchToFd (requires ext-pcntl)
public function attachSigwinch(): bool

Naming. These builders are canonically with*() (house law: a clone-returning builder is a with-mutation; a discarded return is then visibly a no-op). The historical set*() names (setPrompt, setMatchStyle, setWindowHeight, setWindowWidth, setOffset, setItemFormatter, setFilterFn, setRanker) remain as one-hop @deprecated aliases so existing hosts keep compiling; removal rides the repo-wide setter-campaign ruling and will arrive as its own breaking change, never silently.

API — QuickPick state mutations

// Show the overlay and reset cursor/filter
public function show(): self

// Hide the overlay
public function hide(): self

// Append one or more characters to the filter text and re-filter. Resets
// the cursor to 0. Input is END-ONLY by design — the drawn caret `▏` sits
// at the end of the filter and there is no motion through it; a mid-filter
// typo means backspace/clear and retype. The MAX_FILTER_LENGTH (256
// codepoint) budget is enforced by CLAMPING the appended run: a paste at
// 255 lands exactly 256, never past it, and at the cap the header edge
// shows a `⋯` overflow indicator (compare filterAtCap()).
public function type(string $chars): self

// True once the filter holds MAX_FILTER_LENGTH codepoints: type() then
// refuses input and the header shows the overflow indicator.
public function filterAtCap(): bool

// Remove the last codepoint from the filter text — grapheme clusters such
// as '👍🏽' span several codepoints, so clearing one may take several
// backspaces. Unlike type(), the
// cursor CLAMPS to the new list end instead of resetting — deliberate
// asymmetry: narrowing preserves your place, widening does not.
public function backspace(): self

// Clear filter text and show all items
public function clear(): self

// Move cursor up (default 1). A step below 1 throws InvalidArgumentException
// (-025: negative steps silently reversed direction and parked the cursor
// out of range).
public function cursorUp(int $n = 1): self

// Move cursor down (default 1). A step below 1 throws (same rule as
// cursorUp).
public function cursorDown(int $n = 1): self

// Jump to first item
public function cursorTop(): self

// Jump to last item
public function cursorBottom(): self

API — QuickPick queries

public function isShown(): bool       // Whether overlay is visible
public function cursor(): int        // Current 0-based cursor index
public function filterText(): string // Current filter string
public function selected(): ?Item   // Currently selected Item (or null)
public function items(): array       // Filtered items (list<Item>)
public function itemCount(): int      // Number of visible (filtered) items
public function allCount(): int      // Total number of items
public function border(): ?\SugarCraft\Style\Border
public function style(): ?\SugarCraft\Style\Style
public function helpBar(): ?HelpBar
public function statusBar(): ?StatusBar
public function onResize(): ?\Closure  // Registered resize callback (cols, rows)

API — QuickPick rendering

// Composite the overlay over a background view and return the result.
public function view(string $backgroundView): string

The method was originally declared View(). It is now lowercase view(), matching PSR-1 and the Model–Update–View render contract of QuickPickHost::view(). Nothing to migrate: PHP resolves method names case-insensitively, so an existing $h->View($bg) call still binds here.

API — Item interface

use SugarCraft\QuickPick\Item;
use SugarCraft\QuickPick\FilteredItem;

// Item contract
interface Item {
    public function number(): int;  // 1-based ordinal for display
    public function value(): string; // Display text
}

// Numbered item implementation
final readonly class FilteredItem implements Item {
    public function __construct(private int $number, private string $value) {}
    public static function new(int $number, string $value): self; // house factory, same seeds
    public function number(): int { return $this->number; }
    public function value(): string { return $this->value; }
}

API — FileHistory

use SugarCraft\QuickPick\History\FileHistory;
use SugarCraft\QuickPick\FilteredItem;

// Point at a history file. Without a baseDir, nothing touches the filesystem
// yet — the file is created lazily on the first append() via exclusive-open,
// then chmod'ed 0600 before the first payload line. That chmod is
// best-effort: if the filesystem
// refuses it, the mode follows the process umask and nothing is signalled.
// Use a path you own; on shared hosts, never a predictable
// world-writable location such as /tmp (a planted symlink there is refused
// outright — see below). The parent directory must already exist —
// FileHistory creates only the file, never intermediate directories, so a
// missing parent surfaces as a RuntimeException on the first append().
$history = new FileHistory(getenv('HOME') . '/.myapp/history.jsonl');

// Optionally jail the file inside a private base directory. That check is
// EAGER, not lazy: the constructor realpath-confines the path immediately,
// rejects anything resolving outside the base (via '..', an absolute path
// elsewhere, a symlinked parent — or a symlink at the file itself), and
// throws InvalidArgumentException when the base directory itself does not
// exist.
$history = new FileHistory('history.jsonl', baseDir: getenv('HOME') . '/.myapp');

// FileHistory::new(path, baseDir, maxEntries) is the house factory — same
// seeds, same semantics; the constructor stays public.

// Append an Item as the raw journal row (stored as a JSON line:
// {"n":1,"v":"apple","f":1}\n — "f" is the row-format stamp; rows written
// before the stamp existed load unchanged, rows from a FUTURE format are
// skipped whole rather than guessed at).
// Fails LOUD — a RuntimeException when the file cannot be opened, locked,
// or fully written, or when the path is a symlink. Nothing is ever
// silently dropped.
$history->append(new FilteredItem(1, 'apple'));

// Read all items back; lines that are not encoded entries (bad JSON,
// scalars, arrays without a value field) are skipped.
$items = $history->all();  // returns list<Item>, renumbered 1..N by current load
                          // position (-075): the archived write-time ordinal in
                          // each row is display-ignored, so a replay numbers
                          // like the fresh list it feeds

// Clear the history: the file is truncated in place under an exclusive
// lock (permissions and inode are preserved; no unlink-and-recreate).
$history->clear();

// Get the history file path (absolute and confined when baseDir is set).
$path = $history->path();

History management

append() is a raw journal: one row per selection, forever. That is the right shape when every pick is an event worth keeping — but as a MRU list it grows the launch read into a per-keystroke scan over its own duplicates (upstream theHermit deduped; plain fgets used to slurp whole hostile lines). The managed API covers both halves (-030):

use SugarCraft\QuickPick\History\FileHistory;
use SugarCraft\QuickPick\FilteredItem;

// appendDistinct(): append, then rewrite the row SET under one held
// exclusive lock — an earlier row with the same value is dropped (the
// newest occurrence keeps the newest position), and rows every reader
// already ignores (unparseable, future-format, oversized) are not carried
// forward. The rewrite is housekeeping for free.
$history = new FileHistory(getenv('HOME') . '/.myapp/history.jsonl');
$history->appendDistinct(new FilteredItem(1, 'apple'));
$history->appendDistinct(new FilteredItem(2, 'banana'));
$history->appendDistinct(new FilteredItem(3, 'apple')); // apple moves to newest
// -> all(): banana, apple

// Growth bound: construct with a cap and each managed rewrite keeps at
// most that many NEWEST rows. Null (the default) is unbounded, and plain
// append() never consults the cap — byte behavior unchanged.
$capped = new FileHistory(getenv('HOME') . '/.myapp/history.jsonl', null, 200);
$capped->appendDistinct(new FilteredItem(1, 'the-201st')); // oldest row trimmed

// Rotation for the raw journal stays manual: clear() truncates in place
// under the same lock, or rewrite the file yourself between sessions.

Read-side bound (independent of growth): a row longer than 64 KiB cannot have been written here, so all() drops it whole — drained to the next newline so following rows still read — and counts the drop in droppedOversizedLines(). The next appendDistinct() rewrite drops such rows from the file permanently.

Numbering is positional: all() renumbers its rows 1..N at load (-075), so dedupe and trims never leave stale ordinals on screen; the archived n inside each row records what the number was AT WRITE TIME and is otherwise display-ignored.

API — HelpBar

use SugarCraft\QuickPick\HelpBar;

// Create with optional shortcuts — word-form labels are the
// screen-reader-safe choice (see the note below the fence)
$bar = new HelpBar([
    'Up/Down' => 'navigate',
    'Enter'   => 'select',
    'PgUp'    => 'page back',   // redundant next to Up/Down...
]);

// ...so drop it again: withoutShortcut() removes an entry by key
$bar = $bar->withoutShortcut('PgUp')
           ->withShortcut('Ctrl+R', 'reload');

// HelpBar::new($shortcuts, $visible) is the house factory — same seeds. The
// optional bool starts the bar hidden: new HelpBar([], visible: false)
// renders '' until show().

// Read back the entries (key → description)
$shortcuts = $bar->shortcuts();

// Render: "Up/Down: navigate │ Enter: select │ Ctrl+R: reload"
echo $bar->render();

// Visibility lives on both bars (Visible trait): show() / hide() /
// isVisible(), all fluent except the query. A hidden bar renders the empty
// string — that is how the overlay omits the line entirely:
$bar->hide()->render();       // ''
$bar->hide()->isVisible();    // false
$bar->show()->isVisible();    // true

Shortcut labels are free-form strings rendered verbatim, so prefer word-form entries like 'Up/Down' over glyphs like '↑↓' for screen-reader listeners — the frame interprets neither, the difference is purely what a reader hears.

API — StatusBar

use SugarCraft\QuickPick\StatusBar;

// Create with optional message
$bar = new StatusBar('3 of 12 items');

// StatusBar::new($message, $visible) is the house factory — same seeds; the
// second constructor parameter is the optional visibility flag (default true).

// Fluent setters
$bar = $bar->withMessage('Searching...')   // replaces the constructor message
           ->withSegment('count', '7');    // named segment

// Read back the message and the named segments (name → value)
$message  = $bar->message();
$segments = $bar->segments();

// Render: "[count: 7] Searching..."
echo $bar->render();

// Each call removes exactly one thing — a named segment, the message, or
// visibility — and returns a clone: $bar itself still holds the state echoed
// above, so all three lines start from the same full frame:
$bar->withoutSegment('count')->render(); // 'Searching...'
$bar->withNoMessage()->render();         // '[count: 7]'
$bar->hide()->render();                  // '' — a hidden bar renders empty
$bar->hide()->isVisible();               // false — the query completes the
$bar->show()->isVisible();               // true  — show()/hide()/isVisible() trio

Wiring keyboard input

QuickPick reads no input itself. It holds state and renders; your event loop decodes terminal keys and forwards them. A conventional mapping:

Key Call
printable text $h = $h->type($s)
Backspace $h = $h->backspace()
Ctrl+U $h = $h->clear()
Up / Down $h = $h->cursorUp() / $h->cursorDown() (step argument optional; there are no page keys — call with a step)
Home / End $h = $h->cursorTop() / $h->cursorBottom()
Enter (accept) $choice = $h->selected() — null means nothing to accept — then $h = $h->hide()
Esc (cancel) $h = $h->hide()

hide() is not accept(): the overlay simply stops rendering; reading selected() before hiding is your accept path. The QuickPickHost interface's update(QuickPick $model, string $msg): array — returning [$host, $picker] — expects exactly this forwarding — $msg strings are host-defined, nothing in this library decodes them.

SIGWINCH resize

use SugarCraft\QuickPick\QuickPick;

$h = QuickPick::new($items)
    ->withOnResize(function (int $cols, int $rows): void {
        echo "Terminal resized to {$cols}x{$rows}\n";
    });

// attachSigwinch() returns bool — whether the handler installed — not the
// QuickPick, so call it on its own line rather than continuing the chain.
if ($h->attachSigwinch() === false) {
    // A genuine install failure: no sugar-pty (suggested, not required), no
    // ext-pcntl, no SIGWINCH support, the OS refused pcntl_signal(), or no
    // withOnResize() callback was registered.
    // Poll the size yourself, or simply carry on without resize events.
}

Two ways to live without sugar-pty. The plain one: handle the signal in your own runtime and tell the picker its cached width is stale — one call covers the whole clone family because the width holder is shared:

$loop->addSignal(SIGWINCH, function () use (&$h): void {
    $h->invalidateAutoWidth();   // next view() re-measures from the terminal
});

The wired one: pass an installer callable. It receives the descriptor to watch, the geometry probe, and the composed handler (invalidation + your withOnResize callback), and answers whether it installed — reuse the library's exact semantics over any delivery mechanism you have:

$h->attachSigwinch(
    fn(int $fd, callable $probe, \Closure $handler): bool => my_signal_registry::watch(SIGWINCH,
        static fn(): void => $handler(...$probe()),
    ),
);

Installing and reporting are separate facts. A true return only says the handler is wired up: SIGWINCH is raised by the terminal driver, so on a non-tty STDIN (pipe, redirect) the callback may simply never fire even though the attach succeeded. If you want a size-polling fallback, gate it on stream_isatty(STDIN) — not on the return value.

The width memo is a shared object, not a per-instance property, so a resize invalidates the whole clone family at once: attach before or after your fluent pipeline settles, the live clone still sees every geometry change. One binding does remain instance-flavoured: the handler forwards to the attach-time instance's registered callback, so call withOnResize() before attachSigwinch() — a callback swapped in on a later clone is not re-registered by the old handler.

Signals are process-global. In a long-lived host (PHP-FPM worker, ReactPHP daemon, test suite) detach them at session teardown with SugarCraft\Pty\SignalForwarder::reset() — when you used the default installer; your own $installer owns its teardown.

Composition contract — QuickPickHost

Implement QuickPickHost to use QuickPick inside a larger Model–Update–View application. update() answers a TWO-element array — [host, picker] — because every keystroke on a QuickPick is a fresh fluent clone: the tuple carries the updated picker back, so the host needs no mutable state whatsoever (-006; the single-value : Model shape used to force it).

use SugarCraft\QuickPick\QuickPick;
use SugarCraft\QuickPick\QuickPickHost;

final class MyModel implements QuickPickHost {
    /** @return array{0: QuickPickHost, 1: QuickPick} */
    public function update(QuickPick $model, string $msg): array {
        $next = match ($msg) {
            'down'  => $model->cursorDown(),
            'up'    => $model->cursorUp(),
            default => $model,
        };
        return [$this, $next];
    }

    public function view(QuickPick $model): string {
        return $model->view($this->background);
    }
}

Naming. The contract shipped as Model — the bare word collided with sugar-core's house SugarCraft\Core\Model, a different shape (-044). The old name remains as an empty @deprecated alias (interface Model extends QuickPickHost), so instanceof checks and type-hints keep resolving; IMPLEMENTORS of the old single-return shape must adopt the tuple — the alias cannot abstract a signature change.

License

MIT

Credits & inspiration

Originally inspired by Genekkion/theHermit — fuzzy finder / quick-fix overlay for terminal UIs; SugarCraft is developed as a native PHP project.

Divergences from the antecedent

Three upstream behaviors were consciously not ported; each is a design stance, not a gap (dated 2026-11, reviewed against the whole surface):

  • No title/titleStyle channel — upstream's framed heading row above the list has no equivalent here. The header IS the prompt+filter line; hosts that need a title render it in the background view or attach a StatusBar. (withPrompt() covers the in-frame label role.)
  • No auto-centering — upstream recomputes its left padding on every resize message; this lib keeps positioning MANUAL (withOffset(x, y)). The frame is composed over the host's own string, so centering math belongs to whoever owns that string — an automatic padding would fight host layouts that are not full-screen.
  • Frameless, colorless by default — upstream ships bordered, colored lipgloss styling out of the box. The default here is pure Unicode runes (no SGR at all, border off), because the overlay is designed to sit on arbitrary host output without repainting it; border and style are opt-in (withBorder(), withStyle(), withMatchStyle()).

Where it fits

QuickPick is a TRANSIENT SELECTION overlay: a fuzzy-filtered choice on top of a view string you already render — command palette, file picker, quick-fix. It is not a form control: if the choice is one field inside a larger input flow, sugar-forms/sugar-widgets own that lifecycle (focus, submit, validation); if you need a persistent interactive table, that is sugar-table or sugar-treelist. As of this writing no in-repo app consumes it — it is published as a building block. Upstream mapping lives in docs/MATCHUPS.md; the pre-port pattern research (Bubble Tea, bubbles/list, readline histories, Fish) is kept in docs/research/libraries/sugar-quickpick-research.md, which carries a dated status banner against the shipped surface.