SugarQuickpick
Fuzzy finder / quick-pick overlay for terminal UIs
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
Keyboard contract (condensed)
QuickPick reads no input itself — your event loop decodes keys and forwards calls:
| Key | Call |
|---|---|
| printable text | type($s) |
| Backspace | backspace() |
| Ctrl+U | clear() |
| Up / Down | cursorUp() / cursorDown() — optional step argument; there are no page keys, call with a step |
| Home / End | cursorTop() / 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
- Source on GitHub
- Full README
- Package-internal demo drivers — runnable from a clone, not shipped as a starter template
- Originally inspired by Genekkion/theHermit (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| QuickPick | new(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) |
| QuickPick | withItems(array $items) | Replace items; the filter text is kept and re-applied (cursor resets) |
| QuickPick | withPrompt(string) | Set filter prompt string |
| QuickPick | withFilterFn(Closure) | Set custom filter predicate: Closure(Item): bool |
| QuickPick | withItemFormatter(Closure) | Set item formatter: Closure(value: string, isSelected: bool, number: int): string |
| QuickPick | withNumbered(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) |
| QuickPick | withMatchStyle(string) | Set ANSI SGR codes for match highlighting |
| QuickPick | withWindowHeight(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) |
| QuickPick | withWindowWidth(int) | Set overlay width (0 = auto) |
| QuickPick | withOffset(int $x, int $y) | Set overlay position (pure placement; negatives clamp; visibility unchanged) |
| QuickPick | show() / hide() | Show the overlay (resetting cursor and filter) or hide it |
| QuickPick | type(string) / backspace() / clear() | Modify filter text |
| QuickPick | cursorUp/Down/Top/Bottom() | Navigate item cursor |
| QuickPick | selected() | 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) |
| QuickPick | items() / itemCount() / allCount() | Query filtered/all item state |
| QuickPick | withBorder(?Border) | Apply sugar-style Border to overlay window |
| QuickPick | withStyle(?Style) | Apply sugar-style Style to overlay window |
| QuickPick | withHelpBar(?HelpBar) | Attach keyboard-shortcut summary below filter list |
| QuickPick | withStatusBar(?StatusBar) | Attach status message line at overlay bottom |
| QuickPick | withRanker(?FuzzyMatcher) | Plug a sugar-fuzzy ranker (per-keystroke full-corpus scoring); null restores substring filter; emphasis styling is a separate opt-in via withMatchStyle() |
| QuickPick | withOnResize(?Closure) | Register callback invoked on SIGWINCH (cols, rows); null detaches |
| QuickPick | attachSigwinch(?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 |
| QuickPick | invalidateAutoWidth() | Drop the memoized computed width across the whole clone family (shared holder) — the manual resize path when neither pcntl nor sugar-pty is installed |
| QuickPick | border() / style() / helpBar() / statusBar() | Query attached border, style, help bar, status bar |
| QuickPick | view(string $backgroundView) | Render composited overlay over background |
| HelpBar | new(array $shortcuts, bool $visible) | Create help bar with key→description pairs |
| HelpBar | withShortcut(key, desc) / withoutShortcut(key) | Add/remove shortcut entry |
| HelpBar | show() / hide() / isVisible() | Control visibility |
| HelpBar | shortcuts() | Read back the key→description map |
| HelpBar | render() | Render as "key: desc │ key: desc ..." string |
| StatusBar | new(string $message, bool $visible) | Create status bar with message |
| StatusBar | withMessage(string) / withNoMessage() | Set or clear primary message |
| StatusBar | withSegment(name, value) / withoutSegment(name) | Add/remove named segment |
| StatusBar | show() / hide() / isVisible() | Control visibility |
| StatusBar | message() / segments() | Read back the message and the name→value segments |
| StatusBar | render() | Render as "[name: value] message" string |
| Item | interface number(), value() | Contract for filterable items |
| FilteredItem | new(int $number, string $value) | Numbered Item implementation |
| FileHistory | new(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)) |
| FileHistory | append(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 |
| FileHistory | appendDistinct(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 |
| FileHistory | all() | 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) |
| FileHistory | clear() / path() | Empty the history (ftruncate under a hard-required exclusive lock — lock failure throws before a byte moves) or get the file path |
| QuickPickHost | interface update(QuickPick, string): array, view(QuickPick): string | Model–Update–View embedding contract — update() answers the [host, picker] tuple, so the updated QuickPick never needs mutable host state |
| Model | @deprecated alias of QuickPickHost | Declares 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
QuickPick overlay over a sample background: unfiltered list, one typed filter, cursor move.