@litfamily/litclaude 1.0.62 → 1.0.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.64 - 2026-11-25
4
+
5
+ - The installer asks its questions on cards in a real terminal: the step, a title, one sentence on what the answer
6
+ does, the choices and the keys. Lists take arrows, `j`/`k`, numbers and Enter, with the status-line preview on every
7
+ colour row; yes or no is two buttons with the default lit and named. An answered card folds to one line, the five
8
+ install steps tick on one card, and the last card says what was installed, the settings and what to do next.
9
+ - The questions, their order, defaults and stored results are the same, and Ctrl+C still stops with exit code 1. The
10
+ Enter people press after `y` or `n`, and keys typed while files are copied, no longer answer the next question.
11
+ - Pipes, `CI`, `--yes`, `TERM=dumb`, small windows and the `LITCLAUDE_*_PROMPT` hooks print exactly what they did.
12
+ `NO_COLOR` draws the cards without colour, and a terminal without UTF-8 gets ASCII borders.
13
+ - The READMEs and the guide name all five questions, and the guide shows the new screens.
14
+
15
+ ## 1.0.63 - 2026-11-25
16
+
17
+ - The LIT card wears a sunset in the terminal: a half-sunk sun whose light ripples, a sea that runs outward from it,
18
+ twinkling stars and a neon border from pink to the accent. It is drawn only where no words are, moves while Claude
19
+ works and holds still at rest, and the card's rows, words and widths stay as they were.
20
+ - The gauges on the card and the status line have round ends with the icon font, and without it in Windows
21
+ Terminal 1.21 or later and VS Code. `LITCLAUDE_HUD_GLYPHS=basic` and `glyphs basic` bring the square ends back.
22
+ - A usage window that will run out before its reset shows `! out 1h28m` on the status line.
23
+ - The session state keeps a small receipt for each replay key, so it no longer grows with every start.
24
+ - `TERM=dumb` terminals get plain ASCII art.
25
+ - The READMEs, the guide and the card reference describe and show the new card.
26
+
3
27
  ## 1.0.62 - 2026-11-24
4
28
 
5
29
  - `lit continue`, `lit resume` and `lit 계속` in a fresh session now carry on the existing work. Before,
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
- <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/cover-motion.webp" width="100%" alt="LitFamily motion cover: seven armored robots power on one by one, the LitClaude robot wakes with glowing eyes and a lit frame, then LITFAMILY and KEEP THE WORK LIT. light up." /></picture></p>
1
+ <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/cover-motion.webp" width="100%" alt="LitFamily motion cover: seven armored robots power on one by one, the LitClaude robot wakes with glowing eyes and a lit frame, then LITFAMILY and KEEP THE WORK LIT. light up." /></picture></p>
2
2
 
3
3
  <h1 align="center">LitClaude</h1>
4
4
  <p align="center"><strong>Keep the work lit.</strong></p>
5
5
  <p align="center">LitClaude is an add-on for Claude Code. It makes Claude check its own work before it says "done", and leaves a note so the next session starts where this one stopped.</p>
6
6
  <p align="center">
7
- <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/readme/badge-version.svg" alt="1.0.62" />
8
- <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
7
+ <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/readme/badge-version.svg" alt="1.0.64" />
8
+ <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
9
9
  </p>
10
10
  <p align="center">
11
- <a href="https://github.com/wjgoarxiv/litclaude#readme">Full guide and skills gallery on GitHub</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/README_ko-KR.md">한국어</a>
11
+ <a href="https://github.com/wjgoarxiv/litclaude#readme">Full guide and skills gallery on GitHub</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/README_ko-KR.md">한국어</a>
12
12
  </p>
13
13
 
14
14
  You ask Claude for a feature. It writes the code and says it is finished, and a day later you find the tests
