TypeScript
fix(mobile): chat chips match desktop and the composer again (#22169)
olivercdaaa742c9cf
diff --git a/apps/mobile/assets/context-chip-icons/circle-dashed.png b/apps/mobile/assets/context-chip-icons/circle-dashed.pngnew file mode 100644index 00000000000..72985d77921Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/circle-dashed.png differdiff --git a/apps/mobile/assets/context-chip-icons/film.png b/apps/mobile/assets/context-chip-icons/film.pngnew file mode 100644index 00000000000..399752993e3Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/film.png differdiff --git a/apps/mobile/assets/context-chip-icons/git-merge.png b/apps/mobile/assets/context-chip-icons/git-merge.pngnew file mode 100644index 00000000000..06c049331e5Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-merge.png differdiff --git a/apps/mobile/assets/context-chip-icons/git-pull-request-arrow.png b/apps/mobile/assets/context-chip-icons/git-pull-request-arrow.pngnew file mode 100644index 00000000000..344120c4cc6Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-pull-request-arrow.png differdiff --git a/apps/mobile/assets/context-chip-icons/git-pull-request-closed.png b/apps/mobile/assets/context-chip-icons/git-pull-request-closed.pngnew file mode 100644index 00000000000..777b0953639Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-pull-request-closed.png differdiff --git a/apps/mobile/assets/context-chip-icons/git-pull-request-draft.png b/apps/mobile/assets/context-chip-icons/git-pull-request-draft.pngnew file mode 100644index 00000000000..b1490a873e4Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-pull-request-draft.png differdiff --git a/apps/mobile/assets/context-chip-icons/image.png b/apps/mobile/assets/context-chip-icons/image.pngnew file mode 100644index 00000000000..ac0ef9f7b44Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/image.png differdiff --git a/apps/mobile/assets/context-chip-icons/message-circle.png b/apps/mobile/assets/context-chip-icons/message-circle.pngnew file mode 100644index 00000000000..9f409bf70c2Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/message-circle.png differdiff --git a/apps/mobile/assets/context-chip-icons/messages-square.png b/apps/mobile/assets/context-chip-icons/messages-square.pngnew file mode 100644index 00000000000..73f5da79357Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/messages-square.png differdiff --git a/apps/mobile/assets/context-chip-icons/mouse-pointer-click.png b/apps/mobile/assets/context-chip-icons/mouse-pointer-click.pngnew file mode 100644index 00000000000..64d8e727fb5Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/mouse-pointer-click.png differdiff --git a/apps/mobile/assets/context-chip-icons/skill.png b/apps/mobile/assets/context-chip-icons/skill.pngnew file mode 100644index 00000000000..60e960d2323Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/skill.png differdiff --git a/apps/mobile/assets/context-chip-icons/terminal.png b/apps/mobile/assets/context-chip-icons/terminal.pngnew file mode 100644index 00000000000..188638a9c2fBinary files /dev/null and b/apps/mobile/assets/context-chip-icons/terminal.png differdiff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex fdd83742516..c7e8406bc17 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -40,6 +40,7 @@"config:preview": "APP_VARIANT=preview expo config","config:prod": "APP_VARIANT=production expo config","profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",+ "sync:chip-icons": "node scripts/sync-context-chip-icons.mjs","sync:pierre-icons": "node scripts/sync-pierre-file-icons.mjs","measure-renders": "node scripts/measure-renders.mts","generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",diff --git a/apps/mobile/scripts/sync-context-chip-icons.mjs b/apps/mobile/scripts/sync-context-chip-icons.mjsnew file mode 100644index 00000000000..aac4983d75e--- /dev/null+++ b/apps/mobile/scripts/sync-context-chip-icons.mjs@@ -0,0 +1,93 @@+import * as NodeFS from "node:fs";+import * as NodeModule from "node:module";+import * as NodePath from "node:path";+import * as NodeURL from "node:url";++const scriptDirectory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));+const appDirectory = NodePath.resolve(scriptDirectory, "..");+const repositoryRoot = NodePath.resolve(appDirectory, "../..");+const outputDirectory = NodePath.join(appDirectory, "assets/context-chip-icons");+const generatedModulePath = NodePath.join(appDirectory, "src/lib/contextChipIcons.generated.ts");++const requireFromWeb = NodeModule.createRequire(+ NodePath.join(repositoryRoot, "apps/web/package.json"),+);+const requireFromScripts = NodeModule.createRequire(+ NodePath.join(repositoryRoot, "scripts/package.json"),+);+const sharp = requireFromScripts("sharp");+const lucideIconsDirectory = NodePath.join(+ NodePath.dirname(requireFromWeb.resolve("lucide-react/package.json")),+ "dist/esm/icons",+);+const webChipSource = NodeFS.readFileSync(+ NodePath.join(repositoryRoot, "apps/web/src/components/composerInlineChip.ts"),+ "utf8",+);+const skillSvg = webChipSource.match(/SKILL_CHIP_ICON_SVG = `([\s\S]*?)`;/)?.[1];++if (!skillSvg) {+ throw new Error(+ "Could not read SKILL_CHIP_ICON_SVG from apps/web/src/components/composerInlineChip.ts",+ );+}++const lucideIcons = [+ "circle-dashed",+ "film",+ "git-merge",+ "git-pull-request-arrow",+ "git-pull-request-closed",+ "git-pull-request-draft",+ "image",+ "message-circle",+ "messages-square",+ "mouse-pointer-click",+ "terminal",+];++async function lucideSvg(name) {+ const module = await import(+ NodeURL.pathToFileURL(NodePath.join(lucideIconsDirectory, `${name}.js`)).href+ );+ const body = module.__iconNode+ .map(([tag, { key: _key, ...attributes }]) => {+ const attributeText = Object.entries(attributes)+ .map(([attribute, value]) => `${attribute}="${value}"`)+ .join(" ");+ return `<${tag} ${attributeText}/>`;+ })+ .join("");+ return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;+}++async function renderIcon(token, svg) {+ const sized = svg+ .replace(/^<svg[^>]*?>/, (tag) =>+ tag+ .replace(/ (?:width|height)="[^"]*"/g, "")+ .replace("<svg ", '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" '),+ )+ .replaceAll("currentColor", "#ffffff");+ await sharp(Buffer.from(sized), { density: 72 * (64 / 24) })+ .resize(64, 64)+ .png()+ .toFile(NodePath.join(outputDirectory, `${token}.png`));+}++NodeFS.rmSync(outputDirectory, { recursive: true, force: true });+NodeFS.mkdirSync(outputDirectory, { recursive: true });++for (const name of lucideIcons) {+ await renderIcon(name, await lucideSvg(name));+}+await renderIcon("skill", skillSvg);++const tokens = [...lucideIcons, "skill"].sort();+const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const CONTEXT_CHIP_ICON_SOURCES = {\n${tokens+ .map(+ (token) =>+ ` ${/^\w+$/.test(token) ? token : `"${token}"`}: require("../../assets/context-chip-icons/${token}.png"),`,+ )+ .join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;+NodeFS.writeFileSync(generatedModulePath, generatedSource);diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsxindex f279c6d8ceb..a0a6fa74346 100644--- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx+++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx@@ -57,7 +57,6 @@ export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {codeBackgroundColor: codeBackground,codeBlockBackgroundColor: codeBackground,fileTextColor: codeText,- skillTextColor: codeText,quoteMarkerColor: blockquoteBorder,dividerColor: horizontalRule,fontSize: nativeMarkdownTypography.fontSize,diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 03e9066c9c2..d733b751ace 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -3,8 +3,8 @@ import * as Dialog from "../../components/ui/Dialog";import { useOpenPullRequest } from "../../native/useOpenPullRequest";import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";+import { enrichedContextLinkCustomization } from "../../native/useEnrichedLinkVariants";import {- enrichedContextLinkPresentation,enrichedSkillDisplayName,enrichedSkillInstructionsPath,enrichedSkillReference,@@ -169,7 +169,6 @@ import {resolveNativeMarkdownTypography,} from "../../lib/appearancePreferences";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";-import { markdownFileIconSource } from "../../lib/markdownFileIcons";import { PierreEntryIcon } from "../../components/PierreEntryIcon";import { markdownLinkIconSource } from "../../lib/markdownLinkIcons";import {@@ -866,8 +865,6 @@ function useMarkdownStyles(): MarkdownStyleSets {const markdownUserCodeText = theme["--color-md-user-code-text"];const markdownUserInlineCodeText = theme["--color-user-bubble-foreground-muted"];const markdownUserFenceBg = theme["--color-md-user-fence-bg"];- const inlineSkillForeground = theme["--color-inline-skill-foreground"];- const userBubbleSkillForeground = theme["--color-user-bubble-skill-foreground"];const regularFontFamily = FONT_FAMILIES.regular;const boldFontFamily = FONT_FAMILIES.bold;@@ -884,7 +881,6 @@ function useMarkdownStyles(): MarkdownStyleSets {codeBackgroundColor: markdownUserCodeBg,codeBlockBackgroundColor: markdownUserFenceBg,fileTextColor: markdownUserBodyColor,- skillTextColor: userBubbleSkillForeground,quoteMarkerColor: markdownUserBodyColor,dividerColor: markdownUserBodyColor,contextChipBorderColor,@@ -907,7 +903,6 @@ function useMarkdownStyles(): MarkdownStyleSets {codeBackgroundColor: markdownCodeBg,codeBlockBackgroundColor: markdownCodeBg,fileTextColor: markdownCodeText,- skillTextColor: inlineSkillForeground,quoteMarkerColor: markdownBlockquoteBorder,dividerColor: markdownHrColor,contextChipBorderColor,@@ -923,7 +918,6 @@ function useMarkdownStyles(): MarkdownStyleSets {}, [boldFontFamily,contextChipBorderColor,- inlineSkillForeground,markdownBlockquoteBorder,markdownBodyColor,markdownCodeBg,@@ -939,7 +933,6 @@ function useMarkdownStyles(): MarkdownStyleSets {markdownUserInlineCodeText,nativeMarkdownTypography,regularFontFamily,- userBubbleSkillForeground,]);}@@ -1566,12 +1559,9 @@ function UserMessageContent(props: UserMessageContentProps) {});}},- linkCustomization: (href) => {- const presentation = enrichedContextLinkPresentation(href, props.context?.records);- return presentation- ? { color: presentation.color, icon: markdownFileIconSource(presentation.icon) }- : props.linkHandlers.linkCustomization?.(href);- },+ linkCustomization: (href) =>+ enrichedContextLinkCustomization(href, props.context?.records ?? []) ??+ props.linkHandlers.linkCustomization?.(href),}}/>{selected ? (diff --git a/apps/mobile/src/lib/composerChipPresentation.test.ts b/apps/mobile/src/lib/composerChipPresentation.test.tsindex 94aa1a0f8b2..faf5aba2229 100644--- a/apps/mobile/src/lib/composerChipPresentation.test.ts+++ b/apps/mobile/src/lib/composerChipPresentation.test.ts@@ -21,24 +21,24 @@ describe("contextChipPresentation image detection", () => {const { contextChipPresentation } = await import("./composerChipPresentation");expect(contextChipPresentation("file", { kind: "file", name: "IMG_4997.PNG", mimeType: "" }),- ).toEqual({ accent: "#d55665", symbol: "photo" });+ ).toEqual({ accent: "#d55665", symbol: "photo", icon: "image" });expect(contextChipPresentation("file", {kind: "file",name: "shot",mimeType: "image/jpeg",}),- ).toEqual({ accent: "#d55665", symbol: "photo" });+ ).toEqual({ accent: "#d55665", symbol: "photo", icon: "image" });});it("leaves genuine documents and videos alone", async () => {const { contextChipPresentation } = await import("./composerChipPresentation");expect(contextChipPresentation("file", { kind: "file", name: "notes.txt", mimeType: "text/plain" }),- ).toEqual({ accent: "#0090cd", symbol: "doc" });+ ).toEqual({ accent: "#0090cd", symbol: "doc", icon: null });expect(contextChipPresentation("file", { kind: "file", name: "clip.mp4", mimeType: "video/mp4" }),- ).toEqual({ accent: "#d06217", symbol: "play.rectangle" });+ ).toEqual({ accent: "#d06217", symbol: "play.rectangle", icon: "film" });});});@@ -59,7 +59,7 @@ describe("pull request chip status", () => {expect((await chip("closed")).accent).toBe("#d55665");});- it("keeps one glyph across every state, so only colour carries the status", async () => {+ it("keeps one composer glyph across every state, so only colour carries the status", async () => {const symbols = await Promise.all([chip("open"), chip("open", true), chip("merged"), chip("closed")].map(async (pending) => (await pending).symbol,@@ -68,6 +68,13 @@ describe("pull request chip status", () => {expect(new Set(symbols)).toEqual(new Set(["git-pull-request"]));});+ it("gives message chips web's per-state pull request glyphs", async () => {+ expect((await chip("open")).icon).toBe("git-pull-request-arrow");+ expect((await chip("open", true)).icon).toBe("git-pull-request-draft");+ expect((await chip("merged")).icon).toBe("git-merge");+ expect((await chip("closed")).icon).toBe("git-pull-request-closed");+ });+it("falls back to the generic pull request chip when the state is unknown", async () => {const { contextChipPresentation } = await import("./composerChipPresentation");expect(@@ -78,3 +85,20 @@ describe("pull request chip status", () => {).toBe("#7079e4");});});++describe("context chip kinds", () => {+ it("gives thread context its own teal chip instead of the file style", async () => {+ const { contextChipPresentation } = await import("./composerChipPresentation");+ expect(contextChipPresentation("thread")).toMatchObject({+ accent: "#009c96",+ icon: "messages-square",+ });+ });++ it("shows unknown kinds as a neutral chip rather than a file", async () => {+ const { contextChipPresentation } = await import("./composerChipPresentation");+ const presentation = contextChipPresentation("future-kind");+ expect(presentation.accent).toBeUndefined();+ expect(presentation.icon).toBe("circle-dashed");+ });+});diff --git a/apps/mobile/src/lib/composerChipPresentation.ts b/apps/mobile/src/lib/composerChipPresentation.tsindex 90e2d5d15fa..518b5843eca 100644--- a/apps/mobile/src/lib/composerChipPresentation.ts+++ b/apps/mobile/src/lib/composerChipPresentation.ts@@ -1,22 +1,51 @@import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";import { imageMimeType } from "@t3tools/shared/image";import { videoMimeType } from "@t3tools/shared/video";++import type { CONTEXT_CHIP_ICON_SOURCES } from "./contextChipIcons.generated";++export type ContextChipIcon = keyof typeof CONTEXT_CHIP_ICON_SOURCES;++interface ContextChipPresentation {+ readonly accent?: string;+ readonly symbol: string;+ readonly icon: ContextChipIcon | null;+}+/*** These are the sRGB form of the same OKLCH set web uses, so a chip looks the same on every- * surface. See `composerInlineChip.ts`.+ * surface. See `ContextChip.tsx`.*/const CONTEXT_CHIP_PRESENTATIONS = {- image: { accent: "#d55665", symbol: "photo" },- video: { accent: "#d06217", symbol: "play.rectangle" },- file: { accent: "#0090cd", symbol: "doc" },- mention: { accent: "#0096af", symbol: "doc" },- terminal: { accent: "#009f6e", symbol: "terminal" },- element: { accent: "#b87501", symbol: "cursorarrow.click" },- "preview-annotation": { accent: "#b87501", symbol: "cursorarrow.click" },- "review-comment": { accent: "#8a70dd", symbol: "text.bubble" },- "pull-request": { accent: "#7079e4", symbol: "git-pull-request" },- skill: { accent: "#b261be", symbol: "cube" },-} as const;+ image: { accent: "#d55665", symbol: "photo", icon: "image" },+ video: { accent: "#d06217", symbol: "play.rectangle", icon: "film" },+ file: { accent: "#0090cd", symbol: "doc", icon: null },+ mention: { accent: "#0096af", symbol: "doc", icon: null },+ terminal: { accent: "#009f6e", symbol: "terminal", icon: "terminal" },+ element: { accent: "#b87501", symbol: "cursorarrow.click", icon: "mouse-pointer-click" },+ "preview-annotation": {+ accent: "#b87501",+ symbol: "cursorarrow.click",+ icon: "mouse-pointer-click",+ },+ "review-comment": { accent: "#8a70dd", symbol: "text.bubble", icon: "message-circle" },+ "pull-request": {+ accent: "#7079e4",+ symbol: "git-pull-request",+ icon: "git-pull-request-arrow",+ },+ skill: { accent: "#b261be", symbol: "cube", icon: "skill" },+ thread: {+ accent: "#009c96",+ symbol: "bubble.left.and.bubble.right",+ icon: "messages-square",+ },+} as const satisfies Record<string, ContextChipPresentation>;++export const UNAVAILABLE_CONTEXT_CHIP_PRESENTATION: ContextChipPresentation = {+ symbol: "doc",+ icon: "circle-dashed",+};export function composerChipSizeSuffix(record?: {readonly kind?: string;@@ -27,11 +56,11 @@ export function composerChipSizeSuffix(record?: {}const PULL_REQUEST_CHIP_PRESENTATIONS = {- open: { accent: "#009f6e", symbol: "git-pull-request" },- draft: { accent: "#7f8793", symbol: "git-pull-request" },- merged: { accent: "#8a70dd", symbol: "git-pull-request" },- closed: { accent: "#d55665", symbol: "git-pull-request" },-} as const;+ open: { accent: "#009f6e", symbol: "git-pull-request", icon: "git-pull-request-arrow" },+ draft: { accent: "#7f8793", symbol: "git-pull-request", icon: "git-pull-request-draft" },+ merged: { accent: "#8a70dd", symbol: "git-pull-request", icon: "git-merge" },+ closed: { accent: "#d55665", symbol: "git-pull-request", icon: "git-pull-request-closed" },+} as const satisfies Record<string, ContextChipPresentation>;export function contextChipPresentation(kind: string,@@ -45,7 +74,7 @@ export function contextChipPresentation(readonly isDraft?: boolean;};},-) {+): ContextChipPresentation {const presentationKind =kind === "file" &&videoMimeType({@@ -71,5 +100,5 @@ export function contextChipPresentation(}return Object.hasOwn(CONTEXT_CHIP_PRESENTATIONS, presentationKind)? CONTEXT_CHIP_PRESENTATIONS[presentationKind as keyof typeof CONTEXT_CHIP_PRESENTATIONS]- : CONTEXT_CHIP_PRESENTATIONS.file;+ : UNAVAILABLE_CONTEXT_CHIP_PRESENTATION;}diff --git a/apps/mobile/src/lib/contextChipIcons.generated.ts b/apps/mobile/src/lib/contextChipIcons.generated.tsnew file mode 100644index 00000000000..10a8b6af70a--- /dev/null+++ b/apps/mobile/src/lib/contextChipIcons.generated.ts@@ -0,0 +1,16 @@+import type { ImageSourcePropType } from "react-native";++export const CONTEXT_CHIP_ICON_SOURCES = {+ "circle-dashed": require("../../assets/context-chip-icons/circle-dashed.png"),+ film: require("../../assets/context-chip-icons/film.png"),+ "git-merge": require("../../assets/context-chip-icons/git-merge.png"),+ "git-pull-request-arrow": require("../../assets/context-chip-icons/git-pull-request-arrow.png"),+ "git-pull-request-closed": require("../../assets/context-chip-icons/git-pull-request-closed.png"),+ "git-pull-request-draft": require("../../assets/context-chip-icons/git-pull-request-draft.png"),+ image: require("../../assets/context-chip-icons/image.png"),+ "message-circle": require("../../assets/context-chip-icons/message-circle.png"),+ "messages-square": require("../../assets/context-chip-icons/messages-square.png"),+ "mouse-pointer-click": require("../../assets/context-chip-icons/mouse-pointer-click.png"),+ skill: require("../../assets/context-chip-icons/skill.png"),+ terminal: require("../../assets/context-chip-icons/terminal.png"),+} as const satisfies Readonly<Record<string, ImageSourcePropType>>;diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts b/apps/mobile/src/lib/enrichedLinkPresentation.test.tsindex d4c6e5648f0..39b12dbb8b3 100644--- a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts+++ b/apps/mobile/src/lib/enrichedLinkPresentation.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vite-plus/test";-import type { ComposerContextId, ReviewCommentContextRecord } from "@t3tools/contracts";+import type {+ ComposerContextId,+ ComposerContextRecord,+ ReviewCommentContextRecord,+} from "@t3tools/contracts";import {enrichedContextLinkPresentation,enrichedLinkVariantPattern,@@ -108,25 +112,58 @@ describe("Enriched link presentation", () => {};expect(enrichedContextLinkPresentation("t3-context://v1/review-comment/review_1", [record]),- ).toEqual({ color: "#8a70dd", icon: "git" });- expect(- enrichedContextLinkPresentation("t3-context://v1/review-comment/review_2", [record]),- ).toEqual({ color: "#8a70dd", icon: "markdown" });+ ).toEqual({ accent: "#8a70dd", icon: { kind: "chip", name: "git-merge" } });});- it("retains recognizable presentation for unavailable and future context kinds", () => {+ it("shows a context the message no longer carries as an unavailable chip", () => {+ expect(enrichedContextLinkPresentation("t3-context://v1/terminal/missing", [])).toEqual({+ icon: { kind: "chip", name: "circle-dashed" },+ });+ });++ it("keeps each kind's own look when no records are known", () => {expect(enrichedContextLinkPresentation("t3-context://v1/terminal/missing")).toEqual({- color: "#009f6e",- icon: "bash",+ accent: "#009f6e",+ icon: { kind: "chip", name: "terminal" },});expect(enrichedContextLinkPresentation("t3-context://v1/skill/missing")).toEqual({- color: "#b261be",- icon: "mcp",+ accent: "#b261be",+ icon: { kind: "chip", name: "skill" },});expect(enrichedContextLinkPresentation("t3-context://v1/future/missing")).toEqual({- color: "#0090cd",- icon: "default",+ icon: { kind: "chip", name: "circle-dashed" },});expect(enrichedContextLinkPresentation("https://example.com/terminal/missing")).toBeUndefined();});++ it("uses the file-type icon and size for attachments and mentions", () => {+ const records: ReadonlyArray<ComposerContextRecord> = [+ {+ version: 1,+ contextId: "file_1" as ComposerContextId,+ kind: "file",+ label: "notes.md",+ attachmentId: "attachment_1",+ name: "notes.md",+ mimeType: "text/markdown",+ sizeBytes: 2048,+ },+ {+ version: 1,+ contextId: "mention_1" as ComposerContextId,+ kind: "mention",+ label: "math.ts",+ path: "src/math.ts",+ },+ ];+ expect(enrichedContextLinkPresentation("t3-context://v1/file/file_1", records)).toEqual({+ accent: "#0090cd",+ icon: { kind: "file", name: "markdown" },+ label: "notes.md · 2 KB",+ });+ expect(enrichedContextLinkPresentation("t3-context://v1/mention/mention_1", records)).toEqual({+ accent: "#0096af",+ icon: { kind: "file", name: "typescript" },+ });+ });});diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.ts b/apps/mobile/src/lib/enrichedLinkPresentation.tsindex 99289ed247b..aa4ea56a05b 100644--- a/apps/mobile/src/lib/enrichedLinkPresentation.ts+++ b/apps/mobile/src/lib/enrichedLinkPresentation.ts@@ -1,31 +1,38 @@import type { ComposerContextRecord } from "@t3tools/contracts";-import { contextChipPresentation } from "./composerChipPresentation";-import type { MarkdownFileIcon } from "./markdownLinks";+import {+ composerChipSizeSuffix,+ contextChipPresentation,+ type ContextChipIcon,+ UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,+} from "./composerChipPresentation";+import { resolveMarkdownFileIcon, type MarkdownFileIcon } from "./markdownLinks";import type { SelectableMarkdownSkill } from "../native/SelectableMarkdownText.types";import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";-const CONTEXT_ICONS: Readonly<Record<string, MarkdownFileIcon>> = {- photo: "image",- "play.rectangle": "video",- terminal: "bash",- "cursorarrow.click": "react",- "text.bubble": "markdown",- "git-pull-request": "git",- cube: "mcp",- doc: "default",-};+export type EnrichedChipIcon =+ | { readonly kind: "chip"; readonly name: ContextChipIcon }+ | { readonly kind: "file"; readonly name: MarkdownFileIcon };export function enrichedContextLinkPresentation(href: string,records?: ReadonlyArray<ComposerContextRecord>,-) {+): { accent?: string; icon: EnrichedChipIcon; label?: string } | undefined {const reference = parseComposerContextHref(href);if (!reference) return undefined;const record = records?.find((candidate) => candidate.contextId === reference.contextId);- const presentation = contextChipPresentation(reference.kind, record);+ const presentation =+ records && !record+ ? UNAVAILABLE_CONTEXT_CHIP_PRESENTATION+ : contextChipPresentation(reference.kind, record);+ const size = composerChipSizeSuffix(record);+ const fileName =+ record && "path" in record ? record.path : record && "name" in record ? record.name : "";return {- color: presentation.accent,- icon: CONTEXT_ICONS[presentation.symbol] ?? "default",+ ...(presentation.accent ? { accent: presentation.accent } : {}),+ icon: presentation.icon+ ? { kind: "chip", name: presentation.icon }+ : { kind: "file", name: resolveMarkdownFileIcon(fileName) },+ ...(record && size ? { label: `${record.label} · ${size}` } : {}),};}diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.tsindex 640a512dd4e..42f737f16b3 100644--- a/apps/mobile/src/lib/markdownDocument.ts+++ b/apps/mobile/src/lib/markdownDocument.ts@@ -140,6 +140,37 @@ export function markdownWithHtml(markdown: string): string {return markdown;}+const INLINE_CODE_SPAN = /`+([^`\r\n]+)`+/g;++export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {+ if (![...markdown.matchAll(INLINE_CODE_SPAN)].some(([, code]) => fileLink.test(code!.trim())))+ return markdown;+ const edits: Array<{ start: number; end: number; content: string }> = [];+ const visit = (node: MarkdownNode) => {+ if (node.type === "inlineCode") {+ const start = node.position?.start.offset;+ const end = node.position?.end.offset;+ const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");+ if (+ start !== undefined &&+ end !== undefined &&+ fileLink.test(node.value) &&+ !/[<>]/.test(node.value)+ )+ edits.push({+ start,+ end,+ content: `[${escaped}](<${escaped}>)`,+ });+ } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)+ node.children.forEach(visit);+ };+ visit(parser.parse(markdown));+ for (const edit of edits.reverse())+ markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);+ return markdown;+}+// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.function isTableDelimiterRow(line: string): boolean {if (!line.includes("-")) return false;diff --git a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts b/apps/mobile/src/lib/markdownInlineFileLinks.test.tsnew file mode 100644index 00000000000..139ff9abcf8--- /dev/null+++ b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vite-plus/test";+import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";+import { markdownWithInlineFileLinks, parseMarkdownDocument } from "./markdownDocument";++const rewrite = (markdown: string) =>+ markdownWithInlineFileLinks(markdown, ENRICHED_INLINE_FILE_LINK_REGEX);++describe("inline code that names a file", () => {+ it("becomes a link to the same path", () => {+ expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(+ "See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).",+ );+ });++ it("keeps commands, identifiers and URLs as code", () => {+ const markdown = "Run `vp test run`, call `useMemo`, open `https://example.com/a.ts`.";+ expect(rewrite(markdown)).toBe(markdown);+ });++ it("leaves fenced code blocks and code already inside a link alone", () => {+ const markdown = "```\nsrc/math.ts:2\n```\n\n[`src/math.ts`](src/math.ts)";+ expect(rewrite(markdown)).toBe(markdown);+ });++ it("handles double-backtick spans", () => {+ expect(rewrite("Open ``src/math.ts`` now.")).toBe("Open [src/math.ts](<src/math.ts>) now.");+ });++ it("links to the exact path when it holds backslashes or ampersands", () => {+ for (const path of ["C:\\repo\\_private\\file.ts", "./src/a©.ts", "./src/[id].ts"]) {+ const paragraph = parseMarkdownDocument(rewrite(`\`${path}\``)).children[0];+ const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;+ expect(link?.type === "link" && link.url).toBe(path);+ expect(+ link?.type === "link" && link.children[0]?.type === "text" && link.children[0].value,+ ).toBe(path);+ }+ });+});diff --git a/apps/mobile/src/lib/markdownLinks.test.ts b/apps/mobile/src/lib/markdownLinks.test.tsindex bf34d7cdc37..0f1783a5dca 100644--- a/apps/mobile/src/lib/markdownLinks.test.ts+++ b/apps/mobile/src/lib/markdownLinks.test.ts@@ -51,7 +51,7 @@ describe("resolveMarkdownLinkPresentation", () => {kind: "file",href,icon: "typescript",- label: "main.ts:42:7",+ label: "main.ts · L42:C7",path,line: 42,column: 7,@@ -63,7 +63,7 @@ describe("resolveMarkdownLinkPresentation", () => {kind: "file",href: "apps/mobile/src/index.ts:10",icon: "typescript",- label: "index.ts:10",+ label: "index.ts · L10",path: "apps/mobile/src/index.ts",line: 10,});@@ -107,7 +107,7 @@ describe("resolveMarkdownLinkPresentation", () => {path: "src/main.ts",line: 18,column: 2,- label: "main.ts:18:2",+ label: "main.ts · L18:C2",});});diff --git a/apps/mobile/src/lib/markdownLinks.ts b/apps/mobile/src/lib/markdownLinks.tsindex e18fef748a9..7eb9fec8cd7 100644--- a/apps/mobile/src/lib/markdownLinks.ts+++ b/apps/mobile/src/lib/markdownLinks.ts@@ -1,5 +1,5 @@import { fileBasename } from "@t3tools/shared/path";-import { formatFilePathPosition } from "@t3tools/shared/fileLinks";+import { fileLinkLabel } from "@t3tools/shared/fileLinks";import {inlineCodeFilePathCandidate,normalizeMarkdownLinkDestination,@@ -279,7 +279,7 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPresekind: "file",href: normalized,icon: resolveMarkdownFileIcon(target.path),- label: fileBasename(formatFilePathPosition(target)),+ label: fileLinkLabel(target, new Map()),path: target.path,...(target.line ? { line: target.line } : {}),...(target.column ? { column: target.column } : {}),diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsxindex 7e7ecf39674..5d965dad4dc 100644--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx@@ -4,7 +4,11 @@ import {formatComposerContextHref,formatComposerContextReference,} from "@t3tools/shared/composerContextReferences";-import { markdownWithHtml, markdownWithTableBreaks } from "../lib/markdownDocument";+import {+ markdownWithHtml,+ markdownWithInlineFileLinks,+ markdownWithTableBreaks,+} from "../lib/markdownDocument";import { useCallback, useMemo, useState, type ReactNode } from "react";import { Platform, Share, StyleSheet, View } from "react-native";import {@@ -151,7 +155,13 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {const { renderImage, resolveImageSource } = props;const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();const markdown = useMemo(- () => markdownWithTableBreaks(markdownWithHtml(props.markdown)),+ () =>+ markdownWithTableBreaks(+ markdownWithInlineFileLinks(+ markdownWithHtml(props.markdown),+ ENRICHED_INLINE_FILE_LINK_REGEX,+ ),+ ),[props.markdown],);const [documentAssets, setDocumentAssets] = useState<DocumentAssetsEvent["assets"]>([]);@@ -178,7 +188,6 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {const linkRecognition = useMemo(() => ({text: enrichedSkillLinkRegex(props.skills) ?? undefined,- inlineCode: ENRICHED_INLINE_FILE_LINK_REGEX,}),[props.skills],);diff --git a/apps/mobile/src/native/SelectableMarkdownText.types.ts b/apps/mobile/src/native/SelectableMarkdownText.types.tsindex e1a133e57bc..a0af8585bc6 100644--- a/apps/mobile/src/native/SelectableMarkdownText.types.ts+++ b/apps/mobile/src/native/SelectableMarkdownText.types.ts@@ -10,7 +10,6 @@ export interface NativeMarkdownTextStyle {readonly codeBackgroundColor: string;readonly codeBlockBackgroundColor: string;readonly fileTextColor: string;- readonly skillTextColor: string;readonly quoteMarkerColor: string;readonly dividerColor: string;readonly contextChipBorderColor?: string;@@ -64,6 +63,7 @@ export interface MarkdownLinkCustomization {readonly color?: string;readonly label?: string;readonly icon?: import("react-native").ImageSourcePropType;+ readonly chip?: { readonly accent?: string; readonly tintsIcon: boolean };}export interface SelectableMarkdownTextProps {diff --git a/apps/mobile/src/native/useEnrichedLinkVariants.ts b/apps/mobile/src/native/useEnrichedLinkVariants.tsindex 81ed0881c2f..31f97493739 100644--- a/apps/mobile/src/native/useEnrichedLinkVariants.ts+++ b/apps/mobile/src/native/useEnrichedLinkVariants.ts@@ -5,38 +5,65 @@ import type {MarkdownDocumentAsset,MarkdownStyle,} from "react-native-enriched-markdown";+import type { ComposerContextRecord } from "@t3tools/contracts";+import { contextChipPresentation } from "../lib/composerChipPresentation";+import { CONTEXT_CHIP_ICON_SOURCES } from "../lib/contextChipIcons.generated";+import { FONT_FAMILIES } from "../lib/fontFamilies";import { markdownFileIconSource } from "../lib/markdownFileIcons";import { markdownLinkIconSource } from "../lib/markdownLinkIcons";import { resolveMarkdownLinkIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";-import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types";+import type {+ MarkdownLinkCustomization,+ SelectableMarkdownTextProps,+} from "./SelectableMarkdownText.types";import {enrichedContextLinkPresentation,enrichedLinkVariantPattern,enrichedSkillDisplayName,enrichedSkillReference,+ type EnrichedChipIcon,} from "../lib/enrichedLinkPresentation";+function chipIconSource(icon: EnrichedChipIcon) {+ return icon.kind === "chip"+ ? CONTEXT_CHIP_ICON_SOURCES[icon.name]+ : markdownFileIconSource(icon.name);+}++export function enrichedContextLinkCustomization(+ href: string,+ records?: ReadonlyArray<ComposerContextRecord>,+): MarkdownLinkCustomization | undefined {+ const context = enrichedContextLinkPresentation(href, records);+ if (!context) return undefined;+ return {+ label: context.label,+ icon: chipIconSource(context.icon),+ chip: { accent: context.accent, tintsIcon: context.icon.kind === "chip" },+ };+}+function presentation(url: string,props: Pick<SelectableMarkdownTextProps, "linkCustomization" | "skills" | "textStyle">,-) {+): MarkdownLinkCustomization | undefined {const custom = props.linkCustomization?.(url);if (custom) return custom;- const context = enrichedContextLinkPresentation(url);- if (context) return { color: context.color, icon: markdownFileIconSource(context.icon) };+ const context = enrichedContextLinkCustomization(url);+ if (context) return context;const skill = enrichedSkillReference(url, props.skills);if (skill)return {- color: props.textStyle.skillTextColor,label: enrichedSkillDisplayName(skill),- icon: markdownFileIconSource("mcp"),+ icon: CONTEXT_CHIP_ICON_SOURCES.skill,+ chip: { accent: contextChipPresentation("skill").accent, tintsIcon: true },};const link = resolveMarkdownLinkPresentation(url);if (link.kind === "file")return {- color: props.textStyle.fileTextColor,label: link.label,icon: markdownFileIconSource(link.icon),+ chip: { accent: contextChipPresentation("mention").accent, tintsIcon: false },};const icon = link.kind === "external" ? resolveMarkdownLinkIcon(link.host) : null;return icon@@ -54,7 +81,7 @@ export function useEnrichedLinkVariants() {const { linkCustomization, skills, textStyle } = props;const links = useMemo(() => {- const byUrl = new Map<string, NonNullable<ReturnType<typeof presentation>>>();+ const byUrl = new Map<string, MarkdownLinkCustomization>();for (const asset of assets) {if (asset.kind !== "link" || byUrl.has(asset.url)) continue;const value = presentation(asset.url, { linkCustomization, skills, textStyle });@@ -62,11 +89,21 @@ export function useEnrichedLinkVariants(}return byUrl;}, [assets, linkCustomization, skills, textStyle]);+ const chipForegrounds = useMemo(+ () =>+ new Map(+ [...links].map(([url, link]) => [+ url,+ link.chip ? (link.chip.accent ?? textStyle.color) : undefined,+ ]),+ ),+ [links, textStyle],+ );const linkVariants = useMemo<MarkdownStyle["linkVariants"]>(() =>Object.fromEntries([...links].map(([url, link]) => {- const color = link.color ?? textStyle.fileTextColor;+ const chipForeground = chipForegrounds.get(url);return [enrichedLinkVariantPattern(url),{@@ -77,15 +114,15 @@ export function useEnrichedLinkVariants(paddingHorizontal: 5,paddingVertical: 2,},- fontFamily: textStyle.fontFamily,- color,+ fontFamily: chipForeground ? FONT_FAMILIES.medium : textStyle.fontFamily,+ color: chipForeground ?? link.color ?? textStyle.fileTextColor,underline: false,backgroundColor: "transparent",},];}),),- [links, textStyle],+ [chipForegrounds, links, textStyle],);const linkPillContent = useMemo<Record<string, LinkPillContent>>(() =>@@ -95,11 +132,11 @@ export function useEnrichedLinkVariants({label: link.label,iconUri: link.icon ? Image.resolveAssetSource(link.icon)?.uri : undefined,- iconTintColor: link.iconTintColor,+ iconTintColor: link.chip?.tintsIcon ? chipForegrounds.get(url) : link.iconTintColor,},]),),- [links],+ [chipForegrounds, links],);return { linkVariants, linkPillContent };}