All 48 libraries

SugarQuickpick

Fuzzy finder / quick-pick overlay for terminal UIs

inspired by Genekkion/theHermit tuifuzzyfinderoverlayquick-pick

SugarQuickpick code coverage

Fuzzy-search overlay: a render-and-state component your event loop drives — you decode keys and forward them (type(), cursorUp()/Down()); Enter is answered by the selected() query and hide() is the lifecycle call — neither is input the library consumes, it reads none itself. Composes into any SugarCraft app via the package-local QuickPickHost contract (the old Model name remains as a @deprecated alias). Supports structured Item objects, custom filter predicates, and persistent JSONL history.

Install

composer require sugarcraft/sugar-quickpick

Requirements: PHP 8.3+, no hard extension floor. ext-pcntl and sugarcraft/sugar-pty are both optional and both serve only the opt-in attachSigwinch() resize attach — sugar-pty supplies its automatic SignalForwarder path (and an ext-ffi install floor with it); without either, attachSigwinch() returns false and you drive resizes yourself (invalidateAutoWidth() once per resize, or pass a host installer callable). Everything else is pure string rendering. A UTF-8 capable terminal is expected: the built-in chrome draws ↕ ─ ▏ ⋯ runes, which show as mojibake on legacy non-UTF-8 terminals.

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.

Quickstart — plain strings

use SugarCraft\QuickPick\QuickPick;

$quickpick = QuickPick::new(
    items: ['Ruby', 'PHP', 'Go', 'Rust', 'Python'],
)->withPrompt('Choose language: ');

Quickstart — numbered items + history

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

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

$quickpick = QuickPick::new($items)
    ->withFilterFn(fn($item) => $item->number() > 0)
    ->withPrompt('> ');

// Persist selections (path you own; files created are 0600)
$historyPath = getenv('HOME') . '/.myapp/history.jsonl';
@mkdir(\dirname($historyPath), 0700, true); // FileHistory creates the file, never its parent
$history = new FileHistory($historyPath);
if ($choice = $quickpick->selected()) {
    $history->append($choice);
}
$allItems = $history->all(); // renumbered 1..N by current load position — archived write-time ordinals are display-ignored

Concepts

QuickPick is a render-and-state component. It owns the filter text, the item list, the cursor and the window offset. Your event loop owns the keys: it decodes them and forwards calls such as type(), cursorDown() and backspace(), then renders view() over the background string the host already has.

Items are plain strings or Item objects. Strings are coerced by ItemFactory, and each coerced string takes its input position as its ordinal. FilteredItem is the numbered Item implementation. The default filter is a case-folded substring match. withRanker() swaps in subsequence scoring, and withFilterFn() adds a predicate that decides which items are candidates at all.

Accepting is two calls, and the convention is to read in this order. Read selected() first, which returns the highlighted item or null when nothing matches. Then call hide(). hide() is the lifecycle call, not an accept. It clears visibility and keeps the filter and cursor, so selected() still answers after it. Read it first anyway, so the accept reads in the order the lifecycle implies.

Tasks

  • Pick one value from a fixed list. Build QuickPick::new(['Ruby', 'PHP', 'Go'])->withPrompt('Choose language: '), forward keys to type(), cursorUp() and cursorDown(), and on Enter read selected() before calling hide().
  • Remember recent choices. After an accept, call FileHistory::append() with the choice. On the next run, all() returns the saved entries, renumbered by their current load position. appendDistinct() is last-wins: older copies of the same value are dropped, the newest occurrence moves to the end, and the file is rewritten whole. The optional entry cap bounds growth.
  • Restrict the candidates. Pass a predicate such as fn(Item $item): bool => ... to withFilterFn(). Only items the predicate accepts reach the text match.
  • Place the overlay over a background. Render the host's own view string, then position the picker with withOffset($x, $y), cap it with withWindowHeight(), and add a border with withBorder(). Positioning is manual, so centering stays with the host.
  • Follow terminal resizes. Call withOnResize() to receive resize events. Call attachSigwinch() to forward SIGWINCH automatically when ext-pcntl or sugar-pty is available. Otherwise call invalidateAutoWidth() once per resize, or supply your own size source with withTtySizeProvider().

What's in the box

