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);
Concepts
A veil is an immutable overlay description. It holds the foreground content, the anchor and offset, the backdrop dimming, the z-index and the optional animation. Veil::composite() takes a foreground string, a background string and the anchor, and returns one frame string. Nothing is drawn to a terminal. The host writes the frame.
The compositor works on cells, not bytes. ANSI and zone-marker envelopes take zero columns, and wide glyphs count as two. VeilStack layers several veils by ascending z-index. The shared RenderSession remembers the last full frame, so a redraw emits only the cells that changed. Because the session belongs to the veil, a program should keep one veil in its model rather than building a new one on every paint.
Tasks
- Center a modal over a dimmed background. Call
Veil::centered($modal, $base, 50), or build a veil withwithBackdrop(40)and callcomposite()withPosition::CENTERfor both axes. - Stack a tooltip above a modal. Add each veil to a
VeilStackwithwithZIndex(), then callcompositeAll(). Higher z-indexes paint on top. - Animate an opening. Set
withAnimation(AnimationKind::SLIDE)and callanimate($fg, $bg, ..., $progress)on each tick, with progress from 0 to 1. PasswithReducedMotion(true)to jump straight to the settled frame. - Dismiss on a click outside the overlay. Mark interactive text with
mark(), composite the frame, pass the rendered frame toscan(), and callisClickOutside($mouseMsg)on the returned veil. The zones survive laterwith*()calls. - Show text from users or the network. Pass it to
withUntrustedContent(), which neutralizes control characters, forged zone sentinels and live OSC-8 links at set time. RawwithContent()andcomposite()payloads pass through verbatim.
What's in the box
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()).maxZIndex() / minZIndex() return null for an empty stack, since 0 is a real z-index.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.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.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.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.
Keys and input
sugar-overlay has no key handling, by design. The host binds Esc and Enter to its own dismiss action, and it uses isClickOutside() for pointer dismissal. Mouse input comes from sugar-mouse, and scan() builds the zones. For focus movement, use sugar-focus or sugar-navstack. zoneRects() and lastZoneRect($id) publish each zone's rectangle in the same 1-based cell space that hit() uses, so a focus ring and a click agree on one geometry.
Configuration and options
| Option | Type | Default | Effect |
|---|---|---|---|
Veil::withBackdrop() | int, 0 to 100 | 0 | Dimming of the background. Values are clamped to the range. 0 leaves the background untouched. |
Veil::withAnimation() | ?AnimationKind or a configured Fade, Scale or Slide | null | Transition used by animate(). A preset applies that kind's default easing curve. |
Veil::withZIndex() | int | 0 | Stacking order inside a VeilStack. Ascending order paints later veils on top. |
Veil::withPosition() | ?Position per axis, plus x and y offsets | centered by the caller's arguments | Anchor and cell offsets for the veil itself. Used by VeilStack::compositeAll(). |
Veil::withBorder() | ?Border | null | Border chrome around the content. It applies to every composited frame. |
Veil::withClickOutsideDismiss() | flag | off | Enables isClickOutside(). It throws if scan() has not run. |
Veil::withReducedMotion() | bool | false | When true, animate() paints the settled frame at any progress. |
Veil::withoutZoneMarkers() | flag | markers on | Opts out of the hit-test arena, so the frame carries no zone envelopes. |
Veil::withUntrustedContent() | string | '' | Sets content after sweeping it. Use it for any payload that did not come from the program itself. |
Veil::withAutoSize() | flag | n/a | Deprecated no-op kept for source compatibility. Border chrome applies unconditionally. |
Theme, backdrop and color
The backdrop is the only color the compositor adds on its own. It dims each non-empty background line with a computed pen. The dimming does not compound across stacked veils, because the first dim to touch a cell governs. The pen assumes a light default foreground. On a terminal that renders dark text, the gray pen brightens that text instead, so set withBackdrop(0) there.
The renderer does not read NO_COLOR, because the dim pen is itself color. A host that honors NO_COLOR should pre-strip the backdrop, call withBackdrop(0) and skip animations. Borders and styles come from sugar-style, and Border::hidden() or Border::ascii() give a frame with no box glyphs.
Examples
examples/basic.php: a modal box overlaid on a background frame. Run it withphp examples/basic.php.examples/multiple-overlays.php: several overlays composited on one base view in z-order. Run it withphp examples/multiple-overlays.php.examples/interactive.php: an animated reveal, followed by a scripted interaction. Run it withphp examples/interactive.php.examples/overflow.php: a narrow-canvas demo that asks for the overlay's size before rendering a wide modal. Run it withphp examples/overflow.php.
Testing
Run the suite from the lib root:
composer install && vendor/bin/phpunit
The suite covers compositing and the delta law, animation progress and the easing classes, the z-index stack, the sweep of untrusted content, the link degradation rules, and the README snippets. To check your own overlays, composite to a fixed width and height and compare the frame with an expected string, or use the golden helpers in sugar-testing.
Troubleshooting and FAQ
- The background looks too dark, or dark text got brighter. The dim pen assumes a light default foreground. On a dark-text terminal, use
withBackdrop(0)or pre-dim the background yourself. - A single-line overlay does not come back as raw text. It is placed at its anchor over the single-line background, unlike the upstream raw passthrough. The README's Divergences section records this on purpose.
- An empty foreground still dims the screen. The backdrop ramp applies to every row, so an empty overlay over
withBackdrop(n)withnabove zero yields a dimmed canvas. This matches the README's divergence note. isClickOutside()throws. Dismissal is on, butscan()has not run on the frame that is on screen. Callscan()on the rendered frame first.scan()throws on duplicate zone ids. Eachmark()id must be unique within one frame. Rename one of the marks.VeilStack::add()throwsOverflowException. A stack holds at most 256 layers. Remove stale veils withremoveWhere()orclear().- Redraws show ghost cells after a cursor desync. Call
resetPreviousFrame()to force a full frame, orwithoutSession()for a full frame from a new session.
Upstream mapping
The surface mirrors the Go antecedent, rmhubbert/bubbletea-overlay. Two branches of its Composite() are deliberately not mirrored, and the README's Divergences section pins both with CompositeDeltaLawTest.
| Upstream behavior (Go) | SugarOverlay |
|---|---|
| Single-line foreground returned raw, ignoring placement | Laid out like any other frame. "HI" over "abcd" yields HIcd. |
| Empty foreground passes the background through verbatim | The backdrop ramp still applies. Pass-through holds only at opacity 0. |
| Overlay composition over a background string | Veil::composite() and VeilStack::compositeAll() |
Architecture
The public classes are Veil, which is the immutable overlay description, and VeilStack, the ordered collection. RenderSession remembers the last frame and decides what to emit. It owns no terminal, and sugar-cellbuffer encodes the delta. MarkedFrame is the width algebra for one line, and it is the shared knife behind clipping and the security sweep. SgrWalker walks the SGR and OSC runs of a line, so their envelopes cost zero columns. Lines and Cluster split and step through text. Position carries the nine anchors, and the Animation namespace holds the Fade, Scale and Slide transitions.
The lib builds on the monorepo's cell model. sugar-cellbuffer provides the diff buffer, sugar-mouse provides the hit-testing scanner and marks, sugar-spring provides the cubic-bezier easing, sugar-style provides border and style chrome, and sugar-core provides the width measurement.
Changelog and versioning
The package ships no CHANGELOG file. The commit history of sugar-overlay/ in the monorepo is the record of changes. withAutoSize() is a deprecated no-op that remains for source compatibility.
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)) |
| Veil | place(foreground, background, ?Placement $at = null) | The one placement door every other spelling routes through (composite(), centered(), animate(), the stack passes); omitting $at uses the veil's own placement(). Same frame protocol, trust boundary and diff session as composite() |
| Veil | withPlacement(Placement) / placement(): Placement | Store the placement a stack pass places this veil with (same storage as withPosition()); an unset axis reads as CENTER |
| Placement | new(Position $vertical = CENTER, Position $horizontal = CENTER, int $x = 0, int $y = 0) / centered(int $x = 0, int $y = 0) | Immutable anchor pair plus cell offset, the placement value every door shares |
| Placement | withAnchors(Position, Position) / withOffset(int, int) / offsetBy(int $dx, int $dy) | New anchors, a replaced offset, or a moved offset |
| Modal | render(int $cols, int $rows): string / handleKey(KeyMsg): [?Modal, ?\Closure] | Interface for one modal layer: its body for the canvas, and the next modal (null closes it) plus an optional command |
| ModalStack | new() / push(Modal, ?Veil = null) / pop() / top(): ?Modal | Immutable stack of modals; push() defaults to a 50% backdrop CENTER/CENTER veil and throws OverflowException beyond MAX_LAYERS (256) |
| ModalStack | handleKey(KeyMsg): [ModalStack, ?\Closure] / render(string $background, int $cols, int $rows) | Route a key to the top modal; paint every modal bottom to top, each placed with its veil's placement over the canvas so far |
| ModalStack | all() / isEmpty() / count() | Queries (count() via Countable) |
| 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 | Lines::split(text) | Line split with the trailing-newline rule (a closing \n does not open an empty line) |
| Cluster | Cluster::next(s, pos) | 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) |
Only methods declared in sugar-overlay/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\Overlay
AnimationFrame final readonly class
The per-frame result of an overlay animation: the foreground text as it should be painted at this progress, plus the anchor-relative travel offsets to add to the composite() call's xOffset/yOffset.
| Method | Summary |
|---|---|
__construct(public string $foreground, public int $verticalOffset = 0, public int $horizontalOffset = 0) | |
static fromArray(array $frame): self | Compatibility adapter for the legacy array shape returned by Animation\Slide::apply() (public since 1.x — the shape stays until the 2.0 flip, this wraps it at the consumer). |
Modal interface
One modal layer a ModalStack paints and routes keys to.
| Method | Summary |
|---|---|
render(int $cols, int $rows): string | The modal's body for a canvas of $cols x $rows cells. The stack places it with the layer's Placement and veil (dim, border); the modal only decides what it shows and may size itself to the canvas. |
handleKey(KeyMsg $msg): array | React to a key while this modal is on top. |
ModalStack final class
Modals stacked in push order: the last pushed is on top, gets every key, and paints over everything beneath it.
| Method | Summary |
|---|---|
static new(): self | |
push(Modal $modal, ?Veil $veil = null): self | Push a modal on top. |
pop(): self | Drop the top modal (a no-op on an empty stack). |
top(): ?Modal | The modal on top, or null when the stack is empty. |
handleKey(KeyMsg $msg): array | Route a key to the top modal. The modal it returns replaces it; null closes it. An empty stack ignores the key (the host routes it on). |
render(string $background, int $cols, int $rows): string | Paint every modal, bottom to top, over $background. |
all(): array | |
isEmpty(): bool | |
count(): int |
Placement final class
Where an overlay lands on its canvas: a vertical and a horizontal anchor plus a cell offset.
| Method | Summary |
|---|---|
static new(Position $vertical = Position::CENTER, Position $horizontal = Position::CENTER, int $x = 0, int $y = 0): self | Anchor pair plus offset; CENTER/CENTER with no offset by default. |
static centered(int $x = 0, int $y = 0): self | CENTER/CENTER, the modal anchor, with an optional nudge. |
withAnchors(Position $vertical, Position $horizontal): self | Same offset, new anchors. |
withOffset(int $x, int $y): self | Same anchors, the offset replaced. |
offsetBy(int $dx, int $dy): self | Same anchors, the offset moved by ($dx, $dy). |
Position enum
Overlay position constants.
Cases: TOP · RIGHT · BOTTOM · LEFT · CENTER · TOP_RIGHT · BOTTOM_RIGHT · BOTTOM_LEFT · TOP_LEFT
PHP also provides cases().
| Method | Summary |
|---|---|
yOffset(int $fgHeight, int $bgHeight): int | Resolve the vertical cell offset (rows from the top) for this position given the foreground and background heights. Centering truncates toward zero (upstream Go integer division); the result is deliberately unclamped (SO-11), so an overlay larger than the backdrop yields a negative offset. |
xOffset(int $fgWidth, int $bgWidth): int | Resolve the horizontal cell offset (columns from the left) for this position given the foreground and background widths. |
RenderSession final class
Mutable render-session state for diff-based frame emission.
| Method | Summary |
|---|---|
__construct() | |
shouldEmitFull(int $width, int $height): bool | Returns true when there is no prior output or the dimensions differ, meaning the next composite must emit a full frame. |
rememberFull(string $output, int $width, int $height): void | Remember a full-frame output string and clear the diff buffer (used when emitting a full frame or after a resize). |
lastFullFrame(): ?string | The FULL frame behind the most recent emission, or null if nothing has been painted through this session yet. |
diff(string $output, int $width, int $height, callable $bufferFactory): string | Build diff delta between the given full output and the remembered previous output. |
reset(): void | Reset all session state, forcing the next composite to emit a full frame. |
SgrWalker final class
The lib's ONE SGR parameter parser.
| Method | Summary |
|---|---|
static fold(string $params, array $pen): array | Fold one SGR parameter string (the bytes between \e[ and m) into the pen state. Pure: the carry comes in and a fresh state comes out. |
static legs(string $params): array | Split a parameter string into colon legs: each leg is [code, subParameterStrings]. An empty parameter string folds to one reset leg — ECMA-48 equates \e[m with SGR 0, and both old walkers read intval('') = 0 the same way. |
static extendedColor(array $operands, bool $colonForm): ?int | Resolve an extended-color leg's operands to 0xRRGGBB, or null when the leg is malformed (unknown mode, missing operands). Non-numeric operands intval to 0 exactly as the old walkers did; out-of-range channels saturate via channel(), never wrap. |
static channel(int $component): int | Clamp one 38;2 / 48;2 color component into 0–255, the way terminals saturate an out-of-range value — 300 paints as 255, never as the 300 & 0xFF = 44 a bit-mask would produce. |
static ansiColorToHex(int $idx, bool $bright = false): int | |
static xterm256ToHex(int $n): int | Standard xterm 256-color palette index → 0xRRGGBB: 0-7 and 8-15 map through ansiColorToHex(), 16-231 the 6×6×6 cube, 232-255 the grayscale ramp. The index is clamped into 0-255 first (channel(), as sugar-cellbuffer does): unclamped, 38;5;300 ran the gray-ramp formula to 688 per channel and returned 0x2b2b2b0, a value outside 0xRRGGBB. |
Veil final class
Terminal overlay compositor.
| Method | Summary |
|---|---|
static new(): self | Create a new Veil instance. |
static centered(string $content, string $backdrop, int $dimmingPercent = 50, int $xOffset = 0, int $yOffset = 0): string | The modal preset: dim the backdrop, then centre the content over it. |
withBackdrop(int $opacity): self | Set the backdrop opacity for dimming the background. |
withAnimation(AnimationKind|Fade|Scale|Slide|null $animation): self | Set the animation for overlay transitions. |
animation(): AnimationKind|Fade|Scale|Slide|null | Read-only accessor for the animation driver (preset kind or instance). |
zIndex(): int | Read-only accessor for z-index. |
clickOutsideDismiss(): bool | Read-only accessor for click-outside-dismiss flag. |
autoSize(): bool | Read-only accessor for the auto-size flag. |
border(): ?Border | Read-only accessor for border chrome. |
withZIndex(int $zIndex): self | Set the z-index for stacking order. |
withClickOutsideDismiss(bool $enabled = true): self | Set the click-outside-dismiss flag. |
withAutoSize(bool $enabled = true): self | Set the auto-size flag. |
withBorder(?Border $border): self | Set the border chrome for wrapping veil content, or clear it with null. |
withPosition(?Position $vertical, ?Position $horizontal, int $x = 0, int $y = 0): self | Set the vertical and horizontal position anchors for this veil. |
withPlacement(Placement $placement): self | Store a placement on this veil: the anchor pair and offset a VeilStack::compositeAll() or ModalStack pass places it with. Same storage as withPosition() (which can also clear an axis); read it back with placement(). |
placement(): Placement | The stored placement, an unset axis reading as CENTER (the default every stack pass applies). |
withContent(string $content): self | Attach the overlay content this veil paints when a VeilStack drives it. A veil WITHOUT content acts as a backdrop-only layer: the stack pass dims (or passes through) the canvas beneath it and writes no foreground of its own. |
withUntrustedContent(string $content): self | withContent() for text you do NOT trust: before attaching, the sweep applies Sanitize::untrustedForDisplay() (SGR/OSC/C1 controls marked invisible, CRLF and lone CR folded to LF) plus stripZoneSentinels() (forged U+E000/U+E001 zone sentinels removed), then folds TAB to four spaces — the fixed cost Width itself charges a tab, NOT the cell the terminal moves to (a surviving TAB advances to the next 8-column stop). The fold keeps the compositor's width accounting from being poisoned by a byte whose painted width differs from the one Width charges. Image markers (U+E002 and up) are preserved by design. |
content(): string | Read-only accessor for the stack-driven overlay content ('' = none). |
withoutZoneMarkers(): self | Return a copy whose mark() emits no zone envelopes at all. |
withReducedMotion(bool $reduced = true): self | Honour the user's reduced-motion preference. |
lastFullFrame(): ?string | The FULL (non-delta) frame the last composite()/animate() emitted, or null if none has been painted through this veil's session yet. |
vPosition(): ?Position | Read-only accessor for vertical position anchor. |
hPosition(): ?Position | Read-only accessor for horizontal position anchor. |
positionX(): int | Read-only accessor for X position offset in columns. |
positionY(): int | Read-only accessor for Y position offset in rows. |
applyBorderChrome(string $content): string | Wrap content with border chrome using sugar-style Style. |
isClickOutside(\SugarCraft\Core\Msg\MouseMsg $mouse): bool | Check if a mouse message is outside the veil zone. |
scan(string $rendered): self | Feed a rendered output string to the internal scanner so that subsequent hit-testing can determine which zone contains a given coordinate pair. |
hit(int $col, int $row): ?Zone | Return the zone at the given terminal cell, or null if no zone contains it. Columns and rows are 1-based (sugar-mouse zone space). |
lastZoneRect(string $id): ?array | The rect the current scan registered for $id — the focus-ring door (sugar-overlay-030): a host that carries a focused zone id can paint its ring from published geometry without owning the Scanner. |
zoneRects(): array | Every zone the current scan registered, in the Scanner's scan order, as {id, x, y, w, h} paint rects (the same 1-based space as lastZoneRect()). Tab/arrow cycling walks this list; the ring of the selected entry is drawn from lastZoneRect(). Empty on a markerless scan. |
mark(string $id, string $content): string | Wrap $content with a zone marker so the scanner can later extract its bounding box. |
animate(string $foreground, string $background, Position $vertical, Position $horizontal, float $progress, int $xOffset = 0, int $yOffset = 0): string | Apply animation and composite the overlay onto the background. |
coveredCells(string $foreground, string $background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0): ?array | Which canvas cells the composite actually covers — the rect zone-lift hosts need to know which hot zones an overlay hides (sugar-overlay-012). |
overflowFor(string $foreground, string $background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0): ?array | How far the block overhangs the canvas — the predicate that lets a host warn BEFORE rendering a clipped modal (sugar-overlay-007). |
composite(string $foreground, string $background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0): string | Composite a foreground string over a background string. |
place(string $foreground, string $background, ?Placement $at = null): string | Composite $foreground over $background at a Placement: the one placement door every other spelling routes through (composite(), centered(), animate(), the stack passes). Omitting $at uses this veil's own placement(). |
splitLines(string $text): array | Split a multi-line string into an array of lines. |
maxLineWidth(array $lines): int | Get the maximum line width (in characters) of an array of lines. |
lineWidth(string $line): int | Get the display width of a single line, in terminal cells. |
resetPreviousFrame(): void | Reset the diff state, forcing the next composite to emit a full frame. |
withoutSession(): self | Return a copy of this veil with a fresh RenderSession. |
VeilStack final class
Ordered collection of Veil instances rendered by z-index.
| Method | Summary |
|---|---|
static new(): self | Create a new empty VeilStack. |
add(Veil $veil): self | Add a veil to the stack. |
clear(): self | Remove all veils from the stack. |
removeWhere(\Closure $predicate): self | Remove veils matching the given predicate. |
composite(string $background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0): string | Composite all veils onto the background in z-index order (lowest first). |
compositeAll(string $background, int $xOffset = 0, int $yOffset = 0): string | Composite all veils at their individual positions. |
sorted(): array | Return veils sorted by z-index ascending. |
all(): array | |
isEmpty(): bool | |
count(): int | |
filter(\Closure $predicate): self | Filter veils by a predicate. |
maxZIndex(): ?int | Get the highest z-index in the stack, or null when the stack is empty. |
minZIndex(): ?int | Get the lowest z-index in the stack, or null when the stack is empty. |
SugarCraft\Overlay\Animation
AnimationKind enum
Animation kinds for overlay transitions.
Cases: SLIDE · FADE · SCALE
PHP also provides cases().
Fade final class
Fade animation — the foreground brightens in from black as progress grows.
| Method | Summary |
|---|---|
__construct(private readonly ?CubicBezier $easing = null) | |
static new(?CubicBezier $easing = null): self | |
easedProgress(float $progress): float | The eased scalar progress for this curve (0.0–1.0, saturating at the ends). Veil::animate() drives the scrim ramp from the SAME value the content glides on (sugar-overlay-066). |
apply(string $foreground, float $progress): string | Apply fade animation to the foreground at the given progress. |
opacity(float $progress): int | Get the opacity value for this progress (0-100). |
Scale final class
Scale animation — foreground "grows" from center outward.
| Method | Summary |
|---|---|
__construct(private readonly ?CubicBezier $easing = null) | |
static new(?CubicBezier $easing = null): self | |
easedProgress(float $progress): float | The eased scalar progress for this curve, saturating at the ends. Veil::animate() drives the scrim ramp from the SAME value the content glides on (sugar-overlay-066). |
apply(string $foreground, float $progress): string | Apply scale animation to the foreground at the given progress. |
Slide final class
Slide animation — foreground enters from the anchor direction.
| Method | Summary |
|---|---|
__construct(private readonly ?CubicBezier $easing = null) | |
static new(?CubicBezier $easing = null): self | |
easedProgress(float $progress): float | The eased scalar progress for this curve, saturating at the ends. Veil::animate() drives the scrim ramp from the SAME value the content glides on (sugar-overlay-066). The travel offsets themselves keep using the raw curve — an overshoot that slides a hair past its landing is visible in the motion and stays. |
applyFrame(string $foreground, float $progress, Position $vertical, Position $horizontal): AnimationFrame | The typed per-frame result: the foreground plus the anchor-relative travel offsets to add to the composite() call (sugar-overlay-013 — the shape the untyped array form used to hide). |
apply(string $foreground, float $progress, Position $vertical, Position $horizontal): array | The legacy array shape (public since 1.x), delegating to applyFrame() — source-compatible until the 2.0 flip. New consumers take the typed frame; the magic-key array is the compat reading, not the contract. |
Demos.
VHS-recorded GIFs of the basic and multiple-overlays examples. Regenerated automatically on every push that touches the source.
Modal overlay
Modal pinned over a background frame.
Multiple overlays
Stacked overlays composited in z-order.Related
- SugarMouse: mouse hit-testing and zone trackers.
- SugarSpring: damped spring physics, a declared dependency of this overlay.