@xynogen/pix-display 0.4.4 → 0.6.0

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-display",
3
- "version": "0.4.4",
3
+ "version": "0.6.0",
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,8 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
- "@xynogen/pix-pretty": "^3.1.0",
42
- "@xynogen/pix-runtime": "^0.22.4"
41
+ "@xynogen/pix-pretty": "^3.3.0",
42
+ "@xynogen/pix-runtime": "^0.24.0"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@mathjax/src": "4.1.3",
@@ -1,11 +1,21 @@
1
+ import { RST } from "@xynogen/pix-pretty/ansi";
1
2
  import {
2
3
  AssistantMessageComponent,
3
4
  type Theme,
4
5
  truncateToWidth,
5
6
  visibleWidth,
6
7
  } from "@xynogen/pix-pretty/tui";
8
+ import { gutterWidth, lineGutter } from "@xynogen/pix-pretty/utils";
7
9
  import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
8
10
  import { wrapMethod } from "@xynogen/pix-runtime/patch";
11
+ import {
12
+ COPY_BUTTON,
13
+ type CodeFrame,
14
+ FOLD_ARROW,
15
+ forgetFrames,
16
+ isFolded,
17
+ rememberFrames,
18
+ } from "./code-frame.ts";
9
19
 
10
20
  const OPENING_FENCE_RE = /^```([^`]*)$/;
