All 48 libraries

SugarOverlay

Terminal overlay compositor

inspired by rmhubbert/bubbletea-overlay overlaycompositingui

SugarOverlay code coverage

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 with withBackdrop(40) and call composite() with Position::CENTER for both axes.
  • Stack a tooltip above a modal. Add each veil to a VeilStack with withZIndex(), then call compositeAll(). Higher z-indexes paint on top.
  • Animate an opening. Set withAnimation(AnimationKind::SLIDE) and call animate($fg, $bg, ..., $progress) on each tick, with progress from 0 to 1. Pass withReducedMotion(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 to scan(), and call isClickOutside($mouseMsg) on the returned veil. The zones survive later with*() 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. Raw withContent() and composite() payloads pass through verbatim.

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 transitionswithAnimation() + 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 dismisswithClickOutsideDismiss() + 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 diffingcomposite() 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 chromewithBorder() 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 contentwithUntrustedContent() 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 by scan() publishes every zone's rect (zoneRects() / lastZoneRect($id)) in the same 1-based cell space hit() 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 have Border::hidden() and Border::ascii() from sugar-style.
  • NO_COLOR is 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 with withBackdrop(0) and no animation.
  • Reduced motion — withReducedMotion() makes animate() 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's Probe::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

OptionTypeDefaultEffect
Veil::withBackdrop()int, 0 to 1000Dimming of the background. Values are clamped to the range. 0 leaves the background untouched.
Veil::withAnimation()?AnimationKind or a configured Fade, Scale or SlidenullTransition used by animate(). A preset applies that kind's default easing curve.
Veil::withZIndex()int0Stacking order inside a VeilStack. Ascending order paints later veils on top.
Veil::withPosition()?Position per axis, plus x and y offsetscentered by the caller's argumentsAnchor and cell offsets for the veil itself. Used by VeilStack::compositeAll().
Veil::withBorder()?BordernullBorder chrome around the content. It applies to every composited frame.
Veil::withClickOutsideDismiss()flagoffEnables isClickOutside(). It throws if scan() has not run.
Veil::withReducedMotion()boolfalseWhen true, animate() paints the settled frame at any progress.
Veil::withoutZoneMarkers()flagmarkers onOpts 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()flagn/aDeprecated 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 with php examples/basic.php.
  • examples/multiple-overlays.php: several overlays composited on one base view in z-order. Run it with php examples/multiple-overlays.php.
  • examples/interactive.php: an animated reveal, followed by a scripted interaction. Run it with php examples/interactive.php.
  • examples/overflow.php: a narrow-canvas demo that asks for the overlay's size before rendering a wide modal. Run it with php 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) with n above zero yields a dimmed canvas. This matches the README's divergence note.
  • isClickOutside() throws. Dismissal is on, but scan() has not run on the frame that is on screen. Call scan() on the rendered frame first.
  • scan() throws on duplicate zone ids. Each mark() id must be unique within one frame. Rename one of the marks.
  • VeilStack::add() throws OverflowException. A stack holds at most 256 layers. Remove stale veils with removeWhere() or clear().
  • Redraws show ghost cells after a cursor desync. Call resetPreviousFrame() to force a full frame, or withoutSession() 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 placementLaid out like any other frame. "HI" over "abcd" yields HIcd.
Empty foreground passes the background through verbatimThe backdrop ramp still applies. Pass-through holds only at opacity 0.
Overlay composition over a background stringVeil::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

Try the quickstart →

API

ClassMethodDescription
Veilnew()Create a new veil
Veilstatic centered(content, backdrop, dimmingPercent = 50, xOffset = 0, yOffset = 0)One-shot CENTER/CENTER composite — the library in one static call
Veilcomposite(foreground, background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0)Composite one string over another; offsets are cells
Veilanimate(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
VeilwithBackdrop(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
Veilscan(rendered) / hit(col, row) / isClickOutside(MouseMsg) / mark(id, text) / lastFullFrame(): ?stringZone 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
VeilwithoutSession() / 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))
Veilplace(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()
VeilwithPlacement(Placement) / placement(): PlacementStore the placement a stack pass places this veil with (same storage as withPosition()); an unset axis reads as CENTER
Placementnew(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
PlacementwithAnchors(Position, Position) / withOffset(int, int) / offsetBy(int $dx, int $dy)New anchors, a replaced offset, or a moved offset
Modalrender(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
ModalStacknew() / push(Modal, ?Veil = null) / pop() / top(): ?ModalImmutable stack of modals; push() defaults to a 50% backdrop CENTER/CENTER veil and throws OverflowException beyond MAX_LAYERS (256)
ModalStackhandleKey(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
ModalStackall() / isEmpty() / count()Queries (count() via Countable)
VeilStacknew() / add(Veil) / removeWhere(\Closure) / filter(\Closure) / clear()Immutable stack of veils; add() throws OverflowException beyond MAX_LAYERS (256)
VeilStackcomposite(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
VeilStackmaxZIndex(): ?int / minZIndex(): ?intHighest / lowest z-index, null for an empty stack
VeilcoveredCells(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
PositionTOP / 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
RenderSessionshouldEmitFull() / rememberFull() / lastFullFrame() / diff() / reset()Remembered-frame bookkeeping behind composite()'s diff emission — owns no terminal: it answers what to emit, sugar-cellbuffer encodes it
MarkedFramemeasure() / 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)
LinesLines::split(text)Line split with the trailing-newline rule (a closing \n does not open an empty line)
ClusterCluster::next(s, pos)Byte-safe cluster stepping used by the walkers
AnimationsAnimationKind (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
VeilStacksorted() / 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.

MethodSummary
__construct(public string $foreground, public int $verticalOffset = 0, public int $horizontalOffset = 0)
static fromArray(array $frame): selfCompatibility 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.

MethodSummary
render(int $cols, int $rows): stringThe 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): arrayReact 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.

MethodSummary
static new(): self
push(Modal $modal, ?Veil $veil = null): selfPush a modal on top.
pop(): selfDrop the top modal (a no-op on an empty stack).
top(): ?ModalThe modal on top, or null when the stack is empty.
handleKey(KeyMsg $msg): arrayRoute 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): stringPaint 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.

MethodSummary
static new(Position $vertical = Position::CENTER, Position $horizontal = Position::CENTER, int $x = 0, int $y = 0): selfAnchor pair plus offset; CENTER/CENTER with no offset by default.
static centered(int $x = 0, int $y = 0): selfCENTER/CENTER, the modal anchor, with an optional nudge.
withAnchors(Position $vertical, Position $horizontal): selfSame offset, new anchors.
withOffset(int $x, int $y): selfSame anchors, the offset replaced.
offsetBy(int $dx, int $dy): selfSame 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().

MethodSummary
yOffset(int $fgHeight, int $bgHeight): intResolve 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): intResolve 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.

MethodSummary
__construct()
shouldEmitFull(int $width, int $height): boolReturns 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): voidRemember a full-frame output string and clear the diff buffer (used when emitting a full frame or after a resize).
lastFullFrame(): ?stringThe 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): stringBuild diff delta between the given full output and the remembered previous output.
reset(): voidReset all session state, forcing the next composite to emit a full frame.

SgrWalker final class

The lib's ONE SGR parameter parser.

MethodSummary
static fold(string $params, array $pen): arrayFold 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): arraySplit 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): ?intResolve 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): intClamp 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): intStandard 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.

