โ† All 40 libraries

SugarToast

๐Ÿ”” SugarToast

Floating notification overlays

inspired by DaltonSW/bubbleup notificationtoastalertoverlay

SugarToast code coverage

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.

Install

composer require sugarcraft/sugar-toast

Quickstart

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

What's in the box

Four typesInfo, Success, Warning, Error โ€” each with a distinct symbol and color.
Positions9 positions: TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight.
Auto-dismissConfigurable duration. Passing 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()).
Symbol setsNerdFont, Unicode, or Ascii.
Overflow controlDropOldest, DropNewest, or Enqueue when maxConcurrent is exceeded.
Progress toastsInline progress bar (0โ€“100%) beneath the message body.
Action buttons[Label] buttons with closure callbacks; their frame cells are exported by actionRects()/actionAt() for host-side mouse and keyboard dispatch.
History logCumulative immutable record of dismissed and overflow-evicted alerts via history(); clear() never resets it.
Styled alertsPer-alert background, foreground, and border colour overrides via Color.

Source & demos

Try the quickstart โ†’

API

ClassMethodDescription
Toastnew(int $maxWidth = 50)Factory โ€” max width in cells
ToastwithPosition(Position)Set screen position (9 positions)
ToastwithDuration(?float $seconds)Auto-dismiss after N seconds (null = no expiry is armed โ€” alerts persist unless an explicit expiry is given)
ToastwithAllowEscToClose(bool)Set the Escape-dismiss preference flag (the renderer handles no input; the host reads it)
ToastwithMaxWidth(int)Set maximum alert width in cells
ToastwithMinWidth(int)Set minimum alert width in cells
ToastwithSymbolSet(SymbolSet)NerdFont, Unicode, or Ascii symbol sets
ToastwithMaxConcurrent(?int)Cap concurrent alerts (null = unlimited; values < 1 throw)
ToastwithOverflow(Overflow)Strategy when cap exceeded: DropOldest, DropNewest, Enqueue
ToastwithHistoryLimit(?int $n)Cap history log, oldest evicted first (default 100; null = unbounded)
Toastalert(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
ToastprogressToast(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
Toastpush(Alert $alert)Enqueue a pre-built Alert (styled/actioned)
ToastcancelAlert(int $index)Make a queued alert persistent (never auto-dismisses); $index addresses the activeAlerts() order
ToastextendAlert(int $index, float $additionalSeconds) / extendAll(float)Push one (in activeAlerts() order) / every expiring alert's expiry later
ToastallowEscToClose(): boolRead the Escape-dismiss preference flag
Toasterror(string), warning(string), info(string), success(string)Convenience alert helpers
ToasthasActiveAlert(): boolReturns true if non-expired alerts are queued
Toastdismiss(), clear(), pruneExpired()Manage alert lifecycle; dismiss() files EVERY queued alert (expired included) into history, clear() drops without recording, pruneExpired() is silent
Toasthistory(): list<Alert>Return all recorded alerts โ€” dismissed AND overflow-evicted; cumulative, clear() never resets it
Toastview(string $background, int $w = 80, int $h = 24): stringComposite the toast layer over the background frame; dimensions outside 1..10000 throw; content that cannot fit ellipsizes instead of vanishing
Alertnew(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
AlertwithProgress(float)Attach progress bar (finite 0.0โ€“1.0; out-of-range clamps, NAN/INF throw)
AlertwithActions(list<Action>)Attach action buttons
AlertisExpired(): boolCheck expiry
AlertwithExpiry(float $duration)Set expiry from now
AlertwithoutExpiry() / withCancelledExpiry()Make the alert persistent (never auto-dismisses)
AlertwithExtendedExpiry(float)Move the expiry later by N seconds
AlertwithBackgroundColor(?Color) / withForegroundColor(?Color) / withBorderColor(?Color)Per-alert colour overrides (null = type default)
Actionnew(string $label, \Closure(): void $callback)Factory
Action$label: non-empty-stringUser-visible button label (readonly; normalised at construction โ€” inline SGR kept, other control/escape constructs stripped, printable-empty refused)
Action$callback: \Closure(): voidInvoked when action is triggered (readonly)
HistoryLogpush(Alert, ?int $limit = null): selfAppend alert (evicting oldest past $limit), return new immutable log
HistoryLogall(): list<Alert>Return all recorded alerts
HistoryLogcount(): intNumber of recorded entries
ToastactiveAlerts(): list<Alert>The live queue exactly as view() sees it (expired filtered)
ToastremoveAlert(string $id): selfRetire the queued alert with this id, unrecorded
ToastactionRects(string $background = '', int $viewportWidth = 80, int $viewportHeight = 24): list<array{action,alert,alertIndex,actionIndex,row,col,width}>Absolute frame cells of every painted button
ToastactionAt(int $col, int $row, string $background = '', int $viewportWidth = 80, int $viewportHeight = 24): ?ActionWhich Action covers a frame position (first match in queue order)
ToastnextExpiry(): ?float / secondsUntilNextExpiry(): ?floatAbsolute epoch / seconds of the soonest live expiry (null when none)
ToastwithAccessibleText(bool $on = true) / accessibleText(): boolOpt-in plain-text severity word + progress percentages beside the colour/glyph channel
ToastTypeInfo, Success, Warning, ErrorToast type constants
ToastTypelabel() / icon(SymbolSet) / nerdIcon() / unicodeIcon() / asciiPrefix() / color()Translated label via Lang::t() (i18n-aware); per-set glyphs and the default ANSI colour
PositionxOffset(int $alertWidth, int $viewportWidth): int / yOffset(int $alertHeight, int $frameHeight, int $stackedBefore = 0): intPlacement maths โ€” xOffset can go negative when the box outgrows the viewport (view() clamps to 0)
PositionTopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight9 screen positions
OverflowDropOldest, DropNewest, EnqueueOverflow strategy when maxConcurrent is exceeded
SymbolSetNerdFont, Unicode, AsciiSymbol set for alert icons
Langt(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.

Internationalization

User-facing strings use SugarCraft\Toast\Lang::t(). All keys are in lang/en.php under the toast namespace.

KeyDefaultParameters
type.info / type.warning / type.error / type.successInfo / Warning / Error / Successโ€”
dismissPress any key to dismissโ€”
count{count} notification(s){count}

To localize, copy lang/en.php to lang/<code>.php and translate the values.

Demos.

VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.

All toast types

All toast types

Each type rendered as its own sequential full-viewport frame.
Basic toast

Basic toast

Multiple queued toasts across three sections; no duration is set โ€” nothing auto-dismisses, the host drives pruning.