⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
tui-design
Design, mock up, build and review terminal UIs — full-screen TUIs, interactive CLIs and pickers, and plugin panels or popups inside a host (herdr, tmux, Neovim, k9s, lazygit). Use when designing, reviewing (from code, a live capture or a screenshot) or redesigning a TUI's layout, keybindings, states or colors, including requests that name a known TUI (lazygit, k9s, btop, yazi, helix, fzf); writing terminal mockups; building or fixing one in Ink, Textual, Bubble Tea, Ratatui or gum; mapping a col
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
// README
tui-design
An agent skill that designs, mocks, builds and audits terminal UIs with evidence instead of taste: full-screen apps, interactive CLIs and pickers, and plugin panels or popups inside a host (tmux, Neovim, k9s, lazygit, …).
Every sketch is a .mock frame on the real cell grid — linted at a declared size and rendered to PNG
before anyone sees it. Not for web or native GUIs, terminal-emulator themes, editor themes, or shell prompts.

Concept C of the worked example: a linted .mock at 120×30 and
256 colors, built with mockkit.py and scored on the visual-craft rubric.
Every design comes back as a self-contained HTML gallery: each frame in every state, size and theme, with keyboard navigation, side by side, and TXT / ANSI / SVG / PNG export. The reference frames are published at https://diegomarino.github.io/tui-design/.