MethodSummary
static new(): selfCreate a new Veil instance.
static centered(string $content, string $backdrop, int $dimmingPercent = 50, int $xOffset = 0, int $yOffset = 0): stringThe modal preset: dim the backdrop, then centre the content over it.
withBackdrop(int $opacity): selfSet the backdrop opacity for dimming the background.
withAnimation(AnimationKind|Fade|Scale|Slide|null $animation): selfSet the animation for overlay transitions.
animation(): AnimationKind|Fade|Scale|Slide|nullRead-only accessor for the animation driver (preset kind or instance).
zIndex(): intRead-only accessor for z-index.
clickOutsideDismiss(): boolRead-only accessor for click-outside-dismiss flag.
autoSize(): boolRead-only accessor for the auto-size flag.
border(): ?BorderRead-only accessor for border chrome.
withZIndex(int $zIndex): selfSet the z-index for stacking order.
withClickOutsideDismiss(bool $enabled = true): selfSet the click-outside-dismiss flag.
withAutoSize(bool $enabled = true): selfSet the auto-size flag.
withBorder(?Border $border): selfSet the border chrome for wrapping veil content, or clear it with null.
withPosition(?Position $vertical, ?Position $horizontal, int $x = 0, int $y = 0): selfSet the vertical and horizontal position anchors for this veil.
withPlacement(Placement $placement): selfStore 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(): PlacementThe stored placement, an unset axis reading as CENTER (the default every stack pass applies).
withContent(string $content): selfAttach 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): selfwithContent() 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(): stringRead-only accessor for the stack-driven overlay content ('' = none).
withoutZoneMarkers(): selfReturn a copy whose mark() emits no zone envelopes at all.
withReducedMotion(bool $reduced = true): selfHonour the user's reduced-motion preference.
lastFullFrame(): ?stringThe FULL (non-delta) frame the last composite()/animate() emitted, or null if none has been painted through this veil's session yet.
vPosition(): ?PositionRead-only accessor for vertical position anchor.
hPosition(): ?PositionRead-only accessor for horizontal position anchor.
positionX(): intRead-only accessor for X position offset in columns.
positionY(): intRead-only accessor for Y position offset in rows.
applyBorderChrome(string $content): stringWrap content with border chrome using sugar-style Style.
isClickOutside(\SugarCraft\Core\Msg\MouseMsg $mouse): boolCheck if a mouse message is outside the veil zone.
scan(string $rendered): selfFeed 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): ?ZoneReturn 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): ?arrayThe 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(): arrayEvery 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): stringWrap $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): stringApply animation and composite the overlay onto the background.
coveredCells(string $foreground, string $background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0): ?arrayWhich 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): ?arrayHow 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): stringComposite a foreground string over a background string.
place(string $foreground, string $background, ?Placement $at = null): stringComposite $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): arraySplit a multi-line string into an array of lines.
maxLineWidth(array $lines): intGet the maximum line width (in characters) of an array of lines.
lineWidth(string $line): intGet the display width of a single line, in terminal cells.
resetPreviousFrame(): voidReset the diff state, forcing the next composite to emit a full frame.
withoutSession(): selfReturn a copy of this veil with a fresh RenderSession.

