Search by

sugarcraft / sugar-datepicker

detain

Interactive month-grid date picker for terminal UIs. Supports month/year navigation with min/max selection constraints, single and range selection via a model wrapper implementing the MVC-style Model-Update-View (TEA) loop, keyboard navigation with a visible cursor, i18n month/day names, and customi

dev-master 2026-11-18 18:48 UTC

This package is auto-updated.

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


README

sugar-datepicker

CI codecov Packagist License PHP

SugarDatepicker

Formerly published as sugarcraft/sugar-calendar (renamed 2026-10). Namespace changed: SugarCraft\Calendar\ → SugarCraft\DatePicker\.

sugar-datepicker — an interactive date picker component for terminal UIs, for PHP 8.3+.

Features

  • Month/year navigation — programmatic GoTo* steps, and PageUp/PageDown month steps driven through the Model; the view window is clamped to the calendar floor (January 0001) and to optional min/max bounds
  • Keyboard handling — handleKey() for arrow keys, Home/End, Enter to select, Esc to clear (works in both single and range modes)
  • Date selection — select/clear a single date, or a start/end range
  • Min/max date constraints — the month view clamps to the allowed window and Enter silently refuses a selection outside it (the receiver comes back unchanged); the cursor can still rest on out-of-bounds days, which the grid renders dimmed (faint) whatever their today/selected state — the disabled cue composes onto state colours rather than being masked by them
  • Model–Update–View (TEA) integration — a Model wrapper implementing the sugar-core Model contract (init()/update(Msg)/view()), recording picker events into an optional EventStore
  • Today highlight — show the reference "today" distinctly; withoutToday() hides the marker outright, withClockToday() resumes wall-clock following
  • Selected date and range styling — seven SGR style setters, validated
  • Pure renderer — outputs ANSI strings, no external TUI framework needed

Related widgets

SugarCraft\Dashboard\Components\Select\DatePicker (sugar-dashboard) is a separate widget with its own API: a labelled form-input field for dashboard grids — it wraps a text entry with an optional calendar popup and speaks the dashboard SizedItem protocol. This package is the standalone TEA calendar: no label chrome, no popup overlay, no dashboard dependency. Neither consumes the other; pick by context (form field → dashboard, embedded calendar → this one).

Install

composer require sugarcraft/sugar-datepicker:@dev

No tagged release yet — the package currently ships only dev-master from Packagist, so consume it with the @dev constraint above until the first version tag lands. The 2026-10 rename left the old sugarcraft/sugar-calendar provider registered and frozen at its last old-name release; depend on the new name only.

Quick Start

use SugarCraft\DatePicker\DatePicker;

$picker = DatePicker::new(new \DateTimeImmutable('2026-05-01'));
$picker = $picker->handleKey(DatePicker::KEY_ENTER);  // select the cursor date

echo $picker->view();  // render the month grid
$selected = $picker->selectedDate();  // 2026-05-01

Or drive it as a TEA model:

use SugarCraft\Core\Msg\KeyMsg;
use SugarCraft\Core\KeyType;
use SugarCraft\DatePicker\DatePicker;
use SugarCraft\DatePicker\Model;

$model = Model::new(new \DateTimeImmutable('2026-05-15'));
[$model, $cmd] = $model->update(new KeyMsg(KeyType::Right));
[$model, $cmd] = $model->update(new KeyMsg(KeyType::Enter));  // selects the date
echo $model->view();

// A fully configured picker enters the model directly (seed time and picker
// are mutually exclusive — passing both throws):
$picker = DatePicker::new(new \DateTimeImmutable('2026-05-15'))
    ->withRangeMode(true)
    ->withWidth(30);
$model = Model::new(picker: $picker);

// Mid-flight reconfiguration keeps the attached EventStore instance:
$model = $model->withPicker(fn (DatePicker $p) => $p->withRangeMode(false));

Navigation

// Month navigation
$picker = $picker->goToPreviousMonth();
$picker = $picker->goToNextMonth();
$picker = $picker->goToPreviousYear();
$picker = $picker->goToNextYear();
$picker = $picker->goToToday();

// Set arbitrary month
$picker = $picker->setTime(new \DateTimeImmutable('2025-12-01'));

