The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): HTML links in pull request comments open when tapped (#22110)
oliver committed
Oct 23, 2026 at 19:36 UTC
26c3625f484eadd4d5b6ca5a3dd1f8f8bd5533b4
2 files changed
+184
-31
apps/mobile/src/lib/markdownDocument.ts
+151
-30
@@ -55,8 +55,56 @@ function attribute(tag: string, name: string): string | null {
55
return null;
56
}
57
58
-/** Called only for parsed HTML nodes, so Markdown code examples keep their literal tags. */
59
-export function markdownHtmlContent(content: string): string {
58
+function markdownDestination(url: string): string {
59
+ return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
60
+}
61
+
62
+const ANCHOR_TAG = /^<\/?a[\s/>]/i;
63
+
64
+/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
65
+type AnchorState = { readonly pending: string[]; open: number };
66
+
67
+// Code spans keep their text; an odd trailing backslash would escape the closing "]".
68
+function escapeLinkLabel(text: string): string {
69
+ return text
70
+ .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
71
+ match.startsWith("`") || match.length % 2 === 0
72
+ ? match
73
+ : `${match.slice(0, -1)}\\${match.slice(-1)}`,
74
+ )
75
+ .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
76
+}
77
+
78
+// An unescaped "!" before the inserted "[" would turn the link into an image.
79
+function bangBefore(text: string, index: number): boolean {
80
+ if (text[index - 1] !== "!") return false;
81
+ let backslashes = 0;
82
+ while (text[index - 2 - backslashes] === "\\") backslashes += 1;
83
+ return backslashes % 2 === 0;
84
+}
85
+
86
+/**
87
+ * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
88
+ * Markdown link; any other anchor keeps its text unlinked.
89
+ */
90
+function anchorMarkdown(tags: readonly string[]): AnchorState {
91
+ const replacements = tags.map(() => "");
92
+ const open: Array<{ index: number; href: string | undefined }> = [];
93
+ tags.forEach((tag, index) => {
94
+ if (tag[1] !== "/") {
95
+ const href = attribute(tag, "href")?.trim();
96
+ open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
97
+ return;
98
+ }
99
+ const opening = open.pop();
100
+ if (!opening?.href) return;
101
+ replacements[opening.index] = "[";
102
+ replacements[index] = `](${markdownDestination(opening.href)})`;
103
+ });
104
+ return { pending: replacements, open: 0 };
105
+}
106
+
107
+function markdownHtmlTags(content: string): RegExpExecArray[] {
108
// An HTML block such as <details> can also contain Markdown fences and code spans.
109
const codeRanges: Array<{ start: number; end: number }> = [];
110
const tags = [...content.matchAll(HTML_TAG)];
@@ -101,40 +149,113 @@ export function markdownHtmlContent(content: string): string {
149
codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
150
index = closingIndex;
151
}
104
- return content.replace(HTML_TAG, (tag, offset: number) => {
105
- if (codeRanges.some((range) => offset >= range.start && offset < range.end)) return tag;
106
- if (tag.startsWith("<!--")) return "";
107
- if (/^<img\b/i.test(tag)) {
108
- const src = attribute(tag, "src");
109
- if (!src) return "";
110
- const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
111
- const href = src
112
- .replace(/&/g, "\\&")
113
- .replace(/</g, "%3C")
114
- .replace(/>/g, "%3E")
115
- .replace(/\n/g, "");
116
- return ``;
117
- }
118
- if (/^<summary\b/i.test(tag)) return "\n\n**";
119
- if (/^<\/summary\s*>/i.test(tag)) return "**\n\n";
120
- if (/^<br\b/i.test(tag)) return " \n";
121
- if (/^<\/?(?:p|div|details)\b/i.test(tag)) return "\n\n";
122
- return "";
123
- });
152
+ return tags.filter(
153
+ (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
154
+ );
155
+}
156
+
157
+/**
158
+ * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
159
+ * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
160
+ */
161
+export function markdownHtmlContent(
162
+ content: string,
163
+ options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
164
+): string {
165
+ const tags = markdownHtmlTags(content);
166
+ const anchors =
167
+ options.anchors ??
168
+ anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
169
+ let result = "";
170
+ let end = 0;
171
+ for (const match of tags) {
172
+ const text = content.slice(end, match.index);
173
+ result += anchors.open > 0 ? escapeLinkLabel(text) : text;
174
+ const replacement = htmlTagMarkdown(match[0], anchors, options);
175
+ if (replacement === "[" && bangBefore(result, result.length))
176
+ result = `${result.slice(0, -1)}\\!`;
177
+ result +=
178
+ anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
179
+ ? replacement.replace(/^ /, "")
180
+ : replacement;
181
+ end = match.index + match[0].length;
182
+ }
183
+ const text = content.slice(end);
184
+ return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
185
+}
186
+
187
+function htmlTagMarkdown(
188
+ tag: string,
189
+ anchors: AnchorState,
190
+ options: { readonly inTableCell?: boolean },
191
+): string {
192
+ if (tag.startsWith("<!--")) return "";
193
+ if (ANCHOR_TAG.test(tag)) {
194
+ const replacement = anchors.pending.shift() ?? "";
195
+ if (replacement === "[") anchors.open += 1;
196
+ else if (replacement) anchors.open -= 1;
197
+ return replacement;
198
+ }
199
+ if (/^<img\b/i.test(tag)) {
200
+ const src = attribute(tag, "src");
201
+ if (!src) return "";
202
+ const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
203
+ return `})`;
204
+ }
205
+ // A blank line inside an open link label would end the paragraph before its "]".
206
+ const blockBreak = anchors.open === 0 ? "\n\n" : " ";
207
+ if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
208
+ if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
209
+ // A line break would end the table row, so a cell keeps its content on one line.
210
+ if (/^<br\b/i.test(tag)) return options.inTableCell ? " " : " \n";
211
+ if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
212
+ return "";
213
}
214
215
export function markdownWithHtml(markdown: string): string {
216
if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
217
const edits: Array<{ start: number; end: number; content: string }> = [];
129
- const visit = (node: MarkdownNode) => {
130
- if (node.type === "html") {
131
- const start = node.position?.start.offset;
132
- const end = node.position?.end.offset;
133
- if (start !== undefined && end !== undefined)
134
- edits.push({ start, end, content: markdownHtmlContent(node.value) });
135
- } else if ("children" in node) node.children.forEach(visit);
218
+ const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
219
+ if (!("children" in node)) return;
220
+ inTableCell ||= node.type === "tableCell";
221
+ const children: readonly MarkdownNode[] = node.children;
222
+ // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
223
+ const anchors =
224
+ node.type === "root" || node.type === "blockquote" || node.type === "listItem"
225
+ ? undefined
226
+ : anchorMarkdown(
227
+ children.flatMap((child) =>
228
+ child.type === "html"
229
+ ? markdownHtmlTags(child.value)
230
+ .map((tag) => tag[0])
231
+ .filter((tag) => ANCHOR_TAG.test(tag))
232
+ : [],
233
+ ),
234
+ );
235
+ for (const child of children) {
236
+ const start = child.position?.start.offset;
237
+ const end = child.position?.end.offset;
238
+ const linkLabel = inLink || (anchors?.open ?? 0) > 0;
239
+ if (child.type === "text") {
240
+ if (linkLabel && start !== undefined && end !== undefined) {
241
+ const content = escapeLinkLabel(markdown.slice(start, end));
242
+ if (content !== markdown.slice(start, end)) edits.push({ start, end, content });
243
+ }
244
+ continue;
245
+ }
246
+ if (child.type !== "html") {
247
+ visit(child, inTableCell, linkLabel);
248
+ continue;
249
+ }
250
+ const content = markdownHtmlContent(child.value, { anchors, inTableCell });
251
+ if (start === undefined || end === undefined) continue;
252
+ // Text before an outermost link is never edited, so this edit cannot overlap another.
253
+ if (content.startsWith("[") && !linkLabel && bangBefore(markdown, start))
254
+ edits.push({ start: start - 1, end: start, content: "\\!" });
255
+ edits.push({ start, end, content });
256
+ }
257
};
137
- visit(parser.parse(markdown));
258
+ visit(parser.parse(markdown), false, false);
259
for (const edit of edits.reverse())
260
markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
261
return markdown;
apps/mobile/src/lib/markdownHtml.test.ts
+33
-1
@@ -13,7 +13,7 @@ describe("HTML in native Markdown", () => {
13
markdownHtmlContent(
14
"<a href='https://example.com'><img src='https://example.com/banner.svg' alt='Review' /></a>",
15
),
16
- ).toBe("");
16
+ ).toBe("[](<https://example.com>)");
17
});
18
19
it("decodes HTML attributes once and preserves entity-shaped query values through Markdown", () => {
@@ -62,4 +62,36 @@ describe("HTML in native Markdown", () => {
62
expect(result).toContain('```html\n<img src="literal.png">\n```');
63
expect(result).toContain('`<img src="inline.png">`');
64
});
65
+
66
+ it("links HTML anchors in a table cell without breaking the row at <br>", () => {
67
+ const document = parseMarkdownDocument(
68
+ "| Status | Preview URL |\n| - | - |\n| Done | <a href='https://commit.example.com'>Commit</a><br><a href='https://branch.example.com'>Branch</a> |",
69
+ );
70
+ const table = document.children[0];
71
+ expect(table?.type).toBe("table");
72
+ if (table?.type !== "table") return;
73
+ expect(table.children).toHaveLength(2);
74
+ expect(table.children[1]?.children[1]?.children).toMatchObject([
75
+ { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
76
+ { type: "text", value: " " },
77
+ { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
78
+ ]);
79
+ });
80
+
81
+ it("keeps a table row intact when an anchor href contains a pipe", () => {
82
+ const document = parseMarkdownDocument(
83
+ "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1|2'>Open</a> | done |",
84
+ );
85
+ const table = document.children[0];
86
+ expect(table?.type).toBe("table");
87
+ if (table?.type !== "table") return;
88
+ expect(table.children[1]?.children).toMatchObject([
89
+ { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
90
+ { children: [{ value: "done" }] },
91
+ ]);
92
+ });
93
+
94
+ it("keeps anchor text unlinked for unsafe hrefs", () => {
95
+ expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
96
+ });
97
});