算法艺术创作
algorithmic-art
通过代码和可调参数创作生成艺术与交互式视觉效果。
design-cli-output【设计与创意】Design terminal output for a CLI tool with chalk colors, Unicode glyphs, multiple verbosity levels (human, verbose, quiet, JSON), and consistent voice rules. Covers color palette selection, status indicator design, reporter function architecture, ceremony/narrative output variants, and cross-terminal compatibility. Use when building a new CLI reporte…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
為命令列工具設計一致之多層終端輸出。
用 chalk 建命名色盤物件。
載 chalk 於無色回退之後。 回退須代色盤所用之每一呼叫形,非僅傳字串而已:
// A factory returns a *function*; a direct style returns a string. Enumerate
// this list against the installed chalk, not from memory — chalk 6 added the
// three underline* variants, and a list that omits them is wrong for those names.
const FACTORIES = new Set(['ansi256', 'bgAnsi256', 'bgHex', 'bgRgb', 'hex',
'rgb', 'underlineAnsi256', 'underlineHex', 'underlineRgb']);
function makeChalkStub() {
return new Proxy((text) => text, {
get(target, prop) {
if (prop === 'then') return undefined; // must not be a thenable
if (prop === 'level') return 0; // no color support, truthfully
if (typeof prop === 'symbol') return Reflect.get(target, prop);
return FACTORIES.has(prop) ? () => makeChalkStub() : makeChalkStub();
},
});
}
let chalk;
try { chalk = (await import('chalk')).default; }
catch { chalk = makeChalkStub(); }
四不變式,短拙之替身各失其一:
(text) => text,非 {}。鏈式(chalk.bold.cyan('x'))須每一節既可索引亦可呼叫。new Proxy({}, { get: () => (s) => s }) 足直接樣式而破工廠:chalk.hex('#FF6B35') 遂為字串 '#FF6B35',呼之則擲 TypeError: ... is not a function。色盤於模組載入時建,故此回退於 import 之際即斃其工具——正當降為純文字之所以存也。then 須為 undefined。 若替身以函數應每一屬性,則 await chalk 永懸:運行時呼 .then 而候一無人喚之回調。Node 報 Detected unsettled top-level await,出碼 13。level 須為數。 能力閘讀 chalk.level >= 1;真值替身啟之,而其後實無色可支。以此 import 後存留之物件建色盤。
標準色盤(事務性輸出):
// Status colors
const ok = chalk.green; // success
const fail = chalk.red; // errors
const warn = chalk.yellow; // warnings
const info = chalk.cyan; // identifiers, names
const dim = chalk.dim; // secondary info, paths
const bold = chalk.bold; // headers
暖色盤(儀式/敘事輸出):
const C = {
flame: chalk.hex('#FF6B35'), // active elements, fire
amber: chalk.hex('#FFB347'), // arriving items, warm highlights
spark: chalk.hex('#FFF4E0'), // individual items (sparks/skills)
ember: chalk.hex('#8B4513'), // cold/dormant states
warm: chalk.hex('#D4A574'), // neutral warm text
dim: chalk.dim, // background, secondary
fail: chalk.red, // errors stay red (honest)
};
色盤設計規則:
chalk.hex('#FF6B35'))預期: 具命名項之色盤物件,且其回退已行之,非僅書之而已。
失敗時: 直行回退之路;色盤非發覺其已破之所。替身在域中,則:
console.assert(chalk.dim('x') === 'x'); // direct style
console.assert(chalk.hex('#fff')('x') === 'x'); // factory — the usual defect
console.assert(chalk.bold.cyan('x') === 'x'); // chain
console.assert(chalk.level === 0); // capability gate stays shut
await chalk; // must not hang
NO_COLOR=1 不覆此事。彼行一可用之 chalk 而擇不發轉義;回退則行一 import 失敗之 chalk。二路無共用之碼。註釋詳備之生產替身、此疾之復現、及上諸檢之可運行本,見 Extended Examples。
為狀態溝通擇 Unicode 圖符或 ASCII 字元:
ASCII(最大相容性):
+ created/installed (green)
- removed/deleted (red)
= skipped/unchanged (dim)
! error/warning (red)
Unicode(更豐富,需 UTF-8 終端):
✦ item/skill/practice (spark)
◉ active/burning state
◎ cooling/embers state
○ cold/dormant state
◌ available/not installed
✗ failed item
✓ success (use sparingly — not all terminals render it well)
擇選準則:
--ascii 旗標或 NO_COLOR 偵測兩者兼供預期: 一瞥即可溝通狀態而不恃色之圖符集。
失敗時: 若圖符於測試中渲染為 ? 或方框,以 ASCII 等效替之。+/-/=/! 集處處可用。
每指令應支援四輸出層級:
| 層級 | 旗標 | 受眾 | 內容 |
|---|---|---|---|
| 預設 | (無) | 終端前之人 | 格式化、著色、有料 |
| Verbose | --verbose 或 --ceremonial | 欲詳情之人 | 逐項明細,到達序列 |
| Quiet | --quiet | 腳本、CI | 極簡之行,狀態圖符,無裝飾 |
| JSON | --json | 機器消費者 | 結構化、可解析、完整 |
實作模式:
function output(data, options) {
if (options.json) {
console.log(JSON.stringify(data, null, 2));
return;
}
if (options.quiet) {
for (const item of data.items) {
const icon = item.ok ? '+' : '!';
console.log(`${icon} ${item.id}`);
}
return;
}
// Default (or verbose) human output
printFormatted(data, { verbose: options.verbose });
}
JSON 輸出規則:
預期: 四明層級,於指令間行為一致。
失敗時: 若 verbose 模式過噪,設其為自選(--ceremonial)而非漸進冗長度層級。
定所有輸出函數遵循之語氣與風格。此防指令間不一致。
聲音規則例(自 campfire reporter):
標準(非儀式)輸出之聲音規則:
預期: 輸出函數須遵之 3-7 聲音規則之書面集。
失敗時: 若規則感覺武斷,測之:以有無每規則書同一輸出。若去規則不改輸出品質,該規則不需。
以聚焦之函數組輸出為 reporter 模組:
// reporter.js — standard output
export function printResults(results) { ... }
export function printItemTable(items) { ... }
export function printDetections(detections) { ... }
export function printAudit(auditResults) { ... }
export function printDryRun() { ... }
export function warn(msg) { ... }
export function error(msg) { ... }
export { chalk };
每函數遵同結構:
為儀式輸出建別模組:
// campfire-reporter.js — warm narrative output
export function printArrival({ teamId, agents, results, ceremonial }) { ... }
export function printScatter({ teamId, agents, results }) { ... }
export function printTend(fires) { ... }
export function printCampfireList({ teams, state, reg }) { ... }
export function printFireSummary({ team, fireData, reg }) { ... }
export function printJson(data) { ... }
預期: 獨立可用之 reporter 函數——各自處理格式化而不依呼叫者狀態。
失敗時: 若函數長於 ~50 行,抽出輔助。reporter 函數應易於孤立地審閱。
驗輸出於不同情境中正確渲染:
# With colors (interactive terminal)
node cli/index.js list --domains
# Without colors (piped)
node cli/index.js list --domains | cat
# With NO_COLOR environment variable
NO_COLOR=1 node cli/index.js list --domains
# JSON mode (parseable)
node cli/index.js campfire --json | jq .
# In CI (typically no TTY)
CI=true node cli/index.js audit
# The no-color fallback. A failed import cannot be provoked with an env var, so
# assert on the stub itself in the suite rather than reaching it through the CLI.
# Pass a glob, not a directory: `node --test <dir>` stopped expanding at Node 22.
node --test 'cli/test/*.test.js'
檢之於:
jq . 以驗)預期: 輸出於所有六情境中皆正確。
失敗時: 若 ANSI 碼漏,確 chalk 尊 NO_COLOR。若 Unicode 破,提供 ASCII 回退模式。又須知:綠套於色一無所證。測試運行者 pipe stdout,使 chalk.level 為 0,故著色與無色之輸出逐位元相同,色雖全破而斷言猶立。欲證色可用,須 FORCE_COLOR=3 及對轉義序列之斷言。
level === 0、await 皆已檢jq 可解析new Proxy({}, { get: () => (s) => s }) 讀之如全,且誠覆 chalk.dim 與 chalk.red,然每一工廠遂返一字串,而呼叫者即欲呼之。色盤於模組載入時建,故 TypeError 落於 import 之際——回退於其所以存之唯一情境中敗得最重。步驟一列替身須滿之四不變式。--json 模式僅輸出有效 JSON。單一漏行(如「DRY RUN」)破 JSON 解析器。若指令須兩者皆示,明離之或於 JSON 模式中抑人類文字。Math.max(...items.map(i => i.id.length)) 動態算填充。+、OK、ERR)配色。--quiet 模式中,增噪。以顯式旗標閘儀式輸出。scaffold-cli-command — 用此輸出之指令test-cli-application — 測輸出合預期build-cli-plugin — 插件透過此輸出系統報結果