From fd878e8feb739d12f3fe07df79bcdd605e449fd9 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:54:34 +0100 Subject: [PATCH 01/23] feat: frame the menus in a header box and lay them out in columns --- CONTRIBUTING.md | 4 +- README.md | 12 +- lib/cli.js | 87 ++++++------ lib/list.js | 242 +++++++++++++++++++++++++-------- lib/prompts.js | 91 +++++++------ lib/ui.js | 123 ++++++++++------- lib/width.js | 14 +- test/cli.test.js | 73 +++++----- test/list.test.js | 313 +++++++++++++++++++++++++++++++------------ test/prompts.test.js | 172 +++++++++--------------- test/ui.test.js | 114 ++++++++-------- test/width.test.js | 10 +- 12 files changed, 769 insertions(+), 486 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cb4c61d..0a38ef6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,9 +69,9 @@ node scripts/try-install.js --again -- web dev # with arguments for dws | `list.js` | The list used by every menu: keys, mouse, drawing, search | | `fuzzy.js` | Fuzzy matching and ranking for the list search | | `width.js` | Measuring, cutting and wrapping text by its terminal width | -| `ui.js` | Colours, the header and screen clearing | +| `ui.js` | Colours, the header box and screen clearing | -Menus use the list in `list.js`, which owns the terminal while it is open; free-text and yes/no questions still use `@inquirer/prompts`. Test the list through `createList()` with fake input and output streams, as `test/list.test.js` does, rather than in a real terminal. With `mouse: true`, the list asks for the cursor position after each drawing; a test answers with a reply such as `` (the last line is on row 20) before sending clicks. To see how a real terminal reports the mouse, run `node scripts/mouse-check.js` in it, and record the result in the roadmap's terminal support table and in `detectTerminal()`. +Menus use the list in `list.js`, which owns the terminal while it is open; free-text and yes/no questions still use `@inquirer/prompts`. The list also draws the header box from `ui.js`, which `cli.js` passes as `header`, so the whole screen redraws together. Test the list through `createList()` with fake input and output streams, as `test/list.test.js` does, rather than in a real terminal. With `mouse: true`, the list asks for the cursor position after each drawing; a test answers with a reply such as `` (the last line is on row 20) before sending clicks. To see how a real terminal reports the mouse, run `node scripts/mouse-check.js` in it, and record the result in the roadmap's terminal support table and in `detectTerminal()`. Each file in `lib/` starts with a comment describing what it contains and how it is used. Keep that comment accurate when you change the file. diff --git a/README.md b/README.md index a5b17d1..acfcd27 100644 --- a/README.md +++ b/README.md @@ -96,9 +96,9 @@ This installs two equivalent commands, `dev-workspace` and the shorter `dws`. | Enter | Open the selected project or run the script | | Ctrl+C | Stop a running script, or quit from a menu | -Each list also has entries to go **Back**, **Exit**, or **Change workspace**. +Each list also has entries to go **Back**, **Exit**, or **Change workspace**, under a line that separates them from the projects or scripts. -Long workspace paths and script commands are cut to fit, and emoji or CJK characters in folder names never break the layout. +Every menu opens with a small box that shows where you are: the tool's name, followed by the project you are in (`◆ dev-workspace › web-app`), the workspace folder, and in a project, its package manager on the right. Each script's command is shown next to its name, in a column of its own, and tags such as `last run` sit at the right edge. The layout stays within 100 columns on wide terminals. Long workspace paths and script commands are cut with `…` to fit, and emoji or CJK characters in folder names never break the layout. ### Searching @@ -125,7 +125,7 @@ In a terminal without full support, the first menu shows a short note, once: wha ### Recent projects and scripts -The five projects you used most recently are listed first, under **Recent**. In a project's script list, the cursor starts on the script you ran last, marked `(last run)`. This history is kept in a separate `state.json` file next to the configuration (see [Configuration](#configuration)); `dws --clear-history` deletes it without touching your settings. +The five projects you used most recently are listed first, under **Recent**. In a project's script list, the cursor starts on the script you ran last, tagged `last run`. This history is kept in a separate `state.json` file next to the configuration (see [Configuration](#configuration)); `dws --clear-history` deletes it without touching your settings. ### Running scripts @@ -137,9 +137,9 @@ To pass arguments to a script, choose **Run with arguments…** at the end of th Every subfolder of the workspace is listed as a project, including links to folders (symbolic links, and junctions on Windows), except folders that are never projects: names starting with a dot (such as `.git` or `.vscode`) and `node_modules`. Only the immediate subfolders are listed; projects nested deeper are not discovered. -Projects are sorted by name, ignoring case. Folders without a `package.json` have no scripts to run, so they appear dimmed at the end of the list, marked `(no package.json)`, and cannot be selected. A `package.json` that starts with a UTF-8 byte order mark, as Windows PowerShell 5.1 and some editors write it, is read normally, as npm does. +Projects are sorted by name, ignoring case. Folders without a `package.json` have no scripts to run, so they appear dimmed at the end of the list, tagged `no package.json`, and cannot be selected. A `package.json` that starts with a UTF-8 byte order mark, as Windows PowerShell 5.1 and some editors write it, is read normally, as npm does. -In the script list, the selected script's command is shown below the list, shortened to fit the terminal. Lifecycle hooks are listed with their main script instead of separately: with `prebuild`, `build` and `postbuild` scripts, the list shows only `build`, described as `node build.js (+ prebuild, postbuild)`. Running `build` runs its hooks too, as the package manager normally does. A hook without its main script, such as `postinstall` on its own, is listed like any other script. In Yarn 2+ projects, which never run these hooks, every hook is listed as a separate script so you can still run it. +In the script list, each script's command is shown next to its name, shortened to fit the terminal. Lifecycle hooks are listed with their main script instead of separately: with `prebuild`, `build` and `postbuild` scripts, the list shows only `build`, with the command `node build.js (+ prebuild, postbuild)`; when the command is shortened, the hooks are always kept. Running `build` runs its hooks too, as the package manager normally does. A hook without its main script, such as `postinstall` on its own, is listed like any other script. In Yarn 2+ projects, which never run these hooks, every hook is listed as a separate script so you can still run it. ## Package managers @@ -157,7 +157,7 @@ Each project's scripts run with the package manager that project uses. It is cho 3. npm, when neither is present. -The project screen shows the choice and the reason, for example `Package manager: pnpm (from pnpm-lock.yaml)`. If that package manager is not installed, the CLI explains how to install it. For pnpm and Yarn it suggests `corepack enable` on Node.js 24 and earlier; Node.js 25 and later no longer include Corepack, so there it suggests `npm install --global` first. +The box at the top of the project screen shows the choice and the reason, for example `pnpm · pnpm-lock.yaml`. If that package manager is not installed, the CLI explains how to install it. For pnpm and Yarn it suggests `corepack enable` on Node.js 24 and earlier; Node.js 25 and later no longer include Corepack, so there it suggests `npm install --global` first. Whether `pre` and `post` hooks run is decided by the package manager: npm, pnpm, Bun and Yarn 1 run them, while Yarn 2 and later ignore them. The CLI recognises Yarn 2+ from a `packageManager` field such as `yarn@4.5.0`, or from a `yarn.lock` that starts with a `__metadata:` block, and then lists the hooks separately instead of grouping them. diff --git a/lib/cli.js b/lib/cli.js index f8ffc58..a7dbb71 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -5,7 +5,10 @@ // runs the main loop: load or configure the workspace, list its projects // (recently used ones first), list a project's scripts with its detected // package manager, run the chosen script with that tool, optionally with -// arguments, then offer to run it again. Workspace paths typed at the prompt +// arguments, then offer to run it again. Every menu shows the header box +// from ui.js, with the project as a breadcrumb and its package manager as +// the tag; empty and error states are shown in the box's screen, as the +// list's body. Workspace paths typed at the prompt // or passed with --workspace go through resolveDirectoryInput(), so ~, // quotes and escaped spaces work without a shell. // @@ -93,17 +96,15 @@ import { waitForBack, } from './prompts.js' -import { clearScreen, color, printHeader } from './ui.js' +import { clearScreen, color, headerLines } from './ui.js' const { version } = createRequire(import.meta.url)('../package.json') -// "pnpm (from pnpm-lock.yaml)", "yarn (from the packageManager field)"... +// The header tag: "pnpm · pnpm-lock.yaml", "yarn · packageManager field"... function describePackageManager({ name, source }) { - if (source === 'default') return `${name} (default)` - if (source === 'packageManager') { - return `${name} (from the packageManager field)` - } - return `${name} (from ${source})` + if (source === 'default') return `${name} · default` + if (source === 'packageManager') return `${name} · packageManager field` + return `${name} · ${source}` } // Quote arguments that would otherwise be read differently, for display. @@ -217,7 +218,7 @@ const defaultDependencies = { ui: { clearScreen, color, - printHeader, + headerLines, }, output: { log: (...args) => console.log(...args), @@ -256,6 +257,11 @@ export function createCli(overrides = {}) { let root = '' let history = emptyState() + // The header box for a menu, drawn by the list at its current width. + function header(crumbs = [], tag) { + return width => ui.headerLines({ workspace: root, crumbs, tag }, width) + } + // Update the history and save it. History is a convenience, so a failed // save is ignored rather than interrupting the user. async function remember(change) { @@ -467,9 +473,13 @@ export function createCli(overrides = {}) { } // Ask which script to run and return { script, args }, or null for Back. - async function chooseRun(scripts, lastScript) { + // The header is drawn by the first menu only: the next ones appear under it. + async function chooseRun(scripts, lastScript, frame) { while (true) { - const selected = await prompts.chooseScript(scripts, { lastScript }) + const selected = await prompts.chooseScript(scripts, { + lastScript, + header: frame, + }) if (selected !== RUN_WITH_ARGUMENTS) { return selected && { script: selected, args: [] } @@ -500,13 +510,14 @@ export function createCli(overrides = {}) { }) } catch (error) { ui.clearScreen() - ui.printHeader(root, `PROJECT / ${project.name}`) - output.error( - ui.color(` Could not read package.json: ${error.message}`, 'red'), - ) - output.log() - await prompts.waitForBack('Return to projects') + await prompts.waitForBack('Return to projects', { + header: header([project.name]), + body: [ + [`Could not read package.json: ${error.message}`, 'red'], + ['Fix the file, then open the project again.', 'dim'], + ], + }) return } @@ -515,29 +526,28 @@ export function createCli(overrides = {}) { // The run to repeat when the user picks "Run again". let run = null + const frame = header([project.name], describePackageManager(packageManager)) + while (true) { ui.clearScreen() - ui.printHeader(root, `PROJECT / ${project.name}`) if (!run) { if (scripts.length === 0) { - output.log(ui.color(' No scripts found in this project.', 'yellow')) - output.log(' Check that package.json defines a scripts object.') - output.log() - - await prompts.waitForBack('Return to projects') + await prompts.waitForBack('Return to projects', { + header: frame, + body: [ + [`No scripts in ${project.name}.`, 'yellow'], + ['Add a "scripts" object to its package.json.', 'dim'], + ], + }) return } - output.log( - ui.color( - ` Package manager: ${describePackageManager(packageManager)}`, - 'dim', - ), + run = await chooseRun( + scripts, + history.lastScripts[project.directory], + frame, ) - output.log() - - run = await chooseRun(scripts, history.lastScripts[project.directory]) if (!run) return } @@ -631,17 +641,18 @@ export function createCli(overrides = {}) { } ui.clearScreen() - ui.printHeader(root) const projects = await readProjects() - - if (projects.length === 0) { - output.log(ui.color(' No project folders found.', 'yellow')) - output.log() - } - const choice = await prompts.chooseProject(projects, { recent: recentProjects(history, projects), + header: header(), + body: + projects.length === 0 + ? [ + ['No project folders in this workspace.', 'yellow'], + ['Add one, or change the workspace.', 'dim'], + ] + : [], }) if (!choice) return diff --git a/lib/list.js b/lib/list.js index cd7c838..85445dd 100644 --- a/lib/list.js +++ b/lib/list.js @@ -7,11 +7,22 @@ // characters underlined), Backspace edits the search, and Escape or Ctrl+U // clears it. Ctrl+C rejects with an ExitPromptError, as Inquirer's prompts do. // -// Items are { label, value, icon, hint, description, disabled, action } or -// { separator }. Disabled items are shown dimmed and skipped by the cursor; +// Items are { label, value, icon, detail, detailEnd, hint, disabled, action } +// or { separator }. Disabled items are shown dimmed and skipped by the cursor; // action items ("Back", "Exit", …) and separators are hidden while searching, // so Enter never triggers an action by accident. // +// The layout, from the top: the `header` lines (a function of the width that +// returns lines of [text, ...styles] segments, such as the box from ui.js), +// the `body` lines ([text, style] pairs, for a message such as an error), +// the message with the search, the items, and the help line, with a blank +// line between each part. Lines are at most MAX_WIDTH columns wide. Items +// line up in columns: the icon and label, then the dim `detail` (cut with … +// to fit, except its `detailEnd`), then the `hint` or `disabled` reason on +// the right. Separators are shown in capitals, after a blank line, and a rule +// separates the actions from the items above them. When the list closes, the +// header stays, followed by a one-line summary of the answer. +// // The list owns the terminal while it is open: raw mode, key decoding // (parseKeys) and drawing. A chunk of input that ends in an unfinished // escape sequence is held for up to 50 ms, so an arrow key split over two @@ -21,10 +32,10 @@ // draws a line wider than the terminal, measured with textWidth() from // width.js, so the line count stays exact. When the terminal gets narrower, // it rewraps the lines already drawn; the list counts the rows they now take, -// so the next drawing still starts on the first line. Visible item i is drawn -// on line 1 + i - top. Raw mode is turned off and the cursor shown again on -// every way out, including exit and the signals in SIGNALS, which are then -// sent again so they still end the process. +// so the next drawing still starts on the first line. Each drawing records +// which item is on which line, for the mouse. Raw mode is turned off and the +// cursor shown again on every way out, including exit and the signals in +// SIGNALS, which are then sent again so they still end the process. // // With `mouse`, the list also switches on mouse reporting (SGR mode, with // motion) while it is open, and off again on every way out. To know which @@ -38,7 +49,8 @@ // item opens it, so a double-click opens any item. A terminal sends a // double-click as two presses, so clicks are ignored for OPEN_DELAY after an // item opens; otherwise the second press would land on the next list. Hover -// marks the item under the pointer with ›. The wheel moves the cursor, and +// marks the item under the pointer with ›, and with colours gives its whole +// row a grey background. The wheel moves the cursor, and // pressing it (the middle button) opens the selected item, wherever the // pointer is; the help line says so while the mouse is on. // Keys work as without the mouse. A `note` is shown in yellow under the @@ -50,7 +62,7 @@ import { StringDecoder } from 'node:string_decoder' import { fuzzyFilter } from './fuzzy.js' import { USE_COLORS } from './ui.js' -import { fitText, textWidth, wrapText } from './width.js' +import { fitText, textWidth, truncateText, wrapText } from './width.js' const ESC = '\x1b' const HIDE_CURSOR = `${ESC}[?25l` @@ -69,6 +81,11 @@ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] const OPEN_DELAY = 300 const REPLY_TIMEOUT = 100 +// The widest a line gets, so the columns stay together on wide terminals, +// and the widest the label column gets before details move further right. +export const MAX_WIDTH = 100 +const MAX_LABEL_WIDTH = 32 + export class ExitPromptError extends Error { name = 'ExitPromptError' } @@ -192,7 +209,11 @@ const STYLES = { dim: ['\x1b[2m', '\x1b[22m'], underline: ['\x1b[4m', '\x1b[24m'], cyan: ['\x1b[36m', '\x1b[39m'], + green: ['\x1b[32m', '\x1b[39m'], yellow: ['\x1b[33m', '\x1b[39m'], + red: ['\x1b[31m', '\x1b[39m'], + // Bright black: a soft grey in every common terminal theme. + hover: ['\x1b[100m', '\x1b[49m'], } // A line is a list of [text, ...styles] segments, cut to `width` columns @@ -223,6 +244,10 @@ function renderLine(segments, width, useColors) { const isSelectable = item => !item.separator && !item.disabled +// An item's icon and label, as drawn after its marker. +const labelText = item => + item.icon ? `${item.icon} ${item.label}` : item.label + export function createList({ input = process.stdin, output = process.stdout, @@ -243,6 +268,8 @@ export function createList({ searchable = true, mouse = false, note, + header, + body = [], }) { let query = '' let rows = [] @@ -256,6 +283,32 @@ export function createList({ const positionRequests = [] // The screen row under the mouse pointer. let pointerRow = null + // The index in `rows` of the item on each line of the last drawing. + let lineItems = [] + + // Labels line up in a column, as wide as the widest one (icon included), + // up to MAX_LABEL_WIDTH. Actions have no details, so they do not count. + const labelWidth = Math.min( + MAX_LABEL_WIDTH, + Math.max( + 0, + ...items + .filter(item => !item.separator && !item.action) + .map(item => textWidth(labelText(item))), + ), + ) + + function lineWidth() { + return Math.min(MAX_WIDTH, Math.max(10, (output.columns || 80) - 1)) + } + + function headerLines(width) { + return header ? header(width) : [] + } + + function noteLines(width) { + return note ? wrapText(note, width - 2) : [] + } function filter() { if (!query) return items.map(item => ({ item, positions: [] })) @@ -271,8 +324,20 @@ export function createList({ return rows.findIndex(row => isSelectable(row.item)) } + // As many items as fit in the window next to everything else the list + // draws: the message, help line and blank lines, the header, body and + // note, the blank line before each separator and the rule. function visibleRows() { - return Math.max(3, Math.min(pageSize, (output.rows || 24) - 4)) + const width = lineWidth() + const parts = [headerLines(width), body, noteLines(width)] + let others = 4 + + for (const lines of parts) if (lines.length) others += lines.length + 1 + + others += rows.filter(row => row.item.separator).length + if (rows.some(row => row.item.action)) others += 1 + + return Math.max(3, Math.min(pageSize, (output.rows || 24) - others - 1)) } // Keep the cursor inside the window, and show a separator that sits @@ -329,63 +394,121 @@ export function createList({ function itemAt(screenRow) { if (firstRow === null || screenRow === null) return -1 - const offset = screenRow - firstRow - 1 - const index = top + offset + const index = lineItems[screenRow - firstRow] - if (offset < 0 || offset >= visibleRows() || index >= rows.length) { - return -1 - } + if (index === undefined || index >= rows.length) return -1 return isSelectable(rows[index].item) ? index : -1 } - function itemSegments({ item, positions }, selected, hovered) { + // The detail, cut with … to fit in `room` columns; its end stays whole. + function fitDetail({ detail, detailEnd = '' }, room) { + const end = textWidth(detailEnd) + + if (textWidth(detail) + end <= room) return detail + detailEnd + if (room - end < 2) return truncateText(detail + detailEnd, room) + + return truncateText(detail, room - end) + detailEnd + } + + function itemSegments({ item, positions }, selected, hovered, width) { const marker = selected ? ['❯ ', 'cyan'] : hovered ? ['› ', 'dim'] : [' '] - const icon = item.icon ? [`${item.icon} `] : [''] const base = item.disabled ? ['dim'] : selected ? ['cyan'] : [] const matched = new Set(positions) - const label = [...item.label].map((character, index) => [ - character, - ...base, - ...(matched.has(index) ? ['bold', 'underline'] : []), - ]) - const note = item.disabled ? item.disabled : item.hint - - return [ - [' '], - marker, - [icon[0], ...base], - ...label, - ...(note ? [[` ${note}`, 'dim']] : []), - ] + const segments = [[' '], marker] + + if (item.icon) segments.push([`${item.icon} `, ...base]) + + for (const [index, character] of [...item.label].entries()) { + segments.push([ + character, + ...base, + ...(matched.has(index) ? ['bold', 'underline'] : []), + ]) + } + + const tag = item.disabled || item.hint + const tagRoom = tag ? textWidth(tag) + 2 : 0 + let used = 4 + textWidth(labelText(item)) + + if (item.detail) { + const column = Math.max(used + 2, 4 + labelWidth + 2) + const text = fitDetail(item, width - column - tagRoom) + + if (text) { + segments.push([' '.repeat(column - used)], [text, 'dim']) + used = column + textWidth(text) + } + } + + if (tag) { + // On the right, or straight after the label when there is no room. + const gap = Math.max(2, width - used - textWidth(tag)) + + segments.push([' '.repeat(gap)], [tag, 'dim']) + used += gap + textWidth(tag) + } + + if (!hovered || !useColors) return segments + if (used < width) segments.push([' '.repeat(width - used)]) + + return segments.map(([text, ...styles]) => [text, ...styles, 'hover']) } function render() { - const width = Math.max(10, (output.columns || 80) - 1) + const width = lineWidth() const size = visibleRows() + const frame = headerLines(width) const lines = [] + // Found on the last drawing, before its lines are forgotten. + const hovered = mouse ? itemAt(pointerRow) : -1 + + lineItems = [] + + if (frame.length) lines.push(...frame, []) + + if (body.length) { + for (const [text, ...styles] of body) { + lines.push([[' '], [text, ...styles]]) + } + + lines.push([]) + } + const prompt = [[' '], [message, 'bold']] if (query) prompt.push([' '], [query, 'cyan']) - else if (searchable) prompt.push([' type to search', 'dim']) + else if (searchable) { + const hint = 'type to search' + const gap = width - 2 - textWidth(message) - textWidth(hint) - lines.push(prompt) + prompt.push([' '.repeat(Math.max(2, gap))], [hint, 'dim']) + } - const hovered = mouse ? itemAt(pointerRow) : -1 + lines.push(prompt, []) for (const [offset, row] of rows.slice(top, top + size).entries()) { + const index = top + offset + const { item } = row + + if (item.separator) { + if (offset > 0) lines.push([]) + + lines.push([[' '], [item.separator.toUpperCase(), 'dim']]) + continue + } + + if (item.action && offset > 0 && !rows[index - 1].item.action) { + lines.push([[' '], ['─'.repeat(Math.max(0, width - 2)), 'dim']]) + } + + lineItems[lines.length] = index lines.push( - row.item.separator - ? [[' '], [row.item.separator, 'dim']] - : itemSegments( - row, - top + offset === cursor, - top + offset === hovered, - ), + itemSegments(row, index === cursor, index === hovered, width), ) } @@ -396,10 +519,6 @@ export function createList({ ]) } - const description = rows[cursor]?.item.description - - if (description) lines.push([[' '], [description, 'dim']]) - const help = ['↑↓ move', 'Enter select'] // Opening with the wheel is not something people expect, so say it. @@ -407,14 +526,14 @@ export function createList({ if (query) help.push('Esc clear search') if (rows.length > size) help.push(`${cursor + 1}/${rows.length}`) - lines.push([[' '], [help.join(' · '), 'dim']]) + lines.push([], [[' '], [help.join(' · '), 'dim']]) + + const notes = noteLines(width) - if (note) { + if (notes.length) { lines.push([]) - for (const line of wrapText(note, width - 2)) { - lines.push([[' '], [line, 'yellow']]) - } + for (const line of notes) lines.push([[' '], [line, 'yellow']]) } paint(lines.map(line => renderLine(line, width, useColors))) @@ -512,11 +631,20 @@ export function createList({ exitEvents.kill(exitEvents.pid, signal) } - // Draw the summary, then close and call `settle`. A position reply - // still on its way would reach whatever reads the input next, such as - // a script, so the list first waits for it, up to REPLY_TIMEOUT. + // Draw the header and the summary (or nothing), then close and call + // `settle`. A position reply still on its way would reach whatever + // reads the input next, such as a script, so the list first waits for + // it, up to REPLY_TIMEOUT. function finish(summary, settle) { - paint(summary === undefined ? [] : [summary]) + const width = lineWidth() + const frame = headerLines(width) + const lines = frame.length ? [...frame, [], summary] : [summary] + + paint( + summary === undefined + ? [] + : lines.map(line => renderLine(line, width, useColors)), + ) output.write('\n') if (positionRequests.length === 0) { @@ -632,11 +760,7 @@ export function createList({ clicksFrom = now() + OPEN_DELAY finish( - renderLine( - [[' '], [message, 'bold'], [' '], [item.label, 'cyan']], - Math.max(10, (output.columns || 80) - 1), - useColors, - ), + [[' '], [message, 'bold'], [' '], [item.label, 'cyan']], () => resolve(item.value), ) } else if (result === 'cancel') { diff --git a/lib/prompts.js b/lib/prompts.js index 6cca005..513bd3a 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -10,18 +10,22 @@ // heading, and folders without a package.json dimmed and unselectable. It // returns the project, CHANGE_WORKSPACE when the user picks that entry, or // null for Exit. chooseScript() puts the cursor on the project's last script, -// shows the selected script's command, cut to the terminal width (measured -// with width.js, so wide characters count as two columns), and its -// pre/post hooks, and returns the script, RUN_WITH_ARGUMENTS when offered and -// picked, or null for Back. askForArguments() splits what the user typed with -// splitArguments(). waitAfterCommand() returns true for "Run again". +// tagged "last run", shows each script's command next to it (the list cuts +// it to the width) followed by its pre/post hooks, and returns the script, +// RUN_WITH_ARGUMENTS when offered and picked, or null for Back. +// askForArguments() splits what the user typed with splitArguments(). +// waitAfterCommand() returns true for "Run again". +// +// chooseProject(), chooseScript() and waitForBack() take the `header` and +// `body` the list draws above its message (see list.js). Action entries use +// symbols one column wide (⚙ ✕ ← … ↻), so their labels line up. // // useMouse() turns the mouse on or off for every menu from then on, and // gives a note (from terminal.js) to show under the next menu only, with a // function called when that menu shows it. // // Used by cli.js through the default instance exported at the bottom. Tests -// pass fake prompt functions and a terminal width to createPrompts(). +// pass fake prompt functions to createPrompts(). import { confirm as inquirerConfirm, @@ -30,7 +34,6 @@ import { import { splitArguments } from './args.js' import { select as listSelect } from './list.js' -import { fitText, textWidth } from './width.js' // Returned by chooseProject when the user wants another workspace. export const CHANGE_WORKSPACE = Symbol('change-workspace') @@ -38,37 +41,39 @@ export const CHANGE_WORKSPACE = Symbol('change-workspace') // Returned by chooseScript when the user wants to pass arguments. export const RUN_WITH_ARGUMENTS = Symbol('run-with-arguments') -function truncate(text, width) { - return textWidth(text) <= width ? text : `${fitText(text, width - 1)}…` -} - -// The command shown under the selected script, cut to fit on one line. The -// hooks note is kept whole, so only the command itself is shortened. The list -// indents it by two columns and leaves the last column free. -function describeScript(script, terminalColumns) { - const hooks = script.hooks?.length ? ` (+ ${script.hooks.join(', ')})` : '' - const width = Math.max(20, (terminalColumns || 80) - 3) - textWidth(hooks) - - return truncate(script.command, Math.max(10, width)) + hooks -} - function projectItem(project) { return { - icon: '📁', label: project.name, value: project, // Shown dimmed and skipped by the cursor: there is nothing to run. ...(project.hasPackageJson === false && { - disabled: '(no package.json)', + disabled: 'no package.json', }), } } +// The list cuts the command to fit, but keeps the hooks note whole. +function scriptItem(script, lastScript) { + return { + label: script.name, + value: script, + detail: script.command, + ...(script.hooks?.length && { + detailEnd: ` (+ ${script.hooks.join(', ')})`, + }), + ...(script.name === lastScript && { hint: 'last run' }), + } +} + +// The header and body for the list, left out while unset. +function frame({ header, body } = {}) { + return { ...(header && { header }), ...(body?.length && { body }) } +} + export function createPrompts({ confirm = inquirerConfirm, input = inquirerInput, select = listSelect, - columns = () => process.stdout.columns, } = {}) { let mouse = false let note = null @@ -111,13 +116,13 @@ export function createPrompts({ }) }, - async chooseProject(projects, { recent = [] } = {}) { + async chooseProject(projects, { recent = [], ...options } = {}) { const others = projects.filter(project => !recent.includes(project)) const items = others.map(projectItem) if (recent.length > 0) { items.unshift({ separator: 'Recent' }, ...recent.map(projectItem), { - separator: 'Projects', + separator: 'All projects', }) } @@ -126,33 +131,29 @@ export function createPrompts({ items: [ ...items, { - // With its emoji selector, every terminal draws it two columns - // wide, as string-width counts it. - icon: '⚙️', + icon: '⚙', label: 'Change workspace', value: CHANGE_WORKSPACE, action: true, }, - { icon: '↩', label: 'Exit', value: null, action: true }, + { icon: '✕', label: 'Exit', value: null, action: true }, ], + ...frame(options), }) }, // With `forArguments`, the list picks the script to run with arguments: - // it has no "Run with arguments…" entry, and Back returns to the scripts. - async chooseScript(scripts, { lastScript, forArguments = false } = {}) { - const items = scripts.map(script => ({ - icon: '▶', - label: script.name, - value: script, - description: describeScript(script, columns()), - ...(script.name === lastScript && { hint: '(last run)' }), - })) + // it has no "Run with arguments" entry, and Back returns to the scripts. + async chooseScript( + scripts, + { lastScript, forArguments = false, ...options } = {}, + ) { + const items = scripts.map(script => scriptItem(script, lastScript)) if (!forArguments && scripts.length > 0) { items.push({ icon: '…', - label: 'Run with arguments…', + label: 'Run with arguments', value: RUN_WITH_ARGUMENTS, action: true, }) @@ -165,13 +166,14 @@ export function createPrompts({ items: [ ...items, { - icon: '↩', + icon: '←', label: forArguments ? 'Back to scripts' : 'Back to projects', value: null, action: true, }, ], default: scripts.find(script => script.name === lastScript), + ...frame(options), }) }, @@ -191,11 +193,12 @@ export function createPrompts({ return splitArguments(text) }, - async waitForBack(message = 'Return to projects') { + async waitForBack(message = 'Return to projects', options = {}) { return menu({ message, - items: [{ icon: '↩', label: 'Back', value: true }], + items: [{ icon: '←', label: 'Back', value: true }], searchable: false, + ...frame(options), }) }, @@ -204,7 +207,7 @@ export function createPrompts({ message: 'What next?', items: [ { icon: '↻', label: 'Run again', value: true }, - { icon: '↩', label: 'Back to scripts', value: false }, + { icon: '←', label: 'Back to scripts', value: false }, ], searchable: false, }) diff --git a/lib/ui.js b/lib/ui.js index 99465ea..b2a3010 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -1,20 +1,29 @@ -// Terminal output helpers: colours, the boxed header and clearing the screen. +// Terminal output helpers: colours, the header box and clearing the screen. // // color() wraps text in ANSI colour codes, unless output is not a terminal or // NO_COLOR is set. USE_COLORS is that decision, shared with list.js. // -// printHeader() draws the 44-column box showing the workspace and the current -// section. Its text is measured and cut with width.js, so emoji and wide -// characters never push the border out of line. Its emoji carry their -// variation selector (⚙️), so every terminal draws them two columns wide, as -// width.js counts them. +// headerLines() returns the three lines of the box shown at the top of every +// menu, for a given width: // -// Used by cli.js through the default instance exported at the bottom. Tests -// call createUi() with colours forced on or off and a fake log function. +// ╭─ ◆ dev-workspace › web-app ──────────── npm · package-lock.json ─╮ +// │ E:\dev │ +// ╰──────────────────────────────────────────────────────────────────╯ +// +// The top border carries the name and the breadcrumb of the current screen, +// and an optional tag on the right, dropped when the name needs the room. The +// workspace path is cut with … when it does not fit. The lines are made of +// [text, ...styles] segments that list.js draws, so the box redraws with the +// list when the window is resized. It uses one thin line style and only +// characters one column wide, measured with width.js, so its border lines up +// in every terminal. +// +// Used by cli.js, color() through the default instance exported at the +// bottom. Tests call createUi() with colours forced on or off. -import { fitText, textWidth } from './width.js' +import { textWidth, truncateText } from './width.js' -const HEADER_WIDTH = 44 +const NAME = 'dev-workspace' export const USE_COLORS = Boolean(process.stdout.isTTY && !process.env.NO_COLOR) @@ -28,10 +37,7 @@ const ANSI = { red: '\x1b[31m', } -export function createUi({ - useColors = USE_COLORS, - log = (...args) => console.log(...args), -} = {}) { +export function createUi({ useColors = USE_COLORS } = {}) { function color(value, shade) { if (!useColors || !ANSI[shade]) { return String(value) @@ -40,49 +46,64 @@ export function createUi({ return `${ANSI[shade]}${value}${ANSI.reset}` } - function printHeader(workspace, section = 'PROJECT EXPLORER') { - const width = HEADER_WIDTH - const cyan = text => color(text, 'cyan') - - function row(text = '', shade = 'reset', centered = false) { - const available = width - 2 - const visible = fitText(` ${text} `, available) - const remaining = available - textWidth(visible) - - const left = centered ? Math.floor(remaining / 2) : 0 - const right = remaining - left - - return ( - cyan(' │') + - ' '.repeat(left) + - color(visible, shade) + - ' '.repeat(right) + - cyan('│') - ) - } + return { color } +} + +// The header box, as lines of segments at most `width` columns wide, starting +// with the same two-column margin as the rest of the list. +export function headerLines({ workspace, crumbs = [], tag }, width) { + // The box, corners included; its title row holds "╭─ ", the title, a space, + // at least one "─", the tag part and "╮". + const box = Math.max(10, width - 2) + const room = box - 6 + const name = `◆ ${NAME}` + const trail = crumbs.map(crumb => ` › ${crumb}`).join('') + const tagPart = tag ? ` ${tag} ─` : '' - const border = (left, middle, right) => - ` ${cyan(left + middle.repeat(width - 2) + right)}` - - log() - log(border('╭', '━', '╮')) - log(row()) - log(row('🚀 DEV WORKSPACE CLI', 'bold', true)) - log(row('⚙️ DEVELOPER TOOLKIT', 'cyan', true)) - log(row()) - log(border('├', '─', '┤')) - log(row('📂 WORKSPACE', 'yellow')) - log(row(`📍 ${workspace}`, 'bold')) - log(border('├', '─', '┤')) - log(row(`🧭 ${section}`, 'green')) - log(border('╰', '━', '╯')) + const showTag = tag && textWidth(name + trail + tagPart) <= room + let title + let fill + + if (textWidth(name + trail) <= room) { + title = [ + ['◆', 'cyan'], + [` ${NAME}`, 'bold'], + ...crumbs.flatMap(crumb => [[' › ', 'dim'], [crumb]]), + ] + fill = room - textWidth(name + trail) - (showTag ? textWidth(tagPart) : 0) + } else { + const cut = truncateText(trail, Math.max(0, room - textWidth(name))) + + title = [['◆', 'cyan'], [` ${NAME}`, 'bold'], [cut]] + fill = Math.max(0, room - textWidth(name + cut)) } - return { color, printHeader } + const top = [ + [' '], + ['╭─ ', 'dim'], + ...title, + [` ${'─'.repeat(fill + 1)}`, 'dim'], + ...(showTag ? [[` ${tag} `], ['─', 'dim']] : []), + ['╮', 'dim'], + ] + + const path = truncateText(workspace, box - 5) + + return [ + top, + [ + [' '], + ['│', 'dim'], + [` ${path}`], + [' '.repeat(box - 4 - textWidth(path))], + ['│', 'dim'], + ], + [[' '], [`╰${'─'.repeat(box - 2)}╯`, 'dim']], + ] } export function clearScreen() { console.clear() } -export const { color, printHeader } = createUi() +export const { color } = createUi() diff --git a/lib/width.js b/lib/width.js index b537ac6..2561e31 100644 --- a/lib/width.js +++ b/lib/width.js @@ -6,12 +6,13 @@ // terminals draw narrow, such as ⚙ without its emoji variation selector. // fitText() keeps the start of a text that fits in a number of columns, // without splitting a character made of several code points (an emoji -// sequence, or a letter with its accents). +// sequence, or a letter with its accents). truncateText() does the same, but +// ends a text it shortens with …, so the cut shows. // wrapText() breaks a text into lines of at most a number of columns, between // words; a word wider than a line is cut with fitText(). // -// Used by ui.js for the header, list.js for every line it draws and the mouse -// note, and prompts.js for the script descriptions. +// Used by ui.js for the header, and list.js for every line it draws, the +// details next to each item and the mouse note. import stringWidth from 'string-width' @@ -37,6 +38,13 @@ export function fitText(text, width) { return result } +export function truncateText(text, width) { + if (textWidth(text) <= width) return text + if (width < 1) return '' + + return `${fitText(text, width - 1)}…` +} + export function wrapText(text, width) { const lines = [] let line = '' diff --git a/test/cli.test.js b/test/cli.test.js index 021cbe1..a9ab443 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -6,6 +6,7 @@ import assert from 'node:assert/strict' import { createCli, findProject } from '../lib/cli.js' import { CHANGE_WORKSPACE, RUN_WITH_ARGUMENTS } from '../lib/prompts.js' import { emptyState } from '../lib/state.js' +import { headerLines } from '../lib/ui.js' import { resolveDirectoryInput } from '../lib/workspace.js' const { version } = createRequire(import.meta.url)('../package.json') @@ -21,6 +22,7 @@ function createDependencies(overrides = {}) { mouseSettings: [], errors: [], logs: [], + menus: [], } const dependencies = { @@ -83,21 +85,29 @@ function createDependencies(overrides = {}) { prompts: { askForArguments: async () => [], askForWorkspace: async () => WORKSPACE, - chooseProject: async () => null, - chooseScript: async () => null, + chooseProject: async (projects, options) => { + calls.menus.push(options) + return null + }, + chooseScript: async (scripts, options) => { + calls.menus.push(options) + return null + }, confirmWorkspaceChange: async () => true, useMouse: (enabled, note = null, onNoteShown = null) => { calls.mouse.push({ enabled, note }) calls.showNote = onNoteShown }, waitAfterCommand: async () => undefined, - waitForBack: async () => undefined, + waitForBack: async (message, options) => { + calls.menus.push(options) + }, }, ui: { clearScreen: () => undefined, color: value => String(value), - printHeader: () => undefined, + headerLines, }, output: { @@ -188,11 +198,8 @@ test('CLI exits cleanly when the project list is empty', async () => { await cli.run() assert.equal(calls.discoveredWorkspaces.length, 1) - assert.ok( - calls.logs.some(args => - args.join(' ').includes('No project folders found'), - ), - ) + assert.match(menuText(calls), /No project folders in this workspace\./) + assert.match(menuText(calls), /◆ dev-workspace ─/) }) test('CLI treats prompt cancellation as a normal exit', async () => { @@ -271,9 +278,7 @@ test('CLI handles a project with no npm scripts', async () => { await createCli(dependencies).run() - assert.ok( - calls.logs.some(args => args.join(' ').includes('No scripts found')), - ) + assert.match(menuText(calls), /No scripts in empty-project\./) }) test('CLI runs a selected script and reports success', async () => { @@ -411,14 +416,11 @@ test('CLI handles errors while reading a project package.json', async () => { await createCli(dependencies).run() - assert.ok( - calls.errors.some(args => - args.join(' ').includes('Could not read package.json'), - ), - ) - assert.ok( - calls.errors.some(args => args.join(' ').includes('Invalid package JSON')), + assert.match( + menuText(calls), + /Could not read package\.json: Invalid package JSON/, ) + assert.match(menuText(calls), /› broken-project/) }) test('CLI handles errors when starting a command', async () => { @@ -483,7 +485,7 @@ test('CLI treats prompt abortion as a normal exit', async () => { test('CLI propagates unexpected errors', async () => { const { dependencies } = createDependencies({ ui: { - printHeader: () => { + clearScreen: () => { throw new Error('Unexpected UI failure') }, }, @@ -496,6 +498,19 @@ function loggedText(calls) { return calls.logs.map(args => args.join(' ')).join('\n') } +// What the recorded menus show above their message: the header box, at 80 +// columns, and the body. +function menuText(calls) { + return calls.menus + .flatMap(options => [ + ...(options?.header?.(80) ?? []).map(line => + line.map(([text]) => text).join(''), + ), + ...(options?.body ?? []).map(([text]) => text), + ]) + .join('\n') +} + test('CLI lets the user change the workspace from the project list', async () => { const otherWorkspace = path.resolve('fake/other') const choices = [CHANGE_WORKSPACE, null] @@ -862,20 +877,17 @@ test('CLI runs scripts with the detected package manager', async () => { assert.deepEqual(runs, [ ['dev', project.directory, { packageManager: 'pnpm' }], ]) - assert.match( - loggedText(calls), - /Package manager: pnpm \(from pnpm-lock\.yaml\)/, - ) assert.match(loggedText(calls), /Running: pnpm run dev/) }) -test('CLI explains where the package manager choice comes from', async () => { +test('CLI shows the project and its package manager in the header', async () => { const cases = [ [ - { name: 'yarn', source: 'packageManager' }, - /yarn \(from the packageManager field\)/, + { name: 'pnpm', source: 'pnpm-lock.yaml' }, + /◆ dev-workspace › p ─+ pnpm · pnpm-lock\.yaml ─╮/, ], - [{ name: 'npm', source: 'default' }, /npm \(default\)/], + [{ name: 'yarn', source: 'packageManager' }, /yarn · packageManager field/], + [{ name: 'npm', source: 'default' }, /npm · default/], ] for (const [detected, expected] of cases) { @@ -895,7 +907,7 @@ test('CLI explains where the package manager choice comes from', async () => { await createCli(dependencies).run() - assert.match(loggedText(calls), expected) + assert.match(menuText(calls), expected) } }) @@ -1260,7 +1272,8 @@ test('CLI starts the script list on the last script run', async () => { await createCli(dependencies).run() - assert.deepEqual(scriptOptions, { lastScript: 'build' }) + assert.equal(scriptOptions.lastScript, 'build') + assert.equal(typeof scriptOptions.header, 'function') }) test('CLI keeps going when the history cannot be saved', async () => { diff --git a/test/list.test.js b/test/list.test.js index 6cb5473..46a9b55 100644 --- a/test/list.test.js +++ b/test/list.test.js @@ -88,6 +88,12 @@ function createTerminal({ columns = 60, rows = 30, now } = {}) { return terminal } +// A line with `right` aligned to the list's right edge: a 60-column terminal +// leaves 59 columns, as the last one stays free. +function aligned(left, right, width = 59) { + return left + ' '.repeat(width - textWidth(left) - textWidth(right)) + right +} + const projects = ['api', 'billing-api', 'design-system', 'docs', 'web'].map( name => ({ label: name, value: name, icon: '📁' }), ) @@ -138,14 +144,17 @@ test('select draws the list and returns the chosen value', async () => { }) assert.deepEqual(terminal.screen(), [ - ' Select a project type to search', - ' ❯ 📁 api', - ' 📁 billing-api', - ' 📁 design-system', - ' 📁 docs', - ' 📁 web', + aligned(' Select a project', 'type to search'), + '', + ' ❯ 📁 api', + ' 📁 billing-api', + ' 📁 design-system', + ' 📁 docs', + ' 📁 web', + ` ${'─'.repeat(57)}`, ' Change workspace', ' Exit', + '', ' ↑↓ move · Enter select', ]) @@ -155,7 +164,7 @@ test('select draws the list and returns the chosen value', async () => { // The list is replaced by a one-line summary of the answer. assert.ok( terminal.written.endsWith( - '\x1b[8A\r\x1b[J Select a project design-system\n\x1b[?25h', + '\x1b[11A\r\x1b[J Select a project design-system\n\x1b[?25h', ), ) }) @@ -260,8 +269,10 @@ test('typing filters the list, best match first, and hides actions', async () => assert.deepEqual(terminal.screen(), [ ' Select a project api', - ' ❯ 📁 api', - ' 📁 billing-api', + '', + ' ❯ 📁 api', + ' 📁 billing-api', + '', ' ↑↓ move · Enter select · Esc clear search', ]) @@ -282,9 +293,9 @@ test('Backspace edits the search and Escape clears it', async t => { assert.ok(terminal.screen().some(line => line.includes('No matches'))) terminal.type(KEYS.backspace) - assert.deepEqual(terminal.screen().slice(1, 3), [ - ' ❯ 📁 design-system', - ' 📁 docs', + assert.deepEqual(terminal.screen().slice(2, 4), [ + ' ❯ 📁 design-system', + ' 📁 docs', ]) // Enter does nothing while nothing matches. @@ -292,7 +303,7 @@ test('Backspace edits the search and Escape clears it', async t => { t.mock.timers.tick(50) // The full list is back, actions included, with the cursor kept. - assert.equal(terminal.screen().length, 9) + assert.equal(terminal.screen().length, 12) terminal.type(KEYS.escape, KEYS.up, KEYS.enter) @@ -306,7 +317,7 @@ test('Escape keeps the selected item when clearing the search', async t => { terminal.type('w', 'e', KEYS.escape) t.mock.timers.tick(50) - assert.ok(terminal.screen().includes(' ❯ 📁 web')) + assert.ok(terminal.screen().includes(' ❯ 📁 web')) terminal.type(KEYS.enter) assert.equal(await result, 'web') @@ -323,7 +334,7 @@ test('an arrow key split over two chunks is not read as Escape', async t => { // The search is kept, and Down moved to the second match. assert.ok(terminal.screen()[0].includes('Pick a')) - assert.ok(terminal.screen().includes(' ❯ 📁 billing-api')) + assert.ok(terminal.screen().includes(' ❯ 📁 billing-api')) terminal.type(KEYS.enter) assert.equal(await result, 'billing-api') @@ -357,12 +368,14 @@ test('select skips disabled items and separators', async () => { ], }) - assert.deepEqual(terminal.screen().slice(0, 6), [ - ' Pick type to search', - ' Recent', + assert.deepEqual(terminal.screen().slice(0, 8), [ + aligned(' Pick', 'type to search'), + '', + ' RECENT', ' ❯ web', - ' Projects', - ' notes (no package.json)', + '', + ' PROJECTS', + aligned(' notes', '(no package.json)'), ' api', ]) @@ -371,27 +384,31 @@ test('select skips disabled items and separators', async () => { assert.equal(await result, 'api') }) -test('select starts on the default value and shows its description', async () => { +test('select starts on the default value and lines up the details', async () => { const terminal = createTerminal() const result = terminal.select({ message: 'Select a script', items: [ - { label: 'dev', value: 'dev', description: 'vite' }, + { label: 'dev', value: 'dev', detail: 'vite' }, { label: 'build', value: 'build', - description: 'vite build', - hint: '(last run)', + detail: 'vite build', + hint: 'last run', }, + { label: 'Back', value: null, action: true }, ], default: 'build', }) assert.deepEqual(terminal.screen(), [ - ' Select a script type to search', - ' dev', - ' ❯ build (last run)', - ' vite build', + aligned(' Select a script', 'type to search'), + '', + ' dev vite', + aligned(' ❯ build vite build', 'last run'), + ` ${'─'.repeat(57)}`, + ' Back', + '', ' ↑↓ move · Enter select', ]) @@ -399,6 +416,114 @@ test('select starts on the default value and shows its description', async () => assert.equal(await result, 'build') }) +test('a detail is cut to fit, keeping its end whole', async () => { + const terminal = createTerminal({ columns: 40 }) + const result = terminal.select({ + message: 'Pick', + items: [ + { + label: 'build', + value: 1, + detail: `node ${'x'.repeat(100)}.js`, + detailEnd: ' (+ prebuild)', + hint: 'last run', + }, + // Each 日 takes two columns. + { label: 'echo', value: 2, detail: `echo ${'日'.repeat(40)}` }, + ], + }) + + const [build, echo] = terminal.screen().slice(2, 4) + + assert.equal(build, ' ❯ build nod… (+ prebuild) last run') + assert.ok(echo.endsWith('…'), echo) + assert.ok(textWidth(echo) <= 39, echo) + + terminal.type(KEYS.enter) + await result +}) + +test('a tag follows the label when the line has no room to align it', async () => { + const terminal = createTerminal({ columns: 20 }) + const result = terminal.select({ + message: 'Pick', + items: [ + { label: 'a-long-name', value: 1, detail: 'vite', hint: 'last run' }, + ], + }) + + // 19 columns: no room for the detail, and the tag is cut at the edge. + assert.equal(terminal.screen()[2], ' ❯ a-long-name la') + + terminal.type(KEYS.enter) + await result +}) + +test('a header and a body are drawn above the message, and the header stays', async () => { + const terminal = createTerminal({ rows: 14 }) + const widths = [] + const result = terminal.select({ + message: 'Pick', + items: projects, + header: width => { + widths.push(width) + return [[[' '], ['[box]', 'dim']]] + }, + body: [['Could not read package.json', 'red'], ['Fix it.']], + mouse: true, + }) + + assert.deepEqual(terminal.screen().slice(0, 7), [ + ' [box]', + '', + ' Could not read package.json', + ' Fix it.', + '', + aligned(' Pick', 'type to search'), + '', + ]) + assert.equal(widths.at(-1), 59) + + // 14 rows: the header, body, message, help and blank lines take 9, and one + // row stays free, which leaves room for 4 items. + assert.match(terminal.screen().at(-1), /1\/5$/) + + // 13 lines ending on row 20: api is on row 15. + terminal.reply(20) + terminal.click(16) + terminal.reply(20) + terminal.click(16) + + assert.equal(await result, 'billing-api') + // The summary replaces the list, under the header. + assert.ok(terminal.written.includes('\x1b[J [box]\n\n Pick billing-api\n')) +}) + +test('hover gives the whole row a grey background when colours are on', async () => { + const terminal = createTerminal() + const select = createList({ + input: terminal.input, + output: terminal.output, + exitEvents: terminal.exitEvents, + useColors: true, + }) + const result = select({ message: 'Pick', items: projects, mouse: true }) + + // 9 lines ending on row 10: billing-api is on row 5. + terminal.reply(10) + terminal.hover(5) + + const line = terminal.screen()[3] + + assert.ok(line.startsWith('\x1b[100m \x1b[49m'), JSON.stringify(line)) + assert.equal(textWidth(line), 59) + assert.ok(line.endsWith(`\x1b[100m${' '.repeat(41)}\x1b[49m`), line) + assert.ok(!terminal.screen()[2].includes('\x1b[100m')) + + terminal.type(KEYS.enter) + await result +}) + test('a list that is not searchable ignores typing', async () => { const terminal = createTerminal() const result = terminal.select({ @@ -426,19 +551,20 @@ test('a long list scrolls to keep the cursor visible', async () => { })) const result = terminal.select({ message: 'Pick', items }) - // 10 rows leave room for 6 items, the message and the help line. - assert.equal(terminal.screen().length, 8) + // 10 rows leave room for 5 items next to the message, the help line and + // the blank lines between them. + assert.equal(terminal.screen().length, 9) assert.match(terminal.screen().at(-1), /1\/40$/) terminal.type(KEYS.pageDown) - assert.ok(terminal.screen().includes(' ❯ project-6')) - assert.match(terminal.screen().at(-1), /6\/40$/) + assert.ok(terminal.screen().includes(' ❯ project-5')) + assert.match(terminal.screen().at(-1), /5\/40$/) terminal.type(KEYS.end) - assert.equal(terminal.screen().at(-2), ' ❯ project-40') + assert.equal(terminal.screen().at(-3), ' ❯ project-40') terminal.type(KEYS.home) - assert.equal(terminal.screen()[1], ' ❯ project-1') + assert.equal(terminal.screen()[2], ' ❯ project-1') terminal.type(KEYS.up, KEYS.enter) assert.equal(await result, 1) @@ -458,12 +584,12 @@ test('select redraws in place, and never wider than the terminal', async () => { terminal.written = '' terminal.type('a') - // Back up two lines (three were drawn), then clear and draw again. - assert.ok(terminal.written.startsWith('\x1b[2A\r\x1b[J')) + // Back up four lines (five were drawn), then clear and draw again. + assert.ok(terminal.written.startsWith('\x1b[4A\r\x1b[J')) terminal.output.columns = 40 terminal.output.emit('resize') - assert.ok(terminal.screen()[1].endsWith('a-very-long-project-name')) + assert.ok(terminal.screen()[2].endsWith('a-very-long-project-name')) terminal.type(KEYS.enter) await result @@ -476,19 +602,20 @@ test('select redraws from its first line after the terminal gets narrower', asyn items: [{ label: 'a-very-long-project-name', value: 1, icon: '📁' }], }) - // The three lines are 22, 32 and 24 columns wide. At 20 columns the - // terminal rewraps each of them onto two rows: six rows, so back up five. + // The message, item and help lines are 39, 31 and 24 columns wide, with a + // blank line after the first two. At 20 columns the terminal rewraps each + // of the three onto two rows: eight rows, so back up seven. terminal.written = '' terminal.output.columns = 20 terminal.output.emit('resize') - assert.ok(terminal.written.startsWith('\x1b[5A\r\x1b[J')) + assert.ok(terminal.written.startsWith('\x1b[7A\r\x1b[J')) // The new drawing fits, so the next one backs up its own lines only. terminal.written = '' terminal.type('a') - assert.ok(terminal.written.startsWith('\x1b[2A\r\x1b[J')) + assert.ok(terminal.written.startsWith('\x1b[4A\r\x1b[J')) terminal.type(KEYS.enter) await result @@ -506,7 +633,7 @@ test('select highlights matched characters when colours are on', async () => { terminal.type('d', 'c') - const line = terminal.screen()[1] + const line = terminal.screen()[2] assert.ok(line.includes('\x1b[36m❯ \x1b[39m'), JSON.stringify(line)) assert.ok(line.includes('\x1b[4m\x1b[1m\x1b[36md'), JSON.stringify(line)) @@ -608,10 +735,11 @@ test('a closing list waits for its last position reply, but not for long', async mouse: true, }) + // 9 lines ending on row 10: api is on row 4. time += 300 terminal.reply(10) terminal.hover(6) - terminal.type('\x1b[<0;8;5M\x1b[10;1R\x1b[10;1R') + terminal.type('\x1b[<0;8;4M\x1b[10;1R\x1b[10;1R') assert.equal(await second, 'api') assert.equal(terminal.input.listenerCount('data'), 0) @@ -638,20 +766,23 @@ test('a click selects an item and a second click opens it', async () => { mouse: true, }) - // 9 lines (message, 7 items, help) ending on row 20: api is on row 13. + // 12 lines (message, 5 items, rule, 2 actions, help and the blank lines) + // ending on row 20: api is on row 11, the rule on row 16. terminal.reply(20) - terminal.click(15) + terminal.click(13) - assert.equal(terminal.screen()[3], ' ❯ 📁 design-system') + assert.equal(terminal.screen()[4], ' ❯ 📁 design-system') - // The help line and rows outside the list do nothing. + // The help line, the rule, blank lines and rows outside the list do nothing. terminal.reply(20) terminal.click(20) - terminal.click(12) + terminal.click(16) + terminal.click(10) + terminal.click(8) - assert.equal(terminal.screen()[3], ' ❯ 📁 design-system') + assert.equal(terminal.screen()[4], ' ❯ 📁 design-system') - terminal.click(15) + terminal.click(13) assert.equal(await result, 'design-system') }) @@ -665,9 +796,9 @@ test('Back and Exit entries can be clicked', async () => { }) terminal.reply(20) - terminal.click(19) + terminal.click(18) terminal.reply(20) - terminal.click(19) + terminal.click(18) assert.equal(await result, null) }) @@ -681,9 +812,10 @@ test('clicks are ignored briefly after an item opens', async () => { mouse: true, }) - // The first press of a double-click opens api, which is selected. + // The first press of a double-click opens api, which is selected: 9 lines + // ending on row 10 put it on row 4. terminal.reply(10) - terminal.click(5) + terminal.click(4) assert.equal(await first, 'api') const second = terminal.select({ @@ -694,13 +826,13 @@ test('clicks are ignored briefly after an item opens', async () => { // The second press lands on the next list and is ignored. terminal.reply(10) - terminal.click(6) - assert.equal(terminal.screen()[1], ' ❯ 📁 api') + terminal.click(5) + assert.equal(terminal.screen()[2], ' ❯ 📁 api') time += 300 - terminal.click(6) + terminal.click(5) terminal.reply(10) - terminal.click(6) + terminal.click(5) assert.equal(await second, 'billing-api') }) @@ -718,17 +850,17 @@ test('clicks skip separators and disabled items', async () => { mouse: true, }) - // 6 lines ending on row 6: the separator is on row 2. - terminal.reply(6) - terminal.click(2) - terminal.click(4) - terminal.reply(6) + // 8 lines ending on row 8: the separator is on row 3, old on row 5. + terminal.reply(8) + terminal.click(3) + terminal.click(5) + terminal.reply(8) - assert.equal(terminal.screen()[2], ' ❯ web') + assert.equal(terminal.screen()[3], ' ❯ web') - terminal.click(5) - terminal.reply(6) - terminal.click(5) + terminal.click(6) + terminal.reply(8) + terminal.click(6) assert.equal(await result, 'api') }) @@ -741,13 +873,14 @@ test('hover marks the item under the pointer, and the wheel moves the cursor', a mouse: true, }) + // 9 lines ending on row 10: design-system is on row 6. terminal.reply(10) - terminal.hover(7) + terminal.hover(6) - assert.deepEqual(terminal.screen().slice(1, 4), [ - ' ❯ 📁 api', - ' 📁 billing-api', - ' › 📁 design-system', + assert.deepEqual(terminal.screen().slice(2, 5), [ + ' ❯ 📁 api', + ' 📁 billing-api', + ' › 📁 design-system', ]) // Moving within the same item neither redraws nor asks again. @@ -755,18 +888,18 @@ test('hover marks the item under the pointer, and the wheel moves the cursor', a const before = terminal.written - terminal.hover(7) + terminal.hover(6) assert.equal(terminal.written, before) - terminal.type('\x1b[<65;8;7M', '\x1b[<65;8;7M') + terminal.type('\x1b[<65;8;6M', '\x1b[<65;8;6M') - assert.deepEqual(terminal.screen().slice(1, 4), [ - ' 📁 api', - ' 📁 billing-api', - ' ❯ 📁 design-system', + assert.deepEqual(terminal.screen().slice(2, 5), [ + ' 📁 api', + ' 📁 billing-api', + ' ❯ 📁 design-system', ]) - terminal.type('\x1b[<64;8;7M', KEYS.enter) + terminal.type('\x1b[<64;8;6M', KEYS.enter) assert.equal(await result, 'billing-api') }) @@ -781,7 +914,7 @@ test('pressing the wheel opens the selected item, wherever the pointer is', asyn }) assert.equal( - terminal.screen()[6], + terminal.screen()[8], ' ↑↓ move · Enter select · Middle-click select', ) @@ -803,7 +936,7 @@ test('pressing the wheel opens the selected item, wherever the pointer is', asyn terminal.reply(10) terminal.type('\x1b[<1;8;10M') terminal.reply(10) - assert.equal(terminal.screen()[0], ' Pick type to search') + assert.equal(terminal.screen()[0], aligned(' Pick', 'type to search')) time += 300 terminal.type('\x1b[<1;8;10M') @@ -819,19 +952,19 @@ test('clicks follow the list when it scrolls', async () => { })) const result = terminal.select({ message: 'Pick', items, mouse: true }) - // 4 visible items, so 6 lines, ending on the last row. + // 3 visible items, so 7 lines, ending on the last row. terminal.reply(8) terminal.type(KEYS.end) terminal.reply(8) - assert.equal(terminal.screen()[1], ' project-6') + assert.equal(terminal.screen()[2], ' project-7') - // project-6 is on row 4, so project-7 on row 5. + // project-7 is on row 4, so project-8 on row 5. terminal.click(5) terminal.reply(8) terminal.click(5) - assert.equal(await result, 7) + assert.equal(await result, 8) }) test('a position reply that was not asked for is ignored', async () => { @@ -845,9 +978,9 @@ test('a position reply that was not asked for is ignored', async () => { terminal.reply(10) // Shift+F3 in some terminals looks like a reply. terminal.reply(1) - terminal.click(6) + terminal.click(5) - assert.equal(terminal.screen()[2], ' ❯ 📁 billing-api') + assert.equal(terminal.screen()[3], ' ❯ 📁 billing-api') terminal.type(KEYS.enter) assert.equal(await result, 'billing-api') @@ -862,8 +995,10 @@ test('a note is shown under the list, wrapped to its width', async () => { }) assert.deepEqual(terminal.screen(), [ - ' Pick type to search', - ' ❯ 📁 api', + aligned(' Pick', 'type to search', 29), + '', + ' ❯ 📁 api', + '', ' ↑↓ move · Enter select', '', ' Mouse support has not been', diff --git a/test/prompts.test.js b/test/prompts.test.js index faadc38..f19596e 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -5,7 +5,6 @@ import { RUN_WITH_ARGUMENTS, createPrompts, } from '../lib/prompts.js' -import { textWidth } from '../lib/width.js' function createPromptMocks(results = {}) { const calls = { @@ -76,19 +75,33 @@ test('chooseProject lists projects, then workspace and exit actions', async () = assert.deepEqual(calls.select[0], { message: 'Select a project', items: [ - { icon: '📁', label: 'project-a', value: projects[0] }, - { icon: '📁', label: 'project-b', value: projects[1] }, + { label: 'project-a', value: projects[0] }, + { label: 'project-b', value: projects[1] }, { - icon: '⚙️', + icon: '⚙', label: 'Change workspace', value: CHANGE_WORKSPACE, action: true, }, - { icon: '↩', label: 'Exit', value: null, action: true }, + { icon: '✕', label: 'Exit', value: null, action: true }, ], }) }) +test('chooseProject passes the header and body to the list', async () => { + const { calls, prompts } = createPromptMocks({ select: null }) + const header = () => [] + const body = [['No project folders in this workspace.', 'yellow']] + + await prompts.chooseProject([], { header, body }) + await prompts.chooseProject([], { header, body: [] }) + + assert.equal(calls.select[0].header, header) + assert.deepEqual(calls.select[0].body, body) + // An empty body is left out. + assert.equal(Object.hasOwn(calls.select[1], 'body'), false) +}) + test('chooseProject supports an empty project list', async () => { const { calls, prompts } = createPromptMocks({ select: null }) @@ -112,7 +125,15 @@ test('chooseProject shows recent projects first, under a heading', async () => { assert.deepEqual( calls.select[0].items.map(item => item.separator ?? item.label), - ['Recent', 'web', 'api', 'Projects', 'docs', 'Change workspace', 'Exit'], + [ + 'Recent', + 'web', + 'api', + 'All projects', + 'docs', + 'Change workspace', + 'Exit', + ], ) }) @@ -126,13 +147,8 @@ test('chooseProject disables folders without a package.json', async () => { await prompts.chooseProject(projects) assert.deepEqual(calls.select[0].items.slice(0, 2), [ - { icon: '📁', label: 'web', value: projects[0] }, - { - icon: '📁', - label: 'notes', - value: projects[1], - disabled: '(no package.json)', - }, + { label: 'web', value: projects[0] }, + { label: 'notes', value: projects[1], disabled: 'no package.json' }, ]) }) @@ -149,30 +165,44 @@ test('chooseScript lists scripts with their command, then the actions', async () assert.deepEqual(calls.select[0], { message: 'Select a script', items: [ - { - icon: '▶', - label: 'dev', - value: scripts[0], - description: 'nuxt dev', - }, - { - icon: '▶', - label: 'build', - value: scripts[1], - description: 'nuxt build', - }, + { label: 'dev', value: scripts[0], detail: 'nuxt dev' }, + { label: 'build', value: scripts[1], detail: 'nuxt build' }, { icon: '…', - label: 'Run with arguments…', + label: 'Run with arguments', value: RUN_WITH_ARGUMENTS, action: true, }, - { icon: '↩', label: 'Back to projects', value: null, action: true }, + { icon: '←', label: 'Back to projects', value: null, action: true }, ], default: undefined, }) }) +test('chooseScript keeps the hooks note apart, so the list never cuts it', async () => { + const { calls, prompts } = createPromptMocks({ select: null }) + const header = () => [] + + await prompts.chooseScript( + [ + { + name: 'build', + command: 'vite build', + hooks: ['prebuild', 'postbuild'], + }, + ], + { header }, + ) + + assert.deepEqual(calls.select[0].items[0], { + label: 'build', + value: calls.select[0].items[0].value, + detail: 'vite build', + detailEnd: ' (+ prebuild, postbuild)', + }) + assert.equal(calls.select[0].header, header) +}) + test('chooseScript starts on the last script run', async () => { const scripts = [ { name: 'dev', command: 'nuxt dev' }, @@ -183,7 +213,7 @@ test('chooseScript starts on the last script run', async () => { await prompts.chooseScript(scripts, { lastScript: 'build' }) assert.equal(calls.select[0].default, scripts[1]) - assert.equal(calls.select[0].items[1].hint, '(last run)') + assert.equal(calls.select[0].items[1].hint, 'last run') assert.equal(calls.select[0].items[0].hint, undefined) }) @@ -207,7 +237,7 @@ test('chooseScript supports an empty script list', async () => { assert.equal(result, null) assert.deepEqual(calls.select[0].items, [ - { icon: '↩', label: 'Back to projects', value: null, action: true }, + { icon: '←', label: 'Back to projects', value: null, action: true }, ]) }) @@ -232,17 +262,21 @@ test('waitForBack uses its default message', async () => { assert.equal(result, true) assert.deepEqual(calls.select[0], { message: 'Return to projects', - items: [{ icon: '↩', label: 'Back', value: true }], + items: [{ icon: '←', label: 'Back', value: true }], searchable: false, }) }) -test('waitForBack accepts a custom message', async () => { +test('waitForBack accepts a custom message, header and body', async () => { const { calls, prompts } = createPromptMocks({ select: true }) + const header = () => [] + const body = [['Could not read package.json', 'red']] - await prompts.waitForBack('Return to scripts') + await prompts.waitForBack('Return to scripts', { header, body }) assert.equal(calls.select[0].message, 'Return to scripts') + assert.equal(calls.select[0].header, header) + assert.deepEqual(calls.select[0].body, body) }) test('waitAfterCommand offers to run again first', async () => { @@ -255,84 +289,12 @@ test('waitAfterCommand offers to run again first', async () => { message: 'What next?', items: [ { icon: '↻', label: 'Run again', value: true }, - { icon: '↩', label: 'Back to scripts', value: false }, + { icon: '←', label: 'Back to scripts', value: false }, ], searchable: false, }) }) -test('chooseScript fits the command to the terminal width', async () => { - const calls = [] - const select = async options => { - calls.push(options) - return null - } - const long = `node ${'x'.repeat(200)}.js` - - for (const [columns, expectedLength] of [ - [40, 37], - [120, 117], - [undefined, 77], - [5, 20], - ]) { - calls.length = 0 - - await createPrompts({ select, columns: () => columns }).chooseScript([ - { name: 'build', command: long }, - ]) - - const { description } = calls[0].items[0] - - assert.equal(description.length, expectedLength, String(columns)) - assert.ok(description.endsWith('…')) - } - - calls.length = 0 - await createPrompts({ select, columns: () => 40 }).chooseScript([ - { name: 'dev', command: 'node server.js' }, - ]) - assert.equal(calls[0].items[0].description, 'node server.js') -}) - -test('chooseScript keeps the hooks note when shortening the command', async () => { - const calls = [] - const select = async options => { - calls.push(options) - return null - } - - await createPrompts({ select, columns: () => 50 }).chooseScript([ - { - name: 'build', - command: `node ${'x'.repeat(100)}.js`, - hooks: ['prebuild', 'postbuild'], - }, - ]) - - const { description } = calls[0].items[0] - - assert.equal(description.length, 47) - assert.ok(description.endsWith('… (+ prebuild, postbuild)'), description) -}) - -test('chooseScript measures the command in columns, not characters', async () => { - const calls = [] - const select = async options => { - calls.push(options) - return null - } - - // Each 日 takes two columns. - await createPrompts({ select, columns: () => 40 }).chooseScript([ - { name: 'build', command: `echo ${'日'.repeat(40)}` }, - ]) - - const { description } = calls[0].items[0] - - assert.equal(textWidth(description), 36) - assert.ok(description.endsWith('…')) -}) - test('useMouse turns the mouse on for every menu and shows the note once', async () => { const { calls, prompts } = createPromptMocks({ select: null }) diff --git a/test/ui.test.js b/test/ui.test.js index c9fd915..809c6ac 100644 --- a/test/ui.test.js +++ b/test/ui.test.js @@ -1,6 +1,6 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { createUi } from '../lib/ui.js' +import { createUi, headerLines } from '../lib/ui.js' import { textWidth } from '../lib/width.js' test('color returns plain text when colors are disabled', () => { @@ -29,78 +29,76 @@ test('color returns plain text for an unknown shade', () => { assert.equal(color('Hello', 'purple'), 'Hello') }) -test('printHeader logs the default section and workspace', () => { - const lines = [] - const { printHeader } = createUi({ - useColors: false, - log: (...args) => lines.push(args.join(' ')), - }) - - printHeader('/projects') +// The header as plain text: each line's segments joined, without styles. +function header(options, width = 60) { + return headerLines(options, width).map(line => + line.map(([text]) => text).join(''), + ) +} - assert.ok(lines.some(line => line.includes('DEV WORKSPACE CLI'))) - assert.ok(lines.some(line => line.includes('DEVELOPER TOOLKIT'))) - assert.ok(lines.some(line => line.includes('WORKSPACE'))) - assert.ok(lines.some(line => line.includes('/projects'))) - assert.ok(lines.some(line => line.includes('PROJECT EXPLORER'))) +test('headerLines draws the name and workspace in a box', () => { + assert.deepEqual(header({ workspace: '/projects' }, 40), [ + ' ╭─ ◆ dev-workspace ──────────────────╮', + ' │ /projects │', + ' ╰────────────────────────────────────╯', + ]) }) -test('printHeader supports a custom section', () => { - const lines = [] - const { printHeader } = createUi({ - useColors: false, - log: (...args) => lines.push(args.join(' ')), - }) - - printHeader('/projects', 'PROJECT SCRIPTS') +test('headerLines shows the breadcrumb and the tag in the top border', () => { + const [top] = header( + { workspace: '/projects', crumbs: ['web-app'], tag: 'npm · default' }, + 60, + ) - assert.ok(lines.some(line => line.includes('PROJECT SCRIPTS'))) + assert.equal( + top, + ' ╭─ ◆ dev-workspace › web-app ──────────── npm · default ─╮', + ) }) -test('printHeader applies colors when enabled', () => { - const lines = [] - const { printHeader } = createUi({ - useColors: true, - log: (...args) => lines.push(args.join(' ')), - }) +test('headerLines styles the parts of the box', () => { + const [top] = headerLines({ workspace: '/p', crumbs: ['web'] }, 40) - printHeader('/projects') - - assert.ok(lines.some(line => line.includes('\x1b[36m'))) - assert.ok(lines.some(line => line.includes('\x1b[0m'))) + assert.deepEqual(top.slice(1, 6), [ + ['╭─ ', 'dim'], + ['◆', 'cyan'], + [' dev-workspace', 'bold'], + [' › ', 'dim'], + ['web'], + ]) }) -// The header lines, without the blank line before them. -function headerLines(workspace) { - const lines = [] - const { printHeader } = createUi({ - useColors: false, - log: (...args) => lines.push(args.join(' ')), - }) - - printHeader(workspace) - - return lines.filter(Boolean) -} +test('headerLines drops the tag, then cuts the breadcrumb, when short of room', () => { + const options = { + workspace: '/projects', + crumbs: ['a-project-with-a-long-name'], + tag: 'pnpm · pnpm-lock.yaml', + } + const [wide] = header(options, 70) + const [narrow] = header(options, 40) -// The 44-column box, indented by two columns. -const HEADER_LINE_WIDTH = 2 + 44 + assert.ok(wide.includes('a-project-with-a-long-name'), wide) + assert.ok(!wide.includes('pnpm'), wide) + assert.ok(narrow.includes('› a-project-wit…'), narrow) +}) -test('printHeader keeps its border aligned around wide characters', () => { - const lines = headerLines('/projets/日本語/📦-app') +test('headerLines keeps its border aligned around wide characters', () => { + for (const width of [30, 60, 100]) { + const lines = header( + { workspace: '/projets/日本語/📦-app', crumbs: ['日本語'], tag: 'npm' }, + width, + ) - assert.ok(lines.some(line => line.includes('日本語/📦-app'))) - assert.ok(lines.some(line => line.includes('⚙️ DEVELOPER TOOLKIT'))) + assert.ok(lines[1].includes('日本語/📦-app') || width < 40, lines[1]) - for (const line of lines) { - assert.equal(textWidth(line), HEADER_LINE_WIDTH, line) + for (const line of lines) assert.equal(textWidth(line), width, line) } }) -test('printHeader cuts a long workspace path to fit', () => { - const lines = headerLines(`/${'very-long-folder/'.repeat(10)}`) +test('headerLines cuts a long workspace path to fit', () => { + const lines = header({ workspace: `/${'very-long-folder/'.repeat(10)}` }, 50) - for (const line of lines) { - assert.equal(textWidth(line), HEADER_LINE_WIDTH, line) - } + assert.ok(lines[1].endsWith('… │'), lines[1]) + + for (const line of lines) assert.equal(textWidth(line), 50, line) }) diff --git a/test/width.test.js b/test/width.test.js index c415fa6..fe73e62 100644 --- a/test/width.test.js +++ b/test/width.test.js @@ -1,7 +1,7 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { fitText, textWidth, wrapText } from '../lib/width.js' +import { fitText, textWidth, truncateText, wrapText } from '../lib/width.js' test('textWidth counts emoji and wide characters as two columns', () => { assert.equal(textWidth('web'), 3) @@ -41,3 +41,11 @@ test('wrapText breaks between words and cuts words wider than a line', () => { assert.deepEqual(wrapText('日本', 1), ['日', '本']) assert.deepEqual(wrapText('', 10), []) }) + +test('truncateText ends a shortened text with an ellipsis', () => { + assert.equal(truncateText('vite build', 20), 'vite build') + assert.equal(truncateText('vite build', 6), 'vite …') + // Each 日 takes two columns, so only two fit before the ellipsis. + assert.equal(truncateText('日本語です', 6), '日本…') + assert.equal(truncateText('vite', 0), '') +}) From 6368f2f4b28de46ce056bf55702e0a401270fa62 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:54:50 +0100 Subject: [PATCH 02/23] docs: tick the framed header and menu layout --- ROADMAP.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index dbb7a28..1a18f9a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -155,8 +155,8 @@ The check script draws its items on fixed rows, so its clicks are offset once th - [x] **Correct layout:** measure text by its terminal width (`string-width`) so emoji and wide characters never break the header border. - [ ] **Path truncation:** shorten long workspace paths in the middle (`C:/Users/…/projects/web`) instead of cutting off the end. - [ ] **Alternate screen:** show the menus on the terminal's alternate screen, as `less` and `vim` do, leaving it before a script runs and on every exit path. Resizing the window can then redraw the whole screen, header included, without leaving broken lines or duplicate headers in the scrollback. -- [ ] **Framed header:** the same small box on every screen instead of the 11-line header, with `◆ dev-workspace` and a breadcrumb (`› web-app › build`) set in its top border and the workspace inside. One thin line style and only single-width symbols, so it lines up in every terminal. The list draws it, so it redraws with the list and holds the buttons [#30](https://github.com/modulane/dev-workspace-cli/issues/30). -- [ ] **Menu layout:** aligned columns (name, dim details such as the script's command, tags on the right), uppercase group titles, one blank line between the parts of the screen, single-width symbols on actions only, and a full-row hover highlight that falls back to `›` with `NO_COLOR` [#67](https://github.com/modulane/dev-workspace-cli/issues/67). +- [x] **Framed header:** the same small box on every screen instead of the 11-line header, with `◆ dev-workspace` and a breadcrumb (`› web-app › build`) set in its top border and the workspace inside. One thin line style and only single-width symbols, so it lines up in every terminal. The list draws it, so it redraws with the list and holds the buttons [#30](https://github.com/modulane/dev-workspace-cli/issues/30). +- [x] **Menu layout:** aligned columns (name, dim details such as the script's command, tags on the right), uppercase group titles, one blank line between the parts of the screen, single-width symbols on actions only, and a full-row hover highlight that falls back to `›` with `NO_COLOR` [#67](https://github.com/modulane/dev-workspace-cli/issues/67). - [ ] **Run result:** show the command before a script's output, and after it `✔ build finished in 4.2s` or `✖ build failed · exit 1 · 0.8s`, with "Run again" and "Back" side by side [#69](https://github.com/modulane/dev-workspace-cli/issues/69). - [ ] **Escape goes back:** with an empty search, Escape returns to the previous screen, or exits from the project list [#70](https://github.com/modulane/dev-workspace-cli/issues/70). - [ ] **Consistent theme:** apply one theme to every prompt, with all colours going through `color()` so `NO_COLOR` and non-TTY output are always respected. Support `FORCE_COLOR`. From 9b9b9050d4cdf1db0218f24c6794faedbb597518 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:21:29 +0100 Subject: [PATCH 03/23] feat: apply one colour theme to every prompt and support FORCE_COLOR Closes #31 --- CONTRIBUTING.md | 4 +- README.md | 32 +++++++----- ROADMAP.md | 2 +- lib/args.js | 7 ++- lib/list.js | 24 ++------- lib/prompts.js | 10 +++- lib/ui.js | 114 ++++++++++++++++++++++++++++++++++--------- test/args.test.js | 3 ++ test/prompts.test.js | 7 +++ test/ui.test.js | 91 ++++++++++++++++++++++++++++++++-- 10 files changed, 228 insertions(+), 66 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a38ef6..a6019f2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,10 +69,12 @@ node scripts/try-install.js --again -- web dev # with arguments for dws | `list.js` | The list used by every menu: keys, mouse, drawing, search | | `fuzzy.js` | Fuzzy matching and ranking for the list search | | `width.js` | Measuring, cutting and wrapping text by its terminal width | -| `ui.js` | Colours, the header box and screen clearing | +| `ui.js` | The colour theme, the header box and screen clearing | Menus use the list in `list.js`, which owns the terminal while it is open; free-text and yes/no questions still use `@inquirer/prompts`. The list also draws the header box from `ui.js`, which `cli.js` passes as `header`, so the whole screen redraws together. Test the list through `createList()` with fake input and output streams, as `test/list.test.js` does, rather than in a real terminal. With `mouse: true`, the list asks for the cursor position after each drawing; a test answers with a reply such as `` (the last line is on row 20) before sending clicks. To see how a real terminal reports the mouse, run `node scripts/mouse-check.js` in it, and record the result in the roadmap's terminal support table and in `detectTerminal()`. +Every colour comes from the theme in `ui.js`: `color()` for plain output, `styleText()` for the list, and `inquirerTheme()` for the `@inquirer/prompts` questions. Do not write ANSI codes elsewhere, so `NO_COLOR` and `FORCE_COLOR` are always respected. + Each file in `lib/` starts with a comment describing what it contains and how it is used. Keep that comment accurate when you change the file. Modules receive their side effects (file system, prompts, process spawning) as parameters with real defaults, so tests can replace them with fakes. Tests live in `test/`, one file per module. diff --git a/README.md b/README.md index acfcd27..6f7349f 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,12 @@ Each list also has entries to go **Back**, **Exit**, or **Change workspace**, un Every menu opens with a small box that shows where you are: the tool's name, followed by the project you are in (`◆ dev-workspace › web-app`), the workspace folder, and in a project, its package manager on the right. Each script's command is shown next to its name, in a column of its own, and tags such as `last run` sit at the right edge. The layout stays within 100 columns on wide terminals. Long workspace paths and script commands are cut with `…` to fit, and emoji or CJK characters in folder names never break the layout. +### Colours + +Colour marks where you are, and little else: cyan for the selected entry, the current project in the header and your search, green, red and yellow for results and warnings, and dim text for details. The workspace and arguments prompts use the same colours as the menus. Everything still reads without colour: the selected entry keeps its `❯` marker, and group titles are in capitals. + +Colours are on in a terminal and off when output is redirected to a file or another program. Set `NO_COLOR` to turn them off, or `FORCE_COLOR` to turn them on anyway (`FORCE_COLOR=0` turns them off). `FORCE_COLOR` wins when both are set, as in Node.js. + ### Searching Start typing in the project or script list to filter it. The characters you type must appear in the name in the same order, but not necessarily next to each other: `dsy` finds `design-system`. The best matches come first, preferring names that start with what you typed and matches at the start of words, and the matched characters are underlined. While you search, the **Back**, **Exit** and **Change workspace** entries are hidden, so Enter never picks one by accident. @@ -183,19 +189,19 @@ dws web dev -- --port 4000 # pass everything after -- to the script dev-workspace [options] [project [script] [-- arguments]] ``` -| Option | Description | -| ------------------------ | ----------------------------------------------------------- | -| `-w, --workspace ` | Use `` as the workspace and save it | -| `--no-mouse` | Use only the keyboard in menus, for this run | -| `--set-mouse ` | Save whether menus use the mouse | -| `--config-path` | Print the location of the configuration file | -| `--clear-history` | Forget the recent projects and last scripts | -| `--add-alias ` | Create another command that starts the CLI | -| `--remove-alias ` | Delete an alias created with `--add-alias` | -| `--list-aliases` | List the commands that start the CLI | -| `--reset` | Delete the configuration, history and custom aliases | -| `-v, --version` | Print the version | -| `-h, --help` | Show the help (coloured in a terminal; supports `NO_COLOR`) | +| Option | Description | +| ------------------------ | ------------------------------------------------------------ | +| `-w, --workspace ` | Use `` as the workspace and save it | +| `--no-mouse` | Use only the keyboard in menus, for this run | +| `--set-mouse ` | Save whether menus use the mouse | +| `--config-path` | Print the location of the configuration file | +| `--clear-history` | Forget the recent projects and last scripts | +| `--add-alias ` | Create another command that starts the CLI | +| `--remove-alias ` | Delete an alias created with `--add-alias` | +| `--list-aliases` | List the commands that start the CLI | +| `--reset` | Delete the configuration, history and custom aliases | +| `-v, --version` | Print the version | +| `-h, --help` | Show the help (coloured as described in [Colours](#colours)) | ## Aliases diff --git a/ROADMAP.md b/ROADMAP.md index 1a18f9a..8aad593 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -159,7 +159,7 @@ The check script draws its items on fixed rows, so its clicks are offset once th - [x] **Menu layout:** aligned columns (name, dim details such as the script's command, tags on the right), uppercase group titles, one blank line between the parts of the screen, single-width symbols on actions only, and a full-row hover highlight that falls back to `›` with `NO_COLOR` [#67](https://github.com/modulane/dev-workspace-cli/issues/67). - [ ] **Run result:** show the command before a script's output, and after it `✔ build finished in 4.2s` or `✖ build failed · exit 1 · 0.8s`, with "Run again" and "Back" side by side [#69](https://github.com/modulane/dev-workspace-cli/issues/69). - [ ] **Escape goes back:** with an empty search, Escape returns to the previous screen, or exits from the project list [#70](https://github.com/modulane/dev-workspace-cli/issues/70). -- [ ] **Consistent theme:** apply one theme to every prompt, with all colours going through `color()` so `NO_COLOR` and non-TTY output are always respected. Support `FORCE_COLOR`. +- [x] **Consistent theme:** apply one theme to every prompt, with all colours going through `color()` so `NO_COLOR` and non-TTY output are always respected. Support `FORCE_COLOR` [#31](https://github.com/modulane/dev-workspace-cli/issues/31). - [ ] **Project details:** show package manager, script count and Git branch (if any) next to each project, without slowing down the list (read lazily, cache per session). - [ ] **First-run experience:** suggest common folders that exist (`~/dev`, `~/projects`, `~/code`, `~/src`, `~/repos`) as choices, with "Enter another path" as the last option. - [x] **Typed paths:** the workspace prompt and `--workspace` accept the forms a shell would normally clean up: `~/projects`, quoted paths (as copied by Explorer's "Copy as path") and, outside Windows, escaped spaces (`my\ projects`). A missing folder is reported with the full path that was checked ([#9](https://github.com/modulane/dev-workspace-cli/issues/9)). diff --git a/lib/args.js b/lib/args.js index 1a5c11c..6e4a248 100644 --- a/lib/args.js +++ b/lib/args.js @@ -8,8 +8,8 @@ // // formatHelp() builds the `--help` text, which must list every option defined // here. It colours headings, commands and placeholders through the given -// function (ui.color), so NO_COLOR and non-TTY output stay plain; with no -// function it returns plain text. +// function (ui.color), so NO_COLOR, FORCE_COLOR and non-TTY output are +// respected; with no function it returns plain text. // // splitArguments() splits arguments typed at the "Run with arguments…" prompt // into a list, honouring single and double quotes. No shell is involved, so @@ -54,6 +54,9 @@ export function formatHelp(color = value => String(value)) { ${color('Environment:', 'bold')} ${color('DEV_WORKSPACE_CONFIG', 'cyan')} Use a custom configuration file path + ${color('NO_COLOR', 'cyan')} Turn colours off + ${color('FORCE_COLOR', 'cyan')} Turn colours on, even when output is not + a terminal (0 turns them off) ` } diff --git a/lib/list.js b/lib/list.js index 85445dd..d0404e4 100644 --- a/lib/list.js +++ b/lib/list.js @@ -21,7 +21,8 @@ // to fit, except its `detailEnd`), then the `hint` or `disabled` reason on // the right. Separators are shown in capitals, after a blank line, and a rule // separates the actions from the items above them. When the list closes, the -// header stays, followed by a one-line summary of the answer. +// header stays, followed by a one-line summary of the answer. Styles are +// applied with styleText() from ui.js, only when colours are on (useColors). // // The list owns the terminal while it is open: raw mode, key decoding // (parseKeys) and drawing. A chunk of input that ends in an unfinished @@ -61,7 +62,7 @@ import { StringDecoder } from 'node:string_decoder' import { fuzzyFilter } from './fuzzy.js' -import { USE_COLORS } from './ui.js' +import { USE_COLORS, styleText } from './ui.js' import { fitText, textWidth, truncateText, wrapText } from './width.js' const ESC = '\x1b' @@ -204,18 +205,6 @@ export function parseKeys(text) { return keys } -const STYLES = { - bold: ['\x1b[1m', '\x1b[22m'], - dim: ['\x1b[2m', '\x1b[22m'], - underline: ['\x1b[4m', '\x1b[24m'], - cyan: ['\x1b[36m', '\x1b[39m'], - green: ['\x1b[32m', '\x1b[39m'], - yellow: ['\x1b[33m', '\x1b[39m'], - red: ['\x1b[31m', '\x1b[39m'], - // Bright black: a soft grey in every common terminal theme. - hover: ['\x1b[100m', '\x1b[49m'], -} - // A line is a list of [text, ...styles] segments, cut to `width` columns // before the styles are applied, so escape codes never count as width. function renderLine(segments, width, useColors) { @@ -229,12 +218,7 @@ function renderLine(segments, width, useColors) { if (!part) continue - line += useColors - ? styles.reduce( - (styled, style) => `${STYLES[style][0]}${styled}${STYLES[style][1]}`, - part, - ) - : part + line += styleText(part, styles, useColors) if (part.length < text.length) break } diff --git a/lib/prompts.js b/lib/prompts.js index 513bd3a..e7d0ffc 100644 --- a/lib/prompts.js +++ b/lib/prompts.js @@ -4,7 +4,8 @@ // path, confirming a workspace change, choosing a project or script, asking // for script arguments, and the choice after a command. Menus use the list // from list.js, which supports fuzzy search; the text and yes/no questions use -// @inquirer/prompts. +// @inquirer/prompts, with the theme from ui.js so they match the menus and +// respect NO_COLOR and FORCE_COLOR. // // chooseProject() shows the recently used projects first, under a "Recent" // heading, and folders without a package.json dimmed and unselectable. It @@ -25,7 +26,7 @@ // function called when that menu shows it. // // Used by cli.js through the default instance exported at the bottom. Tests -// pass fake prompt functions to createPrompts(). +// pass fake prompt functions, and a theme, to createPrompts(). import { confirm as inquirerConfirm, @@ -34,6 +35,7 @@ import { import { splitArguments } from './args.js' import { select as listSelect } from './list.js' +import { inquirerTheme } from './ui.js' // Returned by chooseProject when the user wants another workspace. export const CHANGE_WORKSPACE = Symbol('change-workspace') @@ -74,6 +76,7 @@ export function createPrompts({ confirm = inquirerConfirm, input = inquirerInput, select = listSelect, + theme = inquirerTheme(), } = {}) { let mouse = false let note = null @@ -106,6 +109,7 @@ export function createPrompts({ return input({ message: 'Workspace path', validate, + theme, }) }, @@ -113,6 +117,7 @@ export function createPrompts({ return confirm({ message: 'Choose a new workspace directory?', default: true, + theme, }) }, @@ -188,6 +193,7 @@ export function createPrompts({ return error.message } }, + theme, }) return splitArguments(text) diff --git a/lib/ui.js b/lib/ui.js index b2a3010..061678b 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -1,7 +1,19 @@ -// Terminal output helpers: colours, the header box and clearing the screen. +// Terminal output helpers: the colour theme, the header box and clearing the +// screen. // -// color() wraps text in ANSI colour codes, unless output is not a terminal or -// NO_COLOR is set. USE_COLORS is that decision, shared with list.js. +// This file is the one place that knows colour codes. STYLES maps each style +// name to the codes that switch it on and off, and styleText() applies a list +// of them; color() is the same for a single string, and list.js uses +// styleText() for every line it draws. The theme sticks to one accent: cyan +// for "you are here" (the selected item, the current screen in the +// breadcrumb, the search), green, red and yellow only for results and +// warnings, and bold and dim for hierarchy. inquirerTheme() gives the +// Inquirer prompts the same look, so their text goes through color() too. +// +// colorsEnabled() decides whether to colour at all: FORCE_COLOR turns colours +// on (or off, set to 0 or false) whatever else is true, as in Node itself; +// otherwise output must be a terminal and NO_COLOR unset or empty. +// USE_COLORS is that decision for this process, shared with list.js. // // headerLines() returns the three lines of the box shown at the top of every // menu, for a given width: @@ -18,35 +30,76 @@ // characters one column wide, measured with width.js, so its border lines up // in every terminal. // -// Used by cli.js, color() through the default instance exported at the -// bottom. Tests call createUi() with colours forced on or off. +// Used by cli.js and prompts.js, color() and inquirerTheme() through the +// default instance exported at the bottom. Tests call createUi() with colours +// forced on or off. import { textWidth, truncateText } from './width.js' const NAME = 'dev-workspace' -export const USE_COLORS = Boolean(process.stdout.isTTY && !process.env.NO_COLOR) +export function colorsEnabled({ + env = process.env, + stream = process.stdout, +} = {}) { + const force = env.FORCE_COLOR + + if (force !== undefined) return force !== '0' && force !== 'false' + + return Boolean(stream.isTTY) && !env.NO_COLOR +} -const ANSI = { - reset: '\x1b[0m', - bold: '\x1b[1m', - dim: '\x1b[2m', - cyan: '\x1b[36m', - green: '\x1b[32m', - yellow: '\x1b[33m', - red: '\x1b[31m', +export const USE_COLORS = colorsEnabled() + +// Each style closes with its own code, not a full reset, so styles nest. +export const STYLES = { + bold: ['\x1b[1m', '\x1b[22m'], + dim: ['\x1b[2m', '\x1b[22m'], + underline: ['\x1b[4m', '\x1b[24m'], + cyan: ['\x1b[36m', '\x1b[39m'], + green: ['\x1b[32m', '\x1b[39m'], + yellow: ['\x1b[33m', '\x1b[39m'], + red: ['\x1b[31m', '\x1b[39m'], + // Bright black: a soft grey in every common terminal theme. + hover: ['\x1b[100m', '\x1b[49m'], +} + +// `text` with each of `styles` applied, the last one outermost. Unknown +// names are skipped. +export function styleText(text, styles, useColors = USE_COLORS) { + if (!useColors) return String(text) + + return styles + .filter(style => STYLES[style]) + .reduce( + (styled, style) => `${STYLES[style][0]}${styled}${STYLES[style][1]}`, + String(text), + ) } export function createUi({ useColors = USE_COLORS } = {}) { - function color(value, shade) { - if (!useColors || !ANSI[shade]) { - return String(value) - } + function color(value, ...styles) { + return styleText(value, styles, useColors) + } - return `${ANSI[shade]}${value}${ANSI.reset}` + // Inquirer's theme, with every colour going through color(). + function inquirerTheme() { + return { + prefix: { idle: color('?', 'cyan'), done: color('✔', 'green') }, + style: { + answer: text => color(text, 'cyan'), + message: text => color(text, 'bold'), + error: text => color(`> ${text}`, 'red'), + defaultAnswer: text => color(`(${text})`, 'dim'), + help: text => color(text, 'dim'), + highlight: text => color(text, 'cyan'), + key: text => color(`<${text}>`, 'cyan', 'bold'), + confirmDefault: text => color(text, 'cyan'), + }, + } } - return { color } + return { color, inquirerTheme } } // The header box, as lines of segments at most `width` columns wide, starting @@ -65,16 +118,24 @@ export function headerLines({ workspace, crumbs = [], tag }, width) { let fill if (textWidth(name + trail) <= room) { + // The last crumb is the current screen: "you are here". title = [ ['◆', 'cyan'], [` ${NAME}`, 'bold'], - ...crumbs.flatMap(crumb => [[' › ', 'dim'], [crumb]]), + ...crumbs.flatMap((crumb, index) => [ + [' › ', 'dim'], + index === crumbs.length - 1 ? [crumb, 'cyan'] : [crumb], + ]), ] fill = room - textWidth(name + trail) - (showTag ? textWidth(tagPart) : 0) } else { const cut = truncateText(trail, Math.max(0, room - textWidth(name))) - title = [['◆', 'cyan'], [` ${NAME}`, 'bold'], [cut]] + title = [ + ['◆', 'cyan'], + [` ${NAME}`, 'bold'], + [cut, 'dim'], + ] fill = Math.max(0, room - textWidth(name + cut)) } @@ -83,7 +144,12 @@ export function headerLines({ workspace, crumbs = [], tag }, width) { ['╭─ ', 'dim'], ...title, [` ${'─'.repeat(fill + 1)}`, 'dim'], - ...(showTag ? [[` ${tag} `], ['─', 'dim']] : []), + ...(showTag + ? [ + [` ${tag} `, 'dim'], + ['─', 'dim'], + ] + : []), ['╮', 'dim'], ] @@ -106,4 +172,4 @@ export function clearScreen() { console.clear() } -export const { color } = createUi() +export const { color, inquirerTheme } = createUi() diff --git a/test/args.test.js b/test/args.test.js index 94910af..8b61986 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -107,6 +107,9 @@ test('formatHelp defaults to plain text', () => { Environment: DEV_WORKSPACE_CONFIG Use a custom configuration file path + NO_COLOR Turn colours off + FORCE_COLOR Turn colours on, even when output is not + a terminal (0 turns them off) `, ) }) diff --git a/test/prompts.test.js b/test/prompts.test.js index f19596e..0de5e7e 100644 --- a/test/prompts.test.js +++ b/test/prompts.test.js @@ -6,6 +6,9 @@ import { createPrompts, } from '../lib/prompts.js' +// Passed through to Inquirer as it is. +const THEME = { prefix: '>' } + function createPromptMocks(results = {}) { const calls = { confirm: [], @@ -30,6 +33,7 @@ function createPromptMocks(results = {}) { calls.select.push(options) return Object.hasOwn(results, 'select') ? results.select : 'mock-result' }, + theme: THEME, }), } } @@ -44,6 +48,7 @@ test('askForWorkspace passes its message and validator to input', async () => { assert.equal(calls.input.length, 1) assert.equal(calls.input[0].message, 'Workspace path') assert.equal(calls.input[0].validate, validate) + assert.equal(calls.input[0].theme, THEME) }) test('confirmWorkspaceChange defaults to true', async () => { @@ -56,6 +61,7 @@ test('confirmWorkspaceChange defaults to true', async () => { { message: 'Choose a new workspace directory?', default: true, + theme: THEME, }, ]) }) @@ -250,6 +256,7 @@ test('askForArguments splits the answer and validates quotes', async () => { assert.deepEqual(result, ['--port', '4000', 'two words']) assert.equal(calls.input[0].message, 'Arguments for dev') + assert.equal(calls.input[0].theme, THEME) assert.equal(calls.input[0].validate('--port 4000'), true) assert.equal(calls.input[0].validate('"open'), 'Close the " quote.') }) diff --git a/test/ui.test.js b/test/ui.test.js index 809c6ac..3746891 100644 --- a/test/ui.test.js +++ b/test/ui.test.js @@ -1,6 +1,12 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { createUi, headerLines } from '../lib/ui.js' +import { + STYLES, + colorsEnabled, + createUi, + headerLines, + styleText, +} from '../lib/ui.js' import { textWidth } from '../lib/width.js' test('color returns plain text when colors are disabled', () => { @@ -19,8 +25,72 @@ test('color converts values to strings when colors are disabled', () => { test('color wraps text in ANSI codes when colors are enabled', () => { const { color } = createUi({ useColors: true }) - assert.equal(color('Hello', 'cyan'), '\x1b[36mHello\x1b[0m') - assert.equal(color('Warning', 'yellow'), '\x1b[33mWarning\x1b[0m') + assert.equal(color('Hello', 'cyan'), '\x1b[36mHello\x1b[39m') + assert.equal(color('Warning', 'yellow'), '\x1b[33mWarning\x1b[39m') +}) + +test('color applies several styles, the last one outermost', () => { + const { color } = createUi({ useColors: true }) + + assert.equal(color('Hi', 'cyan', 'bold'), '\x1b[1m\x1b[36mHi\x1b[39m\x1b[22m') +}) + +test('styleText closes each style with its own code, so styles nest', () => { + const inner = styleText('b', ['cyan'], true) + + assert.equal( + styleText(`a${inner}c`, ['bold'], true), + '\x1b[1ma\x1b[36mb\x1b[39mc\x1b[22m', + ) + assert.equal(styleText('plain', ['cyan', 'bold'], false), 'plain') + assert.ok(Object.values(STYLES).every(([open, close]) => open !== close)) +}) + +test('colorsEnabled needs a terminal and no NO_COLOR', () => { + const tty = { isTTY: true } + + assert.equal(colorsEnabled({ env: {}, stream: tty }), true) + assert.equal(colorsEnabled({ env: {}, stream: {} }), false) + assert.equal(colorsEnabled({ env: { NO_COLOR: '1' }, stream: tty }), false) + // An empty NO_COLOR does not count, as the NO_COLOR convention says. + assert.equal(colorsEnabled({ env: { NO_COLOR: '' }, stream: tty }), true) +}) + +test('colorsEnabled lets FORCE_COLOR override everything else', () => { + for (const value of ['1', '2', '3', 'true', '']) { + const env = { FORCE_COLOR: value, NO_COLOR: '1' } + + assert.equal(colorsEnabled({ env, stream: {} }), true, value) + } + + for (const value of ['0', 'false']) { + const env = { FORCE_COLOR: value } + + assert.equal(colorsEnabled({ env, stream: { isTTY: true } }), false, value) + } +}) + +test('inquirerTheme styles Inquirer prompts through color()', () => { + const plain = createUi({ useColors: false }).inquirerTheme() + const colored = createUi({ useColors: true }).inquirerTheme() + + assert.deepEqual(plain.prefix, { idle: '?', done: '✔' }) + assert.equal(plain.style.error('Bad path'), '> Bad path') + assert.equal(plain.style.defaultAnswer('Y/n'), '(Y/n)') + assert.equal(plain.style.key('enter'), '') + + for (const style of Object.values(plain.style)) { + assert.ok(!style('text').includes('\x1b[')) + } + + assert.equal(colored.prefix.idle, '\x1b[36m?\x1b[39m') + assert.equal(colored.prefix.done, '\x1b[32m✔\x1b[39m') + assert.equal(colored.style.answer('yes'), '\x1b[36myes\x1b[39m') + assert.equal(colored.style.message('Path'), '\x1b[1mPath\x1b[22m') + assert.equal(colored.style.error('Bad'), '\x1b[31m> Bad\x1b[39m') + assert.equal(colored.style.help('hint'), '\x1b[2mhint\x1b[22m') + assert.equal(colored.style.highlight('x'), '\x1b[36mx\x1b[39m') + assert.equal(colored.style.confirmDefault('Y'), '\x1b[36mY\x1b[39m') }) test('color returns plain text for an unknown shade', () => { @@ -63,9 +133,24 @@ test('headerLines styles the parts of the box', () => { ['╭─ ', 'dim'], ['◆', 'cyan'], [' dev-workspace', 'bold'], + [' › ', 'dim'], + ['web', 'cyan'], + ]) +}) + +test('headerLines marks only the current screen in the breadcrumb', () => { + const [top] = headerLines( + { workspace: '/p', crumbs: ['web', 'build'], tag: 'npm' }, + 60, + ) + + assert.deepEqual(top.slice(4, 8), [ [' › ', 'dim'], ['web'], + [' › ', 'dim'], + ['build', 'cyan'], ]) + assert.ok(top.some(([text, style]) => text === ' npm ' && style === 'dim')) }) test('headerLines drops the tag, then cuts the breadcrumb, when short of room', () => { From ecac62553a3cdb4dd33c75d43c9bcf00e9ce2b6d Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:32:59 +0100 Subject: [PATCH 04/23] feat: shorten long workspace paths in the middle Closes #28 --- lib/ui.js | 6 ++--- lib/width.js | 56 +++++++++++++++++++++++++++++++++++++++++++++- test/ui.test.js | 7 +++--- test/width.test.js | 31 ++++++++++++++++++++++++- 4 files changed, 92 insertions(+), 8 deletions(-) diff --git a/lib/ui.js b/lib/ui.js index 061678b..8469721 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -24,7 +24,7 @@ // // The top border carries the name and the breadcrumb of the current screen, // and an optional tag on the right, dropped when the name needs the room. The -// workspace path is cut with … when it does not fit. The lines are made of +// workspace path is shortened in the middle when it does not fit. The lines are made of // [text, ...styles] segments that list.js draws, so the box redraws with the // list when the window is resized. It uses one thin line style and only // characters one column wide, measured with width.js, so its border lines up @@ -34,7 +34,7 @@ // default instance exported at the bottom. Tests call createUi() with colours // forced on or off. -import { textWidth, truncateText } from './width.js' +import { textWidth, truncatePath, truncateText } from './width.js' const NAME = 'dev-workspace' @@ -153,7 +153,7 @@ export function headerLines({ workspace, crumbs = [], tag }, width) { ['╮', 'dim'], ] - const path = truncateText(workspace, box - 5) + const path = truncatePath(workspace, box - 5) return [ top, diff --git a/lib/width.js b/lib/width.js index 2561e31..48189fd 100644 --- a/lib/width.js +++ b/lib/width.js @@ -11,7 +11,7 @@ // wrapText() breaks a text into lines of at most a number of columns, between // words; a word wider than a line is cut with fitText(). // -// Used by ui.js for the header, and list.js for every line it draws, the +// Used by ui.js for the header and its workspace path, and list.js for every line it draws, the // details next to each item and the mouse note. import stringWidth from 'string-width' @@ -45,6 +45,60 @@ export function truncateText(text, width) { return `${fitText(text, width - 1)}…` } +// The end of a text that fits in `width` columns, after … +function truncateStart(text, width) { + if (width < 1) return '' + + const segments = [...segmenter.segment(text)].map(({ segment }) => segment) + let used = 1 + let result = '' + + for (const segment of segments.reverse()) { + const columns = stringWidth(segment) + + if (used + columns > width) break + + result = segment + result + used += columns + } + + return `…${result}` +} + +export function truncatePath(text, width) { + if (textWidth(text) <= width) return text + + const separator = /[\\/]/.exec(text)?.[0] + + if (!separator) return truncateText(text, width) + + const [root, ...folders] = text.split(separator) + const fits = (start, end) => + textWidth([...start, '…', ...end].join(separator)) <= width + const start = [root] + const end = [] + + // The last folders first, then the first ones, while … stays between. + while ( + end.length < folders.length && + fits(start, [folders.at(-end.length - 1), ...end]) + ) { + end.unshift(folders.at(-end.length - 1)) + } + + // Not even the last folder fits after the root: keep the end of the path. + if (end.length === 0) return truncateStart(text, width) + + while ( + start.length < folders.length - end.length && + fits([...start, folders[start.length - 1]], end) + ) { + start.push(folders[start.length - 1]) + } + + return [...start, '…', ...end].join(separator) +} + export function wrapText(text, width) { const lines = [] let line = '' diff --git a/test/ui.test.js b/test/ui.test.js index 3746891..a98197e 100644 --- a/test/ui.test.js +++ b/test/ui.test.js @@ -180,10 +180,11 @@ test('headerLines keeps its border aligned around wide characters', () => { } }) -test('headerLines cuts a long workspace path to fit', () => { - const lines = header({ workspace: `/${'very-long-folder/'.repeat(10)}` }, 50) +test('headerLines shortens a long workspace path in the middle', () => { + const workspace = `/${'very-long-folder/'.repeat(10)}web` + const lines = header({ workspace }, 50) - assert.ok(lines[1].endsWith('… │'), lines[1]) + assert.ok(lines[1].includes('│ /…/very-long-folder/very-long-folder/web')) for (const line of lines) assert.equal(textWidth(line), 50, line) }) diff --git a/test/width.test.js b/test/width.test.js index fe73e62..081396c 100644 --- a/test/width.test.js +++ b/test/width.test.js @@ -1,7 +1,13 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { fitText, textWidth, truncateText, wrapText } from '../lib/width.js' +import { + fitText, + textWidth, + truncatePath, + truncateText, + wrapText, +} from '../lib/width.js' test('textWidth counts emoji and wide characters as two columns', () => { assert.equal(textWidth('web'), 3) @@ -49,3 +55,26 @@ test('truncateText ends a shortened text with an ellipsis', () => { assert.equal(truncateText('日本語です', 6), '日本…') assert.equal(truncateText('vite', 0), '') }) + +test('truncatePath keeps the root and the last folders that fit', () => { + const windows = 'C:\\Users\\someone\\Documents\\projects\\web' + + assert.equal(truncatePath(windows, 60), windows) + assert.equal(truncatePath(windows, 24), 'C:\\Users\\…\\projects\\web') + assert.equal(truncatePath(windows, 18), 'C:\\…\\projects\\web') + assert.equal( + truncatePath('/home/someone/dev/clients/acme', 20), + '/…/dev/clients/acme', + ) + assert.equal(truncatePath('~/dev/日本語/app', 14), '~/…/日本語/app') + assert.equal(truncatePath('~/dev/日本語/app', 12), '~/dev/…/app') +}) + +test('truncatePath keeps the end of a path whose last folder is too long', () => { + const path = '/srv/a-very-long-folder-name' + + assert.equal(truncatePath(path, 10), '…lder-name') + assert.equal(textWidth(truncatePath('/srv/日本語日本語', 6)), 5) + assert.equal(truncatePath('/srv/long-name', 0), '') + assert.equal(truncatePath('no-separator-at-all', 8), 'no-sepa…') +}) From 350254b36c0da5f110922a2bc927a6751994be43 Mon Sep 17 00:00:00 2001 From: versnic <37933264+versnic@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:33:00 +0100 Subject: [PATCH 05/23] feat: exit with a clear message when input is not a terminal Closes #34 --- README.md | 3 ++- ROADMAP.md | 4 ++-- lib/cli.js | 23 +++++++++++++++++++++-- lib/terminal.js | 9 ++++++++- test/cli.test.js | 33 +++++++++++++++++++++++++++++++++ test/terminal.test.js | 6 ++++++ 6 files changed, 72 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 6f7349f..7a2fecf 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ This installs two equivalent commands, `dev-workspace` and the shorter `dws`. Each list also has entries to go **Back**, **Exit**, or **Change workspace**, under a line that separates them from the projects or scripts. -Every menu opens with a small box that shows where you are: the tool's name, followed by the project you are in (`◆ dev-workspace › web-app`), the workspace folder, and in a project, its package manager on the right. Each script's command is shown next to its name, in a column of its own, and tags such as `last run` sit at the right edge. The layout stays within 100 columns on wide terminals. Long workspace paths and script commands are cut with `…` to fit, and emoji or CJK characters in folder names never break the layout. +Every menu opens with a small box that shows where you are: the tool's name, followed by the project you are in (`◆ dev-workspace › web-app`), the workspace folder, and in a project, its package manager on the right. Each script's command is shown next to its name, in a column of its own, and tags such as `last run` sit at the right edge. The layout stays within 100 columns on wide terminals. Long workspace paths are shortened in the middle (`C:Users…projectsweb`), keeping the folders that tell them apart, and script commands are cut with `…` to fit, and emoji or CJK characters in folder names never break the layout. ### Colours @@ -182,6 +182,7 @@ dws web dev -- --port 4000 # pass everything after -- to the script - The project is found by its exact name first, then ignoring case, then by the start of its name, as long as only one project starts that way: `dws des build` runs `build` in `design-system`. If several projects match, the CLI lists them. - Any script in `package.json` can be run by name, including `pre` and `post` hooks. - With a script, nothing is asked and the screen is not cleared, so direct mode also works in other scripts. The CLI exits with the script's exit code, or 128 plus the signal number if a signal stopped it, as shells do (130 after Ctrl+C). It exits with code 1 if it cannot start the script, for example when no workspace is saved yet. +- Without a script, the CLI needs a terminal to read keys from. When its input is redirected (`dws < file`, or in a CI job), it exits with code 1 and a message saying how to run a script directly, instead of waiting for keys that never come. ## Command-line options diff --git a/ROADMAP.md b/ROADMAP.md index 8aad593..102bdb9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -153,7 +153,7 @@ The check script draws its items on fixed rows, so its clicks are offset once th ### Layout and appearance - [x] **Correct layout:** measure text by its terminal width (`string-width`) so emoji and wide characters never break the header border. -- [ ] **Path truncation:** shorten long workspace paths in the middle (`C:/Users/…/projects/web`) instead of cutting off the end. +- [x] **Path truncation:** shorten long workspace paths in the middle (`C:/Users/…/projects/web`) instead of cutting off the end [#28](https://github.com/modulane/dev-workspace-cli/issues/28). - [ ] **Alternate screen:** show the menus on the terminal's alternate screen, as `less` and `vim` do, leaving it before a script runs and on every exit path. Resizing the window can then redraw the whole screen, header included, without leaving broken lines or duplicate headers in the scrollback. - [x] **Framed header:** the same small box on every screen instead of the 11-line header, with `◆ dev-workspace` and a breadcrumb (`› web-app › build`) set in its top border and the workspace inside. One thin line style and only single-width symbols, so it lines up in every terminal. The list draws it, so it redraws with the list and holds the buttons [#30](https://github.com/modulane/dev-workspace-cli/issues/30). - [x] **Menu layout:** aligned columns (name, dim details such as the script's command, tags on the right), uppercase group titles, one blank line between the parts of the screen, single-width symbols on actions only, and a full-row hover highlight that falls back to `›` with `NO_COLOR` [#67](https://github.com/modulane/dev-workspace-cli/issues/67). @@ -163,7 +163,7 @@ The check script draws its items on fixed rows, so its clicks are offset once th - [ ] **Project details:** show package manager, script count and Git branch (if any) next to each project, without slowing down the list (read lazily, cache per session). - [ ] **First-run experience:** suggest common folders that exist (`~/dev`, `~/projects`, `~/code`, `~/src`, `~/repos`) as choices, with "Enter another path" as the last option. - [x] **Typed paths:** the workspace prompt and `--workspace` accept the forms a shell would normally clean up: `~/projects`, quoted paths (as copied by Explorer's "Copy as path") and, outside Windows, escaped spaces (`my\ projects`). A missing folder is reported with the full path that was checked ([#9](https://github.com/modulane/dev-workspace-cli/issues/9)). -- [ ] **Non-interactive guard:** when stdin is not a TTY and no direct-mode arguments are given, exit with a clear message instead of a prompt error. +- [x] **Non-interactive guard:** when stdin is not a TTY and no direct-mode arguments are given, exit with a clear message instead of a prompt error [#34](https://github.com/modulane/dev-workspace-cli/issues/34). - [x] **Coloured `--help`.** **Done when:** screenshots of the main screens look correct in Windows Terminal, PowerShell, macOS Terminal, iTerm2 and a Linux terminal, at 80 and 120 columns, with and without `NO_COLOR`. diff --git a/lib/cli.js b/lib/cli.js index a7dbb71..ae56f65 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -12,6 +12,9 @@ // or passed with --workspace go through resolveDirectoryInput(), so ~, // quotes and escaped spaces work without a shell. // +// Menus and questions need a terminal for input: without one, and without +// a script to run directly, run() fails with a message saying so. +// // Direct mode: `dev-workspace ` opens that project's scripts, and // `dev-workspace