All 42 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

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()

Accessibility & 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).

Source & demos

Try the quickstart →

API

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)

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.