TypeScript
fix(markdown): preserve descriptive file-link labels (#15509)
maria1d013c7ca1ed
diff --git a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.tsindex 75d1e852acf..6ae50075093 100644--- a/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts+++ b/apps/mobile/modules/t3-markdown-text/src/nativeMarkdownText.ts@@ -1,4 +1,5 @@import type { MarkdownNode } from "react-native-nitro-markdown/headless";+import { isMarkdownFileLinkLabel } from "@t3tools/client-runtime/markdown-links";import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";import { imageMimeType } from "@t3tools/shared/image";import { isWindowsAbsolutePath } from "@t3tools/shared/path";@@ -109,7 +110,8 @@ export function nativeMarkdownContextCopyRanges(}>,) {let offset = 0;- return runs.flatMap(({ run, text, inlineImageLength }) => {+ const ranges: Array<{ start: number; end: number; text: string }> = [];+ for (const [index, { run, text, inlineImageLength }] of runs.entries()) {const start = offset;offset += text.length + inlineImageLength;const reference = parseComposerContextHref(run.href ?? "");@@ -117,11 +119,25 @@ export function nativeMarkdownContextCopyRanges(? formatComposerContextReference({ ...reference, label: run.text }): run.skillName? `$${run.skillName}`- : run.fileIcon && run.href- ? (run.sourceText ?? `[${run.text}](<${run.href}>)`)- : null;- return source === null ? [] : [{ start, end: offset, text: source }];- });+ : run.sourceText !== undefined+ ? run.sourceText+ : run.fileIcon && run.href+ ? `[${run.text}](<${run.href}>)`+ : null;+ if (source === null) continue;+ const previous = ranges.at(-1);+ if (+ run.sourceText !== undefined &&+ !runs[index - 1]?.run.fileIcon &&+ previous?.end === start &&+ previous.text === source+ ) {+ previous.end = offset;+ } else {+ ranges.push({ start, end: offset, text: source });+ }+ }+ return ranges;}import type { SelectableMarkdownSkill } from "./SelectableMarkdownText.types";@@ -181,6 +197,7 @@ interface RunContext {readonly href?: string;readonly externalHost?: string;readonly fileIcon?: MarkdownFileIcon;+ readonly sourceText?: string;readonly role?: NativeMarkdownTextRun["role"];readonly headingLevel?: number;readonly depth?: number;@@ -268,6 +285,7 @@ function sameRunStyle(left: NativeMarkdownTextRun, right: NativeMarkdownTextRun)left.href === right.href &&left.externalHost === right.externalHost &&left.fileIcon === right.fileIcon &&+ left.sourceText === right.sourceText &&left.skillName === right.skillName &&left.skillLabel === right.skillLabel &&left.role === right.role &&@@ -298,6 +316,7 @@ function appendRun(...(context.href ? { href: context.href } : {}),...(context.externalHost ? { externalHost: context.externalHost } : {}),...(context.fileIcon ? { fileIcon: context.fileIcon } : {}),+ ...(context.sourceText !== undefined ? { sourceText: context.sourceText } : {}),...(context.role ? { role: context.role } : {}),...(context.headingLevel ? { headingLevel: context.headingLevel } : {}),...(context.depth ? { depth: context.depth } : {}),@@ -432,6 +451,36 @@ function nodeTextContent(node: MarkdownNode): string {return (node.children ?? []).map(nodeTextContent).join("");}+function fileLinkLabelMarkdown(node: MarkdownNode): string {+ const children = (node.children ?? []).map(fileLinkLabelMarkdown).join("");+ switch (node.type) {+ case "bold":+ return `**${children}**`;+ case "italic":+ return `*${children}*`;+ case "strikethrough":+ return `~~${children}~~`;+ case "code_inline": {+ const content = nodeTextContent(node);+ const fence = "`".repeat(+ Math.max(0, ...(content.match(/`+/g) ?? []).map((run) => run.length)) + 1,+ );+ const padding = /^`|`$|^ .* $/.test(content) && content.trim().length > 0 ? " " : "";+ return `${fence}${padding}${content}${padding}${fence}`;+ }+ case "soft_break":+ return "\n";+ case "line_break":+ return " \n";+ case "text":+ return textNodeContent(nodeTextContent(node)).replace(/[\\[\]*_`~]/g, "\\$&");+ case "image":+ return `![${(node.alt ?? "").replace(/[\\[\]]/g, "\\$&")}](<${node.href ?? ""}>)`;+ default:+ return node.content ?? children;+ }+}+function appendNode(runs: NativeMarkdownTextRun[],node: MarkdownNode,@@ -482,6 +531,23 @@ function appendNode(}const presentation = resolveMarkdownLinkPresentation(node.href ?? "");if (presentation.kind === "file") {+ const label = textNodeContent(nodeTextContent(node));+ if (!isMarkdownFileLinkLabel(label, presentation.href)) {+ const fileRuns: NativeMarkdownTextRun[] = [];+ const fileContext = {+ ...context,+ href: presentation.href,+ sourceText: `[${fileLinkLabelMarkdown(node)}](<${presentation.href}>)`,+ };+ appendChildren(fileRuns, node, fileContext);+ appendRun(fileRuns, " ", fileContext);+ appendRun(fileRuns, presentation.label, {+ ...fileContext,+ fileIcon: presentation.icon,+ });+ runs.push(...fileRuns);+ return runs;+ }return appendRun(runs, presentation.label, {...context,href: presentation.href,diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 7d591d59e8c..0f55d36c011 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -36,6 +36,8 @@ import {type CodexArtifactTemplate,} from "@t3tools/client-runtime/codex-artifact-templates";import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";+import { isMarkdownFileLinkLabel } from "@t3tools/client-runtime/markdown-links";+import { getTextContent, type MarkdownNode } from "react-native-nitro-markdown/headless";import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import {@@ -721,7 +723,7 @@ interface MarkdownStyleSet {}const failedMarkdownFaviconHosts = new Set<string>();-const MarkdownLinkLabelContext = createContext(false);+const MarkdownLinkLabelContext = createContext<"file" | "other" | null>(null);const markdownLinkStyles = StyleSheet.create({inlineIcon: {width: 14,@@ -813,6 +815,22 @@ function MarkdownInlineCode(props: {);}+function MarkdownImage(props: {+ readonly node: MarkdownNode;+ readonly renderImage: MarkdownImageRenderer;+}) {+ const insideLink = useContext(MarkdownLinkLabelContext);+ if (insideLink === "file")+ return <NativeText>{props.node.alt ?? props.node.title ?? ""}</NativeText>;+ return props.node.href+ ? props.renderImage({+ href: props.node.href,+ alt: props.node.alt ?? null,+ title: props.node.title ?? null,+ })+ : null;+}+const ARTIFACT_TEMPLATE_SYMBOL_BY_KIND: Record<CodexArtifactTemplate["artifactKind"],AppSymbolName@@ -1183,26 +1201,31 @@ function useMarkdownStyles(preserveSoftBreaks: boolean,highlightCode: boolean,): CustomRenderers => ({- link: ({ children, href = "" }) => {+ link: ({ children, node, href = "" }) => {const presentation = resolveMarkdownLinkPresentation(href);if (presentation.kind === "file") {return (- <NativeText- className="font-t3-bold"- onPress={() => onLinkPress(href)}- style={{ color: inlineTextColor }}- >- <Image- source={markdownFileIconSource(presentation.icon)}- style={markdownLinkStyles.inlineIcon}- />- {presentation.label}- </NativeText>+ <MarkdownLinkLabelContext.Provider value="file">+ <NativeText onPress={() => onLinkPress(href)} style={{ color: inlineTextColor }}>+ {!isMarkdownFileLinkLabel(getTextContent(node), href) && <>{children} </>}+ <NativeText+ className="font-t3-bold"+ onPress={() => onLinkPress(href)}+ style={{ color: inlineTextColor }}+ >+ <Image+ source={markdownFileIconSource(presentation.icon)}+ style={markdownLinkStyles.inlineIcon}+ />+ {presentation.label}+ </NativeText>+ </NativeText>+ </MarkdownLinkLabelContext.Provider>);}if (presentation.kind === "external") {return (- <MarkdownLinkLabelContext.Provider value>+ <MarkdownLinkLabelContext.Provider value="other"><MarkdownExternalLinkhref={presentation.href}host={presentation.host}@@ -1216,7 +1239,7 @@ function useMarkdownStyles(}const linkHref = presentation.href;return (- <MarkdownLinkLabelContext.Provider value>+ <MarkdownLinkLabelContext.Provider value="other"><NativeTextclassName="underline"onPress={@@ -1265,14 +1288,7 @@ function useMarkdownStyles(})}</View>),- image: ({ node }) =>- node.href- ? (renderImage({- href: node.href,- alt: node.alt ?? null,- title: node.title ?? null,- }) ?? undefined)- : undefined,+ image: ({ node }) => <MarkdownImage node={node} renderImage={renderImage} />,code_inline: ({ content }) => (<MarkdownInlineCodecontent={content ?? ""}diff --git a/apps/mobile/src/lib/nativeMarkdownText.test.ts b/apps/mobile/src/lib/nativeMarkdownText.test.tsindex fca30deea89..0a4357ee124 100644--- a/apps/mobile/src/lib/nativeMarkdownText.test.ts+++ b/apps/mobile/src/lib/nativeMarkdownText.test.ts@@ -138,7 +138,7 @@ describe("nativeMarkdownTextRuns", () => {{type: "link",href: "file:///repo/README.md#L12",- children: [{ type: "text", content: "ignored label" }],+ children: [{ type: "text", content: "validates the input" }],},],};@@ -150,14 +150,116 @@ describe("nativeMarkdownTextRuns", () => {externalHost: "example.com",},{ text: " " },+ {+ text: "validates the input ",+ href: "file:///repo/README.md#L12",+ sourceText: "[validates the input](<file:///repo/README.md#L12>)",+ },{text: "README.md:12",href: "file:///repo/README.md#L12",fileIcon: "markdown",+ sourceText: "[validates the input](<file:///repo/README.md#L12>)",+ },+ ]);+ });++ it.each([true, false])("copies descriptive file links with collapsed chips=%s", (collapsed) => {+ const link: MarkdownNode = {+ type: "link",+ href: "/repo/src/example.ts:12",+ children: [+ { type: "text", content: "validates " },+ { type: "bold", children: [{ type: "text", content: "the input" }] },+ ],+ };+ const runs = nativeMarkdownTextRuns({ type: "paragraph", children: [link, link] });+ expect(runs.map((run) => run.text).join("")).toBe(+ "validates the input example.ts:12validates the input example.ts:12",+ );+ expect(runs.filter((run) => run.bold).map((run) => run.text)).toEqual([+ "the input",+ "the input",+ ]);+ const ranges = nativeMarkdownContextCopyRanges(+ runs.map((run) => ({+ run,+ text: collapsed && run.fileIcon ? "" : run.text,+ inlineImageLength: run.fileIcon ? 1 : 0,+ })),+ );+ const length = "validates the input ".length + (collapsed ? 1 : "example.ts:12".length + 1);+ expect(ranges).toEqual([+ { start: 0, end: length, text: "[validates **the input**](</repo/src/example.ts:12>)" },+ {+ start: length,+ end: length * 2,+ text: "[validates **the input**](</repo/src/example.ts:12>)",},]);});+ it("keeps filename-labelled links as chips", () => {+ expect(+ nativeMarkdownTextRuns({+ type: "paragraph",+ children: [+ {+ type: "link",+ href: "/repo/src/example.ts:12",+ children: [{ type: "code_inline", content: "src/example.ts:12" }],+ },+ ],+ }),+ ).toEqual([{ text: "example.ts:12", href: "/repo/src/example.ts:12", fileIcon: "typescript" }]);+ });++ it.each([+ [{ type: "italic", children: [{ type: "text", content: "details" }] }, "*details*"],+ [{ type: "strikethrough", children: [{ type: "text", content: "details" }] }, "~~details~~"],+ [{ type: "code_inline", content: "`details`" }, "`` `details` ``"],+ [{ type: "code_inline", content: " details " }, "` details `"],+ [{ type: "text", content: "[details] *literal*" }, "\\[details\\] \\*literal\\*"],+ [{ type: "soft_break" }, "\n"],+ [{ type: "line_break" }, " \n"],+ [+ { type: "image", alt: "details", href: "https://example.com/icon.png" },+ "",+ ],+ ] satisfies ReadonlyArray<readonly [MarkdownNode, string]>)(+ "keeps descriptive label markup when copying %j",+ (child, source) => {+ const runs = nativeMarkdownTextRuns({+ type: "paragraph",+ children: [+ {+ type: "link",+ href: "/repo/a.ts",+ children: [{ type: "text", content: "see " }, child],+ },+ ],+ });+ expect(+ nativeMarkdownContextCopyRanges(+ runs.map((run) => ({+ run,+ text: run.fileIcon ? "" : run.text,+ inlineImageLength: run.fileIcon ? 1 : 0,+ })),+ ),+ ).toEqual([+ {+ start: 0,+ end:+ runs+ .filter((run) => !run.fileIcon)+ .reduce((length, run) => length + run.text.length, 0) + 1,+ text: `[see ${source}](</repo/a.ts>)`,+ },+ ]);+ },+ );+it("keeps hard breaks and collapses soft breaks", () => {const node: MarkdownNode = {type: "paragraph",diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 5358e253af4..26b97c24719 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -161,6 +161,7 @@ import {shouldOpenMarkdownFileLinkInEditor,type MarkdownFileLinkMeta,} from "../markdown-links";+import { isMarkdownFileLinkLabel } from "@t3tools/client-runtime/markdown-links";import { readLocalApi } from "../localApi";import { useAssetUrlRefresh, useAssetUrlState } from "../assets/assetUrls";import { cn } from "../lib/utils";@@ -3022,6 +3023,7 @@ const CHAT_MARKDOWN_COMPONENTS = {updateThreadPullRequestLink,fileLinkChip,renderContextReference,+ text,} = use(ChatMarkdownRendererContext);const citation = href ? parseAssistantCitationHref(href) : null;if (citation) return <AssistantCitationChip citation={citation} />;@@ -3233,10 +3235,21 @@ const CHAT_MARKDOWN_COMPONENTS = {);}- return fileLinkChip(- fileLinkMeta,- `[${fileLinkMeta.basename}](${normalizedHref})`,- normalizedHref,+ const label = nodeToPlainText(children);+ const start = node?.position?.start.offset;+ const end = node?.position?.end.offset;+ const source = start !== undefined && end !== undefined ? text.slice(start, end) : "";+ const copyMarkdown =+ source.startsWith("[") && source.includes("](")+ ? source+ : `[${(label || fileLinkMeta.basename).replace(/[\\[\]]/g, "\\$&")}](${normalizedHref})`;+ const chip = fileLinkChip(fileLinkMeta, copyMarkdown, normalizedHref);+ return isMarkdownFileLinkLabel(label, normalizedHref) ? (+ chip+ ) : (+ <span data-markdown-copy={copyMarkdown}>+ {children} {chip}+ </span>);},code: function MarkdownCode({ node, children, className, ...props }) {diff --git a/packages/client-runtime/src/markdownLinks.test.ts b/packages/client-runtime/src/markdownLinks.test.tsindex deea6960478..b6e52e4534a 100644--- a/packages/client-runtime/src/markdownLinks.test.ts+++ b/packages/client-runtime/src/markdownLinks.test.ts@@ -3,12 +3,36 @@ import { describe, expect, it } from "vite-plus/test";import {fileBasename,inlineCodeFilePathCandidate,+ isMarkdownFileLinkLabel,parseFileUrlHref,parseMarkdownFileLink,splitFilePathPosition,workspaceRelativeFilePath,} from "./markdownLinks.ts";+describe("isMarkdownFileLinkLabel", () => {+ it.each([+ ["validates the input", "/repo/src/example.ts:12", false],+ ["read src/example.ts", "/repo/src/example.ts:12", false],+ ["example.ts?why this matters", "/repo/src/example.ts", false],+ ["example.ts", "/repo/src/example.ts:12", true],+ ["example.ts:12", "/repo/src/example.ts:12", true],+ ["example.ts:99", "/repo/src/example.ts:12", false],+ ["example.ts:12:2", "/repo/src/example.ts:12:2", true],+ ["example.ts:12:3", "/repo/src/example.ts:12:2", false],+ ["example.ts:12", "/repo/src/example.ts", false],+ ["src/example.ts:12", "/repo/src/example.ts:12", true],+ ["./src/example.ts", "/repo/src/example.ts", true],+ ["/repo/src/example.ts", "/repo/src/example.ts", true],+ ["src/", "/home/me/project/src/", true],+ ["EXAMPLE.TS", "C:/repo/src/example.ts:12", true],+ ["file name.ts", "file:///repo/file%20name.ts", true],+ ["", "/repo/src/example.ts", true],+ ])("classifies %s for %s", (label, href, expected) => {+ expect(isMarkdownFileLinkLabel(label, href)).toBe(expected);+ });+});+describe("inlineCodeFilePathCandidate", () => {it.each([["src\\main.ts", "src/main.ts"],diff --git a/packages/client-runtime/src/markdownLinks.ts b/packages/client-runtime/src/markdownLinks.tsindex 0a32f506108..88db0e5a725 100644--- a/packages/client-runtime/src/markdownLinks.ts+++ b/packages/client-runtime/src/markdownLinks.ts@@ -265,6 +265,29 @@ export function formatFilePathPosition(position: FilePathPosition): string {return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;}+/** Keeps filename and destination-path labels compact without discarding prose. */+export function isMarkdownFileLinkLabel(label: string, href: string): boolean {+ const destination = parseMarkdownFileLink(href);+ if (!destination) return false;+ const normalize = (path: string) =>+ path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");+ const labelPosition = splitFilePathPosition(label.trim());+ if (+ (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||+ (labelPosition.column !== undefined && labelPosition.column !== destination.column)+ ) {+ return false;+ }+ let labelPath = normalize(labelPosition.path);+ let destinationPath = normalize(destination.path);+ if (labelPath.length === 0) return true;+ if (isWindowsAbsolutePath(destination.path)) {+ labelPath = labelPath.toLowerCase();+ destinationPath = destinationPath.toLowerCase();+ }+ return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);+}+export function isRelativeFilePath(path: string): boolean {return (RELATIVE_PATH_PREFIX_PATTERN.test(path) ||