Steps never throw and never wrap: the view position is clamped at the calendar floor (January 0001 — earlier years cannot be represented as Y-m-d grid dates) and, when set, at the min/max bound months. Stepping at a clamp boundary is a no-op. The cursor index is re-clamped into the new month on every navigation step: it keeps its grid position whenever that position is a day cell of the new month, so a step into a shorter month lands on its last day only when the old index falls past the new month's day-cell window. The mirror edge exists at the top, symmetric: forward stepping at December 9999 is a no-op, exactly like backward stepping at January 0001. Year 10000 cannot round-trip the strict four-digit !Y-m-d grid encoding, so the view ceiling refuses to enter it. (Historical note: until 2026-11 this edge degraded instead — the view rendered year 10000 with a null cursor date and a refusing selectDate(), never crashing, and QA pinned that tolerated behaviour; the clamp restates the same safety as design rather than accident.) The bounds setters enforce the same window at the boundary: withMinDate/withMaxDate throw InvalidArgumentException naming the date when it lies outside 0001-01-01..9999-12-31 — a zero date (classic MySQL empty-row value) can no longer floor the view into an all-dim dead month.

Selection

Single mode (default) — Enter (via handleKey or the Model) selects the date under the cursor; Esc clears the selection:

$picker = $picker->handleKey(DatePicker::KEY_ENTER);  // SelectDate() under the hood
$picker = $picker->handleKey(DatePicker::KEY_ESCAPE); // ClearDate() under the hood
$picker = $picker->clearDate();                       // programmatic equivalent
$picker = $picker->toggleSelection();                 // select-or-clear in one call

If the cursor rests on an empty lead-in/trailing grid cell, Enter is REFUSED in every mode (the cursor only moves within the current grid; arrow keys do not wrap into neighbouring months). A dimmed, out-of-bounds day is refused too. Both refusals return the picker unchanged and surface as a selection_refused event when a bare Enter drove the key through Model (see Events).

Range mode — the first Enter sets the start, the second the end (normalized so start ≤ end), a third restarts:

$picker = $picker->withRangeMode(true);
$picker = $picker->handleKey(DatePicker::KEY_ENTER); // rangeStart
// ... move cursor ...
$picker = $picker->handleKey(DatePicker::KEY_ENTER); // rangeEnd (complete)
$picker = $picker->rangeStart();
$picker = $picker->rangeEnd();

Restoring a saved range does not need keystrokes: withRange($from, $to) presets both endpoints programmatically — each must lie inside the current bounds (throws naming the offender otherwise) and they may not be crossed. It deliberately does not enable range mode; compose the two:

$picker = $picker
    ->withRange(new \DateTimeImmutable('2026-05-04'), new \DateTimeImmutable('2026-05-08'))
    ->withRangeMode(true);
$cleared = $picker->withRange(null); // clears both endpoints, keeps the mode

Min/max bounds

$picker = $picker
    ->withMinDate(new \DateTimeImmutable('2026-03-10'))
    ->withMaxDate(new \DateTimeImmutable('2026-05-20'));

$picker->inBounds(new \DateTimeImmutable('2026-04-01')); // true
$picker = $picker->withoutMinDate();  // lift one bound again
$picker = $picker->withoutMaxDate();

Bounds are compared at midnight (time-of-day is ignored). Setting a bound pulls the currently viewed month into the window and re-clamps the cursor. Selecting a date outside the window is refused (the receiver is returned unchanged); an existing selection is never retroactively cleared — it simply remains dimmed like any other out-of-bounds day. Each setter throws an InvalidArgumentException only when the new bound crosses the existing one — setting minDate after maxDate (or maxDate before minDate) is accepted as long as the resulting pair stays ordered.

Today anchor

$picker = $picker->withToday(new \DateTimeImmutable('2026-05-15')); // pin "today"
$picker = $picker->withoutToday();     // hide the marker (no today cell renders)
$picker = $picker->withClockToday();   // follow the wall clock again

withoutToday() is a true hide (dp-33): until withClockToday() or a fresh withToday() restores an anchor, no cell wears the today/selected-today style (the only marker-suppression route since invalid SGR is refused — an empty style string would have been a lie). goToToday() still navigates to the real current day while hidden: the date exists, the highlight is off (unless that day lies outside a min/max window, in which case the view stays clamped inside the window — see the Min/max bounds section above). A clock-following picker re-reads the wall clock on every render, so a session open across midnight silently repaints a different today — there is no tick source to cache against, by design.

Rendering

echo $picker->view();                 // default 21 columns, no week numbers
echo $picker->view(30, true);         // 34 columns: 30-wide grid + 4-cell week column

