@devries-cameron20 / t3code Mirror · read-only / commits / cdaaa742c9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 22:00 UTC

fix(mobile): chat chips match desktop and the composer again (#22169)

oliver committed Oct 20, 2026 at 10:03 UTC cdaaa742c9cf0637b80c4bb5d7fe2c1c26b64b63
28 files changed +402 -90
apps/mobile/assets/context-chip-icons/circle-dashed.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/circle-dashed.png differ
apps/mobile/assets/context-chip-icons/film.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/film.png differ
apps/mobile/assets/context-chip-icons/git-merge.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-merge.png differ
apps/mobile/assets/context-chip-icons/git-pull-request-arrow.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-pull-request-arrow.png differ
apps/mobile/assets/context-chip-icons/git-pull-request-closed.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-pull-request-closed.png differ
apps/mobile/assets/context-chip-icons/git-pull-request-draft.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/git-pull-request-draft.png differ
apps/mobile/assets/context-chip-icons/image.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/image.png differ
apps/mobile/assets/context-chip-icons/message-circle.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/message-circle.png differ
apps/mobile/assets/context-chip-icons/messages-square.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/messages-square.png differ
apps/mobile/assets/context-chip-icons/mouse-pointer-click.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/mouse-pointer-click.png differ
apps/mobile/assets/context-chip-icons/skill.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/skill.png differ
apps/mobile/assets/context-chip-icons/terminal.png
Binary files /dev/null and b/apps/mobile/assets/context-chip-icons/terminal.png differ
apps/mobile/package.json
+1
@@ -40,6 +40,7 @@
40 "config:preview": "APP_VARIANT=preview expo config",
41 "config:prod": "APP_VARIANT=production expo config",
42 "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
43 + "sync:chip-icons": "node scripts/sync-context-chip-icons.mjs",
44 "sync:pierre-icons": "node scripts/sync-pierre-file-icons.mjs",
45 "measure-renders": "node scripts/measure-renders.mts",
46 "generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",
apps/mobile/scripts/sync-context-chip-icons.mjs new
+93
@@ -0,0 +1,93 @@
1 +import * as NodeFS from "node:fs";
2 +import * as NodeModule from "node:module";
3 +import * as NodePath from "node:path";
4 +import * as NodeURL from "node:url";
5 +
6 +const scriptDirectory = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
7 +const appDirectory = NodePath.resolve(scriptDirectory, "..");
8 +const repositoryRoot = NodePath.resolve(appDirectory, "../..");
9 +const outputDirectory = NodePath.join(appDirectory, "assets/context-chip-icons");
10 +const generatedModulePath = NodePath.join(appDirectory, "src/lib/contextChipIcons.generated.ts");
11 +
12 +const requireFromWeb = NodeModule.createRequire(
13 + NodePath.join(repositoryRoot, "apps/web/package.json"),
14 +);
15 +const requireFromScripts = NodeModule.createRequire(
16 + NodePath.join(repositoryRoot, "scripts/package.json"),
17 +);
18 +const sharp = requireFromScripts("sharp");
19 +const lucideIconsDirectory = NodePath.join(
20 + NodePath.dirname(requireFromWeb.resolve("lucide-react/package.json")),
21 + "dist/esm/icons",
22 +);
23 +const webChipSource = NodeFS.readFileSync(
24 + NodePath.join(repositoryRoot, "apps/web/src/components/composerInlineChip.ts"),
25 + "utf8",
26 +);
27 +const skillSvg = webChipSource.match(/SKILL_CHIP_ICON_SVG = `([\s\S]*?)`;/)?.[1];
28 +
29 +if (!skillSvg) {
30 + throw new Error(
31 + "Could not read SKILL_CHIP_ICON_SVG from apps/web/src/components/composerInlineChip.ts",
32 + );
33 +}
34 +
35 +const lucideIcons = [
36 + "circle-dashed",
37 + "film",
38 + "git-merge",
39 + "git-pull-request-arrow",
40 + "git-pull-request-closed",
41 + "git-pull-request-draft",
42 + "image",
43 + "message-circle",
44 + "messages-square",
45 + "mouse-pointer-click",
46 + "terminal",
47 +];
48 +
49 +async function lucideSvg(name) {
50 + const module = await import(
51 + NodeURL.pathToFileURL(NodePath.join(lucideIconsDirectory, `${name}.js`)).href
52 + );
53 + const body = module.__iconNode
54 + .map(([tag, { key: _key, ...attributes }]) => {
55 + const attributeText = Object.entries(attributes)
56 + .map(([attribute, value]) => `${attribute}="${value}"`)
57 + .join(" ");
58 + return `<${tag} ${attributeText}/>`;
59 + })
60 + .join("");
61 + return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
62 +}
63 +
64 +async function renderIcon(token, svg) {
65 + const sized = svg
66 + .replace(/^<svg[^>]*?>/, (tag) =>
67 + tag
68 + .replace(/ (?:width|height)="[^"]*"/g, "")
69 + .replace("<svg ", '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" '),
70 + )
71 + .replaceAll("currentColor", "#ffffff");
72 + await sharp(Buffer.from(sized), { density: 72 * (64 / 24) })
73 + .resize(64, 64)
74 + .png()
75 + .toFile(NodePath.join(outputDirectory, `${token}.png`));
76 +}
77 +
78 +NodeFS.rmSync(outputDirectory, { recursive: true, force: true });
79 +NodeFS.mkdirSync(outputDirectory, { recursive: true });
80 +
81 +for (const name of lucideIcons) {
82 + await renderIcon(name, await lucideSvg(name));
83 +}
84 +await renderIcon("skill", skillSvg);
85 +
86 +const tokens = [...lucideIcons, "skill"].sort();
87 +const generatedSource = `import type { ImageSourcePropType } from "react-native";\n\nexport const CONTEXT_CHIP_ICON_SOURCES = {\n${tokens
88 + .map(
89 + (token) =>
90 + ` ${/^\w+$/.test(token) ? token : `"${token}"`}: require("../../assets/context-chip-icons/${token}.png"),`,
91 + )
92 + .join("\n")}\n} as const satisfies Readonly<Record<string, ImageSourcePropType>>;\n`;
93 +NodeFS.writeFileSync(generatedModulePath, generatedSource);
apps/mobile/src/features/files/FileMarkdownPreview.tsx
-1
@@ -57,7 +57,6 @@ export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
57 codeBackgroundColor: codeBackground,
58 codeBlockBackgroundColor: codeBackground,
59 fileTextColor: codeText,
60 - skillTextColor: codeText,
60 quoteMarkerColor: blockquoteBorder,
61 dividerColor: horizontalRule,
62 fontSize: nativeMarkdownTypography.fontSize,
apps/mobile/src/features/threads/ThreadFeed.tsx
+4 -14
@@ -3,8 +3,8 @@ import * as Dialog from "../../components/ui/Dialog";
3 import { useOpenPullRequest } from "../../native/useOpenPullRequest";
4 import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
5 import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
6 +import { enrichedContextLinkCustomization } from "../../native/useEnrichedLinkVariants";
7 import {
7 - enrichedContextLinkPresentation,
8 enrichedSkillDisplayName,
9 enrichedSkillInstructionsPath,
10 enrichedSkillReference,
@@ -169,7 +169,6 @@ import {
169 resolveNativeMarkdownTypography,
170 } from "../../lib/appearancePreferences";
171 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
172 -import { markdownFileIconSource } from "../../lib/markdownFileIcons";
172 import { PierreEntryIcon } from "../../components/PierreEntryIcon";
173 import { markdownLinkIconSource } from "../../lib/markdownLinkIcons";
174 import {
@@ -866,8 +865,6 @@ function useMarkdownStyles(): MarkdownStyleSets {
865 const markdownUserCodeText = theme["--color-md-user-code-text"];
866 const markdownUserInlineCodeText = theme["--color-user-bubble-foreground-muted"];
867 const markdownUserFenceBg = theme["--color-md-user-fence-bg"];
869 - const inlineSkillForeground = theme["--color-inline-skill-foreground"];
870 - const userBubbleSkillForeground = theme["--color-user-bubble-skill-foreground"];
868 const regularFontFamily = FONT_FAMILIES.regular;
869 const boldFontFamily = FONT_FAMILIES.bold;
870
@@ -884,7 +881,6 @@ function useMarkdownStyles(): MarkdownStyleSets {
881 codeBackgroundColor: markdownUserCodeBg,
882 codeBlockBackgroundColor: markdownUserFenceBg,
883 fileTextColor: markdownUserBodyColor,
887 - skillTextColor: userBubbleSkillForeground,
884 quoteMarkerColor: markdownUserBodyColor,
885 dividerColor: markdownUserBodyColor,
886 contextChipBorderColor,
@@ -907,7 +903,6 @@ function useMarkdownStyles(): MarkdownStyleSets {
903 codeBackgroundColor: markdownCodeBg,
904 codeBlockBackgroundColor: markdownCodeBg,
905 fileTextColor: markdownCodeText,
910 - skillTextColor: inlineSkillForeground,
906 quoteMarkerColor: markdownBlockquoteBorder,
907 dividerColor: markdownHrColor,
908 contextChipBorderColor,
@@ -923,7 +918,6 @@ function useMarkdownStyles(): MarkdownStyleSets {
918 }, [
919 boldFontFamily,
920 contextChipBorderColor,
926 - inlineSkillForeground,
921 markdownBlockquoteBorder,
922 markdownBodyColor,
923 markdownCodeBg,
@@ -939,7 +933,6 @@ function useMarkdownStyles(): MarkdownStyleSets {
933 markdownUserInlineCodeText,
934 nativeMarkdownTypography,
935 regularFontFamily,
942 - userBubbleSkillForeground,
936 ]);
937 }
938
@@ -1566,12 +1559,9 @@ function UserMessageContent(props: UserMessageContentProps) {
1559 });
1560 }
1561 },
1569 - linkCustomization: (href) => {
1570 - const presentation = enrichedContextLinkPresentation(href, props.context?.records);
1571 - return presentation
1572 - ? { color: presentation.color, icon: markdownFileIconSource(presentation.icon) }
1573 - : props.linkHandlers.linkCustomization?.(href);
1574 - },
1562 + linkCustomization: (href) =>
1563 + enrichedContextLinkCustomization(href, props.context?.records ?? []) ??
1564 + props.linkHandlers.linkCustomization?.(href),
1565 }}
1566 />
1567 {selected ? (
apps/mobile/src/lib/composerChipPresentation.test.ts
+29 -5
@@ -21,24 +21,24 @@ describe("contextChipPresentation image detection", () => {
21 const { contextChipPresentation } = await import("./composerChipPresentation");
22 expect(
23 contextChipPresentation("file", { kind: "file", name: "IMG_4997.PNG", mimeType: "" }),
24 - ).toEqual({ accent: "#d55665", symbol: "photo" });
24 + ).toEqual({ accent: "#d55665", symbol: "photo", icon: "image" });
25 expect(
26 contextChipPresentation("file", {
27 kind: "file",
28 name: "shot",
29 mimeType: "image/jpeg",
30 }),
31 - ).toEqual({ accent: "#d55665", symbol: "photo" });
31 + ).toEqual({ accent: "#d55665", symbol: "photo", icon: "image" });
32 });
33
34 it("leaves genuine documents and videos alone", async () => {
35 const { contextChipPresentation } = await import("./composerChipPresentation");
36 expect(
37 contextChipPresentation("file", { kind: "file", name: "notes.txt", mimeType: "text/plain" }),
38 - ).toEqual({ accent: "#0090cd", symbol: "doc" });
38 + ).toEqual({ accent: "#0090cd", symbol: "doc", icon: null });
39 expect(
40 contextChipPresentation("file", { kind: "file", name: "clip.mp4", mimeType: "video/mp4" }),
41 - ).toEqual({ accent: "#d06217", symbol: "play.rectangle" });
41 + ).toEqual({ accent: "#d06217", symbol: "play.rectangle", icon: "film" });
42 });
43 });
44
@@ -59,7 +59,7 @@ describe("pull request chip status", () => {
59 expect((await chip("closed")).accent).toBe("#d55665");
60 });
61
62 - it("keeps one glyph across every state, so only colour carries the status", async () => {
62 + it("keeps one composer glyph across every state, so only colour carries the status", async () => {
63 const symbols = await Promise.all(
64 [chip("open"), chip("open", true), chip("merged"), chip("closed")].map(
65 async (pending) => (await pending).symbol,
@@ -68,6 +68,13 @@ describe("pull request chip status", () => {
68 expect(new Set(symbols)).toEqual(new Set(["git-pull-request"]));
69 });
70
71 + it("gives message chips web's per-state pull request glyphs", async () => {
72 + expect((await chip("open")).icon).toBe("git-pull-request-arrow");
73 + expect((await chip("open", true)).icon).toBe("git-pull-request-draft");
74 + expect((await chip("merged")).icon).toBe("git-merge");
75 + expect((await chip("closed")).icon).toBe("git-pull-request-closed");
76 + });
77 +
78 it("falls back to the generic pull request chip when the state is unknown", async () => {
79 const { contextChipPresentation } = await import("./composerChipPresentation");
80 expect(
@@ -78,3 +85,20 @@ describe("pull request chip status", () => {
85 ).toBe("#7079e4");
86 });
87 });
88 +
89 +describe("context chip kinds", () => {
90 + it("gives thread context its own teal chip instead of the file style", async () => {
91 + const { contextChipPresentation } = await import("./composerChipPresentation");
92 + expect(contextChipPresentation("thread")).toMatchObject({
93 + accent: "#009c96",
94 + icon: "messages-square",
95 + });
96 + });
97 +
98 + it("shows unknown kinds as a neutral chip rather than a file", async () => {
99 + const { contextChipPresentation } = await import("./composerChipPresentation");
100 + const presentation = contextChipPresentation("future-kind");
101 + expect(presentation.accent).toBeUndefined();
102 + expect(presentation.icon).toBe("circle-dashed");
103 + });
104 +});
apps/mobile/src/lib/composerChipPresentation.ts
+48 -19
@@ -1,22 +1,51 @@
1 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
2 import { imageMimeType } from "@t3tools/shared/image";
3 import { videoMimeType } from "@t3tools/shared/video";
4 +
5 +import type { CONTEXT_CHIP_ICON_SOURCES } from "./contextChipIcons.generated";
6 +
7 +export type ContextChipIcon = keyof typeof CONTEXT_CHIP_ICON_SOURCES;
8 +
9 +interface ContextChipPresentation {
10 + readonly accent?: string;
11 + readonly symbol: string;
12 + readonly icon: ContextChipIcon | null;
13 +}
14 +
15 /**
16 * These are the sRGB form of the same OKLCH set web uses, so a chip looks the same on every
6 - * surface. See `composerInlineChip.ts`.
17 + * surface. See `ContextChip.tsx`.
18 */
19 const CONTEXT_CHIP_PRESENTATIONS = {
9 - image: { accent: "#d55665", symbol: "photo" },
10 - video: { accent: "#d06217", symbol: "play.rectangle" },
11 - file: { accent: "#0090cd", symbol: "doc" },
12 - mention: { accent: "#0096af", symbol: "doc" },
13 - terminal: { accent: "#009f6e", symbol: "terminal" },
14 - element: { accent: "#b87501", symbol: "cursorarrow.click" },
15 - "preview-annotation": { accent: "#b87501", symbol: "cursorarrow.click" },
16 - "review-comment": { accent: "#8a70dd", symbol: "text.bubble" },
17 - "pull-request": { accent: "#7079e4", symbol: "git-pull-request" },
18 - skill: { accent: "#b261be", symbol: "cube" },
19 -} as const;
20 + image: { accent: "#d55665", symbol: "photo", icon: "image" },
21 + video: { accent: "#d06217", symbol: "play.rectangle", icon: "film" },
22 + file: { accent: "#0090cd", symbol: "doc", icon: null },
23 + mention: { accent: "#0096af", symbol: "doc", icon: null },
24 + terminal: { accent: "#009f6e", symbol: "terminal", icon: "terminal" },
25 + element: { accent: "#b87501", symbol: "cursorarrow.click", icon: "mouse-pointer-click" },
26 + "preview-annotation": {
27 + accent: "#b87501",
28 + symbol: "cursorarrow.click",
29 + icon: "mouse-pointer-click",
30 + },
31 + "review-comment": { accent: "#8a70dd", symbol: "text.bubble", icon: "message-circle" },
32 + "pull-request": {
33 + accent: "#7079e4",
34 + symbol: "git-pull-request",
35 + icon: "git-pull-request-arrow",
36 + },
37 + skill: { accent: "#b261be", symbol: "cube", icon: "skill" },
38 + thread: {
39 + accent: "#009c96",
40 + symbol: "bubble.left.and.bubble.right",
41 + icon: "messages-square",
42 + },
43 +} as const satisfies Record<string, ContextChipPresentation>;
44 +
45 +export const UNAVAILABLE_CONTEXT_CHIP_PRESENTATION: ContextChipPresentation = {
46 + symbol: "doc",
47 + icon: "circle-dashed",
48 +};
49
50 export function composerChipSizeSuffix(record?: {
51 readonly kind?: string;
@@ -27,11 +56,11 @@ export function composerChipSizeSuffix(record?: {
56 }
57
58 const PULL_REQUEST_CHIP_PRESENTATIONS = {
30 - open: { accent: "#009f6e", symbol: "git-pull-request" },
31 - draft: { accent: "#7f8793", symbol: "git-pull-request" },
32 - merged: { accent: "#8a70dd", symbol: "git-pull-request" },
33 - closed: { accent: "#d55665", symbol: "git-pull-request" },
34 -} as const;
59 + open: { accent: "#009f6e", symbol: "git-pull-request", icon: "git-pull-request-arrow" },
60 + draft: { accent: "#7f8793", symbol: "git-pull-request", icon: "git-pull-request-draft" },
61 + merged: { accent: "#8a70dd", symbol: "git-pull-request", icon: "git-merge" },
62 + closed: { accent: "#d55665", symbol: "git-pull-request", icon: "git-pull-request-closed" },
63 +} as const satisfies Record<string, ContextChipPresentation>;
64
65 export function contextChipPresentation(
66 kind: string,
@@ -45,7 +74,7 @@ export function contextChipPresentation(
74 readonly isDraft?: boolean;
75 };
76 },
48 -) {
77 +): ContextChipPresentation {
78 const presentationKind =
79 kind === "file" &&
80 videoMimeType({
@@ -71,5 +100,5 @@ export function contextChipPresentation(
100 }
101 return Object.hasOwn(CONTEXT_CHIP_PRESENTATIONS, presentationKind)
102 ? CONTEXT_CHIP_PRESENTATIONS[presentationKind as keyof typeof CONTEXT_CHIP_PRESENTATIONS]
74 - : CONTEXT_CHIP_PRESENTATIONS.file;
103 + : UNAVAILABLE_CONTEXT_CHIP_PRESENTATION;
104 }
apps/mobile/src/lib/contextChipIcons.generated.ts new
+16
@@ -0,0 +1,16 @@
1 +import type { ImageSourcePropType } from "react-native";
2 +
3 +export const CONTEXT_CHIP_ICON_SOURCES = {
4 + "circle-dashed": require("../../assets/context-chip-icons/circle-dashed.png"),
5 + film: require("../../assets/context-chip-icons/film.png"),
6 + "git-merge": require("../../assets/context-chip-icons/git-merge.png"),
7 + "git-pull-request-arrow": require("../../assets/context-chip-icons/git-pull-request-arrow.png"),
8 + "git-pull-request-closed": require("../../assets/context-chip-icons/git-pull-request-closed.png"),
9 + "git-pull-request-draft": require("../../assets/context-chip-icons/git-pull-request-draft.png"),
10 + image: require("../../assets/context-chip-icons/image.png"),
11 + "message-circle": require("../../assets/context-chip-icons/message-circle.png"),
12 + "messages-square": require("../../assets/context-chip-icons/messages-square.png"),
13 + "mouse-pointer-click": require("../../assets/context-chip-icons/mouse-pointer-click.png"),
14 + skill: require("../../assets/context-chip-icons/skill.png"),
15 + terminal: require("../../assets/context-chip-icons/terminal.png"),
16 +} as const satisfies Readonly<Record<string, ImageSourcePropType>>;
apps/mobile/src/lib/enrichedLinkPresentation.test.ts
+49 -12
@@ -1,5 +1,9 @@
1 import { describe, expect, it } from "vite-plus/test";
2 -import type { ComposerContextId, ReviewCommentContextRecord } from "@t3tools/contracts";
2 +import type {
3 + ComposerContextId,
4 + ComposerContextRecord,
5 + ReviewCommentContextRecord,
6 +} from "@t3tools/contracts";
7 import {
8 enrichedContextLinkPresentation,
9 enrichedLinkVariantPattern,
@@ -108,25 +112,58 @@ describe("Enriched link presentation", () => {
112 };
113 expect(
114 enrichedContextLinkPresentation("t3-context://v1/review-comment/review_1", [record]),
111 - ).toEqual({ color: "#8a70dd", icon: "git" });
112 - expect(
113 - enrichedContextLinkPresentation("t3-context://v1/review-comment/review_2", [record]),
114 - ).toEqual({ color: "#8a70dd", icon: "markdown" });
115 + ).toEqual({ accent: "#8a70dd", icon: { kind: "chip", name: "git-merge" } });
116 });
117
117 - it("retains recognizable presentation for unavailable and future context kinds", () => {
118 + it("shows a context the message no longer carries as an unavailable chip", () => {
119 + expect(enrichedContextLinkPresentation("t3-context://v1/terminal/missing", [])).toEqual({
120 + icon: { kind: "chip", name: "circle-dashed" },
121 + });
122 + });
123 +
124 + it("keeps each kind's own look when no records are known", () => {
125 expect(enrichedContextLinkPresentation("t3-context://v1/terminal/missing")).toEqual({
119 - color: "#009f6e",
120 - icon: "bash",
126 + accent: "#009f6e",
127 + icon: { kind: "chip", name: "terminal" },
128 });
129 expect(enrichedContextLinkPresentation("t3-context://v1/skill/missing")).toEqual({
123 - color: "#b261be",
124 - icon: "mcp",
130 + accent: "#b261be",
131 + icon: { kind: "chip", name: "skill" },
132 });
133 expect(enrichedContextLinkPresentation("t3-context://v1/future/missing")).toEqual({
127 - color: "#0090cd",
128 - icon: "default",
134 + icon: { kind: "chip", name: "circle-dashed" },
135 });
136 expect(enrichedContextLinkPresentation("https://example.com/terminal/missing")).toBeUndefined();
137 });
138 +
139 + it("uses the file-type icon and size for attachments and mentions", () => {
140 + const records: ReadonlyArray<ComposerContextRecord> = [
141 + {
142 + version: 1,
143 + contextId: "file_1" as ComposerContextId,
144 + kind: "file",
145 + label: "notes.md",
146 + attachmentId: "attachment_1",
147 + name: "notes.md",
148 + mimeType: "text/markdown",
149 + sizeBytes: 2048,
150 + },
151 + {
152 + version: 1,
153 + contextId: "mention_1" as ComposerContextId,
154 + kind: "mention",
155 + label: "math.ts",
156 + path: "src/math.ts",
157 + },
158 + ];
159 + expect(enrichedContextLinkPresentation("t3-context://v1/file/file_1", records)).toEqual({
160 + accent: "#0090cd",
161 + icon: { kind: "file", name: "markdown" },
162 + label: "notes.md · 2 KB",
163 + });
164 + expect(enrichedContextLinkPresentation("t3-context://v1/mention/mention_1", records)).toEqual({
165 + accent: "#0096af",
166 + icon: { kind: "file", name: "typescript" },
167 + });
168 + });
169 });
apps/mobile/src/lib/enrichedLinkPresentation.ts
+23 -16
@@ -1,31 +1,38 @@
1 import type { ComposerContextRecord } from "@t3tools/contracts";
2 -import { contextChipPresentation } from "./composerChipPresentation";
3 -import type { MarkdownFileIcon } from "./markdownLinks";
2 +import {
3 + composerChipSizeSuffix,
4 + contextChipPresentation,
5 + type ContextChipIcon,
6 + UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,
7 +} from "./composerChipPresentation";
8 +import { resolveMarkdownFileIcon, type MarkdownFileIcon } from "./markdownLinks";
9 import type { SelectableMarkdownSkill } from "../native/SelectableMarkdownText.types";
10 import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
11
7 -const CONTEXT_ICONS: Readonly<Record<string, MarkdownFileIcon>> = {
8 - photo: "image",
9 - "play.rectangle": "video",
10 - terminal: "bash",
11 - "cursorarrow.click": "react",
12 - "text.bubble": "markdown",
13 - "git-pull-request": "git",
14 - cube: "mcp",
15 - doc: "default",
16 -};
12 +export type EnrichedChipIcon =
13 + | { readonly kind: "chip"; readonly name: ContextChipIcon }
14 + | { readonly kind: "file"; readonly name: MarkdownFileIcon };
15
16 export function enrichedContextLinkPresentation(
17 href: string,
18 records?: ReadonlyArray<ComposerContextRecord>,
21 -) {
19 +): { accent?: string; icon: EnrichedChipIcon; label?: string } | undefined {
20 const reference = parseComposerContextHref(href);
21 if (!reference) return undefined;
22 const record = records?.find((candidate) => candidate.contextId === reference.contextId);
25 - const presentation = contextChipPresentation(reference.kind, record);
23 + const presentation =
24 + records && !record
25 + ? UNAVAILABLE_CONTEXT_CHIP_PRESENTATION
26 + : contextChipPresentation(reference.kind, record);
27 + const size = composerChipSizeSuffix(record);
28 + const fileName =
29 + record && "path" in record ? record.path : record && "name" in record ? record.name : "";
30 return {
27 - color: presentation.accent,
28 - icon: CONTEXT_ICONS[presentation.symbol] ?? "default",
31 + ...(presentation.accent ? { accent: presentation.accent } : {}),
32 + icon: presentation.icon
33 + ? { kind: "chip", name: presentation.icon }
34 + : { kind: "file", name: resolveMarkdownFileIcon(fileName) },
35 + ...(record && size ? { label: `${record.label} · ${size}` } : {}),
36 };
37 }
38
apps/mobile/src/lib/markdownDocument.ts
+31
@@ -140,6 +140,37 @@ export function markdownWithHtml(markdown: string): string {
140 return markdown;
141 }
142
143 +const INLINE_CODE_SPAN = /`+([^`\r\n]+)`+/g;
144 +
145 +export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
146 + if (![...markdown.matchAll(INLINE_CODE_SPAN)].some(([, code]) => fileLink.test(code!.trim())))
147 + return markdown;
148 + const edits: Array<{ start: number; end: number; content: string }> = [];
149 + const visit = (node: MarkdownNode) => {
150 + if (node.type === "inlineCode") {
151 + const start = node.position?.start.offset;
152 + const end = node.position?.end.offset;
153 + const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
154 + if (
155 + start !== undefined &&
156 + end !== undefined &&
157 + fileLink.test(node.value) &&
158 + !/[<>]/.test(node.value)
159 + )
160 + edits.push({
161 + start,
162 + end,
163 + content: `[${escaped}](<${escaped}>)`,
164 + });
165 + } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
166 + node.children.forEach(visit);
167 + };
168 + visit(parser.parse(markdown));
169 + for (const edit of edits.reverse())
170 + markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
171 + return markdown;
172 +}
173 +
174 // A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
175 function isTableDelimiterRow(line: string): boolean {
176 if (!line.includes("-")) return false;
apps/mobile/src/lib/markdownInlineFileLinks.test.ts new
+39
@@ -0,0 +1,39 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";
3 +import { markdownWithInlineFileLinks, parseMarkdownDocument } from "./markdownDocument";
4 +
5 +const rewrite = (markdown: string) =>
6 + markdownWithInlineFileLinks(markdown, ENRICHED_INLINE_FILE_LINK_REGEX);
7 +
8 +describe("inline code that names a file", () => {
9 + it("becomes a link to the same path", () => {
10 + expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(
11 + "See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).",
12 + );
13 + });
14 +
15 + it("keeps commands, identifiers and URLs as code", () => {
16 + const markdown = "Run `vp test run`, call `useMemo`, open `https://example.com/a.ts`.";
17 + expect(rewrite(markdown)).toBe(markdown);
18 + });
19 +
20 + it("leaves fenced code blocks and code already inside a link alone", () => {
21 + const markdown = "```\nsrc/math.ts:2\n```\n\n[`src/math.ts`](src/math.ts)";
22 + expect(rewrite(markdown)).toBe(markdown);
23 + });
24 +
25 + it("handles double-backtick spans", () => {
26 + expect(rewrite("Open ``src/math.ts`` now.")).toBe("Open [src/math.ts](<src/math.ts>) now.");
27 + });
28 +
29 + it("links to the exact path when it holds backslashes or ampersands", () => {
30 + for (const path of ["C:\\repo\\_private\\file.ts", "./src/a&copy;.ts", "./src/[id].ts"]) {
31 + const paragraph = parseMarkdownDocument(rewrite(`\`${path}\``)).children[0];
32 + const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
33 + expect(link?.type === "link" && link.url).toBe(path);
34 + expect(
35 + link?.type === "link" && link.children[0]?.type === "text" && link.children[0].value,
36 + ).toBe(path);
37 + }
38 + });
39 +});
apps/mobile/src/lib/markdownLinks.test.ts
+3 -3
@@ -51,7 +51,7 @@ describe("resolveMarkdownLinkPresentation", () => {
51 kind: "file",
52 href,
53 icon: "typescript",
54 - label: "main.ts:42:7",
54 + label: "main.ts · L42:C7",
55 path,
56 line: 42,
57 column: 7,
@@ -63,7 +63,7 @@ describe("resolveMarkdownLinkPresentation", () => {
63 kind: "file",
64 href: "apps/mobile/src/index.ts:10",
65 icon: "typescript",
66 - label: "index.ts:10",
66 + label: "index.ts · L10",
67 path: "apps/mobile/src/index.ts",
68 line: 10,
69 });
@@ -107,7 +107,7 @@ describe("resolveMarkdownLinkPresentation", () => {
107 path: "src/main.ts",
108 line: 18,
109 column: 2,
110 - label: "main.ts:18:2",
110 + label: "main.ts · L18:C2",
111 });
112 });
113
apps/mobile/src/lib/markdownLinks.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { fileBasename } from "@t3tools/shared/path";
2 -import { formatFilePathPosition } from "@t3tools/shared/fileLinks";
2 +import { fileLinkLabel } from "@t3tools/shared/fileLinks";
3 import {
4 inlineCodeFilePathCandidate,
5 normalizeMarkdownLinkDestination,
@@ -279,7 +279,7 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
279 kind: "file",
280 href: normalized,
281 icon: resolveMarkdownFileIcon(target.path),
282 - label: fileBasename(formatFilePathPosition(target)),
282 + label: fileLinkLabel(target, new Map()),
283 path: target.path,
284 ...(target.line ? { line: target.line } : {}),
285 ...(target.column ? { column: target.column } : {}),
apps/mobile/src/native/EnrichedMarkdownText.tsx
+12 -3
@@ -4,7 +4,11 @@ import {
4 formatComposerContextHref,
5 formatComposerContextReference,
6 } from "@t3tools/shared/composerContextReferences";
7 -import { markdownWithHtml, markdownWithTableBreaks } from "../lib/markdownDocument";
7 +import {
8 + markdownWithHtml,
9 + markdownWithInlineFileLinks,
10 + markdownWithTableBreaks,
11 +} from "../lib/markdownDocument";
12 import { useCallback, useMemo, useState, type ReactNode } from "react";
13 import { Platform, Share, StyleSheet, View } from "react-native";
14 import {
@@ -151,7 +155,13 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
155 const { renderImage, resolveImageSource } = props;
156 const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
157 const markdown = useMemo(
154 - () => markdownWithTableBreaks(markdownWithHtml(props.markdown)),
158 + () =>
159 + markdownWithTableBreaks(
160 + markdownWithInlineFileLinks(
161 + markdownWithHtml(props.markdown),
162 + ENRICHED_INLINE_FILE_LINK_REGEX,
163 + ),
164 + ),
165 [props.markdown],
166 );
167 const [documentAssets, setDocumentAssets] = useState<DocumentAssetsEvent["assets"]>([]);
@@ -178,7 +188,6 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
188 const linkRecognition = useMemo(
189 () => ({
190 text: enrichedSkillLinkRegex(props.skills) ?? undefined,
181 - inlineCode: ENRICHED_INLINE_FILE_LINK_REGEX,
191 }),
192 [props.skills],
193 );
apps/mobile/src/native/SelectableMarkdownText.types.ts
+1 -1
@@ -10,7 +10,6 @@ export interface NativeMarkdownTextStyle {
10 readonly codeBackgroundColor: string;
11 readonly codeBlockBackgroundColor: string;
12 readonly fileTextColor: string;
13 - readonly skillTextColor: string;
13 readonly quoteMarkerColor: string;
14 readonly dividerColor: string;
15 readonly contextChipBorderColor?: string;
@@ -64,6 +63,7 @@ export interface MarkdownLinkCustomization {
63 readonly color?: string;
64 readonly label?: string;
65 readonly icon?: import("react-native").ImageSourcePropType;
66 + readonly chip?: { readonly accent?: string; readonly tintsIcon: boolean };
67 }
68
69 export interface SelectableMarkdownTextProps {
apps/mobile/src/native/useEnrichedLinkVariants.ts
+51 -14
@@ -5,38 +5,65 @@ import type {
5 MarkdownDocumentAsset,
6 MarkdownStyle,
7 } from "react-native-enriched-markdown";
8 +import type { ComposerContextRecord } from "@t3tools/contracts";
9 +import { contextChipPresentation } from "../lib/composerChipPresentation";
10 +import { CONTEXT_CHIP_ICON_SOURCES } from "../lib/contextChipIcons.generated";
11 +import { FONT_FAMILIES } from "../lib/fontFamilies";
12 import { markdownFileIconSource } from "../lib/markdownFileIcons";
13 import { markdownLinkIconSource } from "../lib/markdownLinkIcons";
14 import { resolveMarkdownLinkIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
11 -import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types";
15 +import type {
16 + MarkdownLinkCustomization,
17 + SelectableMarkdownTextProps,
18 +} from "./SelectableMarkdownText.types";
19 import {
20 enrichedContextLinkPresentation,
21 enrichedLinkVariantPattern,
22 enrichedSkillDisplayName,
23 enrichedSkillReference,
24 + type EnrichedChipIcon,
25 } from "../lib/enrichedLinkPresentation";
26
27 +function chipIconSource(icon: EnrichedChipIcon) {
28 + return icon.kind === "chip"
29 + ? CONTEXT_CHIP_ICON_SOURCES[icon.name]
30 + : markdownFileIconSource(icon.name);
31 +}
32 +
33 +export function enrichedContextLinkCustomization(
34 + href: string,
35 + records?: ReadonlyArray<ComposerContextRecord>,
36 +): MarkdownLinkCustomization | undefined {
37 + const context = enrichedContextLinkPresentation(href, records);
38 + if (!context) return undefined;
39 + return {
40 + label: context.label,
41 + icon: chipIconSource(context.icon),
42 + chip: { accent: context.accent, tintsIcon: context.icon.kind === "chip" },
43 + };
44 +}
45 +
46 function presentation(
47 url: string,
48 props: Pick<SelectableMarkdownTextProps, "linkCustomization" | "skills" | "textStyle">,
22 -) {
49 +): MarkdownLinkCustomization | undefined {
50 const custom = props.linkCustomization?.(url);
51 if (custom) return custom;
25 - const context = enrichedContextLinkPresentation(url);
26 - if (context) return { color: context.color, icon: markdownFileIconSource(context.icon) };
52 + const context = enrichedContextLinkCustomization(url);
53 + if (context) return context;
54 const skill = enrichedSkillReference(url, props.skills);
55 if (skill)
56 return {
30 - color: props.textStyle.skillTextColor,
57 label: enrichedSkillDisplayName(skill),
32 - icon: markdownFileIconSource("mcp"),
58 + icon: CONTEXT_CHIP_ICON_SOURCES.skill,
59 + chip: { accent: contextChipPresentation("skill").accent, tintsIcon: true },
60 };
61 const link = resolveMarkdownLinkPresentation(url);
62 if (link.kind === "file")
63 return {
37 - color: props.textStyle.fileTextColor,
64 label: link.label,
65 icon: markdownFileIconSource(link.icon),
66 + chip: { accent: contextChipPresentation("mention").accent, tintsIcon: false },
67 };
68 const icon = link.kind === "external" ? resolveMarkdownLinkIcon(link.host) : null;
69 return icon
@@ -54,7 +81,7 @@ export function useEnrichedLinkVariants(
81 ) {
82 const { linkCustomization, skills, textStyle } = props;
83 const links = useMemo(() => {
57 - const byUrl = new Map<string, NonNullable<ReturnType<typeof presentation>>>();
84 + const byUrl = new Map<string, MarkdownLinkCustomization>();
85 for (const asset of assets) {
86 if (asset.kind !== "link" || byUrl.has(asset.url)) continue;
87 const value = presentation(asset.url, { linkCustomization, skills, textStyle });
@@ -62,11 +89,21 @@ export function useEnrichedLinkVariants(
89 }
90 return byUrl;
91 }, [assets, linkCustomization, skills, textStyle]);
92 + const chipForegrounds = useMemo(
93 + () =>
94 + new Map(
95 + [...links].map(([url, link]) => [
96 + url,
97 + link.chip ? (link.chip.accent ?? textStyle.color) : undefined,
98 + ]),
99 + ),
100 + [links, textStyle],
101 + );
102 const linkVariants = useMemo<MarkdownStyle["linkVariants"]>(
103 () =>
104 Object.fromEntries(
105 [...links].map(([url, link]) => {
69 - const color = link.color ?? textStyle.fileTextColor;
106 + const chipForeground = chipForegrounds.get(url);
107 return [
108 enrichedLinkVariantPattern(url),
109 {
@@ -77,15 +114,15 @@ export function useEnrichedLinkVariants(
114 paddingHorizontal: 5,
115 paddingVertical: 2,
116 },
80 - fontFamily: textStyle.fontFamily,
81 - color,
117 + fontFamily: chipForeground ? FONT_FAMILIES.medium : textStyle.fontFamily,
118 + color: chipForeground ?? link.color ?? textStyle.fileTextColor,
119 underline: false,
120 backgroundColor: "transparent",
121 },
122 ];
123 }),
124 ),
88 - [links, textStyle],
125 + [chipForegrounds, links, textStyle],
126 );
127 const linkPillContent = useMemo<Record<string, LinkPillContent>>(
128 () =>
@@ -95,11 +132,11 @@ export function useEnrichedLinkVariants(
132 {
133 label: link.label,
134 iconUri: link.icon ? Image.resolveAssetSource(link.icon)?.uri : undefined,
98 - iconTintColor: link.iconTintColor,
135 + iconTintColor: link.chip?.tintsIcon ? chipForegrounds.get(url) : link.iconTintColor,
136 },
137 ]),
138 ),
102 - [links],
139 + [chipForegrounds, links],
140 );
141 return { linkVariants, linkPillContent };
142 }