Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(editor): stop autolinking URLs inside HTML tags (MUL-8960) (#10299)

Jiayuan Zhange19bda9baa76
diff --git a/packages/ui/markdown/issue-identifiers.ts b/packages/ui/markdown/issue-identifiers.ts
index 889a1bf434..ec5e2d2759 100644
--- a/packages/ui/markdown/issue-identifiers.ts
+++ b/packages/ui/markdown/issue-identifiers.ts
@@ -1,6 +1,7 @@
import {
detectLinks,
findCodeRanges,
+ findHtmlTagRanges,
findMarkdownLinkRanges,
isInsideCode,
rangesOverlap,
@@ -55,6 +56,7 @@ export function isIssueIdentifier(value: string): boolean {
* Skipped contexts (never rewritten):
* - fenced code blocks, inline code, and math (findCodeRanges)
* - existing markdown links / images (findMarkdownLinkRanges)
+ * - HTML tag attributes and `<a>` elements (findHtmlTagRanges)
* - detected URLs / emails / file paths (detectLinks)
* - dotted filename tails like `ABC-123.ts` and path segments like `FOO-1/bar`
*/
@@ -64,6 +66,7 @@ export function preprocessIssueIdentifiers(text: string): string {
const codeRanges = findCodeRanges(text)
const linkRanges = findMarkdownLinkRanges(text)
+ const htmlRanges = findHtmlTagRanges(text, codeRanges)
const detectedLinks = detectLinks(text)
IDENTIFIER_RE.lastIndex = 0
@@ -82,6 +85,8 @@ export function preprocessIssueIdentifiers(text: string): string {
if (isInsideCode(start, codeRanges)) continue
// Inside an existing markdown link/image (label OR destination).
if (linkRanges.some((r) => rangesOverlap(range, r))) continue
+ // Inside an HTML tag's attributes or an `<a>` element.
+ if (htmlRanges.some((r) => rangesOverlap(range, r))) continue
// Inside a detected URL / email / file path.
if (detectedLinks.some((l) => rangesOverlap(range, l))) continue
diff --git a/packages/ui/markdown/linkify.test.ts b/packages/ui/markdown/linkify.test.ts
index e6dd47fe43..c9f35b766c 100644
--- a/packages/ui/markdown/linkify.test.ts
+++ b/packages/ui/markdown/linkify.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest'
import { performance } from 'node:perf_hooks'
-import { findCodeRanges, findBlockCodeRanges, preprocessLinks } from './linkify'
+import { findCodeRanges, findBlockCodeRanges, findHtmlTagRanges, preprocessLinks } from './linkify'
describe('fenced code boundaries used by preprocessing and chunked loading', () => {
it.each([
@@ -169,6 +169,54 @@ it.each(['x', ''])('scans repeated list prefixes without backtracking (%j)', (su
expect(performance.now() - start).toBeLessThan(250)
})
+describe('raw HTML during linkification', () => {
+ it.each([
+ '<img src="https://host/a.png" width="400" />',
+ "<img src='https://host/a.png'>",
+ '<img src=https://host/a.png>',
+ '<img\n src="https://host/a.png"\n alt="www.example.com"\n/>',
+ '<IMG SRC="https://host/a.png">',
+ '<a href="https://example.com">docs</a>',
+ '<a href="https://example.com">https://example.com</a>',
+ '<A HREF="https://example.com"><img src="https://host/a.png"></A>',
+ '<source srcset="https://host/a.webp 2x" />',
+ ])('leaves %j untouched', (html) => {
+ const source = `Text\n\n${html}\n\nEnd`
+ expect(preprocessLinks(source)).toBe(source)
+ })
+
+ it('still links prose URLs around and between HTML tags', () => {
+ expect(
+ preprocessLinks('see https://a.example <img src="https://host/a.png"> and https://b.example'),
+ ).toBe(
+ 'see [https://a.example](https://a.example) <img src="https://host/a.png"> and [https://b.example](https://b.example)',
+ )
+ expect(preprocessLinks('<br>https://a.example<br/>')).toBe(
+ '<br>[https://a.example](https://a.example)<br/>',
+ )
+ expect(preprocessLinks('<details><summary>Logs</summary>\n\nhttps://a.example\n</details>')).toBe(
+ '<details><summary>Logs</summary>\n\n[https://a.example](https://a.example)\n</details>',
+ )
+ })
+
+ it('does not treat autolinks, escaped tags, or tags in code as HTML', () => {
+ expect(findHtmlTagRanges('<https://a.example> <[email protected]>')).toEqual([])
+ expect(preprocessLinks('\\<img src="https://host/a.png">')).toBe(
+ '\\<img src="[https://host/a.png](https://host/a.png)">',
+ )
+ expect(preprocessLinks('`<a href="x">` then https://a.example </a>')).toBe(
+ '`<a href="x">` then [https://a.example](https://a.example) </a>',
+ )
+ })
+
+ it('scans an unterminated tag with many attributes without backtracking', () => {
+ const source = '<img' + ' a=b/c/d'.repeat(2000) + ' https://a.example'
+ const start = performance.now()
+ expect(preprocessLinks(source)).toContain('[https://a.example](https://a.example)')
+ expect(performance.now() - start).toBeLessThan(250)
+ })
+})
+
describe('reference definitions during linkification', () => {
it.each([
'[shot]: https://cdn.example/chart.png',
diff --git a/packages/ui/markdown/linkify.ts b/packages/ui/markdown/linkify.ts
index 5bc68534f4..ebce91e8ca 100644
--- a/packages/ui/markdown/linkify.ts
+++ b/packages/ui/markdown/linkify.ts
@@ -263,6 +263,43 @@ export function findMarkdownLinkRanges(text: string): CodeRange[] {
return ranges
}
+// CommonMark raw-HTML open tag (spec "Raw HTML"). Unquoted values exclude
+// whitespace, so attribute boundaries are unambiguous and matching stays linear.
+const HTML_ATTRIBUTE = String.raw`\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\x60]+|'[^']*'|"[^"]*"))?`
+const HTML_OPEN_TAG_REGEX = new RegExp(
+ String.raw`<[A-Za-z][A-Za-z0-9-]*(?:${HTML_ATTRIBUTE})*\s*\/?>`,
+ 'g'
+)
+const HTML_ANCHOR_CLOSE_REGEX = /<\/a\s*>/gi
+
+/**
+ * Find raw HTML open tags so auto-linkification leaves their attribute values
+ * alone: rewriting `<img src="https://…">` produces `src="[url](url)"`, which
+ * renders blank and is saved back as a broken image. An `<a>` range runs
+ * through its `</a>`, since its text is already link text.
+ */
+export function findHtmlTagRanges(text: string, codeRanges: CodeRange[] = []): CodeRange[] {
+ if (!text.includes('<')) return []
+
+ const ranges: CodeRange[] = []
+ HTML_OPEN_TAG_REGEX.lastIndex = 0
+ let match
+ while ((match = HTML_OPEN_TAG_REGEX.exec(text)) !== null) {
+ const start = match.index
+ if (isEscaped(text, start) || isInsideCode(start, codeRanges)) continue
+
+ let end = start + match[0].length
+ if (/^<a[\s>]/i.test(match[0]) && !match[0].endsWith('/>')) {
+ HTML_ANCHOR_CLOSE_REGEX.lastIndex = end
+ const close = HTML_ANCHOR_CLOSE_REGEX.exec(text)
+ if (close) end = close.index + close[0].length
+ }
+ ranges.push({ start, end })
+ HTML_OPEN_TAG_REGEX.lastIndex = end
+ }
+ return ranges
+}
+
/**
* Check if a link at given position is already a markdown link
* Looks for patterns like [text](url) or [text][ref]
@@ -413,6 +450,8 @@ export function preprocessLinks(text: string): string {
if (links.length === 0) return text
+ const htmlRanges = findHtmlTagRanges(text, codeRanges)
+
// Build result, converting raw links to markdown links
let result = ''
let lastIndex = 0
@@ -424,6 +463,9 @@ export function preprocessLinks(text: string): string {
// Skip if this match is inside an existing markdown link or image.
if (markdownLinkRanges.some((range) => rangesOverlap(link, range))) continue
+ // Skip if inside an HTML tag's attributes or an `<a>` element.
+ if (htmlRanges.some((range) => rangesOverlap(link, range))) continue
+
// Skip if already a markdown link
if (isAlreadyLinked(text, link.start, link.end)) continue
diff --git a/packages/views/editor/extensions/image-markdown-roundtrip.test.ts b/packages/views/editor/extensions/image-markdown-roundtrip.test.ts
index 63e5278294..86d29b6250 100644
--- a/packages/views/editor/extensions/image-markdown-roundtrip.test.ts
+++ b/packages/views/editor/extensions/image-markdown-roundtrip.test.ts
@@ -3,6 +3,7 @@ import { Editor } from "@tiptap/core";
import StarterKit from "@tiptap/starter-kit";
import { Markdown } from "@tiptap/markdown";
import { ImageExtension } from "./index";
+import { preprocessMarkdown } from "../utils/preprocess";
const IMAGE_URL = "https://cdn.example.com/screen.png";
const IMAGE_MD = `![screen](${IMAGE_URL})`;
@@ -85,4 +86,18 @@ describe("ImageExtension markdown round-trip", () => {
);
expect(findParagraphTexts(reparsed)).toEqual(["after"]);
});
+
+ it("keeps the src of an HTML <img> through preprocessing and save", () => {
+ const editor = makeEditor();
+ const input = `Text\n\n<img src="${IMAGE_URL}" width="400" />\n\nEnd`;
+ editor.commands.setContent(preprocessMarkdown(input, { cdnDomain: "" }), {
+ contentType: "markdown",
+ });
+
+ const image = editor.getJSON().content?.find((n) => n.type === "image");
+ expect(image?.attrs).toMatchObject({ src: IMAGE_URL, width: 400 });
+ expect(editor.getMarkdown().trimEnd()).toBe(
+ `Text\n\n![](${IMAGE_URL})\n\nEnd`,
+ );
+ });
});
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index b95a3e40e8..275e12c3f0 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -748,6 +748,18 @@ describe("ReadonlyContent inline data-URI images", () => {
// the <img>. AttachmentRenderer still mounts an <img>, but with an empty src.
expect(container.querySelector("img")?.getAttribute("src") ?? "").toBe("");
});
+
+ it("keeps the src of a raw HTML <img>", () => {
+ const { container } = renderWithQuery(
+ <ReadonlyContent
+ content={'Text\n\n<img src="https://host/a.png" width="400" />\n\nEnd'}
+ />,
+ );
+
+ expect(container.querySelector("img")?.getAttribute("src")).toBe(
+ "https://host/a.png",
+ );
+ });
});
describe("ReadonlyContent slash command rendering", () => {
diff --git a/packages/views/editor/utils/issue-identifiers.test.ts b/packages/views/editor/utils/issue-identifiers.test.ts
index fe17aee5c2..9c6bbca63e 100644
--- a/packages/views/editor/utils/issue-identifiers.test.ts
+++ b/packages/views/editor/utils/issue-identifiers.test.ts
@@ -36,6 +36,14 @@ describe("preprocessIssueIdentifiers", () => {
);
});
+ it("skips identifiers inside HTML attributes and anchors", () => {
+ const source =
+ '<img src="https://host/a.png" alt="MUL-1 screenshot"> <a href="#x">MUL-2</a> MUL-3';
+ expect(preprocessIssueIdentifiers(source)).toBe(
+ '<img src="https://host/a.png" alt="MUL-1 screenshot"> <a href="#x">MUL-2</a> [MUL-3](mention://issue/MUL-3)',
+ );
+ });
+
// --- skip: code -------------------------------------------------------
it("skips identifiers inside inline code", () => {
expect(preprocessIssueIdentifiers("use `MUL-1` here")).toBe(