What you get
| You ask for | You get |
|---|---|
| opinions on a TUI or screenshot | findings ordered by user harm, each with evidence and what it needs |
| a new screen or redesign | three concepts → linted frames × state × size → HTML gallery |
| code, a prototype, or a theme in a stack | a starter (Ink, Textual, Bubble Tea, Ratatui, gum) plus cell-level compare |
| a measured audit | live capture or screenshot → description → 135-check report |
| only colors | 44 tokens, contrast at truecolor and 16 colors, exporters |
Try it
- "Sketch a log viewer for our job runner at 80×24 and at a 60-column split."
- "Review this screenshot of my TUI. What would you change first?"
- "Map Gruvbox onto my Textual app's theme and check contrast at 16 colors."
Install
npx skills add diegomarino/tui-design # into the current project
npx skills add diegomarino/tui-design -g # for your user, all projects
npx skills add diegomarino/tui-design#v0.1.0 # pinned to a release
Or copy only skills/tui-design/ into .claude/skills/ or .agents/skills/ (~2.1 MB of references,
scripts, themes and starters). Scripts need Python 3.11+; PNG rendering needs rsvg-convert (librsvg).
Full requirements and more prompts: Getting started.
What it does
- Terminal-honest frames. Every sketch is a
.mockon the cell grid at a declared size, linted and rendered to PNG before review. Mockups → - A gallery to judge it. One HTML page per design, every frame in every chosen theme. Gallery →
- Host capability profiles. A plugin's design starts from what the host can draw: a test card (attributes,
16/256/24-bit color, glyph widths), a key probe, and a
#! caps:line on every frame. Host verification → - Audits that separate perception from judgment. A live capture or a screenshot pipeline (colors sampled from pixels, never guessed) produces a description, redraws it, diffs it against the source, then runs a 135-check list. Audit →
- Themes and contrast. 25 variants of 10 schemes on 44 semantic tokens, contrast checked at truecolor and 16 colors; exporters for Textual, Ink, Lip Gloss, Ratatui, gum and CSS. Themes →
- Five framework starters. Ink, Textual, Bubble Tea, Ratatui and gum render the same demo from a theme JSON, with a headless frame mode to compare a build with its mockup cell by cell. Starters →
- Design guidance with sources. Archetypes, keys and navigation, lifecycle (cleanup, suspend, editor handoff), the shell contract (exit codes, signals, pipes) and accessibility — drawn from k9s, lazygit, btop, yazi, helix and the frameworks' own docs.
Evidence
A/B on 24 cases × 4 models (skill vs baseline, same prompt and fixtures): +25 to +37 pass-rate points, at 2.5–4× cost per run (one repetition). Roughly half the gain is the skill's checked artifacts; the rest is behavior a baseline could have shown. What each run does, and the limits of that number: Evals.
Documentation
| Doc | Covers |
|---|---|
| Getting started | install, first prompts, branches |
| Concepts | frames, the cell grid, caps, perception vs judgment, tokens |
| Showcase: deploy console | worked example, three concepts |
| Features | mockups · gallery · host verification · audit · themes · starters |
| Evals | what was measured, the published scores, how to repeat a run |
| Architecture · CHANGELOG | scripts, tests, recipes for contributors |
Repository layout
skills/tui-design/ the skill (the only folder `npx skills add` installs)
docs/ documentation, generated images, the worked example
evals/ behavior and trigger evals, results and ledger
tests/ unit tests for the skill's scripts, the eval harness and the gallery page
tools/ check_public.sh, check_links.py, make_screenshots.py
.github/workflows/ pages.yml publishes the reference gallery
Contributing
See CONTRIBUTING.md and docs/contributing/architecture.md.
Every commit under skills/tui-design/ reaches users on their next npx skills update, so changes there land
finished.
Credits and license
Ideas adopted from gfargo/tui-design-skill, color values from each scheme's upstream project, and the rest of the third-party material are listed in CREDITS.md.
MIT © @diegomarino
// HOW IT'S BUILT
// FILES
184 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/tui-design/SKILL.md19 KBae3a778d9e34upstream ↗
--- name: tui-design description: Design, mock up, build and review terminal UIs — full-screen TUIs, interactive CLIs and pickers, and plugin panels or popups inside a host (herdr, tmux, Neovim, k9s, lazygit). Use when designing, reviewing (from code, a live capture or a screenshot) or redesigning a TUI's layout, keybindings, states or colors, including requests that name a known TUI (lazygit, k9s, btop, yazi, helix, fzf); writing terminal mockups; building or fixing one in Ink, Textual, Bubble Tea, Ratatui or gum; mapping a color scheme (Catppuccin, Dracula, Nord, Gruvbox, Tokyo Night, Rosé Pine…) onto a TUI's theme; fixing misaligned glyphs, flicker, NO_COLOR, exit codes, signals, pipes or a broken terminal after exit; suspend or $EDITOR handoff; or profiling a slow TUI. Not for web or native GUIs, terminal-emulator, editor or shell-prompt themes. license: MIT --- # tui-design Design, prototype, build and review terminal UIs with evidence instead of taste. Everything here is **terminal-honest**: a screen is a grid of cells, one font size, integer columns, colors and SGR attributes (bold, dim, italic, underline, inverse, strike), box-drawing for structure. A design that cannot be drawn in that grid — or that the host cannot draw — does not exist. `SKILL_DIR` is this skill's base directory; run every script as `SKILL_DIR/scripts/<name>` (Python ones with `python3`, or `uv run` when the script header says so). `--help` is the source of truth for flags. ## Before any branch: classify and frame 1. **Product shape** (`references/layout-archetypes.md#product-shapes`): full-screen session · inline picker (summon–choose–exit) · one-shot CLI · **plugin or popup inside a host**. The shape fixes the output contract and who owns the screen, keys and styling. For an inline picker, a one-shot CLI or any app that can run in a pipe or script, the shell boundary (exit codes, Ctrl-C and SIGPIPE, which stream gets what, `--json`, cd on exit) is part of the design: `references/cli-contract.md`. 2. **Constraints that change the advice.** Ask before recommending when unknown: the host's or framework's **capability profile** (widgets, attributes such as italic, color depth, glyph level, reserved keys), the stack and where the code is, the usual terminal size, the theme, and what may change vs what must stay. Read the code when you have it. **Measure the host.** The profile is what the host can draw, not what the current code uses: a plugin drawing 8 curses colors today may run in a truecolor pane. For a plugin or popup inside a host, put this in the same message as your other questions: "run `python3 SKILL_DIR/scripts/test_card.py` inside the host (`--curses` if the app uses curses) and send me a screenshot" (it shows attributes, 16/256/24-bit color, fills and glyph widths; compare it with `assets/test-card/*--reference.png`). Record the result as the `#! caps:` line every mock carries, with `source=test-card` (or `docs` when the host documents it); until the screenshot arrives write `source=assumed`, which `--check` keeps warning about (`references/formats.md#capability-profile`). 3. **What already works.** Inventory the current UI's good decisions (alignment, striping, freshness cues…) and keep them unless you drop one on purpose and say so. ## Working rules (every branch) - **Tokens, never raw colors.** Every color is a semantic token (`fg.muted`, `border.focus`, `status.error`…) from `references/themes/_tokens.json`, resolved by a theme. Mockups reject hex. - **Single-width glyphs within the caps.** Use the safe set in `references/visual-vocabulary.md#v1-width-hazards-and-the-glyph-linter-policy`; emoji and East-Asian-wide glyphs shift columns. `render_mockup.py --check` enforces this and the `#! caps:` profile. - **States × sizes.** Every screen exists in the required states and sizes of `references/formats.md#frame-naming`, with a too-small message below its minimum size. - **Glyph + color.** Status is a glyph and a color (`✓` success, `▲` warning, `✗` error); color alone carries nothing, and a status marker never contradicts its content. - **Hints in the footer.** Key hints live in the footer (`key verb key verb`, context left, global right); only a modal or a which-key popup shows its own hints; `?` opens full help. - **Any sketch shown to the user is a frame.** Build it with `mockkit.py` or pass it through `render_mockup.py --check` at a declared size — hand-typed box sketches drift off the grid. Text tables in chat must keep exact column widths too. - **Render and look.** Before showing any frame, render it to PNG and inspect the image with this host's image tool (the Host tools table in `references/audit-protocol.md`). A frame you have not looked at is unverified. - **Real data.** Fill frames from a real source: a snapshot or fixture in the repo, the user's screenshot, their examples. A value you invent is drawn in `fg.faint`, listed in a `#! note:` and named as invented in your answer; never present invented content as a finding. - **Plain words for the user.** Never show internal labels (branch letters, check ids without their meaning); say "live capture" or "from the screenshot". Put assumptions in `#! note:` lines or the design doc, never as text inside the UI. - **Artifacts stay in a working directory** (scratch or the current project), with the generator script next to the frames. Read the input and reference files that already exist before building, keep them as they are unless the task asks to change them, and put test or sample data in new files. Ask before writing into another repository the user names. - **Read references by section.** Open the reference's **Sections** list (its first lines) and read only the line range of the section the step needs: `sed -n 'START,ENDp' FILE`, or the Read tool with offset=START, limit=END−START+1. Never read a whole reference, or the skill tree. - **Private tmux only.** Any tmux you start (tests, captures, a host to try a plugin in) runs as `tmux -L <name>`; never run `tmux kill-server` without `-L`: the default server is the user's. - **Slow startup.** When the user asks to profile a slow TUI or to shorten time to the first frame, read the startup column in `references/frameworks/choosing.md`. Those are measured startup times for the five frameworks. This skill has no profiler. - **Gaps in this skill** found while working: tell the user; do not edit the installed copy. ## Pick the branch | The user wants… | Branch | |---|---| | opinions or advice on a TUI or screenshot ("how would you improve it?", "is this useful?") | **C0. Quick review** | | a new TUI, a redesign, a screen layout, mockups | **A. Design** | | code in a framework, a prototype that runs, a theme applied in code, a rendering bug fixed | **B. Build** (after A, or from an agreed design) | | a measured, evidence-backed audit of a running app or a screenshot | **C. Audit** | | only colors: choose a scheme, map tokens, check contrast, export a theme | **D. Color** | Branches chain: C0 → A → B → C (audit the result) is the full loop. Structural problems found in C0 go to A (mock the redesign) before any full audit. ## C0. Quick review 1. **Read** `references/audit-quick.md` (§0, the quick-review core) and the archetype file in `references/archetypes/` (chooser: `references/layout-archetypes.md#1-choose-an-archetype`) or the section of `references/interaction.md` that matches the screen. Done when you can name the archetype and the §0 items that apply. 2. **Frame**: product shape and constraints (above). For a plugin or an unknown stack, ask for the capability profile (for a plugin, the test-card screenshot) before recommending anything that needs it. 3. **Apply §0 and the two reflexes**: the countable clutter audit and the floor test (80×24 and a 60-column split). For a capture or a `.mock`, `ansi_grid.py --clutter` counts the clutter. 4. **Answer**: recommendation first; findings ordered by user harm (`references/audit-quick.md#order-findings-by-user-harm`), **one line each in this shape**: `- **<change>** — <evidence>. Needs: <what the host or terminal must provide, or "nothing new">` (e.g. `Needs: italic`, `Needs: a second pane`, `Needs: nothing new`); what to keep; open questions. Offer mockups (branch A) for structural changes and a full audit (C) when the user wants a measured report. Done when every applicable §0 item is pass, fail or n/a and every recommendation names its requirement. ## A. Design 1. **Frame the task.** Copy `references/templates/design-system.md` into the working directory; it is filled progressively by steps 1, 3, 5 and 7. Fill its §0 Brief (main job per screen, data shown, sizes, product shape, capability profile, what may change, what to keep). Done when each item has a concrete value, or is listed under Assumptions for the user to confirm. 2. **Diverge, then choose.** Reframe the user's job before restyling the current screen: sketch **3 genuinely different concepts** as one `normal` frame each (e.g. a queue/inbox, a map, a spotlight/palette, a dashboard of counts with drill-down — see `references/visual-craft.md#ambition-reframe-before-restyling` and the archetypes in `references/layout-archetypes.md#1-choose-an-archetype`), render and look at them, and compare them against the job. Pick one (or merge) with the user when the choice is theirs. Done when the chosen concept names its exemplar app (`references/exemplars.md#8-archetype-catalog-other-tuis`), its focus order, and why it beats the other two. 3. **Set interaction.** Keys, navigation model, help, confirmations, search from `references/interaction.md` (§1–§5); write them into the design system's §4 keymap. Check each key against `references/interaction.md#key-availability` (macOS F-keys and Option, the host's prefix and bindings); for a plugin, ask the user to run `SKILL_DIR/scripts/key_probe.py` with the footer's keys inside the host. Done when every action has a key that reaches the app, and §4 has the footer hint list for each screen, mode and overlay. 4. **Mock every state and size** with `mockkit.py` (widget helpers, archetype recipes and the states × sizes `matrix()`: `references/mockkit.md`; exact signatures: `references/mockkit-api.md`; format: `references/formats.md#mockup-format`; start from the nearest file in `assets/mockups/<archetype>/` or the demo `assets/demo/fleet--normal--80x24.mock`), named `<variant>--<state>--<cols>x<rows>.mock`, each with the `#! caps:` line. Done when every required state × size exists and `render_mockup.py FILE --check` reports 0 errors for each, and the `#! caps:` line says `source=test-card` or `docs` (or the user declined the test card and your answer says the profile is assumed). For a plugin inside a host, also draw the chosen frame there with `python3 SKILL_DIR/scripts/play_mock.py FRAME.mock` (`d` toggles 256 ↔ 16 colors) and get a screenshot before building. 5. **Pick the theme.** Choose a scheme from `references/color-schemes.md#how-to-choose` (default: one that passes every floor in both depths, e.g. `catppuccin-mocha`); confirm token roles in `references/color-tokens.md#the-44-tokens`. Done when `contrast_check.py ID` and `contrast_check.py ID --depth 16` both exit 0, or each failure is recorded in the design system. 6. **Craft pass.** Open `references/visual-craft.md#aesthetic-rubric` and score each key frame's PNG on C1 composition, C2 hierarchy, C3 color budget, C4 structure economy, C5 selection, C6 state at a glance, C7 typography, C8 signature (0–2 each, definitions there), at the caps depth and at 16 colors, into the design system's §10 table. Fix what scores below 2 when a cheap change lifts it, then re-score. Done when every key frame scores ≥ 12/16 with no 0 at both depths, and `render_mockup.py FILE --check` shows no `craft CRn` warning, or each one is waived with `#! note: craft-ok CRn <reason>`. 7. **Finish the design system.** Fill the remaining sections; take the 16-color column from `preview_theme.py ID --depth 16`. Done when no `{{` placeholder remains and unused rows are deleted. 8. **Show it.** Build a gallery (`gallery.py DIR… --themes a,b -o gallery.html`; each frame exports as TXT/ANSI/SVG/PNG), render key frames to PNG (`render_mockup.py FILE --theme ID -o f.ansi`, then `ansi_render.py f.ansi --theme ID --format png -o f.png`), look at them, and self-review with `references/audit-quick.md` (§0). List every behavior the mockups invent as an open decision. Done when every key frame PNG has been read, checklist failures are fixed or listed, open decisions are listed, and the user has the gallery path. Offer to publish the gallery when the user should judge visuals and your environment can publish pages. ## B. Build 1. **Choose the framework** with `references/frameworks/choosing.md#3-pick-x-when` unless the user fixed it, then read that framework's file in `references/frameworks/` (versions, layout API, pitfalls, one-frame capture recipe) and `references/lifecycle.md` (terminal cleanup, suspend, test pyramid). Bubble Tea code on the web is mostly v1; the v2 notes there are mandatory. Done when the framework and its pinned versions are written down. 2. **Start from the proto-starter** in `assets/proto-starters/<framework>/` (renders the Fleet demo, reads a flat theme JSON, has `--frame --cols --rows --theme --depth` and `capture.sh`). Copy it into the project and keep the frame mode. Done when the copy renders a frame at 80×24. 3. **Apply the theme.** Generate the starter's flat theme with `export_theme.py ID --target json -o theme.json`, and framework theme code with `--target textual|ink|lipgloss|ratatui|gum|css`. Name every style after its token; translate design terms with `references/vocabulary.md#2-master-table`. Done when no color literal remains outside the generated theme. 4. **Capture and compare.** For each state × size: frame mode (or `capture_tui.sh -s 80x24 -s 120x30 -o OUT -- CMD` for a running app), then `compare.py design.mock frame.ansi -o cmp.html`. Done when every difference from the mockup is fixed or listed with its framework reason (the starters' READMEs list known ones). 5. **Audit your own frames** with branch C, the live-capture path. Done when the audit report has no blocker. ## C. Audit Follow `references/audit-protocol.md` exactly; it is the procedure, with the commands. Perception is separate from judgment: - **Live capture (the app runs):** `capture_tui.sh` → `ansi_grid.py --describe` gives an exact description; a describer only labels roles and states. - **Screenshot (image only):** `prep_screenshot.py` → `describe_prompt.py` builds each prompt → a vision subagent per prompt (pass 1 layout, pass 2 per leaf region; prompt text in `references/prompts/describe-tui.md`) → `sample_colors.py` (colors come from pixels, never from the model) → `merge_description.py`. - **Fidelity:** `description_to_mock.py` → render → `compare.py` against the source; iterate at most twice. - **Judge:** apply every check in `references/audit-checklist.md` to the validated description, citing region/element ids as evidence; write the report with `references/templates/audit-report.md`. Done when every check is pass, fail (with evidence) or n/a (with reason), and each unverifiable check has had one targeted re-description; any still unverifiable are listed in the report. ## D. Color 1. **Pick** a scheme in `references/color-schemes.md#how-to-choose` (per-scheme detail in `references/schemes/`), with roles from `references/color-tokens.md`; preview with `preview_theme.py ID`. 2. **Check** with `contrast_check.py ID` and `--depth 16`. 3. **Export** with `export_theme.py ID --target …`. A new theme follows `references/themes/catppuccin-mocha.json` and `references/formats.md#theme-json`, with a `provenance` entry per token. Done when both depths pass, or every failure is noted in the theme's `notes` and told to the user. ## Reference map | File | Reach for it when | |---|---| | `references/layout-archetypes.md` | product shapes, choosing/reviewing screen structure, breakpoints, states, too-small screens, tables and zebra striping; one file per archetype in `references/archetypes/` (incl. chat / agent sessions, forms and settings) | | `references/interaction.md` | keys, navigation, help, confirmations, search, mouse, feedback timing, long waits, timeouts and stale data | | `references/exemplars.md` | evidence from k9s, lazygit, lazydocker, gitui, yazi, btop, helix; screenshot corpus | | `references/vocabulary.md` | translating a generic element (panel, list, tabs…) to a framework's name, or back | | `references/frameworks/*.md` | building in Ink, Textual, Bubble Tea, Ratatui or gum; `choosing.md` to pick one (incl. startup time to first frame) | | `references/lifecycle.md` | terminal cleanup on every exit, suspend/editor handoff, resize, non-blocking I/O, test pyramid | | `references/cli-contract.md` | where the app meets the shell: exit codes (0/1/2/130/143), signals and `app \| head`, TTY checks on stdin and stdout, progress and paging, `--json`/NDJSON, error messages, cd on exit and `init` scripts; `SH-` checks | | `references/visual-craft.md` | making it look good and ambitious: composition, hierarchy, color budget, signature elements, the aesthetic rubric and README test, reframing into 3 concepts, with a worked example | | `references/color-tokens.md` | token roles, selection and focus styles, mapping tokens to app theme keys | | `references/color-schemes.md`, `schemes/` | picking a scheme, a token's hex in a scheme, which schemes pass contrast | | `references/terminal-capabilities.md` | color depth, NO_COLOR, dark/light detection, tmux, resize | | `references/terminal-escapes.md` | emitting raw escape sequences, building without a framework, per-terminal feature support | | `references/visual-vocabulary.md` | borders, bars, spinners, status glyphs, width hazards, icon levels and Nerd Fonts | | `references/glyph-data.md` | raw glyph data: full box-drawing chart, wide-char lists, braille bit math, spinner frames, Nerd Font ranges | | `references/accessibility.md` | color-vision deficiency, screen readers, plain mode, reduced motion | | `references/tools.md` | which script does what, when to use it, its key flags; the HTML gallery (keys, export, viewing it locally) | | `references/mockkit.md` | building frames in Python: quick start, which helper for which need (panel, table, listing, tree, keybar, overlay, toosmall), recipes per archetype, `matrix()` for every state × size | | `references/mockkit-api.md` | the exact signature of a mockkit class, method or helper (instead of reading `mockkit.py`) | | `references/formats.md` | `.mock` markup and `#! caps:` profile, theme JSON, 16-color specs, contrast floor values, frame naming and required states, vocabulary ids | | `references/audit-quick.md` | §0 for any quick review or self-review, and the order of findings | | `references/audit-checklist.md` | the full check list for an audit | | `references/audit-protocol.md`, `prompts/describe-tui.md` | a full audit (live capture or screenshot pipeline) | | `references/templates/` | design-system and audit-report documents | | `references/schemas/tui-description.schema.json` | do not read; validate with `merge_description.py --validate`; field meanings are in `prompts/describe-tui.md` |skills/tui-design/assets/proto-starters/bubbletea/README.md5.8 KB319191158ce0upstream ↗
# Fleet — Bubble Tea v2 starter The canonical "Fleet" demo screen (`../../demo/fleet--normal--80x24.mock`) in Bubble Tea v2 + Lip Gloss v2: header band with tabs, focused list, detail panel with severity gauges, message line, key-hint bar. Adapts to any size >= 80x24 (list 32 cols fixed, detail flexible); below that it shows a centered "Terminal too small — need 80×24, have C×R". Verified against the mock (`../../demo/fleet--normal--80x24.mock`): at 80x24 truecolor the frame is cell-for-cell identical (characters, fg/bg, bold) across 7 themes, and `--depth 16` matches `render_mockup.py --depth 16` (0 differing cells for catppuccin-mocha and everforest-dark). There is no 120x30 mock: at 120x30 Bubble Tea and Ratatui render identical frames to each other (0 differing cells); Ink and Textual widen the gauges with the detail pane. `--depth 256` uses this framework's own quantizer, so it differs from the mock's 256-color rounding. Pinned (verified 2026-10-01): Go >= 1.26 (tested 1.27.1), `charm.land/bubbletea/v2` v2.0.10, `charm.land/lipgloss/v2` v2.0.6, `github.com/charmbracelet/colorprofile` v0.4.3. `go.sum` is included (pins the tree). Import paths are the v2 vanity domain; most online Bubble Tea code is v1 (`github.com/charmbracelet/...`, `View() string`). ## Copy it into your project ```sh export SKILL_DIR=/path/to/tui-design # the skill directory (SKILL.md lives there) cp -R "$SKILL_DIR/assets/proto-starters/bubbletea" ./fleet-ui && cd ./fleet-ui python3 "$SKILL_DIR/scripts/export_theme.py" catppuccin-mocha --target json -o theme.json # any theme ID go run . --frame --cols 80 --rows 24 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # frames at 80x24 and 120x30; or ./capture.sh theme.json out/ ``` `capture.sh` finds the skill through `SKILL_DIR` first, then through `../../..` (the starter still inside the skill), and stops with an error naming `SKILL_DIR` if neither works. It only needs the skill to turn a theme ID into JSON: with a JSON path (`./capture.sh theme.json out/`), no `SKILL_DIR` is needed. `theme.json` here is a flat theme JSON (`{id, tokens, ansi16, ...}`); keep the frame mode (`--frame --cols --rows --theme --depth`) in the copy, it is how the design is audited. ## Run ```sh go run . # interactive (alt screen): up/down or j/k select, tab switches pane focus, r restart message, q quits go run . --theme theme.json # a flat theme JSON path (the binary does not take theme IDs; capture.sh does) go build -o fleet . && ./fleet ``` `enter`, `/`, `?` and the tabs 2/3 are drawn (they are part of the demo screen) but not wired. ## One static frame (for gallery / compare / audit) ```sh go run . --frame --cols 120 --rows 30 --theme theme.json --depth truecolor > fleet.ansi # exactly --rows lines ./capture.sh catppuccin-mocha out/ # builds in a temp dir; writes out/bubbletea--normal--80x24.ansi and ...120x30.ansi DEPTH=16 ./capture.sh catppuccin-latte out/ ``` Frame recipe: `m.Update(tea.WindowSizeMsg{...})`, take `m.View().Content` (Lip Gloss v2 `Render()` always emits truecolor), write it through a `colorprofile.Writer{Profile: TrueColor|ANSI256|ANSI}`. `Init()` Cmds are not run, so the frame is the time-zero state. `--selected N` and `--focus-detail` pick another state. ## Theme tokens -> Lip Gloss `theme.json` = `python3 "$SKILL_DIR/scripts/export_theme.py" ID --target json -o theme.json` (embedded default: catppuccin-mocha; `export_theme.py --target lipgloss` emits a ready-made `theme` package of colors if you prefer compile-time constants). `theme.go`: `LoadTheme` (go:embed or file) -> `NewStyles(theme, ansi16)` returns a `Styles` struct, one lipgloss style per UI role (the Bubble Tea convention: there is no theme object in Lip Gloss). View code only touches `Styles`. | UI role | token(s) | |---|---| | header band / app name / tabs | `statusbar.bg`+`statusbar.fg`, `accent.primary` bold, `tab.active.fg` on `tab.active.bg`, `tab.inactive.fg`, `border.default` | | focused / unfocused pane border | `border.focus` / `border.default`; titles `fg.title` bold | | selected row, cursor | `selection.bg` (`selection.inactive.bg` when the list is unfocused), `selection.fg`, `accent.primary` | | status glyphs and words | `status.success/warning/error`, `fg.faint` (stopped), `fg.muted` (running, unselected) | | gauges | `ramp.low` (< 50 %), `ramp.mid` (< 80 %), `ramp.high`, empty `fg.faint` | | footer | `statusbar.*`, `keyhint.key` bold, `keyhint.desc` | Every style paints `bg.base` explicitly, so the frame does not depend on the terminal background. 16-color mode (`--depth 16`): `NewStyles(.., true)` builds styles from the theme's per-token `ansi16` specs (`"4 bold"`, `"default dim"`, `"reverse"`), i.e. the terminal's own palette, not `colorprofile`'s nearest-color guess. When `selection.bg` is `reverse`, the selected row is inverted per segment (each segment keeps its own fg spec and bold, like `render_mockup.py --depth 16`); the unfocused row follows `selection.inactive.bg` (no fill in those themes, only the name is bold). A `bg` fg spec (e.g. `tab.active.fg` in everforest-dark) is drawn as the fill token's slot as foreground + reverse, so the text takes the terminal background color on the fill (`resolver.fgOn`). ## Caveats - Lip Gloss v2 sizing: `Width` is the outer width (border and padding included); `Height` is a minimum (wrapping content grows the block). Rows are therefore padded by hand and the root is clipped with `MaxWidth/MaxHeight`. - Lip Gloss has no border titles: the top edge is drawn by hand and the pane uses `BorderTop(false)`. - Gauges are plain `█`/`░` runs (a `progress` Bubble would add animation, not fidelity). - `View.BackgroundColor` is set so the terminal default background matches `bg.base` while the app runs. - `go mod tidy` needs network only if you change dependencies; first build downloads the modules.skills/tui-design/assets/proto-starters/gum/README.md6.1 KBb589ad0e3c21upstream ↗
# Fleet — gum starter (and what gum cannot do) gum (Charm, v2.0.1 verified 2026-10-01) is a set of shell-callable styling and prompt commands. It **cannot build a persistent multi-pane app**: there is no event loop, no focus, no layout engine, no screen that stays up between commands. Every `gum` call is a separate process that prints once (`style`, `join`, `format`, `table`) or runs one modal prompt and exits (`choose`, `filter`, `input`, `confirm`, `spin`, `pager`). So the lesson of this starter is the split below, not a clone of the Ratatui/Bubble Tea apps. | gum can | gum cannot | |---|---| | Style text: fg/bg, bold/faint/italic/underline/strike, borders (4 styles), padding, margin, fixed width/height, align | Pane focus, a selection that survives between calls, `tab` between panes, live updates | | Compose static layouts: `gum join --horizontal/--vertical` (what `fleet-static.sh` does) | Border titles, per-side borders, reverse video (`style` has no flag), vertical centering | | One interaction at a time: `choose` / `filter` / `confirm` / `input` / `write` / `spin` / `pager` / `table` (select a row) | Redraw on resize or keep key hints on screen; any "?" help overlay or modal | | Theme prompts through `GUM_*` env vars (`lib.sh` `gum_env`) | Theme `style` output through env: each `style` call takes explicit `--foreground/--background` | Use gum for a script's prompts and a one-shot summary. If the user wants "a screen that stays up" (lists, tabs, panes, live data), pick Bubble Tea (`../bubbletea`) or Ratatui (`../ratatui`) (gum itself is a thin CLI over those libraries). ## Files - `fleet-static.sh`: ONE static Fleet frame from `gum style` + `gum join` (header band, two bordered boxes side by side, message line, footer hints); ~100 `gum` spawns, about 4 s at 80x24 (each styled span is a process). - `fleet-flow.sh`: the idiomatic gum flow for the same domain: `gum choose` a service -> `gum confirm` the restart -> `gum spin` -> a styled result line. - `lib.sh`: loads the flat theme JSON with `jq` into `T_<token>`/`A_<token>` variables; `S "fg=TOKEN bg=TOKEN bold" text` is one styled span; `gum_env` exports `GUM_CHOOSE_*`, `GUM_CONFIRM_*`, `GUM_SPIN_*` from the tokens. - `theme.json` (default catppuccin-mocha), `capture.sh`. Needs `gum` and `jq`; bash 3.2 (macOS /bin/bash) is enough. Pinned (verified): gum 2.0.1, jq 1.8.2, tmux >= 3.2 for the interactive capture. No Go/Rust needed; no manifest. ## Copy it into your project ```sh export SKILL_DIR=/path/to/tui-design # the skill directory (SKILL.md lives there) cp -R "$SKILL_DIR/assets/proto-starters/gum" ./fleet-ui && cd ./fleet-ui python3 "$SKILL_DIR/scripts/export_theme.py" catppuccin-mocha --target json -o theme.json # any theme ID ./fleet-static.sh --cols 80 --rows 24 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # frames at 80x24 and 120x30 (+ the tmux flow); or ./capture.sh theme.json out/ ``` `capture.sh` finds the skill through `SKILL_DIR` first, then through `../../..` (the starter still inside the skill), and stops with an error naming `SKILL_DIR` if neither works; it only needs the skill to turn a theme ID into JSON (with a JSON path no `SKILL_DIR` is needed). `fleet-static.sh`, `fleet-flow.sh` and `lib.sh` read only the JSON file. ## Run ```sh ./fleet-flow.sh # interactive: choose -> confirm -> spin (themed from theme.json) ./fleet-static.sh # the static Fleet screen at 80x24 on stdout ./fleet-static.sh --cols 120 --rows 30 --theme theme.json --depth 256 > fleet.ansi # a frame (exactly --rows lines) ./capture.sh catppuccin-mocha out/ # out/gum--normal--80x24.ansi, gum--normal--120x30.ansi, gum-flow--choose--80x24.ansi DEPTH=16 ./capture.sh catppuccin-latte out/ ``` Static output frame capture: `CLICOLOR_FORCE=1 COLORTERM=truecolor` (set by `load_theme`): gum's colorprofile writer would strip color when piped otherwise (`NO_COLOR` is ignored when `CLICOLOR_FORCE` is set and the output is piped). Interactive capture (`capture.sh`): a private `tmux -L gumcap$$` server runs `fleet-flow.sh`, sends `Down`, and writes `capture-pane -p -e`; only that socket is killed. Render it with `ansi_render.py ... --cols 80 --rows 24` (tmux trims trailing blanks). ## Theme tokens -> gum `theme.json` = `python3 "$SKILL_DIR/scripts/export_theme.py" ID --target json -o theme.json`. - Spans: `gum style --foreground '#hex' --background '#hex' [--bold|--faint]`; every span carries `bg.base` so the frame is self-painted. - Prompts: `GUM_CHOOSE_CURSOR_FOREGROUND=accent.primary`, `..._SELECTED_FOREGROUND=status.success`, `GUM_CONFIRM_SELECTED_BACKGROUND=accent.primary` on `fg.on-accent`, `GUM_SPIN_SPINNER_FOREGROUND=accent.primary` (same as `export_theme.py --target gum`). - Boxes: `--border rounded --border-foreground border.focus|border.default`; `gum join` glues them; `fg.title bold` titles, gauges `ramp.low/mid/high`. - `--depth 256` is gum's own downsampling (no `COLORTERM`); `--depth 16` uses the theme's per-token `ansi16` specs as numeric colors. `gum style` has no reverse flag, so `S` (`lib.sh`) wraps the span in SGR 7 ... SGR 0: that gives `reverse` fills (per segment, keeping the fg spec) and the `bg` fg spec (the fill's slot as foreground + reverse, i.e. text in the terminal background color on the fill, e.g. the active tab in everforest-dark). ## Fidelity vs the mock (80x24, catppuccin-mocha: 170 of 1920 cells differ, all from the limits above) - Pane titles are content lines inside the boxes ("Services (6)", "api-gateway"), because gum borders carry no title. The list rows therefore start one row lower than in the mock. - Detail pane is fixed to api-gateway (no `--selected`); there is no selected state, focus or tab handling. - Selected row uses the background token; at `--depth 16` "reverse" is real SGR 7 per segment (see above), so this row's colors match the mock; the differing cells at 16 colors are the same layout cells as at truecolor (170 for catppuccin-mocha and everforest-dark). - `gum style --width/--height` are outer sizes including the border (verified); `--height` pads but never clips, so `fleet-static.sh` pipes through `head -n $rows`.skills/tui-design/assets/proto-starters/ink/README.md4.4 KB923720852146upstream ↗
# Fleet — Ink starter The canonical "Fleet" demo screen (`../../demo/fleet--normal--80x24.mock`) in Ink: header band with tabs, focused list, detail panel with severity gauges, message line, key-hint bar. Adapts to any size >= 80x24; below that it shows a centered "Terminal too small — need 80×24, have C×R". Verified against the mock: at 80x24 truecolor the frame is cell-for-cell identical (characters, fg/bg, bold) across 7 themes, and `--depth 16` matches `render_mockup.py --depth 16` (0 differing cells for catppuccin-mocha and everforest-dark). There is no 120x30 mock: at 120x30 the Ink gauges widen with the detail pane (up to 60 cells), so Ink differs from Bubble Tea/Ratatui (40-cell gauges) in 92 cells and matches Textual. `--depth 256` uses chalk's quantizer, so it differs from the mock's 256-color rounding. Pinned (verified 2026-10-01): Node >= 22 (tested 26.9), `ink` 7.1.1, `react` 19.3.0, `chalk` 5.6.2, `tsx` 4.23.15. ## Copy it into your project ```sh export SKILL_DIR=/path/to/tui-design # the skill directory (SKILL.md lives there) cp -R "$SKILL_DIR/assets/proto-starters/ink" ./fleet-ui && cd ./fleet-ui npm install # local only; no global installs python3 "$SKILL_DIR/scripts/export_theme.py" catppuccin-mocha --target json -o theme.json # any theme ID npx tsx src/cli.tsx --frame --cols 80 --rows 24 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # frames at 80x24 and 120x30; or ./capture.sh theme.json out/ ``` `--theme` takes a flat theme JSON path or a theme ID (an ID is exported through `$SKILL_DIR/scripts/export_theme.py`, so it needs `SKILL_DIR`, or the starter still inside the skill). `capture.sh` resolves the skill the same way (`SKILL_DIR` first, then `../../..`) and stops with an error naming `SKILL_DIR` if neither works; with a JSON path no skill is needed. Keep the frame mode in the copy. ## Install and run ```sh npm install # local only; no global installs npm start # interactive: up/down (or j/k) select, tab switches pane focus, q quits npx tsx src/cli.tsx --theme theme.json --depth 256 # --theme (JSON path or theme ID)/--depth work in interactive mode too ``` ## One static frame (for gallery / compare / audit) ```sh npx tsx src/cli.tsx --frame --cols 120 --rows 30 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # writes out/ink--normal--80x24.ansi and out/ink--normal--120x30.ansi DEPTH=16 ./capture.sh catppuccin-latte out/ ``` Frame recipe: `render()` into a fake non-TTY stdout that reports `columns`/`rows` (so `useWindowSize()` works), with a fake stdin claiming raw-mode support, `debug: true`; read the last frame before unmount, pad to exactly `rows` lines. `renderToString` is not used because `useWindowSize` does not see its `columns`. ## Theme tokens -> Ink `theme.json` = `python3 "$SKILL_DIR/scripts/export_theme.py" ID --target json -o theme.json` (default is catppuccin-mocha). `src/theme.ts` `createTheme(json, depth)` returns `{color(token), text(token, {on, bold, dim})}`: - `<Text {...t.text('fg.muted')}>`, `<Text {...t.text('keyhint.key', {on: 'statusbar.bg', bold: true})}>` - `<Box borderColor={t.color('border.focus')} backgroundColor={t.color('statusbar.bg')}>` - depth `truecolor`/`256`: hex strings; `chalk.level` (3/2) does the down-sampling. - depth `16`: the theme's `ansi16` map (`"4 bold"`, `"default dim"`, `"reverse"`) becomes named colors/`dimColor`/`inverse` (chalk level 1), so the terminal's own palette is used. Matches `render_mockup.py --depth 16`; a `bg` fg spec (e.g. `tab.active.fg` in everforest-dark) becomes the fill token's slot as `color` + `inverse`, so the text takes the terminal background color on the fill. ## Caveats - Ink has no border titles: `Pane` draws the top edge as a `<Text>` line and the box below sets `borderTop={false}`. - Ink has no theme system; tokens are plain props, so changing theme means re-creating the theme object. - `bg.base` is not painted: the terminal's own background shows through (correct on a themed terminal; a PNG renderer needs `--theme` to paint it). Textual paints it. - Gauge bars scale with width (`detailW - 28`, max 60); 20 cells at 80 columns like the mock. - Frame mode is non-interactive (`isTTY=false`): no effects/timers/input are exercised. - Selected-row `reverse` at depth 16 comes out as inverse video per segment, same as the mock renderer.skills/tui-design/assets/proto-starters/ratatui/README.md5.8 KBf581be6a6886upstream ↗
# Fleet — Ratatui starter The canonical "Fleet" demo screen (`../../demo/fleet--normal--80x24.mock`) in Ratatui 0.30: header band with tabs, focused list, detail panel with severity gauges, message line, key-hint bar. Adapts to any size >= 80x24 (list 32 cols fixed, detail flexible); below that it shows a centered "Terminal too small — need 80×24, have C×R". Verified against the mock (`../../demo/fleet--normal--80x24.mock`): at 80x24 truecolor the frame is cell-for-cell identical (characters, fg/bg, bold) across 7 themes, and `--depth 16` matches `render_mockup.py --depth 16` (0 differing cells for catppuccin-mocha and everforest-dark). There is no 120x30 mock: at 120x30 Bubble Tea and Ratatui render identical frames to each other (0 differing cells); Ink and Textual widen the gauges with the detail pane. `--depth 256` uses this framework's own quantizer, so it differs from the mock's 256-color rounding. Pinned (verified 2026-10-01): Rust >= 1.88 (edition 2024; tested 1.98.1), `ratatui` 0.30.2 (re-exports crossterm 0.29), `serde` 1.0 + `serde_json` 1.0 (theme JSON). `Cargo.lock` is not shipped; cargo generates it. ## Copy it into your project ```sh export SKILL_DIR=/path/to/tui-design # the skill directory (SKILL.md lives there) cp -R "$SKILL_DIR/assets/proto-starters/ratatui" ./fleet-ui && cd ./fleet-ui python3 "$SKILL_DIR/scripts/export_theme.py" catppuccin-mocha --target json -o theme.json # any theme ID cargo run -q -- --frame --cols 80 --rows 24 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # frames at 80x24 and 120x30; or ./capture.sh theme.json out/ ``` `capture.sh` finds the skill through `SKILL_DIR` first, then through `../../..` (the starter still inside the skill), and stops with an error naming `SKILL_DIR` if neither works. It only needs the skill to turn a theme ID into JSON: with a JSON path (`./capture.sh theme.json out/`), no `SKILL_DIR` is needed. `theme.json` here is a flat theme JSON (`{id, tokens, ansi16, ...}`); keep the frame mode (`--frame --cols --rows --theme --depth`) in the copy, it is how the design is audited. ## Run ```sh cargo run # interactive (alt screen): up/down or j/k select, tab switches pane focus, r restart message, q quits cargo run -- --theme theme.json # a flat theme JSON path (the binary does not take theme IDs; capture.sh does) cargo build --release && target/release/fleet ``` `enter`, `/`, `?` and the tabs 2/3 are drawn (part of the demo screen) but not wired. ## One static frame (for gallery / compare / audit) ```sh cargo run -q -- --frame --cols 120 --rows 30 --theme theme.json --depth truecolor > fleet.ansi # exactly --rows lines ./capture.sh catppuccin-mocha out/ # builds in a temp dir; writes out/ratatui--normal--80x24.ansi and ...120x30.ansi DEPTH=16 ./capture.sh catppuccin-latte out/ ``` Frame recipe: `Terminal::new(TestBackend::new(cols, rows))`, `terminal.draw(ui::render)`, then `ansi::buffer_to_ansi(buffer, depth)`: one SGR run per style change, wide glyphs skip their continuation cells (width from `Span::width`). Ratatui keeps `Color::Rgb` in cells, so color depth is applied by our serializer: truecolor as-is, 256 = nearest of the xterm 16..255 cube/greys, 16 = the theme's `ansi16` specs (see below). `--selected N` and `--focus-detail` pick another state. ## Theme tokens -> Ratatui `theme.json` = `python3 "$SKILL_DIR/scripts/export_theme.py" ID --target json -o theme.json` (embedded default: catppuccin-mocha; `export_theme.py --target ratatui` emits a ready-made const `Theme` if you prefer compile-time colors). `src/theme.rs`: `Theme::new(&ThemeFile, ansi16)` returns a struct of `Style`s, one per UI role (the `examples/apps/demo2/src/theme.rs` pattern); `ui.rs` only uses those fields. | UI role | token(s) | |---|---| | header band / app name / tabs | `statusbar.bg`+`statusbar.fg`, `accent.primary` bold, `tab.active.fg` on `tab.active.bg`, `tab.inactive.fg`, `border.default` | | focused / unfocused pane border | `border.focus` / `border.default`; titles `fg.title` bold | | selected row, cursor | `selection.bg` (`selection.inactive.bg` when unfocused) as `List::highlight_style`, `selection.fg`, `accent.primary` | | status glyphs and words | `status.success/warning/error`, `fg.faint` (stopped), `fg.muted` (running, unselected) | | gauges | `ramp.low` (< 50 %), `ramp.mid` (< 80 %), `ramp.high`, empty `fg.faint` | | footer | `statusbar.*`, `keyhint.key` bold, `keyhint.desc` | The whole area is painted with `bg.base` once (`Block::new().style(base)`); widgets patch on top. 16-color mode builds the `Style`s from the per-token `ansi16` specs (`"4 bold"`, `"default dim"`, `"reverse"`) with `Color::Indexed(0..15)`/`Reset`, so the terminal's own palette is used. With `selection.bg = reverse` the `List` highlight adds REVERSED to every cell of the row, so each segment is inverted keeping its own fg spec and bold (same as `render_mockup.py --depth 16`); the unfocused row follows `selection.inactive.bg`. A `bg` fg spec (e.g. `tab.active.fg` in everforest-dark) is drawn as the fill token's slot as fg + REVERSED (`Resolver::fg_on`), so the text takes the terminal background color on the fill. ## Caveats - Immediate mode: `ui::render` rebuilds every widget each frame; `ListState` is created per frame from `App.sel`. - `List::highlight_style` is applied over the whole row after the spans, so it only sets the background (spans keep their fg). - Block titles start right after the corner, so the title line is `"─"` + `" Title "`; title spans inherit the border style, so `fg.title` sets its fg explicitly (also `Reset` in 16-color mode) or the title would take the border color. - Gauges are hand-built spans (`█`/`░`) to match the mock exactly; `Gauge`/`LineGauge` widgets draw their own fill glyphs. - `Terminal::new(TestBackend)` frames never run the event loop: no timers, no input.skills/tui-design/assets/proto-starters/textual/README.md4.8 KB32cb2fa436cbupstream ↗
# Fleet — Textual starter The canonical "Fleet" demo screen (`../../demo/fleet--normal--80x24.mock`) in Textual: header band with tabs, focused list, detail panel with severity gauges, message line, key-hint bar. Adapts to any size >= 80x24; below that it shows a centered "Terminal too small — need 80×24, have C×R". Verified against the mock: at 80x24 truecolor the frame is cell-for-cell identical (characters, fg/bg, bold) across 7 themes, and `--depth 16` matches `render_mockup.py --depth 16` (0 differing cells for catppuccin-mocha and everforest-dark). There is no 120x30 mock: at 120x30 the Textual gauges widen with the detail pane (up to 60 cells), so Textual differs from Bubble Tea/Ratatui (40-cell gauges) in 92 cells and matches Ink. `--depth 256` uses Rich's quantizer, so it differs from the mock's 256-color rounding. Pinned (verified 2026-10-01): Python >= 3.11, `textual==8.2.8` (exact: `--frame` uses a private API; Rich 15.0.0 comes with it). ## Copy it into your project ```sh export SKILL_DIR=/path/to/tui-design # the skill directory (SKILL.md lives there) cp -R "$SKILL_DIR/assets/proto-starters/textual" ./fleet-ui && cd ./fleet-ui uv sync # project-local .venv; no global installs python3 "$SKILL_DIR/scripts/export_theme.py" catppuccin-mocha --target json -o theme.json # any theme ID uv run python -m fleet --frame --cols 80 --rows 24 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # frames at 80x24 and 120x30; or ./capture.sh theme.json out/ ``` `--theme` takes a flat theme JSON path or a theme ID (an ID is exported through `$SKILL_DIR/scripts/export_theme.py`, so it needs `SKILL_DIR`, or the starter still inside the skill). `capture.sh` resolves the skill the same way (`SKILL_DIR` first, then `../../..`) and stops with an error naming `SKILL_DIR` if neither works; with a JSON path no skill is needed. Keep the frame mode in the copy. ## Install and run ```sh uv sync # project-local .venv; no global installs uv run python -m fleet # interactive: up/down (or j/k) select, tab switches pane focus, q quits uv run python -m fleet --theme theme.json --depth 256 # --theme: JSON path or theme ID ``` ## One static frame (for gallery / compare / audit) ```sh uv run python -m fleet --frame --cols 120 --rows 30 --theme theme.json --depth truecolor > fleet.ansi ./capture.sh catppuccin-mocha out/ # writes out/textual--normal--80x24.ansi and out/textual--normal--120x30.ansi DEPTH=16 ./capture.sh catppuccin-latte out/ ``` Frame recipe: `App.run_test(size=(cols, rows))` + `pilot.pause()`, then render the compositor strips (`app.screen._compositor.render_update(full=True, ...)`) through a Rich `Console(color_system=...)` — exactly `rows` lines, no cursor-move codes. This is a **private API** (`fleet/__main__.py:frame_to_ansi`); re-verify when bumping Textual. `App.export_screenshot()` is the public alternative but only yields SVG. ## Theme tokens -> Textual `theme.json` = `python3 "$SKILL_DIR/scripts/export_theme.py" ID --target json -o theme.json` (default is catppuccin-mocha). `fleet/theme.py` registers a `Theme` and TCSS (`fleet/app.tcss`) uses only variables: - Textual slots: primary/accent <- `accent.primary`, secondary <- `accent.secondary`, success/warning/error <- `status.*`, foreground <- `fg.default`, background <- `bg.base`, surface <- `bg.surface`, panel <- `bg.raised`, `dark` <- appearance. - Every token also becomes a theme variable `$tok-<token-with-dashes>` (`border.focus` -> `$tok-border-focus`), e.g. `#services:focus { border: round $tok-border-focus; }`. Textual's built-ins do not cover keyhint/ramp/statusbar/tab tokens. - Widget text is markup built from tokens: `self.m("running", "status.success", on="selection.bg", bold=True)`. - depth `16`: tokens resolve to `ansi_<name>` colors from the theme's `ansi16` map and the app runs with `ansi_color=True` (native ANSI codes, terminal palette); `256` uses Rich's down-sampling. A `reverse` fill (`selection.bg`) inverts each segment keeping its own fg spec; a `bg` fg spec (e.g. `tab.active.fg` in everforest-dark) becomes the fill token's `ansi_<name>` + `reverse`, so the text takes the terminal background color on the fill (`Tokens.sty`). ## Caveats - Private compositor API for `--frame` (see above); the pin is the mitigation. - Border titles come with built-in padding, so titles are passed without spaces (`border_title = "Services (6)"`). - Textual paints `bg.base` on the screen, so a translucent terminal background is lost (unlike Ink); at depth 16 it is `ansi_default`. - Focus border uses `:focus` on the pane widget, so `tab` (built-in `focus_next`) moves `border.focus`; hints in the key bar are static. - Frame mode renders without notifications/tooltips (run_test defaults).skills/tui-design/scripts/_ansi.py10 KBc923d1a426f6upstream ↗
"""Shared ANSI/SGR parser for the tui-design scripts (stdlib only). Turns ONE frame of terminal output (a `tmux -L <name> capture-pane -p -e` dump, a rendered `.ansi` mockup, a program's one-shot output) into a grid of cells. Used by ansi_render.py (SVG/PNG/HTML) and ansi_grid.py (JSON + description skeleton). Supported: SGR 16 / 256 / truecolor (`;` and `:` forms), bold dim italic underline (+ styles 4:0-4:5 and SGR 21 double) blink reverse hidden strike overline, underline colour (58/59), tmux's `5:3` overline quirk, OSC 8 hyperlinks, wide (EAW W/F) and zero-width (combining, VS16, ZWJ) characters, tabs (8-col stops). NOT supported (by design): cursor movement, erase sequences, scroll regions, alternate screen. Every other escape sequence is skipped, never emulated. Feed it a single frame (`tmux -L <name> capture-pane -p -e`, `capture_tui.sh` output, `render_mockup.py` output) - a raw pty log of an interactive app is NOT a frame. Colours are None (terminal default), "p:N" (palette index 0-255) or "#rrggbb". """ from __future__ import annotations import re import sys import unicodedata from dataclasses import dataclass from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from _theme import ANSI_NAMES, Theme, palette256 # noqa: E402 # Attribute vocabulary = schemas/tui-description.schema.json style.attrs enum. UL_STYLES = {2: "double_underline", 3: "curly_underline"} # 4:1/4:4/4:5 (single, dotted, dashed) -> "underline" SIMPLE_ATTRS = {1: "bold", 2: "dim", 3: "italic", 4: "underline", 5: "blink", 6: "blink", 7: "reverse", 8: "hidden", 9: "strike", 53: "overline"} ATTR_OFF = {22: ("bold", "dim"), 23: ("italic",), 25: ("blink",), 27: ("reverse",), 28: ("hidden",), 29: ("strike",), 55: ("overline",)} UL_ATTRS = ("underline", "double_underline", "curly_underline") _TOKEN = re.compile( r"\x1b\[([0-9;:]*)m" # SGR r"|\x1b\]8;[^;\x07\x1b]*;([^\x07\x1b]*)(?:\x07|\x1b\\)" # OSC 8 hyperlink (group 2 = URI, may be empty) r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)" # any other OSC: skip r"|\x1b\[[0-?]*[ -/]*[@-~]" # any other CSI: skip (no cursor emulation) r"|\x1b[()*+][0-9A-Za-z]" # charset designation r"|\x1b[@-Z\\-_a-z=>]" # other 2-byte escapes r"|(.)", # a character re.S, ) @dataclass(frozen=True) class Style: fg: str | None = None bg: str | None = None ul: str | None = None # underline colour (SGR 58) attrs: frozenset = frozenset() link: str | None = None @dataclass class Cell: ch: str = " " # "" for the continuation cell of a wide char w: int = 1 # 1, 2, or 0 (continuation) style: Style = Style() BLANK = Cell() def char_width(ch: str) -> int: """Terminal cell width: 0 combining/format (incl. VS15/16, ZWJ), 2 for East Asian W/F, else 1.""" if ch < "\x7f": return 1 if ch >= " " else 0 if unicodedata.category(ch) in ("Mn", "Me", "Cf", "Cc"): return 0 return 2 if unicodedata.east_asian_width(ch) in "WF" else 1 def str_width(s: str) -> int: return sum(char_width(c) for c in s) # ---------------------------------------------------------------- SGR def _color(kind: str, a: list[str]) -> str | None: """Colour from the params after 38/48/58 (already split): ['5','N'] | ['2','r','g','b'] | ['2','','r','g','b'].""" try: if a and a[0] == "5": n = int(a[1]) return f"p:{n}" if 0 <= n <= 255 else None if a and a[0] == "2": r, g, b = (int(x or 0) for x in a[-3:]) if all(0 <= v <= 255 for v in (r, g, b)): return f"#{r:02x}{g:02x}{b:02x}" except (ValueError, IndexError): pass return None def apply_sgr(params: str, st: dict) -> None: """Apply one SGR parameter string to the mutable state dict (fg bg ul attrs link).""" parts = (params or "0").split(";") i = 0 while i < len(parts): p = parts[i] if ":" in p: head, *rest = p.split(":") if head == "4": # 4:N underline style st["attrs"] -= set(UL_ATTRS) n = int(rest[0]) if rest and rest[0].isdigit() else 1 if n: st["attrs"].add(UL_STYLES.get(n) or "underline") elif head == "5" and rest == ["3"]: # tmux writes overline (53) as "5:3" st["attrs"].add("overline") elif head in ("38", "48", "58"): # 38:2::r:g:b / 38:2:r:g:b / 38:5:n st[{"38": "fg", "48": "bg", "58": "ul"}[head]] = _color(head, rest) i += 1 continue try: n = int(p) if p else 0 except ValueError: i += 1 continue if n == 0: st.update(fg=None, bg=None, ul=None, attrs=set()) elif n == 4: st["attrs"] -= set(UL_ATTRS) st["attrs"].add("underline") elif n == 21: st["attrs"] -= set(UL_ATTRS) st["attrs"].add("double_underline") elif n == 24: st["attrs"] -= set(UL_ATTRS) elif n in SIMPLE_ATTRS: st["attrs"].add(SIMPLE_ATTRS[n]) elif n in ATTR_OFF: st["attrs"] -= set(ATTR_OFF[n]) elif 30 <= n <= 37: st["fg"] = f"p:{n - 30}" elif 90 <= n <= 97: st["fg"] = f"p:{n - 90 + 8}" elif 40 <= n <= 47: st["bg"] = f"p:{n - 40}" elif 100 <= n <= 107: st["bg"] = f"p:{n - 100 + 8}" elif n == 39: st["fg"] = None elif n == 49: st["bg"] = None elif n == 59: st["ul"] = None elif n in (38, 48, 58): key = {38: "fg", 48: "bg", 58: "ul"}[n] mode = parts[i + 1] if i + 1 < len(parts) else "" take = 2 if mode == "5" else 4 if mode == "2" else 0 st[key] = _color(str(n), parts[i + 1:i + 1 + take]) if take else None i += take i += 1 # ---------------------------------------------------------------- parsing class Grid: """rows x cols cells. `cells[y][x]`; wide chars occupy two entries (second: ch="", w=0).""" def __init__(self, cells: list[list[Cell]]): self.cells = cells self.rows = len(cells) self.cols = max((len(r) for r in cells), default=0) def text_rows(self) -> list[str]: """Verbatim row text; continuation cells omitted (display width == cols).""" return ["".join(c.ch for c in row if c.w) for row in self.cells] def resize(self, cols: int | None, rows: int | None) -> "Grid": cols = self.cols if cols is None else cols rows = self.rows if rows is None else rows out = [] for y in range(rows): row = list(self.cells[y]) if y < self.rows else [] row = row[:cols] + [BLANK] * (cols - len(row)) if cols and row[cols - 1].w == 2: # cropped wide char -> blank row[cols - 1] = Cell(" ", 1, row[cols - 1].style) out.append(row) return Grid(out) def parse_ansi(text: str, cols: int | None = None, rows: int | None = None) -> Grid: """Parse one frame. Style state carries across lines (tmux does not reset at EOL). Default size = longest line (display cells) x line count (one trailing newline ignored); `cols`/`rows` pad with blank cells or crop. """ text = text.replace("\r\n", "\n").replace("\r", "") if text.endswith("\n"): text = text[:-1] st = {"fg": None, "bg": None, "ul": None, "attrs": set(), "link": None} cache: dict = {} def style() -> Style: key = (st["fg"], st["bg"], st["ul"], frozenset(st["attrs"]), st["link"]) s = cache.get(key) if s is None: s = cache[key] = Style(*key) return s grid: list[list[Cell]] = [] for line in text.split("\n"): row: list[Cell] = [] for m in _TOKEN.finditer(line): ch = m.group(3) if m.group(1) is not None: apply_sgr(m.group(1), st) elif m.group(2) is not None: st["link"] = m.group(2) or None elif ch is not None: if ch == "\t": for _ in range(8 - len(row) % 8): row.append(Cell(" ", 1, style())) continue w = char_width(ch) if w == 0: if row and ord(ch) >= 0x7f: # combining / VS16 / ZWJ -> previous glyph k = len(row) - 1 if not row[k].w and k: k -= 1 row[k].ch += ch continue row.append(Cell(ch, w, style())) if w == 2: row.append(Cell("", 0, row[-1].style)) grid.append(row) return Grid(grid).resize(cols or None, rows or None) # also pads every row to the same width # ---------------------------------------------------------------- colour resolution SLOT_NAMES = {i: f"ansi.{n}" for i, n in enumerate(ANSI_NAMES)} class Resolver: """Resolve parsed colours against a theme: 0-15 + default fg/bg from the theme, 16-255 xterm, truecolor as is.""" def __init__(self, theme: Theme): self.theme = theme self.pal = palette256(theme.ansi) self.fg = theme.foreground self.bg = theme.background self.cursor = theme.cursor or theme.foreground def hex(self, color: str | None, default: str | None = None) -> str | None: if color is None: return default return self.pal[int(color[2:])] if color[0] == "p" else color @staticmethod def slot(color: str | None, default: str) -> str | None: """'ansi.red' | 'p:208' | 'term.fg'|'term.bg' (default) | None (off-palette truecolor).""" if color is None: return default if color[0] == "p": n = int(color[2:]) return SLOT_NAMES[n] if n < 16 else color return None def painted(self, s: Style) -> tuple[str, str | None]: """(fg, bg) as painted. bg None = terminal default background (no fill). reverse and hidden applied.""" fg, bg = self.hex(s.fg, self.fg), self.hex(s.bg) if "reverse" in s.attrs: fg, bg = bg or self.bg, fg if "hidden" in s.attrs: fg = bg or self.bg return fg, bgskills/tui-design/scripts/_craft.py7.2 KBb21b31fe93edupstream ↗
"""Craft lint: the countable README-test failures of references/visual-craft.md, as WARN findings on a parsed .mock. Each rule names a pattern that fails the README test and the principle that fixes it. They are heuristics on the cell grid, so a frame may waive one on purpose with a header line `#! note: craft-ok CRn <reason>`. CR1 bracket chips `[ Items ]`, `[ Apply: F2 ]`, `Search: [ … ]` P9, P11 CR2 label noise 2+ `Label:` prefixes on one row, or `a / b / c` detail lines P11 CR3 constant column a table column with one value on every row (6+ rows) P2, P10 CR4 loud placeholder `(none)` / `(untitled)` ×3+ at full weight P2 CR5 dead gutter 16+ empty columns between columns on every row of a table P1, P11 CR6 dead band a run of blank rows ≥ 1/5 of the frame (not in empty/busy) P1, P10 CR7 footer sprawl key hints spread over 2+ footer rows P9 """ from __future__ import annotations import re BRACKET = re.compile(r"\[\s*([^\[\]]{1,40}?)\s*\]") CHECKBOX = re.compile(r"^(?:[^A-Za-z]{0,8}|[A-Za-z]{1,2})$") # [ ] [x] [+] [9/18] [ok] [i]: controls, counters, ASCII status LABEL = re.compile(r"(?:^|(?<=\s))[A-Z][A-Za-z]+(?: [a-z]+)?: (?=\S)") SLASHED = re.compile(r"\S+ / \S+ / \S+") PLACEHOLDER = re.compile(r"^\((?:[a-z][a-z /-]{1,20})\)$|^<(?:none|empty|unset)>$") WORD = re.compile(r"\S+") QUIET = ("muted", "faint", "disabled", "subtle") GUTTER, BLOCK, CONST_ROWS = 16, 5, 6 SPARSE_STATES = ("empty", "toosmall", "busy", "loading") def _rows(m): """Per body row: (text with one char per cell column, styles per column).""" out = [] for cells in m.grid: chars, styles = [], [] for c in cells: chars.append(c.text[:1] or " ") styles.append(c.style) if c.width == 2: chars.append("\0") styles.append(c.style) pad = m.cols - len(chars) out.append(("".join(chars) + " " * max(0, pad), styles + [None] * max(0, pad))) return out def _quiet(style) -> bool: return style is None or "dim" in style.attrs or any(q in (style.fg or "") for q in QUIET) def _blocks(rows): """Runs of consecutive non-blank rows: [(first_y, last_y)].""" out, start = [], None for y, (t, _) in enumerate(rows + [(" ", [])]): blank = not t.strip(" \0") if not blank and start is None: start = y elif blank and start is not None: out.append((start, y - 1)) start = None return out def craft_findings(m) -> list[tuple[int, int, str, str]]: """(row y, col x, message, hint) per craft problem; rows/cols 0-based into the body grid.""" rows = _rows(m) found: list[tuple[int, int, str, str]] = [] waived = {n.split()[1] for n in m.notes if n.startswith("craft-ok ") and len(n.split()) > 1} def add(rule, y, x, msg, hint): if rule not in waived: found.append((y, x, f"craft {rule}: {msg}", hint + f"; waive with '#! note: craft-ok {rule} <reason>'")) # CR1, CR2: per-row text patterns for y, (t, _) in enumerate(rows): chips = [mt for mt in BRACKET.finditer(t) if not CHECKBOX.match(mt.group(1))] if chips: add("CR1", y, chips[0].start(), f"bracket chip {chips[0].group(0)!r}" + (f" (+{len(chips) - 1} more)" if len(chips) > 1 else ""), "mark the active tab with accent + bold or an underline; keys go in the footer as `key verb` (visual-craft P9, P11)") labels = LABEL.findall(t) if len(labels) >= 2: add("CR2", y, t.find(labels[0]), f"{len(labels)} 'Label:' prefixes on one row", "use aligned key–value rows (key in fg.muted, value in fg.default) or a breadcrumb with › (P11)") elif (ms := SLASHED.search(t)): add("CR2", y, ms.start(), f"slash-joined detail {ms.group(0)[:40]!r}", "use aligned key–value rows or a breadcrumb with › (P11)") # CR3 constant column, CR5 dead gutter: per table block (first row may be a header) for y0, y1 in _blocks(rows): body = list(range(y0 + 1, y1 + 1)) if len(body) < BLOCK: continue cols = None for y in body: toks = {(mt.start(), mt.group(0)) for mt in WORD.finditer(rows[y][0]) if re.search(r"[A-Za-z0-9]", mt.group(0))} cols = toks if cols is None else cols & toks others_vary = len({rows[y][0] for y in body}) > 1 for x, tok in sorted(cols or ()): if len(tok) >= 2 and others_vary and len(body) >= CONST_ROWS: add("CR3", body[0], x, f"column value {tok!r} is the same on all {len(body)} rows", "a value every row shares is not information: move it to the header or the detail (P2, P10)") break empty = [all(rows[y][0][x] == " " for y in body) for x in range(m.cols)] used = [x for x in range(m.cols) if not empty[x]] if used: run = best = 0 best_end = 0 for x in range(used[0], used[-1] + 1): run = run + 1 if empty[x] else 0 if run > best: best, best_end = run, x if best >= GUTTER: add("CR5", body[0], best_end - best + 1, f"{best} empty columns between two columns on all {len(body)} rows", "size the column to its longest value and give the width to one flex column (P1, P11)") # CR4 loud placeholder loud: dict[str, list[tuple[int, int]]] = {} for y, (t, st) in enumerate(rows): for mt in WORD.finditer(t): if PLACEHOLDER.match(mt.group(0)) and not _quiet(st[mt.start()]): loud.setdefault(mt.group(0), []).append((y, mt.start())) for tok, where in loud.items(): if len(where) >= 3: add("CR4", where[0][0], where[0][1], f"placeholder {tok!r} ×{len(where)} at full weight", "say it once per row as a glyph plus a dim or accent word, quieter than real values (P2)") # CR6 dead band (sparse states center a message on purpose) state = m.state or next((s for s in SPARSE_STATES if f"--{s}--" in m.path), "") run, limit = 0, (m.rows + 1 if state in SPARSE_STATES else max(4, m.rows // 5)) for y, (t, st) in enumerate(rows + [("x", [])]): blank = not t.strip(" \0") and all(s is None or not s.bg for s in st) if blank: run += 1 continue if run >= limit and y - run > 0 and y < len(rows): add("CR6", y - run, 0, f"{run} blank rows inside the frame", "size the list to the data and give the rows to the detail, a summary or a roster (P1, P10)") run = 0 # CR7 footer sprawl: trailing rows that carry key hints def keyrow(st): return sum(1 for i, s in enumerate(st) if s and s.fg == "keyhint.key" and (i == 0 or not st[i - 1] or st[i - 1].fg != "keyhint.key")) >= 2 n, y = 0, len(rows) - 1 while y >= 0 and (keyrow(rows[y][1]) or (n == 0 and not rows[y][0].strip())): n += keyrow(rows[y][1]) y -= 1 if n >= 2: add("CR7", y + 1, 0, f"key hints spread over {n} footer rows", "one footer row: context keys left, global keys right; the rest goes in ? help (P9)") return foundskills/tui-design/scripts/_mock.py28 KB746e9ca0884bupstream ↗
"""Parser + linter for the `.mock` v1 mockup markup (private to render_mockup.py; stdlib only). Format: references/formats.md "Mockup format". Glyph policy: references/visual-vocabulary.md "Linter policy". Only the pieces needed by render_mockup.py live here. """ from __future__ import annotations import json import re import unicodedata from dataclasses import dataclass, field from pathlib import Path from _craft import craft_findings from _theme import ATTRS, SKILL_ROOT, load_token_defs VISUAL_VOCAB = SKILL_ROOT / "references" / "visual-vocabulary.md" SCHEMA_FILE = SKILL_ROOT / "references" / "schemas" / "tui-description.schema.json" FALLBACK_ROLES = ( "screen header menubar tabbar toolbar sidebar list table tree detail editor log chart form input " "statusbar footer keybar modal toast popup_menu tooltip panel other" ).split() # Text-default emoji: EAW N/A but widen to 2 with VS16 and may render as colour emoji (WARN). TEXT_EMOJI = set( "✔✖⚠⚙❤ℹ⏺⏸▶◀♥✳↔↕↩↪⏏⏭⏮⏯⏹☀☁☂☎☑☠☢☣☮☯☸☹☺♀♂♠♣♦♨♻⚒⚔⚖⚗⚛⚜⚧⚰⚱✂✈✉✏✒✝✡✴❄❇❣➡⬅⬆⬇" "⤴⤵▪▫◻◼©®™‼⁉⌨⛈⛏⛑⛓⛩⛰⛱⛴⛷⛸⛹✌✍☄☘☝☪☭☦" ) # Replacement hints (the SAFE list of references/visual-vocabulary.md). HINTS = { "✔": "use ✓ U+2713", "✖": "use ✗ U+2717 or ✕ U+2715", "⚠": "use ▲ U+25B2 (status glyph table: references/visual-vocabulary.md V5)", "ℹ": "use 'i'", "⚙": "use a text label or ⋮ U+22EE", "▶": "use ▸ U+25B8 or ► U+25BA", "◀": "use ◂ U+25C2 or ◄ U+25C4", "❤": "use a word or ◉", "♥": "use a word or ◉", "✳": "use ✱ U+2731", "⏺": "use ◉ U+25C9 or ⬤ U+2B24", "⏸": "use '||'", "…": "use ⋯ U+22EF (N) or '...'", "—": "use '-' or '─'", "–": "use '-'", "√": "use ✓ U+2713", "×": "use ✕ U+2715 or 'x'", } # A-class chrome allow-list (INFO; ERROR under --strict-ambiguous): r5 2.2 list + arrows used by key hints. ALLOW_A = set("●○◆■▲▼★…·•→×√←↑↓") # Dashes are EAW=A but ubiquitous in copy and single-width in monospace fonts: INFO like the chrome set. DASHES = set("—–") SAFE_HINT = "pick an N/Na/H glyph (r5 2.2 SAFE list) or accept ambiguity with the default profile" @dataclass class Finding: line: int col: int level: str # ERROR | WARN | INFO msg: str hint: str = "" tag: str = "" # "caps" = capability-profile finding (never collapsed into the glyph INFO summary) def fmt(self, path: str) -> str: h = f" ({self.hint})" if self.hint else "" return f"{path}:{self.line}:{self.col}: {self.level}: {self.msg}{h}" @dataclass class Region: id: str role: str x: int y: int w: int h: int title: str = "" line: int = 0 @dataclass class Style: fg: str | None = None bg: str | None = None attrs: tuple[str, ...] = () @dataclass class Cell: text: str # base char plus any combining marks width: int # 1 or 2 style: Style col: int = 0 # 1-based source column of the cell's first code point (0 = synthetic) @dataclass class Mock: path: str = "<stdin>" cols: int = 80 rows: int = 24 title: str = "" state: str = "" theme: str = "" notes: list[str] = field(default_factory=list) # `#! note:` lines (free text, repeatable) body_line: int = 1 # 1-based source line of body row 0 regions: list[Region] = field(default_factory=list) focus: str = "" # `#! focus <region-id>`: audit truth, ignored by rendering selected: list[tuple[str, int]] = field(default_factory=list) # `#! selected <region-id> <row>`; row = 0-based offset inside the region interior caps: "Caps" = field(default_factory=lambda: Caps()) # `#! caps:` header (+ --caps override); default = everything allowed grid: list[list[Cell]] = field(default_factory=list) # one list of cells per source row findings: list[Finding] = field(default_factory=list) # ------------------------------------------------------------------ widths and glyph classes def char_width(ch: str) -> int: cat = unicodedata.category(ch) if cat in ("Mn", "Me", "Cf"): return 0 if cat in ("Cc", "Cs"): return 0 if ch not in "\t" else 1 return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1 def str_width(s: str) -> int: return sum(char_width(c) for c in s) def known_roles() -> list[str]: try: schema = json.loads(SCHEMA_FILE.read_text()) return list(schema["$defs"]["region"]["properties"]["role"]["enum"]) except (OSError, KeyError, ValueError): return FALLBACK_ROLES # ------------------------------------------------------------------ capability profile CAP_COLORS = {"truecolor": "truecolor", "256": "256", "16": "16", "none": "nocolor"} # caps colors= -> render depth CAP_GLYPHS = ("ascii", "unicode", "nerd") CAP_KEYS = ("attrs", "colors", "glyphs", "widgets", "source") CAP_SOURCES = ("test-card", "docs", "code", "assumed") # where the profile comes from; only test-card/docs are evidence class Caps: """Capability profile of the target host: `attrs=bold,dim colors=16 glyphs=unicode widgets=tabs,list`. `given` holds only the keys that were written explicitly (key -> tuple of values); every property falls back to the default (all attrs, truecolor, unicode, no widget list).""" def __init__(self, given: dict | None = None): self.given: dict[str, tuple[str, ...]] = dict(given or {}) @property def attrs(self) -> tuple[str, ...]: return tuple(self.given["attrs"]) if "attrs" in self.given else tuple(ATTRS) @property def colors(self) -> str: return self.given["colors"][0] if "colors" in self.given else "truecolor" @property def glyphs(self) -> str: return self.given["glyphs"][0] if "glyphs" in self.given else "unicode" @property def source(self) -> str: return self.given["source"][0] if "source" in self.given else "" @property def widgets(self) -> tuple[str, ...]: return tuple(self.given.get("widgets", ())) @property def depth(self) -> str: """The render depth this profile implies (colors=none -> nocolor: no color, attributes kept).""" return CAP_COLORS[self.colors] def merged(self, other: "Caps") -> "Caps": return Caps({**self.given, **other.given}) def spec(self) -> str: return " ".join(f"{k}={','.join(self.given[k])}" for k in CAP_KEYS if k in self.given) def __bool__(self) -> bool: return bool(self.given) def parse_caps(text: str) -> tuple[Caps, list[str]]: """Parse `key=v,v key=v` into (Caps, error messages). Unknown keys and values are errors.""" given: dict[str, tuple[str, ...]] = {} errs: list[str] = [] for item in text.split(): key, sep, val = item.partition("=") if not sep or key not in CAP_KEYS: errs.append(f"bad caps item {item!r}; expected key=v,v with key in {' '.join(CAP_KEYS)}") continue vals = tuple(v for v in val.split(",") if v) if key in given: errs.append(f"duplicate caps key {key!r}") if key == "attrs": if vals == ("none",): vals = () bad = [v for v in vals if v not in ATTRS] if bad: errs.append(f"unknown attrs {','.join(bad)} (valid: {' '.join(ATTRS)} or none)") continue elif key == "colors": if len(vals) != 1 or vals[0] not in CAP_COLORS: errs.append(f"bad colors {val!r} (valid: {' '.join(CAP_COLORS)})") continue elif key == "glyphs": if len(vals) != 1 or vals[0] not in CAP_GLYPHS: errs.append(f"bad glyphs {val!r} (valid: {' '.join(CAP_GLYPHS)})") continue elif key == "source": if len(vals) != 1 or vals[0] not in CAP_SOURCES: errs.append(f"bad source {val!r} (valid: {' '.join(CAP_SOURCES)})") continue given[key] = vals return Caps(given), errs # ------------------------------------------------------------------ ASCII fallbacks (visual-vocabulary.md V9) # Built-in extras for glyphs V9 does not list (copy punctuation); V9 entries win. FALLBACK_EXTRA = {"—": "-", "–": "-", "…": "...", "→": "->", "←": "<-", "↑": "^", "↓": "v", "×": "x", "•": "-"} # Sharp corners and heavy/double rules: V9 only maps them in a comment or not at all. FALLBACK_FORCE = {"┌": "+", "┐": "+", "└": "+", "┘": "+", "━": "-", "┃": "|", "═": "=", "║": "|"} _V9: dict[str, str] | None = None _V9_LINE = re.compile(r'([\w/]+):\s*\[\s*"([^"]*)"\s*,\s*"([^"]*)"\s*\]') def v9_fallbacks(path: Path | None = None) -> dict[str, str]: """glyph -> ASCII fallback parsed from the V9 map in visual-vocabulary.md ({} when absent or unparsable).""" global _V9 if path is None and _V9 is not None: return _V9 out: dict[str, str] = {} try: text = (path or VISUAL_VOCAB).read_text(encoding="utf-8") m = re.search(r"^##\s+V9\b.*?$(.*?)(?=^##\s|\Z)", text, re.M | re.S) for _role, glyphs, ascii_ in _V9_LINE.findall(m.group(1) if m else ""): g_, a_ = glyphs.strip(), ascii_.strip() if " " in g_: # "╭ ╮ ╰ ╯": space-separated glyphs share the one ASCII chars, per_char = [c for c in g_ if not c.isspace()], False else: # "▁▂▃▄", "├──": same length -> glyph i maps to ASCII char i chars, per_char = list(g_), len(a_) == len(g_) > 1 for i, c in enumerate(chars): out.setdefault(c, a_[i] if per_char else (a_ or ascii_)) except OSError: out = {} if path is None: _V9 = out return out def ascii_fallback(ch: str) -> str: """ASCII replacement for a glyph: V9 first, then the built-in extras; "" when unknown.""" return FALLBACK_FORCE.get(ch) or v9_fallbacks().get(ch) or FALLBACK_EXTRA.get(ch, "") def classify_glyph(ch: str, strict: bool, nerd: bool, caps: Caps | None = None) -> tuple[str, str, str] | None: """Return (level, message, hint) for a body code point, or None when it is fine.""" cp = ord(ch) cat = unicodedata.category(ch) eaw = unicodedata.east_asian_width(ch) u = f"U+{cp:04X}" if cp in (0xFE0F, 0xFE0E): return "ERROR", f"variation selector {u} in layout text", "never emit VS15/VS16; width is terminal-dependent" if cp == 0x200D: return "ERROR", f"zero-width joiner {u} in layout text", "ZWJ sequences have no stable cell width" if 0x1F1E6 <= cp <= 0x1F1FF or 0x1F3FB <= cp <= 0x1F3FF: return "ERROR", f"regional indicator / skin-tone modifier {u}", "remove it; use plain text" if cp == 0xFFFD: return "ERROR", "replacement character U+FFFD (encoding damage)", "re-save the file as UTF-8" if cat == "Cc" and ch != "\t": return "ERROR", f"control character {u}", "control codes cannot appear in a mockup" if ch == "\t": return "WARN", "tab character (rendered as 1 space)", "use spaces; tabs have no fixed width" if caps is not None and caps.glyphs == "ascii" and cp > 127: fb = ascii_fallback(ch) return ("ERROR", f"non-ASCII glyph {u} {ch} under caps glyphs=ascii", f"ASCII fallback (V9): {fb!r}" if fb else "no V9 fallback; use a plain ASCII character") if caps is not None and caps.glyphs == "nerd": nerd = True if cat == "Co" or 0xF0000 <= cp <= 0x10FFFF: if caps is not None and "glyphs" in caps.given and caps.glyphs == "unicode": return "ERROR", f"private-use glyph {u} (Nerd Font / Powerline) under caps glyphs=unicode", "use a SAFE Unicode glyph, or declare glyphs=nerd" if nerd: return None return "ERROR", f"private-use glyph {u} (Nerd Font / Powerline)", "use a SAFE Unicode glyph or pass --allow-nerd-font" if eaw in ("W", "F"): return "ERROR", f"wide glyph {u} {unicodedata.name(ch, '?')} (EAW={eaw}, 2 cells)", HINTS.get(ch, "use a 1-cell glyph; emoji/CJK break column alignment") if cat in ("Mn", "Me"): return "WARN", f"combining mark {u} (0 cells, font-dependent)", "precompose the character or avoid it" if ch in TEXT_EMOJI: return "WARN", f"text-default emoji {u} {ch} (2 cells with VS16, may render as colour emoji)", HINTS.get(ch, SAFE_HINT) if cp == 0x2800: return "WARN", "braille blank U+2800 (some fonts draw nothing)", "use a plain space outside graphs" if eaw == "A" and ch in DASHES: return ("ERROR" if strict else "INFO"), f"ambiguous-width (EAW=A) dash {u} {ch}", "single-width in monospace fonts; use '-' or '─' to be strict" if eaw == "A": chrome = 0x2500 <= cp <= 0x259F or 0x25A0 <= cp <= 0x25FF or ch in ALLOW_A if chrome: eaw_n = (0x254C <= cp <= 0x254F or 0x2574 <= cp <= 0x257F or cp in (0x2590, 0x2591) or 0x2596 <= cp <= 0x259F) if eaw_n: return None return ("ERROR" if strict else "INFO"), f"ambiguous-width (EAW=A) chrome glyph {u} {ch}", "1 cell normally, 2 in CJK-ambiguous-wide terminals" return "WARN", f"ambiguous-width (EAW=A) glyph {u} {ch} outside the chrome allow-list", HINTS.get(ch, SAFE_HINT) return None # ------------------------------------------------------------------ box integrity # Corner glyphs per position (light/rounded/heavy/double/mixed) plus ASCII '+'. _CORNERS = { "tl": set("┌╭┏╔╒╓┍┎+"), "tr": set("┐╮┓╗╕╖┑┒+"), "bl": set("└╰┗╚╘╙┕┖+"), "br": set("┘╯┛╝╛╜┙┚+"), } _ASCII_EDGE = set("-=+|") _SCROLL = set("▀▐▌█▓▒░▕▏▎▍▋▊▉") # scrollbar thumb/track glyphs may replace a vertical edge cell def _is_box(ch: str) -> bool: return 0x2500 <= ord(ch[0]) <= 0x257F or ch in _ASCII_EDGE def _row_cells(row: list[Cell]) -> dict[int, Cell]: """Display column -> cell (a wide glyph occupies its first column only).""" out: dict[int, Cell] = {} x = 0 for c in row: out[x] = c x += c.width return out def check_box_integrity(m: Mock) -> None: """ERROR when text overwrites the border of a `#! region` whose bbox corners are box-drawing corners. Top/bottom edges may carry title runs (any text between box glyphs, never touching a corner); the vertical sides must hold box glyphs (scrollbar block glyphs are tolerated) all the way down. """ rows = [_row_cells(r) for r in m.grid] def cell(x: int, y: int) -> tuple[str, int, int]: """(char, source line, source col) at display position; blank beyond the row.""" line = m.body_line + y r = rows[y] if y < len(rows) else {} c = r.get(x) if c is None: used = max((k + r[k].width for k in r), default=0) return " ", line, (max((r[k].col for k in r), default=0) + 1 if x >= used else 1) return c.text, line, c.col or 1 for reg in m.regions: x0, y0, x1, y1 = reg.x, reg.y, reg.x + reg.w - 1, reg.y + reg.h - 1 if reg.w < 2 or reg.h < 2 or x0 < 0 or y0 < 0 or x1 >= m.cols or y1 >= m.rows: continue corners = (("tl", x0, y0), ("tr", x1, y0), ("bl", x0, y1), ("br", x1, y1)) missing = [(x, y) for k, x, y in corners if cell(x, y)[0][0] not in _CORNERS[k]] if len(missing) > 1: # not a box (>=3 intact corners = a box with one overwritten corner) continue bad: list[tuple[int, int]] = list(missing) for y in (y0, y1): # horizontal edges: a title run may sit between box glyphs for x in {x0 + 1, x1 - 1} if reg.w > 2 else (): if not _is_box(cell(x, y)[0][0]): bad.append((x, y)) for y in range(y0 + 1, y1): # vertical sides: no text at all for x in (x0, x1): ch = cell(x, y)[0][0] if not (_is_box(ch) or ch in _SCROLL): bad.append((x, y)) for x, y in sorted(set(bad), key=lambda p: (p[1], p[0])): ch, line, col = cell(x, y) m.findings.append(Finding(line, col, "ERROR", f"region {reg.id} border overwritten at ({x},{y}) by {ch!r}", "keep text inside the box; titles sit between ─ segments")) # ------------------------------------------------------------------ parsing REGION_RE = re.compile(r"^region\s+(\S+)\s+(\S+)\s+(-?\d+),(-?\d+),(-?\d+),(-?\d+)(?:\s+(.*))?$") SIZE_RE = re.compile(r"^(\d+)\s*x\s*(\d+)$") HEX_RE = re.compile(r"#[0-9a-fA-F]{3,8}\b") def _parse_spec(spec: str, defs: dict, line: int, col: int, out: list[Finding]) -> Style: st = Style() attrs: list[str] = [] if not spec.strip(): out.append(Finding(line, col, "ERROR", "empty style tag {}", "use {/} to close or give a token/attribute")) return st for item in spec.split(): if HEX_RE.fullmatch(item) or HEX_RE.fullmatch(item.removeprefix("on:")): out.append(Finding(line, col, "ERROR", f"raw hex color {item!r} not allowed", "use a token from themes/_tokens.json")) elif item.startswith("on:"): tok = item[3:] if tok not in defs: out.append(Finding(line, col, "ERROR", f"unknown token {tok!r} in {item!r}", "see themes/_tokens.json")) elif tok == "fg.on-accent": out.append(Finding(line, col, "ERROR", "'fg.on-accent' is text drawn on a fill, not a fill", "write {fg.on-accent on:status.warning} (chip text on a status/accent fill)")) else: # any other token is a color; "kind" only names its usual role (chips: on:status.warning) st.bg = tok elif item in ATTRS: attrs.append(item) elif item in defs: if defs[item]["kind"] != "fg": out.append(Finding(line, col, "ERROR", f"{item!r} is a bg token; write on:{item}")) else: st.fg = item elif "." in item: out.append(Finding(line, col, "ERROR", f"unknown token {item!r}", "see themes/_tokens.json")) else: out.append(Finding(line, col, "ERROR", f"unknown attribute {item!r}", "valid: " + " ".join(ATTRS))) st.attrs = tuple(dict.fromkeys(attrs)) return st def _merge(stack: list[tuple[Style, int, int]]) -> Style: fg = bg = None attrs: list[str] = [] for st, _, _ in stack: fg = st.fg or fg bg = st.bg or bg attrs += st.attrs return Style(fg, bg, tuple(dict.fromkeys(attrs))) def parse_mock(text: str, path: str = "<stdin>", strict: bool = False, nerd: bool = False, caps: str | None = None) -> Mock: """Parse and lint. `caps` (a `key=v,v …` string) overrides/defines the capability profile (CLI --caps).""" defs = load_token_defs() m = Mock(path=path) f = m.findings lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") if lines and lines[-1] == "": lines.pop() # ---- header i = 0 seen_magic = seen_size = False focus_line, selected_lines = 0, [] caps_line = 0 roles = known_roles() while i < len(lines) and lines[i].startswith("#!"): n = i + 1 body = lines[i][2:].strip() i += 1 if not seen_magic: seen_magic = True if body != "tui-mockup 1": f.append(Finding(n, 1, "ERROR", f"first line must be '#! tui-mockup 1', got {body!r}")) continue if body.startswith("region"): mt = REGION_RE.match(body) if not mt: f.append(Finding(n, 1, "ERROR", "malformed region", "#! region <id> <role> x,y,w,h [title]")) continue rid, role, x, y, w, h, title = mt.groups() reg = Region(rid, role, int(x), int(y), int(w), int(h), title or "", n) if not re.fullmatch(r"r[0-9]+", rid): f.append(Finding(n, 1, "ERROR", f"region id {rid!r} must match r<N>")) if any(r.id == rid for r in m.regions): f.append(Finding(n, 1, "ERROR", f"duplicate region id {rid!r}")) if role not in roles: f.append(Finding(n, 1, "ERROR", f"unknown region role {role!r}", "valid: " + " ".join(roles))) m.regions.append(reg) continue words = body.split() if words and words[0] == "focus": if len(words) != 2 or not re.fullmatch(r"r[0-9]+", words[1]): f.append(Finding(n, 1, "ERROR", "malformed focus", "#! focus <region-id>")) elif m.focus: f.append(Finding(n, 1, "ERROR", "duplicate '#! focus' header", "one focused region per mockup")) else: m.focus = words[1] focus_line = n continue if words and words[0] == "selected": if len(words) != 3 or not re.fullmatch(r"r[0-9]+", words[1]) or not words[2].isdigit(): f.append(Finding(n, 1, "ERROR", "malformed selected", "#! selected <region-id> <row> (row = 0-based offset inside the region interior)")) else: m.selected.append((words[1], int(words[2]))) selected_lines.append(n) continue key, sep, val = body.partition(":") key, val = key.strip(), val.strip() if not sep: f.append(Finding(n, 1, "WARN", f"header line without 'key:' ({body!r})")) elif key == "size": ms = SIZE_RE.match(val) if not ms or int(ms.group(1)) < 1 or int(ms.group(2)) < 1: f.append(Finding(n, 1, "ERROR", f"bad size {val!r}", "expected COLSxROWS, e.g. 80x24")) else: m.cols, m.rows, seen_size = int(ms.group(1)), int(ms.group(2)), True elif key == "caps": parsed, errs = parse_caps(val) for e in errs: f.append(Finding(n, 1, "ERROR", f"#! caps: {e}")) if caps_line: f.append(Finding(n, 1, "ERROR", "duplicate '#! caps:' header", "one capability profile per mockup")) else: m.caps, caps_line = parsed, n elif key in ("title", "state", "theme"): setattr(m, key, val) elif key == "note": m.notes.append(val) else: f.append(Finding(n, 1, "WARN", f"unknown header key {key!r}")) if caps: over, errs = parse_caps(caps) for e in errs: f.append(Finding(1, 1, "ERROR", f"--caps: {e}")) m.caps = m.caps.merged(over) caps_line = caps_line or 1 if m.caps.colors in ("16", "none"): depth = m.caps.depth f.append(Finding(caps_line or 1, 1, "INFO", f"caps colors={m.caps.colors}: render and check with --depth {depth}", "render_mockup.py defaults to this depth; run contrast_check.py ID --depth 16", tag="caps")) if m.caps and m.caps.source in ("", "code", "assumed"): why = {"": "says nowhere where it comes from", "code": "comes from what the current code uses", "assumed": "is assumed"}[m.caps.source] f.append(Finding(caps_line or 1, 1, "WARN", f"caps profile {why}, not from the host", "ask the user to run `python3 SKILL_DIR/scripts/test_card.py` (`--curses` for a curses app) inside " "the host and send a screenshot, then write source=test-card; source=docs if the host documents it", tag="caps")) if not seen_magic: f.append(Finding(1, 1, "ERROR", "missing '#! tui-mockup 1' header")) if not seen_size: f.append(Finding(1, 1, "ERROR", "missing '#! size: COLSxROWS' (assuming 80x24)")) for r in m.regions: if r.w < 1 or r.h < 1 or r.x < 0 or r.y < 0 or r.x + r.w > m.cols or r.y + r.h > m.rows: f.append(Finding(r.line, 1, "ERROR", f"region {r.id} bbox {r.x},{r.y},{r.w},{r.h} outside size {m.cols}x{m.rows}")) ids = {r.id: r for r in m.regions} if m.focus and m.focus not in ids: f.append(Finding(focus_line, 1, "ERROR", f"'#! focus' names unknown region {m.focus!r}", "declare it with '#! region' first")) for (rid, row), n in zip(m.selected, selected_lines): if rid not in ids: f.append(Finding(n, 1, "ERROR", f"'#! selected' names unknown region {rid!r}", "declare it with '#! region' first")) elif row >= ids[rid].h: f.append(Finding(n, 1, "ERROR", f"'#! selected {rid} {row}': row outside the region (h={ids[rid].h})")) # ---- body m.body_line = i + 1 stack: list[tuple[Style, int, int]] = [] glyphs: dict[tuple[str, str], dict] = {} base = Style() for ri, raw in enumerate(lines[i:]): n = i + ri + 1 if raw.startswith("#! "): f.append(Finding(n, 1, "ERROR", "header line after body started", "all '#!' lines must precede the first body row")) cells: list[Cell] = [] width = 0 overflow_at = 0 cur = _merge(stack) if stack else base j = 0 while j < len(raw): ch = raw[j] col = j + 1 if ch == "{": if raw.startswith("{{", j): ch = "{" j += 1 else: end = raw.find("}", j) if end < 0: f.append(Finding(n, col, "ERROR", "unterminated tag '{'", "literal brace is '{{'")) j += 1 continue spec = raw[j + 1:end] if spec == "/": if not stack: f.append(Finding(n, col, "ERROR", "unbalanced {/}: no open tag")) else: stack.pop() else: st = _parse_spec(spec, defs, n, col, f) for a in st.attrs: if a not in m.caps.attrs: f.append(Finding(n, col, "ERROR", f"attribute {a!r} not in caps attrs={','.join(m.caps.attrs) or 'none'} (cell x={width},y={ri})", "drop it, or carry the emphasis with an allowed attribute or a glyph")) stack.append((st, n, col)) cur = _merge(stack) if stack else base j = end + 1 continue elif ch == "}": if raw.startswith("}}", j): j += 1 else: f.append(Finding(n, col, "ERROR", "stray '}'", "literal brace is '}}'")) j += 1 continue j += 1 g = classify_glyph(ch, strict, nerd, m.caps) if g: key = (g[0], ch) d = glyphs.setdefault(key, {"first": (n, col), "lines": [], "msg": g[1], "hint": g[2], "count": 0}) d["count"] += 1 if n not in d["lines"]: d["lines"].append(n) w = char_width(ch) if w == 0: if cells: cells[-1].text += ch continue if ch == "\t": ch = " " if width + w > m.cols and not overflow_at: overflow_at = col cells.append(Cell(ch, w, cur, col)) width += w if overflow_at: f.append(Finding(n, overflow_at, "ERROR", f"row is {width} cells wide, exceeds cols={m.cols}", "trim the line or raise #! size")) m.grid.append(cells) for st, n, col in stack: f.append(Finding(n, col, "ERROR", "unbalanced tag: never closed with {/}")) if len(m.grid) > m.rows: f.append(Finding(i + m.rows + 1, 1, "ERROR", f"{len(m.grid)} body rows exceed rows={m.rows}", "drop rows or raise #! size")) for (level, ch), d in sorted(glyphs.items(), key=lambda kv: (kv[1]["first"], kv[0])): n, col = d["first"] where = ",".join(map(str, d["lines"][:8])) + ("…" if len(d["lines"]) > 8 else "") msg = d["msg"] + (f" [{d['count']}x, lines {where}]" if d["count"] > 1 else "") f.append(Finding(n, col, level, msg, d["hint"])) check_box_integrity(m) for y, x, msg, hint in craft_findings(m): f.append(Finding(m.body_line + y, x + 1, "WARN", msg, hint, tag="craft")) f.sort(key=lambda x: (x.line, x.col, x.level)) return mskills/tui-design/scripts/_theme.py11 KB9bf7cd37ed3cupstream ↗
"""Shared theme + color utilities for the tui-design scripts (stdlib only). Contract (see references/color-tokens.md): - Token definitions live in references/themes/_tokens.json. - A theme lives in references/themes/<id>.json and contains `terminal` (background, foreground, cursor, selection, 16-entry `ansi` list) and `tokens` (token -> palette name or "#rrggbb"), plus optional `ansi16` per-token overrides. Missing tier-2 tokens resolve through `fallback`. """ from __future__ import annotations import json import math import re from dataclasses import dataclass, field from pathlib import Path SKILL_ROOT = Path(__file__).resolve().parent.parent THEMES_DIR = SKILL_ROOT / "references" / "themes" TOKENS_FILE = THEMES_DIR / "_tokens.json" HEX_RE = re.compile(r"^#[0-9a-fA-F]{6}$") ANSI_NAMES = [ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "bright_black", "bright_red", "bright_green", "bright_yellow", "bright_blue", "bright_magenta", "bright_cyan", "bright_white", ] ATTRS = ("bold", "dim", "italic", "underline", "inverse", "strike") SGR_ATTR = {"bold": 1, "dim": 2, "italic": 3, "underline": 4, "inverse": 7, "strike": 9} # xterm defaults for indexes 0-15 when no theme is given. XTERM16 = [ "#000000", "#cd0000", "#00cd00", "#cdcd00", "#0000ee", "#cd00cd", "#00cdcd", "#e5e5e5", "#7f7f7f", "#ff0000", "#00ff00", "#ffff00", "#5c5cff", "#ff00ff", "#00ffff", "#ffffff", ] # ---------------------------------------------------------------- hex / rgb def hex_to_rgb(h: str) -> tuple[int, int, int]: h = h.lstrip("#") return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) def rgb_to_hex(rgb: tuple[int, int, int]) -> str: return "#{:02x}{:02x}{:02x}".format(*rgb) def palette256(ansi16: list[str] | None = None) -> list[str]: """xterm 256-color palette; 0-15 from the theme (or xterm defaults).""" pal = list(ansi16 or XTERM16) levels = [0, 95, 135, 175, 215, 255] for r in levels: for g in levels: for b in levels: pal.append(rgb_to_hex((r, g, b))) for i in range(24): v = 8 + 10 * i pal.append(rgb_to_hex((v, v, v))) return pal # ---------------------------------------------------------------- OKLab def _srgb_to_lin(c: float) -> float: c /= 255.0 return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 def oklab(h: str) -> tuple[float, float, float]: r, g, b = (_srgb_to_lin(c) for c in hex_to_rgb(h)) l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b l_, m_, s_ = (math.copysign(abs(x) ** (1 / 3), x) for x in (l, m, s)) return ( 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_, 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_, 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_, ) def oklab_distance(a: str, b: str) -> float: return math.dist(oklab(a), oklab(b)) _CUBE_LAB: list[tuple[int, tuple[float, float, float]]] | None = None def nearest256(h: str) -> int: """Nearest xterm index in 16..255 by OKLab distance (0-15 are theme-defined, never used).""" global _CUBE_LAB if _CUBE_LAB is None: pal = palette256() _CUBE_LAB = [(i, oklab(pal[i])) for i in range(16, 256)] t = oklab(h) return min(_CUBE_LAB, key=lambda item: math.dist(t, item[1]))[0] # ---------------------------------------------------------------- contrast def relative_luminance(h: str) -> float: r, g, b = (_srgb_to_lin(c) for c in hex_to_rgb(h)) return 0.2126 * r + 0.7152 * g + 0.0722 * b def contrast_ratio(fg: str, bg: str) -> float: a, b = relative_luminance(fg), relative_luminance(bg) hi, lo = max(a, b), min(a, b) return (hi + 0.05) / (lo + 0.05) def blend(fg: str, bg: str, alpha: float) -> str: """Alpha-composite fg over bg (used to model dim text: alpha ~0.55).""" f, b = hex_to_rgb(fg), hex_to_rgb(bg) return rgb_to_hex(tuple(round(alpha * x + (1 - alpha) * y) for x, y in zip(f, b))) # ---------------------------------------------------------------- tokens def load_token_defs(path: Path = TOKENS_FILE) -> dict[str, dict]: return json.loads(Path(path).read_text())["tokens"] def parse_ansi16(spec: str) -> tuple[str | int, tuple[str, ...]]: """'4 bold' -> (4, ('bold',)); 'default dim' -> ('default', ('dim',)); 'reverse' -> ('reverse', ()). 'bg' (fg tokens only) = "terminal background as text": the cell is drawn as the fill's slot with SGR 7, so text takes the terminal's default background. Used for chips in 16-color mode. """ parts = spec.split() head, attrs = parts[0], tuple(parts[1:]) for a in attrs: if a not in ATTRS: raise ValueError(f"unknown attribute {a!r} in ansi16 spec {spec!r}") if head in ("default", "reverse", "bg"): return head, attrs if head in ANSI_NAMES: return ANSI_NAMES.index(head), attrs idx = int(head) if not 0 <= idx <= 15: raise ValueError(f"ansi16 color index out of range in {spec!r}") return idx, attrs @dataclass class Theme: id: str name: str appearance: str background: str foreground: str cursor: str | None selection_background: str | None ansi: list[str] palette: dict[str, str] tokens: dict[str, str] = field(default_factory=dict) # token -> resolved hex ansi16: dict[str, tuple] = field(default_factory=dict) # token -> (color, attrs) raw: dict = field(default_factory=dict) def hex(self, token: str) -> str: try: return self.tokens[token] except KeyError: raise KeyError(f"unknown token {token!r} (see references/themes/_tokens.json)") from None def _resolve_value(value: str, palette: dict[str, str], where: str) -> str: if HEX_RE.match(value): return value.lower() if value in palette: return palette[value].lower() raise ValueError(f"{where}: {value!r} is neither #rrggbb nor a palette name") def find_theme_file(name_or_path: str) -> Path: p = Path(name_or_path) if p.suffix == ".json" and p.exists(): return p cand = THEMES_DIR / f"{name_or_path}.json" if cand.exists(): return cand available = ", ".join(list_themes()) raise FileNotFoundError(f"theme {name_or_path!r} not found. Available: {available}") def list_themes() -> list[str]: return sorted(p.stem for p in THEMES_DIR.glob("*.json") if not p.name.startswith("_")) def load_theme(name_or_path: str, token_defs: dict[str, dict] | None = None) -> Theme: path = find_theme_file(name_or_path) data = json.loads(path.read_text()) defs = token_defs or load_token_defs() term = data["terminal"] palette = {k: v for k, v in data.get("palette", {}).items() if isinstance(v, str) and HEX_RE.match(v)} ansi = [c.lower() for c in term["ansi"]] if len(ansi) != 16: raise ValueError(f"{path}: terminal.ansi must have 16 entries") raw_tokens: dict[str, str] = data.get("tokens", {}) unknown = set(raw_tokens) - set(defs) if unknown: raise ValueError(f"{path}: unknown tokens {sorted(unknown)}") resolved: dict[str, str] = {} def resolve(tok: str, seen: tuple = ()) -> str: if tok in resolved: return resolved[tok] if tok in seen: raise ValueError(f"{path}: fallback cycle {' -> '.join(seen + (tok,))}") if tok in raw_tokens: val = _resolve_value(raw_tokens[tok], palette, f"{path}: tokens.{tok}") else: fb = defs[tok].get("fallback") if not fb: raise ValueError(f"{path}: tier-1 token {tok!r} is missing") val = resolve(fb, seen + (tok,)) resolved[tok] = val return val for tok in defs: resolve(tok) overrides = data.get("ansi16", {}) ansi16 = {tok: parse_ansi16(overrides.get(tok, d["ansi16"])) for tok, d in defs.items()} return Theme( id=data.get("id", path.stem), name=data.get("name", path.stem), appearance=data.get("appearance", "dark"), background=term["background"].lower(), foreground=term["foreground"].lower(), cursor=(term.get("cursor") or None), selection_background=(term.get("selection_background") or None), ansi=ansi, palette=palette, tokens=resolved, ansi16=ansi16, raw=data, ) # ---------------------------------------------------------------- SGR def sgr(theme: Theme, fg: str | None, bg: str | None, attrs: tuple[str, ...] = (), depth: str = "truecolor") -> str: """Escape sequence for a cell style given token names. depth: truecolor | 256 | 16 | nocolor | none.""" if depth == "none": return "" if depth == "nocolor": # NO_COLOR emulation: keep attributes, drop every color; selection-style `reverse` # specs (16-color mode) survive as inverse so the cursor row stays visible. keep = list(attrs) for tok in (fg, bg): if tok and theme.ansi16[tok][0] == "reverse": keep.append("inverse") if tok: keep += [a for a in theme.ansi16[tok][1] if a in ("bold", "underline", "inverse", "italic", "strike")] return "\x1b[" + ";".join(["0"] + [str(SGR_ATTR[a]) for a in dict.fromkeys(keep)]) + "m" codes: list[str] = ["0"] extra_attrs: list[str] = list(attrs) reverse = False if depth == "16": if fg and theme.ansi16[fg][0] == "bg": # Text in the terminal background color on the fill: paint the fill as fg and reverse. extra_attrs += theme.ansi16[fg][1] fill = theme.ansi16[bg][0] if bg else "default" if isinstance(fill, int): codes.append(str(30 + fill if fill < 8 else 90 + fill - 8)) reverse = True fg = bg = None if fg: color, a = theme.ansi16[fg] extra_attrs += a if color == "reverse": reverse = True elif color != "default": codes.append(str(30 + color if color < 8 else 90 + color - 8)) if bg: color, a = theme.ansi16[bg] if color == "reverse": reverse = True elif color != "default": codes.append(str(40 + color if color < 8 else 100 + color - 8)) else: for tok, base in ((fg, 38), (bg, 48)): if not tok: continue h = theme.hex(tok) if depth == "256": codes.append(f"{base};5;{nearest256(h)}") else: r, g, b = hex_to_rgb(h) codes.append(f"{base};2;{r};{g};{b}") if reverse: extra_attrs.append("inverse") for a in dict.fromkeys(extra_attrs): codes.append(str(SGR_ATTR[a])) return "\x1b[" + ";".join(codes) + "m" RESET = "\x1b[0m"skills/tui-design/scripts/ansi_grid.py32 KBee174a36a76fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/ansi_render.py17 KBb94db93678e9upstream ↗
#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = [] # /// """ansi_render.py - render one ANSI frame as a themed terminal-window SVG / PNG / HTML. Parser: stdlib (_ansi.py, shared with ansi_grid.py). Theme: references/themes/<id>.json (ANSI 0-15, default fg/bg, cursor); indexes 16-255 are the xterm cube/greys; truecolor passes through. Layout is cell-exact: every narrow glyph gets its own x, wide (CJK/emoji) glyphs are centred over 2 cells, backgrounds are rects drawn first, so the grid never drifts with font metrics. Examples: python3 scripts/ansi_render.py frame.ansi --theme catppuccin-mocha --title myapp -o frame.svg uv run scripts/ansi_render.py frame.ansi --cols 120 --format png --scale 2 -o frame.png uv run scripts/ansi_render.py frame.ansi --format png --quantize --geometry frame.geo.json -o frame.png tmux -L NAME capture-pane -t PANE -p -e | python3 scripts/ansi_render.py - --no-chrome --format html -o frame.html Input must be ONE frame (capture-pane / capture_tui.sh / render_mockup.py output). Cursor movement and erase sequences are NOT emulated (skipped); a raw pty log of an interactive app is not a frame. Attribute fidelity: bold=font-weight 700; dim=fill-opacity .55; italic=font-style; reverse swaps painted fg/bg (default colours come from the theme); hidden=not drawn; blink=drawn static; underline / strike / overline are drawn as lines (underline colour from SGR 58 if set); double underline = two lines; CURLY underline is approximated by a small zigzag line; dotted/dashed (4:4, 4:5) render as a plain underline. Colour emoji are NOT supported by rsvg (monochrome silhouette or tofu); cursor is only drawn with --cursor. PNG needs the `rsvg-convert` binary. The package depends on the OS (macOS: `brew install librsvg`; Debian/Ubuntu: `apt install librsvg2-bin`; Fedora/RHEL: `dnf install librsvg2-tools`; Arch: `pacman -S librsvg`; Alpine: `apk add rsvg-convert`). The missing-binary error names the command for this machine. --quantize needs `pngquant`. Fonts: JetBrains Mono NL, falling back to Menlo, monospace (the grid stays exact either way). Exit: 0 ok, 2 usage/environment error (missing file, theme, binary). """ from __future__ import annotations import argparse import json import shutil import subprocess import sys from html import escape from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from _ansi import Resolver, parse_ansi # noqa: E402 from _theme import load_theme # noqa: E402 FONT = "'JetBrains Mono NL',Menlo,monospace" CHROME_FONT = "'SF Pro Text',Helvetica,sans-serif" DIM_OPACITY = 0.55 class Layout: def __init__(self, size: float, chrome: bool): self.size = size self.cw = size * 0.6 self.lh = round(size * 1.3) self.base = round(size * 0.93) self.px, self.pt, self.pb = 14, 8, 12 self.tb = 34 if chrome else 0 # title-bar height def x(self, col: float) -> float: return self.px + col * self.cw def top(self, row: int) -> float: return self.tb + self.pt + row * self.lh def runs(row, keyfn): """Merge horizontally adjacent cells with an equal non-None key -> (start_col, end_col_excl, key, cells).""" out, col, cur = [], 0, None for c in row: if not c.w: continue k = keyfn(c) if cur and k is not None and k == cur[2] and cur[1] == col: cur[1] = col + c.w cur[3].append((col, c)) else: cur = [col, col + c.w, k, [(col, c)]] if k is not None else None if cur: out.append(cur) col += c.w return out def n(v: float) -> str: return f"{v:.1f}".rstrip("0").rstrip(".") # Block elements drawn as exact rectangles (x, y, w, h as fractions of the cell): fonts leave seams between # adjacent glyphs (visible in browsers), rectangles tile perfectly. Shades (░▒▓) stay glyphs. BLOCKS = {"█": (0, 0, 1, 1), "▀": (0, 0, 1, .5), "▄": (0, .5, 1, .5), "▌": (0, 0, .5, 1), "▐": (.5, 0, .5, 1), "▔": (0, 0, 1, 1 / 8), "▕": (7 / 8, 0, 1 / 8, 1)} BLOCKS.update({ch: (0, 1 - k / 8, 1, k / 8) for k, ch in enumerate("▁▂▃▄▅▆▇", 1)}) BLOCKS.update({ch: (0, 0, k / 8, 1) for k, ch in enumerate("▏▎▍▌▋▊▉", 1)}) def render_svg(grid, theme, *, title="", chrome=True, size=14.0, font=FONT, cursor=None): """Return (svg_text, geometry_dict at scale 1).""" res, L = Resolver(theme), Layout(size, chrome) painted = {} # Style -> (fg, bg) def paint(c): s = c.style if s not in painted: painted[s] = res.painted(s) return painted[s] W = round(L.px * 2 + grid.cols * L.cw) H = L.tb + L.pt + grid.rows * L.lh + L.pb chrome_fg = theme.hex("border.default") o = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">', f'<rect width="{W}" height="{H}" rx="{10 if chrome else 0}" fill="{res.bg}"/>'] if chrome: o += [f'<circle cx="{cx}" cy="17" r="6" fill="{chrome_fg}"/>' for cx in (22, 42, 62)] if title: o.append(f'<text x="{n(W / 2)}" y="21" fill="{chrome_fg}" font-family="{CHROME_FONT}" font-size="12" ' f'text-anchor="middle">{escape(title, quote=False)}</text>') o.append(f'<g font-family="{font}" font-size="{n(size)}" xml:space="preserve">') lw = max(1, round(size / 14)) for y, row in enumerate(grid.cells): top = L.top(y) # 1. backgrounds (merged runs) for a, b, bg, _ in runs(row, lambda c: paint(c)[1]): o.append(f'<rect x="{n(L.x(a))}" y="{n(top)}" width="{n((b - a) * L.cw)}" height="{L.lh}" fill="{bg}"/>') # 2. text: narrow glyphs per-glyph x in runs of contiguous columns; wide / multi-codepoint glyphs alone def bkey(c): if c.w != 1 or c.ch not in BLOCKS or "hidden" in c.style.attrs: return None return (c.ch, paint(c)[0], "dim" in c.style.attrs) for a, b, (ch, fg, dim), _ in runs(row, bkey): # merged per glyph kind: no seams between cells fx, fy, fw, fh = BLOCKS[ch] op = ' fill-opacity="0.55"' if dim else "" if (fx, fw) == (0, 1): o.append(f'<rect x="{n(L.x(a))}" y="{n(top + fy * L.lh)}" width="{n((b - a) * L.cw)}" ' f'height="{n(fh * L.lh)}" fill="{fg}"{op}/>') else: for col in range(a, b): o.append(f'<rect x="{n(L.x(col) + fx * L.cw)}" y="{n(top + fy * L.lh)}" width="{n(fw * L.cw)}" ' f'height="{n(fh * L.lh)}" fill="{fg}"{op}/>') def tkey(c): s = c.style if c.w != 1 or len(c.ch) != 1 or "hidden" in s.attrs or c.ch == " " or c.ch in BLOCKS: return None # spaces end a run: browsers collapse them in SVG text return (paint(c)[0], "bold" in s.attrs, "italic" in s.attrs, "dim" in s.attrs) for a, b, key, cells in runs(row, tkey): if cells: xs = " ".join(n(L.x(col)) for col, _ in cells) o.append(f'<text x="{xs}" y="{n(top + L.base)}"{_tattrs(key)}>' f'{escape("".join(c.ch for _, c in cells), quote=False)}</text>') col = 0 for c in row: if c.w and (c.w == 2 or len(c.ch) > 1) and c.ch.strip() and "hidden" not in c.style.attrs: fg, s = paint(c)[0], c.style.attrs key = (fg, "bold" in s, "italic" in s, "dim" in s) cx = L.x(col) + c.w * L.cw / 2 o.append(f'<text x="{n(cx)}" y="{n(top + L.base)}" text-anchor="middle"{_tattrs(key)}>' f'{escape(c.ch, quote=False)}</text>') col += c.w # 3. line decorations def dkey(kind): def f(c): if kind not in c.style.attrs: return None return (res.hex(c.style.ul) or paint(c)[0], "dim" in c.style.attrs) return f for kind in ("underline", "double_underline", "curly_underline", "strike", "overline"): for a, b, (color, dim), _ in runs(row, dkey(kind)): o.append(_deco(kind, L.x(a), L.x(b), top, L, color, dim, lw)) if cursor: cx, cy = cursor if 0 <= cx < grid.cols and 0 <= cy < grid.rows: o.append(f'<rect x="{n(L.x(cx))}" y="{n(L.top(cy))}" width="{n(L.cw)}" height="{L.lh}" ' f'fill="{res.cursor}" fill-opacity="0.6"/>') o.append("</g></svg>") geo = {"cols": grid.cols, "rows": grid.rows, "cell_px": [L.cw, L.lh], "origin_px": [L.px, L.tb + L.pt], "width_px": W, "height_px": H, "scale": 1, "font_size": size, "theme": theme.id, "chrome": chrome} return "\n".join(o) + "\n", geo def _tattrs(key) -> str: fg, bold, italic, dim = key a = f' fill="{fg}"' if bold: a += ' font-weight="700"' if italic: a += ' font-style="italic"' if dim: a += f' fill-opacity="{DIM_OPACITY}"' return a def _deco(kind, x0, x1, top, L, color, dim, lw) -> str: op = f' stroke-opacity="{DIM_OPACITY}"' if dim else "" st = f'stroke="{color}" stroke-width="{lw}"{op} fill="none"' uy = top + L.base + 2 if kind == "underline": return f'<line x1="{n(x0)}" y1="{n(uy)}" x2="{n(x1)}" y2="{n(uy)}" {st}/>' if kind == "double_underline": return (f'<path d="M{n(x0)} {n(uy - 1.5)}H{n(x1)}M{n(x0)} {n(uy + 1)}H{n(x1)}" {st}/>') if kind == "strike": y = top + L.base - L.size * 0.3 return f'<line x1="{n(x0)}" y1="{n(y)}" x2="{n(x1)}" y2="{n(y)}" {st}/>' if kind == "overline": return f'<line x1="{n(x0)}" y1="{n(top + 1)}" x2="{n(x1)}" y2="{n(top + 1)}" {st}/>' pts, x, up = [], x0, True # curly: zigzag, half a cell per segment step = L.cw / 2 while x < x1 - 0.01: pts.append(f"{n(x)},{n(uy + (0.5 if up else 2.5))}") x, up = x + step, not up pts.append(f"{n(x1)},{n(uy + (0.5 if up else 2.5))}") return f'<polyline points="{" ".join(pts)}" {st}/>' # ---------------------------------------------------------------- output formats def to_html(svg: str, theme, title: str) -> str: return (f'<!doctype html>\n<html><head><meta charset="utf-8"><title>{escape(title or "ANSI frame")}</title>' f'<style>html,body{{margin:0;background:{theme.background}}}body{{padding:16px}}' f'svg{{display:block;max-width:100%;height:auto;margin:0 auto}}</style></head>\n<body>\n{svg}</body></html>\n') def need(binary: str, hint: str) -> str: path = shutil.which(binary) if not path: sys.exit(f"{binary} not found: {hint}") return path def _os_release_ids(text: str) -> set[str]: ids: set[str] = set() for line in text.splitlines(): if line.startswith(("ID=", "ID_LIKE=")): value = line.split("=", 1)[1].strip().strip("\"'") ids.update(part.lower() for part in value.replace(",", " ").split()) return ids # The binary is always rsvg-convert. These are the packages that provide it. _RSVG_PACKAGES = ( (frozenset({"debian", "ubuntu", "linuxmint", "pop", "raspbian", "kali"}), "apt install librsvg2-bin"), (frozenset({"fedora", "rhel", "centos", "rocky", "almalinux"}), "dnf install librsvg2-tools"), (frozenset({"arch", "manjaro", "endeavouros"}), "pacman -S librsvg"), (frozenset({"alpine"}), "apk add rsvg-convert"), ) _RSVG_ANY = ( "macOS: brew install librsvg; Debian/Ubuntu: apt install librsvg2-bin; " "Fedora/RHEL: dnf install librsvg2-tools; Arch: pacman -S librsvg; Alpine: apk add rsvg-convert" ) def rsvg_install_hint(platform: str | None = None, release_text: str | None = None) -> str: """Install command for the rsvg-convert binary on this OS. The binary name does not change.""" platform = sys.platform if platform is None else platform if platform == "darwin": return "brew install librsvg" if platform.startswith("linux"): if release_text is None: try: release_text = Path("/etc/os-release").read_text(encoding="utf-8") except OSError: release_text = "" ids = _os_release_ids(release_text) for keys, cmd in _RSVG_PACKAGES: if ids & keys: return cmd return _RSVG_ANY def to_png(svg: str, scale: float, quantize: bool) -> bytes: rsvg = need("rsvg-convert", rsvg_install_hint()) fc = shutil.which("fc-match") if fc: fam = subprocess.run([fc, "JetBrains Mono NL", "-f", "%{family}"], capture_output=True, text=True).stdout if "JetBrains" not in fam: print("warning: font 'JetBrains Mono NL' not installed; PNG falls back to Menlo/monospace " "(grid stays cell-exact, glyph shapes differ)", file=sys.stderr) r = subprocess.run([rsvg, "-z", str(scale), "-f", "png"], input=svg.encode(), capture_output=True) if r.returncode: sys.exit(f"rsvg-convert failed: {r.stderr.decode(errors='replace').strip()}") png = r.stdout if quantize: pq = need("pngquant", "brew install pngquant") q = subprocess.run([pq, "--quality", "90-100", "--speed", "1", "-"], input=png, capture_output=True) if q.returncode == 0: png = q.stdout else: print("warning: pngquant could not reach quality 90-100; keeping unquantized PNG", file=sys.stderr) return png def main(argv=None) -> int: ap = argparse.ArgumentParser(description="Render one ANSI frame as a themed terminal-window SVG/PNG/HTML.", epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("input", help="ANSI file, or - for stdin") ap.add_argument("--theme", default="catppuccin-mocha", help="theme id or path (default catppuccin-mocha)") ap.add_argument("--cols", type=int, help="force grid width (pad/crop); default = longest line") ap.add_argument("--rows", type=int, help="force grid height (pad/crop); default = line count") ap.add_argument("--title", help="window title in the chrome (default: input file stem)") ap.add_argument("--no-chrome", action="store_true", help="no title bar / dots (tight image)") ap.add_argument("--format", choices=("svg", "png", "html"), help="default: from -o extension, else svg") ap.add_argument("--scale", type=float, default=2, help="PNG zoom factor (default 2)") ap.add_argument("--quantize", action="store_true", help="PNG: pngquant --quality 90-100") ap.add_argument("--size", type=float, default=14, help="font size in px (default 14; cell = 0.6em x 1.3em)") ap.add_argument("--font", default=FONT, help=f"SVG font-family (default {FONT})") ap.add_argument("--cursor", metavar="COL,ROW", help="draw a cursor block at this 0-based cell") ap.add_argument("--geometry", metavar="OUT.json", help="write cell geometry sidecar (cell_px, origin_px, cols, rows)") ap.add_argument("-o", "--out", help="output file (default stdout)") a = ap.parse_args(argv) try: theme = load_theme(a.theme) text = sys.stdin.read() if a.input == "-" else Path(a.input).read_text(encoding="utf-8", errors="replace") except (OSError, FileNotFoundError, ValueError, KeyError) as e: print(f"error: {e}", file=sys.stderr) return 2 fmt = a.format or (Path(a.out).suffix.lstrip(".").lower() if a.out else "svg") if fmt not in ("svg", "png", "html"): print(f"error: unknown format {fmt!r} (svg|png|html)", file=sys.stderr) return 2 cursor = tuple(int(v) for v in a.cursor.split(",")) if a.cursor else None title = a.title if a.title is not None else (Path(a.input).stem if a.input != "-" else "") grid = parse_ansi(text, a.cols, a.rows) svg, geo = render_svg(grid, theme, title=title, chrome=not a.no_chrome, size=a.size, font=a.font, cursor=cursor) try: if fmt == "png": data = to_png(svg, a.scale, a.quantize) geo.update(scale=a.scale, cell_px=[geo["cell_px"][0] * a.scale, geo["cell_px"][1] * a.scale], origin_px=[v * a.scale for v in geo["origin_px"]], width_px=round(geo["width_px"] * a.scale), height_px=round(geo["height_px"] * a.scale)) else: data = (to_html(svg, theme, title) if fmt == "html" else svg).encode() except SystemExit as e: print(f"error: {e.code}", file=sys.stderr) return 2 if a.out: Path(a.out).write_bytes(data) else: sys.stdout.buffer.write(data) if a.geometry: Path(a.geometry).write_text(json.dumps(geo, indent=2) + "\n") return 0 if __name__ == "__main__": sys.exit(main())skills/tui-design/scripts/capture_tui.sh15 KB3768be2ed606upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/check_versions.py10 KB8fe7fa1f0532upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/compare.py17 KB5e78dfcf1359upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/contrast_check.py8.2 KB963cc13885dfupstream ↗
#!/usr/bin/env python3 """WCAG contrast floors (contract section 3) for one, many or all themes. Examples: python3 contrast_check.py catppuccin-mocha python3 contrast_check.py --all --format json python3 contrast_check.py --all --depth 16 # resolve ansi16 specs against terminal.ansi python3 contrast_check.py path/to/theme.json Floors (ratio vs bg.base unless noted): fg.default >= 4.5 required (7 preferred, advisory); fg.muted >= 4.5; fg.faint >= 3; status.{error,warning,success,info}, accent.primary, keyhint.key, link >= 4.5; border.focus >= 3; selection.fg on selection.bg >= 4.5; fg.on-accent on accent.primary and on each status.* >= 4.5. Advisory (reported as `advisory`, never change the exit code; JSON rows carry "advisory": true): fg.default (7 preferred); text on the selected row, i.e. fg.default, fg.muted, status.*, accent.primary on selection.bg >= 4.5 and fg.faint on selection.bg >= 3; fg.on-accent on tab.active.bg >= 4.5 when the theme fills the active tab (tab.active.bg differs from bg.base; at --depth 16 only when its ansi16 spec is not `default`); FS-09: contrast of border.focus at least 1.5x that of border.default (one focus indicator). --depth 16: a token becomes terminal.ansi[N] / terminal fg|bg (default); `dim` = blend(fg, bg, 0.55); `reverse` (or the inverse attribute) swaps the pair. Bold-as-bright is not modelled. Exit 0 = every required floor passes; 1 = a required floor fails; 2 = usage error. """ from __future__ import annotations import argparse import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from _theme import Theme, blend, contrast_ratio, list_themes, load_theme # noqa: E402 STATUS = ["status.error", "status.warning", "status.success", "status.info"] # (check name, fg token, bg token, floor, required) CHECKS: list[tuple[str, str, str, float, bool]] = ( [("fg.default", "fg.default", "bg.base", 4.5, True), ("fg.default (preferred)", "fg.default", "bg.base", 7.0, False), ("fg.muted", "fg.muted", "bg.base", 4.5, True), ("fg.faint", "fg.faint", "bg.base", 3.0, True)] + [(t, t, "bg.base", 4.5, True) for t in STATUS] + [("accent.primary", "accent.primary", "bg.base", 4.5, True), ("keyhint.key", "keyhint.key", "bg.base", 4.5, True), ("link", "link", "bg.base", 4.5, True), ("border.focus", "border.focus", "bg.base", 3.0, True), ("selection.fg on selection.bg", "selection.fg", "selection.bg", 4.5, True), ("fg.on-accent on accent.primary", "fg.on-accent", "accent.primary", 4.5, True)] + [(f"fg.on-accent on {t}", "fg.on-accent", t, 4.5, True) for t in STATUS] + [("fg.default on selection.bg", "fg.default", "selection.bg", 4.5, False), ("fg.muted on selection.bg", "fg.muted", "selection.bg", 4.5, False), ("fg.faint on selection.bg", "fg.faint", "selection.bg", 3.0, False)] + [(f"{t} on selection.bg", t, "selection.bg", 4.5, False) for t in STATUS] + [("accent.primary on selection.bg", "accent.primary", "selection.bg", 4.5, False)] ) TAB_CHECK = ("fg.on-accent on tab.active.bg", "fg.on-accent", "tab.active.bg", 4.5, False) def tab_is_filled(theme: Theme, depth: str) -> bool: """True when the active tab is painted on a fill of its own (not the base background).""" if depth == "16": return theme.ansi16["tab.active.bg"][0] != "default" return theme.hex("tab.active.bg") != theme.hex("bg.base") def resolve_pair(theme: Theme, fg_tok: str, bg_tok: str, depth: str) -> tuple[str, str]: """Effective (fg hex, bg hex) of a cell drawn with fg_tok on bg_tok.""" if depth != "16": return theme.hex(fg_tok), theme.hex(bg_tok) fcol, fattrs = theme.ansi16[fg_tok] bcol, _ = theme.ansi16[bg_tok] def hexof(col, default): return default if col in ("default", "reverse", "bg") else theme.ansi[col] if fcol == "bg": # text in terminal bg on the fill (drawn as fill-slot + reverse) fill = theme.ansi[bcol] if isinstance(bcol, int) else theme.foreground fg = theme.background return (blend(fg, fill, 0.55) if "dim" in fattrs else fg), fill fg, bg = hexof(fcol, theme.foreground), hexof(bcol, theme.background) if fcol == "reverse" or bcol == "reverse" or "inverse" in fattrs: fg, bg = bg, fg if "dim" in fattrs: fg = blend(fg, bg, 0.55) return fg, bg def run_theme(arg: str, depth: str) -> list[dict]: try: th = load_theme(arg) except (FileNotFoundError, ValueError, KeyError, OSError) as e: return [{"theme": Path(arg).stem, "check": "load", "fg": "", "bg": "", "fg_hex": "", "bg_hex": "", "ratio": 0.0, "floor": 0.0, "pass": False, "required": True, "advisory": False, "error": str(e)}] rows = [] checks = CHECKS + ([TAB_CHECK] if tab_is_filled(th, depth) else []) for name, ft, bt, floor, required in checks: fh, bh = resolve_pair(th, ft, bt, depth) ratio = contrast_ratio(fh, bh) rows.append({"theme": th.id, "check": name, "fg": ft, "bg": bt, "fg_hex": fh, "bg_hex": bh, "ratio": round(ratio, 2), "floor": floor, "pass": ratio >= floor, "required": required, "advisory": not required}) # FS-09 (advisory): the focused border must stand out from inactive borders — # ratio = contrast(border.focus) / contrast(border.default), both against bg.base. ff, fb = resolve_pair(th, "border.focus", "bg.base", depth) df, db = resolve_pair(th, "border.default", "bg.base", depth) rel = contrast_ratio(ff, fb) / contrast_ratio(df, db) rows.append({"theme": th.id, "check": "border.focus vs border.default (FS-09, x)", "fg": "border.focus", "bg": "border.default", "fg_hex": ff, "bg_hex": df, "ratio": round(rel, 2), "floor": 1.5, "pass": rel >= 1.5, "required": False, "advisory": True}) return rows def to_markdown(rows: list[dict], depth: str) -> str: out = [f"Contrast floors, depth={depth} (WCAG 2.x ratio)", "", "| theme | check | fg | bg | ratio | floor | pass |", "|---|---|---|---|---|---|---|"] for r in rows: if r["check"] == "load": out.append(f"| {r['theme']} | load | | | | | FAIL: {r['error']} |") continue verdict = "ok" if r["pass"] else ("FAIL" if r["required"] else "advisory") out.append(f"| {r['theme']} | {r['check']} | {r['fg']} {r['fg_hex']} | {r['bg']} {r['bg_hex']} " f"| {r['ratio']:.2f} | {r['floor']:g} | {verdict} |") themes = sorted({r["theme"] for r in rows}) out += ["", "Summary:"] for t in themes: tr = [r for r in rows if r["theme"] == t] fails = [r["check"] for r in tr if not r["pass"] and r["required"]] warns = [r["check"] for r in tr if not r["pass"] and not r["required"]] line = f"- {t}: {sum(r['pass'] for r in tr)}/{len(tr)} pass" if fails: line += "; FAIL: " + ", ".join(fails) if warns: line += "; advisory below floor: " + ", ".join(warns) out.append(line) return "\n".join(out) + "\n" def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description="Check contract section 3 contrast floors for themes.", epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("themes", nargs="*", help="theme ids or paths to theme .json") ap.add_argument("--all", action="store_true", help="every theme in references/themes/") ap.add_argument("--depth", choices=["truecolor", "16"], default="truecolor") ap.add_argument("--format", choices=["md", "json"], default="md") ap.add_argument("-o", "--out", help="write here instead of stdout") a = ap.parse_args(argv) names = list_themes() if a.all else a.themes if not names: ap.error("give one or more theme ids, or --all") rows: list[dict] = [] for n in sorted(dict.fromkeys(names)): rows += run_theme(n, a.depth) text = (json.dumps({"depth": a.depth, "results": rows}, indent=2) + "\n") if a.format == "json" \ else to_markdown(rows, a.depth) if a.out: Path(a.out).write_text(text, encoding="utf-8") else: sys.stdout.write(text) return 1 if any(not r["pass"] and r["required"] for r in rows) else 0 if __name__ == "__main__": sys.exit(main())skills/tui-design/scripts/describe_prompt.py21 KB084e29048b67upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/description_to_mock.py21 KB0c45e6f9cc44upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/export_theme.py16 KBcada0532db35upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/gallery.py29 KB8ae514f6d557upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/key_probe.py5.3 KB08e4ff9fc3b5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/merge_description.py44 KBb548ad11db15upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/mockkit.py86 KB55b0449b2a1fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/play_mock.py6.2 KB1cf066e3f2d6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/prep_screenshot.py40 KBd3b5e0884086upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/preview_theme.py7.3 KBc6a461d159f6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/render_mockup.py12 KB05fd2c2c5183upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/sample_colors.py15 KBa4f1bb2ff96dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/score_description.py29 KBd6890bd416ceupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/scripts/test_card.py11 KB664abf1857b1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/accessibility.md26 KB2f66f522f647upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/a-dashboard.md2.5 KBc223883d000dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/b-list-detail.md2.3 KB5ca8a9a5318cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/c-miller-columns.md2.1 KB424627440942upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/d-editor.md2.3 KB54c5c931f8c6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/e-log-viewer.md2.7 KBd792e66d3330upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/f-form-wizard.md7.1 KB3d8d001a7d84upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/g-command-palette.md2.7 KB6f9a3804dbdfupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/h-tree-browser.md2.4 KB870accf91a12upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/i-table-explorer.md2.9 KB3599128fc6b1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/j-inline-picker.md4.8 KB43e34c923402upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/archetypes/k-chat-session.md9.1 KBf5336db67169upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/audit-checklist.md36 KB3ef324dac90bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/audit-protocol.md33 KB5ae0de76266bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/audit-quick.md17 KB1de0967020c4upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/cli-contract.md25 KBfc7c02487400upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/color-schemes.md14 KBd642c04fe0adupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/color-tokens.md26 KBaf0e0159060eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/exemplars.md23 KB993d3662cf0aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/formats.md15 KBad7cef7c673cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/frameworks/bubbletea.md40 KB23916524b26aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/frameworks/choosing.md14 KBd1ba535ca82dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/frameworks/gum.md30 KB09ed2b8bf694upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/frameworks/ink.md37 KB95eda8c1be7dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/frameworks/ratatui.md38 KB7d2a2610a180upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/frameworks/textual.md35 KBaa93d61d570aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/glyph-data.md10 KBcfe31618e805upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/interaction.md28 KBa323c5249d3aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/layout-archetypes.md28 KB04318a8fa1d5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/lifecycle.md15 KB38d5087fa79fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/mockkit-api.md17 KBff4c14c75586upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/mockkit.md15 KBd7f6f7465b65upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/prompts/describe-tui.md26 KB2c2021848962upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemas/tui-description.schema.json25 KB9a1b8d2f8a92upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/catppuccin.md20 KB041905b0dbbaupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/dracula.md14 KB9c724767c484upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/everforest.md13 KBcbb3e0834ed3upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/gruvbox.md14 KBa27d2dfd9970upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/kanagawa.md18 KB0826f38bc3afupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/nord.md10 KB7beaca95f3a8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/onedark.md14 KB793aad830cdcupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/rose-pine.md16 KB5506db8fd510upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/solarized.md14 KBb67a9b27383fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/schemes/tokyonight.md20 KBa1adc6b53bd7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/templates/audit-report.md9.7 KB2955a4c26b8fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/templates/design-system.md18 KB4da77346e8f8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/terminal-capabilities.md25 KB479acedaee77upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/terminal-escapes.md16 KBd92465bf4a1eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/_tokens.json8.3 KBf176e9a3d35fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/catppuccin-frappe.json6.5 KBe2f69c486272upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/catppuccin-latte.json6.9 KB6798e504e305upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/catppuccin-macchiato.json6.5 KB02ec4427b285upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/catppuccin-mocha.json6.7 KBb6349115fb26upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/dracula-alucard.json6.3 KB82797227d32bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/dracula-classic.json6.1 KBe5db68565029upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/everforest-dark.json5.9 KBb29fbdcbc031upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/everforest-light.json6.5 KB4c7b12bba442upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/gruvbox-dark.json7.5 KB0d803138d1d7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/gruvbox-light.json7.9 KB8c656ffd1435upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/kanagawa-dragon.json5.3 KB90b2e26d3f9aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/kanagawa-lotus.json6.3 KB754d003a358eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/kanagawa-wave.json5.6 KBb7ceba2cbafaupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/nord-dark.json6.3 KB26e2efa1547bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/onedark-dark.json5.7 KB41e11eecd978upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/onedark-light.json5.6 KB8c5f2162d4feupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/rose-pine-dawn.json7.6 KB4d29ada171caupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/rose-pine-main.json7.1 KBeb753c055ef0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/rose-pine-moon.json7.1 KBadc964e5ab1aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/solarized-dark.json5.7 KBc352c3c66580upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/solarized-light.json5.0 KBcb58d889232eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/tokyonight-day.json7.5 KB24a58ef8cdfdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/tokyonight-moon.json7.1 KBfcb38d444163upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/tokyonight-night.json7.3 KB8c5dd2f3d551upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/themes/tokyonight-storm.json7.5 KB188d3a967383upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/tools.md3.5 KBc60d29bf7253upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/visual-craft.md27 KBf0ed63ea5a7fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/visual-vocabulary.md30 KBf0a91356bd3aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/references/vocabulary.md33 KBf44128756075upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/demo/fleet--normal--80x24.mock5.9 KB0da67fcfdb8bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/chat/session--busy--80x24.mock3.6 KB3fb828cb6f8cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/chat/session--empty--80x24.mock2.5 KB204f9d7af04cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/chat/session--normal--120x30.mock6.4 KB09ec6023705bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/chat/session--normal--80x24.mock3.6 KB992dd98527deupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/command-palette/palette--empty--80x24.mock7.2 KB719b38a710e9upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/command-palette/palette--normal--120x30.mock12 KB029f4bb2b1f9upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/command-palette/palette--normal--80x24.mock7.3 KBb24e4ea65ff5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/dashboard/sysmon--error--80x24.mock7.6 KB56de3fec83cdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/dashboard/sysmon--normal--120x30.mock12 KB8c23f76c20edupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/dashboard/sysmon--normal--80x24.mock8.7 KBace65cc8c78eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/dashboard/sysmon--toosmall--60x18.mock813 Beabe56f6fe7fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/editor/code--error--80x24.mock3.2 KB91c1ba846444upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/editor/code--normal--120x30.mock8.7 KBd3560244cfc1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/editor/code--normal--80x24.mock6.7 KB93778adb3759upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/form-wizard/setup--error--80x24.mock3.4 KB463b31a744e8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/form-wizard/setup--normal--120x30.mock10 KB313392e85e69upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/form-wizard/setup--normal--80x24.mock3.5 KB13ecdddf60baupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/list-detail/prs--empty--80x24.mock4.9 KB1af0f6b971f8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/list-detail/prs--normal--120x30.mock9.4 KB52db56403c79upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/list-detail/prs--normal--80x24.mock6.6 KB643065f49c36upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/log-viewer/stream--empty--80x24.mock2.6 KBccc042b57acdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/log-viewer/stream--normal--120x30.mock8.3 KB4891f7b61593upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/log-viewer/stream--normal--80x24.mock5.4 KB80e9b87b8d50upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/miller-columns/files--error--80x24.mock4.1 KB4f38e0c8fe77upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/miller-columns/files--normal--120x30.mock8.2 KB167aaf9803caupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/miller-columns/files--normal--80x24.mock5.6 KBa288d313f35dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/table-explorer/pods--error--80x24.mock5.0 KB9baabbf4a4e7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/table-explorer/pods--normal--120x30.mock7.8 KB2fb34013ad29upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/table-explorer/pods--normal--80x24.mock5.3 KBbdcf2a193a27upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/tree-browser/diskusage--busy--80x24.mock6.4 KB2941ed01d6fdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/tree-browser/diskusage--normal--120x30.mock12 KB5dd435e84e24upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/mockups/tree-browser/diskusage--normal--80x24.mock7.0 KB7c1c4e59c129upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/capture.sh1.9 KB69b6ef74b295upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/data.go2.1 KBde49ae8ccc54upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/go.mod919 B2ee6647c3d27upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/go.sum3.7 KBb5f3a13c0329upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/main.go3.1 KBcb92ada96f0bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/theme.go6.7 KB555de8f198e3upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/theme.json3.0 KBd43582312b64upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/bubbletea/view.go6.9 KB442bb5e5fb32upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/gum/capture.sh2.4 KBbaba1c86c339upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/gum/fleet-flow.sh1.3 KBce5c9fc512ecupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/gum/fleet-static.sh5.5 KBbb692d7e2fd7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/gum/lib.sh3.6 KB6f69ee7fc83aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/gum/theme.json3.0 KBd43582312b64upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/.gitignore14 Bc2658d7d1b31upstream ↗
node_modules/skills/tui-design/assets/proto-starters/ink/capture.sh1.8 KBfabceff79ad5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/package.json566 B9a7760a508c3upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/src/App.tsx7.7 KBccd970b5e292upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/src/cli.tsx4.3 KB4f95c1478552upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/src/data.ts2.3 KBa0af6394e367upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/src/theme.ts4.2 KB12bcd2825872upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/theme.json3.0 KBd43582312b64upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ink/tsconfig.json296 B37ebfa2a6378upstream ↗
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "jsx": "react-jsx", "strict": true, "noEmit": true, "allowImportingTsExtensions": true, "skipLibCheck": true, "resolveJsonModule": true }, "include": ["src"] }skills/tui-design/assets/proto-starters/ratatui/capture.sh2.1 KBc151d44d5e78upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/Cargo.toml309 Bb3d0602e98b2upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/src/ansi.rs4.2 KB606e1a463ed7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/src/data.rs3.0 KB2653456273c0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/src/main.rs3.8 KB8e163aeb4910upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/src/theme.rs6.7 KB6f746e9f44afupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/src/ui.rs8.1 KBd928385f5769upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/ratatui/theme.json3.0 KBd43582312b64upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/.gitignore28 B7e20f52a0f3bupstream ↗
.venv/ __pycache__/ uv.lockskills/tui-design/assets/proto-starters/textual/capture.sh1.8 KB7f94a7517965upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/fleet/__init__.py47 B5bf1af604bb8upstream ↗
"""Fleet: tui-design Textual proto-starter."""skills/tui-design/assets/proto-starters/textual/fleet/__main__.py2.1 KBbd4be9782765upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/fleet/app.py7.9 KBbfcf86777780upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/fleet/app.tcss1.2 KB1ed48472b5b9upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/fleet/data.py1.8 KB93fb4d7b4413upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/fleet/theme.py5.7 KBb56c5e493bc4upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/pyproject.toml453 Bff2e630a8e66upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/proto-starters/textual/theme.json3.0 KBd43582312b64upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/test-card/curses--reference.png61 KBcd2b58463e7fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/tui-design/assets/test-card/raw--reference.png54 KB1520484764fdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/diegomarino-tui-design-skills-tui-design.md