view() takes a column width and a showWeekNumbers flag. The TOTAL width — the width-wide calendar area plus the optional 4-cell ISO week column — is clamped into [natural grid: 21 without a week column / 25 with one, 63] and never rejected. The floor guarantees all seven day columns stay visible (a narrower request would amputate the Friday/Saturday columns while leaving their days selectable), so the rendered width is never below the natural grid. Those two arguments are optional: a null argument falls back to the picker's configured render state (withWidth() / withShowWeekNumbers()), so the argless contract render honours the host's intent without every caller re-passing it.

Because out-of-band requests clamp silently, a host that lays out around the picker should not shadow the arithmetic: renderWidth() is the exact oracle, running the same clamp path as view() for the same arguments (and falling back to the stored render state when called argless):

$picker->renderWidth(30, true);      // 34 — what view(30, true) will measure
$picker->renderWidth(64);            // 63 — the band ceiling, never rejected

The band's endpoints are published too: DatePicker::MIN_TOTAL_WIDTH (21, plus the 4-cell week column when enabled) and DatePicker::MAX_TOTAL_WIDTH (63).

Sizing for hosts

Every render is exactly nine rows:

Row Content
0 header (May 2026, locale template)
1 day-name abbreviations
2 ─ separator
3–8 six week rows
  • Clamped to the band, never rejected. A request below the natural floor clamps UP (a host asking for 10 columns receives 21, or 25 with the week gutter — more than asked), and a request above 63 clamps DOWN to MAX_TOTAL_WIDTH. renderWidth() is the oracle of that law.
  • Height never clips or scrolls. On a six-row region, rows 7–8 simply fall off the bottom — measuring the container is the host's duty; reserve nine rows (or place the widget in scrollable chrome).
  • The separator is box-drawing ─ (U+2500): the grid assumes a UTF-8 output charset and will mojibake on latin1/CP437 hosts.
  • The ISO week column renders LEFT, shifting the seven-cell band four columns right — the geometry hitTest() mirrors, so coordinate math must use the same flag.

Mouse seam. hitTest($col, $row) maps a character coordinate of a rendered view to the DateTimeImmutable under it, or null — header, day-name row, separator, the week-number gutter, blank lead-in/trailing cells, and out-of-band padding all answer null and never throw. It mirrors the picker's week-column state (third argument overrides it), so a host with a mouse-aware framework converts its click cells and hits this seam instead of re-deriving the grid math; which coordinates are even clickable (chrome vs content zone-marking) stays host-side.

Styling

Seven style setters accept bare SGR digit strings (e.g. '7', '1;31', '4;35') up to SGR_MAX_LEN (32 characters). The accept set and the decoder are one enumerated truth (SUPPORTED_SGR): attributes 1-7 and 9, foregrounds 30-37/90-97, backgrounds 40-47/100-107. Anything else — escape sequences, dangling delimiters, the extended-color introducers 38/48 and 58, the reset/off codes (0, 21-29, 39, 49, 53), 8 (hidden) and out-of-table numbers — is refused loudly with the offending code named, because a setter that silently dropped the code (or mis-read 58;5;9 as blink+strike) would be a style lie. Blink 5/6 is accepted but discouraged — prefer 1/4/7; hosts with a reduced-motion lint should avoid it:

$picker = $picker
    ->withHeaderStyle('1;36')
    ->withDayNameStyle('1')
    ->withTodayStyle('1;33')
    ->withSelectedStyle('1;32')
    ->withSelectedTodayStyle('1;33;44')
    ->withCursorStyle('7')
    ->withRangeStyle('4;35');

Shipped defaults (the values a fresh picker renders with — the example above deliberately overrides them):

Setter Default SGR Renders as
withHeaderStyle '1;37' bold white
withDayNameStyle '90' bright black
withTodayStyle '1;32' bold green
withSelectedStyle '1;36' bold cyan
withSelectedTodayStyle '1;33' bold yellow
withCursorStyle '7' reverse video
withRangeStyle '1;35' bold magenta

There is no dedicated disabled-day style: every out-of-bounds day always receives the built-in faint composition, layered onto whichever style the chain above chose, and none of the seven setters influence it.

Accessibility and terminal fallbacks