@@ -53,7 +53,9 @@ npx @litfamily/litclaude@latest install
53
53
  ```
54
54
 
55
55
  On the first run npx asks whether to install the package; answer `y`. The installer registers
56
- the plugin, adds the LitClaude status line and asks for its colour and an optional output style.
56
+ the plugin, adds the LitClaude status line and asks up to five short questions on cards (its colour,
57
+ an output style, the icon font, the Co-Authored-By line and the `CLAUDE.md` block); Enter takes the
58
+ marked default.
57
59
  A new install uses the `safe` permission mode, which adds no permission rules, and leaves your
58
60
  other Claude settings as they are. It also fetches the video skill's rendering engine and
59
61
  fonts up front. Start Claude Code again afterwards so the plugin loads.
@@ -109,14 +111,15 @@ through the Claude Code marketplace instead has no status line and is updated or
109
111
  the `/plugin` menu.
110
112
 
111
113
  These commands open with the synthwave LIT mark; a terminal without colour gets it in plain glyphs, and one
112
- without UTF-8, or piped output, gets the single line `LIT · claude code`. A lock left by a crashed session
113
- clears itself. If `state lock timed out` still appears, close the project's Claude Code sessions and delete
114
+ without UTF-8, or piped output, gets the single line `LIT · claude code`. While you work, a card above the prompt shows the
115
+ stage, and a moving sunset fills its free space. A lock left by a crashed
116
+ session clears itself. If `state lock timed out` still appears, close the project's Claude Code sessions and delete
114
117
  the lock folder the message names.
115
118
 
116
119
  ## More
117
120
 
118
121
  - [Full guide and skills gallery on GitHub](https://github.com/wjgoarxiv/litclaude#readme)
119
- - [Privacy and network behavior](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/privacy.md)
120
- - [Migration and ownership conflicts](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/migration.md)
121
- - [Release history](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/CHANGELOG.md)
122
- - [MIT license](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/LICENSE)
122
+ - [Privacy and network behavior](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/privacy.md)
123
+ - [Migration and ownership conflicts](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/migration.md)
124
+ - [Release history](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/CHANGELOG.md)
125
+ - [MIT license](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/LICENSE)
package/README_ko-KR.md CHANGED
@@ -1,14 +1,14 @@
1
- <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/cover-motion.webp" width="100%" alt="LitFamily 모션 커버: 일곱 로봇 패널이 차례로 켜지고, LitClaude 로봇의 눈과 테두리가 빛난 뒤 LITFAMILY와 KEEP THE WORK LIT. 문구가 밝아지는 영상" /></picture></p>
1
+ <p align="center"><picture><source media="(prefers-reduced-motion: reduce)" srcset="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/cover-motion-still.webp" /><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/cover-motion.webp" width="100%" alt="LitFamily 모션 커버: 일곱 로봇 패널이 차례로 켜지고, LitClaude 로봇의 눈과 테두리가 빛난 뒤 LITFAMILY와 KEEP THE WORK LIT. 문구가 밝아지는 영상" /></picture></p>
2
2
 
3
3
  <h1 align="center">LitClaude</h1>
4
4
  <p align="center"><strong>Keep the work lit.</strong></p>
5
5
  <p align="center">LitClaude는 Claude Code에 붙이는 추가 기능입니다. Claude가 "다 됐어요"라고 말하기 전에 자기 작업을 직접 확인하게 하고, 다음 세션이 이어서 시작할 수 있도록 기록을 남기게 합니다.</p>
6
6
  <p align="center">
7
- <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/readme/badge-version.svg" alt="1.0.62" />
8
- <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
7
+ <img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/readme/badge-version.svg" alt="1.0.64" />
8
+ <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/LICENSE"><img src="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/assets/readme/badge-license.svg" alt="MIT license" /></a>
9
9
  </p>
10
10
  <p align="center">
11
- <a href="https://github.com/wjgoarxiv/litclaude/blob/main/README_ko-KR.md">전체 안내와 스킬 갤러리는 GitHub에서</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/README.md">English</a>
11
+ <a href="https://github.com/wjgoarxiv/litclaude/blob/main/README_ko-KR.md">전체 안내와 스킬 갤러리는 GitHub에서</a> · <a href="https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/README.md">English</a>
12
12
  </p>
13
13
 
14
14
  Claude에게 기능을 하나 부탁하면 코드를 쓰고 끝났다고 말합니다. 그런데 다음 날 보니 테스트는 한 번도 돌지 않았습니다. 새 세션을 열면 프로젝트 설명을 처음부터 다시 해야 합니다.
@@ -48,7 +48,8 @@ npx @litfamily/litclaude@latest install
48
48
  ```
49
49
 
50
50
  처음 실행하면 npx가 패키지를 설치할지 묻는데, `y`로 답하면 됩니다. 설치 프로그램은 플러그인을
51
- 등록하고 LitClaude 상태 줄을 붙인 뒤, 상태 줄 색상과 쓰고 싶은 출력 스타일을 묻습니다. 새로
51
+ 등록하고 LitClaude 상태 줄을 붙인 뒤, 짧은 질문을 최대 다섯 개까지 카드로 묻습니다(상태 줄 색상, 출력
52
+ 스타일, 아이콘 글꼴, Co-Authored-By 줄, `CLAUDE.md` 구역). Enter는 표시된 기본값을 고릅니다. 새로
52
53
  설치하면 권한 규칙을 더하지 않는 `safe` 권한 모드로 시작하고 나머지 Claude 설정은 그대로 둡니다.
53
54
  영상 스킬에 필요한 렌더링 엔진과 글꼴도 미리 받아 둡니다. 설치가 끝나면 플러그인이 로드되도록
54
55
  Claude Code를 다시 시작하세요.
@@ -102,13 +103,13 @@ npx @litfamily/litclaude@latest uninstall
102
103
  업데이트와 제거는 `/plugin` 메뉴에서 합니다.
103
104
 
104
105
  이 명령들은 신스웨이브 LIT 마크로 시작합니다. 색이 없는 터미널에서는 기호로만 그리고, UTF-8을 쓰지 않는 터미널이나
105
- 파이프로 넘긴 출력에는 `LIT · claude code` 한 줄만 나옵니다. 세션이 비정상으로 끝나 남은 잠금은 저절로 풀립니다. 그래도
106
+ 파이프로 넘긴 출력에는 `LIT · claude code` 한 줄만 나옵니다. 일하는 동안 프롬프트 위 카드가 지금 단계를 보여 주고, 빈자리에는 움직이는 노을이 뜹니다. 세션이 비정상으로 끝나 남은 잠금은 저절로 풀립니다. 그래도
106
107
  `state lock timed out`이 보이면 그 프로젝트의 Claude Code 세션을 닫고 메시지에 적힌 잠금 폴더를 지우면 됩니다.