Fuzzy matchingCase-folded substring filter; a candidate must match in the first half of the text (codepoint-based). withRanker() swaps in true subsequence scoring; a rejected-by-bias count surfaces as “N hidden by anchor bias”.
Composition wrapperQuickPickHost contract: update() answers [host, picker] — the updated QuickPick rides the tuple, the host needs no mutable state.
ConfigurableCustom formatter, prompt, match highlight style; window height is a maximum, clamped to the terminal row budget on short screens.
Item interfaceStructured Item objects with number() + value() instead of raw strings.
Custom filter predicateswithFilterFn() applies arbitrary Closure(Item): bool logic — seedable straight through new().
Persistent historyFileHistory stores items as JSONL (version-stamped rows), post-open fd-trust verified, oversized lines dropped at a 64 KiB read cap, with appendDistinct() dedupe and an optional entry cap.
Border & StylewithBorder() frames every row (T-junction separator); withStyle() paints each rendered row via sugar-style.
HelpBar / StatusBarKeyboard-shortcut summary and status message rendered below the overlay.
SIGWINCH resizewithOnResize() + attachSigwinch() forward terminal resize events via SignalForwarder.

Keyboard contract (condensed)

QuickPick reads no input itself — your event loop decodes keys and forwards calls:

KeyCall
printable texttype($s)
Backspacebackspace()
Ctrl+Uclear()
Up / DowncursorUp() / cursorDown() — optional step argument; there are no page keys, call with a step
Home / EndcursorTop() / cursorBottom()
Enter (accept)selected(), then hide() — hide() is not accept(): read the selection before hiding; null means nothing to accept
Esc (cancel)hide()

Configuration and options

OptionTypeDefaultEffect
itemsarray of string or Item[]Seed list, set in new() or replaced with withItems(). The filter text is kept and re-applied.
QuickPick::withPrompt()string'> 'Label in front of the filter line.
QuickPick::withFilterFn()Closure(Item): boolaccepts every itemPredicate that decides which items are candidates.
QuickPick::withRanker()?FuzzyMatchernullNull keeps the case-folded substring match. A matcher from sugar-fuzzy adds subsequence scoring.
QuickPick::withItemFormatter()Closure(string, bool, int): stringa ● or two spaces, then the ordinal, then the itemRenders one row. The third argument is the printed ordinal, or 0 when numbering is off.
QuickPick::withNumbered()booltruefalse hands the formatter 0 for every row, so the row shows only the cursor dot.
QuickPick::withWindowHeight()int10Overlay height maximum in rows, header and separator included. Visible items are the height minus 2, and one fewer while the overflow marker shows. Values below 2 are raised to 2, and the window is clamped to the terminal's row budget on short screens.
QuickPick::withWindowWidth()int00 sizes the overlay automatically. A positive value caps the outer width in cells.
QuickPick::withOffset()int, int0, 0Top-left position over the background. Negative values clamp to 0, and the column is clamped so the overlay never starts past the right edge.
QuickPick::withMatchStyle()string (ANSI)''SGR applied to the matched characters. Empty means no color.
QuickPick::withBorder()?BordernullFrames every row with a T-junction separator. Off by default.
QuickPick::withStyle()?StylenullPaints each rendered row through sugar-style. Off by default.
QuickPick::withOnResize()?ClosurenullCallback run on terminal resize, used with attachSigwinch().

Theme, style and color policy

