@xynogen/pix-display 0.3.9 → 0.4.1
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/package.json +9 -3
- package/src/code-blocks.ts +13 -9
- package/src/directives.ts +489 -0
- package/src/image.ts +98 -0
- package/src/index.ts +24 -1
- package/src/math.ts +283 -0
- package/src/mermaid.ts +339 -0
- package/src/tables.ts +86 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xynogen/pix-display",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Pi core extension — inline chips, thinking blocks, and framed code rendering",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -38,8 +38,14 @@
|
|
|
38
38
|
"access": "public"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@xynogen/pix-pretty": "^
|
|
42
|
-
"@xynogen/pix-runtime": "^0.
|
|
41
|
+
"@xynogen/pix-pretty": "^3.0.2",
|
|
42
|
+
"@xynogen/pix-runtime": "^0.22.3"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@mathjax/src": "4.1.3",
|
|
46
|
+
"@resvg/resvg-wasm": "2.6.2",
|
|
47
|
+
"beautiful-mermaid": "1.1.3",
|
|
48
|
+
"inter-font": "3.19.0"
|
|
43
49
|
},
|
|
44
50
|
"peerDependencies": {
|
|
45
51
|
"@earendil-works/pi-coding-agent": "*",
|
package/src/code-blocks.ts
CHANGED
|
@@ -19,7 +19,7 @@ type RenderMode = "tui" | "rpc" | "json" | "print";
|
|
|
19
19
|
|
|
20
20
|
type PatchablePrototype = {
|
|
21
21
|
[PATCHED]?: boolean;
|
|
22
|
-
render(width: number): string[];
|
|
22
|
+
render(width: number): readonly string[];
|
|
23
23
|
invalidate(): void;
|
|
24
24
|
};
|
|
25
25
|
|
|
@@ -31,11 +31,11 @@ let activeTheme: CodeFrameTheme | undefined;
|
|
|
31
31
|
* their print/RPC session clear the theme silently disables code frames in the
|
|
32
32
|
* still-running parent transcript.
|
|
33
33
|
*/
|
|
34
|
-
export function themeAfterSessionStart(
|
|
35
|
-
current:
|
|
34
|
+
export function themeAfterSessionStart<T extends CodeFrameTheme>(
|
|
35
|
+
current: T | undefined,
|
|
36
36
|
mode: RenderMode,
|
|
37
|
-
theme:
|
|
38
|
-
):
|
|
37
|
+
theme: T,
|
|
38
|
+
): T | undefined {
|
|
39
39
|
return mode === "tui" ? theme : current;
|
|
40
40
|
}
|
|
41
41
|
|
|
@@ -96,7 +96,11 @@ function bodyLine(line: string, width: number, layoutIndent: number): string {
|
|
|
96
96
|
* Replace native Markdown fence rows with a themed code frame while preserving
|
|
97
97
|
* the syntax-highlighted ANSI content produced by Pi for every language.
|
|
98
98
|
*/
|
|
99
|
-
export function renderCodeFences(
|
|
99
|
+
export function renderCodeFences(
|
|
100
|
+
lines: readonly string[],
|
|
101
|
+
width: number,
|
|
102
|
+
theme: CodeFrameTheme,
|
|
103
|
+
): readonly string[] {
|
|
100
104
|
if (width < 12) return lines;
|
|
101
105
|
|
|
102
106
|
const out = [...lines];
|
|
@@ -144,15 +148,15 @@ function patchAssistantRenderer(): void {
|
|
|
144
148
|
{
|
|
145
149
|
width: number;
|
|
146
150
|
theme: CodeFrameTheme;
|
|
147
|
-
input: string[];
|
|
148
|
-
output: string[];
|
|
151
|
+
input: readonly string[];
|
|
152
|
+
output: readonly string[];
|
|
149
153
|
}
|
|
150
154
|
>();
|
|
151
155
|
prototype.invalidate = function invalidateCodeFrames(): void {
|
|
152
156
|
cache.delete(this);
|
|
153
157
|
nativeInvalidate.call(this);
|
|
154
158
|
};
|
|
155
|
-
prototype.render = function renderWithCodeFrames(width: number): string[] {
|
|
159
|
+
prototype.render = function renderWithCodeFrames(width: number): readonly string[] {
|
|
156
160
|
const lines = nativeRender.call(this, width);
|
|
157
161
|
if (!activeTheme) return lines;
|
|
158
162
|
const previous = cache.get(this);
|
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Directives in assistant Markdown (generic-directive syntax, as in Codex):
|
|
3
|
+
*
|
|
4
|
+
* ::card[23]{label="Total entri"} leaf: consecutive value cards render side by side;
|
|
5
|
+
* a subtitle= or body lines (up to a blank line) make it a full-width card
|
|
6
|
+
* ::bar[120]{label="pix-core"} leaf: consecutive lines render as one bar chart
|
|
7
|
+
* ::stacked[40]{label="pix-core"} leaf: consecutive lines render as one stacked 100% bar with a legend
|
|
8
|
+
* :red[text] :green[text] :yellow[text] :blue[text] inline: colored emphasis
|
|
9
|
+
* :spark[1 4 2 8 5] inline: sparkline ▁▃▂▇▅
|
|
10
|
+
* :badge[Tahap 1]{color=green} inline: label on a tinted background
|
|
11
|
+
*
|
|
12
|
+
* Display only: the session and the model keep the raw text. Code fences and
|
|
13
|
+
* inline code stay literal.
|
|
14
|
+
*/
|
|
15
|
+
import { BOLD, FG_BLUE, FG_DIM, FG_GREEN, FG_RED, FG_YELLOW, RST } from "@xynogen/pix-pretty/ansi";
|
|
16
|
+
import {
|
|
17
|
+
getCapabilities,
|
|
18
|
+
getMarkdownTheme,
|
|
19
|
+
Markdown,
|
|
20
|
+
truncateToWidth,
|
|
21
|
+
visibleWidth,
|
|
22
|
+
wrapTextWithAnsi,
|
|
23
|
+
} from "@xynogen/pix-pretty/tui";
|
|
24
|
+
import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
|
|
25
|
+
import { parseImage, renderImage } from "./image.ts";
|
|
26
|
+
import { renderMathBlocks } from "./math.ts";
|
|
27
|
+
import { renderMermaidBlocks } from "./mermaid.ts";
|
|
28
|
+
|
|
29
|
+
const BAR = /^::bar\[([^\]\n]+)\](?:\{([^}\n]*)\})?\s*$/;
|
|
30
|
+
// The lines right after a card, up to a blank line, are its Markdown body.
|
|
31
|
+
const CARD = /^::card(?:\[([^\]\n]*)\])?(?:\{([^}\n]*)\})?\s*$/;
|
|
32
|
+
const ITALIC = "\x1b[3m";
|
|
33
|
+
// SGR and OSC 8 sequences in already-rendered text: kept as is, only the text between is escaped.
|
|
34
|
+
const ESCAPE_SEQ = /(\x1b\[[0-9;]*m|\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\))/;
|
|
35
|
+
const STACKED = /^::stacked\[([^\]\n]+)\](?:\{([^}\n]*)\})?\s*$/;
|
|
36
|
+
// Parts without color= cycle through these: the four status colors, then extras.
|
|
37
|
+
const PART_COLORS = [
|
|
38
|
+
FG_BLUE,
|
|
39
|
+
FG_GREEN,
|
|
40
|
+
FG_YELLOW,
|
|
41
|
+
FG_RED,
|
|
42
|
+
"\x1b[38;2;180;120;220m",
|
|
43
|
+
"\x1b[38;2;90;190;200m",
|
|
44
|
+
"\x1b[38;2;220;140;80m",
|
|
45
|
+
"\x1b[38;2;150;150;150m",
|
|
46
|
+
];
|
|
47
|
+
// One glyph per part, so a part still reads without color.
|
|
48
|
+
const PART_GLYPHS = ["█", "▓", "▒", "░"];
|
|
49
|
+
// Left-aligned partial blocks, 1/8 to 7/8 of a cell.
|
|
50
|
+
const PARTIAL = " ▏▎▍▌▋▊▉";
|
|
51
|
+
const MAX_BAR_LABEL = 20;
|
|
52
|
+
const MAX_V_COL = 10;
|
|
53
|
+
const ATTR = /(\w+)=(?:"((?:[^"\\]|\\.)*)"|([^\s"}]+))/g;
|
|
54
|
+
const FENCE = /^\s*(```|~~~)/;
|
|
55
|
+
const MIN_CARD = 16;
|
|
56
|
+
const MAX_CHART = 72;
|
|
57
|
+
// NBSP pads the axis gutter: Markdown would strip or code-block leading spaces.
|
|
58
|
+
const NBSP = "\u00a0";
|
|
59
|
+
const COLORS: Record<string, string> = {
|
|
60
|
+
red: FG_RED,
|
|
61
|
+
green: FG_GREEN,
|
|
62
|
+
yellow: FG_YELLOW,
|
|
63
|
+
blue: FG_BLUE,
|
|
64
|
+
};
|
|
65
|
+
// Dark tints of COLORS for badge backgrounds: the colored text stays readable on them.
|
|
66
|
+
const BADGE_BG: Record<string, string> = {
|
|
67
|
+
red: "\x1b[48;2;70;32;32m",
|
|
68
|
+
green: "\x1b[48;2;30;58;40m",
|
|
69
|
+
yellow: "\x1b[48;2;68;56;24m",
|
|
70
|
+
blue: "\x1b[48;2;30;45;80m",
|
|
71
|
+
};
|
|
72
|
+
const SPARK = "▁▂▃▄▅▆▇█";
|
|
73
|
+
const MAX_SPARK = 60;
|
|
74
|
+
// A file path with a directory and an extension, optionally `:line[:col]`: `src/a.ts:12`.
|
|
75
|
+
const PATH = String.raw`(?:~|\.{1,2})?\/?(?:[\w.@-]+\/)+[\w@-][\w.@-]*\.[A-Za-z]\w{0,7}(?::\d+(?::\d+)?)?`;
|
|
76
|
+
const PATH_ONLY = new RegExp(`^${PATH}$`);
|
|
77
|
+
// A code span is matched first, so `:red[x]` inside backticks stays literal. Order matters:
|
|
78
|
+
// a link or URL is consumed whole before the path pattern could match inside it.
|
|
79
|
+
const INLINE = new RegExp(
|
|
80
|
+
[
|
|
81
|
+
String.raw`(?<ticks>\`+)(?<code>[^\`]*?)\k<ticks>`,
|
|
82
|
+
String.raw`(?<![\w:]):(?<name>red|green|yellow|blue|spark)\[(?<text>[^\]\n]+)\]`,
|
|
83
|
+
String.raw`(?<![\w:]):badge\[(?<badge>[^\]\n]+)\](?:\{(?<badgeAttrs>[^}\n]*)\})?`,
|
|
84
|
+
String.raw`(?<!!)\[(?<linkText>[^\]\n]+)\]\((?<href>https?:\/\/[^\s)]+)\)`,
|
|
85
|
+
String.raw`(?<![\w/(<\]])(?<url>https?:\/\/[^\s<>()\]]*[^\s<>()\].,;:!?'"])`,
|
|
86
|
+
String.raw`(?<![\w/.:~@-])(?<path>${PATH})(?![\w/@-])`,
|
|
87
|
+
].join("|"),
|
|
88
|
+
"g",
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
/** Sparkline for 2..MAX_SPARK finite numbers; undefined leaves the directive as text. */
|
|
92
|
+
export function sparkline(raw: string): string | undefined {
|
|
93
|
+
const values = raw
|
|
94
|
+
.split(/[\s,]+/)
|
|
95
|
+
.filter(Boolean)
|
|
96
|
+
.map(Number);
|
|
97
|
+
if (values.length < 2 || values.length > MAX_SPARK) return undefined;
|
|
98
|
+
if (values.some((v) => !Number.isFinite(v))) return undefined;
|
|
99
|
+
const min = Math.min(...values);
|
|
100
|
+
const span = Math.max(...values) - min;
|
|
101
|
+
const last = SPARK.length - 1;
|
|
102
|
+
return values
|
|
103
|
+
.map((v) => SPARK[span === 0 ? last >> 1 : Math.round(((v - min) / span) * last)])
|
|
104
|
+
.join("");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Label on a tinted background, no padding, so the tint ends at the text and does not
|
|
109
|
+
* bleed into the spaces around it. With `href`, the whole badge is an OSC 8 link (BEL
|
|
110
|
+
* terminated: a `\` would start a Markdown escape). `\x1b[39m`/`\x1b[49m` reset only the
|
|
111
|
+
* colors, so bold or italic around the badge survives.
|
|
112
|
+
*/
|
|
113
|
+
function badge(text: string, color: string, href?: string): string {
|
|
114
|
+
const key = COLORS[color] ? color : "blue";
|
|
115
|
+
const linked = href ? `\x1b]8;;${literal(href)}\x07${text}\x1b]8;;\x07` : text;
|
|
116
|
+
return `${BADGE_BG[key]}${COLORS[key]}${linked}\x1b[39m\x1b[49m`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** `example.com` for `https://www.example.com/a/b`. */
|
|
120
|
+
function host(url: string): string {
|
|
121
|
+
try {
|
|
122
|
+
return new URL(url).host.replace(/^www\./, "");
|
|
123
|
+
} catch {
|
|
124
|
+
return url;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
type InlineGroups = Partial<Record<string, string>>;
|
|
129
|
+
|
|
130
|
+
/** One inline match: directives, plus links, bare URLs and file paths as badges. */
|
|
131
|
+
function inlineMatch(match: string, g: InlineGroups): string {
|
|
132
|
+
if (g.ticks) return g.code && PATH_ONLY.test(g.code) ? badge(literal(g.code), "green") : match;
|
|
133
|
+
if (g.badge) return badge(g.badge, attrs(g.badgeAttrs).color ?? "");
|
|
134
|
+
if (g.path) return badge(literal(g.path), "green");
|
|
135
|
+
// Without OSC 8 the badge would hide the URL: keep Pi's own link rendering.
|
|
136
|
+
const links = getCapabilities().hyperlinks;
|
|
137
|
+
if (g.href) return links ? badge(g.linkText ?? "", "blue", g.href) : match;
|
|
138
|
+
if (g.url) return links ? badge(literal(host(g.url)), "blue", g.url) : match;
|
|
139
|
+
if (g.name && g.name !== "spark") return `${COLORS[g.name]}${g.text}\x1b[39m`;
|
|
140
|
+
const spark = sparkline(g.text ?? "");
|
|
141
|
+
return spark ? `${FG_BLUE}${spark}\x1b[39m` : match;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function colorInline(line: string): string {
|
|
145
|
+
return line.replace(INLINE, (match, ...rest) => inlineMatch(match, rest.at(-1) as InlineGroups));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** {@link colorInline} on every line outside code fences. */
|
|
149
|
+
function inlineLines(lines: readonly string[]): string[] {
|
|
150
|
+
let fenced = false;
|
|
151
|
+
return lines.map((line) => {
|
|
152
|
+
if (FENCE.test(line)) fenced = !fenced;
|
|
153
|
+
return fenced ? line : colorInline(line);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function attrs(raw: string | undefined): Record<string, string> {
|
|
158
|
+
const out: Record<string, string> = {};
|
|
159
|
+
for (const [, key, quoted, bare] of (raw ?? "").matchAll(ATTR)) {
|
|
160
|
+
// Only `\"` is an escape, so a Windows path keeps its backslashes.
|
|
161
|
+
if (key) out[key] = quoted?.replaceAll('\\"', '"') ?? bare ?? "";
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** `color=red|green|yellow|blue`; anything else keeps the default accent. */
|
|
167
|
+
function colorOf(name: string | undefined): string {
|
|
168
|
+
return (name && COLORS[name]) || FG_BLUE;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* X-axis rows under a plot `cols` wide: tick marks on the baseline and labels
|
|
173
|
+
* placed left to right, skipping any label that would touch the previous one.
|
|
174
|
+
*/
|
|
175
|
+
function xAxis(
|
|
176
|
+
labels: readonly string[],
|
|
177
|
+
at: (i: number) => number,
|
|
178
|
+
cols: number,
|
|
179
|
+
): [string, string] {
|
|
180
|
+
const rule = Array.from({ length: cols }, () => "─");
|
|
181
|
+
let text = "";
|
|
182
|
+
labels.forEach((raw, i) => {
|
|
183
|
+
const label = truncateToWidth(raw, MAX_BAR_LABEL, "…");
|
|
184
|
+
const size = visibleWidth(label);
|
|
185
|
+
const col = Math.min(cols - 1, at(i));
|
|
186
|
+
const start = Math.max(0, Math.min(cols - size, col - (size >> 1)));
|
|
187
|
+
const used = visibleWidth(text);
|
|
188
|
+
if ((used > 0 && start <= used) || start + size > cols) return;
|
|
189
|
+
rule[col] = "┬";
|
|
190
|
+
text += NBSP.repeat(start - used) + literal(label);
|
|
191
|
+
});
|
|
192
|
+
return [rule.join(""), text];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function axisNumber(n: number): string {
|
|
196
|
+
return String(Number(n.toPrecision(4)));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
type Bar = { value: number; label: string; color: string; vertical: boolean; height: number };
|
|
200
|
+
|
|
201
|
+
function parseBar(line: string): Bar | undefined {
|
|
202
|
+
const match = BAR.exec(line);
|
|
203
|
+
const value = Number(match?.[1]);
|
|
204
|
+
if (!match || !Number.isFinite(value)) return undefined;
|
|
205
|
+
const { label = "", color, direction, height } = attrs(match[2]);
|
|
206
|
+
return {
|
|
207
|
+
value,
|
|
208
|
+
label,
|
|
209
|
+
color: colorOf(color),
|
|
210
|
+
vertical: direction === "vertical",
|
|
211
|
+
height: Math.min(20, Math.max(3, Number(height) || 8)),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Vertical bar chart: y axis from 0 to max, each value just above its bar, label row. */
|
|
216
|
+
export function renderVerticalBars(bars: readonly Bar[], width: number): string[] | undefined {
|
|
217
|
+
const max = Math.max(...bars.map((b) => b.value), 0);
|
|
218
|
+
const height = bars[0]?.height ?? 8;
|
|
219
|
+
const numbers = bars.map((b) => axisNumber(b.value));
|
|
220
|
+
// Tick k sits at the top edge of bar row k (value max · (height - k) / height):
|
|
221
|
+
// max on top, half when the rows split evenly. The baseline carries 0.
|
|
222
|
+
const ticks = new Array<string>(height).fill("");
|
|
223
|
+
ticks[0] = axisNumber(max);
|
|
224
|
+
if (height % 2 === 0) ticks[height / 2] = axisNumber(max / 2);
|
|
225
|
+
const gutter = Math.max(1, ...ticks.map((t) => t.length));
|
|
226
|
+
const natural = Math.max(
|
|
227
|
+
...bars.map((b, i) => Math.max(visibleWidth(b.label), numbers[i]?.length ?? 0)),
|
|
228
|
+
);
|
|
229
|
+
const room = Math.min(width, MAX_CHART) - gutter - 1;
|
|
230
|
+
const col = Math.min(MAX_V_COL, natural, Math.floor((room + 1) / bars.length) - 1);
|
|
231
|
+
// Too narrow to keep each value readable: the caller falls back to horizontal.
|
|
232
|
+
if (col < Math.max(...numbers.map((n) => n.length), 2)) return undefined;
|
|
233
|
+
const cell = (text: string, style = "") => {
|
|
234
|
+
const fitted = truncateToWidth(text, col, "…");
|
|
235
|
+
const pad = NBSP.repeat(col - visibleWidth(fitted));
|
|
236
|
+
return style ? `${style}${literal(fitted)}${RST}${pad}` : `${literal(fitted)}${pad}`;
|
|
237
|
+
};
|
|
238
|
+
const pad = (text: string) => literal(NBSP.repeat(gutter - text.length) + text);
|
|
239
|
+
const axis = (tick: string | undefined) =>
|
|
240
|
+
tick === undefined ? NBSP.repeat(gutter + 1) : `${pad(tick)}${FG_DIM}${tick ? "┤" : "│"}${RST}`;
|
|
241
|
+
const row = (cells: string[]) => cells.join(NBSP);
|
|
242
|
+
const levels = bars.map((b) =>
|
|
243
|
+
max > 0 ? Math.round((Math.max(0, b.value) / max) * height * 8) : 0,
|
|
244
|
+
);
|
|
245
|
+
// Row r counts up from the baseline; row `height` holds the tallest bar's value.
|
|
246
|
+
const rows: string[] = [];
|
|
247
|
+
for (let r = height; r >= 0; r--) {
|
|
248
|
+
const cells = bars.map((bar, i) => {
|
|
249
|
+
const filled = Math.ceil((levels[i] ?? 0) / 8);
|
|
250
|
+
if (r === filled) return cell(numbers[i] ?? "");
|
|
251
|
+
if (r > filled) return NBSP.repeat(col);
|
|
252
|
+
const level = Math.min(8, (levels[i] ?? 0) - r * 8);
|
|
253
|
+
return `${bar.color}${(SPARK[level - 1] ?? "█").repeat(col)}${RST}`;
|
|
254
|
+
});
|
|
255
|
+
const tick = r < height ? (ticks[height - 1 - r] ?? "") : undefined;
|
|
256
|
+
if (r < height || cells.some((c) => !c.startsWith(NBSP))) rows.push(axis(tick) + row(cells));
|
|
257
|
+
}
|
|
258
|
+
rows.push(`${pad("0")}${FG_DIM}└${"─".repeat(bars.length * (col + 1) - 1)}${RST}`);
|
|
259
|
+
rows.push(axis(undefined) + row(bars.map((b) => cell(b.label))));
|
|
260
|
+
return rows;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Horizontal bar chart: label column, bar scaled to the largest value, value text, x axis. */
|
|
264
|
+
export function renderBars(bars: readonly Bar[], width: number): string[] {
|
|
265
|
+
const max = Math.max(...bars.map((b) => b.value), 0);
|
|
266
|
+
const labels = bars.map((b) => truncateToWidth(b.label, MAX_BAR_LABEL, "…"));
|
|
267
|
+
const labelWidth = Math.max(...labels.map((l) => visibleWidth(l)));
|
|
268
|
+
const numbers = bars.map((b) => axisNumber(b.value));
|
|
269
|
+
const barWidth = Math.max(
|
|
270
|
+
1,
|
|
271
|
+
Math.min(width, MAX_CHART) - labelWidth - Math.max(...numbers.map((n) => n.length)) - 2,
|
|
272
|
+
);
|
|
273
|
+
const rows = bars.map((bar, i) => {
|
|
274
|
+
const eighths = max > 0 ? Math.round((Math.max(0, bar.value) / max) * barWidth * 8) : 0;
|
|
275
|
+
const fill = "█".repeat(eighths >> 3) + (PARTIAL[eighths & 7] ?? "").trim();
|
|
276
|
+
const label = labels[i] ?? "";
|
|
277
|
+
const gap = NBSP.repeat(labelWidth - visibleWidth(label));
|
|
278
|
+
const axis = `${FG_DIM}│${RST}`;
|
|
279
|
+
return `${literal(label)}${gap}${axis}${bar.color}${fill}${RST} ${literal(numbers[i] ?? "")}`;
|
|
280
|
+
});
|
|
281
|
+
// Ticks at 0, half and max; a full bar fills `barWidth` cells, so max sits on the last one.
|
|
282
|
+
const at = [0, (barWidth - 1) >> 1, barWidth - 1];
|
|
283
|
+
const [rule, text] = xAxis(
|
|
284
|
+
["0", axisNumber(max / 2), axisNumber(max)],
|
|
285
|
+
(i) => at[i] ?? 0,
|
|
286
|
+
barWidth,
|
|
287
|
+
);
|
|
288
|
+
const indent = NBSP.repeat(labelWidth);
|
|
289
|
+
return [...rows, `${indent}${FG_DIM}└${rule}${RST}`, `${indent}${NBSP}${text}`];
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
type Part = { value: number; label: string; color?: string };
|
|
293
|
+
|
|
294
|
+
function parsePart(line: string): Part | undefined {
|
|
295
|
+
const match = STACKED.exec(line);
|
|
296
|
+
const value = Number(match?.[1]);
|
|
297
|
+
if (!match || !Number.isFinite(value) || value < 0) return undefined;
|
|
298
|
+
const { label = "", color } = attrs(match[2]);
|
|
299
|
+
return { value, label, color: color ? COLORS[color] : undefined };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Shares of one whole as a stacked 100% bar over a legend of value and percent.
|
|
304
|
+
* Each part has its own glyph as well as its color, so color is never the only
|
|
305
|
+
* signal. A part above zero keeps at least one cell.
|
|
306
|
+
*/
|
|
307
|
+
export function renderStacked(parts: readonly Part[], width: number): string[] {
|
|
308
|
+
const total = parts.reduce((sum, p) => sum + p.value, 0);
|
|
309
|
+
const colors = parts.map((p, i) => p.color ?? PART_COLORS[i % PART_COLORS.length] ?? FG_BLUE);
|
|
310
|
+
const glyphs = parts.map((_, i) => PART_GLYPHS[i % PART_GLYPHS.length] ?? "█");
|
|
311
|
+
const shown = parts.filter((p) => p.value > 0).length;
|
|
312
|
+
const spare = Math.max(0, Math.min(width, MAX_CHART) - shown);
|
|
313
|
+
// Cumulative rounding keeps the cells summing to the bar width.
|
|
314
|
+
let acc = 0;
|
|
315
|
+
let used = 0;
|
|
316
|
+
const bar = parts
|
|
317
|
+
.map((p, i) => {
|
|
318
|
+
if (p.value <= 0 || total <= 0) return "";
|
|
319
|
+
acc += p.value;
|
|
320
|
+
const end = Math.round((acc / total) * spare);
|
|
321
|
+
const cells = 1 + end - used;
|
|
322
|
+
used = end;
|
|
323
|
+
return `${colors[i]}${(glyphs[i] ?? "").repeat(cells)}${RST}`;
|
|
324
|
+
})
|
|
325
|
+
.join("");
|
|
326
|
+
const labels = parts.map((p) => truncateToWidth(p.label, MAX_BAR_LABEL, "…"));
|
|
327
|
+
const labelWidth = Math.max(...labels.map((l) => visibleWidth(l)));
|
|
328
|
+
const numbers = parts.map((p) => axisNumber(p.value));
|
|
329
|
+
const numberWidth = Math.max(...numbers.map((n) => n.length));
|
|
330
|
+
const legend = parts.map((p, i) => {
|
|
331
|
+
const label = labels[i] ?? "";
|
|
332
|
+
const number = numbers[i] ?? "";
|
|
333
|
+
const pct = total > 0 ? `${Math.round((p.value / total) * 100)}%` : "0%";
|
|
334
|
+
const gap = NBSP.repeat(labelWidth - visibleWidth(label) + 1 + numberWidth - number.length);
|
|
335
|
+
return `${colors[i]}●${RST}${NBSP}${literal(label)}${gap}${literal(number)}${NBSP}${FG_DIM}${literal(pct)}${RST}`;
|
|
336
|
+
});
|
|
337
|
+
return bar ? [bar, ...legend] : legend;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Backslash-escape Markdown punctuation so the text keeps its characters and width.
|
|
342
|
+
* Brackets and parens stay bare: Pi reads `\(`…`\)` and `\[`…`\]` as LaTeX delimiters.
|
|
343
|
+
*/
|
|
344
|
+
function literal(text: string): string {
|
|
345
|
+
return text.replace(/[!-'*-/:-@\\^_`{-~]/g, "\\$&");
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* One card: optional label, accent title, italic subtitle and Markdown body. A card
|
|
350
|
+
* with only a value and label is small; a subtitle or body makes it full width.
|
|
351
|
+
*/
|
|
352
|
+
type Card = { title: string; label: string; subtitle: string; color: string; body: string[] };
|
|
353
|
+
|
|
354
|
+
function parseCard(line: string): Card | undefined {
|
|
355
|
+
const match = CARD.exec(line);
|
|
356
|
+
if (!match) return undefined;
|
|
357
|
+
const { label = "", subtitle = "", color } = attrs(match[2]);
|
|
358
|
+
return { title: match[1] ?? "", label, subtitle, color: colorOf(color), body: [] };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const isFull = (card: Card) => card.subtitle !== "" || card.body.some((line) => line.trim());
|
|
362
|
+
|
|
363
|
+
/** Text rows of one card wrapped to `inner` columns; the body is rendered as Markdown. */
|
|
364
|
+
function cardLines({ title, label, subtitle, color, body }: Card, inner: number): string[] {
|
|
365
|
+
const wrap = (text: string, style = "") =>
|
|
366
|
+
text ? wrapTextWithAnsi(`${style}${text}${RST}`, inner) : [];
|
|
367
|
+
const head = [...wrap(label), ...wrap(title, `${BOLD}${color}`), ...wrap(subtitle, ITALIC)];
|
|
368
|
+
const text = inlineLines(body).join("\n").trim();
|
|
369
|
+
const rendered = text ? [...new Markdown(text, 0, 0, getMarkdownTheme()).render(inner)] : [];
|
|
370
|
+
while (rendered.length > 0 && !rendered.at(-1)?.trim()) rendered.pop();
|
|
371
|
+
return [...head, ...(head.length > 0 && rendered.length > 0 ? [""] : []), ...rendered];
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Dim rounded frame `width` columns wide, padded with blank rows to `height`. */
|
|
375
|
+
function box(lines: readonly string[], width: number, height: number): string[] {
|
|
376
|
+
const inner = width - 4;
|
|
377
|
+
const rule = "─".repeat(width - 2);
|
|
378
|
+
const row = (line: string) => {
|
|
379
|
+
const fitted = truncateToWidth(line, inner, "…");
|
|
380
|
+
const pad = " ".repeat(Math.max(0, inner - visibleWidth(fitted)));
|
|
381
|
+
// Escape the text, not the escape sequences between it.
|
|
382
|
+
const text = fitted.split(ESCAPE_SEQ).map((s, i) => (i % 2 ? s : literal(s)));
|
|
383
|
+
return `${FG_DIM}│${RST} ${text.join("")}${RST}${pad} ${FG_DIM}│${RST}`;
|
|
384
|
+
};
|
|
385
|
+
return [
|
|
386
|
+
`${FG_DIM}╭${rule}╮${RST}`,
|
|
387
|
+
...lines.map(row),
|
|
388
|
+
...Array.from({ length: height - lines.length }, () => row("")),
|
|
389
|
+
`${FG_DIM}╰${rule}╯${RST}`,
|
|
390
|
+
];
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Cards side by side, as many per row as fit `width`. */
|
|
394
|
+
function cardRow(cards: readonly Card[], width: number): string[] {
|
|
395
|
+
const perRow = Math.max(1, Math.min(cards.length, Math.floor((width + 1) / (MIN_CARD + 1))));
|
|
396
|
+
const cardWidth = Math.floor((width + 1) / perRow) - 1;
|
|
397
|
+
const rows: string[] = [];
|
|
398
|
+
for (let i = 0; i < cards.length; i += perRow) {
|
|
399
|
+
const texts = cards.slice(i, i + perRow).map((card) => cardLines(card, cardWidth - 4));
|
|
400
|
+
const height = Math.max(...texts.map((t) => t.length));
|
|
401
|
+
const boxes = texts.map((t) => box(t, cardWidth, height));
|
|
402
|
+
rows.push(...(boxes[0] ?? []).map((_, r) => boxes.map((b) => b[r]).join(" ")));
|
|
403
|
+
}
|
|
404
|
+
return rows;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Runs of small cards side by side; a full card spans the width on its own. */
|
|
408
|
+
export function renderCards(cards: readonly Card[], width: number): string[] {
|
|
409
|
+
const rows: string[] = [];
|
|
410
|
+
for (let i = 0; i < cards.length; ) {
|
|
411
|
+
let end = i + 1;
|
|
412
|
+
if (!isFull(cards[i] as Card)) while (end < cards.length && !isFull(cards[end] as Card)) end++;
|
|
413
|
+
rows.push(...cardRow(cards.slice(i, end), width));
|
|
414
|
+
i = end;
|
|
415
|
+
}
|
|
416
|
+
return rows;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export function renderDirectives(markdown: string, width: number): string {
|
|
420
|
+
// Cheap pre-check: most replies have no directive, link or path at all.
|
|
421
|
+
if (!/::(?:card|bar|stacked|image)|:[a-z]+\[|https?:\/\/|\w\//.test(markdown)) return markdown;
|
|
422
|
+
const out: string[] = [];
|
|
423
|
+
let fenced = false;
|
|
424
|
+
let cards: Card[] = [];
|
|
425
|
+
let bars: Bar[] = [];
|
|
426
|
+
let parts: Part[] = [];
|
|
427
|
+
// Blank lines keep each block a paragraph of its own.
|
|
428
|
+
const flush = () => {
|
|
429
|
+
if (cards.length > 0) out.push("", ...renderCards(cards, width), "");
|
|
430
|
+
// The first bar's direction= picks the layout for the whole chart.
|
|
431
|
+
const vertical = bars[0]?.vertical ? renderVerticalBars(bars, width) : undefined;
|
|
432
|
+
if (bars.length > 0) out.push("", ...(vertical ?? renderBars(bars, width)), "");
|
|
433
|
+
if (parts.length > 0) out.push("", ...renderStacked(parts, width), "");
|
|
434
|
+
cards = [];
|
|
435
|
+
bars = [];
|
|
436
|
+
parts = [];
|
|
437
|
+
};
|
|
438
|
+
for (const line of markdown.split("\n")) {
|
|
439
|
+
// Lines right after a card, up to a blank line or the next block directive, are
|
|
440
|
+
// its body; a fence in the body stays whole.
|
|
441
|
+
const last = cards.at(-1);
|
|
442
|
+
if (last && (fenced || (line.trim() && !/^::\w/.test(line)))) {
|
|
443
|
+
if (FENCE.test(line)) fenced = !fenced;
|
|
444
|
+
last.body.push(line);
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
if (FENCE.test(line)) fenced = !fenced;
|
|
448
|
+
const card = fenced || width < MIN_CARD ? undefined : parseCard(line);
|
|
449
|
+
if (card) {
|
|
450
|
+
if (bars.length > 0 || parts.length > 0) flush();
|
|
451
|
+
cards.push(card);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const bar = fenced || width < MIN_CARD ? undefined : parseBar(line);
|
|
455
|
+
if (bar) {
|
|
456
|
+
if (cards.length > 0 || parts.length > 0) flush();
|
|
457
|
+
bars.push(bar);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
const part = fenced || width < MIN_CARD ? undefined : parsePart(line);
|
|
461
|
+
if (part) {
|
|
462
|
+
if (cards.length > 0 || bars.length > 0) flush();
|
|
463
|
+
parts.push(part);
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
const image = fenced ? undefined : parseImage(line, attrs);
|
|
467
|
+
const block = image ? renderImage(image, width) : undefined;
|
|
468
|
+
if (block) {
|
|
469
|
+
flush();
|
|
470
|
+
out.push("", ...block, "");
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
flush();
|
|
474
|
+
out.push(fenced ? line : colorInline(line));
|
|
475
|
+
}
|
|
476
|
+
flush();
|
|
477
|
+
return out.join("\n");
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
export default function directivesExtension(pi: ExtensionAPI): void {
|
|
481
|
+
pi.registerMarkdownTransformer?.(
|
|
482
|
+
(markdown, { availableWidth }) =>
|
|
483
|
+
renderDirectives(
|
|
484
|
+
renderMathBlocks(renderMermaidBlocks(markdown, availableWidth), availableWidth),
|
|
485
|
+
availableWidth,
|
|
486
|
+
),
|
|
487
|
+
{ messageTypes: ["assistant"] },
|
|
488
|
+
);
|
|
489
|
+
}
|
package/src/image.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `::image[alt]{src="file:///abs/path.png" width=40}` — a local image in an
|
|
3
|
+
* assistant reply. Display only, like the other directives.
|
|
4
|
+
*
|
|
5
|
+
* Only `file://` URLs and absolute paths: a remote image is downloaded first by a
|
|
6
|
+
* visible tool call, so rendering never touches the network.
|
|
7
|
+
*/
|
|
8
|
+
import { basename } from "node:path";
|
|
9
|
+
import { FG_DIM, RST } from "@xynogen/pix-pretty/ansi";
|
|
10
|
+
import { getImageDimensions, Image } from "@xynogen/pix-pretty/tui";
|
|
11
|
+
import { readFileSync, statSync } from "@xynogen/pix-runtime/fs";
|
|
12
|
+
import { localFilePath } from "@xynogen/pix-runtime/paths";
|
|
13
|
+
|
|
14
|
+
const IMAGE = /^::image\[([^\]\n]*)\](?:\{([^}\n]*)\})?\s*$/;
|
|
15
|
+
// Read synchronously during render, so bound the bytes one directive can load.
|
|
16
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
17
|
+
const MIME: Record<string, string> = {
|
|
18
|
+
png: "image/png",
|
|
19
|
+
jpg: "image/jpeg",
|
|
20
|
+
jpeg: "image/jpeg",
|
|
21
|
+
gif: "image/gif",
|
|
22
|
+
webp: "image/webp",
|
|
23
|
+
};
|
|
24
|
+
const NBSP = "\u00a0";
|
|
25
|
+
|
|
26
|
+
export type ImageDirective = { alt: string; src: string; width?: number };
|
|
27
|
+
|
|
28
|
+
export function parseImage(
|
|
29
|
+
line: string,
|
|
30
|
+
attrs: (raw: string | undefined) => Record<string, string>,
|
|
31
|
+
): ImageDirective | undefined {
|
|
32
|
+
const match = IMAGE.exec(line);
|
|
33
|
+
if (!match) return undefined;
|
|
34
|
+
const { src, width } = attrs(match[2]);
|
|
35
|
+
if (!src) return undefined;
|
|
36
|
+
const cells = Number(width);
|
|
37
|
+
return { alt: match[1] ?? "", src, width: cells > 0 ? cells : undefined };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Pi may re-render a message many times; keep the encoded rows per file version and width.
|
|
41
|
+
// Insertion-ordered, so dropping the first key evicts the oldest entry.
|
|
42
|
+
const cache = new Map<string, string[]>();
|
|
43
|
+
const MAX_CACHE = 16;
|
|
44
|
+
|
|
45
|
+
/** A dim one-line reason the image is not shown. Markdown punctuation is escaped. */
|
|
46
|
+
function note(text: string): string[] {
|
|
47
|
+
return [`${FG_DIM}(image: ${text.replace(/[\\`*_]/g, "\\$&")})${RST}`];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Rows for one image: terminal image sequences when the terminal supports them, else
|
|
52
|
+
* Pi's text fallback. Blank rows are kept as NBSP so Markdown reserves the image height.
|
|
53
|
+
*/
|
|
54
|
+
export function renderImage(image: ImageDirective, width: number): string[] {
|
|
55
|
+
const path = localFilePath(image.src);
|
|
56
|
+
if (!path) return note(`${image.alt || image.src}: only file:// or absolute paths`);
|
|
57
|
+
const mime = MIME[path.split(".").pop()?.toLowerCase() ?? ""];
|
|
58
|
+
if (!mime) return note(`${image.alt || path}: unsupported type`);
|
|
59
|
+
let size: number;
|
|
60
|
+
let mtime: number;
|
|
61
|
+
try {
|
|
62
|
+
({ size, mtimeMs: mtime } = statSync(path));
|
|
63
|
+
} catch {
|
|
64
|
+
return note(`${image.alt || path}: not found`);
|
|
65
|
+
}
|
|
66
|
+
if (size > MAX_BYTES) return note(`${image.alt || path}: larger than 8 MB`);
|
|
67
|
+
const key = `${path}\0${mtime}\0${size}\0${width}\0${image.width ?? ""}`;
|
|
68
|
+
const hit = cache.get(key);
|
|
69
|
+
if (hit) return hit;
|
|
70
|
+
let data: string;
|
|
71
|
+
try {
|
|
72
|
+
data = readFileSync(path).toString("base64");
|
|
73
|
+
} catch {
|
|
74
|
+
return note(`${image.alt || path}: unreadable`);
|
|
75
|
+
}
|
|
76
|
+
const rows = renderImageRows(data, mime, width, {
|
|
77
|
+
maxWidthCells: Math.min(image.width ?? 60, width),
|
|
78
|
+
filename: basename(path),
|
|
79
|
+
});
|
|
80
|
+
cache.set(key, rows);
|
|
81
|
+
if (cache.size > MAX_CACHE) cache.delete(cache.keys().next().value ?? "");
|
|
82
|
+
return rows;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type RowOptions = { maxWidthCells: number; maxHeightCells?: number; filename?: string };
|
|
86
|
+
|
|
87
|
+
/** Image rows through Pi's `Image`; blank rows become NBSP so Markdown keeps the height. */
|
|
88
|
+
export function renderImageRows(
|
|
89
|
+
data: string,
|
|
90
|
+
mime: string,
|
|
91
|
+
width: number,
|
|
92
|
+
options: RowOptions,
|
|
93
|
+
): string[] {
|
|
94
|
+
const dims = getImageDimensions(data, mime) ?? undefined;
|
|
95
|
+
return new Image(data, mime, { fallbackColor: (s) => `${FG_DIM}${s}${RST}` }, options, dims)
|
|
96
|
+
.render(width)
|
|
97
|
+
.map((row) => row || NBSP);
|
|
98
|
+
}
|