@phren/cli 0.1.42 → 0.1.45

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.
Files changed (97) hide show
  1. package/dist/capabilities/cli.js +1 -1
  2. package/dist/capabilities/mcp.js +1 -1
  3. package/dist/capabilities/vscode.js +3 -3
  4. package/dist/capabilities/web-ui.js +29 -29
  5. package/dist/cli/actions.d.ts +1 -1
  6. package/dist/cli/actions.js +7 -2
  7. package/dist/cli/config-proactivity.d.ts +6 -6
  8. package/dist/cli/hooks-output.js +15 -6
  9. package/dist/cli/hooks.d.ts +1 -1
  10. package/dist/cli/hooks.js +16 -5
  11. package/dist/cli/session-stop.d.ts +1 -1
  12. package/dist/cli/session-tool-hook.d.ts +1 -1
  13. package/dist/cli-registry.js +1 -1
  14. package/dist/data/access.js +2 -1
  15. package/dist/generated/memory-ui-graph.browser.js +481 -318
  16. package/dist/governance/locks.js +6 -0
  17. package/dist/governance/scores.d.ts +9 -1
  18. package/dist/governance/scores.js +12 -1
  19. package/dist/graph-core/index.d.ts +2 -0
  20. package/dist/graph-core/index.js +2 -0
  21. package/dist/graph-core/model.d.ts +84 -0
  22. package/dist/graph-core/model.js +355 -0
  23. package/dist/graph-core/types.d.ts +110 -0
  24. package/dist/graph-core/types.js +43 -0
  25. package/dist/index.js +4 -1
  26. package/dist/init/init-uninstall.d.ts +1 -0
  27. package/dist/init/init-uninstall.js +13 -3
  28. package/dist/init/setup.js +11 -4
  29. package/dist/link/context.js +2 -1
  30. package/dist/link/link.js +3 -2
  31. package/dist/link/skills.js +2 -1
  32. package/dist/memory-ui-graph.runtime.js +481 -318
  33. package/dist/phren-core.d.ts +16 -0
  34. package/dist/phren-core.js +21 -0
  35. package/dist/phren-paths.js +8 -4
  36. package/dist/profile-store.d.ts +2 -0
  37. package/dist/profile-store.js +16 -19
  38. package/dist/project-config.js +2 -1
  39. package/dist/shared/fragment-graph.js +7 -2
  40. package/dist/shared/index.js +1 -1
  41. package/dist/shared/retrieval.d.ts +38 -0
  42. package/dist/shared/retrieval.js +62 -4
  43. package/dist/shell/entry.d.ts +10 -2
  44. package/dist/shell/entry.js +128 -97
  45. package/dist/shell/graph/canvas.d.ts +64 -0
  46. package/dist/shell/graph/canvas.js +256 -0
  47. package/dist/shell/graph/controller.d.ts +164 -0
  48. package/dist/shell/graph/controller.js +645 -0
  49. package/dist/shell/graph/glyphs.d.ts +12 -0
  50. package/dist/shell/graph/glyphs.js +31 -0
  51. package/dist/shell/graph/graph-view.d.ts +12 -0
  52. package/dist/shell/graph/graph-view.js +408 -0
  53. package/dist/shell/graph/layout.d.ts +68 -0
  54. package/dist/shell/graph/layout.js +267 -0
  55. package/dist/shell/input.d.ts +4 -1
  56. package/dist/shell/input.js +28 -5
  57. package/dist/shell/intro.d.ts +37 -0
  58. package/dist/shell/intro.js +82 -0
  59. package/dist/shell/keys.d.ts +36 -0
  60. package/dist/shell/keys.js +107 -0
  61. package/dist/shell/logo-fx.d.ts +35 -0
  62. package/dist/shell/logo-fx.js +128 -0
  63. package/dist/shell/render.d.ts +34 -1
  64. package/dist/shell/render.js +220 -66
  65. package/dist/shell/shell.d.ts +13 -1
  66. package/dist/shell/shell.js +61 -10
  67. package/dist/shell/startup.d.ts +37 -0
  68. package/dist/shell/startup.js +105 -0
  69. package/dist/shell/state-store.d.ts +1 -1
  70. package/dist/shell/state-store.js +1 -1
  71. package/dist/shell/types.js +1 -0
  72. package/dist/shell/view.d.ts +3 -0
  73. package/dist/shell/view.js +26 -4
  74. package/dist/store-registry.d.ts +13 -0
  75. package/dist/store-registry.js +109 -37
  76. package/dist/test-global-setup.d.ts +1 -0
  77. package/dist/test-global-setup.js +22 -0
  78. package/dist/tool-registry.js +1 -0
  79. package/dist/tools/memory.js +12 -5
  80. package/dist/tools/ops.js +1 -1
  81. package/dist/ui/data.d.ts +15 -7
  82. package/dist/ui/data.js +102 -3
  83. package/dist/utils-fts.js +2 -1
  84. package/dist/utils-helpers.d.ts +1 -0
  85. package/dist/utils-helpers.js +6 -0
  86. package/dist/utils.d.ts +1 -1
  87. package/dist/utils.js +1 -1
  88. package/package.json +38 -7
  89. package/starter/global/skills/phren-consolidate/SKILL.md +152 -0
  90. package/starter/global/skills/phren-discover/SKILL.md +175 -0
  91. package/starter/global/skills/phren-init/SKILL.md +216 -0
  92. package/starter/global/skills/phren-profiles/SKILL.md +121 -0
  93. package/starter/global/skills/phren-sync/SKILL.md +261 -0
  94. package/dist/init-uninstall.d.ts +0 -3
  95. package/dist/init-uninstall.js +0 -514
  96. package/dist/init-walkthrough.d.ts +0 -55
  97. package/dist/init-walkthrough.js +0 -524
