Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Color homepage command comparison (#3939)
Maximilian Roosd6300f1c1bc1
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex e41088780..6c07401bd 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -52,7 +52,7 @@ View changes: http://127.0.0.1:<port>| `src/pages/index.astro` | Homepage route; renders the canonical `worktrunk.md` body || `src/styles/custom.css` | Worktrunk's visual system and narrow Starlight adjustments || `src/plugins/stable-heading-ids.mjs` | Stable public anchor IDs for Markdown headings |-| `src/plugins/worktrunk-terminal.mjs` | Shell syntax, prompts, copy behavior, Clap help roles, and ANSI-derived output styling |+| `src/plugins/worktrunk-terminal.mjs` | Shell syntax, homepage comparison roles, prompts, copy behavior, Clap help roles, and ANSI-derived output styling || `src/themes/worktrunk-code.mjs` | Light and dark syntax themes for source and command blocks || `src/generated/terminal-styles.json` | Generated site-only span styles from ANSI command snapshots || `src/components/Head.astro` | Social metadata, structured data, and analytics |diff --git a/docs/astro.config.mjs b/docs/astro.config.mjsindex a0c3e99d7..cc079b07b 100644--- a/docs/astro.config.mjs+++ b/docs/astro.config.mjs@@ -8,7 +8,10 @@ import { rehypeResponsiveTables } from './src/plugins/responsive-tables.mjs';import { rehypeStableHeadingIds } from './src/plugins/stable-heading-ids.mjs';import { sidebar } from './src/site-navigation.mjs';import { sitemapCompatibility } from './src/plugins/sitemap-compatibility.mjs';-import { pluginWorktrunkTerminal } from './src/plugins/worktrunk-terminal.mjs';+import {+ pluginWorktrunkTerminal,+ rehypeComparisonCommands,+} from './src/plugins/worktrunk-terminal.mjs';import {worktrunkDarkCodeTheme,worktrunkLightCodeTheme,@@ -27,6 +30,7 @@ export default defineConfig({rehypePlugins: [rehypeStableHeadingIds,rehypePagefindCommandReferences,+ rehypeComparisonCommands,rehypeResponsiveTables,],}),diff --git a/docs/package-lock.json b/docs/package-lock.jsonindex 9a0636126..868505a2a 100644--- a/docs/package-lock.json+++ b/docs/package-lock.json@@ -10,7 +10,8 @@"@astrojs/sitemap": "^3.7.3","@astrojs/starlight": "^0.41.7","@expressive-code/core": "^0.44.1",- "astro": "^7.2.4"+ "astro": "^7.2.4",+ "hast-util-from-html": "^2.0.3"},"devDependencies": {"@astrojs/check": "^0.9.10",diff --git a/docs/package.json b/docs/package.jsonindex 876ae41f9..f0f430f1a 100644--- a/docs/package.json+++ b/docs/package.json@@ -16,7 +16,8 @@"@astrojs/sitemap": "^3.7.3","@astrojs/starlight": "^0.41.7","@expressive-code/core": "^0.44.1",- "astro": "^7.2.4"+ "astro": "^7.2.4",+ "hast-util-from-html": "^2.0.3"},"devDependencies": {"@astrojs/check": "^0.9.10",diff --git a/docs/src/plugins/worktrunk-terminal.mjs b/docs/src/plugins/worktrunk-terminal.mjsindex aa15de7bf..d706ea974 100644--- a/docs/src/plugins/worktrunk-terminal.mjs+++ b/docs/src/plugins/worktrunk-terminal.mjs@@ -1,3 +1,5 @@+import { fromHtml } from 'hast-util-from-html';+import terminalStyles from '../generated/terminal-styles.json' with { type: 'json' };const terminalBlocks = new WeakMap();@@ -18,6 +20,16 @@ function addClass(node, className) {: [classes, className];}+function classNames(node) {+ const classes = node.properties?.className ?? [];+ return Array.isArray(classes) ? classes : String(classes).split(/\s+/u).filter(Boolean);+}++function nodeText(node) {+ if (node.type === 'text') return node.value;+ return node.children?.map(nodeText).join('') ?? '';+}+function findCodeElement(node) {if (node?.type === 'element'@@ -124,6 +136,96 @@ function appendSegment(segments, text, tone) {}}+/** Split a shell recipe into the syntax roles used by the site code theme. */+export function shellCommandSegments(text) {+ const segments = [];+ const tokens = /(?<space>\s+)|(?<operator>&&|\\)|(?<word>[^\s&\\]+)/gu;+ let cursor = 0;+ let expectCommand = true;++ for (const match of text.matchAll(tokens)) {+ appendSegment(segments, text.slice(cursor, match.index));+ const token = match[0];+ if (match.groups.space) {+ appendSegment(segments, token);+ if (token.includes('\n')) expectCommand = true;+ cursor = match.index + token.length;+ continue;+ }+ if (match.groups.operator) {+ appendSegment(segments, token);+ if (token === '&&') expectCommand = true;+ cursor = match.index + token.length;+ continue;+ }++ const tone = expectCommand+ ? 'command'+ : /^--?[A-Za-z0-9]/u.test(token)+ ? 'option'+ : 'argument';+ appendSegment(segments, token, tone);+ expectCommand = false;+ cursor = match.index + token.length;+ }+ appendSegment(segments, text.slice(cursor));++ return segments;+}++function renderShellCommand(code) {+ code.children = shellCommandSegments(nodeText(code)).map(({ text: value, tone }) => tone+ ? {+ type: 'element',+ tagName: 'span',+ properties: { className: [`wt-shell-${tone}`] },+ children: [{ type: 'text', value }],+ }+ : { type: 'text', value });+}++/** Add build-only shell syntax roles to the homepage command comparison. */+export function rehypeComparisonCommands() {+ return (tree) => {+ function decorate(node, insideComparison = false) {+ const comparison = insideComparison || (+ node.type === 'element'+ && node.tagName === 'table'+ && classNames(node).includes('cmd-compare')+ );+ if (comparison && node.type === 'element' && node.tagName === 'code') {+ renderShellCommand(node);+ return;+ }+ node.children?.forEach((child) => decorate(child, comparison));+ }++ function expandRawComparisons(node) {+ for (let index = 0; index < (node.children?.length ?? 0); index += 1) {+ const child = node.children[index];+ if (child.type === 'raw' && child.value.includes('cmd-compare')) {+ const fragment = fromHtml(child.value, { fragment: true });+ const comparison = fragment.children.find((candidate) => (+ candidate.type === 'element'+ && candidate.tagName === 'table'+ && classNames(candidate).includes('cmd-compare')+ ));+ if (comparison) {+ decorate(comparison);+ node.children.splice(index, 1, ...fragment.children);+ index += fragment.children.length - 1;+ continue;+ }+ }+ expandRawComparisons(child);+ }+ }++ decorate(tree);+ expandRawComparisons(tree);+ };+}+function helpInlineSegments(text) {const segments = [];const tokenPattern = /\[[^\]\n]+:\s*[^\]\n]+\]|\[experimental\]|--[a-z0-9][a-z0-9-]*(?:\.\.\.)?|(?<![\w-])-[A-Za-z](?=[,\s]|$)|<[^>\n]+>(?:\.\.\.)?|\[[A-Z][A-Z0-9_-]*\](?:\.\.\.)?/gu;diff --git a/docs/src/styles/custom.css b/docs/src/styles/custom.cssindex 2d99353f2..3ac6c8afa 100644--- a/docs/src/styles/custom.css+++ b/docs/src/styles/custom.css@@ -21,8 +21,9 @@--wt-terminal-gutter: #a8a29e;--wt-terminal-ink: #403a35;--wt-terminal-dim: #756b62;- --wt-code-command: #9b6500;- --wt-code-string: #527a16;+ --wt-code-command: #8a5a00;+ --wt-code-string: #4a6e14;+ --wt-code-flag: #a03c15;--wt-code-option: #1d4ed8;--wt-focus: var(--wt-copper);--wt-font-display: 'Newsreader', ui-serif, 'Iowan Old Style', 'Palatino Linotype', Palatino,@@ -75,6 +76,7 @@--wt-terminal-dim: #9f9488;--wt-code-command: #e5b567;--wt-code-string: #a3be8c;+ --wt-code-flag: #e09a82;--wt-code-option: #93c5fd;--sl-color-accent-low: var(--wt-gold-wash);--sl-color-accent: var(--wt-copper);@@ -394,13 +396,17 @@ header.header {.sl-markdown-content .cmd-compare th:nth-child(2),.sl-markdown-content .cmd-compare td:nth-child(2) {- background: color-mix(in srgb, var(--wt-gold) 7%, transparent);+ background: color-mix(in srgb, var(--wt-gold) 7%, var(--wt-paper));}.sl-markdown-content .cmd-compare tbody tr + tr {border-block-start: 1px solid var(--wt-line);}+.sl-markdown-content .cmd-compare tbody td {+ background: var(--wt-paper);+}+.sl-markdown-content .cmd-compare tbody td:first-child {color: var(--wt-ink-muted);font-weight: 600;@@ -427,6 +433,19 @@ header.header {white-space: pre-wrap;}+.sl-markdown-content .cmd-compare .wt-shell-command {+ color: var(--wt-code-command);+ font-weight: 700;+}++.sl-markdown-content .cmd-compare .wt-shell-argument {+ color: var(--wt-code-string);+}++.sl-markdown-content .cmd-compare .wt-shell-option {+ color: var(--wt-code-flag);+}+@media (max-width: 44rem) {.sl-markdown-content .cmd-compare:not(:where(.not-content *)) {overflow: visible;diff --git a/docs/tests/browser-site.test.mjs b/docs/tests/browser-site.test.mjsindex 9c10c2b1c..23e07fa91 100644--- a/docs/tests/browser-site.test.mjs+++ b/docs/tests/browser-site.test.mjs@@ -231,6 +231,42 @@ test('code artifacts keep their visual hierarchy in both themes', async () => {assert.ok(ratio >= 4.5, `${theme} shell token ${text} contrast is ${ratio.toFixed(2)}:1`);}+ await page.goto(baseUrl + '/', { waitUntil: 'domcontentloaded' });+ await page.evaluate((selectedTheme) => {+ document.documentElement.dataset.theme = selectedTheme;+ }, theme);+ const comparisonStyles = await page.evaluate(() => {+ const table = document.querySelector('.cmd-compare');+ return {+ text: table.textContent,+ tokens: [...table.querySelectorAll('[class^="wt-shell-"]')].map((span) => {+ const cell = span.closest('td');+ return {+ role: [...span.classList].find((name) => name.startsWith('wt-shell-'))+ .replace('wt-shell-', ''),+ color: getComputedStyle(span).color,+ background: getComputedStyle(cell).backgroundColor,+ };+ }),+ };+ });+ assert.match(comparisonStyles.text, /wt switch -c -x claude feat/);+ assert.match(comparisonStyles.text, /git worktree add -b feat \.\.\/repo\.feat/);+ const roleColors = new Map(comparisonStyles.tokens.map(({ role, color }) => [role, color]));+ assert.equal(roleColors.size, 3, `${theme} comparison is missing a syntax role`);+ assert.equal(+ new Set(roleColors.values()).size,+ roleColors.size,+ theme + ' comparison syntax roles collapse to the same color',+ );+ for (const { role, color, background } of comparisonStyles.tokens) {+ const ratio = contrastRatio(color, background);+ assert.ok(+ ratio >= 4.5,+ theme + ' comparison ' + role + ' contrast is ' + ratio.toFixed(2) + ':1',+ );+ }+await page.goto(`${baseUrl}/list/`, { waitUntil: 'domcontentloaded' });await page.evaluate((selectedTheme) => {document.documentElement.dataset.theme = selectedTheme;diff --git a/docs/tests/built-site.test.mjs b/docs/tests/built-site.test.mjsindex e5d10d5c8..44ca2b555 100644--- a/docs/tests/built-site.test.mjs+++ b/docs/tests/built-site.test.mjs@@ -165,11 +165,17 @@ test('build preserves the public route contract', async () => {);assert.match(homepage, /<img src="\/assets\/docs\/light\/wt-core\.gif"/);assert.equal(homepage.match(/<h1\b/g)?.length, 1);- assert.match(homepage, /<pre><code>git worktree add -b feat \.\.\/repo\.feat && \\\ncd \.\.\/repo\.feat && \\\nclaude<\/code><\/pre>/);+ assert.match(+ homepage,+ /<pre[^>]*><code><span class="wt-shell-command">git<\/span> <span class="wt-shell-argument">worktree<\/span> <span class="wt-shell-argument">add<\/span> <span class="wt-shell-option">-b<\/span>/,+ );const comparison = homepage.match(/<table class="cmd-compare">([\s\S]*?)<\/table>/)?.[1];assert.ok(comparison, 'homepage is missing the command comparison table');assert.equal(comparison.match(/<td data-label="Worktrunk">/g)?.length, 4);assert.equal(comparison.match(/<td data-label="Plain git">/g)?.length, 4);+ assert.equal(comparison.match(/class="wt-shell-command"/g)?.length, 12);+ assert.equal(comparison.match(/class="wt-shell-option"/g)?.length, 4);+ assert.equal(comparison.match(/class="wt-shell-argument"/g)?.length, 21);assert.match(homepage, /class="wt-terminal-green"/);assert.match(homepage, /class="wt-terminal-red"/);const switchPage = await readFile(routeFile('/switch/'), 'utf8');diff --git a/docs/tests/plugins.test.mjs b/docs/tests/plugins.test.mjsindex e32328730..7ac68053e 100644--- a/docs/tests/plugins.test.mjs+++ b/docs/tests/plugins.test.mjs@@ -10,7 +10,9 @@ import { rehypeResponsiveTables } from '../src/plugins/responsive-tables.mjs';import {commandReferenceSegments,pluginWorktrunkTerminal,+ rehypeComparisonCommands,semanticOutputSegments,+ shellCommandSegments,} from '../src/plugins/worktrunk-terminal.mjs';function prepareCodeBlock(plugin, codeBlock) {@@ -223,6 +225,118 @@ test('responsive records reject tables that cannot stack unambiguously', () => {}});+test('homepage comparison commands gain shell roles without changing their text', () => {+ const command = {+ type: 'element',+ tagName: 'code',+ properties: {},+ children: [{+ type: 'text',+ value: 'git worktree add -b feat ../repo.feat && \\\ncd ../repo.feat',+ }],+ };+ const outsideCode = structuredClone(command);+ const comparison = {+ type: 'element',+ tagName: 'table',+ properties: { className: ['cmd-compare'] },+ children: [{+ type: 'element',+ tagName: 'tbody',+ properties: {},+ children: [{+ type: 'element',+ tagName: 'tr',+ properties: {},+ children: [{+ type: 'element',+ tagName: 'td',+ properties: {},+ children: [command],+ }],+ }],+ }],+ };+ const tree = { type: 'root', children: [outsideCode, comparison] };++ rehypeComparisonCommands()(tree);++ assert.deepEqual(shellCommandSegments(command.children.map((child) => (+ child.children?.[0]?.value ?? child.value+ )).join('')), [+ { text: 'git', tone: 'command' },+ { text: ' ' },+ { text: 'worktree', tone: 'argument' },+ { text: ' ' },+ { text: 'add', tone: 'argument' },+ { text: ' ' },+ { text: '-b', tone: 'option' },+ { text: ' ' },+ { text: 'feat', tone: 'argument' },+ { text: ' ' },+ { text: '../repo.feat', tone: 'argument' },+ { text: ' && \\\n' },+ { text: 'cd', tone: 'command' },+ { text: ' ' },+ { text: '../repo.feat', tone: 'argument' },+ ]);+ assert.equal(command.children.map((child) => child.children?.[0]?.value ?? child.value).join(''),+ 'git worktree add -b feat ../repo.feat && \\\ncd ../repo.feat');+ assert.deepEqual(+ command.children.filter((child) => child.type === 'element')+ .map((child) => child.properties.className[0]),+ [+ 'wt-shell-command',+ 'wt-shell-argument',+ 'wt-shell-argument',+ 'wt-shell-option',+ 'wt-shell-argument',+ 'wt-shell-argument',+ 'wt-shell-command',+ 'wt-shell-argument',+ ],+ );+ assert.deepEqual(outsideCode, structuredClone({+ type: 'element',+ tagName: 'code',+ properties: {},+ children: [{+ type: 'text',+ value: 'git worktree add -b feat ../repo.feat && \\\ncd ../repo.feat',+ }],+ }));+});++test('raw homepage comparison markup is expanded before shell roles are added', () => {+ const source = 'wt switch -c feat';+ const tree = {+ type: 'root',+ children: [{+ type: 'raw',+ value: '<table class="cmd-compare"><tbody><tr><td><code>'+ + source+ + '</code></td></tr></tbody></table>',+ }],+ };++ rehypeComparisonCommands()(tree);++ const table = tree.children[0];+ const code = table.children[0].children[0].children[0].children[0];+ assert.equal(table.type, 'element');+ assert.equal(code.children.map((child) => child.children?.[0]?.value ?? child.value).join(''), source);+ assert.deepEqual(+ code.children.filter((child) => child.type === 'element')+ .map((child) => child.properties.className[0]),+ ['wt-shell-command', 'wt-shell-argument', 'wt-shell-option', 'wt-shell-argument'],+ );+});++test('shell command roles preserve syntax outside the styled grammar', () => {+ const source = 'cmd & next\ncmd 2>&1';+ assert.equal(shellCommandSegments(source).map(({ text }) => text).join(''), source);+});+test('console blocks separate copyable recipes from output', () => {const lines = ['# Recent', '$ wt list', '', '# Failed', '$ wt list --full'].map((text) => ({text,