11
21
  const CLOSING_FENCE_RE = /^```\s*$/;
@@ -67,12 +77,23 @@ function fenceLabel(line: string): string | undefined {
67
77
  return info.split(/\s+/, 1)[0] || DEFAULT_LABEL;
68
78
  }
69
79
 
70
- function topRule(width: number, language: string, theme: CodeFrameTheme): string {
71
- const available = Math.max(1, width - 4);
80
+ function topRule(
81
+ width: number,
82
+ language: string,
83
+ theme: CodeFrameTheme,
84
+ lines: number,
85
+ folded: boolean,
86
+ ): string {
87
+ const meta = folded ? theme.fg("dim", `· ${lines} lines `) : "";
88
+ const available = Math.max(1, width - 4 - COPY_BUTTON.length - visibleWidth(meta));
72
89
  const displayLanguage = truncateToWidth(language, available, "…");
73
90
  const label = theme.bold(theme.fg("accent", ` ${displayLanguage} `));
74
- const ruleWidth = Math.max(0, width - visibleWidth(label) - 2);
75
- return `${theme.fg("borderMuted", "──")}${label}${theme.fg("borderMuted", "─".repeat(ruleWidth))}`;
91
+ const ruleWidth = Math.max(
92
+ 0,
93
+ width - FOLD_ARROW - visibleWidth(label) - visibleWidth(meta) - COPY_BUTTON.length,
94
+ );
95
+ const arrow = theme.fg("accent", folded ? "▸" : "▾");
96
+ return `${arrow}${label}${meta}${theme.fg("borderMuted", "─".repeat(ruleWidth))}${theme.fg("dim", COPY_BUTTON)}`;
76
97
  }
77
98
 
78
99
  function bottomRule(width: number, theme: CodeFrameTheme): string {
@@ -80,10 +101,9 @@ function bottomRule(width: number, theme: CodeFrameTheme): string {
80
101
  }
81
102
 
82
103
  function bodyLine(line: string, width: number, layoutIndent: number): string {
83
- const content = truncateToWidth(stripLayoutWhitespace(line, layoutIndent), width, "…");
84
- // Keep every code row free of frame glyphs and layout padding. Selection must
85
- // copy only source text, including meaningful relative indentation in Python.
86
- return content;
104
+ // Code column only; the caller prepends the same numbered gutter as the
105
+ // file-content renderer.
106
+ return truncateToWidth(stripLayoutWhitespace(line, layoutIndent), width, "…");
87
107
  }
88
108
 
89
109
  /**
@@ -94,6 +114,7 @@ export function renderCodeFences(
94
114
  lines: readonly string[],
95
115
  width: number,
96
116
  theme: CodeFrameTheme,
117
+ frames: CodeFrame[] = [],
97
118
  ): readonly string[] {
98
119
  if (width < 12) return lines;
99
120
 
@@ -110,22 +131,31 @@ export function renderCodeFences(
110
131
 
111
132
  const frameWidth = width;
112
133
  const body = out.slice(start + 1, end);
134
+ const numberWidth = Math.max(3, String(body.length).length);
135
+ const codeWidth = Math.max(1, width - gutterWidth(numberWidth));
113
136
  const bodyIndents = body
114
137
  .map((line) => plainText(line))
115
138
  .filter((line) => line.trim().length > 0)
116
139
  .map((line) => leadingSpaces(line));
117
140
  const bodyIndent = bodyIndents.length > 0 ? Math.min(...bodyIndents) : 0;
118
- const framed: string[] = [];
119
-
120
- framed.push(`${oscSequences(out[start] ?? "")}${topRule(frameWidth, language, theme)}`);
121
- for (let index = start + 1; index < end; index++) {
122
- framed.push(
123
- `${oscSequences(out[index] ?? "")}${bodyLine(out[index] ?? "", width, bodyIndent)}`,
124
- );
141
+ const source = body
142
+ .map((line) => plainText(stripLayoutWhitespace(line, bodyIndent)))
143
+ .join("\n");
144
+ const isFoldedBlock = isFolded(source);
145
+ const framed: string[] = [
146
+ `${oscSequences(out[start] ?? "")}${topRule(frameWidth, language, theme, body.length, isFoldedBlock)}`,
147
+ ];
148
+ if (!isFoldedBlock) {
149
+ for (let index = start + 1; index < end; index++) {
150
+ framed.push(
151
+ `${oscSequences(out[index] ?? "")}${lineGutter(index - start, numberWidth)}${bodyLine(out[index] ?? "", codeWidth, bodyIndent)}${RST}`,
152
+ );
153
+ }
154
+ framed.push(`${oscSequences(out[end] ?? "")}${bottomRule(frameWidth, theme)}`);
125
155
  }
126
- framed.push(`${oscSequences(out[end] ?? "")}${bottomRule(frameWidth, theme)}`);
127
156
 
128
157
  out.splice(start, end - start + 1, ...framed);
158
+ frames.push({ row: start, text: source });
129
159
  start += framed.length - 1;
130
160
  }
131
161
  return out;
@@ -148,6 +178,7 @@ function patchAssistantRenderer(): void {
148
178
  (native) =>
149
179
  function invalidateCodeFrames(this: object): void {
150
180
  cache.delete(this);
181
+ forgetFrames(this);
151
182
  native.call(this);
152
183
  },
153
184
  );
@@ -168,7 +199,9 @@ function patchAssistantRenderer(): void {
168
199
  ) {
169
200
  return previous.output;
170
201
  }
171
- const output = renderCodeFences(lines, width, activeTheme);
202
+ const frames: CodeFrame[] = [];
203
+ const output = renderCodeFences(lines, width, activeTheme, frames);
204
+ rememberFrames(this, frames);
172
205
  cache.set(this, { width, theme: activeTheme, input: [...lines], output });
173
206
  return output;
174
207
  },
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Interactions on a code frame's header row: the arrow at the left folds the block,
3
+ * the `copy` button at the right end writes its source to the system clipboard.
4
+ *
5
+ * Rows come from the same render that drew the frames, so a hit test cannot drift
6
+ * from what the user sees. Display only: the session keeps the raw text.
7
+ */
8
+ import { showTransientMessage, type TransientErrorUI } from "@xynogen/pix-pretty/transient-error";
9
+ import { getErrorMessage } from "@xynogen/pix-runtime/errors";
10
+ import { copyToClipboard } from "@xynogen/pix-runtime/host";
11
+
12
+ /** Right-aligned header label. Its width is the click target at the row's end. */
13
+ export const COPY_BUTTON = " copy ";
14
+ /** Columns taken by the fold arrow at the row's start. */
15
+ export const FOLD_ARROW = 1;
16
+
17
+ /** One framed block: its header row in the rendered lines, and the source it holds. */
18
+ export type CodeFrame = { row: number; text: string };
19
+
20
+ type Click = { type: string; button: string; x: number; y: number; width: number };
21
+ type Owner = { invalidate?(): void };
22
+
23
+ // Keyed by the message component that rendered the frames; rebuilt on every render.
24
+ const frames = new WeakMap<object, readonly CodeFrame[]>();
25
+ // Blocks the user folded, by source text, so the state survives re-renders.
26
+ const folded = new Set<string>();
27
+
28
+ let ui: TransientErrorUI | undefined;
29
+ let write = copyToClipboard;
30
+
31
+ /** Remember the UI for feedback and the clipboard writer (tests pass a fake). */
32
+ export function initCodeFrames(target: TransientErrorUI, copy = copyToClipboard): void {
33
+ ui = target;
34
+ write = copy;
35
+ }
36
+
37
+ export function isFolded(text: string): boolean {
38
+ return folded.has(text);
39
+ }
40
+
41
+ /** Pi's expand key opens every block again. Returns whether anything was folded. */
42
+ export function setCodeFramesExpanded(expanded: boolean): boolean {
43
+ if (!expanded || folded.size === 0) return false;
44
+ folded.clear();
45
+ return true;
46
+ }
47
+
48
+ export function rememberFrames(owner: object, list: readonly CodeFrame[]): void {
49
+ frames.set(owner, list);
50
+ }
51
+
52
+ export function forgetFrames(owner: object): void {
53
+ frames.delete(owner);
54
+ }
55
+
56
+ function notify(message: string, level: "info" | "warning"): void {
57
+ if (ui) showTransientMessage(ui, message, level);
58
+ }
59
+
60
+ function copyFrame(frame: CodeFrame): void {
61
+ const lines = frame.text.split("\n").length;
62
+ void write(frame.text).then(
63
+ () => notify(`copied ${lines} lines`, "info"),
64
+ (error: unknown) => notify(`copy failed: ${getErrorMessage(error)}`, "warning"),
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Left click on a frame's header: the arrow folds the block, the trailing `copy`
70
+ * button writes it. Returns true when the click was ours.
71
+ */
72
+ export function frameClickAt(owner: Owner, event: Click): boolean {
73
+ if (event.type !== "click" || event.button !== "left") return false;
74
+ const frame = frames.get(owner)?.find((candidate) => candidate.row === event.y);
75
+ if (!frame) return false;
76
+ if (event.x < FOLD_ARROW) {
77
+ if (folded.has(frame.text)) folded.delete(frame.text);
78
+ else folded.add(frame.text);
79
+ owner.invalidate?.();
80
+ return true;
81
+ }
82
+ if (event.x < event.width - COPY_BUTTON.length) return false;
83
+ copyFrame(frame);
84
+ return true;
85
+ }
package/src/directives.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  wrapTextWithAnsi,
24
24
  } from "@xynogen/pix-pretty/tui";
25
25
  import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
26
+ import { foldsOpen, renderFolds } from "./fold.ts";
26
27
  import { parseImage, renderImage } from "./image.ts";
27
28
  import { renderMathBlocks } from "./math.ts";
28
29
  import { renderMermaidBlocks } from "./mermaid.ts";
@@ -106,14 +107,14 @@ export function sparkline(raw: string): string | undefined {
106
107
  }
107
108
 
108
109
  /**
109
- * Label on a tinted background, no padding, so the tint ends at the text and does not
110
- * bleed into the spaces around it. With `href`, the whole badge is an OSC 8 link (BEL
111
- * terminated: a `\` would start a Markdown escape). `\x1b[39m`/`\x1b[49m` reset only the
112
- * colors, so bold or italic around the badge survives.
110
+ * Plain badges have no padding. Links include a clickable space on either side, so the
111
+ * tinted hit area extends beyond the letters. OSC 8 uses BEL termination (a `\` would
112
+ * start a Markdown escape). `\x1b[39m`/`\x1b[49m` reset only the colors, so bold or
113
+ * italic around the badge survives.
113
114
  */
114
115
  function badge(text: string, color: string, href?: string): string {
115
116
  const key = COLORS[color] ? color : "blue";
116
- const linked = href ? `\x1b]8;;${literal(href)}\x07${text}\x1b]8;;\x07` : text;
117
+ const linked = href ? `\x1b]8;;${literal(href)}\x07\u00a0${text}\u00a0\x1b]8;;\x07` : text;
117
118
  return `${BADGE_BG[key]}${COLORS[key]}${linked}\x1b[39m\x1b[49m`;
118
119
  }
119
120
 
@@ -478,9 +479,10 @@ export function renderDirectives(markdown: string, width: number): string {
478
479
  return out.join("\n");
479
480
  }
480
481
 
481
- /** The display pipeline for assistant Markdown: Mermaid, math, then directives. */
482
+ /** The display pipeline for assistant Markdown: folds, Mermaid, math, then directives. */
482
483
  export function renderDisplayMarkdown(markdown: string, width: number): string {
483
- return renderDirectives(renderMathBlocks(renderMermaidBlocks(markdown, width), width), width);
484
+ const unfolded = renderFolds(markdown, foldsOpen());
485
+ return renderDirectives(renderMathBlocks(renderMermaidBlocks(unfolded, width), width), width);
484
486
  }
485
487
 
486
488
  export default function directivesExtension(pi: ExtensionAPI): void {
package/src/fold.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * `::fold[Title]` … `::fold`: the model marks a section to show folded.
3
+ *
4
+ * Folded, the section is one summary line. A left click on that line toggles the one
5
+ * fold, like a thinking block. Pi's expand key (ctrl+o) sets every fold, like tool
6
+ * output: Pi calls `setExpanded` on each chat component that has one, so assistant
7
+ * messages get one here. Display only: the session keeps the raw text.
8
+ */
9
+ import { FG_BLUE, FG_DIM, RST } from "@xynogen/pix-pretty/ansi";
10
+ import {
11
+ AssistantMessageComponent,
12
+ stripTerminalSequences,
13
+ type Theme,
14
+ } from "@xynogen/pix-pretty/tui";
15
+ import { wrapMethod } from "@xynogen/pix-runtime/patch";
16
+ import { frameClickAt, setCodeFramesExpanded } from "./code-frame.ts";
17
+
18
+ const FOLD = /^::fold(?:\[([^\]\n]*)\])?\s*$/;
19
+ const FENCE = /^\s*(```|~~~)/;
20
+ const HEADER = /^\s*[▸▾] /;
21
+
22
+ type Fold = { title: string; lines: string[] };
23
+ type FoldUI = { getToolsExpanded(): boolean; theme: Pick<Theme, "fg"> };
24
+
25
+ let open = false;
26
+ let accent = (text: string) => `${FG_BLUE}${text}\x1b[39m`;
27
+ // Folds the user clicked, by title and body: they keep their state across re-renders.
28
+ const clicked = new Map<string, boolean>();
29
+
30
+ const keyOf = (fold: Fold) => `${fold.title}\n${fold.lines.join("\n")}`;
31
+
32
+ /** Lines outside folds as strings, each fold as one item. A marker in a code fence stays text. */
33
+ function parse(markdown: string): (string | Fold)[] {
34
+ const items: (string | Fold)[] = [];
35
+ let fenced = false;
36
+ let fold: Fold | undefined;
37
+ for (const line of markdown.split("\n")) {
38
+ const marker = fenced ? undefined : FOLD.exec(line);
39
+ if (marker) {
40
+ if (fold) items.push(fold);
41
+ fold = fold ? undefined : { title: marker[1]?.trim() ?? "", lines: [] };
42
+ continue;
43
+ }
44
+ if (FENCE.test(line)) fenced = !fenced;
45
+ if (fold) fold.lines.push(line);
46
+ else items.push(line);
47
+ }
48
+ // An unclosed fold (still streaming) runs to the end.
49
+ if (fold) items.push(fold);
50
+ return items;
51
+ }
52
+
53
+ /** Collapse each `::fold` section to one line, or show it whole under a header when open. */
54
+ export function renderFolds(markdown: string, expanded: boolean): string {
55
+ if (!markdown.includes("::fold")) return markdown;
56
+ return parse(markdown)
57
+ .flatMap((item) => {
58
+ if (typeof item === "string") return [item];
59
+ const title = accent(item.title || "Folded");
60
+ if (clicked.get(keyOf(item)) ?? expanded)
61
+ return ["", `${accent("▾")} ${title}`, "", ...item.lines, ""];
62
+ const meta = `${FG_DIM}· ${item.lines.length} lines (click or ctrl+o to expand)${RST}`;
63
+ return ["", `${accent("▸")} ${title} ${meta}`, ""];
64
+ })
65
+ .join("\n");
66
+ }
67
+
68
+ export function foldsOpen(): boolean {
69
+ return open;
70
+ }
71
+
72
+ const isHeader = (line: string | undefined) => HEADER.test(stripTerminalSequences(line ?? ""));
73
+
74
+ /** Each fold's header row with its key: headers appear in the order of the message's folds. */
75
+ export function foldHeaders(
76
+ lines: readonly string[],
77
+ texts: readonly string[],
78
+ ): { row: number; key: string }[] {
79
+ const keys = texts.flatMap((text) =>
80
+ parse(text).flatMap((item) => (typeof item === "string" ? [] : [keyOf(item)])),
81
+ );
82
+ const rows = lines.flatMap((line, row) => (isHeader(line) ? [row] : []));
83
+ return rows.flatMap((row, i) => {
84
+ const key = keys[i];
85
+ return key === undefined ? [] : [{ row, key }];
86
+ });
87
+ }
88
+
89
+ /**
90
+ * Row after an open fold's body. The rows after the fold are the same open or closed, so
91
+ * render it closed once: its header ends at the first blank row, and what follows is that tail.
92
+ */
93
+ function openEnd(
94
+ component: AssistantMessageComponent,
95
+ width: number,
96
+ header: { row: number; key: string },
97
+ openRows: number,
98
+ ): number {
99
+ const previous = clicked.get(header.key);
100
+ clicked.set(header.key, false);
101
+ component.invalidate();
102
+ const closed = component.render(width);
103
+ if (previous === undefined) clicked.delete(header.key);
104
+ else clicked.set(header.key, previous);
105
+ component.invalidate();
106
+ let end = header.row;
107
+ while (end < closed.length && stripTerminalSequences(closed[end] ?? "").trim()) end++;
108
+ return openRows - (closed.length - end);
109
+ }
110
+
111
+ /** The fold under row `y`: its header, or anywhere in an open fold's body. */
112
+ function foldAt(
113
+ component: AssistantMessageComponent,
114
+ width: number,
115
+ y: number,
116
+ ): string | undefined {
117
+ const lines = component.render(width);
118
+ const above = foldHeaders(lines, textsOf(component)).filter(({ row }) => row <= y);
119
+ const nearest = above.at(-1);
120
+ if (!nearest) return undefined;
121
+ if (nearest.row === y) return nearest.key;
122
+ if (!(clicked.get(nearest.key) ?? open)) return undefined;
123
+ return y < openEnd(component, width, nearest, lines.length) ? nearest.key : undefined;
124
+ }
125
+
126
+ function textsOf(component: object): string[] {
127
+ const content: unknown = Reflect.get(component, "lastMessage")?.content;
128
+ if (!Array.isArray(content)) return [];
129
+ return content
130
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
131
+ .map((block) => String(block.text).trim());
132
+ }
133
+
134
+ /** Start state and colors from the session's UI. */
135
+ export function initFolds(ui: FoldUI): void {
136
+ open = ui.getToolsExpanded();
137
+ accent = (text) => ui.theme.fg("accent", text);
138
+ }
139
+
140
+ /** Click a header, or an open fold's body, to toggle it; the expand key sets all folds. */
141
+ export function followFoldInput(): void {
142
+ Object.defineProperty(AssistantMessageComponent.prototype, "setExpanded", {
143
+ configurable: true,
144
+ writable: true,
145
+ value(this: AssistantMessageComponent, expanded: boolean): void {
146
+ open = expanded;
147
+ if (setCodeFramesExpanded(expanded)) this.invalidate();
148
+ if (textsOf(this).some((text) => text.includes("::fold"))) this.invalidate();
149
+ },
150
+ });
151
+ wrapMethod(
152
+ AssistantMessageComponent.prototype,
153
+ "handleMouse",
154
+ (native) =>
155
+ function foldOnClick(this: AssistantMessageComponent, event) {
156
+ const result = native.call(this, event);
157
+ if (result || event.type !== "click" || event.button !== "left") return result;
158
+ const key = foldAt(this, event.width, event.y);
159
+ if (key === undefined) return frameClickAt(this, event) ? { handled: true } : undefined;
160
+ clicked.set(key, !(clicked.get(key) ?? open));
161
+ this.invalidate();
162
+ return { handled: true };
163
+ },
164
+ );
165
+ }
package/src/index.ts CHANGED
@@ -8,7 +8,9 @@
8
8
  * @xynogen/pix-pretty/chips Inline chips (tag format, editor, sent messages)
9
9
  * thinking.ts Leaked reasoning tag → native thinking content blocks
10
10
  * code-blocks.ts Framed, syntax-highlighted code fences in LLM output
11
+ * code-copy.ts The `copy` button on a code frame's header row
11
12
  * directives.ts `::card[…]`, charts and inline directives in LLM output
13
+ * fold.ts `::fold[Title]` … `::fold` sections, opened by click or Pi's expand key
12
14
  * tables.ts Themed Markdown tables with column alignment
13
15
  */
14
16
 
@@ -17,7 +19,9 @@ import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
17
19
  import { once } from "@xynogen/pix-runtime/once";
18
20
 
19
21
  import codeBlocksExtension from "./code-blocks.ts";
22
+ import { initCodeFrames } from "./code-frame.ts";
20
23
  import directivesExtension from "./directives.ts";
24
+ import { followFoldInput, initFolds } from "./fold.ts";
21
25
  import { hasDisplayMath, offerMathInstall, startMath } from "./math.ts";
22
26
  import { hasMermaid, offerMermaidInstall, startMermaid } from "./mermaid.ts";
23
27
  import tablesExtension from "./tables.ts";
@@ -32,6 +36,12 @@ export default async function pixDisplayExtension(pi: ExtensionAPI): Promise<voi
32
36
  tablesExtension(pi);
33
37
  directivesExtension(pi);
34
38
  workingExtension(pi);
39
+ followFoldInput();
40
+ pi.on("session_start", (_event, ctx) => {
41
+ if (ctx.mode !== "tui") return;
42
+ initFolds(ctx.ui);
43
+ initCodeFrames(ctx.ui);
44
+ });
35
45
  pi.on("agent_end", (event, ctx) => {
36
46
  if (ctx.mode !== "tui") return;
37
47
  const fail = (what: string) => (err: unknown) =>
package/src/tables.ts CHANGED
@@ -1,10 +1,21 @@
1
- import { Markdown, sliceByColumn, type Theme, visibleWidth } from "@xynogen/pix-pretty/tui";
1
+ import {
2
+ Markdown,
3
+ sliceByColumn,
4
+ stripTerminalSequences,
5
+ type Theme,
6
+ visibleWidth,
7
+ } from "@xynogen/pix-pretty/tui";
2
8
  import type { ExtensionAPI } from "@xynogen/pix-runtime/host";
3
9
  import { wrapMethod } from "@xynogen/pix-runtime/patch";
4
10
  import { themeAfterSessionStart } from "./code-blocks.ts";
5
11
 
6
12
  type TableTheme = Pick<Theme, "bold" | "fg">;
7
13
  type Align = "left" | "center" | "right" | null;
14
+ type Cell = { text: string; tokens?: readonly unknown[] };
15
+ type TableToken = { raw?: string; align?: readonly Align[]; header: Cell[]; rows: Cell[][] };
16
+ type Sort = { col: number; desc: boolean };
17
+ type HeaderHit = { numeric: boolean[]; lines: Set<string> };
18
+ type Click = { type: string; button: string; x: number; y: number; width: number };
8
19
 
9
20
  const CORNERS: Record<string, string> = { "┌": "╭", "┐": "╮", "└": "╰", "┘": "╯" };
10
21
  const HEAVY: Record<string, string> = { "├": "┝", "─": "━", "┼": "┿", "┤": "┥" };
@@ -15,6 +26,128 @@ const TRAILING_PAD_RE = /(?: |\x1b\[[0-9;]*m)+$/;
15
26
  const STYLE_RESET = "\x1b[22;23;24;25;27;28;29;39;49m";
16
27
 
17
28
  let activeTheme: TableTheme | undefined;
29
+ // Sort per table source, so it survives re-renders.
30
+ const sorts = new Map<string, Sort>();
31
+ // Per Markdown: each table's source → its clickable header rows (plain text).
32
+ const headers = new WeakMap<object, Map<string, HeaderHit>>();
33
+ // Column borders in any table row: plain, styled, top border and header rule.
34
+ const SEPARATORS = new Set("│┌┐╭╮┬├┤┼┝┥┿");
35
+ const segmenter = new Intl.Segmenter();
36
+
37
+ // A whole cell that is a number: `3,781`, `-2.5`, `84%`, `12 ms`. Not a version like `0.8.0`.
38
+ const NUMBER = /^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\s*(?:%|[a-zA-Z]{1,3})?$/;
39
+
40
+ const plainCell = (text: string) => text.replace(/[*_`~]/g, "").trim();
41
+
42
+ export function cellNumber(text: string): number | undefined {
43
+ const plain = plainCell(text);
44
+ return NUMBER.test(plain) ? Number.parseFloat(plain.replaceAll(",", "")) : undefined;
45
+ }
46
+
47
+ export function isNumericColumn(rows: readonly (readonly Cell[])[], col: number): boolean {
48
+ const cells = rows.map((row) => plainCell(row[col]?.text ?? "")).filter(Boolean);
49
+ return cells.length > 0 && cells.every((cell) => cellNumber(cell) !== undefined);
50
+ }
51
+
52
+ /** Rows sorted by one column; empty cells stay last. Numbers by value, text A-Z with natural digits. */
53
+ export function sortRows<T extends Cell>(
54
+ rows: readonly T[][],
55
+ col: number,
56
+ desc: boolean,
57
+ numeric: boolean,
58
+ ): T[][] {
59
+ const key = (row: readonly T[]) => plainCell(row[col]?.text ?? "");
60
+ const compare = (a: string, b: string) =>
61
+ numeric
62
+ ? (cellNumber(a) ?? 0) - (cellNumber(b) ?? 0)
63
+ : a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
64
+ return [...rows].sort((rowA, rowB) => {
65
+ const a = key(rowA);
66
+ const b = key(rowB);
67
+ if (!a || !b) return a ? -1 : b ? 1 : 0;
68
+ return desc ? compare(b, a) : compare(a, b);
69
+ });
70
+ }
71
+
72
+ /**
73
+ * Column under terminal column `x` of a plain table row, from the row's own borders: a
74
+ * column spans its left border up to the next one, so a click on a border still counts.
75
+ */
76
+ export function columnAt(plain: string, x: number): number | undefined {
77
+ const borders: number[] = [];
78
+ let at = 0;
79
+ for (const { segment } of segmenter.segment(plain)) {
80
+ if (SEPARATORS.has(segment)) borders.push(at);
81
+ at += visibleWidth(segment);
82
+ }
83
+ const last = borders.length - 1;
84
+ if (last < 1 || x < (borders[0] ?? 0) || x > (borders[last] ?? 0)) return undefined;
85
+ const col = borders.findIndex((edge) => x < edge) - 1;
86
+ return col < 0 ? last - 1 : col;
87
+ }
88
+
89
+ /** A copy of the table token with rows sorted and an arrow on the sorted header. */
90
+ function sortedToken(token: TableToken, sort: Sort): TableToken {
91
+ const arrow = { type: "text", raw: "", text: sort.desc ? " ▼" : " ▲" };
92
+ const header = token.header.map((cell, i) =>
93
+ i === sort.col ? { ...cell, tokens: [...(cell.tokens ?? []), arrow] } : cell,
94
+ );
95
+ const numeric = isNumericColumn(token.rows, sort.col);
96
+ return { ...token, header, rows: sortRows(token.rows, sort.col, sort.desc, numeric) };
97
+ }
98
+
99
+ /** Remember a table's header block (top border, header rows, rule) so a click there sorts it. */
100
+ function rememberHeader(owner: object, token: TableToken, lines: readonly string[]): void {
101
+ const plain = lines.map((line) => stripTerminalSequences(line).trim());
102
+ // Pi falls back to raw Markdown when the table cannot fit: nothing to click.
103
+ if (!token.raw || !/^[┌╭]/.test(plain[0] ?? "")) return;
104
+ const rule = plain.findIndex((line) => /^[├┝]/.test(line));
105
+ const hits = headers.get(owner) ?? new Map<string, HeaderHit>();
106
+ headers.set(owner, hits);
107
+ hits.set(token.raw, {
108
+ numeric: token.header.map((_, i) => isNumericColumn(token.rows, i)),
109
+ lines: new Set(plain.slice(0, rule < 0 ? 2 : rule + 1)),
110
+ });
111
+ }
112
+
113
+ /** The table a clicked row belongs to. Two tables can share a row (same widths): the k-th match wins. */
114
+ function tableAt(
115
+ owner: Markdown,
116
+ lines: readonly string[],
117
+ y: number,
118
+ ): { raw: string; hit: HeaderHit } | undefined {
119
+ const hits = headers.get(owner);
120
+ const row = lines[y];
121
+ if (!hits || row === undefined) return undefined;
122
+ const plain = stripTerminalSequences(row).trim();
123
+ // Current tables in text order; a streamed table leaves stale partial sources behind.
124
+ const tokens: unknown = Reflect.get(owner, "cachedTokens")?.deref()?.tokens;
125
+ const order = Array.isArray(tokens)
126
+ ? tokens.filter((t) => t?.type === "table").map((t) => String(t.raw))
127
+ : [...hits.keys()];
128
+ const matches = order.filter((raw) => hits.get(raw)?.lines.has(plain));
129
+ const before = lines.slice(0, y).filter((line) => stripTerminalSequences(line).trim() === plain);
130
+ const raw = matches[before.length];
131
+ const hit = raw === undefined ? undefined : hits.get(raw);
132
+ return raw !== undefined && hit ? { raw, hit } : undefined;
133
+ }
134
+
135
+ /** Left click anywhere in a header block: sort by that column; again on it reverses. */
136
+ function sortOnClick(this: Markdown, event: Click): { handled: true } | undefined {
137
+ if (event.type !== "click" || event.button !== "left") return undefined;
138
+ const lines = this.render(event.width);
139
+ const table = tableAt(this, lines, event.y);
140
+ if (!table) return undefined;
141
+ // The untrimmed row keeps the left padding, so `x` maps straight to its borders.
142
+ const col = columnAt(stripTerminalSequences(lines[event.y] ?? ""), event.x);
143
+ if (col === undefined) return undefined;
144
+ const prev = sorts.get(table.raw);
145
+ // Numbers start large to small, text A-Z.
146
+ const desc = prev?.col === col ? !prev.desc : (table.hit.numeric[col] ?? false);
147
+ sorts.set(table.raw, { col, desc });
148
+ this.invalidate();
149
+ return { handled: true };
150
+ }
18
151
 
19
152
  function alignCell(cell: string, width: number, align: Align | undefined): string {
20
153
  const tail = cell.match(TRAILING_PAD_RE)?.[0] ?? "";
@@ -69,15 +202,20 @@ function patchTableRenderer(): void {
69
202
  Markdown.prototype,
70
203
  "renderTable",
71
204
  (native) =>
72
- function renderStyledTable(
73
- this: unknown,
74
- token: { align?: readonly Align[] },
75
- ...rest: unknown[]
76
- ) {
77
- const lines: string[] = native.call(this, token, ...rest);
78
- return activeTheme ? styleTable(lines, token.align ?? [], activeTheme) : lines;
205
+ function renderStyledTable(this: object, token: TableToken, ...rest: unknown[]) {
206
+ const sort = token.raw ? sorts.get(token.raw) : undefined;
207
+ const lines: string[] = native.call(this, sort ? sortedToken(token, sort) : token, ...rest);
208
+ const styled = activeTheme ? styleTable(lines, token.align ?? [], activeTheme) : lines;
209
+ rememberHeader(this, token, styled);
210
+ return styled;
79
211
  },
80
212
  );
213
+ // Markdown has no mouse handler of its own; Pi routes clicks to any component with one.
214
+ Object.defineProperty(Markdown.prototype, "handleMouse", {
215
+ configurable: true,
216
+ writable: true,
217
+ value: sortOnClick,
218
+ });
81
219
  }
82
220
 
83
221
  export default function tablesExtension(pi: ExtensionAPI): void {