The picker emits raw SGR unconditionally — nothing in this lib consults a colour profile, honours NO_COLOR, or sniffs for dumb terminals. That policy belongs to the host, and the seams are:

  • Strip host-side. For text-safe output, pipe view() through the host's own ANSI stripper (sugar-core's Ansi::strip is the same seam the golden tests use), and run the optional ColorProfile ladder in the host framework — this widget prints digits and leaves the decision to the consumer.
  • Monochrome at the source. Because empty style strings are refused (see Styling), a colourless build re-points every setter at attribute-only codes, e.g. ->withHeaderStyle('1')->withDayNameStyle('2')->withTodayStyle('1;4') ->withSelectedStyle('3')->withSelectedTodayStyle('1;3') ->withCursorStyle('7')->withRangeStyle('9') — bold / faint / italic / underline / reverse / crossed-out stay distinguishable without any colour channel.
  • Marginal contrast. The shipped 90 bright-black day-name and week styles are the lowest-contrast defaults; 37 or 97 are the suggested alternates on dark themes.
  • Which cues survive a colourless display. The cursor's reverse block and the faint attribute on disabled days do (faint composes onto the state colour rather than masking it, so a dimmed today keeps BOTH cues); green/cyan/yellow state colours alone do not. Where even that is not enough, withoutToday() (see Today anchor) removes the marker outright rather than faking suppression.
  • Blink. Codes 5/6 decode but are discouraged (see Styling); hosts with a reduced-motion lint should avoid them.

Embedding hazard: do not bind bare Ctrl chords to quit

NUL bytes and corrupted paste sequences arrive on many terminals as Char messages with invented Ctrl chords (rune='', ctrl=true). This widget's Model is inert to them — unguarded keys are ignored and guarded keys refuse loudly — but a host that maps "any Ctrl chord" to quit force-quits on every garbage paste. Bind quit to a named key or an explicit, labelled chord.

Keyboard handling

handleKey() is the non-TEA wire surface; Model is the TEA one. Both channels' vocabularies, in one table (dp-10, printables added by dp-36):

Action handleKey() string (KEY_* value) Model KeyMsg type
Move cursor left, right, up, down KeyType::Left/Right/Up/Down
First/last selectable day home, end KeyType::Home, KeyType::End
Select / arm or complete a range leg enter KeyType::Enter
Clear selection / cancel range esc (BC wire value) or escape (sugar-core spelling) — both act KeyType::Escape
Month back / forward pgup, pgdn KeyType::PageUp, KeyType::PageDown
Vim-style cursor moves — (Model channel only) bare lowercase runes h/j/k/l on KeyType::Char
Jump to today — (Model channel only) bare rune t on KeyType::Char
Toggle selection (no-move Enter) — (Model channel only) space — KeyType::Space or KeyType::Char with rune=' '; single mode only
Year jump programmatic only: goToPreviousYear(), goToNextYear() —

Unrecognized keys are surfaced through error_log('datepicker: unknown key …') and leave the receiver unchanged (loud at integration time, state-safe at runtime — no throw). A TEA application never needs to call handleKey(): the Model maps every KeyType arm itself.

Honest limitations — three upstream features are deliberate divergences, not omissions: (1) upstream's Focus enum, tab-cycling and per-focus arrows are DROPPED here (single-cursor design, so no key vocabulary exists for them); (2) upstream's replaceable-every-binding key.Binding seam is NOT ported — the mapping is a fixed table (KEY_* constants plus the dp-36 printable arms), and rebinding is a host-layer job: match the keys you want in your own input reducer and call the public picker methods (moveCursorLeft(), goToNextMonth(), toggleSelection(), …) or emit your own KeyMsg equivalents — every action the fixed table can take is also a public method; (3) there is no month-wrap on arrow keys and no typeahead year entry (arrows clamp at the grid edge and can rest on empty lead-in/trailing cells, where Enter is refused in every mode — dp-26). Home and End land on the first/last selectable day of the viewed month: the jump scans past dimmed min/max-violating days, and a whole month outside the window leaves the cursor in place. Chord policy: through the Model, the action keys Enter, Escape, PageUp, PageDown and the printable bindings h/j/k/l/t/space are host-reserved under ANY chord — Ctrl, Alt or Shift held — so a chat host's Shift+Enter newline (or a terminal's Ctrl+L) is never hijacked, and a shifted 'H' is not silently a left arrow either. The arrows and Home/End are the deliberate terminal-compatibility exception: they act bare and chorded alike. PageUp/PageDown step one month on both channels; larger jumps between months and years go through the goTo*() methods.

Events

