@narumitw/pi-inline 0.0.0-stage → 0.1.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.
@@ -0,0 +1,103 @@
1
+ import type { Dirent } from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { posix, resolve } from "node:path";
4
+
5
+ const refreshIntervalMs = 5_000;
6
+
7
+ async function scanFiles(root: string, signal: AbortSignal): Promise<Set<string>> {
8
+ const paths = new Set<string>();
9
+ const directories = [""];
10
+ for (const directory of directories) {
11
+ if (signal.aborted) return paths;
12
+ let entries: Dirent[];
13
+ try {
14
+ entries = await readdir(resolve(root, directory), { withFileTypes: true });
15
+ } catch {
16
+ // A directory can disappear during a scan. Retry it in the next snapshot.
17
+ continue;
18
+ }
19
+ if (signal.aborted) return paths;
20
+ for (const entry of entries) {
21
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
22
+ const path = posix.join(directory, entry.name);
23
+ if (entry.isDirectory()) {
24
+ directories.push(path);
25
+ } else if (entry.isFile()) {
26
+ paths.add(path);
27
+ }
28
+ }
29
+ }
30
+ return paths;
31
+ }
32
+
33
+ interface FileMatch {
34
+ path?: string;
35
+ /** Markdown matches for an ambiguous bare filename, including the root file if present. */
36
+ sources?: readonly string[];
37
+ }
38
+
39
+ interface FileIndex {
40
+ find(target: string): FileMatch | undefined;
41
+ dispose(): void;
42
+ }
43
+
44
+ function samePaths(previous: Set<string>, next: Set<string>): boolean {
45
+ if (previous.size !== next.size) return false;
46
+ for (const path of next) {
47
+ if (!previous.has(path)) return false;
48
+ }
49
+ return true;
50
+ }
51
+
52
+ /** Indexes workspace files on first lookup and refreshes until disposed. */
53
+ export function createFileIndex(root: string, onChange: () => void): FileIndex {
54
+ const controller = new AbortController();
55
+ let paths = new Set<string>();
56
+ let names = new Map<string, string[]>();
57
+ let started = false;
58
+ let timer: ReturnType<typeof setTimeout> | undefined;
59
+
60
+ async function refresh(): Promise<void> {
61
+ const next = await scanFiles(root, controller.signal);
62
+ if (controller.signal.aborted) return;
63
+ timer = setTimeout(() => void refresh(), refreshIntervalMs).unref();
64
+ if (samePaths(paths, next)) return;
65
+
66
+ paths = next;
67
+ names = new Map();
68
+ for (const path of [...paths].sort()) {
69
+ const name = posix.basename(path);
70
+ const matches = names.get(name);
71
+ if (!matches) names.set(name, [path]);
72
+ else if (name === path) matches.unshift(path);
73
+ else matches.push(path);
74
+ }
75
+ onChange();
76
+ }
77
+
78
+ return {
79
+ find(target) {
80
+ const path = target.replace(/^\.\//, "");
81
+ if (controller.signal.aborted || !path || /[\\\p{Cc}]/u.test(path)) return undefined;
82
+ if (!started) {
83
+ started = true;
84
+ void refresh();
85
+ }
86
+ const note = `${path}.md`;
87
+ const exact = paths.has(path) ? path : paths.has(note) ? note : undefined;
88
+ if (target.includes("/")) return exact ? { path: exact } : undefined;
89
+
90
+ const literal = names.get(path);
91
+ const name = exact ?? (literal && (literal.length === 1 || /\.md$/i.test(path)) ? path : note);
92
+ const matches = names.get(name);
93
+ if (!matches) return undefined;
94
+ const primary = exact ?? (matches.length === 1 ? matches[0] : undefined);
95
+ if (matches.length > 1 && /\.md$/i.test(name)) return { path: primary, sources: matches };
96
+ return primary ? { path: primary } : undefined;
97
+ },
98
+ dispose() {
99
+ controller.abort();
100
+ clearTimeout(timer);
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,182 @@
1
+ import { posix, resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
4
+ import { Markdown, stripTerminalSequences, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { type PreviewExcerpt, renderPreviewFrame } from "./filelinks.js";
6
+ import { createFileIndex } from "./wikilink-index.js";
7
+
8
+ const cardInset = 6; // Two borders and two spaces on each side.
9
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: OSC 8 uses literal ESC and BEL bytes.
10
+ const osc8 = /\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g;
11
+
12
+ /** Preview metadata for a wikilink to one Markdown file. */
13
+ export interface WikiNote {
14
+ path: string;
15
+ }
16
+
17
+ /** Preview metadata for a bare filename that matches multiple Markdown files. */
18
+ interface WikiGroup {
19
+ filename: string;
20
+ sources: readonly string[];
21
+ }
22
+
23
+ /** The file or group to show when hovering over a wikilink chip. */
24
+ export type WikiPreview = WikiNote | WikiGroup;
25
+
26
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Match the OSC 8 group ID, not its click destination.
27
+ const groupLink = /\x1b\]8;id=(pi-inline-markup-[\w-]+);[^\x07\x1b]*/g;
28
+
29
+ /** Substitutes hover IDs for click URLs in a copy of the screen line. */
30
+ export function hoverLinkLine(line: string): string {
31
+ return line.replace(groupLink, "\x1b]8;;wiki:$1");
32
+ }
33
+
34
+ function displayPath(path: string): string {
35
+ return stripTerminalSequences(path).replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/gu, " ");
36
+ }
37
+
38
+ function renderWikiBody(excerpt: PreviewExcerpt, theme: Theme, width: number): string[] {
39
+ const hasFrontmatter = /^---[ \t]*\n/.test(excerpt.text);
40
+ const bodyText = hasFrontmatter ? excerpt.text.replace(/^---[ \t]*\n[\s\S]*?^---[ \t]*(?:\n|$)/m, "") : excerpt.text;
41
+ // Do not show frontmatter that runs past the read limit.
42
+ if (hasFrontmatter && bodyText === excerpt.text) return [];
43
+ const text = bodyText.replace(/^(?:[ \t]*\n)+/, "").trimEnd();
44
+ if (!text) return [];
45
+ const markdown = new Markdown(
46
+ text,
47
+ 0,
48
+ 0,
49
+ {
50
+ ...getMarkdownTheme(),
51
+ heading: (text) => theme.fg("text", text),
52
+ underline: (text) => text,
53
+ bold: (text) => theme.style(text, { bold: true }),
54
+ linkUrl: () => "", // Keep link text, but do not show URLs in the card.
55
+ highlightCode: undefined,
56
+ },
57
+ { color: (text) => theme.fg("text", text) },
58
+ { renderLatex: false },
59
+ );
60
+ const lines = markdown.render(width).map((line) => line.replace(osc8, "").trimEnd());
61
+ while (lines.length && isBlank(lines.at(-1) ?? "")) lines.pop();
62
+ return lines;
63
+ }
64
+
65
+ function isBlank(line: string): boolean {
66
+ return !stripTerminalSequences(line).trim();
67
+ }
68
+
69
+ function clipBody(lines: string[], clipped: boolean, theme: Theme, width: number, limit: number): string[] {
70
+ const body = lines.slice(0, limit);
71
+ if (clipped || lines.length > limit) {
72
+ while (body.length && isBlank(body.at(-1) ?? "")) body.pop();
73
+ const last = body.pop() ?? "";
74
+ body.push(truncateToWidth(last, width - 1, "") + theme.fg("muted", "…"));
75
+ }
76
+ return body;
77
+ }
78
+
79
+ /** Renders one Markdown note, omitting its YAML front matter. */
80
+ export function renderWikiPreview(
81
+ excerpt: PreviewExcerpt,
82
+ theme: Theme,
83
+ width: number,
84
+ height: number,
85
+ ): { width: number; lines: string[] } | undefined {
86
+ const bodyWidth = width - cardInset;
87
+ const rendered = renderWikiBody(excerpt, theme, bodyWidth);
88
+ if (!rendered.length) return undefined;
89
+
90
+ const caption = `${theme.fg("accent", "▎")} ${theme.fg("muted", excerpt.filename)}`;
91
+ const spacer = height >= 7 ? [""] : [];
92
+ const body = clipBody(rendered, excerpt.clipped, theme, bodyWidth, height - 3 - spacer.length);
93
+ return renderWikiCard([caption, ...spacer, ...body], theme, width);
94
+ }
95
+
96
+ /** Determines how many sources to read, reserving rows for paths and overflow. */
97
+ export function wikiGroupSourceLimit(total: number, height: number): number {
98
+ const slots = Math.min(3, total, Math.floor((height - 3) / 2));
99
+ return Math.max(0, slots === total ? slots : Math.min(slots, Math.floor((height - 4) / 2)));
100
+ }
101
+
102
+ /** Stacks brief excerpts in candidate order, with a count for sources not shown. */
103
+ export function renderWikiGroupPreview(
104
+ group: WikiGroup,
105
+ excerpts: readonly (PreviewExcerpt | undefined)[],
106
+ theme: Theme,
107
+ width: number,
108
+ height: number,
109
+ ): { width: number; lines: string[] } {
110
+ const { filename, sources } = group;
111
+ const count = excerpts.length;
112
+ const remaining = sources.length - count;
113
+ const content = [`${theme.fg("accent", "▎")} ${theme.fg("muted", displayPath(filename))}`];
114
+ const bodyWidth = width - cardInset - 2;
115
+ if (count > 0) {
116
+ const limit = Math.min(2, Math.floor((height - 3 - Number(remaining > 0)) / count) - 1);
117
+ for (const [index, excerpt] of excerpts.entries()) {
118
+ const path = displayPath(sources[index]);
119
+ content.push(theme.fg("accent", path.includes("/") ? path : `./${path}`));
120
+ const rendered = excerpt ? renderWikiBody(excerpt, theme, bodyWidth).filter((line) => !isBlank(line)) : [];
121
+ const body = rendered.length
122
+ ? clipBody(rendered, excerpt?.clipped ?? false, theme, bodyWidth, limit)
123
+ : [theme.fg("muted", "Preview unavailable")];
124
+ content.push(...body.map((line) => ` ${line}`));
125
+ }
126
+ }
127
+ if (remaining > 0) {
128
+ const footer =
129
+ count === 0 ? `${remaining} matching files` : `… ${remaining} more ${remaining === 1 ? "file" : "files"}`;
130
+ content.push(theme.fg("muted", footer));
131
+ }
132
+ return renderWikiCard(content, theme, width);
133
+ }
134
+
135
+ function renderWikiCard(content: string[], theme: Theme, width: number): { width: number; lines: string[] } {
136
+ const usedWidth = Math.max(...content.map(visibleWidth)) + cardInset;
137
+ const cardWidth = Math.min(width, Math.max(30, usedWidth));
138
+ return { width: cardWidth, lines: renderPreviewFrame(theme, content, cardWidth, 2, true) };
139
+ }
140
+
141
+ interface WikiBadge {
142
+ label: string;
143
+ href?: string;
144
+ groupId?: string;
145
+ }
146
+
147
+ /** Tracks wikilink targets and their previews while explicitly enabled in a session. */
148
+ export function createWikilinks(root: string, onChange: () => void) {
149
+ const previews = new Map<string, WikiPreview>();
150
+ const index = createFileIndex(root, () => {
151
+ previews.clear();
152
+ onChange();
153
+ });
154
+ return {
155
+ findPreview: (href: string) => previews.get(href),
156
+ resolve(body: string): WikiBadge | undefined {
157
+ const [name, alias] = body.split("|", 2);
158
+ const target = name.replace(/\\$/, "").split("#", 1)[0].trim();
159
+ if (!target) return undefined;
160
+ const { path, sources } = index.find(target) ?? {};
161
+ const filename = sources ? posix.basename(sources[0]) : undefined;
162
+ const displayTarget = path ?? filename;
163
+ const label = alias?.trim() || (displayTarget ? posix.basename(displayTarget, ".md") : target);
164
+ const absolutePath = path ? resolve(root, path) : undefined;
165
+ const href = absolutePath ? pathToFileURL(absolutePath).href : undefined;
166
+ if (sources && filename) {
167
+ const groupId = `pi-inline-markup-${Buffer.from(filename).toString("base64url")}`;
168
+ const key = `wiki:${groupId}`;
169
+ if (!previews.has(key)) previews.set(key, { filename, sources });
170
+ return { label, href, groupId };
171
+ }
172
+ if (href && absolutePath && /\.md$/i.test(absolutePath) && !previews.has(href)) {
173
+ previews.set(href, { path: absolutePath });
174
+ }
175
+ return { label, href };
176
+ },
177
+ dispose() {
178
+ index.dispose();
179
+ previews.clear();
180
+ },
181
+ };
182
+ }