SugarOverlay
Terminal overlay compositor
Composite overlay views (modals, tooltips, toasts) on top of a base TUI frame. Render your models first, then let the compositor handle positioning, backdrop dimming, z-ordering, animated transitions and click-outside hit-testing.
Install
composer require sugarcraft/sugar-overlay
Quickstart
use SugarCraft\Overlay\{Position, Veil, VeilStack};
$baseView = "underlying text\nmore underlying\ntext underneath";
$modalView = "[modal]";
$tooltip = "Click to dismiss";
$veil = Veil::new()->withBackdrop(40); // 40% dim — 60% brightness remains
// Composite a foreground string centered over a background string
echo $veil->composite($modalView, $baseView, Position::CENTER, Position::CENTER);
// Layer several overlays by z-index
$stack = VeilStack::new()
->add(Veil::new()->withContent($modalView)->withZIndex(1))
->add(Veil::new()->withContent($tooltip)->withZIndex(2)
->withPosition(Position::TOP, Position::RIGHT));
echo $stack->compositeAll($baseView);
What's in the box
PositioningNine anchors — Top, Right, Bottom, Left, Center and the four corners — plus X/Y offsets in cells (columns/rows).
Backdrop dimmingTruecolor opacity blend (0–100): every non-empty background line is wrapped in a computed dim pen during assembly (the blend does not compound across stacked veils — the first dim to touch a cell governs — and the pen assumes a light default foreground: on a terminal that renders dark text, the gray pen brightens that text instead of dimming it).
Animated transitions
withAnimation() + animate(…, $progress): SLIDE enters from the anchored edge, SCALE reveals lines from the center outward, and FADE brightens the overlay in from black through a truecolor gray pen (terminals cannot alpha-blend), returning the original bytes at full opacity. Progress is clamped to 0–1 and the scrim ramps with the animation; withReducedMotion() makes any progress emit the settled frame in one shot for hosts reading the platform preference (sugar-colorprofile's Probe::reducedMotion()).VeilStackOrdered collection of veils rendered by ascending z-index;
maxZIndex() / minZIndex() return null for an empty stack, since 0 is a real z-index.Click-outside dismiss
withClickOutsideDismiss() + scan() / isClickOutside() via sugar-mouse zones. The scanned zones travel with the veil across later with*() calls, so a click is judged against the frame that was on screen.Buffer diffing
composite() diffs against the previous frame and emits only changed cells. An empty background returns the overlay itself as the frame, and extended color operands saturate before any arithmetic runs: 38;2;r;g;b components and 38;5;n palette indices clamp to 0–255 each, so a hostile 38;5;300 cannot push the grayscale-ramp formula (38;5;232-255 is the grey ramp, not the 6×6×6 color cube) past the 0xRRGGBB range the cell model stores.Border chrome
withBorder() wraps veil content in a terminal border; when a border is configured the chrome applies to every composited frame — withAutoSize() is a deprecated no-op retained for source compatibility.Untrusted content
withUntrustedContent() sweeps payloads at set time: control characters, forged U+E000/U+E001 zone sentinels and live OSC-8 links are neutralised (CRLF/CR folded to LF, TAB to its measured four cells), while sugar-image's U+E002 marker band passes through untouched. Backgrounds are as attacker-reachable as foregrounds — both paths are documented trust boundaries. Raw withContent() and composite() payloads pass through verbatim — sweep hostile frames yourself with sugar-core Sanitize::untrustedForMarkedFrames() before mark(): the sweep strips every U+E000/U+E001 sentinel, legitimate zone markers included, so order matters — sweep, then mark, then render.Accessibility
- The keyboard half is yours, the geometry is not hidden — sugar-overlay ships no key handling by design: bind Esc/Enter to the same dismiss action
isClickOutside()answers and keep focus movement inside sugar-focus / sugar-navstack. The clone returned byscan()publishes every zone's rect (zoneRects()/lastZoneRect($id)) in the same 1-based cell spacehit()uses, so a focus ring and a click agree on one geometry by construction. - Announce with text, not chrome — when an overlay opens, the title line you emit is the screen-reader cue; a
withBorder()frame only adds box-glyph noise for terminal readers and is a sighted-user affordance — users who want the box gone haveBorder::hidden()andBorder::ascii()from sugar-style. NO_COLORis the host's choice — the renderer deliberately does not consult it, because the dim pen is color; a host that honors it emits the backdrop pre-striped and runs withwithBackdrop(0)and no animation.- Reduced motion —
withReducedMotion()makesanimate()paint the settled frame in one shot (no dim sweep, no travel; the scrim ramps with the animation otherwise). The fleet-standard read is sugar-colorprofile'sProbe::reducedMotion(), but it sees only environment variables — offer an in-app setting as well.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by rmhubbert/bubbletea-overlay (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| Veil | new() | Create a new veil |
| Veil | static centered(content, backdrop, dimmingPercent = 50, xOffset = 0, yOffset = 0) | One-shot CENTER/CENTER composite — the library in one static call |
| Veil | composite(foreground, background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0) | Composite one string over another; offsets are cells |
| Veil | animate(foreground, background, $vertical, $horizontal, float $progress, $xOffset = 0, $yOffset = 0) | Composite with the configured animation applied at progress 0..1 — NAN and +INF settle to the finished frame, -INF to the start |
| Veil | withBackdrop(int) / withAnimation(?AnimationKind) / withZIndex(int) / withPosition(?Position, ?Position, x, y) / withContent(string) / withUntrustedContent(string) / withBorder(?Border) / withClickOutsideDismiss() / withoutZoneMarkers() / withReducedMotion(bool) / withAutoSize() | Immutable configuration; scanned zones survive later with*() clones. withUntrustedContent() sweeps at set time; withoutZoneMarkers() opts out of the hit-test arena; withAutoSize() is a deprecated no-op |
| Veil | scan(rendered) / hit(col, row) / isClickOutside(MouseMsg) / mark(id, text) / lastFullFrame(): ?string | Zone hit-testing (all coordinates 1-based); scan() throws InvalidArgumentException on duplicate zone ids, isClickOutside() throws when dismissal is on but scan() has not run; hit-test lastFullFrame() on the diffing path — deltas carry no zone envelopes |
| Veil | withoutSession() / resetPreviousFrame() / content() / applyBorderChrome(string) / splitLines(string) / lineWidth(string) / maxLineWidth(array) | Session control and helpers: withoutSession() re-mints the render session (next composite emits a full frame); resetPreviousFrame() forces one after a cursor desync; lineWidth()/maxLineWidth() count visible CELLS — marker envelopes cost zero columns; maxLineWidth() takes the splitLines() output array: maxLineWidth(splitLines($text)) |
| VeilStack | new() / add(Veil) / removeWhere(\Closure) / filter(\Closure) / clear() | Immutable stack of veils; add() throws OverflowException beyond MAX_LAYERS (256) |
| VeilStack | composite(background, $vertical, $horizontal, $xOffset = 0, $yOffset = 0) / compositeAll(background) | Render every veil by ascending z-index, at a shared position or each at its own; content is read verbatim — sweep untrusted payloads per veil with withUntrustedContent() before stacking |
| VeilStack | maxZIndex(): ?int / minZIndex(): ?int | Highest / lowest z-index, null for an empty stack |
| Veil | coveredCells(fg, bg, $v, $h, x, y) / overflowFor(fg, bg, $v, $h, x, y) / lastZoneRect(id) / zoneRects() | Measure-before-render doors and published geometry: the clipped rect the next composite() paints (null when nothing lands on the canvas) and the overhang the canvas clips away; every scanned zone's rect keyed by id in the same 1-based cell space hit() uses |
| Position | TOP / RIGHT / BOTTOM / LEFT / CENTER / TOP_RIGHT / BOTTOM_RIGHT / BOTTOM_LEFT / TOP_LEFT; yOffset(fgH, bgH) / xOffset(fgW, bgW) | Nine anchors; each axis reads only its component, so the nine cases project to three per axis; xOffset() goes negative when the overlay is wider and the ragged block folds at the clipped extent |
| RenderSession | shouldEmitFull() / rememberFull() / lastFullFrame() / diff() / reset() | Remembered-frame bookkeeping behind composite()'s diff emission — owns no terminal: it answers what to emit, sugar-cellbuffer encodes it |
| MarkedFrame | measure() / take() / drop() / isolation() / segments() (+ segment-level twins) | ANSI/zone-aware width algebra for one line — SGR/OSC runs are zero-width, wide glyphs one column plus a straddle blank; the shared knife behind clipping and the security sweep (a bare CR counts four columns, like a TAB; take() never cuts a wide glyph in half) |
| Lines / Cluster | Lines::split(text) / Cluster::next(s, pos) | Line split with the trailing-newline rule (a closing \n does not open an empty line); byte-safe cluster stepping used by the walkers |
| Animations | AnimationKind (FADE/SLIDE/SCALE); Fade/Scale/Slide::new(?CubicBezier) / easedProgress() / apply(); Slide::applyFrame() / Fade::opacity(); AnimationFrame::fromArray() | Transitions with sugar-spring CubicBezier easing — null selects each class's documented curve (Fade eases in-out, Slide out, Scale out); AnimationFrame::fromArray() adapts the legacy array shape until the 2.0 flip |
| VeilStack | sorted() / all() / isEmpty() / count() | Queries (count() via Countable) |
Demos.
VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.
Modal overlay
Modal pinned over a background frame.