Model::new() takes an optional EventStore as its second argument. When one is attached, every state transition — a value change, never a flag edge — is recorded as a typed event the host drains with release() after each update. Each drained row has the fixed shape array{type: string, payload: array, time: int} — time is whole epoch-seconds from the store's clock seam (real wall clock by default; inject EventStore::new(clock: …) for deterministic tests). Event kinds are PickerEvent constants; compare against the constants, never hand-copied strings (a typo in a raw literal fails silently, a typo in a class constant does not):

  • PickerEvent::CURSOR_MOVED ('cursor_moved') — payload {index, date} (date is Y-m-d or null on an empty cell) — the cursor index changed.
  • PickerEvent::RANGE_STARTED ('range_started') — payload {date} (Y-m-d) — range mode's first Enter armed the start (unset → set).
  • PickerEvent::RANGE_RESTARTED ('range_restarted') — payload {from, to} — a third Enter on a completed range dropped the end and re-armed the start (dp-09; to may equal from, the dropped end is the transition).
  • PickerEvent::RANGE_CLEARED ('range_cleared') — payload {from} — range endpoints went from armed to fully cleared (Escape, pending or completed alike).
  • PickerEvent::DATE_SELECTED ('date_selected') — single mode: payload {date} when the selected day changed; range mode: {date, rangeStart, rangeEnd} when the end becomes non-null (the start-arming Enter is reported by RANGE_STARTED, not here).
  • PickerEvent::DATE_CLEARED ('date_cleared') — empty payload {} — the single-mode selection went from set to unset (Esc or a toggling Enter).
  • PickerEvent::MONTH_CHANGED ('month_changed') — payload {year, month} — the viewed month stepped (PageUp/PageDown); a step clamped by the bound months records nothing.
  • PickerEvent::SELECTION_REFUSED ('selection_refused') — payload {date, reason} — a bare Enter could not select (dp-09, symmetric across modes since dp-26). reason is out_of_bounds (dimmed day under cursor, date carries it) or empty_cell (blank lead-in/trailing cell — the single-mode first-of-month fallback that could select a day up to six cells away is retired; date is null there). A chorded Enter never acts, so it is never refused either.

Recording channel (settled ruling): the TEA Model is the only emitter. DatePicker::handleKey() and the imperative methods are the non-TEA surface and record nothing — a host driving the picker directly either wraps it in a Model or diffs picker states itself; that asymmetry is the contract, not an oversight.

The event census is now complete: range restarts, cancels, month steps and refusals are all announced. Polling stays the authoritative channel — a SELECTION_REFUSED is an announcement of an error state a host may surface immediately, not a replacement for reading selectedDate()/rangeStart()/ rangeEnd() after each update.

API surface

Beyond DatePicker itself, the shipped public classes are:

  • PickerEvent — final const-only class: the eight recorded event kinds (CURSOR_MOVED, RANGE_STARTED, RANGE_RESTARTED, RANGE_CLEARED, DATE_SELECTED, DATE_CLEARED, MONTH_CHANGED, SELECTION_REFUSED) as the published wire vocabulary; see Events above.
  • DateRange — an immutable start/end value object: promoted public readonly $start/$end plus withStart()/withEnd() clones; contains($date) (compares calendar days, timezone-safe — while the range is open-ended a null end admits every day from the start forward, the mid-selection caveat), durationInDays(?$now = null) (whole elapsed days — 2026-01-01 to 2026-01-03 returns 2 although the calendar span covers three days; signed: an inverted range returns the negative count while contains() still reads it as empty; optional clock seam: a null end measures against $now), and isComplete().
  • EventStore / EventStoreInterface — the host-facing transition channel: record($type, $payload), release() (drain-and-clear), hasEvents(), count(), and a __construct(?\Closure $clock = null) deterministic-time seam for tests. It keeps a bounded ring of MAX_EVENTS (1000) and evicts the oldest records beyond that, so a host that never drains cannot grow memory without limit.
  • Navigation::gridIndexToDate($index, $month, $year) — maps a raw grid index to a date; it throws when month is outside 1–12 or year is below 1, which the picker's view floor prevents from ever reaching it in normal use.
  • Lang — the lib-internal i18n façade (extends the sugar-core base): it exists so Lang::t() resolves through this package's namespace and is not a host-facing API — consume translations by editing lang/<code>.php, never by calling into this class.
  • Model — the TEA wrapper (init()/update($msg)/view()/ subscriptions()). Its update() command is always null — a host learns the outcome by polling picker()->selectedDate()/rangeStart()/rangeEnd() after each update, never from a returned command. The EventStore reports the same transitions for convenience, but not on range mode's cancel and restart paths (see Events above), so polling stays authoritative. The shared Core\Model::view() contract is argless, and it honours the picker's render state: configure width and the week-number column with withWidth()/withShowWeekNumbers() and every contract-driven render uses them; an explicit picker()->view($width, $showWeekNumbers) still wins per call (a null argument falls back to state either way).
  • DatePicker accessors — minDate(), maxDate(), isRangeMode(), cursorIndex(), viewMonth(), viewYear(), dateAtCursor(), todayHidden(), hitTest() (see Mouse seam), and moveToDate() (aim the cursor at an existing value).
  • Naming — camelCase is the house API (AGENTS.md). The picker's verbs and accessors are declared in camelCase (goTo*(), setTime(), move*(), selectDate(), clearDate(), toggleSelection(), selectedDate(), isSelecting(), cursorIndex(), viewMonth(), viewYear(), view(), with*Style()) alongside the with*()/without*() builders, handleKey(), rangeStart(), rangeEnd(), isRangeMode(), minDate(), maxDate() and dateAtCursor(). They were originally declared PascalCase mirroring upstream bubble-datepicker; the rename keeps every PascalCase call site working unchanged because PHP method resolution is case-insensitive — the old spellings (GoToPreviousMonth(), View(), With*Style(), …) are deprecated in guidance, not in dispatch. There is still no setRangeMode(): the shipped spelling is withRangeMode(); Model::view() stays lowercase because that is the sugar-core contract.

