Skip to content

Commit 18d2779

Browse files
Yuruzuuclaude
andcommitted
feat(web): links in the rich text composer look like links
Bare http(s) URLs in the rich text composer now render blue with the site's icon in front, matching how the sent message shows them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f7f9e21 commit 18d2779

8 files changed

Lines changed: 212 additions & 41 deletions

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 1 addition & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@ import {
5959
type ServerProviderSkill,
6060
type ThreadPullRequestKey,
6161
} from "@t3tools/contracts";
62-
import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
6362
import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
6463
import {
6564
isAtomCommandInterrupted,
@@ -161,7 +160,7 @@ import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
161160
import { fnv1a32 } from "../lib/diffRendering";
162161
import { LRUCache } from "../lib/lruCache";
163162
import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
164-
import { GitHubIcon } from "./Icons";
163+
import { MarkdownLinkFavicon } from "./chat/MarkdownLinkFavicon";
165164
import { createIncrementalHighlightedDocument } from "../lib/incrementalHighlighting";
166165
import { HighlightedCodeLines } from "./chat/HighlightedCodeLines";
167166
import { RenderErrorBoundary } from "./RenderErrorBoundary";
@@ -1255,45 +1254,6 @@ function normalizeMarkdownLinkHrefKey(href: string): string {
12551254
: rewrittenHref;
12561255
}
12571256

1258-
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
1259-
1260-
const failedFaviconHosts = new Set<string>();
1261-
1262-
function isGitHubHost(host: string): boolean {
1263-
const hostname = host.toLowerCase();
1264-
return hostname === "github.com" || hostname.endsWith(".github.com");
1265-
}
1266-
1267-
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
1268-
const [failedHost, setFailedHost] = useState<string | null>(null);
1269-
const brandIcon = isGitHubHost(host);
1270-
const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);
1271-
return (
1272-
<span
1273-
className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"
1274-
aria-hidden
1275-
>
1276-
{brandIcon ? (
1277-
<GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
1278-
) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
1279-
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
1280-
) : (
1281-
<img
1282-
src={faviconUrl}
1283-
alt=""
1284-
loading="lazy"
1285-
draggable={false}
1286-
className={cn(MARKDOWN_LINK_FAVICON_CLASS_NAME, "rounded-sm")}
1287-
onError={() => {
1288-
failedFaviconHosts.add(host);
1289-
setFailedHost(host);
1290-
}}
1291-
/>
1292-
)}
1293-
</span>
1294-
);
1295-
});
1296-
12971257
const CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME = "max-w-[min(100%,30rem)]";
12981258
const CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME = cn(
12991259
"max-h-[30rem]",

‎apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,22 @@ it.each([
149149
expect(textWithMark(editor, "code")).toEqual(code);
150150
});
151151

152+
it.each([true, false])("styles bare URLs as links (rich text: %s)", async (richTextEnabled) => {
153+
await using screen = await mountEditor(
154+
"see https://github.com/pingdotgg/t3code/pull/1. and `https://example.com`",
155+
richTextEnabled,
156+
);
157+
const links = Array.from(
158+
screen.container.querySelectorAll(".composer-link"),
159+
(link) => link.textContent,
160+
);
161+
expect(links).toEqual(richTextEnabled ? ["https://github.com/pingdotgg/t3code/pull/1"] : []);
162+
// github.com gets the brand icon rather than a fetched favicon.
163+
expect(screen.container.querySelectorAll(".ProseMirror-widget svg")).toHaveLength(
164+
richTextEnabled ? 1 : 0,
165+
);
166+
});
167+
152168
it("still italicizes text when typing a closing asterisk", async () => {
153169
await using screen = await mountEditor("clean *build");
154170
const { editor } = screen;

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
119119
import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView";
120120
import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal";
121121
import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight";
122+
import { ComposerLinkExtension } from "./composerLinkDecorations";
122123
import { importPastedComposerText } from "./composerInlineTokenPaste";
123124
import { didComposerSelectionChangeVisibly } from "./composerSelection";
124125
import type { ComposerDraftContextRecords } from "./composerContextPresentation";
@@ -861,6 +862,7 @@ function createComposerExtensions(richText: boolean) {
861862
? [
862863
ComposerItalicExtension,
863864
ComposerCodeExtension,
865+
ComposerLinkExtension,
864866
ComposerCodeBlockExtension.extend({
865867
addNodeView() {
866868
return ReactNodeViewRenderer(ComposerCodeBlockNodeView, {
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
2+
import { GlobeIcon } from "lucide-react";
3+
import { memo, useState } from "react";
4+
5+
import { cn } from "~/lib/utils";
6+
import { GitHubIcon } from "../Icons";
7+
8+
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
9+
10+
const failedFaviconHosts = new Set<string>();
11+
12+
function isGitHubHost(host: string): boolean {
13+
const hostname = host.toLowerCase();
14+
return hostname === "github.com" || hostname.endsWith(".github.com");
15+
}
16+
17+
export const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
18+
const [failedHost, setFailedHost] = useState<string | null>(null);
19+
const brandIcon = isGitHubHost(host);
20+
const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);
21+
return (
22+
<span
23+
className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"
24+
aria-hidden
25+
>
26+
{brandIcon ? (
27+
<GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
28+
) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
29+
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
30+
) : (
31+
<img
32+
src={faviconUrl}
33+
alt=""
34+
loading="lazy"
35+
draggable={false}
36+
className={cn(MARKDOWN_LINK_FAVICON_CLASS_NAME, "rounded-sm")}
37+
onError={() => {
38+
failedFaviconHosts.add(host);
39+
setFailedHost(host);
40+
}}
41+
/>
42+
)}
43+
</span>
44+
);
45+
});
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { Decoration, Extension } from "@tiptap/core";
2+
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
3+
import { ReactWidgetRenderer } from "@tiptap/react";
4+
5+
import { type ComposerLink, findComposerLinks } from "~/composer-links";
6+
import { MarkdownLinkFavicon } from "./chat/MarkdownLinkFavicon";
7+
8+
function collectComposerLinks(doc: ProseMirrorNode): ComposerLink[] {
9+
const links: ComposerLink[] = [];
10+
doc.descendants((node, pos) => {
11+
if (!node.isTextblock) return true;
12+
if (node.type.spec.code) return false;
13+
// A URL can span several text nodes (part of it bold, say), but not a
14+
// chip, a hard break, or inline code.
15+
let run = "";
16+
let runStart = 0;
17+
const flush = () => {
18+
for (const link of findComposerLinks(run)) {
19+
links.push({ from: runStart + link.from, to: runStart + link.to, host: link.host });
20+
}
21+
run = "";
22+
};
23+
node.forEach((child, offset) => {
24+
if (child.isText && !child.marks.some((mark) => mark.type.spec.code)) {
25+
if (run === "") runStart = pos + 1 + offset;
26+
run += child.text;
27+
} else {
28+
flush();
29+
}
30+
});
31+
flush();
32+
return false;
33+
});
34+
return links;
35+
}
36+
37+
/** Colors bare URLs like the sent message's links and leads each with its site icon. */
38+
export const ComposerLinkExtension = Extension.create({
39+
name: "composerLinks",
40+
addDecorations() {
41+
const editor = this.editor;
42+
return {
43+
create: ({ state }) => {
44+
const decorations: Decoration[] = [];
45+
const occurrencesByHost = new Map<string, number>();
46+
for (const link of collectComposerLinks(state.doc)) {
47+
// Widget keys must be unique and should not follow positions, or
48+
// typing before a link would remount its icon on every keystroke.
49+
const occurrence = occurrencesByHost.get(link.host) ?? 0;
50+
occurrencesByHost.set(link.host, occurrence + 1);
51+
decorations.push(
52+
ReactWidgetRenderer(MarkdownLinkFavicon, {
53+
editor,
54+
pos: link.from,
55+
key: `composer-link-favicon:${link.host}:${occurrence}`,
56+
props: { host: link.host },
57+
side: -1,
58+
}),
59+
Decoration.Inline(link.from, link.to, { class: "composer-link" }),
60+
);
61+
}
62+
return decorations;
63+
},
64+
};
65+
},
66+
});
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { findComposerLinks } from "./composer-links";
4+
5+
function linkTexts(text: string): string[] {
6+
return findComposerLinks(text).map(({ from, to }) => text.slice(from, to));
7+
}
8+
9+
describe("findComposerLinks", () => {
10+
it("finds http(s) URLs with their host", () => {
11+
const url = "https://github.com/pingdotgg/t3code/pull/22426#pullrequestreview-1";
12+
expect(findComposerLinks(`see ${url} now`)).toEqual([
13+
{ from: 4, to: 4 + url.length, host: "github.com" },
14+
]);
15+
});
16+
17+
it("drops trailing punctuation and unbalanced closing parens", () => {
18+
expect(
19+
linkTexts("(https://example.com/a), https://example.com/b. [x](https://example.com/c)"),
20+
).toEqual(["https://example.com/a", "https://example.com/b", "https://example.com/c"]);
21+
expect(linkTexts("https://en.wikipedia.org/wiki/Foo_(bar)!")).toEqual([
22+
"https://en.wikipedia.org/wiki/Foo_(bar)",
23+
]);
24+
});
25+
26+
it("matches GFM's boundaries and keeps quotes inside the path", () => {
27+
expect(
28+
linkTexts('[https://github.com] 1https://example.com/a\'b "https://example.com/c"'),
29+
).toEqual(["https://github.com", "https://example.com/a'b", "https://example.com/c"]);
30+
});
31+
32+
it("ignores URLs glued to a letter or without a host", () => {
33+
expect(linkTexts("xhttps://example.com https:// ftp://example.com")).toEqual([]);
34+
});
35+
36+
it("trims a long run of closing parens in linear time", () => {
37+
const parens = ")".repeat(200_000);
38+
expect(linkTexts(`https://example.com${parens}`)).toEqual(["https://example.com"]);
39+
});
40+
});

‎apps/web/src/composer-links.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { resolveExternalWebLinkHost } from "./components/chat/externalLinkContextMenu";
2+
3+
export interface ComposerLink {
4+
readonly from: number;
5+
readonly to: number;
6+
readonly host: string;
7+
}
8+
9+
// Mirrors GFM's autolink literals in the sent message: an http(s) URL not
10+
// glued to a preceding letter, minus trailing punctuation and unbalanced `)`.
11+
const URL_PATTERN = /(?<![A-Za-z])https?:\/\/[^\s<]+/giu;
12+
const TRAILING_PUNCTUATION = new Set(["!", '"', "'", "*", ",", ".", ":", ";", "?", "]", "_", "~"]);
13+
14+
function trimLinkEnd(url: string): string {
15+
let unbalancedCloses = 0;
16+
for (const character of url) {
17+
if (character === "(") unbalancedCloses -= 1;
18+
else if (character === ")") unbalancedCloses += 1;
19+
}
20+
let end = url.length;
21+
while (end > 0) {
22+
const character = url[end - 1]!;
23+
if (character === ")" && unbalancedCloses > 0) unbalancedCloses -= 1;
24+
else if (!TRAILING_PUNCTUATION.has(character)) break;
25+
end -= 1;
26+
}
27+
return url.slice(0, end);
28+
}
29+
30+
export function findComposerLinks(text: string): ComposerLink[] {
31+
const links: ComposerLink[] = [];
32+
for (const match of text.matchAll(URL_PATTERN)) {
33+
const url = trimLinkEnd(match[0]);
34+
const host = resolveExternalWebLinkHost(url);
35+
if (host) links.push({ from: match.index, to: match.index + url.length, host });
36+
}
37+
return links;
38+
}

‎apps/web/src/index.css‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,6 +2335,10 @@ code {
23352335
padding: 0.05em 0.25em;
23362336
}
23372337

2338+
.composer-tiptap .composer-link {
2339+
color: var(--info-foreground);
2340+
}
2341+
23382342
.composer-rich-marker {
23392343
color: var(--muted-foreground);
23402344
opacity: 0.75;

0 commit comments

Comments
 (0)