Skip to content

Commit 6aaa19b

Browse files
committed
fix(mobile): HTML links in pull request comments open when tapped
1 parent 44a7cb1 commit 6aaa19b

2 files changed

Lines changed: 143 additions & 31 deletions

File tree

‎apps/mobile/src/lib/markdownDocument.ts‎

Lines changed: 102 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,34 @@ function attribute(tag: string, name: string): string | null {
5555
return null;
5656
}
5757

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(/\n/g, "")}>`;
60+
}
61+
62+
const ANCHOR_TAG = /^<\/?a[\s/>]/i;
63+
64+
/**
65+
* Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
66+
* Markdown link; any other anchor keeps its text unlinked.
67+
*/
68+
function anchorMarkdown(tags: readonly string[]): string[] {
69+
const replacements = tags.map(() => "");
70+
const open: Array<{ index: number; href: string | undefined }> = [];
71+
tags.forEach((tag, index) => {
72+
if (tag[1] !== "/") {
73+
const href = attribute(tag, "href")?.trim();
74+
open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
75+
return;
76+
}
77+
const opening = open.pop();
78+
if (!opening?.href) return;
79+
replacements[opening.index] = "[";
80+
replacements[index] = `](${markdownDestination(opening.href)})`;
81+
});
82+
return replacements;
83+
}
84+
85+
function markdownHtmlTags(content: string): RegExpExecArray[] {
6086
// An HTML block such as <details> can also contain Markdown fences and code spans.
6187
const codeRanges: Array<{ start: number; end: number }> = [];
6288
const tags = [...content.matchAll(HTML_TAG)];
@@ -101,40 +127,86 @@ export function markdownHtmlContent(content: string): string {
101127
codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
102128
index = closingIndex;
103129
}
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 `![${alt}](<${href}>)`;
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-
});
130+
return tags.filter(
131+
(tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
132+
);
133+
}
134+
135+
/**
136+
* Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
137+
* `anchors` holds the replacements for the anchor tags still ahead, shared across sibling
138+
* inline HTML nodes because each of those carries a single tag.
139+
*/
140+
export function markdownHtmlContent(
141+
content: string,
142+
options: { readonly anchors?: string[]; readonly inTableCell?: boolean } = {},
143+
): string {
144+
const tags = markdownHtmlTags(content);
145+
const anchors =
146+
options.anchors ??
147+
anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
148+
let result = "";
149+
let end = 0;
150+
for (const match of tags) {
151+
result += content.slice(end, match.index) + htmlTagMarkdown(match[0], anchors, options);
152+
end = match.index + match[0].length;
153+
}
154+
return result + content.slice(end);
155+
}
156+
157+
function htmlTagMarkdown(
158+
tag: string,
159+
anchors: string[],
160+
options: { readonly inTableCell?: boolean },
161+
): string {
162+
if (tag.startsWith("<!--")) return "";
163+
if (ANCHOR_TAG.test(tag)) return anchors.shift() ?? "";
164+
if (/^<img\b/i.test(tag)) {
165+
const src = attribute(tag, "src");
166+
if (!src) return "";
167+
const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
168+
return `![${alt}](${markdownDestination(src)})`;
169+
}
170+
if (/^<summary\b/i.test(tag)) return "\n\n**";
171+
if (/^<\/summary\s*>/i.test(tag)) return "**\n\n";
172+
// A line break would end the table row, so a cell keeps its content on one line.
173+
if (/^<br\b/i.test(tag)) return options.inTableCell ? " " : " \n";
174+
if (/^<\/?(?:p|div|details)\b/i.test(tag)) return "\n\n";
175+
return "";
124176
}
125177

126178
export function markdownWithHtml(markdown: string): string {
127179
if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
128180
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);
181+
const visit = (node: MarkdownNode, inTableCell: boolean) => {
182+
if (!("children" in node)) return;
183+
inTableCell ||= node.type === "tableCell";
184+
const children: readonly MarkdownNode[] = node.children;
185+
// Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
186+
const anchors =
187+
node.type === "root" || node.type === "blockquote" || node.type === "listItem"
188+
? undefined
189+
: anchorMarkdown(
190+
children.flatMap((child) =>
191+
child.type === "html"
192+
? markdownHtmlTags(child.value)
193+
.map((tag) => tag[0])
194+
.filter((tag) => ANCHOR_TAG.test(tag))
195+
: [],
196+
),
197+
);
198+
for (const child of children) {
199+
if (child.type !== "html") {
200+
visit(child, inTableCell);
201+
continue;
202+
}
203+
const start = child.position?.start.offset;
204+
const end = child.position?.end.offset;
205+
const content = markdownHtmlContent(child.value, { anchors, inTableCell });
206+
if (start !== undefined && end !== undefined) edits.push({ start, end, content });
207+
}
136208
};
137-
visit(parser.parse(markdown));
209+
visit(parser.parse(markdown), false);
138210
for (const edit of edits.reverse())
139211
markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
140212
return markdown;

‎apps/mobile/src/lib/markdownHtml.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ describe("HTML in native Markdown", () => {
2121
markdownHtmlContent(
2222
"<a href='https://example.com'><img src='https://example.com/banner.svg' alt='Review' /></a>",
2323
),
24-
).toBe("![Review](<https://example.com/banner.svg>)");
24+
).toBe("[![Review](<https://example.com/banner.svg>)](<https://example.com>)");
2525
});
2626

2727
it("decodes HTML attributes once and preserves entity-shaped query values through Markdown", () => {
@@ -70,4 +70,44 @@ describe("HTML in native Markdown", () => {
7070
expect(result).toContain('```html\n<img src="literal.png">\n```');
7171
expect(result).toContain('`<img src="inline.png">`');
7272
});
73+
74+
it("turns HTML anchors into Markdown links, including inline tags in headings and table cells", () => {
75+
const markdown = [
76+
'## Deploying with &nbsp;<a href="https://workers.dev"><img alt="Workers" src="https://example.com/logo.svg" width="16"></a> &nbsp;Workers',
77+
"",
78+
"| Status | Preview URL |",
79+
"| -|-|",
80+
"| Done <br>[View logs](https://example.com/logs) | <a href='https://commit.example.com'>Commit Preview URL</a><br><br><a href='https://branch.example.com'>Branch Preview URL</a> |",
81+
].join("\n");
82+
const document = parseMarkdownDocument(markdown);
83+
const links: Array<{ url: string; text: string }> = [];
84+
const visit = (node: (typeof document.children)[number] | typeof document) => {
85+
if (node.type === "link")
86+
links.push({
87+
url: node.url,
88+
text: node.children
89+
.map((child) => ("value" in child ? child.value : child.type))
90+
.join(""),
91+
});
92+
if ("children" in node) node.children.forEach(visit);
93+
};
94+
visit(document);
95+
expect(links).toEqual([
96+
{ url: "https://workers.dev", text: "image" },
97+
{ url: "https://example.com/logs", text: "View logs" },
98+
{ url: "https://commit.example.com", text: "Commit Preview URL" },
99+
{ url: "https://branch.example.com", text: "Branch Preview URL" },
100+
]);
101+
expect(document.children[1]).toMatchObject({ type: "table" });
102+
if (document.children[1]?.type === "table")
103+
expect(document.children[1].children).toHaveLength(2);
104+
});
105+
106+
it("keeps anchor text unlinked for unsafe or unclosed hrefs", () => {
107+
expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
108+
expect(markdownWithHtml("<p><a href='https://example.com'>open</p>")).toBe("\n\nopen\n\n");
109+
expect(markdownWithHtml("Mail <a href='mailto:[email protected]'>us</a>")).toBe(
110+
"Mail [us](<mailto:[email protected]>)",
111+
);
112+
});
73113
});

0 commit comments

Comments
 (0)