All 42 libraries

SugarGallery

Poster grids & rails for media TUIs — virtualized PosterGrid, Rail carousel, PosterCard

original — no 1:1 Go counterpart grid gallery virtualization media

SugarGallery code coverage

Browse-row widgets for media terminal UIs: a 2-D virtualized PosterGrid for large libraries, a horizontal Rail browse strip (carousel) for browse rows, and a single PosterCard tile. The grid is sparse — it knows the total item count up front but holds only the cards that have been fetched, keyed by their absolute index, so a 50,000-item library renders as cheaply as a 50-item one; missing indices draw as skeletons and only the rows inside the viewport are ever rendered. Paging is owner-driven: after every cursor move the owner reads visibleRange() (the absolute-index window now on screen — the terminal analogue of the web grid's need-range event) and splices the covering page back in with withItems(). The widgets are renderer-agnostic: a card holds already-rendered poster bytes (produce them however you like, e.g. sugar-image), so this lib pulls in no image decoder. Original SugarCraft component — inspired by terminal list/viewport UX and web media-grid browsing.

Install

composer require sugarcraft/sugar-gallery

PosterGrid — virtualized, sparse, owner-paged

use SugarCraft\Gallery\PosterGrid;
use SugarCraft\Gallery\PosterCard;

$grid = PosterGrid::new(cardWidth: 16, posterHeight: 9)
    ->withViewport($cols, $rows)
    ->withReset(total: 5000);          // a fresh result set

// Keyboard nav (map your keys to these — all clamp + keep the cursor on screen):
$grid = $grid->right();            // ← → step one cell (crosses row edges)
$grid = $grid->down();             // ↑ ↓ move between rows
$grid = $grid->pageDown();         // PgUp / PgDn
$grid = $grid->home();             // Home
$grid = $grid->end();              // End
$grid = $grid->moveTo(2600);       // jump (e.g. an A–Z letter offset)

After each move, read the visible window and fetch the page(s) covering it, then splice the results back in at their absolute index — the need-range pattern, with needsFetch() as the shipped gate (it re-arms only when the window leaves the range you recorded; a null range always fetches):

// Once, before the first move:
$lastFetched = null;                  // needsFetch() always fetches on null

// After each move:
[$start, $end] = $grid->visibleRange(overscanRows: 1);
if ($grid->needsFetch($lastFetched, overscanRows: 1)) {   // the shipped gate
    // fetch items [$start, $end] from your API, build cards keyed by index…
    $grid = $grid->withItems([$start => $card0, $start + 1 => $card1, /* … */]);
    $lastFetched = [$start, $end];    // record what you covered
}

// Async poster arrived for one cell?
$grid = $grid->withItem($index, $card->withPoster($ansi));

Render the visible rows (the cursor shows only when the grid is focused — and on a skeleton cell the ▸ runs down every poster row, a whole-tile ghost, by design; an empty grid renders '' so the owner paints its own empty-state). Frame geometry. A frame is min(visibleRows(), totalRows() - scrollRow()) cell rows tall — rows * cellHeight() + (rows - 1) * vSpacing() lines by columns() * cardWidth() + (columns() - 1) * hSpacing() cells, joined with \n and no trailing newline; the bottom page can be shorter than the window and an empty grid emits zero rows, so a line-diff painter must clear the leftover tail of its reserved box when the page shrinks — stale ghost cards otherwise sit exactly where the user scrolled. Pass a sugar-mouse Manager to make each cell mouse-clickable — wrapped as zone id cell:<index>. Six chrome glyphs matter at narrow layouts, and they split four-and-two. Two are width-neutral and stay put: focus ▸ U+25B8 (the small triangular right, not the ambiguous ▶ U+25B6) and skeleton shade ░ U+2591. The other four are East-Asian-Ambiguous — the rail bullets ● U+25CF and ○ U+25CB, the bar’s filled leg ▓ U+2593, and truncation … U+2026; most terminals draw them single-cell, but a user’s ambiguous-width setting can widen them by a cell.

Paint a focused frame, then scan the zone markers out of it:

echo $grid->render(focused: true);

$frame = $grid->render(true, $zones);
$clean = $zones->scan($frame);                 // strip markers, record bounds
$zone  = $zones->anyInBounds($mouseMsg);       // → Zone|null — read $zone->id ("cell:42")

Rail — horizontal browse strip

use SugarCraft\Gallery\Rail;

$rail = Rail::new('Continue Watching', $cards);
$rail = $rail->moveCursor(+1, Rail::perRow($railWidth, $cardWidth));
echo $rail->render($railWidth, focused: true, cardWidth: 16, posterHeight: 9);

The heading rides the same title guard a card uses (AnsiGuard::stripControls()) and both header lines are clamped to the rail width; the empty state is localized via Lang::t('rail.empty') (16-locale family in lang/). moveCursor() takes a delta. To restore an arbitrary (cursor, scroll) pair — e.g. a remembered position — construct via Rail::new(...): its third and fourth arguments are that pair. A stale pair is clamped on construction, not restored verbatim: the cursor lands inside the card list and the scroll at or below it. The rail composes card bodies raw — the heading is swept, the joined cards are not — so if zones mark the same frame, run render()'s output through AnsiGuard::stripSentinels() before composing it.

PosterCard — one tile

use SugarCraft\Gallery\PosterCard;

$card = new PosterCard(id: '42', title: 'The Matrix', posterUrl: $url);
$card = $card->withPoster($renderedAnsi);   // attach when the async render lands
$card = $card->withSafePoster($fromCache);  // …or sweep untrusted bytes: SGR stays, controls go
$card = $card->withProgress(0.6);           // optional continue-watching bar
echo $card->render(focused: true, width: 16, posterHeight: 9);

Overlay posters (withImage()) draw as a single U+E002-range marker cell inside the reserved block — the image renderer paints the real graphics there, and the marker deliberately survives every text sweep (it lives outside the zone-sentinel window). Text-extraction paths (search, clipboard) therefore see an unassigned private-use glyph at that cell; sugar-core's Sanitize::stripPrivateUse() sweeps the whole block out of extracted text without touching the frame. The rule reaches further than the marker: a withPoster() inline mosaic IS frame text — █/░ runs are ordinary visible characters no sweep tidies — so extract card text from the model (title, positionText()), never the painted frame.

Behavior

Sparse & absolute-indexedThe grid knows the total() up front but holds only fetched cards keyed by absolute index; indices with no card yet render as ░ skeleton placeholders.
Failed is a state, not silenceA cell whose last fetch failed is marked with withFailed(): it falls back to the plain skeleton and hasPoster() stays false, so a retry policy re-queues it. An empty grid renders nothing — emptyMessage() hands the owner the localized sentence to paint instead.
2-D virtualizationOnly the rows inside the viewport are ever rendered, so a 50,000-item library costs the same to draw as a 50-item one.
Owner-driven pagingvisibleRange(overscanRows) returns the absolute-index window on screen (with optional prefetch overscan) — the terminal analogue of the web grid's need-range event; the owner fetches and splices via withItems().
Clamped navigationleft/right/up/down/pageUp/pageDown/home/end/moveTo all clamp into range and scroll the minimum needed to keep the cursor's row visible.
Uniform cellsEach cell is a uniform cardWidth × (posterHeight + 2) box (reserving a title and a progress row), so columns and rows always line up regardless of which cards carry progress bars.
Optional mousePass a sugar-mouse Manager to render() and each real cell is wrapped as zone id cell:<index> for hit-testing — the caller scans the frame and resolves clicks.
Renderer-agnosticA PosterCard holds already-rendered poster bytes (produce them however you like, e.g. sugar-image), so the lib pulls in no image decoder.
ImmutableEvery mutator returns a new grid / rail / card and leaves the receiver untouched, slotting into the immutable Model–Update–View pattern; a no-op move returns the receiver by identity.

Use it for

  • Large media libraries — a browse grid over thousands of posters fetched lazily a page at a time.
  • Browse rows — horizontal Rail browse strips (Continue Watching, per-library rows) with their own cursor and scroll.
  • A–Z / letter jumps — moveTo() to an absolute offset, then page in whatever the visible window now covers.
  • Async posters — start with skeleton cells, then withItem() / withPoster() each tile as its render resolves.
  • Mouse-clickable grids — wire sugar-mouse to resolve cell:<index> clicks back to items.

Source & demos

Dependencies

  • SugarCore — I18n\Lang powers the localized notices and Util\Width measures every cell
  • SugarStyle — Layout::joinHorizontal*/joinVertical* stitches cells, rows, and rails together
  • SugarMouse — a hard require, but its use is opt-in: pass a Zones\Manager to render() and each cell is wrapped as zone id cell:<index>; without one nothing is marked
  • SugarImage — a typical (but not required) source of the pre-rendered poster bytes a PosterCard holds

Try the quickstart →

API

ClassMethodDescription
CardSizestatic new(int $width, int $height, int $hSpacing = 2, int $vSpacing = 1): selfOne clamped size value (width ≥ 4, height ≥ 1, gutters ≥ 0) accepted by PosterGrid::new/withCardSize, Rail::render/perRow/frameHeight and PosterCard::render alongside the int signatures
PosterGridstatic new(int|CardSize $cardWidth, ?int $posterHeight = null, int $hSpacing = 2, int $vSpacing = 1): selfA new empty grid with the given card geometry
PosterGridwithReset(int $total): selfBegin a fresh result set — drop cached cards, return the cursor to the top
PosterGridwithTotal(int $total): selfUpdate the known total without dropping cards, clamping the cursor
PosterGridwithItems(array $items): selfSplice a page of cards in at their absolute indices (new cards win)
PosterGridwithItem(int $index, PosterCard $card): selfSet/replace a single card by absolute index (e.g. an async poster)
PosterGridwithViewport(int $cols, int $rows): selfResize the rendered area, re-clamping scroll to keep the cursor visible
PosterGridleft/right/up/down(): selfMove the cursor one cell, clamped and kept on screen
PosterGridpageUp/pageDown(): selfMove the cursor one viewport of rows
PosterGridhome/end(): selfJump the cursor to the first / last item
PosterGridmoveTo(int $index): selfJump the cursor to an absolute index (e.g. an A–Z offset), clamped
PosterGridvisibleRange(int $overscanRows = 0): arrayThe inclusive [start, end] absolute-index window on screen — the need-range; [0, -1] when empty
PosterGridvisibleCards(int $overscanRows = 0): arrayThe loaded cards inside the window, keyed by absolute index — skeletons absent, order ascending
PosterGridindicesNeedingPoster(int $overscanRows = 0, ?callable $isFillable = null, ?callable $isCached = null): arrayWhich cells to queue an async poster for — the renderer-agnostic half of the fill loop; what counts as sourceable or already cached arrives as callbacks
PosterGridneedsFetch(?array $lastFetched, int $overscanRows = 0): boolWhether the visible window reaches past the range already fetched
PosterGridwithoutItemsOutside(array $range): selfDrop the art of cells outside the live window, so a long scroll does not hold every poster ever rendered
PosterGridcolumns/visibleRows/totalRows/cellHeight(): intDerived geometry of the current layout
PosterGridtotal/loadedCount/cursorIndex/cursorRow/scrollRow(): intCounts and cursor/scroll position accessors
PosterGriditem(int $index): ?PosterCardThe card at an absolute index, or null when not loaded
PosterGridcursorCard(): ?PosterCardThe card under the cursor, or null
PosterGridisEmpty(): boolWhether the grid has no items
PosterGridrender(bool $focused = true, ?SugarCraft\Mouse\Zones\Manager $zones = null): stringRender the visible rows; cursor shown only when focused; optional sugar-mouse cell marking; '' when the grid is empty
PosterGridpositionText(): stringThe grid's position readout — " (3/12)", or '' for an empty grid; the grid frame is deliberately chrome-free, so the composing screen places this string where it belongs
PosterGridfitsViewport(?int $cols = null, ?int $rows = null): boolWhether the cell geometry actually fits a viewport — columns() and visibleRows() floor at one, so a sub-cell viewport renders yet silently lies about what is visible; defaults to the grid's own current viewport
PosterGridstatic emptyMessage(): stringThe localized empty-grid notice (lang key grid.empty) — render() itself stays silent on an empty grid, so this is the seam for an owner-painted message; resolves live, honoring a mid-session locale switch
PosterGridstatic clearBoxCache(): intDrop the shared boxed-cell memo, returning how many entries were cleared — purely an optimization, never changes a single rendered byte
Rail__construct(string $title, array $cards = [], int $cursor = 0, int $scroll = 0)A horizontal browse strip of PosterCards with a title, cursor, and scroll offset; a stale pair is clamped, not restored verbatim
Railstatic new(string $title, array $cards = [], int $cursor = 0, int $scroll = 0): selfCanonical factory — mirrors the public constructor
RailwithCards(array $cards): selfReplace the card list, clamping cursor/scroll into range
RailwithCard(PosterCard $card): selfReplace a single card by id (e.g. when its poster finishes loading)
RailwithTitle(string $title): selfReturn a copy with a different title (immutable+fluent)
RailwithCursor(int $cursor): selfReturn a copy with a different cursor, clamped to [0, count-1]; scroll clamps to at most the cursor so the card stays visible
RailfocusedCard(): ?PosterCardThe card under the cursor, or null
RailisEmpty(): boolWhether the rail has no cards
RailmoveCursor(int $delta, int $perRow): selfMove the cursor by $delta, scrolling so it stays visible
Railstatic perRow(int $railWidth, int $cardWidth, int $spacing = 2): intHow many cards of $cardWidth fit in $railWidth at $spacing gap
RailframeHeight(int $posterHeight): intLines render() will emit — head, poster rows, title, plus a bar row when any loaded card carries progress (conservative upper bound)
Railrender(int $railWidth, bool $focused, int $cardWidth, int $posterHeight, int $spacing = 2): stringRender the title plus the visible slice of cards; the heading is control-stripped and both header lines clamped to $railWidth
PosterCard__construct(string $id, string $title, ?string $posterUrl = null, ?float $progress = null, ?string $poster = null, ?string $styledTitle = null, ?string $posterImage = null, ?int $imageId = null, bool $failed = false)One tile: poster area, title, optional progress bar, and the failed-fetch flag
PosterCardstatic new(string $id, string $title, ?string $posterUrl = null, ?float $progress = null, ?string $poster = null, ?string $styledTitle = null, ?string $posterImage = null, ?int $imageId = null, bool $failed = false): selfCanonical factory — mirrors the public constructor
PosterCardwithPoster(string $ansi): selfAttach the rendered ANSI poster (e.g. when an async render resolves) — emitted verbatim, the caller is the trust boundary
PosterCardwithSafePoster(string $ansi): selfAttach poster bytes through the AnsiGuard sweep row-by-row — colors and block glyphs stay byte-identical, every control sequence goes
PosterCardwithImage(string $bytes, int $id): selfAttach an overlay fill (sixel / kitty / iterm2): the card draws only the marker cell, the runtime paints the art over it
PosterCardwithStyledTitle(string $ansi, bool $assertSafe = false): selfA pre-styled title, emitted verbatim — ANSI-aware truncated with the same ellipsis the plain path shows — the caller is the trust boundary; $assertSafe guards the bytes first and throws on anything but SGR
PosterCardwithSafeStyledTitle(string $ansi): selfThe coercing setter: keep the SGR, drop every other escape — and keep the plain title when only styling and ASCII blank space survive (`trim` semantics; a non-breaking space is text)
PosterCardstatic assertSafeAnsi(string $ansi): stringReturn the styled title or throw — the same guard, standalone
PosterCardwithProgress(?float $progress): selfSet (or clear) the continue-watching progress bar — draws the exact (NN%) label when the row has room; a narrow row drops the label and its unfilled leg shares the skeleton's ░ glyph, so guaranteed readouts come from the host
PosterCardwithFailed(bool $failed = true): selfMark the cell's last fetch as failed (clear with withFailed(false)) — the cell falls back to the plain skeleton and hasPoster() reports it unfilled so a retry policy still re-queues it; attaching real art afterwards does NOT clear the flag, pass withFailed(false) alongside the fill
PosterCardisFailed(): boolWhether the last fetch for this cell failed
PosterCardhasPoster(): boolWhether art will actually paint here — inline text or a marker-addressed overlay
PosterCardrender(bool $focused, int $width, int $posterHeight): stringRender a fixed-$width block: poster (or placeholder) rows, a title row, and a progress row when set
PosterCardstatic clearFitCache(): intDrop the shared fitted-body memo, returning how many entries were cleared — purely an optimization, never changes a single output byte
AnsiGuardstatic assertSafe(string $ansi): stringReturn $ansi when it carries only SGR styling and printable text, else throw with the byte offset and hex of the offender
AnsiGuardstatic isSafe(string $ansi): boolThe same question without the exception
AnsiGuardstatic sanitize(string $ansi): stringDrop every non-SGR escape and control byte, keeping styling and text — color may be lost; a cursor move never will be
AnsiGuardstatic stripControls(string $text): stringDrop escapes and styling alike — what a plain, untrusted title is rendered through (card title and Rail heading)
AnsiGuardstatic stripSentinels(string $text): stringSurgically drop forged U+E000/U+E001 zone sentinels (delegates to sugar-core Sanitize::stripZoneSentinels()) — anything handed to a zone-marking Manager must pass this sweep first; legitimate U+E002-and-up image markers survive untouched
Langstatic t(string $key, array $params = []): stringi18n facade over the 16-locale lang/ family — three keys today: rail.empty (the Rail heading's empty-state line), card.failed (a PosterCard in the failed-fetch state) and grid.empty (the empty PosterGrid message)

Demos.

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

PosterGrid browsing rows

PosterGrid demo

The virtualized grid paged through a large library: cursor moves, skeleton cells resolving into posters as pages splice in, and the Rail strip following the focused row.