Skip to content

Commit 18a33c9

Browse files
juliusmarmingecodex
andcommitted
fix: navigate markdown fragment links
Resolve sanitized fragment IDs within the clicked markdown message so headings and footnote references do not collide across timeline entries, while preserving URL hash history. Co-authored-by: codex <[email protected]>
1 parent c7ca262 commit 18a33c9

2 files changed

Lines changed: 117 additions & 0 deletions

File tree

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,56 @@ describe("ChatMarkdown", () => {
263263
}
264264
});
265265

266+
it("navigates hash links within the clicked markdown message", async () => {
267+
const source = [
268+
"A claim with supporting context.[^context]",
269+
"",
270+
"[^context]: Supporting footnote text.",
271+
].join("\n");
272+
const originalUrl = window.location.href;
273+
const scrollIntoView = vi
274+
.spyOn(HTMLElement.prototype, "scrollIntoView")
275+
.mockImplementation(() => undefined);
276+
const screen = await render(
277+
<div>
278+
<ChatMarkdown text={source} cwd="/repo/project" />
279+
<ChatMarkdown text={source} cwd="/repo/project" />
280+
</div>,
281+
);
282+
283+
try {
284+
const markdownRoots = document.querySelectorAll<HTMLElement>(".chat-markdown");
285+
const secondRoot = markdownRoots[1];
286+
const secondReference =
287+
secondRoot?.querySelector<HTMLAnchorElement>('a[data-footnote-ref=""]');
288+
const secondFootnote = secondRoot?.querySelector<HTMLElement>(
289+
"section[data-footnotes] li[id]",
290+
);
291+
expect(secondReference).not.toBeNull();
292+
expect(secondFootnote).not.toBeNull();
293+
294+
secondReference?.click();
295+
296+
expect(scrollIntoView).toHaveBeenCalledTimes(1);
297+
expect(scrollIntoView.mock.instances[0]).toBe(secondFootnote);
298+
expect(window.location.hash).toBe(secondReference?.hash);
299+
300+
const secondBackref = secondRoot?.querySelector<HTMLAnchorElement>(
301+
"a[data-footnote-backref]",
302+
);
303+
expect(secondBackref).not.toBeNull();
304+
secondBackref?.click();
305+
306+
const secondReferenceTarget = secondReference?.closest<HTMLElement>("[id]");
307+
expect(scrollIntoView).toHaveBeenCalledTimes(2);
308+
expect(scrollIntoView.mock.instances[1]).toBe(secondReferenceTarget);
309+
} finally {
310+
scrollIntoView.mockRestore();
311+
window.history.replaceState(window.history.state, "", originalUrl);
312+
await screen.unmount();
313+
}
314+
});
315+
266316
describe("code block chrome", () => {
267317
it("shows icon-only language titles, text fallbacks, and filename overrides", async () => {
268318
const source = [

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

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -825,6 +825,66 @@ function plainHastText(node: unknown): string | null {
825825
return parts.every((part) => part !== null) ? parts.join("") : null;
826826
}
827827

828+
const SANITIZED_FRAGMENT_PREFIX = "user-content-";
829+
830+
function decodeMarkdownFragmentId(href: string): string {
831+
const encodedId = href.slice(1);
832+
try {
833+
return decodeURIComponent(encodedId);
834+
} catch {
835+
return encodedId;
836+
}
837+
}
838+
839+
function normalizeSanitizedFragmentId(id: string): string {
840+
let normalizedId = id;
841+
while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) {
842+
normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length);
843+
}
844+
return normalizedId;
845+
}
846+
847+
function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null {
848+
const decodedId = decodeMarkdownFragmentId(href);
849+
const normalizedId = normalizeSanitizedFragmentId(decodedId);
850+
const matchesFragment = (element: HTMLElement) =>
851+
element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId;
852+
const markdownRoot = anchor.closest<HTMLElement>(".chat-markdown");
853+
if (markdownRoot) {
854+
const localTargets = Array.from(markdownRoot.querySelectorAll<HTMLElement>("[id]"));
855+
const localTarget = localTargets.find(matchesFragment);
856+
if (localTarget) return localTarget;
857+
}
858+
859+
return (
860+
document.getElementById(decodedId) ??
861+
Array.from(document.querySelectorAll<HTMLElement>("[id]")).find(matchesFragment) ??
862+
null
863+
);
864+
}
865+
866+
function handleMarkdownFragmentClick(event: ReactMouseEvent<HTMLAnchorElement>, href: string) {
867+
if (
868+
event.defaultPrevented ||
869+
event.button !== 0 ||
870+
event.metaKey ||
871+
event.ctrlKey ||
872+
event.shiftKey ||
873+
event.altKey
874+
) {
875+
return;
876+
}
877+
878+
const target = findMarkdownFragmentTarget(event.currentTarget, href);
879+
if (!target) return;
880+
881+
event.preventDefault();
882+
const nextUrl = new URL(window.location.href);
883+
nextUrl.hash = href.slice(1);
884+
window.history.pushState(window.history.state, "", nextUrl);
885+
target.scrollIntoView({ block: "nearest" });
886+
}
887+
828888
function MarkdownExternalLinkContent({
829889
host,
830890
plainText,
@@ -1072,12 +1132,19 @@ function ChatMarkdown({
10721132
if (!fileLinkMeta) {
10731133
const faviconHost = resolveExternalLinkHost(href);
10741134
const isSameDocumentLink = href?.startsWith("#") ?? false;
1135+
const onClick = props.onClick;
10751136
const link = (
10761137
<a
10771138
{...props}
10781139
href={href}
10791140
target={isSameDocumentLink ? undefined : "_blank"}
10801141
rel={isSameDocumentLink ? undefined : "noopener noreferrer"}
1142+
onClick={(event) => {
1143+
onClick?.(event);
1144+
if (isSameDocumentLink && href) {
1145+
handleMarkdownFragmentClick(event, href);
1146+
}
1147+
}}
10811148
>
10821149
{faviconHost ? (
10831150
<MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>

0 commit comments

Comments
 (0)