Skip to content

Commit ef85097

Browse files
committed
fix(repl): show web link destinations in rendered output
Refs #1536
1 parent dca6ac8 commit ef85097

8 files changed

Lines changed: 248 additions & 81 deletions

File tree

‎examples/repl-bench/fixtures/repl-sidekick-markdown.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ Show the Markdown fixture.
4141
**entry strong** plain
4242
*entry slant* plain
4343
`entry code` plain
44-
[entry fixture label](https://example.test/entry-target) plain
44+
[entry fixture label](https://e.test/e) plain
4545
Entry prose keeps going long enough to wrap inside the wide centre pane, so its **entry wrapped strong** run lands after a measured break.
4646
4747
1. entry first step

‎examples/repl-bench/journeys/repl-markdown.test.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88

99
<ReplBench.EntryOutput entry={1} as="entry" />
1010
<AssertEquals actual={entry.status} expected="completed" />
11-
<AssertStringIncludes actual={entry.text} expected="[entry fixture label](https://example.test/entry-target) plain" />
11+
<AssertStringIncludes actual={entry.text} expected="[entry fixture label](https://e.test/e) plain" />
1212
<AssertStringIncludes actual={entry.text} expected="**entry strong** plain" />
1313
<AssertStringIncludes actual={entry.text} expected="```text" />
1414

1515
<ReplBench.WaitForText text="Entry fixture heading" bold={true} />
1616
<ReplBench.WaitForText text="entry strong plain" bold={true} />
17-
<ReplBench.WaitForText text="entry fixture label plain" />
17+
<ReplBench.WaitForText text="entry fixture label" />
18+
<ReplBench.WaitForText text="(https://e.test/e)" />
1819
<ReplBench.WaitForText text="3. [x] entry task step" />
1920
<ReplBench.WaitForText text=" entry fence indent" />
2021
<ReplBench.WaitForText text="Entry fixture end." />
@@ -23,7 +24,8 @@
2324
<ReplBench.Scroll delta={-30} at={receipt} />
2425
<ReplBench.WaitForText text="Sidekick fixture heading" bold={true} />
2526
<ReplBench.WaitForText text="sidekick strong plain" bold={true} />
26-
<ReplBench.WaitForText text="sidekick fixture label plain" />
27+
<ReplBench.WaitForText text="sidekick fixture label" />
28+
<ReplBench.WaitForText text="(https://example.test/sidekick-target)" />
2729
<ReplBench.WaitForText text="• sidekick first item" />
2830
<ReplBench.WaitForText text="• [ ] sidekick task item" />
2931
<ReplBench.WaitForText text="Sidekick fixture end." />

‎packages/cli/src/repl/application.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4415,6 +4415,8 @@ function sidekickComposedRows(
44154415
` ${reading.agent}: `,
44164416
item.text,
44174417
styleOf("output"),
4418+
"",
4419+
{ showDestinations: true },
44184420
),
44194421
);
44204422
metadata();
@@ -4480,23 +4482,27 @@ function chatBody(
44804482
gutter = "",
44814483
marked: {
44824484
readonly mark?: ReplOriginMark;
4485+
readonly showDestinations?: boolean;
44834486
readonly action?: { readonly [name: string]: Json };
44844487
} = {},
44854488
): ReplChatComposed {
4486-
const lines = (formatted?.lines(body, style.role) ?? markdownLines(body, style.role)).map(
4487-
(one, at) => {
4488-
const before = at === 0 ? `${gutter}${lead}` : gutter;
4489-
const runs = tokenRuns([{ text: before, token: style.role }, ...one.runs]);
4490-
return Object.freeze({ text: `${before}${one.text}`, runs });
4491-
},
4492-
);
4489+
const showDestinations = marked.showDestinations === true;
4490+
const lines = (
4491+
formatted?.lines(body, style.role, showDestinations) ??
4492+
markdownLines(body, style.role, showDestinations)
4493+
).map((one, at) => {
4494+
const before = at === 0 ? `${gutter}${lead}` : gutter;
4495+
const runs = tokenRuns([{ text: before, token: style.role }, ...one.runs]);
4496+
return Object.freeze({ text: `${before}${one.text}`, runs });
4497+
});
44934498
return Object.freeze({
44944499
kind: "text" as const,
44954500
key,
44964501
text: lines.map((one) => one.text).join("\n"),
44974502
style,
44984503
lines: Object.freeze(lines),
4499-
...marked,
4504+
mark: marked.mark,
4505+
action: marked.action,
45004506
});
45014507
}
45024508

@@ -13187,6 +13193,7 @@ function workspaceChatComposed(
1318713193
`${CONTROL_ROOM}${MARKER_ROOM}`,
1318813194
{
1318913195
mark: SIDEKICK_MARK,
13196+
showDestinations: true,
1319013197
action:
1319113198
item.request !== undefined && saved !== undefined
1319213199
? inspectionAction("exchange", saved.key)

‎packages/cli/src/repl/markdown.ts‎

Lines changed: 96 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,9 @@
1111
* the body into a syntax tree whose every node is a span of the body. A line is
1212
* drawn from those spans: delimiters are left out, headings, emphasis, list
1313
* markers, link labels and code become styled runs, and everything else is the
14-
* text as written. So no character appears that the body did not hold, and a
15-
* delimiter that never closed, raw HTML, a component-like tag, an image or a
16-
* table is drawn as the text it is. A link shows its label; its target is never
17-
* drawn, opened or written to the terminal as anything. A reference link is a
18-
* link only where the body defines its label.
14+
* text as written. Raw HTML, component-like tags, images, tables and delimiters
15+
* that never closed stay literal. Output and settled replies can also show the
16+
* destination of a validated web link as ordinary text.
1917
*
2018
* Fenced code keeps every payload line as written, indentation and blank lines
2119
* included. Controls are made inert before the grammar reads the text, so a
@@ -46,13 +44,17 @@ export interface ReplMarkdownLine {
4644
* A frame formats the same bodies as the frame before it unless one of them
4745
* changed: a Draft keystroke changes none, and a streamed delta changes one.
4846
* This answers a body asked for before with the lines it was formatted into,
49-
* compared by exact text and role, and keeps only what the owner's latest
47+
* compared by exact text, role and destination display, and keeps only what the owner's latest
5048
* preparation asked for — so a body that changed, closed or went out of view is
5149
* dropped at the next {@link settle}, and nothing outlives the owner.
5250
*/
5351
export interface ReplMarkdownStore {
5452
/** This body's lines, formatted once while the owner keeps asking for it. */
55-
lines(source: string, role: ReplPresentationRole): readonly ReplMarkdownLine[];
53+
lines(
54+
source: string,
55+
role: ReplPresentationRole,
56+
showDestinations?: boolean,
57+
): readonly ReplMarkdownLine[];
5658
/** Keep only the bodies asked for since the last settle. */
5759
settle(): void;
5860
}
@@ -61,9 +63,10 @@ export function createMarkdownStore(): ReplMarkdownStore {
6163
let held = new Map<string, readonly ReplMarkdownLine[]>();
6264
let asked = new Map<string, readonly ReplMarkdownLine[]>();
6365
return {
64-
lines(source, role) {
65-
const key = `${role}\u0000${source}`;
66-
const found = asked.get(key) ?? held.get(key) ?? markdownLines(source, role);
66+
lines(source, role, showDestinations = false) {
67+
const key = `${role}\u0000${showDestinations}\u0000${source}`;
68+
const found =
69+
asked.get(key) ?? held.get(key) ?? markdownLines(source, role, showDestinations);
6770
asked.set(key, found);
6871
return found;
6972
},
@@ -82,10 +85,11 @@ export function createMarkdownStore(): ReplMarkdownStore {
8285
export function markdownLines(
8386
source: string,
8487
role: ReplPresentationRole,
88+
showDestinations = false,
8589
): readonly ReplMarkdownLine[] {
8690
const text = inertCommandText(source);
8791
const top = parseMarkdown(text).topNode;
88-
const reading: Reading = { text, role, defined: definedLabels(text, top) };
92+
const reading: Reading = { text, role, showDestinations, defined: definedLinks(text, top) };
8993
return Object.freeze(
9094
blockLines(reading, blocksOf(reading, childrenOf(top)), [], true, 0, text.length).map(
9195
(parts) => {
@@ -157,8 +161,8 @@ type SyntaxNode = ReturnType<typeof MARKDOWN.parse>["topNode"];
157161
interface Reading {
158162
readonly text: string;
159163
readonly role: ReplPresentationRole;
160-
/** Every reference label the body defines, normalized. */
161-
readonly defined: ReadonlySet<string>;
164+
readonly showDestinations: boolean;
165+
readonly defined: ReadonlyMap<string, SyntaxNode | null>;
162166
}
163167

164168
interface Part {
@@ -189,6 +193,7 @@ type Block =
189193
readonly base: ReplPresentationRole;
190194
readonly styles: readonly Style[];
191195
readonly hidden: readonly Span[];
196+
readonly destinations: ReadonlyMap<number, { readonly from: number; readonly url: string }>;
192197
}
193198
| { readonly kind: "code"; readonly from: number; readonly to: number; readonly fenced: boolean }
194199
| {
@@ -237,16 +242,19 @@ function normalized(label: string): string {
237242
return label.slice(1, -1).trim().replace(/\s+/g, " ").toLowerCase();
238243
}
239244

240-
function definedLabels(text: string, top: SyntaxNode): ReadonlySet<string> {
241-
const defined = new Set<string>();
245+
function definedLinks(text: string, top: SyntaxNode): ReadonlyMap<string, SyntaxNode | null> {
246+
const defined = new Map<string, SyntaxNode | null>();
242247
if (!text.includes("]:")) {
243248
return defined;
244249
}
245250
top.cursor().iterate((ref) => {
246251
if (ref.name === "LinkReference") {
247252
const label = ref.node.getChild("LinkLabel");
248253
if (label !== null) {
249-
defined.add(normalized(text.slice(label.from, label.to)));
254+
const key = normalized(text.slice(label.from, label.to));
255+
if (!defined.has(key)) {
256+
defined.set(key, ref.node.getChild("URL"));
257+
}
250258
}
251259
return false;
252260
}
@@ -284,6 +292,7 @@ function inline(reading: Reading, node: SyntaxNode, base: ReplPresentationRole):
284292
const { text } = reading;
285293
const hidden: Span[] = [];
286294
const styles: Style[] = [];
295+
const destinations = new Map<number, { from: number; url: string }>();
287296
const style = (span: Span, role: ReplPresentationRole, depth: number) => {
288297
styles.push({ from: span.from, to: span.to, role, depth });
289298
};
@@ -303,13 +312,36 @@ function inline(reading: Reading, node: SyntaxNode, base: ReplPresentationRole):
303312
}
304313
walk(childrenOf(one), depth + 1);
305314
break;
306-
case "Link":
307-
if (linked(reading, one)) {
308-
style(one, "markdown-link", depth + 1);
309-
hidden.push(...one.getChildren("URL"));
315+
case "Link": {
316+
const marks = one.getChildren("LinkMark");
317+
const close = marks[1];
318+
if (close === undefined || close.from === one.from + 1) {
319+
break;
320+
}
321+
const urls = one.getChildren("URL");
322+
const reference =
323+
urls.length === 0 || (reading.showDestinations && marks.length === 2)
324+
? reading.defined.get(referenceKey(text, one, close))
325+
: undefined;
326+
if (urls.length === 0 && reference === undefined) {
327+
break;
328+
}
329+
style(one, "markdown-link", depth + 1);
330+
const target = marks.length > 2 ? urls.find((url) => url.from >= close.to) : reference;
331+
const url = reading.showDestinations ? webDestination(text, target) : undefined;
332+
if (url === undefined) {
333+
hidden.push(...urls);
310334
walk(childrenOf(one), depth + 1);
335+
} else {
336+
hidden.push({ from: close.from, to: one.to });
337+
walk(
338+
childrenOf(one).filter((child) => child.from < close.from),
339+
depth + 1,
340+
);
341+
destinations.set(close.from, { from: one.from + 1, url });
311342
}
312343
break;
344+
}
313345
case "Autolink":
314346
style(one, "markdown-link", depth + 1);
315347
hidden.push(...one.getChildren("LinkMark"));
@@ -355,30 +387,42 @@ function inline(reading: Reading, node: SyntaxNode, base: ReplPresentationRole):
355387
// A setext heading ends where its underline line begins.
356388
const underline = node.name.startsWith("Setext") ? node.getChild("HeaderMark") : null;
357389
const until = underline === null ? node.to : lineStart(text, underline.from);
358-
return { kind: "inline", from: node.from, to: node.to, until, base, styles, hidden };
390+
return {
391+
kind: "inline",
392+
from: node.from,
393+
to: node.to,
394+
until,
395+
base,
396+
styles,
397+
hidden,
398+
destinations,
399+
};
359400
}
360401

361-
/**
362-
* Whether a link is drawn as one: an inline link with a label, or a reference
363-
* whose label this body defines. Anything else is the text it was written as.
364-
* Inside a drawn link, the target, its title and the reference label are
365-
* hidden with the brackets.
366-
*/
367-
function linked(reading: Reading, link: SyntaxNode): boolean {
368-
const marks = link.getChildren("LinkMark");
369-
const close = marks[1];
370-
if (close === undefined || close.from === link.from + 1) {
371-
return false;
372-
}
373-
if (link.getChild("URL") !== null) {
374-
return true;
375-
}
402+
function referenceKey(text: string, link: SyntaxNode, close: SyntaxNode): string {
376403
const label = link.getChild("LinkLabel");
377-
const written =
404+
return normalized(
378405
label === null || label.to - label.from === 2
379-
? reading.text.slice(link.from, close.to)
380-
: reading.text.slice(label.from, label.to);
381-
return reading.defined.has(normalized(written));
406+
? text.slice(link.from, close.to)
407+
: text.slice(label.from, label.to),
408+
);
409+
}
410+
411+
function webDestination(text: string, target: SyntaxNode | null | undefined): string | undefined {
412+
if (target == null) {
413+
return undefined;
414+
}
415+
const raw = text.slice(target.from, target.to).replace(/^<(.*)>$/s, "$1");
416+
const url = raw.replace(/\\([!-/:-@[-`{-~])/g, "$1");
417+
// Inert control spellings retain a backslash. Entity spellings are ambiguous
418+
// here because the display grammar supplies spans, not decoded destinations.
419+
if (
420+
!/^https?:\/\/[^/?#]/i.test(url) ||
421+
/[\s\\<>\p{Cc}]|&(?:#\d+|#x[\da-f]+|[a-z][a-z\d]*);|%(?![\da-f]{2})/iu.test(url)
422+
) {
423+
return undefined;
424+
}
425+
return URL.parse(url)?.hostname ? url : undefined;
382426
}
383427

384428
/** What an ATX heading's `#` marks take, with the spacing between them and its text. */
@@ -667,6 +711,18 @@ function inlineLines(
667711
at += 1;
668712
}
669713
for (; at < lineEnd; at += 1) {
714+
const destination = block.destinations.get(at);
715+
if (destination !== undefined) {
716+
let label = "";
717+
for (let index = destination.from; index < at; index += 1) {
718+
if (hidden[index - begin] !== 1) {
719+
label += text[index];
720+
}
721+
}
722+
if (label !== destination.url) {
723+
push(line, ` (${destination.url})`, block.base);
724+
}
725+
}
670726
if (hidden[at - begin] !== 1) {
671727
push(line, text[at], roles[at - begin]);
672728
}

‎packages/cli/src/repl/source-reading.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -328,16 +328,17 @@ function written(
328328
formatted: ReplMarkdownStore | undefined,
329329
): readonly ReplReadingLine[] {
330330
return Object.freeze(
331-
(formatted?.lines(text, style.role) ?? markdownLines(text, style.role)).map((one, index) =>
332-
Object.freeze({
333-
key: `${prefix}:${index}`,
334-
text: one.text,
335-
runs: one.runs,
336-
rail: "rail-pending" as const,
337-
depth: 0,
338-
badge: undefined,
339-
style,
340-
}),
331+
(formatted?.lines(text, style.role, true) ?? markdownLines(text, style.role, true)).map(
332+
(one, index) =>
333+
Object.freeze({
334+
key: `${prefix}:${index}`,
335+
text: one.text,
336+
runs: one.runs,
337+
rail: "rail-pending" as const,
338+
depth: 0,
339+
badge: undefined,
340+
style,
341+
}),
341342
),
342343
);
343344
}

0 commit comments

Comments
 (0)