107
108
 
108
109
  ## 더 보기
109
110
 
110
111
  - [전체 안내와 스킬 갤러리 (GitHub)](https://github.com/wjgoarxiv/litclaude/blob/main/README_ko-KR.md)
111
- - [개인정보와 네트워크 동작](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/privacy.md)
112
- - [이전과 소유권 충돌](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/docs/migration.md)
113
- - [변경 이력](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/CHANGELOG.md)
114
- - [MIT 라이선스](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.62/LICENSE)
112
+ - [개인정보와 네트워크 동작](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/privacy.md)
113
+ - [이전과 소유권 충돌](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/docs/migration.md)
114
+ - [변경 이력](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/CHANGELOG.md)
115
+ - [MIT 라이선스](https://cdn.jsdelivr.net/npm/@litfamily/litclaude@1.0.64/LICENSE)
@@ -0,0 +1,485 @@
1
+ // The installer's cards for a person at a real terminal: choose one, yes or no, live progress and the
2
+ // closing summary. Nothing here runs unless richTerminal() says so; every other run keeps the plain
3
+ // prompts and machine lines in litclaude-ai.js. Cards are drawn in place, never wider than the window
4
+ // or taller than it, and fold to one line once answered.
5
+
6
+ import { emitKeypressEvents } from "node:readline";
7
+ import { ansi16CodeForAccent, hudColorDepth, themeForAccent } from "../plugins/litclaude/lib/hud-accent-palette.mjs";
8
+ import { textWidth } from "../plugins/litclaude/lib/mod/layout.mjs";
9
+
10
+ const MIN_COLS = 40;
11
+ const MIN_ROWS = 12;
12
+ const MAX_WIDTH = 100;
13
+ // `y` and then Enter is a habit: the letter already answered, so an Enter this soon after it belongs to it.
14
+ const LETTER_ENTER_MS = 400;
15
+ const SETTLE_MS = 30;
16
+
17
+ const asciiLocale = (env) => {
18
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
19
+ return locale !== "" && !/utf-?8/iu.test(locale);
20
+ };
21
+
22
+ /** Cards need a person at a terminal: two TTYs, raw mode, room to draw, no CI, no prompt hook in the environment. */
23
+ export const richTerminal = ({ stdin, stdout, env }) => Boolean(
24
+ stdin.isTTY && stdout.isTTY && typeof stdin.setRawMode === "function"
25
+ && !Object.hasOwn(env, "CI") && !/^dumb$/iu.test(env.TERM ?? "")
26
+ && !Object.keys(env).some((name) => /^LITCLAUDE_\w+_PROMPT$/u.test(name))
27
+ && (stdout.columns || 80) >= MIN_COLS && (stdout.rows || 24) >= MIN_ROWS,
28
+ );
29
+
30
+ // ---- colour ----------------------------------------------------------------------------------
31
+ const token = (hex, ansi16) => ({ hex, ansi16 });
32
+ const PINK = token("#ff2d95", 95);
33
+ const VIOLET = token("#b48cff", 94);
34
+ const ORANGE = token("#ff8f3c", 93);
35
+ const INK = token("#0b0e14", 30);
36
+ const IVORY = token("#f2efdf", 97);
37
+ const BAR = token("#34205c", 45);
38
+ const GREEN = token("#50e68c", 92);
39
+ const AMBER = token("#ffb02e", 93);
40
+ const RED = token("#ff5577", 91);
41
+ const CUBE = [0, 95, 135, 175, 215, 255];
42
+ const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
43
+ const toHex = (parts) => `#${parts.map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`;
44
+ const accentToken = (name) => {
45
+ const code = themeForAccent(name).code - 16;
46
+ return token(toHex([Math.floor(code / 36), Math.floor(code / 6) % 6, code % 6].map((v) => CUBE[v])), ansi16CodeForAccent(name) + 60);
47
+ };
48
+ const mix = (stops, t) => {
49
+ const at = Math.max(0, Math.min(1, t)) * (stops.length - 1);
50
+ const i = Math.min(stops.length - 2, Math.floor(at));
51
+ const [a, b] = [rgb(stops[i].hex), rgb(stops[i + 1].hex)];
52
+ return token(toHex(a.map((v, k) => v + (b[k] - v) * (at - i))), stops[Math.round(at)].ansi16);
53
+ };
54
+ const nearest = (v) => CUBE.reduce((best, level, i) => (Math.abs(level - v) < Math.abs(CUBE[best] - v) ? i : best), 0);
55
+ const sgr = ({ hex, ansi16 }, back, depth) => {
56
+ if (depth === "16") return String(ansi16 + (back ? 10 : 0));
57
+ if (depth === "truecolor") return `${back ? 48 : 38};2;${rgb(hex).join(";")}`;
58
+ const [r, g, b] = rgb(hex).map(nearest);
59
+ return `${back ? 48 : 38};5;${16 + 36 * r + 6 * g + b}`;
60
+ };
61
+
62
+ // ---- text ------------------------------------------------------------------------------------
63
+ const strip = (text) => text.replace(/\x1b\[[0-9;]*m/gu, "");
64
+ const cells = (text) => textWidth(strip(text));
65
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - cells(text)));
66
+
67
+ /** Word wrap in terminal cells; a word longer than the line (a path) is cut across lines, never shortened. */
68
+ export const wrap = (text, width) => {
69
+ const lines = [];
70
+ let line = "";
71
+ for (const word of String(text).split(/\s+/u).filter(Boolean)) {
72
+ if (line && cells(line) + 1 + cells(word) <= width) { line += ` ${word}`; continue; }
73
+ if (line) lines.push(line);
74
+ line = "";
75
+ for (const ch of word) {
76
+ if (cells(line + ch) > width) { lines.push(line); line = ""; }
77
+ line += ch;
78
+ }
79
+ }
80
+ return line || lines.length === 0 ? [...lines, line] : lines;
81
+ };
82
+
83
+ const UNICODE = {
84
+ tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│", pointer: "❯", done: "✓", fail: "✗", warn: "!", dot: "·",
85
+ up: "↑", down: "↓", keys: "↑ ↓", sides: "← →", bar: "▌", spin: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
86
+ on: ["╔", "═", "╗", "║", "╚", "╝"], off: ["╭", "─", "╮", "│", "╰", "╯"],
87
+ };
88
+ const ASCII = {
89
+ tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|", pointer: ">", done: "ok", fail: "x", warn: "!", dot: "-",
90
+ up: "^", down: "v", keys: "Up Down", sides: "Left Right", bar: "|", spin: ["-", "\\", "|", "/"],
91
+ on: ["#", "=", "#", "#", "#", "#"], off: ["+", "-", "+", "|", "+", "+"],
92
+ };
93
+ const ASCII_TEXT = { "—": "-", "·": "-", "…": "...", "→": "->", "한국어": "Korean" };
94
+
95
+ // ---- the cards ---------------------------------------------------------------------------------
96
+ export const createInstallUi = ({ stdin, stdout, env, animate = true, settleMs = SETTLE_MS, now = Date.now, proc = process }) => {
97
+ const depth = hudColorDepth(env);
98
+ const ascii = asciiLocale(env);
99
+ const glyph = ascii ? ASCII : UNICODE;
100
+ let accent = "cyan";
101
+ let letterAnsweredAt = -Infinity;
102
+
103
+ const plainText = (text) => (ascii ? String(text).replace(/[—·…→]|한국어/gu, (found) => ASCII_TEXT[found]).replace(/[^\x1b\x20-\x7e]/gu, "?") : String(text));
104
+ const paint = (text, { fg, bg, bold, dim } = {}) => {
105
+ if (depth === "plain" || !text) return text;
106
+ const codes = [bold && "1", dim && "2", fg && sgr(fg, false, depth), bg && sgr(bg, true, depth)].filter(Boolean);
107
+ return codes.length > 0 ? `\x1b[${codes.join(";")}m${text}\x1b[0m` : text;
108
+ };
109
+ // Cells along a gradient; neighbours that round to the same step share one escape.
110
+ const ramp = (text, stops, style, from = 0, span = [...text].length) => {
111
+ if (depth === "plain") return text;
112
+ const runs = [];
113
+ [...text].forEach((ch, i) => {
114
+ const step = Math.round(((from + i) / Math.max(1, span - 1)) * 24);
115
+ if (runs.at(-1)?.step === step) runs.at(-1).text += ch;
116
+ else runs.push({ step, text: ch });
117
+ });
118
+ return runs.map((run) => paint(run.text, style(mix(stops, run.step / 24)))).join("");
119
+ };
120
+ const size = () => ({ cols: stdout.columns || 80, rows: stdout.rows || 24 });
121
+ const cardWidth = () => Math.min(size().cols - 2, MAX_WIDTH);
122
+ const heading = (text) => paint(plainText(text), { bold: true });
123
+ const quiet = (text) => paint(plainText(text), { dim: true });
124
+
125
+ const pill = (text) => (depth === "plain" ? `[${text}]` : ramp(` ${text} `, [ORANGE, PINK], (bg) => ({ fg: INK, bg, bold: true })));
126
+ const frame = ({ tag = "LIT", title, body, tone }) => {
127
+ const width = cardWidth();
128
+ const inner = width - 4;
129
+ const stops = tone === "bad" ? [RED, RED] : [PINK, VIOLET, accentToken(accent)];
130
+ const line = (text, from) => ramp(text, stops, (fg) => ({ fg }), from, width);
131
+ const badge = pill(tag);
132
+ const inEdge = cells(badge) + cells(plainText(title)) + 8 <= width;
133
+ const used = 2 + cells(badge) + (inEdge ? cells(plainText(title)) + 2 : 0);
134
+ const top = line(glyph.tl + glyph.h, 0) + badge + (inEdge ? ` ${heading(title)} ` : "") + line(glyph.h.repeat(width - used - 1) + glyph.tr, used);
135
+ const rows = [...(inEdge ? [] : wrap(plainText(title), inner).map((text) => paint(text, { bold: true }))), ...body];
136
+ return [
137
+ top,
138
+ ...rows.map((row) => `${line(glyph.v, 0)} ${pad(row, inner)} ${line(glyph.v, width - 1)}`),
139
+ line(glyph.bl + glyph.h.repeat(width - 2) + glyph.br, 0),
140
+ ].map((row) => ` ${row}`);
141
+ };
142
+
143
+ // ---- drawing in place ----
144
+ let drawn = [];
145
+ const lift = (count) => (count > 0 ? `\x1b[${count}A` : "");
146
+ const draw = (rows) => {
147
+ const shown = rows.slice(-Math.max(1, size().rows - 1));
148
+ let out = lift(drawn.length);
149
+ if (drawn.length !== shown.length) out += "\r\x1b[J";
150
+ shown.forEach((row, i) => { out += drawn.length === shown.length && drawn[i] === row ? "\r\n" : `\r${row}\x1b[K\r\n`; });
151
+ drawn = shown;
152
+ stdout.write(out);
153
+ };
154
+ // After a resize the old rows may have wrapped: step over what they take up now, then draw afresh.
155
+ const redraw = (rows) => {
156
+ const { cols, rows: height } = size();
157
+ const taken = drawn.reduce((sum, row) => sum + Math.max(1, Math.ceil(cells(row) / cols)), 0);
158
+ stdout.write(`${lift(Math.min(taken, height - 1))}\r\x1b[J`);
159
+ drawn = [];
160
+ draw(rows);
161
+ };
162
+ const replaceWith = (row) => {
163
+ stdout.write(`${lift(drawn.length)}\r\x1b[J${row}\r\n`);
164
+ drawn = [];
165
+ };
166
+
167
+ // ---- the terminal's own state ----
168
+ let active = false;
169
+ const restore = () => {
170
+ if (!active) return;
171
+ active = false;
172
+ stdout.write("\x1b[?25h");
173
+ stdin.setRawMode(false);
174
+ stdin.pause();
175
+ };
176
+ const onSignal = (signal) => { release(); proc.kill(proc.pid, signal); };
177
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
178
+ const acquire = () => {
179
+ active = true;
180
+ stdin.setRawMode(true);
181
+ stdin.resume();
182
+ stdout.write("\x1b[?25l");
183
+ proc.on("exit", restore);
184
+ for (const signal of SIGNALS) proc.on(signal, onSignal);
185
+ };
186
+ const release = () => {
187
+ restore();
188
+ proc.removeListener("exit", restore);
189
+ for (const signal of SIGNALS) proc.removeListener(signal, onSignal);
190
+ };
191
+ const aborted = (key) => new Error(`Aborted with Ctrl+${key}`);
192
+
193
+ // Keys typed before a card is on screen were never meant for it.
194
+ const settle = () => new Promise((resolve, reject) => {
195
+ const onData = (chunk) => { if (String(chunk).includes("\x03")) finish(aborted("C")); };
196
+ const finish = (error) => {
197
+ clearTimeout(timer);
198
+ stdin.removeListener("data", onData);
199
+ if (error) reject(error);
200
+ else resolve();
201
+ };
202
+ const timer = setTimeout(finish, settleMs);
203
+ stdin.on("data", onData);
204
+ });
205
+
206
+ // Draws `view()`, feeds it keys until `onKey` returns { value }, then folds it to `fold(value)`.
207
+ const ask = async ({ view, onKey, fold, stopped }) => {
208
+ acquire();
209
+ let onKeypress;
210
+ let onResize;
211
+ let onEnd;
212
+ try {
213
+ await settle();
214
+ draw(view());
215
+ const value = await new Promise((resolve, reject) => {
216
+ let finished = false;
217
+ onKeypress = (text, key = {}) => {
218
+ if (finished) return;
219
+ if (key.ctrl && (key.name === "c" || key.name === "d")) { finished = true; reject(aborted(key.name.toUpperCase())); return; }
220
+ if (key.ctrl && key.name === "z" && proc.platform !== "win32") {
221
+ // stdin stays open: with nothing left to wait for, the process would end on its return.
222
+ stdout.write("\x1b[?25h");
223
+ stdin.setRawMode(false);
224
+ proc.once("SIGCONT", () => {
225
+ if (finished) return;
226
+ stdin.setRawMode(true);
227
+ stdout.write("\x1b[?25l");
228
+ drawn = [];
229
+ draw(view());
230
+ });
231
+ // The whole job, as the terminal would: a launcher such as npx left running would keep the shell waiting.
232
+ proc.kill(0, "SIGTSTP");
233
+ return;
234
+ }
235
+ if (key.ctrl || key.meta || key.name === "escape") return;
236
+ const enter = key.name === "return" || key.name === "enter";
237
+ if (enter && now() - letterAnsweredAt < LETTER_ENTER_MS) return;
238
+ const answer = onKey({ text, name: key.name, enter });
239
+ if (answer) { finished = true; resolve(answer.value); } else draw(view());
240
+ };
241
+ onResize = () => { if (!finished) redraw(view()); };
242
+ onEnd = () => { if (!finished) { finished = true; reject(new Error("Aborted: the terminal closed")); } };
243
+ emitKeypressEvents(stdin);
244
+ stdin.on("keypress", onKeypress);
245
+ stdout.on("resize", onResize);
246
+ stdin.once("end", onEnd);
247
+ });
248
+ replaceWith(fold(value));
249
+ return value;
250
+ } catch (error) {
251
+ replaceWith(stopped);
252
+ throw error;
253
+ } finally {
254
+ if (onKeypress) stdin.removeListener("keypress", onKeypress);
255
+ if (onResize) stdout.removeListener("resize", onResize);
256
+ if (onEnd) stdin.removeListener("end", onEnd);
257
+ release();
258
+ }
259
+ };
260
+
261
+ const foldRow = (mark, color, title, value) => {
262
+ const room = size().cols;
263
+ const label = cells(title) + cells(value) + 8 + cells(mark) > room ? `${plainText(title)} ` : pad(plainText(title), Math.min(28, Math.max(22, cells(title) + 2)));
264
+ return ` ${paint(mark, { fg: color, bold: true })} ${label} ${value}`;
265
+ };
266
+ const answered = (title, value) => foldRow(glyph.done, GREEN, title, paint(plainText(value), { bold: true }));
267
+ const stoppedRow = (title) => foldRow(glyph.fail, RED, title, "stopped");
268
+ // Key hints, as many to a line as fit; a hint is never split.
269
+ const hints = (parts, width) => parts.reduce((lines, part) => {
270
+ const joined = `${lines.at(-1)} ${part}`;
271
+ return lines.length > 0 && cells(joined) <= width ? [...lines.slice(0, -1), joined] : [...lines, part];
272
+ }, []).map(quiet);
273
+
274
+ // A card that fits the window: roomy when it can be, then without its blank rows.
275
+ const fit = (card, variants) => {
276
+ const budget = size().rows - 1;
277
+ for (const body of variants) {
278
+ const rows = frame({ ...card, body: body.rows });
279
+ const lead = body.tight ? rows : ["", ...rows];
280
+ if (lead.length <= budget || body === variants.at(-1)) return { rows: lead, over: lead.length - budget };
281
+ }
282
+ };
283
+
284
+ /**
285
+ * One choice from a list. `choices` are { id, label, key, views?, detail?, color? }: `views` are the
286
+ * same preview drawn at falling widths, of which the widest that fits every row is shown; `color` is
287
+ * an accent name, shown as a swatch.
288
+ */
289
+ const choose = async ({ tag, title, note, choices, initial, initialTag = "default", onHighlight = () => {} }) => {
290
+ const first = Math.max(0, choices.findIndex(({ id }) => id === initial));
291
+ let at = first;
292
+ const render = () => {
293
+ const inner = cardWidth() - 4;
294
+ const swatch = ({ color }) => (color && depth !== "plain" ? `${paint(ascii ? "##" : "██", { fg: accentToken(color) })} ` : "");
295
+ const labels = choices.map((choice) => swatch(choice) + plainText(choice.label));
296
+ const labelWidth = Math.max(...labels.map(cells));
297
+ const tagText = [depth === "plain" ? `(${initialTag})` : initialTag, "*"].find((t, i) => i === 1 || 6 + labelWidth + cells(t) <= inner);
298
+ const tagWidth = cells(tagText) + 2;
299
+ const room = inner - 4 - labelWidth - 2 - tagWidth;
300
+ const views = choices[0].views ?? [];
301
+ const shown = views.findIndex((_, i) => choices.every((choice) => cells(choice.views[i]) <= room));
302
+ const details = !views.length && choices.every(({ detail = "" }) => cells(plainText(detail)) <= room);
303
+ const viewWidth = shown < 0 ? 0 : Math.max(...choices.map((choice) => cells(choice.views[shown])));
304
+ const list = choices.map((choice, i) => {
305
+ const on = i === at;
306
+ const extra = shown >= 0 ? pad(choice.views[shown], viewWidth) : details ? (on ? plainText(choice.detail ?? "") : quiet(choice.detail ?? "")) : "";
307
+ const mark = i === first ? paint(tagText, on ? { bold: true } : { fg: PINK, bold: true }) : "";
308
+ const row = `${on ? glyph.pointer : " "} ${choice.key} ${pad(labels[i], labelWidth)}${extra ? ` ${extra}` : ""}${mark ? ` ${mark}` : ""}`;
309
+ if (!on || depth === "plain") return row;
310
+ const bar = `\x1b[${sgr(IVORY, false, depth)};${sgr(BAR, true, depth)}m`;
311
+ return `${bar}${pad(row, inner).replace(/\x1b\[(?:0|39)m/gu, (reset) => reset + bar)}\x1b[0m`;
312
+ });
313
+ const noteRows = wrap(plainText(note), inner);
314
+ const last = choices.at(-1).key;
315
+ const hintRows = hints([`${glyph.keys} move`, `${choices[0].key}-${choices.length > 9 ? "9, 0" : last} jump`, "Enter choose", "Ctrl+C stop"], inner);
316
+ const card = { tag, title };
317
+ const roomy = fit(card, [{ rows: ["", ...noteRows, "", ...list, "", ...hintRows] }, { rows: [...noteRows, "", ...list, "", ...hintRows] }, { rows: [...noteRows, ...list, ...hintRows], tight: true }]);
318
+ if (roomy.over <= 0) return roomy.rows;
319
+ // Too short for the whole list: a window on it that follows the highlight, the arrows saying there is more.
320
+ const shortHint = (more) => hints([more, "Enter choose", "Ctrl+C stop"], inner);
321
+ const spare = size().rows - 1 - frame({ ...card, body: [...noteRows, ...shortHint(`${list.length}/${list.length} ${glyph.up} ${glyph.down}`)] }).length;
322
+ const count = Math.max(1, Math.min(list.length, spare));
323
+ const start = Math.max(0, Math.min(at - Math.floor(count / 2), list.length - count));
324
+ const more = `${at + 1}/${list.length}${start > 0 ? ` ${glyph.up}` : ""}${start + count < list.length ? ` ${glyph.down}` : ""}`;
325
+ return frame({ ...card, body: [...noteRows, ...list.slice(start, start + count), ...shortHint(more)] });
326
+ };
327
+ const move = (to) => { at = (to + choices.length) % choices.length; onHighlight(choices[at].id); };
328
+ const id = await ask({
329
+ view: render,
330
+ stopped: stoppedRow(title),
331
+ fold: (value) => answered(title, choices.find((choice) => choice.id === value).label),
332
+ onKey: ({ text, name, enter }) => {
333
+ if (enter) return { value: choices[at].id };
334
+ if (name === "up" || name === "k") move(at - 1);
335
+ else if (name === "down" || name === "j") move(at + 1);
336
+ else if (name === "home") move(0);
337
+ else if (name === "end") move(choices.length - 1);
338
+ else {
339
+ const jump = choices.findIndex(({ key }) => key === text);
340
+ if (jump >= 0) move(jump);
341
+ }
342
+ return null;
343
+ },
344
+ });
345
+ return id;
346
+ };
347
+
348
+ /** Yes or no, with the default highlighted and named on its button. */
349
+ const confirm = async ({ tag, title, note, initial, foldYes = "yes", foldNo = "no" }) => {
350
+ let yes = initial;
351
+ const buttons = (small) => {
352
+ const inner = cardWidth() - 4;
353
+ const each = [[true, "Yes"], [false, "No"]].map(([value, word]) => {
354
+ const on = value === yes;
355
+ const label = `${on ? glyph.pointer : " "} ${word}${value === initial ? (inner >= 44 ? " (default)" : " default") : ""}`;
356
+ const width = Math.max(...["Yes", "No"].map((w) => w.length)) + (inner >= 44 ? 10 : 8) + 2;
357
+ const text = pad(label, width);
358
+ const set = on ? glyph.on : glyph.off;
359
+ if (small) return [on && depth !== "plain" ? ramp(` ${text} `, [PINK, VIOLET], (bg) => ({ fg: INK, bg, bold: true })) : on ? `[${text}]` : ` ${paint(text, { dim: true })} `];
360
+ if (on && depth !== "plain" && !ascii) {
361
+ const full = ` ${text} `;
362
+ const edge = (ch) => ramp(ch.repeat(cells(full)), [PINK, VIOLET], (fg) => ({ fg }));
363
+ return [edge("▄"), ramp(full, [PINK, VIOLET], (bg) => ({ fg: INK, bg, bold: true })), edge("▀")];
364
+ }
365
+ const style = on ? (t) => paint(t, { fg: PINK, bold: true }) : quiet;
366
+ const box = [set[0] + set[1].repeat(width + 2) + set[2], null, set[4] + set[1].repeat(width + 2) + set[5]];
367
+ return [style(box[0]), style(set[3]) + ` ${on ? paint(text, { bold: true }) : text} ` + style(set[3]), style(box[2])];
368
+ });
369
+ return each[0].map((left, i) => `${left} ${each[1][i]}`).filter((row) => cells(row) <= inner || small);
370
+ };
371
+ const render = () => {
372
+ const inner = cardWidth() - 4;
373
+ const noteRows = wrap(plainText(note), inner);
374
+ const hintRows = hints(["y / n answer", `${glyph.sides} switch`, `Enter = ${yes ? "Yes" : "No"}`, "Ctrl+C stop"], inner);
375
+ const big = buttons(false);
376
+ const small = buttons(true);
377
+ const pair = big.length === 3 ? big : small;
378
+ return fit({ tag, title: `${title} ${initial ? "[Y/n]" : "[y/N]"}` }, [
379
+ { rows: ["", ...noteRows, "", ...pair, "", ...hintRows] },
380
+ { rows: [...noteRows, "", ...pair, "", ...hintRows] },
381
+ { rows: [...noteRows, ...pair, ...hintRows], tight: true },
382
+ { rows: [...noteRows, ...small, ...hintRows], tight: true },
383
+ { rows: [...noteRows, ...small, ...hints(["y / n", `Enter = ${yes ? "Yes" : "No"}`, "Ctrl+C stop"], inner)], tight: true },
384
+ ]).rows;
385
+ };
386
+ return ask({
387
+ view: render,
388
+ stopped: stoppedRow(title),
389
+ fold: (value) => answered(title, value ? foldYes : foldNo),
390
+ onKey: ({ text, name, enter }) => {
391
+ if (enter) return { value: yes };
392
+ if (/^[yn]$/iu.test(text ?? "")) {
393
+ letterAnsweredAt = now();
394
+ return { value: /y/iu.test(text) };
395
+ }
396
+ if (["left", "right", "tab"].includes(name)) yes = !yes;
397
+ return null;
398
+ },
399
+ });
400
+ };
401
+
402
+ // ---- work in progress ----
403
+ // Keys pressed while work runs are dropped (echoed, they would push the card about); Ctrl+C still ends the process.
404
+ const hold = () => {
405
+ acquire();
406
+ const onData = (chunk) => { if (String(chunk).includes("\x03")) onSignal("SIGINT"); };
407
+ stdin.on("data", onData);
408
+ return () => { stdin.removeListener("data", onData); release(); };
409
+ };
410
+
411
+ /** A card of named steps. `run(i, work)` spins on step i; `finish` folds the card to one line. */
412
+ const progress = ({ tag, title, steps }) => {
413
+ const state = steps.map(() => "wait");
414
+ let spin = 0;
415
+ const letGo = hold();
416
+ const render = () => {
417
+ const inner = cardWidth() - 4;
418
+ const nameWidth = Math.max(...steps.map(({ name }) => name.length));
419
+ const body = steps.map(({ name, text }, i) => {
420
+ const mark = { wait: quiet(glyph.dot), run: paint(glyph.spin[spin % glyph.spin.length], { fg: accentToken(accent), bold: true }), done: paint(glyph.done, { fg: GREEN, bold: true }), fail: paint(glyph.fail, { fg: RED, bold: true }) }[state[i]];
421
+ const label = pad(name, nameWidth);
422
+ const row = `${pad(mark, cells(glyph.done))} ${state[i] === "run" ? paint(label, { bold: true }) : state[i] === "wait" ? quiet(label) : label}`;
423
+ return cells(row) + 2 + cells(text) <= inner ? `${row} ${quiet(text)}` : row;
424
+ });
425
+ return ["", ...frame({ tag, title, body, tone: state.includes("fail") ? "bad" : undefined })];
426
+ };
427
+ const onResize = () => redraw(render());
428
+ stdout.on("resize", onResize);
429
+ draw(render());
430
+ const stop = () => { stdout.removeListener("resize", onResize); letGo(); };
431
+ return {
432
+ async run(i, work) {
433
+ state[i] = "run";
434
+ draw(render());
435
+ const timer = animate ? setInterval(() => { spin += 1; draw(render()); }, 80) : undefined;
436
+ try {
437
+ const result = await work();
438
+ state[i] = "done";
439
+ return result;
440
+ } catch (error) {
441
+ state[i] = "fail";
442
+ throw error;
443
+ } finally {
444
+ clearInterval(timer);
445
+ draw(render());
446
+ if (state[i] === "fail") { drawn = []; stop(); }
447
+ }
448
+ },
449
+ finish(label, value, ok = true) { stop(); replaceWith(ok ? answered(label, value) : foldRow(glyph.warn, AMBER, label, plainText(value))); },
450
+ };
451
+ };
452
+
453
+ /** A finished card: sections of marked rows. A value is wrapped, never cut short. */
454
+ const panel = ({ tag, title, sections, tone }) => {
455
+ const inner = cardWidth() - 4;
456
+ const marks = { done: [glyph.done, GREEN], warn: [glyph.warn, AMBER], fail: [glyph.fail, RED], note: [glyph.dot, VIOLET] };
457
+ const labelWidth = Math.max(0, ...sections.flatMap(({ rows }) => rows.map(({ label = "" }) => cells(label)))) + 2;
458
+ const stacked = inner < 56;
459
+ const markWidth = cells(glyph.done) + 1;
460
+ const body = sections.flatMap(({ head, rows }) => [
461
+ "",
462
+ ...(head ? [paint(head, { fg: PINK, bold: true })] : []),
463
+ ...rows.flatMap(({ mark = "done", label = "", value }) => {
464
+ const [sign, color] = marks[mark];
465
+ const lead = `${pad(paint(sign, { fg: color, bold: true }), markWidth)}`;
466
+ const style = mark === "warn" || mark === "fail" ? (t) => paint(t, { bold: true }) : (t) => t;
467
+ if (!label || stacked) {
468
+ const lines = wrap(plainText(value), inner - markWidth);
469
+ const rest = lines.map((text) => " ".repeat(markWidth) + style(text));
470
+ return label ? [lead + heading(label), ...rest] : [lead + style(lines[0]), ...rest.slice(1)];
471
+ }
472
+ return wrap(plainText(value), inner - markWidth - labelWidth).map((text, i) => (i === 0
473
+ ? lead + pad(heading(label), labelWidth) + style(text)
474
+ : " ".repeat(markWidth + labelWidth) + style(text)));
475
+ }),
476
+ ]);
477
+ stdout.write(`\n${frame({ tag, title, body, tone }).join("\n")}\n\n`);
478
+ };
479
+
480
+ return {
481
+ depth, ascii, choose, confirm, progress, panel, paint, plainText, heading,
482
+ setAccent: (name) => { accent = name; },
483
+ cols: () => size().cols,
484
+ };
485
+ };