@@ -3,30 +3,15 @@
3
3
  * Extracted from shell.ts to keep the orchestrator under 300 lines.
4
4
  */
5
5
  import { PhrenShell } from "./shell.js";
6
- import { style, clearScreen, clearToEnd, shellStartupFrames, gradient, badge } from "./render.js";
7
- import { createPhrenAnimator } from "../phren-art.js";
6
+ import { style, clearScreen, paintFrame, enterFullscreen, exitFullscreen, } from "./render.js";
7
+ import { KeyDecoder, ESC_FLUSH_MS } from "./keys.js";
8
+ import { playSplash } from "./intro.js";
8
9
  import { errorMessage } from "../utils.js";
9
10
  import { computePhrenLiveStateToken } from "../shared.js";
10
11
  import { VERSION } from "../init/shared.js";
11
12
  import { loadShellState, saveShellState } from "./state-store.js";
12
13
  const LIVE_STATE_POLL_MS = 2000;
13
- function renderIntroFrame(frame, footer) {
14
- clearScreen();
15
- process.stdout.write(footer ? `${frame}\n${footer}\n` : `${frame}\n`);
16
- clearToEnd();
17
- }
18
- function sleep(ms) {
19
- return new Promise((resolve) => setTimeout(resolve, ms));
20
- }
21
- async function waitForAnyKeypress() {
22
- await new Promise((resolve) => {
23
- const onData = () => {
24
- process.stdin.removeListener("data", onData);
25
- resolve();
26
- };
27
- process.stdin.on("data", onData);
28
- });
29
- }
14
+ const noopWaiter = () => Promise.resolve();
30
15
  export function resolveStartupIntroPlan(phrenPath, version = VERSION) {
31
16
  const state = loadShellState(phrenPath);
32
17
  const mode = state.introMode === "always" || state.introMode === "off" ? state.introMode : "once-per-version";
@@ -47,68 +32,20 @@ function markStartupIntroSeen(phrenPath, version = VERSION) {
47
32
  return;
48
33
  saveShellState(phrenPath, { ...state, introSeenVersion: version });
49
34
  }
50
- async function playStartupIntro(phrenPath, plan = resolveStartupIntroPlan(phrenPath)) {
35
+ async function playStartupIntro(phrenPath, plan = resolveStartupIntroPlan(phrenPath), waitForAnyKeypress = noopWaiter) {
51
36
  if (!process.stdout.isTTY || plan.variant === "skip")
52
37
  return;
53
- const frames = shellStartupFrames(VERSION);
54
- const renderHint = plan.holdForKeypress
55
- ? `${style.dim("Press any key to enter")}`
56
- : `${style.dim("Loading shell…")}`;
57
- if (plan.variant === "full") {
58
- for (const frame of frames.slice(0, -1)) {
59
- renderIntroFrame(frame);
60
- await sleep(160);
61
- }
62
- }
63
- // Start animated phren during loading
64
- const animator = createPhrenAnimator({ facing: "right" });
65
- animator.start();
66
- const _cols = process.stdout.columns || 80;
67
- const tagline = style.dim("local memory for working agents");
68
- const versionBadge = badge(`v${VERSION}`, style.boldBlue);
69
- const logoLines = [
70
- "██████╗ ██╗ ██╗██████╗ ███████╗███╗ ██╗",
71
- "██╔══██╗██║ ██║██╔══██╗██╔════╝████╗ ██║",
72
- "██████╔╝███████║██████╔╝█████╗ ██╔██╗ ██║",
73
- "██╔═══╝ ██╔══██║██╔══██╗██╔══╝ ██║╚██╗██║",
74
- "██║ ██║ ██║██║ ██║███████╗██║ ╚████║",
75
- "╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝",
76
- ].map(l => gradient(l));
77
- const infoLine = `${gradient("◆")} ${style.bold("phren")} ${versionBadge} ${tagline}`;
78
- function renderAnimatedFrame(hint) {
79
- const phrenLines = animator.getFrame();
80
- const rightSide = ["", "", ...logoLines, "", infoLine];
81
- const charWidth = 26;
82
- const maxLines = Math.max(phrenLines.length, rightSide.length);
83
- const merged = [""];
84
- for (let i = 0; i < maxLines; i++) {
85
- const left = (i < phrenLines.length ? phrenLines[i] : "").padEnd(charWidth);
86
- const right = i < rightSide.length ? rightSide[i] : "";
87
- merged.push(left + right);
88
- }
89
- if (hint)
90
- merged.push("", ` ${hint}`);
91
- merged.push("");
92
- renderIntroFrame(merged.join("\n"));
93
- }
94
- // Animate during dwell/loading period
95
- if (plan.holdForKeypress) {
96
- const animInterval = setInterval(() => renderAnimatedFrame(renderHint), 200);
97
- renderAnimatedFrame(renderHint);
98
- await waitForAnyKeypress();
99
- clearInterval(animInterval);
100
- }
101
- else if (plan.dwellMs > 0) {
102
- const startTime = Date.now();
103
- while (Date.now() - startTime < plan.dwellMs) {
104
- renderAnimatedFrame(renderHint);
105
- await sleep(200);
106
- }
107
- }
108
- else {
109
- renderAnimatedFrame(renderHint);
110
- }
111
- animator.stop();
38
+ // The shell is already on the alternate screen; the splash paints in place.
39
+ // A full intro plays the wordmark reveal, a repeat launch opens on the
40
+ // finished wordmark, and either way the shimmer runs until dismissed.
41
+ await playSplash({
42
+ version: VERSION,
43
+ hint: plan.holdForKeypress ? "Press any key to enter" : "Loading shell…",
44
+ reveal: plan.variant === "full",
45
+ dwellMs: plan.dwellMs,
46
+ waitForKeypress: plan.holdForKeypress ? waitForAnyKeypress : undefined,
47
+ fullscreen: false,
48
+ });
112
49
  if (plan.markSeen) {
113
50
  markStartupIntroSeen(phrenPath);
114
51
  }
@@ -143,8 +80,8 @@ export function startLiveStatePoller({ phrenPath, shell, repaint, isExiting = ()
143
80
  clearInterval(poll);
144
81
  };
145
82
  }
146
- export async function startShell(phrenPath, profile) {
147
- const shell = new PhrenShell(phrenPath, profile);
83
+ export async function startShell(phrenPath, profile, startup = {}) {
84
+ const shell = new PhrenShell(phrenPath, profile, undefined, startup);
148
85
  if (!process.stdin.isTTY) {
149
86
  const { createInterface } = await import("readline");
150
87
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY ?? false });
@@ -173,10 +110,40 @@ export async function startShell(phrenPath, profile) {
173
110
  process.stdin.setRawMode(true);
174
111
  process.stdin.resume();
175
112
  process.stdin.setEncoding("utf8");
176
- process.stdout.write("\x1b[?1049h");
113
+ enterFullscreen();
177
114
  let exiting = false;
178
115
  let cleanedUp = false;
179
- const repaint = async () => { clearScreen(); process.stdout.write(await shell.render()); clearToEnd(); };
116
+ // ── Painting ────────────────────────────────────────────────────────────
117
+ // render() is async (the Health view awaits a doctor snapshot) and repaints
118
+ // are triggered from three independent sources — keys, resize, and the live
119
+ // store poller — none of which await each other. Serialising them keeps two
120
+ // renders from interleaving their writes; a repaint requested mid-render is
121
+ // coalesced into a single trailing repaint instead of queueing up.
122
+ let painting = false;
123
+ let repaintQueued = false;
124
+ const repaint = async () => {
125
+ if (painting) {
126
+ repaintQueued = true;
127
+ return;
128
+ }
129
+ painting = true;
130
+ try {
131
+ do {
132
+ repaintQueued = false;
133
+ const frame = await shell.render();
134
+ if (exiting)
135
+ return;
136
+ paintFrame(frame);
137
+ } while (repaintQueued);
138
+ }
139
+ finally {
140
+ painting = false;
141
+ }
142
+ };
143
+ // The graph view animates (layout settle, fly-to) and finishes builds off
144
+ // the key path; give the shell a way to repaint without a keypress.
145
+ shell.setRepaintHandler(() => { if (!exiting && !introActive)
146
+ void repaint(); });
180
147
  let done;
181
148
  const exitPromise = new Promise((resolve) => { done = resolve; });
182
149
  const restoreTerminal = () => {
@@ -191,27 +158,81 @@ export async function startShell(phrenPath, profile) {
191
158
  }
192
159
  catch { }
193
160
  try {
194
- process.stdout.write("\x1b[?1049l");
161
+ exitFullscreen();
195
162
  }
196
163
  catch { }
197
164
  };
198
- const onData = async (key) => {
199
- if (exiting)
165
+ // ── Key delivery ────────────────────────────────────────────────────────
166
+ // stdin hands us whatever arrived in one read, which is often several keys
167
+ // (autorepeat, fast typing, paste). Decode the chunk into discrete keys, then
168
+ // drain them through one sequential pump so handlers never run concurrently,
169
+ // and repaint once per burst rather than once per key.
170
+ const decoder = new KeyDecoder();
171
+ const keyQueue = [];
172
+ let escTimer;
173
+ let introKeyWaiter;
174
+ // Keys pressed while the splash is on screen queue up rather than repainting
175
+ // the dashboard underneath a frame the intro is still animating over.
176
+ let introActive = true;
177
+ const dispatch = (keys) => {
178
+ if (!keys.length)
179
+ return;
180
+ if (introKeyWaiter) {
181
+ // The splash consumes the key that dismisses it; the rest still count.
182
+ const resolveIntro = introKeyWaiter;
183
+ introKeyWaiter = undefined;
184
+ keys = keys.slice(1);
185
+ resolveIntro();
186
+ }
187
+ keyQueue.push(...keys);
188
+ void pump();
189
+ };
190
+ let pumping = false;
191
+ const pump = async () => {
192
+ if (pumping || introActive)
200
193
  return;
194
+ pumping = true;
201
195
  try {
202
- const keep = await shell.handleRawKey(key);
203
- if (!keep) {
204
- exiting = true;
205
- finish();
206
- return;
196
+ while (!exiting && keyQueue.length) {
197
+ while (!exiting && keyQueue.length) {
198
+ const key = keyQueue.shift();
199
+ try {
200
+ const keep = await shell.handleRawKey(key);
201
+ if (!keep) {
202
+ exiting = true;
203
+ keyQueue.length = 0;
204
+ finish();
205
+ return;
206
+ }
207
+ }
208
+ catch (err) {
209
+ shell.setMessage(`Error: ${errorMessage(err)}`);
210
+ }
211
+ }
212
+ if (!exiting)
213
+ await repaint();
207
214
  }
208
- await repaint();
209
215
  }
210
- catch (err) {
211
- shell.setMessage(`Error: ${errorMessage(err)}`);
212
- await repaint();
216
+ finally {
217
+ pumping = false;
213
218
  }
214
219
  };
220
+ const onData = (chunk) => {
221
+ if (exiting)
222
+ return;
223
+ if (escTimer) {
224
+ clearTimeout(escTimer);
225
+ escTimer = undefined;
226
+ }
227
+ dispatch(decoder.push(chunk));
228
+ if (decoder.hasPending()) {
229
+ // A trailing ESC is either the Escape key or the head of a sequence split
230
+ // across reads. Wait briefly for the rest before treating it as Escape.
231
+ escTimer = setTimeout(() => { escTimer = undefined; dispatch(decoder.flush()); }, ESC_FLUSH_MS);
232
+ escTimer.unref?.();
233
+ }
234
+ };
235
+ const waitForIntroKeypress = () => new Promise((resolve) => { introKeyWaiter = resolve; });
215
236
  const onResize = async () => { if (!exiting)
216
237
  await repaint(); };
217
238
  const onSignal = () => {
@@ -227,6 +248,12 @@ export async function startShell(phrenPath, profile) {
227
248
  return;
228
249
  cleanedUp = true;
229
250
  stopPoll();
251
+ if (escTimer) {
252
+ clearTimeout(escTimer);
253
+ escTimer = undefined;
254
+ }
255
+ introKeyWaiter?.();
256
+ introKeyWaiter = undefined;
230
257
  process.stdin.removeListener("data", onData);
231
258
  process.stdout.removeListener("resize", onResize);
232
259
  process.removeListener("SIGINT", onSignal);
@@ -242,8 +269,12 @@ export async function startShell(phrenPath, profile) {
242
269
  process.once("SIGTERM", onSignal);
243
270
  process.once("exit", onProcessExit);
244
271
  try {
245
- await playStartupIntro(phrenPath);
246
- await repaint();
272
+ await playStartupIntro(phrenPath, resolveStartupIntroPlan(phrenPath), waitForIntroKeypress);
273
+ introKeyWaiter = undefined;
274
+ introActive = false;
275
+ if (!exiting)
276
+ await repaint();
277
+ void pump();
247
278
  await exitPromise;
248
279
  }
249
280
  finally {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A braille dot canvas with a text overlay, rendered to ANSI lines.
3
+ *
4
+ * Each terminal cell is a 2×4 grid of braille dots (U+2800–U+28FF), which
5
+ * gives the graph 8× the resolution of plain block characters and — because
6
+ * a cell is roughly twice as tall as it is wide — dots that are close to
7
+ * square, so no aspect correction is needed. Edges and node blobs are drawn
8
+ * in dot space; glyphs, labels and the legend are written into a cell-level
9
+ * overlay that takes precedence when rendering.
10
+ *
11
+ * Every rendered line is exactly `cols` cells wide and built only from
12
+ * width-1 characters, so the shell's `truncateLine`/`displayWidth` pipeline
13
+ * measures it correctly.
14
+ */
15
+ export type ColorMode = "truecolor" | "256";
16
+ /** Tests pin the mode; real terminals are sniffed from COLORTERM/TERM. */
17
+ export declare function setColorMode(mode: ColorMode | null): void;
18
+ export declare function colorMode(): ColorMode;
19
+ export declare function hexToRgb(hex: string): [number, number, number];
20
+ export declare function rgbToHex(r: number, g: number, b: number): string;
21
+ /** Linear blend from `from` toward `to` by `t` in [0, 1]. */
22
+ export declare function blendHex(from: string, to: string, t: number): string;
23
+ /** Nearest xterm-256 index: 6×6×6 colour cube, or the grey ramp for greys. */
24
+ export declare function hexToAnsi256(hex: string): number;
25
+ /** Foreground SGR for a hex colour in the active colour mode. */
26
+ export declare function hexToSgr(hex: string): string;
27
+ export interface DotOptions {
28
+ /** Higher z wins when two draws hit the same cell (node dots beat edges). */
29
+ z?: number;
30
+ /** Light every other dot along a line. */
31
+ dotted?: boolean;
32
+ }
33
+ export declare class BrailleCanvas {
34
+ readonly cols: number;
35
+ readonly rows: number;
36
+ private readonly masks;
37
+ private readonly zs;
38
+ private readonly colors;
39
+ private readonly overlay;
40
+ constructor(cols: number, rows: number);
41
+ get dotWidth(): number;
42
+ get dotHeight(): number;
43
+ private cell;
44
+ setDot(x: number, y: number, color: string, z?: number): void;
45
+ /** Bresenham in dot space. */
46
+ line(x0: number, y0: number, x1: number, y1: number, color: string, opts?: DotOptions): void;
47
+ /** Filled disc in dot space; radius 0 lights a single dot. */
48
+ disc(cx: number, cy: number, radius: number, color: string, z?: number): void;
49
+ /**
50
+ * True when the cells [col, col+width) on `row` hold no overlay text —
51
+ * and, with `avoidDots`, no braille dots either, so a label does not
52
+ * paint over somebody else's node or edge.
53
+ */
54
+ isFree(col: number, row: number, width: number, avoidDots?: boolean): boolean;
55
+ /**
56
+ * Write styled text into the overlay. Characters wider than one cell are
57
+ * replaced with `·` so the row stays exactly `cols` wide. Returns the number
58
+ * of cells written (0 when the text starts off-canvas).
59
+ */
60
+ putText(col: number, row: number, text: string, sgr?: string): number;
61
+ /** Every cell in a rectangle is overlaid with a space, hiding dots underneath (pane backdrop). */
62
+ clearRect(col: number, row: number, width: number, height: number): void;
63
+ render(): string[];
64
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * A braille dot canvas with a text overlay, rendered to ANSI lines.
3
+ *
4
+ * Each terminal cell is a 2×4 grid of braille dots (U+2800–U+28FF), which
5
+ * gives the graph 8× the resolution of plain block characters and — because
6
+ * a cell is roughly twice as tall as it is wide — dots that are close to
7
+ * square, so no aspect correction is needed. Edges and node blobs are drawn
8
+ * in dot space; glyphs, labels and the legend are written into a cell-level
9
+ * overlay that takes precedence when rendering.
10
+ *
11
+ * Every rendered line is exactly `cols` cells wide and built only from
12
+ * width-1 characters, so the shell's `truncateLine`/`displayWidth` pipeline
13
+ * measures it correctly.
14
+ */
15
+ import { displayWidth } from "../render.js";
16
+ const RESET = "\x1b[0m";
17
+ // Braille bit for dot (x, y) inside a cell — x ∈ {0,1}, y ∈ {0..3}.
18
+ const DOT_BITS = [
19
+ [0x01, 0x08],
20
+ [0x02, 0x10],
21
+ [0x04, 0x20],
22
+ [0x40, 0x80],
23
+ ];
24
+ let colorModeOverride = null;
25
+ /** Tests pin the mode; real terminals are sniffed from COLORTERM/TERM. */
26
+ export function setColorMode(mode) {
27
+ colorModeOverride = mode;
28
+ }
29
+ export function colorMode() {
30
+ if (colorModeOverride)
31
+ return colorModeOverride;
32
+ const colorterm = (process.env.COLORTERM || "").toLowerCase();
33
+ if (colorterm === "truecolor" || colorterm === "24bit")
34
+ return "truecolor";
35
+ const term = (process.env.TERM || "").toLowerCase();
36
+ if (term.includes("direct") || term.includes("truecolor"))
37
+ return "truecolor";
38
+ return "256";
39
+ }
40
+ export function hexToRgb(hex) {
41
+ const clean = hex.replace("#", "");
42
+ const full = clean.length === 3 ? clean.split("").map((c) => c + c).join("") : clean.padEnd(6, "0");
43
+ const value = Number.parseInt(full.slice(0, 6), 16);
44
+ if (!Number.isFinite(value))
45
+ return [127, 127, 127];
46
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
47
+ }
48
+ export function rgbToHex(r, g, b) {
49
+ const clampByte = (v) => Math.max(0, Math.min(255, Math.round(v)));
50
+ return `#${[clampByte(r), clampByte(g), clampByte(b)].map((v) => v.toString(16).padStart(2, "0")).join("")}`;
51
+ }
52
+ /** Linear blend from `from` toward `to` by `t` in [0, 1]. */
53
+ export function blendHex(from, to, t) {
54
+ const a = hexToRgb(from);
55
+ const b = hexToRgb(to);
56
+ const k = Math.max(0, Math.min(1, t));
57
+ return rgbToHex(a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k);
58
+ }
59
+ /** Nearest xterm-256 index: 6×6×6 colour cube, or the grey ramp for greys. */
60
+ export function hexToAnsi256(hex) {
61
+ const [r, g, b] = hexToRgb(hex);
62
+ if (Math.abs(r - g) < 10 && Math.abs(g - b) < 10) {
63
+ if (r < 8)
64
+ return 16;
65
+ if (r > 248)
66
+ return 231;
67
+ return 232 + Math.round(((r - 8) / 247) * 23);
68
+ }
69
+ const level = (v) => Math.round((v / 255) * 5);
70
+ return 16 + 36 * level(r) + 6 * level(g) + level(b);
71
+ }
72
+ const sgrCache = new Map();
73
+ /** Foreground SGR for a hex colour in the active colour mode. */
74
+ export function hexToSgr(hex) {
75
+ const key = `${colorMode()}:${hex}`;
76
+ const cached = sgrCache.get(key);
77
+ if (cached)
78
+ return cached;
79
+ const [r, g, b] = hexToRgb(hex);
80
+ const sgr = colorMode() === "truecolor" ? `\x1b[38;2;${r};${g};${b}m` : `\x1b[38;5;${hexToAnsi256(hex)}m`;
81
+ sgrCache.set(key, sgr);
82
+ return sgr;
83
+ }
84
+ export class BrailleCanvas {
85
+ cols;
86
+ rows;
87
+ masks;
88
+ zs;
89
+ colors;
90
+ overlay;
91
+ constructor(cols, rows) {
92
+ this.cols = cols;
93
+ this.rows = rows;
94
+ const cells = Math.max(0, cols * rows);
95
+ this.masks = new Uint8Array(cells);
96
+ this.zs = new Int16Array(cells).fill(-32768);
97
+ this.colors = new Array(cells);
98
+ this.overlay = new Array(cells);
99
+ }
100
+ get dotWidth() { return this.cols * 2; }
101
+ get dotHeight() { return this.rows * 4; }
102
+ cell(col, row) {
103
+ return row * this.cols + col;
104
+ }
105
+ setDot(x, y, color, z = 0) {
106
+ const dx = Math.round(x);
107
+ const dy = Math.round(y);
108
+ if (dx < 0 || dy < 0 || dx >= this.dotWidth || dy >= this.dotHeight)
109
+ return;
110
+ const col = dx >> 1;
111
+ const row = dy >> 2;
112
+ const idx = this.cell(col, row);
113
+ this.masks[idx] |= DOT_BITS[dy & 3][dx & 1];
114
+ if (z >= this.zs[idx]) {
115
+ this.zs[idx] = z;
116
+ this.colors[idx] = color;
117
+ }
118
+ }
119
+ /** Bresenham in dot space. */
120
+ line(x0, y0, x1, y1, color, opts = {}) {
121
+ let ax = Math.round(x0);
122
+ let ay = Math.round(y0);
123
+ const bx = Math.round(x1);
124
+ const by = Math.round(y1);
125
+ const ddx = Math.abs(bx - ax);
126
+ const ddy = -Math.abs(by - ay);
127
+ const sx = ax < bx ? 1 : -1;
128
+ const sy = ay < by ? 1 : -1;
129
+ let err = ddx + ddy;
130
+ let n = 0;
131
+ for (;;) {
132
+ if (!opts.dotted || n % 2 === 0)
133
+ this.setDot(ax, ay, color, opts.z ?? 0);
134
+ if (ax === bx && ay === by)
135
+ break;
136
+ const e2 = 2 * err;
137
+ if (e2 >= ddy) {
138
+ err += ddy;
139
+ ax += sx;
140
+ }
141
+ if (e2 <= ddx) {
142
+ err += ddx;
143
+ ay += sy;
144
+ }
145
+ n++;
146
+ if (n > 100000)
147
+ break;
148
+ }
149
+ }
150
+ /** Filled disc in dot space; radius 0 lights a single dot. */
151
+ disc(cx, cy, radius, color, z = 1) {
152
+ const r = Math.max(0, radius);
153
+ const r2 = r * r + 0.25;
154
+ for (let y = Math.floor(cy - r); y <= Math.ceil(cy + r); y++) {
155
+ for (let x = Math.floor(cx - r); x <= Math.ceil(cx + r); x++) {
156
+ const ddx = x - cx;
157
+ const ddy = y - cy;
158
+ if (ddx * ddx + ddy * ddy <= r2)
159
+ this.setDot(x, y, color, z);
160
+ }
161
+ }
162
+ }
163
+ /**
164
+ * True when the cells [col, col+width) on `row` hold no overlay text —
165
+ * and, with `avoidDots`, no braille dots either, so a label does not
166
+ * paint over somebody else's node or edge.
167
+ */
168
+ isFree(col, row, width, avoidDots = false) {
169
+ if (row < 0 || row >= this.rows || col < 0 || col + width > this.cols)
170
+ return false;
171
+ for (let c = col; c < col + width; c++) {
172
+ const idx = this.cell(c, row);
173
+ if (this.overlay[idx])
174
+ return false;
175
+ if (avoidDots && this.masks[idx])
176
+ return false;
177
+ }
178
+ return true;
179
+ }
180
+ /**
181
+ * Write styled text into the overlay. Characters wider than one cell are
182
+ * replaced with `·` so the row stays exactly `cols` wide. Returns the number
183
+ * of cells written (0 when the text starts off-canvas).
184
+ */
185
+ putText(col, row, text, sgr = "") {
186
+ if (row < 0 || row >= this.rows)
187
+ return 0;
188
+ let c = col;
189
+ let written = 0;
190
+ for (const raw of text) {
191
+ if (c >= this.cols)
192
+ break;
193
+ if (c >= 0) {
194
+ const width = displayWidth(raw);
195
+ const ch = width === 1 ? raw : width === 0 ? "" : "·";
196
+ if (ch) {
197
+ this.overlay[this.cell(c, row)] = { ch, sgr };
198
+ written++;
199
+ }
200
+ else {
201
+ continue;
202
+ }
203
+ }
204
+ c++;
205
+ }
206
+ return written;
207
+ }
208
+ /** Every cell in a rectangle is overlaid with a space, hiding dots underneath (pane backdrop). */
209
+ clearRect(col, row, width, height) {
210
+ for (let r = row; r < row + height; r++) {
211
+ for (let c = col; c < col + width; c++) {
212
+ if (r < 0 || r >= this.rows || c < 0 || c >= this.cols)
213
+ continue;
214
+ this.overlay[this.cell(c, r)] = { ch: " ", sgr: "" };
215
+ }
216
+ }
217
+ }
218
+ render() {
219
+ const lines = [];
220
+ for (let row = 0; row < this.rows; row++) {
221
+ let out = "";
222
+ let current = "";
223
+ let dirty = false;
224
+ for (let col = 0; col < this.cols; col++) {
225
+ const idx = this.cell(col, row);
226
+ const over = this.overlay[idx];
227
+ let ch;
228
+ let sgr;
229
+ if (over) {
230
+ ch = over.ch;
231
+ sgr = over.sgr;
232
+ }
233
+ else if (this.masks[idx]) {
234
+ ch = String.fromCharCode(0x2800 + this.masks[idx]);
235
+ sgr = hexToSgr(this.colors[idx] ?? "#7f8db3");
236
+ }
237
+ else {
238
+ ch = " ";
239
+ sgr = "";
240
+ }
241
+ if (sgr !== current) {
242
+ if (current || dirty)
243
+ out += RESET;
244
+ out += sgr;
245
+ current = sgr;
246
+ dirty = true;
247
+ }
248
+ out += ch;
249
+ }
250
+ if (current || dirty)
251
+ out += RESET;
252
+ lines.push(out);
253
+ }
254
+ return lines;
255
+ }
256
+ }