SugarDatepicker
Interactive month-grid date picker
SugarDatepicker is a month-grid date picker for terminal UIs. It offers single-date and range selection, min and max bounds, keyboard and mouse seams, and localized day and month names in 17 locales. It is a port of the interaction model of EthanEFung/bubble-datepicker (Go), and it renders to an ANSI string. Use DatePicker for a pure value you drive yourself, or Model to run it as a sugar-core TEA model.
Install
composer require sugarcraft/sugar-datepicker:@dev
The package has no tagged release yet, so it ships only dev-master, and the @dev constraint is required until the first version tag lands. It needs PHP ^8.3 and ext-mbstring, and it pulls in sugarcraft/sugar-core and sugarcraft/sugar-cellbuffer. The package was renamed in 2026-10 from sugarcraft/sugar-calendar, and the old name is frozen at its last release, so depend on the new name only.
Quickstart
use SugarCraft\DatePicker\DatePicker;
// The picker opens on the seed date's month, with the cursor on the seed.
// Every step returns a new picker, so rebind each result.
$picker = DatePicker::new(new \DateTimeImmutable('2026-01-15'))
->handleKey(DatePicker::KEY_DOWN) // one row down: Thursday the 22nd
->selectDate(); // select the date under the cursor
echo $picker->selectedDate()->format('Y-m-d'); // 2026-01-22
echo $picker->view(); // the month grid
// Range mode: the first Enter sets the start, the second sets the end.
$range = DatePicker::new(new \DateTimeImmutable('2026-01-15'))
->withRangeMode(true)
->handleKey(DatePicker::KEY_DOWN)->handleKey(DatePicker::KEY_ENTER)
->handleKey(DatePicker::KEY_RIGHT)->handleKey(DatePicker::KEY_RIGHT)
->handleKey(DatePicker::KEY_ENTER);
[$range->rangeStart()->format('j'), $range->rangeEnd()->format('j')]; // ['22', '24']
Drive the same picker as a TEA model when your host runs a sugar-core program loop. The Model maps each KeyMsg itself, and it records transitions to an optional event store:
use SugarCraft\Core\KeyType;
use SugarCraft\Core\Msg\KeyMsg;
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();
Concepts
DatePicker is an immutable value. It holds a viewed month, a cursor on one grid cell, an optional single selection or range, min and max bounds, a today anchor, and the render state (width, week numbers and styles). Each method returns a new picker, and nothing mutates in place. The grid is always six rows of seven days, Sunday first, with blank lead-in and trailing cells. The cursor can rest on a blank cell, but Enter is refused there.
A selection is either refused or accepted, and nothing partial is kept. Enter on a blank cell, or on a day outside the bounds, returns the picker unchanged. The same refusal surfaces as a selection_refused event when the key arrives through Model. Navigation never wraps and never throws. Stepping past a bound, or past the calendar floor at January 0001, is a no-op.
The Model is the only channel that records events. DatePicker::handleKey() and the imperative methods record nothing, by design. A host that drives the picker directly either wraps it in a Model or compares the picker states itself.
Tasks
Limit selection to a date window
Set both bounds. Setting a bound pulls the viewed month into the window and re-clamps the cursor. An out-of-window selection is refused, and an existing selection that falls outside is dimmed, never cleared. examples/constraints.php walks through clamped navigation and refused Enter presses.
use SugarCraft\DatePicker\DatePicker;
$picker = DatePicker::new(new \DateTimeImmutable('2026-05-15'))
->withMinDate(new \DateTimeImmutable('2026-05-10'))
->withMaxDate(new \DateTimeImmutable('2026-07-20'));
$picker->inBounds(new \DateTimeImmutable('2026-04-01')); // false
$picker = $picker->withoutMinDate(); // lift one bound again
Restore a saved range
withRange() presets both endpoints, and each must lie inside the current bounds. It does not enable range mode, so compose the two calls. Pass null to clear the endpoints and keep the mode.
$picker = DatePicker::new(new \DateTimeImmutable('2026-05-15'))
->withRange(new \DateTimeImmutable('2026-05-04'), new \DateTimeImmutable('2026-05-08'))
->withRangeMode(true);
$cleared = $picker->withRange(null); // clears both endpoints, keeps range mode
Pin the reference "today"
By default the today marker follows the wall clock, and it is re-read on every render. withToday() pins a reference day, which keeps renders deterministic in tests. withoutToday() hides the marker, and withClockToday() resumes wall-clock following. goToToday() still navigates to the real current day while the marker is hidden.
use SugarCraft\DatePicker\DatePicker;
$picker = DatePicker::new(new \DateTimeImmutable('2026-05-15'))
->withToday(new \DateTimeImmutable('2026-05-15'));
$hidden = $picker->withoutToday();
$hidden->todayHidden(); // true
Size the grid for a host layout
The width is clamped into a band, never rejected. Ask renderWidth() for the exact width that view() will produce, and reserve nine rows for every render.
use SugarCraft\DatePicker\DatePicker;
$picker = DatePicker::new(new \DateTimeImmutable('2026-05-15'));
$picker->renderWidth(30, true); // 34: a 30-wide grid plus the 4-cell week column
$picker->renderWidth(64); // 63: clamped to MAX_TOTAL_WIDTH
echo $picker->view(30, true);
Resolve a mouse click to a date
hitTest() maps a character coordinate in the rendered view to the date under it, or null for chrome, blank cells and padding. It never throws. It reads the week-column state the picker was configured with, so a host must use the same flag it renders with.
use SugarCraft\DatePicker\DatePicker;
$picker = DatePicker::new(new \DateTimeImmutable('2026-05-15'));
$date = $picker->hitTest(0, 0); // the header row is chrome, so null
Record transitions for analytics or undo
Pass an EventStore to Model::new(), and drain it with release() after each update. Every value change is recorded as one of eight PickerEvent kinds. release() returns the rows oldest first, each shaped array{type, payload, time}, where time is whole epoch seconds. The payload keys for each kind are:
cursor_moved:{index, date}, withdatenull on a blank cell.range_started:{date}.date_selected:{date}in single mode, or{date, rangeStart, rangeEnd}when a range completes.date_cleared: an empty payload.range_restarted:{from, to}, wheretomay equalfrom.range_cleared:{from}.selection_refused:{date, reason}, wherereasonisout_of_boundsorempty_cell, anddateis null on a blank cell.month_changed:{year, month}.
examples/interactive.php prints the drained transcript.
API reference
The table covers the public surface. Each DatePicker method returns a new picker, and each Model method returns a new model, unless the row says otherwise.
| Class | Method | Description |
|---|---|---|
DatePicker | DatePicker::new(?\DateTimeImmutable $time = null) | A picker on the seed's month, with the cursor on the seed. Without a seed, it opens on the current month. |
DatePicker | goToPreviousMonth() / goToNextMonth() / goToPreviousYear() / goToNextYear() / goToToday() | Step the viewed month or year. Steps clamp at the calendar floor, the ceiling and the bounds. |
DatePicker | setTime(\DateTimeImmutable) / moveToDate(\DateTimeImmutable) | Jump the view to a month, or put the cursor on a given day. |
DatePicker | moveCursorLeft() / moveCursorRight() / moveCursorUp() / moveCursorDown() | Move the cursor one cell. The cursor stays within the grid, and it does not wrap into a neighboring month. |
DatePicker | handleKey(string $key) | The string-keyed input door. Accepts the KEY_* constants, and returns the picker unchanged on an unknown key. |
DatePicker | selectDate() / clearDate() / toggleSelection() | Select the cursor date, clear the selection, or do one of the two. A refused selection returns the picker unchanged. |
DatePicker | selectedDate() / isSelecting() | The single selection, or null, and whether a selection is set. |
DatePicker | withRangeMode(bool) / isRangeMode() | Switch range mode on or off, and read the mode. |
DatePicker | rangeStart() / rangeEnd() / withRange(?\DateTimeImmutable $start, ?\DateTimeImmutable $end = null) | Read the endpoints, or preset both. Each endpoint must lie in the bounds, and they may not be crossed. The preset does not enable range mode. |
DatePicker | withMinDate(\DateTimeImmutable) / withMaxDate(\DateTimeImmutable) / withoutMinDate() / withoutMaxDate() | Set or lift a bound. A date outside 0001-01-01..9999-12-31 throws InvalidArgumentException. |
DatePicker | minDate() / maxDate() / inBounds(\DateTimeImmutable) / selectionTarget() / selectionRefusal() | Read the bounds, test a date, or read the date the next Enter would act on and the reason it would be refused. |
DatePicker | withToday(\DateTimeImmutable) / withoutToday() / withClockToday() / todayHidden() | Pin, hide, or resume the today marker, and read whether it is hidden. |
DatePicker | cursorIndex() / dateAtCursor() / viewMonth() / viewYear() | Read the cursor's grid index, the date under it (or null on a blank cell), and the viewed month and year. |
DatePicker | view(?int $width = null, ?bool $showWeekNumbers = null) / renderWidth(?int $width = null, ?bool $showWeekNumbers = null) | Render the nine-row grid, or report the exact width it will occupy. A null argument falls back to the configured state. |
DatePicker | withWidth(int) / withShowWeekNumbers(bool) | The render state that view() uses when no argument is passed. |
DatePicker | withHeaderStyle() / withDayNameStyle() / withTodayStyle() / withSelectedStyle() / withSelectedTodayStyle() / withCursorStyle() / withRangeStyle() | The seven SGR style setters. Each accepts a bare SGR parameter string and refuses anything else. |
DatePicker | hitTest(int $col, int $row, ?bool $showWeekNumbers = null) | Map a character coordinate to the date under it, or null. Never throws. |
DatePicker | DatePicker::MIN_TOTAL_WIDTH / DatePicker::MAX_TOTAL_WIDTH | The width band: the floor is 21 cells, or 25 with the week column, and the ceiling is 63 cells in both cases. |
Model | Model::new(?\DateTimeImmutable $time = null, ?EventStoreInterface $store = null, ?DatePicker $picker = null) | A TEA model. Pass a seed time or a configured picker, never both. Passing both throws. |
Model | init() / update(Msg $msg) / view(?int $width = null, ?bool $showWeekNumbers = null) / subscriptions() | The sugar-core Model contract. init() returns null, and update() always returns a null command. |
Model | picker() / withPicker(callable|DatePicker) | Read the wrapped picker, or change it. The callable form receives the current picker. The event store stays attached. |
EventStore | EventStore::new(?\Closure $clock = null) / record(string $type, array $payload = []) / release() / hasEvents() / count() | A bounded ring of up to MAX_EVENTS (1000) transitions. release() drains it. The clock seam makes tests deterministic. |
EventStoreInterface | record() / release() / hasEvents() / count() | The contract Model consumes, for a store of your own. |
PickerEvent | Eight string constants, one per wire event | CURSOR_MOVED, RANGE_STARTED, RANGE_RESTARTED, RANGE_CLEARED, DATE_SELECTED, DATE_CLEARED, MONTH_CHANGED and SELECTION_REFUSED. |
DateRange | DateRange::new(?\DateTimeImmutable $start = null, ?\DateTimeImmutable $end = null) / withStart() / withEnd() / contains() / durationInDays(?\DateTimeImmutable $now = null) / isComplete() | The immutable start and end value behind range mode. |
Navigation | Navigation::gridIndexToDate(int $gridIndex, int $month, int $year) | Convert a raw grid index to a date. Throws InvalidArgumentException when the month is outside 1 to 12, or the year is below 1. |
Only methods declared in sugar-datepicker/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\DatePicker
DatePicker final class
Interactive date picker component.
| Method | Summary |
|---|---|
__construct(?\DateTimeImmutable $time = null) | Public constructor — kept as a house exception pending a v2 convergence on private ctors; the docs advertise DatePicker::new() as the entry point. |
static new(?\DateTimeImmutable $time = null): self | |
goToPreviousMonth(): self | |
goToNextMonth(): self | |
goToPreviousYear(): self | |
goToNextYear(): self | |
goToToday(): self | |
withMinDate(\DateTimeImmutable $min): self | Set the earliest selectable date. If the current view is before the bound's month it is pulled back into the window. |
withoutMinDate(): self | Remove the lower selection bound. |
withMaxDate(\DateTimeImmutable $max): self | Set the latest selectable date. If the current view is after the bound's month it is pulled back into the window. |
withoutMaxDate(): self | Remove the upper selection bound. |
minDate(): ?\DateTimeImmutable | |
maxDate(): ?\DateTimeImmutable | |
inBounds(\DateTimeImmutable $date): bool | Whether $date lies inside the configured bounds (inclusive). |
selectionTarget(): ?\DateTimeImmutable | The date an Enter on the CURRENT cursor state would attempt to apply: the cursor date, or null on a blank lead-in/trailing cell — the single-mode first-of-month fallback was retired in dp-26 so both modes treat the blank cell identically (refuse, announce). Pure query over current state (dp-09 refusal seam), which is exactly what selectDate() and handleRangeEnter() act on. |
selectionRefusal(): ?string | Why a bare Enter on the CURRENT cursor state would be refused, or null when it would apply (dp-09, symmetric for both modes by dp-26). Vocabulary mirrors PickerEvent::SELECTION_REFUSED payloads: out_of_bounds (dimmed day under cursor) and empty_cell (blank lead-in/trailing cell — Enter there never selects a distant day). |
withToday(\DateTimeImmutable $today): self | Pin the "today" reference (testability). Default (unset) uses the real wall-clock now, so production behavior is unchanged. Pinning also un-hides the marker if withoutToday() had hidden it (dp-33). |
withoutToday(): self | Hide the today marker entirely (dp-33 honest semantics): no cell renders with the today/selected-today style until withClockToday() restores the wall-clock anchor or withToday() pins a new one. Navigation by goToToday() still works while hidden — the date exists, only the marker is off. |
withClockToday(): self | Follow the real wall clock as "today" again after withoutToday() — the state a freshly built picker starts in. The marker re-reads the clock on every render, so a session crossing midnight silently repaints a different today (no tick source, by design; dp-33 documentation flip). |
todayHidden(): bool | True while the today marker is hidden by withoutToday() (dp-33). |
setTime(\DateTimeImmutable $t): self | |
moveToDate(\DateTimeImmutable $date): self | Aim the cursor at an arbitrary date (the edit-existing-value recipe): when $date falls inside the currently viewed month the cursor lands on its cell; otherwise the view is unchanged and the cursor is re-aimed at the viewed month's FIRST SELECTABLE day (min/max consulted via firstValidIndex — the same "aim or reset to first valid" law the constructor and setTime follow). The cursor never keeps a stale position on an out-of-month jump: an off-screen cursor is worse than a reset one. Immutable. |
moveCursorLeft(): self | |
moveCursorRight(): self | |
moveCursorUp(): self | |
moveCursorDown(): self | |
selectDate(): self | Enter selection mode and set the selected date to the cursor date. |
clearDate(): self | Clear selection / exit selection mode. |
toggleSelection(): self | |
withRangeMode(bool $mode): self | |
rangeStart(): ?\DateTimeImmutable | |
rangeEnd(): ?\DateTimeImmutable | |
isRangeMode(): bool | |
withRange(?\DateTimeImmutable $start, ?\DateTimeImmutable $end = null): self | Preset both range endpoints programmatically (dp-19, sugar-datepicker-021): restores a saved [from, to] pair without keystroke simulation — the fragile path that had to survive bounds, clamps and month arithmetic by accident. |
handleKey(string $key): self | Handle keyboard navigation and selection (single AND range mode). |
selectedDate(): ?\DateTimeImmutable | |
isSelecting(): bool | |
cursorIndex(): int | |
viewMonth(): int | |
viewYear(): int | |
dateAtCursor(): ?\DateTimeImmutable | Get the date at the current cursor position, or null when the cursor sits on an empty cell (before the 1st of the month or past the last day in the 6×7 grid). |
hitTest(int $col, int $row, ?bool $showWeekNumbers = null): ?\DateTimeImmutable | Map a character coordinate in a rendered view to the date under it, or null (dp-34). This is the click-to-select seam: a host that receives mouse cells from its framework hits them here instead of reimplementing the grid math — no cell is ever "selected" by a coordinate that renders a blank lead-in/trailing cell, a header, the day-name row, the separator, or out-of-grid padding. NEVER throws. |
renderWidth(?int $width = null, ?bool $showWeekNumbers = null): int | Exact total width the renderer will produce for the given intent, following the SAME clamp path view() takes — the predictable oracle behind the silent-clamp contract (dp-23, sugar-datepicker-026). Null arguments fall back to the stored withWidth()/ withShowWeekNumbers() state, so renderWidth() answers "what will my argless view() measure?" for TEA hosts. |
view(?int $width = null, ?bool $showWeekNumbers = null): string | |
withHeaderStyle(string $s): self | |
withDayNameStyle(string $s): self | |
withTodayStyle(string $s): self | |
withSelectedStyle(string $s): self | |
withSelectedTodayStyle(string $s): self | |
withCursorStyle(string $s): self | |
withRangeStyle(string $s): self | |
withWidth(int $width): self | Configure the render width used by view() and Model::view() whenever no explicit width argument is passed. The intent is stored as given — the renderer clamps into the visible band at draw time (a host sizing from a live terminal may set anything; it will never be rejected). |
withShowWeekNumbers(bool $show): self | Configure whether the ISO week-number column renders by default. As with withWidth(), this is the state-side default; an explicit view($width, $showWeekNumbers) argument still wins per call. |
DateRange final readonly class
Represents a date range with start and end dates.
| Method | Summary |
|---|---|
__construct(public ?\DateTimeImmutable $start = null, public ?\DateTimeImmutable $end = null) | |
static new(?\DateTimeImmutable $start = null, ?\DateTimeImmutable $end = null): self | House factory mirroring the constructor. |
withStart(\DateTimeImmutable $start): self | |
withEnd(\DateTimeImmutable $end): self | |
contains(\DateTimeImmutable $date): bool | |
durationInDays(?\DateTimeImmutable $now = null): ?int | Whole elapsed days between start and end — 2026-01-01 to 2026-01-03 returns 2, although the calendar span covers three days. The count is SIGNED: an inverted range (end before start) reports the negative elapsed figure — 2026-01-05 to 2026-01-01 returns -4, never a mirror +4 — so a consumer can tell "backwards" from "same instant". Membership deliberately disagrees: contains() treats an inverted range as empty (false everywhere); the sign is direction information, not an invitation to probe inside. With an open-ended range, $now supplies the closing date; it defaults to real wall-clock now so the pure-integer math stays testable without a clock injection when the caller wants the live figure. |
isComplete(): bool |
EventStore final class
Simple in-memory event store for calendar state changes.
| Method | Summary |
|---|---|
__construct(private readonly ?\Closure $clock = null) | |
static new(?\Closure $clock = null): self | House factory mirroring the constructor; the public ctor stays legal as the declared store exception (CALIBER_LEARNINGS) pending a v2 flip. |
record(string $type, array $payload = []): void | |
release(): array | |
hasEvents(): bool | |
count(): int |
EventStoreInterface interface
Interface for event stores used in DI-friendly event sourcing.
| Method | Summary |
|---|---|
record(string $type, array $payload = []): void | |
release(): array | |
hasEvents(): bool | |
count(): int | Number of events currently held (before the next drain). |
Lang final class
Per-library translation facade for sugar-datepicker.
Model final class
TEA Model wrapper for the DatePicker component.
| Method | Summary |
|---|---|
__construct(private readonly DatePicker $picker, private readonly ?EventStoreInterface $store = null) | Public constructor — kept as a house exception pending a v2 convergence on private ctors; the docs advertise Model::new() as the entry point (same declared deviation as DatePicker's ctor note). |
static new(?\DateTimeImmutable $time = null, ?EventStoreInterface $store = null, ?DatePicker $picker = null): self | Factory: build a new date-picker model. |
init(): ?\Closure | Init returns null — no startup command needed. |
update(Msg $msg): array | Handle a KeyMsg, returning [nextModel, optionalCmd]. |
view(?int $width = null, ?bool $showWeekNumbers = null): string | Render the grid. Null arguments fall back to the picker's configured state (withWidth()/withShowWeekNumbers()), so a framework-driven host invoking the argless Core\Model contract gets the configured grid — not a hard-coded 21×9. |
subscriptions(): ?Subscriptions | No subscriptions needed. |
picker(): DatePicker | Expose the wrapped picker for direct inspection by callers that prefer the imperative API — including month/year navigation reached through goToNextMonth() and friends, which have no dedicated key beyond PageUp/PageDown. |
withPicker(callable|DatePicker $picker): self | Swap the wrapped picker, keeping the SAME EventStore instance wired in. |
Navigation final readonly class
Grid-index → date conversion for the calendar.
| Method | Summary |
|---|---|
static gridIndexToDate(int $gridIndex, int $month, int $year): ?\DateTimeImmutable | Convert grid index to \DateTimeImmutable for given month/year. |
PickerEvent final class
Wire vocabulary for the events the TEA Model records.
Configuration and options
There is no configuration file and no environment variable. Every option is a setter on DatePicker, and every setter returns a new picker.
| Option | Setter | Default | Effect |
|---|---|---|---|
| Seed date | DatePicker::new() | the current month, when no seed is given | The month the view opens on, with the cursor on the seed date. |
| Width | withWidth(int) | 21 cells, the natural grid | Width of the calendar area, clamped into 21 to 63, or 25 to 63 with the week column. |
| Week numbers | withShowWeekNumbers(bool) | off | Shows the ISO week column on the left, which adds 4 cells. |
| Range mode | withRangeMode(bool) | off | The first Enter sets the start, the second the end, and a third restarts the range. |
| Minimum date | withMinDate() | unset | Earliest selectable day. Navigation clamps to its month. |
| Maximum date | withMaxDate() | unset | Latest selectable day. Navigation clamps to its month. |
| Today | withToday() / withoutToday() / withClockToday() | the wall clock | The reference day for the today marker. withoutToday() removes the marker. |
| Event clock | EventStore::new(clock: …) | the real clock | The time source for event timestamps, in whole epoch seconds. |
Keys and input
The picker has a fixed key table. Rebinding is a host job: match the keys you want in your own input reducer, then call the public methods. Every action in the table is also a public method.
| Action | handleKey() string | Model KeyMsg |
|---|---|---|
| Move the cursor | left, right, up, down | KeyType::Left, Right, Up, Down |
| First or last selectable day | home, end | KeyType::Home, KeyType::End |
| Select, or arm and complete a range leg | enter | KeyType::Enter |
| Clear the selection, or cancel a range | esc or escape | KeyType::Escape |
| Previous or next month | pgup, pgdn | KeyType::PageUp, KeyType::PageDown |
| Vim-style cursor moves | none (Model only) | bare h, j, k, l runes |
| Jump to today | none (Model only) | bare t rune |
| Toggle the selection without moving | none (Model only) | space, in single mode |
Year jumps are programmatic only, through goToPreviousYear() and goToNextYear(). Through Model, the action keys and the letter bindings are reserved to the host under any chord. Ctrl, Alt or Shift held means the key is ignored, so a Shift+Enter newline in a chat host is never hijacked. The six navigation keys act with or without a chord.
Theming and styling
Seven setters take bare SGR parameter strings such as 1;36, up to 32 characters. The accepted set is attributes 1 to 7 and 9, foregrounds 30 to 37 and 90 to 97, and backgrounds 40 to 47 and 100 to 107. Anything else is refused and the offending code is named, which includes escape sequences, the extended-color introducers 38 and 48, and the reset codes. Blink codes 5 and 6 are accepted but discouraged.
| Setter | Default SGR | Renders as |
|---|---|---|
withHeaderStyle() | 1;37 | bold, white as truecolor 38;2;229;229;229 |
withDayNameStyle() | 90 | bright black as truecolor 38;2;127;127;127 |
withTodayStyle() | 1;32 | bold, green as truecolor 38;2;0;205;0 |
withSelectedStyle() | 1;36 | bold, cyan as truecolor 38;2;0;205;205 |
withSelectedTodayStyle() | 1;33 | bold, yellow as truecolor 38;2;205;205;0 |
withCursorStyle() | 7 | reverse video |
withRangeStyle() | 1;35 | bold, magenta as truecolor 38;2;205;0;205 |
The picker does not check the terminal. It does not read NO_COLOR, consult a color profile, or detect a dumb terminal, and it does not fall back to basic colors. Basic foregrounds 30 to 37 and 90 to 97, and backgrounds 40 to 47 and 100 to 107, are mapped through the RGB table of sugar-core's ANSI16 palette and emitted as truecolor (38;2 and 48;2). Attribute-only codes 1, 2, 4, 7 and 9 pass through unchanged. Those choices belong to the host. A colorless build can point every setter at attribute-only codes, for example withHeaderStyle('1'), withDayNameStyle('2'), withTodayStyle('1;4'), withSelectedStyle('3'), withSelectedTodayStyle('1;3'), withCursorStyle('7') and withRangeStyle('9').
Out-of-bounds days always get a faint composition on top of whichever style applies, and no setter changes that. The reverse-video cursor and the faint attribute are the cues that survive a colorless display. The default 90 day-name style has the lowest contrast, so 37 or 97 are the suggested alternates on dark themes.
Examples
Each example is a standalone script under examples/, and each runs on built-in input with no terminal required.
examples/basic.phpwalks May and June 2026, then selects 2026-07-12 in July and 2026-12-03 in December, both with the cursor methods.examples/constraints.phpshows min and max bounds, clamped navigation, and refused and accepted Enter presses.examples/interactive.phpmounts the TEA model in a sugar-core program loop, feeds it a scripted list of key messages, and prints the drained event transcript. It is the reference for how a keystroke reachesupdate().
php examples/basic.php
php examples/constraints.php
php examples/interactive.php
May → June 2026
Month-grid date picker with cursor and selected day, walking the sections of examples/basic.php.
Min and max constraints
The same picker bounded between two dates.
Interactive range selection
The scripted run from examples/interactive.php: cursor moves, a single selection, then a range.Testing
composer install
vendor/bin/phpunit
The suite pins the canonical month layouts with golden-file snapshots through sugar-testing. LangCoverageTest checks every locale file against the English key set. ReadmeSnippetResolvesTest checks that the README code samples resolve against the source. InteractiveDemoTest runs the scripted demo. The rest covers bounds, navigation, the event store, the model and the style setters.
Troubleshooting and FAQ
Enter does nothing on a day
The day is either a blank lead-in or trailing cell, or a dimmed day outside the bounds. Enter is refused in both cases, and the picker comes back unchanged. Through Model, the refusal is recorded as a selection_refused event whose reason is empty_cell or out_of_bounds.
withMinDate() or withMaxDate() throws
The date is outside 0001-01-01..9999-12-31, or the new bound crosses the existing one. A zero date, such as a MySQL empty-row value, is refused for that reason. Check the value before you pass it in.
Model::new() throws when given a time and a picker
Pass either a seed time or a configured picker. Passing both throws, because the time would be silently discarded. Put the seed on the picker with DatePicker::new() when you need both.
The grid is narrower or wider than requested
The requested width is clamped into the band and never rejected. A request below the natural floor grows to 21, or 25 with the week column. A request above 63 shrinks. Ask renderWidth() for the width that view() will produce.
The grid shows mojibake on a latin1 terminal
The separator is the box-drawing character U+2500, and the grid assumes UTF-8 output. Set the terminal and the PHP output to UTF-8.
Ctrl chords quit the host on a paste
Pasted NUL and corrupted bytes arrive as invented Ctrl chords with an empty rune. The model ignores them. A host that maps any Ctrl chord to quit does not, so bind quit to a named key or an explicit, labeled chord.
The today marker is missing
A picker hides the marker after withoutToday() until withClockToday() or a fresh withToday() restores it. A pinned reference day never follows the wall clock, so a session that runs past midnight keeps showing the pinned day.
Events are missing after a direct handleKey() call
handleKey() and the imperative methods record nothing. Only Model emits events. Drive the picker through a Model, or compare the states yourself.
Upstream mapping
The port follows the construction and interaction model of EthanEFung/bubble-datepicker. The table lists where the port differs.
| Upstream concept | SugarCraft | Notes |
|---|---|---|
| Date picker model and construction | Model::new(), DatePicker::new() | The seed or configured-picker construction pattern. |
| Month and cursor navigation | goTo*(), moveCursor*(), handleKey() | Navigation clamps at the bounds and never wraps. |
| Focus, tab cycling and per-focus arrows | not ported | The single-cursor design has no key vocabulary for them. |
| Replaceable key binding | a fixed table, plus host rebinding | The public methods cover every action in the table. |
| Range selection | withRangeMode(), rangeStart(), rangeEnd(), DateRange | The first Enter sets the start, the second sets the end. |
Architecture
The month grid is laid out by DatePicker into a sugar-cellbuffer buffer that is nine rows high and 21 to 63 cells wide (25 to 63 with the week column), and Buffer::toAnsi() serializes it. Cell widths come from the sugar-core width oracle, so the rendered width agrees with renderWidth(). Model wraps the picker as a sugar-core Model. Its update() maps key messages onto the picker, and it records each transition through the EventStoreInterface. Navigation holds the static grid-index conversion, and DateRange is the immutable endpoint value.
Changelog and versioning
The package is pre-1.0 and ships only dev-master. It was renamed in 2026-10 from sugarcraft/sugar-calendar, and the namespace moved from SugarCraft\Calendar\ to SugarCraft\DatePicker\. The upstream PascalCase method spellings still resolve to the camelCase methods, and ApiAliasTest pins them.
Source
Related
- sugar-dashboard has a separate
Components\Select\DatePicker. It is a labeled form field with a calendar popup, and it has its own API. This package is the standalone calendar. - sugar-core supplies the Model contract, the key messages, the width oracle and the i18n lookup.