Internationalization

Day abbreviations and month names resolve through the shared sugar-core i18n lookup (Lang::t): keys day.0–day.6 (Sunday-first) and month.1–month.12 live in lang/en.php, which is the source of truth. Seventeen locales ship: ar, cs, de, en, es, fr, it, ja, ko, nl, pl, pt, pt-br, ru, tr, zh-cn, zh-tw — the recommended set from LOCALES.md. The lookup ladder is exact → base → en → raw, so a new locale is just another lang/<code>.php file carrying the same key set. Every shipped file — not merely English — is machine-checked by LangCoverageTest, which closes the ladder hole where a missing or partial locale file could hide behind the English fallback: its glob walk over the real files goes red instead. The budgets ride the same gate: day.* values fit the 3-column cell budget (an oversized name is clipped to its own slot at render time, never overwriting the next column), month.* fit the 16-column header budget (the natural 21-wide floor minus the year slot), and the day.0–day.6 positional Sunday-first order is pinned.

The keys are POSITIONAL, and there is no week-start knob: day.0 labels the leftmost column, day.6 the rightmost, Sunday-first — translating the file changes the labels, never the layout. A locale that really starts its week on Monday must translate positionally (day.0 = that locale's Sunday name, e.g. So in German), and a consumer who instead writes day.0 = Monday ships silently mislabeled columns. The grid geometry itself — and therefore what a hitTest() coordinate means — is Sunday-first for every locale.

Shared foundations

  • sugar-cellbuffer — month grid rendered as a 7-column × N-row Buffer; the day cells are laid out by DatePicker, and Buffer::toAnsi() serializes them to canonical ANSI SGR output.
  • sugar-core — Util\Width is the canonical display-width oracle (the picker delegates its cell placement widths to it); I18n\Lang powers the translations above.
  • sugar-testing — golden-file snapshot tests via assertGoldenAnsi() pin canonical month layouts.

Examples

php examples/basic.php         # single-mode walk: navigate, move, select
php examples/constraints.php   # min/max bounds: refused and accepted Enter legs
php examples/interactive.php   # real Program loop: scripted KeyMsgs through update(), EventStore transcript

The third example, examples/interactive.php, mounts Model inside a sugar-core Program loop and feeds it a fixed script of KeyMsgs — the runnable reference for how a live keystroke travels through update(). It ends by printing the drained EventStore transcript plus the final grid, so the event wiring is verifiable without a TTY. Every transcript line is a byte-for-byte store event (cursor_moved, date_selected, date_cleared, range_started appear in this script — four of the eight kinds); the only other line is the host's mode switch, prefixed [host] so it can never be mistaken for a fifth wire event. The loop reads from a held-open socket pair rather than STDIN, because Program turns a real stdin EOF into a cooperative quit that would truncate the script mid-run.

Run them from the lib root; from a standalone clone of the split repo, run composer install first so the sibling sugarcraft/* packages resolve.

License

MIT

Credits & inspiration

Design antecedent: EthanEFung/bubble-datepicker; SugarCraft is developed as a native PHP project.