@xynogen/pix-display 0.4.3 → 0.5.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.3",
3
+ "version": "0.5.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",
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,164 @@
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
+
17
+ const FOLD = /^::fold(?:\[([^\]\n]*)\])?\s*$/;
18
+ const FENCE = /^\s*(```|~~~)/;
19
+ const HEADER = /^\s*[▸▾] /;
20
+
21
+ type Fold = { title: string; lines: string[] };
22
+ type FoldUI = { getToolsExpanded(): boolean; theme: Pick<Theme, "fg"> };
23
+
24
+ let open = false;
25
+ let accent = (text: string) => `${FG_BLUE}${text}\x1b[39m`;
26
+ // Folds the user clicked, by title and body: they keep their state across re-renders.
27
+ const clicked = new Map<string, boolean>();
28
+
29
+ const keyOf = (fold: Fold) => `${fold.title}\n${fold.lines.join("\n")}`;
30
+
31
+ /** Lines outside folds as strings, each fold as one item. A marker in a code fence stays text. */
32
+ function parse(markdown: string): (string | Fold)[] {
33
+ const items: (string | Fold)[] = [];
34
+ let fenced = false;
35
+ let fold: Fold | undefined;
36
+ for (const line of markdown.split("\n")) {
37
+ const marker = fenced ? undefined : FOLD.exec(line);
38
+ if (marker) {
39
+ if (fold) items.push(fold);
40
+ fold = fold ? undefined : { title: marker[1]?.trim() ?? "", lines: [] };
41
+ continue;
42
+ }
43
+ if (FENCE.test(line)) fenced = !fenced;
44
+ if (fold) fold.lines.push(line);
45
+ else items.push(line);
46
+ }
47
+ // An unclosed fold (still streaming) runs to the end.
48
+ if (fold) items.push(fold);
49
+ return items;
50
+ }
51
+
52
+ /** Collapse each `::fold` section to one line, or show it whole under a header when open. */
53
+ export function renderFolds(markdown: string, expanded: boolean): string {
54
+ if (!markdown.includes("::fold")) return markdown;
55
+ return parse(markdown)
56
+ .flatMap((item) => {
57
+ if (typeof item === "string") return [item];
58
+ const title = accent(item.title || "Folded");
59
+ if (clicked.get(keyOf(item)) ?? expanded)
60
+ return ["", `${accent("▾")} ${title}`, "", ...item.lines, ""];
61
+ const meta = `${FG_DIM}· ${item.lines.length} lines (click or ctrl+o to expand)${RST}`;
62
+ return ["", `${accent("▸")} ${title} ${meta}`, ""];
63
+ })
64
+ .join("\n");
65
+ }
66
+
67
+ export function foldsOpen(): boolean {
68
+ return open;
69
+ }
70
+
71
+ const isHeader = (line: string | undefined) => HEADER.test(stripTerminalSequences(line ?? ""));
72
+
73
+ /** Each fold's header row with its key: headers appear in the order of the message's folds. */
74
+ export function foldHeaders(
75
+ lines: readonly string[],
76
+ texts: readonly string[],
77
+ ): { row: number; key: string }[] {
78
+ const keys = texts.flatMap((text) =>
79
+ parse(text).flatMap((item) => (typeof item === "string" ? [] : [keyOf(item)])),
80
+ );
81
+ const rows = lines.flatMap((line, row) => (isHeader(line) ? [row] : []));
82
+ return rows.flatMap((row, i) => {
83
+ const key = keys[i];
84
+ return key === undefined ? [] : [{ row, key }];
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Row after an open fold's body. The rows after the fold are the same open or closed, so
90
+ * render it closed once: its header ends at the first blank row, and what follows is that tail.
91
+ */
92
+ function openEnd(
93
+ component: AssistantMessageComponent,
94
+ width: number,
95
+ header: { row: number; key: string },
96
+ openRows: number,
97
+ ): number {
98
+ const previous = clicked.get(header.key);
99
+ clicked.set(header.key, false);
100
+ component.invalidate();
101
+ const closed = component.render(width);
102
+ if (previous === undefined) clicked.delete(header.key);
103
+ else clicked.set(header.key, previous);
104
+ component.invalidate();
105
+ let end = header.row;
106
+ while (end < closed.length && stripTerminalSequences(closed[end] ?? "").trim()) end++;
107
+ return openRows - (closed.length - end);
108
+ }
109
+
110
+ /** The fold under row `y`: its header, or anywhere in an open fold's body. */
111
+ function foldAt(
112
+ component: AssistantMessageComponent,
113
+ width: number,
114
+ y: number,
115
+ ): string | undefined {
116
+ const lines = component.render(width);
117
+ const above = foldHeaders(lines, textsOf(component)).filter(({ row }) => row <= y);
118
+ const nearest = above.at(-1);
119
+ if (!nearest) return undefined;
120
+ if (nearest.row === y) return nearest.key;
121
+ if (!(clicked.get(nearest.key) ?? open)) return undefined;
122
+ return y < openEnd(component, width, nearest, lines.length) ? nearest.key : undefined;
123
+ }
124
+
125
+ function textsOf(component: object): string[] {
126
+ const content: unknown = Reflect.get(component, "lastMessage")?.content;
127
+ if (!Array.isArray(content)) return [];
128
+ return content
129
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
130
+ .map((block) => String(block.text).trim());
131
+ }
132
+
133
+ /** Start state and colors from the session's UI. */
134
+ export function initFolds(ui: FoldUI): void {
135
+ open = ui.getToolsExpanded();
136
+ accent = (text) => ui.theme.fg("accent", text);
137
+ }
138
+
139
+ /** Click a header, or an open fold's body, to toggle it; the expand key sets all folds. */
140
+ export function followFoldInput(): void {
141
+ Object.defineProperty(AssistantMessageComponent.prototype, "setExpanded", {
142
+ configurable: true,
143
+ writable: true,
144
+ value(this: AssistantMessageComponent, expanded: boolean): void {
145
+ open = expanded;
146
+ clicked.clear();
147
+ if (textsOf(this).some((text) => text.includes("::fold"))) this.invalidate();
148
+ },
149
+ });
150
+ wrapMethod(
151
+ AssistantMessageComponent.prototype,
152
+ "handleMouse",
153
+ (native) =>
154
+ function foldOnClick(this: AssistantMessageComponent, event) {
155
+ const result = native.call(this, event);
156
+ if (result || event.type !== "click" || event.button !== "left") return result;
157
+ const key = foldAt(this, event.width, event.y);
158
+ if (key === undefined) return undefined;
159
+ clicked.set(key, !(clicked.get(key) ?? open));
160
+ this.invalidate();
161
+ return { handled: true };
162
+ },
163
+ );
164
+ }
package/src/image.ts CHANGED
@@ -7,9 +7,14 @@
7
7
  */
8
8
  import { basename } from "node:path";
9
9
  import { FG_DIM, RST } from "@xynogen/pix-pretty/ansi";
10
- import { getCapabilities, getImageDimensions, Image } from "@xynogen/pix-pretty/tui";
10
+ import {
11
+ getCapabilities,
12
+ getCellDimensions,
13
+ getImageDimensions,
14
+ Image,
15
+ } from "@xynogen/pix-pretty/tui";
11
16
  import { readFileSync, statSync } from "@xynogen/pix-runtime/fs";
12
- import { localFilePath } from "@xynogen/pix-runtime/paths";
17
+ import { localFilePath, requireFrom } from "@xynogen/pix-runtime/paths";
13
18
 
14
19
  const IMAGE = /^::image\[([^\]\n]*)\](?:\{([^}\n]*)\})?\s*$/;
15
20
  // Read synchronously during render, so bound the bytes one directive can load.
@@ -83,6 +88,7 @@ export function renderImage(image: ImageDirective, width: number): string[] {
83
88
  }
84
89
 
85
90
  type RowOptions = { maxWidthCells: number; maxHeightCells?: number; filename?: string };
91
+ type Dimensions = { widthPx: number; heightPx: number };
86
92
 
87
93
  /** Image rows through Pi's `Image`; blank rows become NBSP so Markdown keeps the height. */
88
94
  export function renderImageRows(
@@ -91,12 +97,84 @@ export function renderImageRows(
91
97
  width: number,
92
98
  options: RowOptions,
93
99
  ): string[] {
94
- const dims = getImageDimensions(data, mime) ?? undefined;
95
- return new Image(data, mime, { fallbackColor: (s) => `${FG_DIM}${s}${RST}` }, options, dims)
100
+ const source = getImageDimensions(data, mime) ?? undefined;
101
+ const png =
102
+ source && getCapabilities().images ? fitToCells(data, source, width, options) : undefined;
103
+ const [shown, type] = png ? [png, "image/png"] : [data, mime];
104
+ const dims = getImageDimensions(shown, type) ?? undefined;
105
+ return new Image(shown, type, { fallbackColor: (s) => `${FG_DIM}${s}${RST}` }, options, dims)
96
106
  .render(width)
97
107
  .map((row) => row || NBSP);
98
108
  }
99
109
 
110
+ type PhotonImage = { get_bytes(): Uint8Array; free(): void };
111
+ type Photon = {
112
+ PhotonImage: { new_from_byteslice(bytes: Uint8Array): PhotonImage };
113
+ resize(image: PhotonImage, width: number, height: number, filter: number): PhotonImage;
114
+ };
115
+ // photon's SamplingFilter.Lanczos3, the filter Pi's own image resize uses.
116
+ const LANCZOS3 = 5;
117
+ let photon: Photon | null | undefined;
118
+
119
+ /** Pi's photon-node (a Pi dependency, not ours): the running CLI's copy, else the peer install's. */
120
+ function loadPhoton(): Photon | null {
121
+ if (photon !== undefined) return photon;
122
+ photon = null;
123
+ const hosts = [
124
+ () => process.argv[1] ?? "",
125
+ // ESM-only package (no `require` export): resolve it the ESM way.
126
+ () => import.meta.resolve("@earendil-works/pi-coding-agent"),
127
+ ];
128
+ for (const host of hosts) {
129
+ try {
130
+ // SAFETY: photon-node is CommonJS with this API; Pi's utils/photon.ts makes the same calls.
131
+ photon = requireFrom(host())("@silvia-odwyer/photon-node") as Photon;
132
+ break;
133
+ } catch {
134
+ // Not resolvable from this host: try the next one.
135
+ }
136
+ }
137
+ return photon;
138
+ }
139
+
140
+ /**
141
+ * The image as a PNG no larger than the pixels its cells show, or undefined when it
142
+ * already fits or cannot be resized. A terminal shows no more than that anyway, and
143
+ * herdr drops a Kitty image whose decoded RGBA exceeds its transfer budget (~30 MB).
144
+ * The box mirrors Pi's `Image`: `width - 2` columns, square-ish rows by default. One
145
+ * extra cell each way absorbs callers' rounding, so a raster sized to its cells stays.
146
+ * ponytail: synchronous (render is sync) and no EXIF rotation; a huge photo costs ~1 s
147
+ * once per cache entry. Upgrade path: Pi's async `resizeImage` plus a transcript redraw.
148
+ */
149
+ function fitToCells(data: string, source: Dimensions, width: number, options: RowOptions) {
150
+ const cell = getCellDimensions();
151
+ const cols = Math.max(1, Math.min(width - 2, options.maxWidthCells));
152
+ const rows = options.maxHeightCells ?? Math.ceil((cols * cell.widthPx) / cell.heightPx);
153
+ if (source.widthPx <= (cols + 1) * cell.widthPx && source.heightPx <= (rows + 1) * cell.heightPx)
154
+ return undefined;
155
+ const scale = Math.min(
156
+ (cols * cell.widthPx) / source.widthPx,
157
+ (rows * cell.heightPx) / source.heightPx,
158
+ );
159
+ const lib = loadPhoton();
160
+ if (!lib) return undefined;
161
+ let image: PhotonImage | undefined;
162
+ let out: PhotonImage | undefined;
163
+ try {
164
+ image = lib.PhotonImage.new_from_byteslice(Buffer.from(data, "base64"));
165
+ const w = Math.max(1, Math.round(source.widthPx * scale));
166
+ const h = Math.max(1, Math.round(source.heightPx * scale));
167
+ out = lib.resize(image, w, h, LANCZOS3);
168
+ return Buffer.from(out.get_bytes()).toString("base64");
169
+ } catch {
170
+ // Undecodable source: show it unchanged and let Pi's Image fall back.
171
+ return undefined;
172
+ } finally {
173
+ out?.free();
174
+ image?.free();
175
+ }
176
+ }
177
+
100
178
  // Space between an image and its frame: columns left/right, rows above/below.
101
179
  const PAD_X = 2;
102
180
  const PAD_Y = 1;
package/src/index.ts CHANGED
@@ -9,6 +9,7 @@
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
11
  * directives.ts `::card[…]`, charts and inline directives in LLM output
12
+ * fold.ts `::fold[Title]` … `::fold` sections, opened by click or Pi's expand key
12
13
  * tables.ts Themed Markdown tables with column alignment
13
14
  */
14
15
 
@@ -18,6 +19,7 @@ import { once } from "@xynogen/pix-runtime/once";
18
19
 
19
20
  import codeBlocksExtension from "./code-blocks.ts";
20
21
  import directivesExtension from "./directives.ts";
22
+ import { followFoldInput, initFolds } from "./fold.ts";
21
23
  import { hasDisplayMath, offerMathInstall, startMath } from "./math.ts";
22
24
  import { hasMermaid, offerMermaidInstall, startMermaid } from "./mermaid.ts";
23
25
  import tablesExtension from "./tables.ts";
@@ -32,6 +34,10 @@ export default async function pixDisplayExtension(pi: ExtensionAPI): Promise<voi
32
34
  tablesExtension(pi);
33
35
  directivesExtension(pi);
34
36
  workingExtension(pi);
37
+ followFoldInput();
38
+ pi.on("session_start", (_event, ctx) => {
39
+ if (ctx.mode === "tui") initFolds(ctx.ui);
40
+ });
35
41
  pi.on("agent_end", (event, ctx) => {
36
42
  if (ctx.mode !== "tui") return;
37
43
  const fail = (what: string) => (err: unknown) =>
package/src/math.ts CHANGED
@@ -194,8 +194,9 @@ export function renderMath(tex: string, width: number): string[] | undefined {
194
194
  const rows = Math.max(1, Math.min(MAX_ROWS, Math.round(math.heightEx * ROWS_PER_EX)));
195
195
  const cols = Math.ceil((rows * cell.heightPx * math.widthEx) / math.heightEx / cell.widthPx);
196
196
  if (cols > width) return undefined;
197
- // Rasterise at 2× the displayed height so the glyphs stay sharp.
198
- const png = engine.rasterise(math.svg, rows * cell.heightPx * 2);
197
+ // Rasterise at the displayed size: cell pixels are the terminal's own resolution,
198
+ // and renderImageRows would shrink anything larger back down.
199
+ const png = engine.rasterise(math.svg, rows * cell.heightPx);
199
200
  const image = renderImageRows(Buffer.from(png).toString("base64"), "image/png", width, {
200
201
  maxWidthCells: cols,
201
202
  maxHeightCells: rows,
package/src/mermaid.ts CHANGED
@@ -280,10 +280,11 @@ export function renderMermaidImage(source: string, width: number): string[] | un
280
280
  const shrink = Math.min(1, (width - FRAME_COLS) / cols, MAX_ROWS / rows);
281
281
  cols = Math.max(1, Math.floor(cols * shrink));
282
282
  rows = Math.max(1, Math.floor(rows * shrink));
283
- // Rasterise at 2× the displayed height so text and lines stay sharp.
283
+ // Rasterise at the displayed size: cell pixels are the terminal's own resolution,
284
+ // and renderImageRows would shrink anything larger back down.
284
285
  let png: Uint8Array;
285
286
  try {
286
- png = engine.rasterise(svg, rows * cell.heightPx * 2);
287
+ png = engine.rasterise(svg, rows * cell.heightPx);
287
288
  } catch {
288
289
  return undefined;
289
290
  }
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 {