Colorless by default. The frame emits no SGR at all; emphasis reaches the cursor row through text channels a screen reader can speak — the ● bullet and ordinal (both your withItemFormatter's bytes, substitutable to plain ASCII; withNumbered(false) drops the ordinals and keeps the dot) and plain-language chrome rows rendered from the Lang catalog (“↕ showing 1-10 of 40”, “no matches”, “no items”, “N hidden by anchor bias”). Every printed ordinal is a POSITION: coerced strings take their input position across the whole list, replayed history renumbers 1..N at load, and cursor() is the accessor for the selected row's position in what is on screen. SGR appears only where the host opts in (withMatchStyle(), withStyle(), the formatter); honoring NO_COLOR/CLICOLOR is host-side — skip the opt-ins on dumb terminals (the default already needs no color).

Examples

The examples are package-internal demo drivers. They run from a clone with composer install in the lib root, and they drive the VHS tapes.

  • examples/basic.php: a fuzzy finder over ten fruit names, drawn over a background view. Run it with php examples/basic.php.
  • examples/interaction.php: scripted keystrokes against a list of command names. It prints the overlay after the initial state, after type('p') and after type('ph'), and it shows the anchor-bias count when some candidates are hidden. Run it with php examples/interaction.php.

Testing

Run the lib's suite from its root:

composer install && vendor/bin/phpunit

The suite covers the filter and ranker, the geometry and anchor-bias rules, UTF-8 filtering, the SIGWINCH attach, the history store and the help and status bars. ReadmeExampleTest keeps the README's examples executable.

Troubleshooting and FAQ

  • The chrome shows question marks or mojibake. The built-in chrome draws ↕ ─ ▏ ⋯. A legacy non-UTF-8 terminal cannot show them, so run the picker in a UTF-8 terminal.
  • attachSigwinch() returns false. Automatic resize needs ext-pcntl or sugar-pty. Without either, call invalidateAutoWidth() once per resize, or pass a size source with withTtySizeProvider().
  • Composer refuses to resolve the sugarcraft/* siblings. The siblings require dev-master. Add "minimum-stability": "dev" and "prefer-stable": true to the consuming root, or pin released tags once they are cut.
  • Enter returns nothing. selected() returns null when the filter matches nothing or the cursor is out of bounds. Check for null before using the value.
  • The history file is never created. FileHistory creates the file but never its parent directory. Create the directory first, and expect files to be written with mode 0600.
  • Ordinals look wrong after a reload. Ordinals are positions in the list on screen. Replayed history renumbers 1..N at load, and the archived write-time ordinals are ignored for display.

Upstream mapping

The lib is inspired by the quick-pick overlay in Genekkion/theHermit (Go). It is a native PHP port, and three upstream behaviors were deliberately not carried over.

Upstream (Go)SugarCraftDivergence
Framed title row above the listThe header is the prompt and filter lineNo title channel. withPrompt() covers the in-frame label, and hosts render titles in the background view or a StatusBar.
Auto-centering on each resizewithOffset(x, y)Positioning stays manual, because the frame is composed over the host's own string and automatic padding would fight non-full-screen layouts.
Bordered, colored lipgloss styling by defaultFrameless, colorless by defaultwithBorder(), withStyle() and withMatchStyle() are opt-in.

Architecture

The package is one main class and a few helpers. QuickPick is the fuzzy finder overlay. QuickPickHost is the update() and view() composition contract, which carries its state in the return tuple. Item and FilteredItem model the candidates. HelpBar and StatusBar render the lines below the overlay, and both use the Visible concern. ItemFactory coerces string and Item lists. Lang is the chrome text catalog, loaded from lang/en.php. History\FileHistory is the JSONL-backed store. Support\AnsiWalk walks escape sequences by codepoint when highlighting, and Support\UntrustedText guards rendered strings at the trust boundary.

Changelog and versioning

The package ships no CHANGELOG file. The commit history of sugar-quickpick/ in the monorepo is the record of changes. Its siblings resolve at dev-master, as the Install section notes.

Source & demos

Try the quickstart →

API reference

ClassMethodDescription
QuickPicknew(array $items, ?Closure $itemFormatter, ?Closure $filterFn)Create fuzzy finder (items: string[] or Item[]; coerced strings take their input position as ordinal; all three seeds factory-reachable)
QuickPickwithItems(array $items)Replace items; the filter text is kept and re-applied (cursor resets)
QuickPickwithPrompt(string)Set filter prompt string
QuickPickwithFilterFn(Closure)Set custom filter predicate: Closure(Item): bool
QuickPickwithItemFormatter(Closure)Set item formatter: Closure(value: string, isSelected: bool, number: int): string
QuickPickwithNumbered(bool $numbered = true)Printed ordinals on/off: off hands the formatter number 0 for every row (built-in default renders the cursor dot alone; a custom formatter honoring "0 = no number" opts out the same way)
QuickPickwithMatchStyle(string)Set ANSI SGR codes for match highlighting
QuickPickwithWindowHeight(int)Set the overlay height MAXIMUM in rows (header+separator included; visible items = height − 2, min 2; overflow/empty states consume an item row; short terminals shrink the budget — the frame never exceeds tty rows minus reserved chrome)
QuickPickwithWindowWidth(int)Set overlay width (0 = auto)
QuickPickwithOffset(int $x, int $y)Set overlay position (pure placement; negatives clamp; visibility unchanged)
QuickPickshow() / hide()Show the overlay (resetting cursor and filter) or hide it
QuickPicktype(string) / backspace() / clear()Modify filter text
QuickPickcursorUp/Down/Top/Bottom()Navigate item cursor
QuickPickselected()Get the Item under the cursor (never null while the filtered list is non-empty — the cursor always rests on an item, so a non-null answer is cursor position, not confirmed intent; null only when no items match)
QuickPickitems() / itemCount() / allCount()Query filtered/all item state
QuickPickwithBorder(?Border)Apply sugar-style Border to overlay window
QuickPickwithStyle(?Style)Apply sugar-style Style to overlay window
QuickPickwithHelpBar(?HelpBar)Attach keyboard-shortcut summary below filter list
QuickPickwithStatusBar(?StatusBar)Attach status message line at overlay bottom
QuickPickwithRanker(?FuzzyMatcher)Plug a sugar-fuzzy ranker (per-keystroke full-corpus scoring); null restores substring filter; emphasis styling is a separate opt-in via withMatchStyle()
QuickPickwithOnResize(?Closure)Register callback invoked on SIGWINCH (cols, rows); null detaches
QuickPickattachSigwinch(?callable $installer = null)Install the resize handler — default uses sugar-pty's SignalForwarder when that suggested package is present; a host $installer(fd, probe, handler) works over any delivery; returns false when nothing attached
QuickPickinvalidateAutoWidth()Drop the memoized computed width across the whole clone family (shared holder) — the manual resize path when neither pcntl nor sugar-pty is installed
QuickPickborder() / style() / helpBar() / statusBar()Query attached border, style, help bar, status bar
QuickPickview(string $backgroundView)Render composited overlay over background
HelpBarnew(array $shortcuts, bool $visible)Create help bar with key→description pairs
HelpBarwithShortcut(key, desc) / withoutShortcut(key)Add/remove shortcut entry
HelpBarshow() / hide() / isVisible()Control visibility
HelpBarshortcuts()Read back the key→description map
HelpBarrender()Render as "key: desc │ key: desc ..." string
StatusBarnew(string $message, bool $visible)Create status bar with message
StatusBarwithMessage(string) / withNoMessage()Set or clear primary message
StatusBarwithSegment(name, value) / withoutSegment(name)Add/remove named segment
StatusBarshow() / hide() / isVisible()Control visibility
StatusBarmessage() / segments()Read back the message and the name→value segments
StatusBarrender()Render as "[name: value] message" string
Iteminterface number(), value()Contract for filterable items
FilteredItemnew(int $number, string $value)Numbered Item implementation
FileHistorynew(string $path, ?string $baseDir, ?int $maxEntries)Target a JSONL history file (nothing touches the filesystem until an op runs — the file is created lazily via exclusive-open then a verified 0600; every later open is fd-trust verified post-open: inode identity, own-uid, no group/other bits — a pre-planted foreign file receives nothing; the parent directory must already exist. With $baseDir the confinement check is eager in the constructor (missing base throws InvalidArgumentException; symlinked or escaping paths refused); $maxEntries caps growth for appendDistinct() rewrites (null = unbounded))
FileHistoryappend(Item)Append item as a version-stamped JSON line; fails loud (RuntimeException) on unopenable, unlocked, short-written (torn bytes rolled back before release), or untrusted paths
FileHistoryappendDistinct(Item)Managed growth: last-wins dedupe by value under one held lock, optional cap trims to the newest N; honest rows re-emit byte-verbatim
FileHistoryall()Read all items, renumbered 1..N by current load position — the archived write-time ordinal in the row is display-ignored (replays number like the fresh lists they feed) (bounded 64 KiB line reads — oversized planted lines are dropped, not slurped; an existing-but-unreadable file throws, a genuinely absent one answers []; unparseable or future-format rows are skipped)
FileHistoryclear() / path()Empty the history (ftruncate under a hard-required exclusive lock — lock failure throws before a byte moves) or get the file path
QuickPickHostinterface update(QuickPick, string): array, view(QuickPick): stringModel–Update–View embedding contract — update() answers the [host, picker] tuple, so the updated QuickPick never needs mutable host state
Model@deprecated alias of QuickPickHostDeclares no members of its own; old type-hints and instanceof keep resolving (implementors must adopt the tuple)

Only methods declared in sugar-quickpick/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\QuickPick

FilteredItem final readonly class

A numbered item for use in QuickPick filter lists.

MethodSummary
__construct(private int $number, private string $value)
static new(int $number, string $value): selfHouse factory (::new()), mirroring QuickPick::new(): same signature as the constructor, which stays public (the docs promise a bare construction site).
number(): int
value(): string

HelpBar final class

HelpBar — renders a single-line keyboard shortcut summary for the QuickPick overlay.

MethodSummary
__construct(array $shortcuts = [], bool $visible = true)
static new(array $shortcuts = [], bool $visible = true): selfHouse factory (::new()), mirroring QuickPick::new(): same signature as the constructor, which stays public (the docs promise a bare construction site).
withShortcut(string $key, string $description): selfAdd a keyboard shortcut entry.
withoutShortcut(string $key): selfRemove a keyboard shortcut entry by key.
shortcuts(): array
render(): stringRender the help bar as a single line of text. Format: "key: description │ key: description │ ..."
show(): self
hide(): self
isVisible(): bool

Item interface

Contract for items displayed in the QuickPick filter list.

MethodSummary
number(): intReturns the ordinal number of this item (1-based for display).
value(): stringReturns the display text of this item.

ItemFactory final class

Factory for converting raw input into Item instances.

MethodSummary
coerce(array $items): array

Lang final class

Per-library translation facade for sugar-quickpick.

Model interface

MethodSummary
update(QuickPick $model, string $msg): arrayHandle a message and return the updated pair.
view(QuickPick $model): stringRender the view given the current QuickPick state.

QuickPick final class

The QuickPick — fuzzy finder / quick-pick overlay component.

MethodSummary
__construct(array $items = [], ?\Closure $itemFormatter = null, ?\Closure $filterFn = null)All three seeds are factory-reachable through new() as well (S-28/-056); the fluent path is the filterFn builder — withFilterFn() today, canonically withFilterFn() after the naming sweep (S-24).
static new(array $items = [], ?\Closure $itemFormatter = null, ?\Closure $filterFn = null): self
withItems(array $items): selfReplace the item list.
withPrompt(string $prompt): self
withMatchStyle(string $ansiStyle): self
withWindowHeight(int $h): selfSet the overlay window height in ROWS of the frame — header and separator included, so the visible item count is $h - 2, minus one more row when the overflow marker is needed. The marker shows only when it fits inside the window: if reserving its row would empty the list band, the marker is suppressed rather than growing the frame (-002).
withWindowWidth(int $w): selfSet the overlay width in cells.
withOffset(int $x, int $y): selfPosition the overlay at (x, y) cells into the background. Pure placement: it does NOT show or hide the overlay (M4).
withItemFormatter(\Closure $fn): selfSet the formatter for item display lines.
withNumbered(bool $numbered = true): selfTurn the printed ordinals on or off (-073).
withFilterFn(\Closure $fn): self
withRanker(?FuzzyMatcher $matcher): selfSet (or clear, with null) a sugar-fuzzy ranker. When set, a non-empty filter text ranks items by descending fuzzy score (true subsequence match) instead of the default contiguous-substring/anchor filter, and match highlighting follows the scored indices. The custom filterFn still applies as a predicate. Pass null to restore the default substring behaviour.
setPrompt(string $prompt): self
setMatchStyle(string $ansiStyle): self
setWindowHeight(int $h): self
setWindowWidth(int $w): self
setOffset(int $x, int $y): self
setItemFormatter(\Closure $fn): self
setFilterFn(\Closure $fn): self
setRanker(?FuzzyMatcher $matcher): self
withBorder(?Border $border): selfApply a border from sugar-style.
withStyle(?Style $style): selfApply a style from sugar-style.
withHelpBar(?HelpBar $helpBar): selfAttach a help bar below the filter list.
withStatusBar(?StatusBar $statusBar): selfAttach a status bar at the bottom of the overlay.
withOnResize(?\Closure $callback): selfRegister a callback to invoke after SIGWINCH resize events. The callback receives (cols: int, rows: int). Pass null to detach a previously registered callback (attachSigwinch() then returns false).
attachSigwinch(?callable $installer = null): boolAttach a SIGWINCH handler via SignalForwarder that queries the live TTY dimensions and forwards (cols, rows) to the stored $onResize callback.
invalidateAutoWidth(): voidDrop the memoized auto width so the next view() re-measures.
withTtySizeProvider(?\Closure $provider): selfInstall a geometry provider for ttySize() (see the property for the semantics). Clone-returning like every other builder; the provider is shared state for the clone family only in the sense that every fluent clone carries the same closure handle.
show(): self
hide(): self
type(string $chars): selfAppend one or more characters to the filter text.
backspace(): selfDrop the last codepoint from the filter text.
clear(): self
cursorUp(int $n = 1): self
cursorDown(int $n = 1): self
cursorTop(): self
cursorBottom(): self
isShown(): bool
cursor(): int
filterText(): string
numbered(): boolWhether rows carry printed ordinals (see withNumbered()).
filterAtCap(): boolTrue once the filter holds MAX_FILTER_LENGTH codepoints: appended input is then refused and the header edge shows the overflow indicator (filterChrome()).
selected(): ?ItemReturns the currently selected item, or null if the cursor is out of bounds (e.g., empty filtered list).
items(): array
itemCount(): int
allCount(): int
border(): ?Border
style(): ?Style
helpBar(): ?HelpBar
statusBar(): ?StatusBar
onResize(): ?\Closure
view(string $backgroundView): stringRender the QuickPick overlay and composite it over $backgroundView.

QuickPickHost interface

Package-local composition contract for embedding QuickPick in a Model–Update–View application.

MethodSummary
update(QuickPick $model, string $msg): arrayHandle a message and return the updated pair.
view(QuickPick $model): stringRender the view given the current QuickPick state.

StatusBar final class

StatusBar — renders a single-line status message for the QuickPick overlay.

MethodSummary
__construct(string $message = '', bool $visible = true)
static new(string $message = '', bool $visible = true): selfHouse factory (::new()), mirroring QuickPick::new(): same signature as the constructor, which stays public (the docs promise a bare construction site).
withMessage(string $message): selfSet the primary status message.
withNoMessage(): selfClear the primary status message.
message(): string
withSegment(string $name, string $value): selfAdd a named segment that can be rendered alongside the primary message.
withoutSegment(string $name): selfRemove a named segment by name.
segments(): array
render(): stringRender the status bar as a single line of text. Format: "[segment1: value] message" When no message and no segments: returns empty string.
show(): self
hide(): self
isVisible(): bool

SugarCraft\QuickPick\Concerns

Visible trait

Provides show/hide/isVisible state for UI components that can be toggled.

MethodSummary
show(): self
hide(): self
isVisible(): bool

SugarCraft\QuickPick\History

FileHistory class

File-backed persistent history for QuickPick items.

MethodSummary
__construct(string $path, ?string $baseDir = null, ?int $maxEntries = null)
static new(string $path, ?string $baseDir = null, ?int $maxEntries = null): selfHouse factory (::new()), mirroring \SugarCraft\QuickPick\QuickPick::new(): same signature as the constructor, which stays public (the docs promise a bare construction site).
append(Item $item): voidAppend an item to the history file.
appendDistinct(Item $item): voidAppend with last-wins dedupe, then trim to the newest cap: the managed row set for hosts that treat history as a MRU list (-030).
all(): arrayRead all items from the history file.
droppedOversizedLines(): intHow many rows the last read pass (all() or appendDistinct()) dropped as oversized.
clear(): voidClear the history file.
path(): stringGet the path to the history file.

SugarCraft\QuickPick\Support

AnsiWalk final class

Escape-aware walk over a terminal string.

MethodSummary
static pieces(string $text): arraySplit a string into escape pieces and single-codepoint text pieces.
static chars(string $text): arrayThe display codepoints of $text, control sequences excluded.
static plain(string $text): stringThe display text of $string with all control sequences stripped.
static paint(string $text, array $matchedSet, string $style): stringRe-emit $text with $style ... Ansi::reset() wrapped around the matched display codepoints.

UntrustedText final class

Trust boundary for every string this component can echo to a terminal.

MethodSummary
static guard(string $value): stringMake $value safe to render inside the fixed-width overlay frame.

WidthMemo final class

Shared auto-width cache for one QuickPick clone family.

MethodSummary
invalidate(): voidDiscard the composed width so the next render re-derives it. Cheap: every ingredient (prompt, filter, cached per-item widths) is still warm.
invalidateItems(): voidDiscard the per-item measurements too — required when the corpus or the formatter closure itself changes, the only two events that make a stored item width wrong rather than merely unused.

Demos.

VHS-recorded GIFs of the package-internal demo drivers (present in the repository clone, not shipped as a starter template). Regenerated automatically on every push that touches the source.

Background + overlay

Background + overlay

QuickPick overlay over a sample background: unfiltered list, one typed filter, cursor move.
Filter interaction

Filter interaction

Filter narrowing the candidate list as you type.
  • SugarFuzzy: fuzzy matching with matched indices and scores, the matcher QuickPick filters with.