sugarcraft / sugar-dashboard
Dashboard TUI library — column grid, constraint layout, ratio grid, data grid, tree, modal, status bar, tabs, plot/canvas, and module/plugin system. Ports patterns from shahar3/bubble-grid, aristocratos/btop, treilik/bubbleboxer, gizak/termui, floatpane/lattice, mko88/bubbletea-tilelayout, mikeschin
Requires
- php: ^8.3
- react/promise: ^3.3
- sugarcraft/sugar-async: dev-master
- sugarcraft/sugar-cellbuffer: dev-master
- sugarcraft/sugar-colorprofile: dev-master
- sugarcraft/sugar-core: dev-master
- sugarcraft/sugar-focus: dev-master
- sugarcraft/sugar-style: dev-master
- sugarcraft/sugar-toast: dev-master
Requires (Dev)
- phpunit/phpunit: ^10.5
- sugarcraft/candy-vcr: @dev
- sugarcraft/sugar-pty: dev-master
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:05 UTC
README
sugar-dashboard — a TUI building-block library for PHP 8.3+: column grid, constraint layout, ratio grid, data grid, tree, modal, status bar, tabs, plot/canvas, and a module/plugin system, with components organized into the namespaces below.
Installation
composer require sugarcraft/sugar-dashboard
Namespace Structure (13 Namespaces)
| Namespace | Description |
|---|---|
Foundation\ |
Pure interfaces + low-level primitives (Item, Sizer, Style, Theme, Color, Rect, Drawable, Buffer, Cell) |
Layout\ |
Layout primitives (Stack, VStack, HStack, ZStack, FlexLayout, GridLayout, Frame, Panel, Split, Spacer, Window, etc.) |
Components\ |
UI components (Modal, Select, Toast, Tabs, StatusBar, Form, Feedback, Nav, Card, Calendar, Tree, Table, etc.) |
Plot\ |
Charts and plotting (Chart, Sparkline, Gauge, Donut, Heatmap, RadarChart, Graph, etc. — the tree/diagram family TreeViz, Sankey, Sunburst, Treemap, Network, MindMap, OrgChart, ClassDiagram, Flowchart, StateMachine, Dendrogram lives in Components\Tree\, not here) |
Module\ |
Module interface + base implementations |
Registry\ |
Registry pattern for modules |
Plugin\ |
Plugin system with JSON protocol |
Modules\ |
Built-in modules (Clock, System, Weather, etc.) |
Msg\ |
Host-traffic message types — TickMsg, the one shared module refresh tick (addressed via TickMsg::for($module) it drives a single module; source-less it serves every ticking module — the five legacy per-module markers Modules\{Clock,Uptime,Weather,Generic}\TickMsg and Modules\System\RefreshMsg are class_alias shims, REMOVED-IN: 2.0.0), and AdapterTickMsg, the scheduled refresh tick that drives legacy panel updates (kept a dedicated type so unrelated traffic, keystrokes above all, passes through without a blocking plugin round-trip) |
Keys\ |
Key registry and mappings |
Position\ |
ANSI-aware geometry helpers |
Output\ |
Extracted helpers (truncate, render bar) |
State\ |
State management |
Foundation Namespace
Interfaces & Contracts
| Type | Description | Key Methods |
|---|---|---|
Item |
Anything that can be rendered as a string | render(): string |
Sizer |
An Item that knows its own dimensions (extends Item) | setSize(int $width, int $height): Sizer, render(): string |
SizedItem |
A Sizer that can also report its intrinsic (unconstrained) size — the measurement contract every layout container in the library uses to size its children (extends Sizer) |
innerSize(): array |
Drawable |
Universal draw contract with rect/setRect/draw | rect(): Rect, setRect(Rect): void, draw(Buffer): void |
Low-Level Primitives
| Type | Description | Key Methods |
|---|---|---|
Cell |
Single terminal cell (rune + Style) — the package's own single source of truth, distinct from \SugarCraft\Vterm\Cell\Cell |
|
Buffer |
Cell grid buffer for drawing — the package's own single source of truth, distinct from \SugarCraft\Vterm\Buffer\Buffer |
cell(x,y), setCell(x,y,Cell), fill(rect,Cell) |
Rect |
Rectangle geometry (rectmath bounds model: minX/minY/maxX/maxY) — distinct from \SugarCraft\Core\Rect (offset+size model) |
contains(), intersect(), dx(), dy() |
Style |
Terminal styling (inline foreground/background Color slots) — the package's own single source of truth, distinct from \SugarCraft\Style\Style (padding/margin/borders) |
withForeground(), withBackground(), withBold(), toAnsi() |
StyleParser |
Parses [text](fg:red,bg:blue) into Dash Cell arrays — the package's own single source of truth, NOT drop-in compatible with \SugarCraft\Style\StyleParser |
|
Color |
Backward-compat alias for \SugarCraft\Core\Util\Color (true duplicate, replaced by class_alias shim — prefer Core import in new code) |
|
Theme |
Pre-defined theme palettes (9 color slots + helpers; fg()/bg() emit at the process-wide ColorMode capability, NO_COLOR → empty string) — the package's own single source of truth, distinct from \SugarCraft\Style\Theme (13 slots, readonly properties, immutable with*() builders, no render helpers) |
dark(), dracula(), oneDark(), githubDark(), light() |
ColorMode |
Process-wide color capability gate for every renderer in the library — charts, gauges and chrome route through it instead of each deciding on its own — the one capability authority; it deliberately diverges from ColorProfile::detect() in three documented, probe-pinned places, see Color Environment |
use(?ColorProfile): void, profile(): ColorProfile |
Threshold |
Maps a numeric value (typically a 0..1 ratio) to a Color via ordered stops — the shared "green below 60%, yellow below 80%, red above" pattern that gauges, meters and status indicators would otherwise each reinvent; health() is the preset triple |
of(array $stops), health(?ok, ?warn, ?critical), colorFor(float): Color, stops() |
EnumCoerce |
Accept-both coercion for knobs converging from a stringly vocabulary onto the enum that already models it (D-147): enum cases pass through, legacy case-value strings resolve with an E_USER_DEPRECATED notice, unknown values throw at the boundary instead of silently defaulting; string-backed enums only |
from(BackedEnum|string, class-string, string): BackedEnum |
EdgeStyle |
String enum Solid/Dashed/Dotted/Bold — currently dormant: no consumers in the library (the live tree-edge variant is Components\Tree\EdgeStyle, which carries Double in place of Bold and is consumed by Network) |
|
Segment |
7-segment display component (digital-clock/calculator style) — renders characters from horizontal and vertical segments | new(string), withDigitWidth(), withShowColon(), withOnColor(), withOffColor(), withContent() |
Dual-source-of-truth (SSOT) note. Five Foundation primitives (
Style/Theme/Rect/Buffer/Cell) plusStyleParserare intentionally distinct from same-named canonical types insugar-style/sugar-core/sugar-vterm. The two families have distinct design lineages and the API shapes diverge. OnlyColorwas a true duplicate and is now aclass_aliasto\SugarCraft\Core\Util\Color. SeeCALIBER_LEARNINGS.mdentries[pattern:dual-foundation-ssot],[pattern:dual-style-ssot],[pattern:dual-theme-ssot],[pattern:dual-rect-models],[pattern:dual-buffer-roles],[pattern:dual-cell-shapes].
Layout Namespace
Layout Enums
| Type | Values |
|---|---|
LayoutDirection |
Horizontal, Vertical |
SplitDirection |
Horizontal, Vertical |
AlignItems |
Start, End, FlexStart, FlexEnd, Center, Stretch, Baseline |
FlexDirection |
Row, Column, RowReverse, ColumnReverse |
FlexWrap |
NoWrap, Wrap, WrapReverse |
HAlign |
Left, Right, Center |
VAlign |
Top, Middle, Bottom |
JustifyContent |
Start, End, FlexStart, FlexEnd, Center, SpaceBetween, SpaceAround, SpaceEvenly |
Layout Containers
Border & Frame Components
Spacing & Layout Helpers
Layout Subsystems (Tile, Boxer, RatioGrid, Focus)
These four subsystems carry the layout names in the GIF grid and the
dashboard-live demo. Each lives under src/Layout/ (the data grid they
feed, Components\GridTable, is documented in the Components section).
| Type | Description | Key Methods/Factories |
|---|---|---|
TileLayout |
Constraint-based tile layout (bubbletea tilelayout pattern): a named root splits its region among child Tiles horizontally or vertically |
horizontal(name), vertical(name), withTile(), withTiles(), withDirection(), withGap(), withTheme(), setSize(), render(), innerSize() |
Constraint |
How a child is sized along a container axis — the fixed/flex/fit constraint model: fixed pixels, a flex weight, or fit-to-content, with min/max clamps; the active flavour is reported as a ConstraintKind enum |
fixed(px), flex(weight), fit(), withMinSize(), withMaxSize() |
Resolver |
Five-phase tile-dimension solver turning constraints into concrete rectangles (resolveLinear for one axis, resolveTile for the 2-D walk) |
resolveLinear(), resolveTile() |
SizeHint |
Min + desired size a widget reports to the solver; widgets supply one through the SizeHinter contract |
empty() |
Boxer |
Tree-based layout engine (bubbleboxer pattern): nested horizontal/vertical Node splits addressed by dotted string path (e.g. 0.1.2); items live beside the tree, so editing a leaf never rebuilds the layout tree |
leaf(address, Item), tree(Node, modelMap), horizontal(...nodes), vertical(...nodes), editLeaf(address, callable), setSize(), render() |
RatioGrid |
Grid whose rows/columns are sized by ratio (termui grid pattern); cells placed by (row, col) coordinate, NewColRow carries the generated guides |
new(columns, rows), withCell(row, col, GridItem), setSize(), render(), innerSize() |
FocusManager |
Persistence wrapper over sugar-focus's FocusRing for a layout hierarchy: the ring owns the ordered focusable ids and wrap-around Tab/Shift-Tab traversal; persistState()/restoreState() park the focused id through a State\Persistence file so focus survives panel swaps and reloads |
register(id), unregister(id), focus(id), blur(id), isFocused(id), focusedId(), focusNext(), focusPrevious(), persistState(persistence, path), restoreState(persistence, path) |
Layout\Grid (StackedGrid Option Parts)
StackedGrid itself is catalogued under Layout Containers; these three are
its Layout\Grid\ option value parts.
| Type | Description | Key Properties |
|---|---|---|
Options |
Grid-level configuration options — fitScreen: false keeps short columns at their natural width (capped at the even share, so the frame never overflows); true (default) pads every column to the even share |
$fitScreen: bool (default: true) |
ItemOptions |
Per-item placement options within StackedGrid | $column: int (0-based), $expandVertical: bool |
ItemWithOptions |
Internal pairing of Item + ItemOptions | $item: Item, $options: ItemOptions |
Plot Namespace (Charts & Visualization)
Chart Components
Value redundancy (color-vision aids)
Color alone should never be the only channel carrying a reading. These shipped toggles encode the same value redundantly as text, position, or shape, so the panels stay readable in a color-blind terminal:
Chart::withShowValues()— prints the numeric value on each bar.Gauge::withPercentage()— prints the fill ratio as a number beside the bar length.Heatmap::withValues()— writes each cell's value over the gradient fill. (HeatMapChartcarries the low→high gradient but no value overlay; label it yourself when color is the only channel.)Plot\Chart\Meter::withGradient($stops, positionWise: true)— hue maps to fill position, so the meter reads identically by height alone.Plot\DistanceFade— selection distance is expressed as a dimming falloff, a shape cue independent of the palette.Plot\Braille\DualSampleGraph::withGradient()andPlot\Braille\BrailleCanvas::withGradient()— the color follows the sample value; the glyph geometry always carries it on its own.
Graph & Network Visualization
btop-derived graphs, meters & process rows
Ported from aristocratos/btop for candy-top; every class is a standalone immutable value object, and the integer color/quantization laws are byte-faithful to btop (several are pinned against oracle fixtures generated from btop's own C++).
| Type | Description | Key Methods/Factories |
|---|---|---|
Plot\Gradient101 |
btop Theme::generateGradients: expand ≥2 stops into a 101-entry ramp (index = percent) with btop's truncating integer law |
expand(list<Color>): list<Color> |
Plot\Braille\BrailleCanvas |
Dot canvas — now with an optional value→color ramp | withGradient(stops, ?scale), withValue(), withoutGradient(), gradient(), value() |
Plot\Braille\DualSampleGraph |
btop Draw::Graph: two adjacent samples quantized into one glyph; braille / block / block2 / tty families |
new(width, height, family, invert, noZero, maxValue, offset), push(), withData(), withGradient(), withUnderlay(), underlay(), render() |
Plot\Chart\Meter |
Analog meter — now with btop's one-row position-colored ■ bar (value redundancy aid — see Value redundancy above) |
withGradient(stops, positionWise), withGlyph(), withInvert(), withMeterBg(), memoStats(), resetMemo() |
Foundation\NetAutoScale |
btop net-graph ceiling hysteresis (grow/shrink only after 5 sustained samples) | new(sync), offer(down, up), downloadMax(), uploadMax(), maxFor(), counters(), forceRescale() |
Foundation\GradientStore |
Named 101-entry ramps — at('cpu', 73) is btop Theme::g("cpu")[73] |
new(), fromStops(), ramp(), withGradient(), at(), gradient(), has(), names() |
Plot\DistanceFade |
btop proc-list distance fade (text dims, metrics blend to grey away from the selection; value redundancy aid — see Value redundancy above) | ramp(), distance(), fadeIndex(), fadeColor(), metricPosition(), metricColor(), flatMetricColor(), metricValues() |
Plot\ProcRow\ProcRowComposer |
One btop process-list row: pid, name, cmd, threads, user, mem, 5×1 cpu graph on graph_bg, cpu% | new(width) (box inner width), row(ProcRow, row, selected, selectMax, ?graph, followed), withColumns(), withPalette(), withProcColors(), withProcGradient(), withFamily() |
Plot\ProcRow\ProcRow |
Process DTO (pid, name, cmd, threads, user, cpu, memPercent, ?memLabel) | new(...) |
Plot\ProcRow\ProcColumns |
btop column widths | btop(boxWidth, cpuGraphs), new(prog, cmd, threads, user, cpuGraphs), width() |
Plot\ProcRow\ProcRowPalette |
Theme slots + the proc / proc_color / process ramps |
btop(), new(...), withRamps(), withSelected(), withFollowed() |
Plot\ProcRow\ProcGraphTracker |
Per-pid mini-graph lifecycle: a graph is created when a pid is first seen busy (cpu > 0), dropped after 10 consecutive samples below IDLE_THRESHOLD (0.1) |
new(width, family), observe(pid, cpu), retain(pids), graph(pid), sample(cpu) |
Run php examples/dual-sample-graph.php for all four graph families,
an inverted graph, the underlay mini-graph and position-mode meters.
Gradient101 + BrailleCanvas gradients
Gradient101::expand($stops) is the shared ramp: two stops are one
0..100 leg, three stops split at 50 (btop's start/mid/end), more stops
split evenly. BrailleCanvas::withGradient($stops, ?Closure $scale = null)
attaches such a ramp; afterwards every setPoint() / setLine() with a
null color paints the ramp color at the canvas' current value
(withValue()), while an explicit color still wins. $scale maps a raw
sample onto 0..1 (clamped) — the place for btop's
(v + offset) * 100 / max_value law. The ramp, scale and value survive
setSize(); withoutGradient() detaches it.
use SugarCraft\Core\Util\Color; use SugarCraft\Dashboard\Plot\Braille\BrailleCanvas; use SugarCraft\Dashboard\Plot\Gradient101; $stops = [Color::hex('#80d0a3'), Color::hex('#dcd179'), Color::hex('#d45454')]; // btop Default cpu $ramp = Gradient101::expand($stops); // 101 Colors; $ramp[50] is #dcd179 $canvas = BrailleCanvas::new(16, 8) ->withGradient($stops, scale: static fn (int|float $v): float => $v / 100); $x = 0; foreach ([10, 35, 60, 90, 40, 20, 75, 100] as $v) { $h = (int) round($v / 100 * 7); $canvas = $canvas->withValue($v)->setLine($x, 7, $x, 7 - $h)->setLine($x + 1, 7, $x + 1, 7 - $h); $x += 2; } echo $canvas->render();
DualSampleGraph
btop's history graph. Each cell pairs the previous and current sample,
each quantized to a band 0..4 per graph row, and looks the pair up in
btop's 5×5 graph_symbols table — so braille packs two samples per cell,
and every push() scrolls the frame half a cell (a whole cell in tty).
new(int $width, int $height, string $family = FAMILY_BRAILLE, bool $invert = false, bool $noZero = false, int $maxValue = 0, int $offset = 0)— familiesFAMILY_BRAILLE(⣿),FAMILY_BLOCK(quadrants; bands 1/2 share a glyph),FAMILY_BLOCK2(2×3 sextants, btop PR #1783 — needs a font with Symbols for Legacy Computing; underlay🬭) andFAMILY_TTY(shades, one sample per cell).DualSampleGraph::FAMILIESlists all four.- Values are percents 0..100 unless
$maxValue > 0, which applies btop'sclamp((v + offset) * 100 / maxValue, 0, 100)(a positive$offsetalone impliesmaxValue100).$invertdraws top-down (btop's upload graph);$noZerokeeps the bottom row at band ≥ 1 so idle still shows a floor line. push(...$values)appends,withData(...$values)replaces the history. History is retained up to the widest width seen (floorHISTORY_CELLS= 1024), so shrinking and growing back redraws old samples.withGradient($stops)colors through aGradient101ramp: a one-row graph colors each cell bymax(prev, cur), taller graphs color each row by its vertical position (value redundancy aid — glyph height alone still carries the reading; see Value redundancy under Chart Components).withUnderlay(Color $inactiveFg)paints btop'sgraph_bgglyph (⣀/▄/🬭/░for the braille / block / block2 / tty families respectively, seeunderlayGlyph()) wherever a one-row graph is transparent; staticunderlay($family, $cells, $inactiveFg)returns the bare strip for callers that compose it themselves.render(?ColorProfile)returnsheightlines; it implementsSizer, sosetSize()drops it into any layout.
use SugarCraft\Core\Util\Color; use SugarCraft\Dashboard\Plot\Braille\DualSampleGraph; $stops = [Color::hex('#80d0a3'), Color::hex('#dcd179'), Color::hex('#d45454')]; echo DualSampleGraph::new(12, 3) ->withGradient($stops) ->withData(5, 12, 30, 55, 80, 95, 70, 45, 20, 10, 35, 60) ->render(), "\n"; // Upload-style: block glyphs, grows downward, raw bytes/s scaled to a 2 KiB ceiling. echo DualSampleGraph::new(12, 2, DualSampleGraph::FAMILY_BLOCK, invert: true, maxValue: 2048) ->push(128, 512, 1024, 2048, 1500, 900) ->render(), "\n"; // A btop proc-list mini-graph: 5×1, never fully blank, on the grey underlay. echo DualSampleGraph::new(5, 1, noZero: true) ->withUnderlay(Color::hex('#404040')) ->push(0, 40, 90) ->render(), "\n";
Meter position mode
Meter::withGradient(array $stops, bool $positionWise = false) attaches a
Gradient101 ramp. With positionWise: false the analog body is colored
by the meter's value. With positionWise: true the meter renders btop's
one-row Draw::Meter bar instead: cell i (1-based) sits at
y = round(i * 100 / width), is filled while value >= y and takes ramp
color y — so a 50% bar on green→red is green-to-yellow, never all
yellow — and the unfilled tail is painted in meter_bg.
withWidth()honours widths down to 1 cell in position mode (a layoutsetSize()width wins when set).withGlyph(string = '■'),withInvert(bool = true)(leftmost cell takes the ramp's high end, e.g. a discharging battery),withMeterBg(?Color)(null = btop's#404040).- Rendered bars are memoized process-wide per shape (stops, width, invert,
glyph, meter_bg) × value 0..100, like btop's per-meter
std::array<string,101>cache, bounded to 64 shapes / 4 MiB.Meter::memoStats()/Meter::resetMemo()expose and clear it;Meter::cacheKey(...)is the shape key.
use SugarCraft\Core\Util\Color; use SugarCraft\Dashboard\Plot\Chart\Meter; $stops = [Color::hex('#80d0a3'), Color::hex('#dcd179'), Color::hex('#d45454')]; echo Meter::new(0.62)->withWidth(20)->withGradient($stops, positionWise: true)->render(), "\n"; echo Meter::new(0.30)->withWidth(20)->withGradient($stops, positionWise: true) ->withInvert()->withGlyph('▮')->withMeterBg(Color::hex('#202020'))->render(), "\n";
NetAutoScale + GradientStore
NetAutoScale is btop's network-graph ceiling, per direction: a speed
above the ceiling bumps a fast counter, one under a tenth of it (with
the ceiling above 10 KiB) bumps a slow counter, and only a counter
reaching 5 rescales — to avg × 1.3 (grow) or avg × 3 (shrink) of the
last 5 samples, floored at NetAutoScale::FLOOR (10 KiB/s). The first
offer() always rescales. new(sync: true) mirrors btop's net_sync
(one shared ceiling). forceRescale(?$downHistory, ?$upHistory) arms a
rescale on the next offer; the public $rescaled flag says whether the
last offer moved a ceiling.
GradientStore is the named-ramp registry a themed monitor reads per
cell. fromStops() takes btop-style flat keys (<name>_start /
_mid / _end; keys without _start are ignored), withGradient()
registers or replaces one (start-only fills all 101 entries), and
at($name, $percent) clamps the percent and throws
\OutOfBoundsException for an unknown name. Expanded ramps are memoized
process-wide (MEMO_CAP = 256).
use SugarCraft\Core\Util\Color; use SugarCraft\Dashboard\Foundation\{GradientStore, NetAutoScale}; $scale = NetAutoScale::new()->offer(50_000, 4_000); // first offer rescales // $scale->downloadMax() === 65000, $scale->uploadMax() === 10240 (floor) for ($i = 0; $i < 5; $i++) { $scale = $scale->offer(200_000, 4_000); // 5 sustained samples above → grow } // $scale->downloadMax() === 260000 $store = GradientStore::fromStops([ 'cpu_start' => Color::hex('#80d0a3'), 'cpu_mid' => Color::hex('#dcd179'), 'cpu_end' => Color::hex('#d45454'), ])->withGradient('proc', Color::hex('#cccccc'), end: Color::hex('#404040')); echo $store->at('cpu', 73)->toHex(); // #d99868
Process rows: ProcRowComposer, DistanceFade, ProcGraphTracker
ProcRowComposer::new($width) (the box's inner width) renders btop's normal-view process
row, exactly width() cells wide, with btop's own column sizing
(ProcColumns::btop(); pass withColumns(ProcColumns::new(...)) for a
custom layout). The selected ($row + 1 === $selected) or followed
row is a bold highlight bar; every other row fades its text by distance
from the selection and colors cpu/name, mem and threads by value
(withProcGradient() / withProcColors() toggle btop's
proc_gradient / proc_colors). Control characters in name/cmd/user
become spaces. Colors come from ProcRowPalette (btop() is btop's
Default theme; withRamps() accepts ramps from a GradientStore).
DistanceFade exposes the underlying law as static helpers — including
btop's deliberate off-by-one ($selected is 1-based, $row 0-based).
ProcGraphTracker owns the per-pid 5×1 DualSampleGraphs: observe()
once per pid per fresh collection, retain($livePids) to sweep dead
pids; sample() lifts any cpu in [0.1, 5) to 5 so a barely-busy
process still shows.
use SugarCraft\Dashboard\Plot\ProcRow\{ProcGraphTracker, ProcRow, ProcRowComposer}; $composer = ProcRowComposer::new(78); // inner width of an 80-column proc box $tracker = ProcGraphTracker::new(); $procs = [ ProcRow::new(1234, 'php', 'php bin/candy-top', threads: 3, user: 'joe', cpu: 42.5, memPercent: 3.2), ProcRow::new(888, 'mysqld', '/usr/sbin/mysqld', threads: 38, user: 'mysql', cpu: 7.1, memPercent: 11.0), ]; foreach ([10.0, 30.0, 42.5] as $cpu) { // three collection ticks $tracker = $tracker->observe(1234, $cpu)->observe(888, 7.1); } foreach ($procs as $row => $p) { echo $composer->row($p, $row, selected: 1, selectMax: count($procs), graph: $tracker->graph($p->pid)), "\n"; }
Components Namespace
Keyboard, focus, mouse and resize contract. No class under
Components\reads input itself: nothing insrc/Components/consumes key, mouse, or resize events. Interactive widgets are pure renderers whose entire input vocabulary is their state setters (withValue(),withActiveIndex(),withSelected(), …), and focus-emphasis is host-driven the same way — a focusedInputgets its highlight through the border color passed to it, not through an internal focus bit.What the lib provides is the machinery the host wires together:
Keys\KeyMap::handle(Key)dispatches a decoded key to its boundKeyActionclosures (on()/onAny()/off();Keys\KeyIdentifiermints the standard binding idsquit(),help(),refresh(),focusNext(),focusPrev());Layout\FocusManagerholds the ordered set of focusable ids, delegating wrap-around Tab/Shift-Tab traversal to sugar-focus'sFocusRingand adding a per-id focused-history flag with durable save/restore; andLayout\Screen::setup()/teardown()emit the session preamble and trailer — alternate screen, hidden cursor, and mouse tracking (Ansi::mouseAllOn()) when enabled. Resize arrives as sugar-core'sWindowSizeMsg. Legacy plugins see none of this traffic — only the tick and the dimensions, per "What a plugin can react to" under Plugin Namespace.
examples/dashboard-live.phpis the worked end-to-end wiring:q/Ctrl-Cquit,Tab/Shift+Taband the arrows rotate panel focus through aFocusManager, and each panel renders into itsBoxerlayout cell. It is the one example that needs a real terminal: piped, it names the PTY requirement on stderr and exits without rendering — every other example renders a pipe-safe one-shot frame (the golden harness asserts those bytes).
Components\GridTable (Data Grid)
The flagship interactive table — a full-featured data grid with sort, filter,
pagination, and column freezing (tealeaves/teagrid law, adapted to PHP with
wither-style immutable setters). The assembly entry point is GridTable
itself; everything else in the directory is its value part.
| Type | Description | Key Methods/Factories |
|---|---|---|
GridTable |
The grid: columns + rows + interactive state, renderable via the Item contract |
new(columns, rows), withColumns(), withRows(), setSize(), sort(), sortState(), filter(), filterText(), pagination(), page(), freezeColumns(), scrollTo(), render() |
Column / Row / Cell |
Grid geometry value parts — column definition (title, width, format), row, and formatted cell | Cell carries value()/format() |
Header / Footer |
Column header and summary footer renderers | Footer summarises configured columns |
Sort / SortState / SortDirection |
Sort engine and its immutable state: active column, direction, toggleDirection() |
isSorted(), column(), direction() |
Filter |
Text/condition filtering across columns | filters(), hasFilter(), isActive(), withFilter(), withoutFilter(), clear() |
Pagination |
Page windowing with clamping | withPage(), clampPage(), totalPages(), offset() |
Overflow / OverflowMode |
Per-cell overflow policy (clip/ellipsis/wrap family) | mode enum + helper |
Scrolling |
Vertical/horizontal scroll state feeding scrollTo() |
|
BorderChars / BorderConfig / BorderRegion |
Border character sets and per-region border configuration | |
Calc |
Column-width arithmetic shared by sort/filter/pagination passes |
Components\Form (Form & Input)
Components\Select (Choice Inputs)
The choice-input family; Option, OverlayPosition and AutoPositionHelper
in the same namespace are its value parts.
Components\Feedback (Non-Modal Feedback)
Components\Toast (Transient Feedback)
Components\Modal (Modal Dialogs)
Modal message protocol.
Components\Modal\Msg\defines the TEA-style answer types a modal interaction produces:AnsweredYesMsg,AnsweredNoMsg,AnsweredEditMsg,AnsweredDeleteMsgandClosedMsg, each afinal readonlyclass extending a shared abstract readonlyMsgbase so a host can pattern-match the whole family in onematcharm. The bundled dialogs are renderableItems — turning key presses into these messages is the host program's seam; the library ships the vocabulary, not the dispatcher.
Components\Nav (Navigation)
Components\Tabs (Tabbed Views)
Components\StatusBar (Status Bar)
Components\Card (Card & Content Components)
Components\Media (Media Components)
Components\Calendar (Calendar & Date Components)
Components\System (System/Console Components)
Components\Tree (Tree Structure Components)
Components\Table (Table Components)
| Type | Description | Key Methods/Factories | GIF |
|---|---|---|---|
TableChart |
Table-based chart | ||
TableBordered |
Bordered table | ![]() |
|
TableZebra |
Zebra-striped table | ![]() |
Keys Namespace (Key Registry)
| Type | Description | Key Properties |
|---|---|---|
Key |
Keyboard key combination; withCtrl() / withAlt() / withShift() return modified copies; matches() tests an incoming key |
toString() |
KeyAction |
Action triggered by a key combination | execute() |
KeyMap |
Keyboard shortcut handler (renderable, implements SizedItem) |
on(), onAny(), off() |
Category |
String-backed enum of key-binding categories | label() |
KeyIdentifier |
Unique identifier for a key binding, built from a string via of() |
of(), quit(), help(), refresh(), focusNext(), focusPrev() |
KeyMeta |
Metadata for a key binding (display string, full description) | display(), fullDescription() |
KeyRegistry |
Static central registry for key bindings (teautils KeyRegistry pattern) | register(), get(), byCategory(), categories(), match(), reset() |
State Namespace (State Management)
| Type | Description | Key Methods |
|---|---|---|
Persistence |
Atomic JSON state save/load (final; delegates to sugar-core AtomicJsonFile) |
save(path, data), load(path): ?array |
Privacy: state and cache writes publish private files — both
PersistenceandWeatherModuleuseAtomicJsonFile::withPermissions(0600), and directories they create are derived to0700. The weather cache at~/.cache/sugar-dashboard/weather.jsonholds your location data (theWeatherModule's configured location, or the IP-derived city when it runs inautomode — the live example reads theWEATHER_LOCATIONenvironment variable) and is never world-readable. AnAtomicJsonFilewrite also leaves a contentless.<basename>.locksidecar (mode 0600) beside the file: it is the cross-process write lock and is deliberately never deleted — removing it re-opens the race it exists to close.
Note:
TransitionType,StateNode, andStateTransitionmoved toComponents\Tree\namespace (PSR-4 one-class-per-file) and are retained here as@internalbackward-compatibility re-exports viaclass_alias.StateMachinelives only inComponents\Tree\— there is noState\StateMachinere-export, and noState\Statetype exists; the state-machine diagram component is documented under the Tree section.
Position Namespace (ANSI-Aware Geometry)
| Type | Description | Key Methods |
|---|---|---|
Center |
Geometry helper computing centered coordinates inside a container (see note below for the renderable Layout\Center) |
|
Overlay |
Auto-positioning helper for overlays — computes the optimal position relative to an anchor, choosing above or below based on available space, clamped to container bounds | calculate(int $overlayWidth, int $overlayHeight, int $anchorX, int $anchorY, int $containerWidth, int $containerHeight): array, fitsBelow(), fitsAbove() |
Note:
Position\Centeris the geometry helper (computes centered coordinates);Layout\Centeris a separate renderable wrapper that centres an item in theLayoutnamespace. Both are live classes — distinct responsibilities, same word.
Output Namespace (Extracted Helpers)
| Type | Description | Key Methods |
|---|---|---|
Truncate |
String truncation with ANSI awareness | |
RenderBar |
Bar rendering helper — color follows the process-wide ColorMode capability (?ColorProfile parameter; NO_COLOR strips every escape) |
|
WrapCells |
Cell-aware text wrapping |
Module Namespace (Module Interface)
| Type | Description | Key Methods |
|---|---|---|
Module |
MVC-style Model–Update–View interface aligned with Core\Model: init(): ?Closure, update(Msg): array{0:Module,1:?Cmd}, `view(): string |
View, subscriptions(): ?Subscriptions, plus name(): string, minSize(): array{0:int,1:int}` |
BaseModule |
Abstract helper — withState(array): static for immutable state, default update() returns [self,null] |
|
LegacyModule |
Array-state module adapter; the Module contract supersedes it (see the accessor-deprecation section for the family roster) |
|
LegacyModuleAdapter |
@internal wrapper that adapts LegacyModule to the Module contract |
|
ModuleConfig |
Module configuration | |
ImagePlacer |
Optional interface for image placements | |
ImagePlacement |
Image placement data | |
TickEpoch |
Focus-regain epoch counter | |
BoundedCommand |
One bounded child-process run: argv array (no shell interpolation), wall-clock deadline (default 5s), 1 MiB output ceiling, and a guaranteed TERM→KILL reap. The pump and the ladder are sugar-async's ChildRun. A Model update or tick must use runAsync(), which runs the child on the loop and settles on a promise; run() blocks the caller until the deadline and is for code outside the loop. SETTLE_CEILING_SECONDS is how long a started run can take to settle, and bounds how long a module may treat a command as in flight |
runAsync(LoopInterface $loop, array $argv, float $timeoutSeconds, int $maxOutputBytes): PromiseInterface · run(array $argv, float $timeoutSeconds, int $maxOutputBytes): array |
ProcAvailability |
Probe-once availability of Linux /proc pseudo-files — probe once, degrade quietly, show a visible 'n/a' sentinel on hosts without /proc instead of failing |
has(string $path): bool |
Registry Namespace (Module Registry)
| Type | Description | Key Methods |
|---|---|---|
Registry |
Instance store for module constructors — the host owns one and passes it around; register/get/has/list/reset are instance methods, so two registries never share a namespace (the old class-level statics made reset() a global mutation with order-dependent callers). Auto-wraps LegacyModule via LegacyModuleAdapter |
Plugin Namespace (Plugin System)
| Type | Description | Key Methods |
|---|---|---|
Request |
Plugin request DTO | |
Response |
Plugin response DTO | |
PluginSdk |
Plugin runner loop | |
ExternalModule |
Spawns a plugin binary as a LegacyModule; the host registers it through Registry which wraps it in LegacyModuleAdapter to meet the Module contract |
|
Discovery |
Plugin discovery from filesystem |
Plugin lifecycle (what a plugin author owes).
ExternalModulespawns the binary withproc_openand speaks line-delimited JSON over stdin/stdout. Each reply must arrive within 5 s on the same line it was requested on, one line at a time, capped at 1 MiB per line — a plugin that answers late, answers twice, or floods is disabled for the session rather than silently retried. Teardown is bounded: closing the three pipes gives a well-behaved plugin its graceful EOF exit, a 2 s polite poll follows, then the shared TERM → grace-poll → KILL → reap ladder (sugar-coreBoundedShutdown) runs, so a wedged plugin binary can never outlive the dashboard that started it — the ladder kills the direct child; grandchildren it spawns (say, from a shell wrapper) outlive it, so authors needing tree-killing wrap the command themselves. Plugin children get a small explicit environment allow-list (an internal allow-list ofPATH,HOME,USER,LANG,TERM,COLORTERM, built by a privateExternalModulehelper — internal behavior, not public API); the dashboard's own secrets are never handed to third-party binaries by inheritance. Any plugin-supplied text reaching terminal chrome (names, error lines) passes through an internal sanitizer (privateExternalModulehelper, not public API) that strips control bytes, CR reflow, and zone sentinels and clips over-length labels. The same bounded-teardown story coversGenericModuleandSystemModulecommand runs (5 s deadline, 1 MiB output cap viaBoundedCommand, with the same direct-children-only reap), and the weather fetch, which runs off the update door: on a host withpcntlit forks aForkedTaskchild under a 15 s parent deadline, and the child's HTTP client is capped byWttrInClient's 5 s stream timeout. A host withoutpcntlfalls back to an in-process fetch that blocks the frame for up to that 5 s timeout.What a plugin can react to. A legacy plugin panel is non-interactive by construction:
LegacyModuleAdapter::update()forwards exactly two message kinds into the round-trip —Msg\AdapterTickMsg(the scheduled refresh tick) andCore\Msg\WindowSizeMsg(a resize). Every other routed message, keys above all, is dropped at the wrapper: each keystroke used to trigger a synchronous write+read against the plugin child, blocking the frame until the answer arrived. The plugin'sview($state, $w, $h)therefore receives the dimensions from the lastWindowSizeMsg, starting at 80×24 until the host forwards a real size, and its refresh cadence is theintervalthe plugin advertises frominit()metadata (default 30 s, floored at 1 s) re-armed as theplugin-refreshtick subscription — not the host's own tick rate. A panel that needs keyboard input is a host component, not a plugin.Motion & reduced motion. The library owns no clock and no event loop: every render is a synchronous, pure snapshot, and all apparent motion is frame-driven by the host. The moving surfaces are exactly three —
Components\Feedback\Spinner, whoserender()picks its animation frame from wall time against thewithInterval()speed it was given,Components\Media\Marquee, whoserender($frame)scrolls text by a frame offset the host advances (nextFrame(),withSpeed()characters per frame,withDirection(), optionalwithFadeEdges()), andComponents\StatusBar\StatusIndicator, whoserender($now)alternates the dot between the configured color and its 50%-toward-black blend on a 500 ms half-cycle from the timestamp the host supplies (a barerender()is the still, bright frame). Everything else that looks alive is presentation only:Components\System\Timerdisplays whateverwithElapsedSeconds()the host feeds it, the tree'sStateTransitioncarries an expanded/collapsed state rather than an animation, and the plot canvases (DotMatrix,BrailleCanvas,DualSampleGraph) render their input statically. Because the host supplies every frame, a reduced-motion presentation is always reachable from the outside — render a fixed frame (Spinner::frameAt(0), or a constant$frameforMarquee) and hold the redraw cadence still. There is deliberately noREDUCE_MOTION/prefers-reduced-motionruntime knob inside the library; honoring such a signal is a host-policy decision (the candy-top app owns that precedent), and the frames above stay valid no matter which way that ruling lands.Color environment. Every color emission funnels through
Foundation\ColorMode— the library's one capability authority (finding M-7 is about renderers never callingColorProfile::detect()on their own, not about the two chains agreeing): the chain checksCLICOLOR_FORCE/FORCE_COLOR(truthy beats every off-switch), thenTERM=dumb→ plain text, thenNO_COLORpresent-and-non-empty → color off with decoration kept, thenCLICOLOR=0→ the same, and everything else lands on the TrueColor floor. It diverges from whatColorProfile::detect()would answer in the documented places, each pinned bytests/Foundation/ColorModeDetectDivergenceTest.php. Since P1-10adetect()answers through sugar-colorprofile's chain when that package is installed, soNO_COLOR=0and the force-over-NO_COLORorder now agree with this funnel. What still differs: a forced level is TrueColor here, while detect answers the chain's level (FORCE_COLOR=1is its Ansi floor); the chain funnels without negotiating sub-tiers, soTERM=xterm-256coloranswers TrueColor here versus detect'sAnsi256(detect additionally consultsCOLORTERM,TERM_PROGRAMand CI hosts, and refuses color on a non-tty stdout — a pipe keeps byte-identical output here, and embedding hosts that know the real destination collapse that last gap deliberately withColorMode::use(ColorProfile::detect(null, $stdout))); andTERM=dumbanswersNoTtyhere, wheredetect()answersAsciiand onlyColorProfile::detectTerminal()answersNoTty. An explicit profile argument — or a seeded override — always wins over the process mode.Sizing. The library never reads the terminal itself: hosts forward
Core\Msg\WindowSizeMsgto the root model, which is whatLegacyModuleAdapterand thedashboard-live.phpdemo consume (the demo falls back to theCOLUMNS/LINESenvironment when unattended). For a full assembly story — event loop, Boxer layout, FocusManager, per-panel tick — readexamples/dashboard-live.phptop to bottom.
Modules Namespace (Built-in Modules)
All built-in modules extend BaseModule and use withState() for immutable state updates.
Per-instance names. Every built-in takes an optional
name:ctor knob; unset it keeps the type name ('clock'), set it gives this instance its own identity ('clock-berlin'). Ticks are addressed to the instance's name, and the module registry keys on it — so hosting two clocks side by side just means naming them apart.
Requirements & environment.
SystemModule,UptimeModuleand friends read Linux interfaces —/proc/stat,/proc/meminfo,/proc/cpuinfo— and degrade to empty output on other kernels rather than failing. GPU rows are queried throughnvidia-smionly when that binary is present (memoized probe), so non-NVIDIA machines pay nothing.WeatherModulereacheswttr.inover the network and falls back to its cache (and to stale cache) when offline.
| Type | Description |
|---|---|
Clock\ClockModule |
Single-line clock |
System\SystemModule |
CPU/mem/uptime stats (+ GPU via nvidia-smi when present) |
Uptime\UptimeModule |
System uptime |
Generic\GenericModule |
Arbitrary command runner — string commands go to the shell (trusted-input contract); array argv runs without a shell, bounded by a kill ladder |
Weather\WeatherModule |
Live weather from wttr.in + 30min cache + stale fallback |
Weather\WttrInClient |
wttr.in J1 JSON API client implementing HttpClient |
Weather\HttpClient |
Interface for weather fetch — allows test doubles |
Weather\WeatherSnapshot |
Readonly DTO: tempC, condition, location, fetchedAt |
Usage Example
use SugarCraft\Dashboard\Layout\{Frame, VStack, Panel}; use SugarCraft\Dashboard\Layout\Grid\{StackedGrid, Options, ItemOptions}; use SugarCraft\Dashboard\Components\Card\Text; // Create a stacked grid layout $grid = new StackedGrid(new Options(fitScreen: true)); // Add items to columns $grid = $grid->withItem( Frame::new( VStack::centered( Text::new('Welcome to SugarDashboard'), Text::new('Build beautiful TUIs') ) )->withPadding(1), new ItemOptions(column: 0, expandVertical: true) ); // Add a panel to the second column $grid = $grid->withItem( Panel::titled( Text::new('This is a panel'), 'Dashboard' ), new ItemOptions(column: 1) ); // Set size and render (setSize returns a sized clone — assign it) $grid = $grid->setSize(80, 24); echo $grid->render();
Testing
cd sugar-dashboard && composer install && vendor/bin/phpunit
Key Bindings and Interactive Flow
The library deliberately ships no hard-wired keystrokes: widgets expose
programmatic behavior and the host wires keys to them. Keys\KeyMap
registers bindings (on()/onAny(); the FIRST registration per
combination wins, later duplicates warn and are shadowed) and dispatches
decoded input through handle(); Keys\KeyRegistry is the semantic-ID
roster for status-bar and help rendering. Layout\FocusManager carries the
focus ring. examples/dashboard-live.php is the worked end-to-end wiring:
| Component | Behavior (public API) | Demo keys (dashboard-live) |
|---|---|---|
Layout\FocusManager |
focusNext(), focusPrevious(), focus(id) |
Tab / Shift+Tab, arrow keys rotate panel focus |
GridTable\GridTable |
sort(Column), filter(string), page(int) |
host-bound — the grid exposes state, not keystrokes |
Form\CommandPalette |
withQuery() feeds filteredCommands(); withSelectedIndex() moves the cursor |
host-bound — invocation is the app's chosen key (commonly Ctrl+P) |
Modal family |
withShowClose() / close-label controls; dismissal is host dispatch |
host-bound — the Esc convention belongs to the app |
| whole app | quit, theme flip | q or Ctrl+C; Ctrl+T swaps the live demo between Theme::dark() and Theme::light() |
The palette/theme key flow: themes are slot palettes (Theme::dark(),
dracula(), oneDark(), githubDark(), light(), …) applied through the
withTheme()/withPalette() builders named in the component tables, while
color capability is negotiated by the Foundation\ColorMode chain (see
Color Environment above, including its three documented divergences from
ColorProfile::detect()). examples/comboBox.php and
examples/dashboard-form.php are render demos: caret, highlight and value
movement on Input/Select/Toggle/Slider are model methods the host
drives from its own key map.
GIF Demos
Example Demos
The examples/ directory contains standalone demo files that showcase individual components and combinations:
| Demo | Description |
|---|---|
dashboard-live.php |
Interactive dashboard — the headline demo. Program event loop, raw mode, Clock/System/Weather modules, Boxer layout, FocusManager, per-panel tick, keyboard navigation (Tab/arrows), quit (q/Ctrl-C). Run with php examples/dashboard-live.php |
dashboard-showcase.php |
Multi-component server dashboard with gauges, charts, timeline, breadcrumb, avatar group |
dashboard-complex.php |
Full-featured analytics dashboard with charts, stats, funnel, sparkline |
dashboard-accordion-timeline.php |
Collapsing Accordion sections beside a milestone Timeline |
dashboard-metrics.php |
Stat cards and StatusIndicator dots over live series |
dashboard-status.php |
Spinner, Progress and Gauge faces with Alert variants |
dashboard-charts.php |
Chart components including area, donut, radar, heatmap |
dashboard-form.php |
Input, Select, Toggle, Slider and Checkbox arranged in a framed two-column grid (render-only) |
dashboard-ui.php |
Badge, Tag and Chip variants on Card and Text chrome (render-only) |
dashboard-nav.php |
Breadcrumb trails and the Navbar row (render-only) |
dashboard-text.php |
FigletText banners and a Marquee scroller (render-only) |
dashboard-time.php |
Clock, Timer and Stopwatch faces with a Calendar heat grid (render-only) |
dashboard-media.php |
QRCode, Barcode and Pictogram plates (render-only) |
dashboard-data.php |
GridTable, List components and a TreeNode table across grid layouts (render-only) |
dashboard-devtools.php |
Diff views, HexDump panels and a LogViewer (render-only) |
dashboard-layout.php |
VStack/HStack/ZStack nesting over a framed grid shell (render-only) |
dual-sample-graph.php |
btop-style DualSampleGraph in all four families (braille / block / block2 / tty), inverted + underlay graphs, and position-colored Meter bars |
The table lists the headline demos only — examples/ carries the full set
(one file per component family and beyond); see the directory for anything
not named above.
Accessor deprecation (2026-10-24)
Per the house bare-accessor convention "Bare accessors (no get") (AGENTS.md), 89 get*() accessors across 41 classes were renamed to their bare twins (8 of them collide with TreeProvider members on classes that do not implement that interface — the remediation pass swept those in as violations, not protocol members). The legacy names remain as byte-identical BC forwarders, each marked @deprecated with REMOVED-IN: 2.0.0 in its docblock — they will be removed in sugar-dashboard v2.0.0.
The protocol members the first pass left on get*() were completed by the 2026-11-06 protocol-completion sweep: SizedItem::getInnerSize() → innerSize() (the interface plus its 187 implementations), Drawable::getRect() → rect() (the interface plus Plot, Badge, Card, and Buffer; setRect() is a mutator and keeps its name), and the TreeProvider quintet → roots()/children()/node()/depth()/totalValue() on both the interface and its sole implementor ArrayTreeProvider. These carry no BC forwarders: the sweep's consumer census found zero call sites outside the lib reaching any of them, and every in-lib call site was re-armed in the same commit, so shims would only have doubled the public surface. The same names on classes that do not implement TreeProvider were violations, not protocol members, and the 2026-10-24 remediation pass swept them into the marked table below (Boxer::getNode, Node::getChildren, the PartitionSegment and DendrogramNode getTotalValue/getDepth pairs, SunburstSegment::getTotalValue, HeatmapCalendar::getTotalValue). Address::getChild() was the roster's only named carve-out — the bare name child() was taken by its static factory; D-133 (2026-11-14) removed the Address VO itself (no production door ever consumed it: boxer addresses are dotted strings end to end), so the carve-out seat is gone with its class. Boolean is*()/has*() predicates are convention-compliant and stay as-is. External consumers (candy-sql, candy-top, sugar-charts) do import sugar-dashboard classes (Gauge, Badge, Card, BrailleCanvas, and more); no external call site reaches a renamed accessor, and the BC forwarders carry any such call until v2.0.0.
Internal call sites in src/ and examples/ were switched to the bare forms in the same commit.
| Namespace | Class | Deprecated | Use instead |
|---|---|---|---|
Components\Calendar |
HeatmapCalendar |
getAverageValue() |
averageValue() |
Components\Calendar |
HeatmapCalendar |
getDataDimensions() |
dataDimensions() |
Components\Calendar |
HeatmapCalendar |
getTotalValue() |
totalValue() |
Components\Card |
Diff |
getStats() |
stats() |
Components\Feedback |
LoadingText |
getCurrentFrame() |
currentFrame() |
Components\Feedback |
LoadingText |
getFrameAt() |
frameAt() |
Components\Feedback |
LoadingText |
getInterval() |
interval() |
Components\Feedback |
LoadingText |
getStyle() |
style() |
Components\Feedback |
Spinner |
getCurrentFrame() |
currentFrame() |
Components\Feedback |
Spinner |
getFrameAt() |
frameAt() |
Components\Feedback |
Spinner |
getFrameCount() |
frameCount() |
Components\Form |
CommandPalette |
getFilteredCommands() |
filteredCommands() |
Components\Form |
Cursor |
getCursorChar() |
cursorChar() |
Components\Form |
Editor |
getContent() |
content() |
Components\Form |
Editor |
getCursorPosition() |
cursorPosition() |
Components\Form |
Editor |
getLine() |
line() |
Components\Form |
Editor |
getLineCount() |
lineCount() |
Components\GridTable |
Cell |
getFormat() |
format() |
Components\GridTable |
Cell |
getValue() |
value() |
Components\GridTable |
Filter |
getFilter() |
filter() |
Components\GridTable |
Filter |
getFilters() |
filters() |
Components\GridTable |
Footer |
getSummaryColumns() |
summaryColumns() |
Components\GridTable |
GridTable |
getFilterText() |
filterText() |
Components\GridTable |
GridTable |
getFrozenColumns() |
frozenColumns() |
Components\GridTable |
GridTable |
getHeight() |
height() |
Components\GridTable |
GridTable |
getPagination() |
pagination() |
Components\GridTable |
GridTable |
getSortState() |
sortState() |
Components\GridTable |
GridTable |
getWidth() |
width() |
Components\GridTable |
Header |
getColumns() |
columns() |
Components\GridTable |
Header |
getSortedColumn() |
sortedColumn() |
Components\GridTable |
Overflow |
getHorizontal() |
horizontal() |
Components\GridTable |
Overflow |
getVertical() |
vertical() |
Components\GridTable |
Scrolling |
getRowHeight() |
rowHeight() |
Components\GridTable |
Scrolling |
getTotalHeight() |
totalHeight() |
Components\GridTable |
Scrolling |
getVisibleRows() |
visibleRows() |
Components\GridTable |
Sort |
getColumn() |
column() |
Components\GridTable |
Sort |
getDirection() |
direction() |
Components\Media |
Video |
getProgressWidth() |
progressWidth() |
Components\StatusBar |
StatusIndicator |
getStatus() |
status() |
Components\StatusBar |
StatusIndicator |
getSymbol() |
symbol() |
Components\System |
LogViewer |
getEntryCount() |
entryCount() |
Components\System |
Stopwatch |
getElapsedMilliseconds() |
elapsedMilliseconds() |
Components\System |
Stopwatch |
getElapsedSeconds() |
elapsedSeconds() |
Components\System |
Terminal |
getHistory() |
history() |
Components\System |
Terminal |
getInput() |
input() |
Components\System |
Terminal |
getOutput() |
output() |
Components\System |
Terminal |
getPrompt() |
prompt() |
Components\System |
Timer |
getRemainingSeconds() |
remainingSeconds() |
Components\Tree |
BranchStyle |
getConnectorChar() |
connectorChar() |
Components\Tree |
BranchStyle |
getEndConnectorChar() |
endConnectorChar() |
Components\Tree |
BranchStyle |
getLineChar() |
lineChar() |
Components\Tree |
DendrogramNode |
getDepth() |
depth() |
Components\Tree |
DendrogramNode |
getTotalValue() |
totalValue() |
Components\Tree |
DrilldownTree |
getBreadcrumbItems() |
breadcrumbItems() |
Components\Tree |
DrilldownTree |
getNavigationStack() |
navigationStack() |
Components\Tree |
SunburstSegment |
getTotalValue() |
totalValue() |
Components\Tree |
UMLClass |
getAttributes() |
attributes() |
Components\Tree |
UMLClass |
getMethods() |
methods() |
Components\Tree |
UMLClass |
getTemplateParams() |
templateParams() |
Foundation |
Buffer |
getCell() |
cell() |
Foundation |
Theme |
getName() |
name() |
Keys |
KeyMap |
getRegisteredKeys() |
registeredKeys() |
Layout |
FocusManager |
getFocusedId() |
focusedId() |
Layout\Boxer |
Boxer |
getHeight() |
height() |
Layout\Boxer |
Boxer |
getItem() |
item() |
Layout\Boxer |
Boxer |
getModelMap() |
modelMap() |
Layout\Boxer |
Boxer |
getNode() |
node() |
Layout\Boxer |
Boxer |
getRoot() |
root() |
Layout\Boxer |
Boxer |
getWidth() |
width() |
Layout\Boxer |
Node |
getAddress() |
address() |
Layout\Boxer |
Node |
getChildren() |
children() |
Layout\Boxer |
Node |
getHeight() |
height() |
Layout\Boxer |
Node |
getWidth() |
width() |
Layout\Tile |
BaseTile |
getName() |
name() |
Layout\Tile |
BaseTile |
getSize() |
size() |
Layout\Tile |
Tile |
getContent() |
content() |
Layout\Tile |
Tile |
getParent() |
parent() |
Module |
BaseModule |
getState() |
state() |
Plot\Braille |
BrailleCanvas |
getCell() |
cell() |
Plot\Braille |
BrailleCanvas |
getPixelSize() |
pixelSize() |
Plot\Canvas |
Canvas |
getPixel() |
pixel() |
Plot\Chart |
Heatmap |
getDataDimensions() |
dataDimensions() |
Plot\Chart |
Heatmap |
getMaxValue() |
maxValue() |
Plot\Chart |
Heatmap |
getMinValue() |
minValue() |
Plot\Chart |
OHLCPoint |
getBodySize() |
bodySize() |
Plot\Chart |
OHLCPoint |
getRange() |
range() |
Plot\Chart |
PartitionSegment |
getDepth() |
depth() |
Plot\Chart |
PartitionSegment |
getTotalValue() |
totalValue() |
Dependencies
- PHP 8.3+ (
^8.3). - Composer runtime deps (spelled as the committed manifest does):
sugarcraft/sugar-cellbufferdev-master— the cell-grid surface the renderers emit into.sugarcraft/sugar-coredev-master— the TEA runtime:Model/Msg/Cmd,Width,Truncate, andUtil\Sanitizethis lib's trust posture leans on (see Security below).sugarcraft/sugar-focusdev-master— focus traversal for the interactive components.sugarcraft/sugar-styledev-master— the SGR style value objects every styled cell routes through.sugarcraft/sugar-toastdev-master— transient notification surface shared with the host app.react/promise^3.3— the promise adapterCmd::promiseresults are handed back on (the weather fetch door resolves through it).
- Dev-only:
phpunit/phpunit^10.5,sugarcraft/candy-vcr(@dev),sugarcraft/sugar-pty— recording/PTY test support, never a runtime need. - Sibling deps are
requireentries only: standalone installs resolve them from Packagist, and CI injects the monorepo path-repo closure before each install (no path repositories are committed to this manifest). - Optional integrations (inbound consumers, not deps): candy-top imports the plot and foundation vocabulary (
Plot\Braille\DualSampleGraph,Plot\DistanceFade,Plot\ProcRow\*,Foundation\NetAutoScale,Foundation\GradientStore) across itsPanel/family —NetPanel,ProcPanel, and the Cpu/Mem/Gpu/Proc/Vms/Ctr views; candy-sql imports the card components and chart primitives (Components\Card\*,Plot\Chart\AreaChart,Plot\Braille\BrailleMatrix,Foundation\Threshold) in itsAdmin/ServerStatus/pages —SidebarGauge,StatusGraphCell,ServerInfoCard.
Security & trust boundaries
- Plugin discovery fails closed, never open to the neighborhood.
Plugin\Discoveryscans only a directory you opted into:CANDY_DASHBOARD_PLUGINS_DIRfirst, then the XDG config and HOME-derived plugin dirs. A candidate directory that is group/world-writable, owned by another uid, or missing from all three env homes is refused with a logged reason (error_log) — discovery never falls back to a world-writable/tmpand never loads code it cannot attribute. - Unencodable plugin state disables the panel, it does not corrupt the frame. The module state store refuses non-UTF-8 payloads at the send seam and normalizes reply bytes at the store seam, so a hostile plugin cannot push broken sequences through persisted state.
- Every untrusted string is swept before it renders. Plugin view content, module labels, the GenericModule output buffer, weather condition/location text, and plot legend/label data all pass through sugar-core's
SugarCraft\Core\Util\Sanitize::untrusted()(oruntrustedForDisplay()plusstripZoneSentinels()on marked-frame chrome) at their choke points — control bytes cannot escape a panel onto the wire, and forged PUA zone markers cannot reach a host's zone parser. - The weather transport is bounded. The wttr.in client refuses replies above the lib's own 1 MiB doctrine (
Module\BoundedCommand::MAX_OUTPUT_BYTES) — declared Content-Length up front, byte-counted during the read — and failure reasons are typed (WeatherTransportFailurevsWeatherParseFailure), so a black-holed or hostile endpoint stalls nothing and the card says why it is empty. - The layout subsystem is documented as experimental. The
Layout,Keys, andStatenamespaces carry an evolving surface ahead of the 2.0.0 freeze; the alternative — dogfooding them onto the Module render path first — is a standing owner decision, and the frames stay valid either way. Nothing in this section is a promise that today's layout API is the shipped one.
License
MIT License - See LICENSE file for details.
Credits & inspiration
Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project.















































































































































