Floating notification overlays
Non-blocking floating notifications at 9 screen positions. Info, Success, Warning, Error types. Auto-dismiss, an Escape-dismiss preference flag for hosts, and stacked multi-toast support.
composer require sugarcraft/sugar-toast
use SugarCraft\Toast\{Toast, ToastType, Position};
$toast = Toast::new(50) // max width 50
->withPosition(Position::MiddleRight)
->withAllowEscToClose(true);
$toast = $toast->alert(ToastType::Success, 'File saved!');
$toast = $toast->alert(ToastType::Error, 'Connection failed');
$bg = str_repeat("background content\n", 20);
echo $toast->view($bg);
null $expiresAt at the alert()/progressToast() doors means "use the configured duration" โ persistence is reached by keeping the toast duration unset or through the explicit sentinel (withoutExpiry()/cancelAlert()).actionRects()/actionAt() for host-side mouse and keyboard dispatch.history(); clear() never resets it.| Class | Method | Description |
|---|---|---|
| Toast | new(int $maxWidth = 50) | Factory โ max width in cells |
| Toast | withPosition(Position) | Set screen position (9 positions) |
| Toast | withDuration(?float $seconds) | Auto-dismiss after N seconds (null = no expiry is armed โ alerts persist unless an explicit expiry is given) |
| Toast | withAllowEscToClose(bool) | Set the Escape-dismiss preference flag (the renderer handles no input; the host reads it) |
| Toast | withMaxWidth(int) | Set maximum alert width in cells |
| Toast | withMinWidth(int) | Set minimum alert width in cells |
| Toast | withSymbolSet(SymbolSet) | NerdFont, Unicode, or Ascii symbol sets |
| Toast | withMaxConcurrent(?int) | Cap concurrent alerts (null = unlimited; values < 1 throw) |
| Toast | withOverflow(Overflow) | Strategy when cap exceeded: DropOldest, DropNewest, Enqueue |
| Toast | withHistoryLimit(?int $n) | Cap history log, oldest evicted first (default 100; null = unbounded) |
| Toast | alert(ToastType|string, string, ?float $expiresAt = null, ?array $actions = null, ?string $id = null) | Add alert; string type = case-insensitive lookup; $expiresAt is an absolute epoch (duration-shaped values throw); null inherits the configured duration; an $id re-queue updates the live alert in place |
| Toast | progressToast(ToastType|string, string, float $progress, ?float $expiresAt = null, ?array $actions = null, ?string $id = null) | Add alert with progress bar (finite 0.0โ1.0; out-of-range clamps, NAN/INF throw); same expiry semantics as alert(); re-calling with the same $id advances one box instead of appending |
| Toast | push(Alert $alert) | Enqueue a pre-built Alert (styled/actioned) |
| Toast | cancelAlert(int $index) | Make a queued alert persistent (never auto-dismisses); $index addresses the activeAlerts() order |
| Toast | extendAlert(int $index, float $additionalSeconds) / extendAll(float) | Push one (in activeAlerts() order) / every expiring alert's expiry later |
| Toast | allowEscToClose(): bool | Read the Escape-dismiss preference flag |
| Toast | error(string), warning(string), info(string), success(string) | Convenience alert helpers |
| Toast | hasActiveAlert(): bool | Returns true if non-expired alerts are queued |
| Toast | dismiss(), clear(), pruneExpired() | Manage alert lifecycle; dismiss() files EVERY queued alert (expired included) into history, clear() drops without recording, pruneExpired() is silent |
| Toast | history(): list<Alert> | Return all recorded alerts โ dismissed AND overflow-evicted; cumulative, clear() never resets it |
| Toast | view(string $background, int $w = 80, int $h = 24): string | Composite the toast layer over the background frame; dimensions outside 1..10000 throw; content that cannot fit ellipsizes instead of vanishing |
| Alert | new(ToastType $type, ?string $message = null, ?float $expiresAt = null, ?float $progress = null, array $actions = [], ?Color $backgroundColor = null, ?Color $foregroundColor = null, ?Color $borderColor = null, bool $persistent = false, ?string $id = null) | Factory mirroring the constructor |
| Alert | withProgress(float) | Attach progress bar (finite 0.0โ1.0; out-of-range clamps, NAN/INF throw) |
| Alert | withActions(list<Action>) | Attach action buttons |
| Alert | isExpired(): bool | Check expiry |
| Alert | withExpiry(float $duration) | Set expiry from now |
| Alert | withoutExpiry() / withCancelledExpiry() | Make the alert persistent (never auto-dismisses) |
| Alert | withExtendedExpiry(float) | Move the expiry later by N seconds |
| Alert | withBackgroundColor(?Color) / withForegroundColor(?Color) / withBorderColor(?Color) | Per-alert colour overrides (null = type default) |
| Action | new(string $label, \Closure(): void $callback) | Factory |
| Action | $label: non-empty-string | User-visible button label (readonly; normalised at construction โ inline SGR kept, other control/escape constructs stripped, printable-empty refused) |
| Action | $callback: \Closure(): void | Invoked when action is triggered (readonly) |
| HistoryLog | push(Alert, ?int $limit = null): self | Append alert (evicting oldest past $limit), return new immutable log |
| HistoryLog | all(): list<Alert> | Return all recorded alerts |
| HistoryLog | count(): int | Number of recorded entries |
| Toast | activeAlerts(): list<Alert> | The live queue exactly as view() sees it (expired filtered) |
| Toast | removeAlert(string $id): self | Retire the queued alert with this id, unrecorded |
| Toast | actionRects(string $background = '', int $viewportWidth = 80, int $viewportHeight = 24): list<array{action,alert,alertIndex,actionIndex,row,col,width}> | Absolute frame cells of every painted button |
| Toast | actionAt(int $col, int $row, string $background = '', int $viewportWidth = 80, int $viewportHeight = 24): ?Action | Which Action covers a frame position (first match in queue order) |
| Toast | nextExpiry(): ?float / secondsUntilNextExpiry(): ?float | Absolute epoch / seconds of the soonest live expiry (null when none) |
| Toast | withAccessibleText(bool $on = true) / accessibleText(): bool | Opt-in plain-text severity word + progress percentages beside the colour/glyph channel |
| ToastType | Info, Success, Warning, Error | Toast type constants |
| ToastType | label() / icon(SymbolSet) / nerdIcon() / unicodeIcon() / asciiPrefix() / color() | Translated label via Lang::t() (i18n-aware); per-set glyphs and the default ANSI colour |
| Position | xOffset(int $alertWidth, int $viewportWidth): int / yOffset(int $alertHeight, int $frameHeight, int $stackedBefore = 0): int | Placement maths โ xOffset can go negative when the box outgrows the viewport (view() clamps to 0) |
| Position | TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight | 9 screen positions |
| Overflow | DropOldest, DropNewest, Enqueue | Overflow strategy when maxConcurrent is exceeded |
| SymbolSet | NerdFont, Unicode, Ascii | Symbol set for alert icons |
| Lang | t(key, params) | Translate a string: 'dismiss', 'count', 'type.*' |
Per-alert render size is bounded too: Toast::MAX_MESSAGE_CELLS truncates over-long messages with a visible marker and Toast::MAX_ACTIONS_PER_ALERT folds surplus buttons into a "[+N more]" row โ the full text and action list still ride the Alert into history.
User-facing strings use SugarCraft\Toast\Lang::t(). All keys are in lang/en.php under the toast namespace.
| Key | Default | Parameters |
|---|---|---|
| type.info / type.warning / type.error / type.success | Info / Warning / Error / Success | โ |
| dismiss | Press any key to dismiss | โ |
| count | {count} notification(s) | {count} |
To localize, copy lang/en.php to lang/<code>.php and translate the values.
VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.