VeilStack final class

Ordered collection of Veil instances rendered by z-index.

MethodSummary
static new(): selfCreate a new empty VeilStack.
add(Veil $veil): selfAdd a veil to the stack.
clear(): selfRemove all veils from the stack.
removeWhere(\Closure $predicate): selfRemove veils matching the given predicate.
composite(string $background, Position $vertical, Position $horizontal, int $xOffset = 0, int $yOffset = 0): stringComposite all veils onto the background in z-index order (lowest first).
compositeAll(string $background, int $xOffset = 0, int $yOffset = 0): stringComposite all veils at their individual positions.
sorted(): arrayReturn veils sorted by z-index ascending.
all(): array
isEmpty(): bool
count(): int
filter(\Closure $predicate): selfFilter veils by a predicate.
maxZIndex(): ?intGet the highest z-index in the stack, or null when the stack is empty.
minZIndex(): ?intGet 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.

MethodSummary
__construct(private readonly ?CubicBezier $easing = null)
static new(?CubicBezier $easing = null): self
easedProgress(float $progress): floatThe 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): stringApply fade animation to the foreground at the given progress.
opacity(float $progress): intGet the opacity value for this progress (0-100).

Scale final class

Scale animation — foreground "grows" from center outward.

MethodSummary
__construct(private readonly ?CubicBezier $easing = null)
static new(?CubicBezier $easing = null): self
easedProgress(float $progress): floatThe 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): stringApply scale animation to the foreground at the given progress.

Slide final class

Slide animation — foreground enters from the anchor direction.

MethodSummary
__construct(private readonly ?CubicBezier $easing = null)
static new(?CubicBezier $easing = null): self
easedProgress(float $progress): floatThe 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): AnimationFrameThe 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): arrayThe 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

Multiple overlays

Stacked overlays composited in z-order.
  • SugarMouse: mouse hit-testing and zone trackers.
  • SugarSpring: damped spring physics, a declared dependency of this overlay.