Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownFragments.ts

124 lines4.0 KB

1import type { MouseEvent as ReactMouseEvent } from "react";
2​
3import { hastPlainTextDeep } from "./markdownHast.logic";
4​
5const SANITIZED_FRAGMENT_PREFIX = "user-content-";
6​
7function decodeMarkdownFragmentId(href: string): string {
8 const encodedId = href.slice(1);
9 try {
10 return decodeURIComponent(encodedId);
11 } catch {
12 return encodedId;
13 }
15​
16function normalizeSanitizedFragmentId(id: string): string {
17 let normalizedId = id;
18 while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) {
19 normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length);
20 }
21 return normalizedId;
23​
24export function normalizeMarkdownFragmentId(hrefOrId: string): string {
25 const raw = hrefOrId.startsWith("#") ? decodeMarkdownFragmentId(hrefOrId) : hrefOrId;
26 return normalizeSanitizedFragmentId(raw);
28​
29function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null {
30 const decodedId = decodeMarkdownFragmentId(href);
31 // Add the sanitizer prefix without stripping prefixes that belong to the authored slug.
32 const sanitizedId = `${SANITIZED_FRAGMENT_PREFIX}${decodedId}`;
33 const normalizedId = normalizeSanitizedFragmentId(decodedId);
34 const matchesFragment = (element: HTMLElement) =>
35 element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId;
36 const markdownRoot = anchor.closest<HTMLElement>(".chat-markdown");
37 if (markdownRoot) {
38 const localTargets = Array.from(markdownRoot.querySelectorAll<HTMLElement>("[id]"));
39 const localTarget =
40 localTargets.find((element) => element.id === sanitizedId) ??
41 localTargets.find(matchesFragment);
42 if (localTarget) return localTarget;
43 }
44​
45 return (
46 document.getElementById(sanitizedId) ??
47 document.getElementById(decodedId) ??
48 Array.from(document.querySelectorAll<HTMLElement>("[id]")).find(matchesFragment) ??
49 null
50 );
52​
53export function handleMarkdownFragmentClick(
54 event: ReactMouseEvent<HTMLAnchorElement>,
55 href: string,
56) {
57 if (
58 event.defaultPrevented ||
59 event.button !== 0 ||
60 event.metaKey ||
61 event.ctrlKey ||
62 event.shiftKey ||
63 event.altKey
64 ) {
65 return;
66 }
67​
68 // Never let the browser follow the fragment or write it to the URL: desktop keeps
69 // its route in the hash, so replacing the hash navigates away from the thread.
70 event.preventDefault();
71 findMarkdownFragmentTarget(event.currentTarget, href)?.scrollIntoView({ block: "start" });
73​
74type HeadingHastNode = {
75 type?: string;
76 tagName?: string;
77 properties?: Record<string, unknown>;
78 children?: HeadingHastNode[];
79};
80​
81// GitHub keeps Ruby's \p{Word} (UTS #18 \w), spaces and hyphens.
82export function githubHeadingSlug(text: string): string {
83 return text
84 .trim()
85 .toLowerCase()
86 .replace(/[^\p{Alphabetic}\p{M}\p{Nd}\p{Pc}\p{Join_Control} -]/gu, "")
87 .replace(/ /g, "-");
89​
90/**
91 * Like the sanitizer's ids, they carry the `user-content-` prefix so they cannot clobber app
92 * element ids; fragment lookup accounts for it.
93 */
94export function rehypeHeadingIds() {
95 return (tree: HeadingHastNode) => {
96 const taken = new Set<string>();
97 const collect = (node: HeadingHastNode) => {
98 const id = node.properties?.id;
99 if (typeof id === "string") taken.add(id);
100 node.children?.forEach(collect);
101 };
102 collect(tree);
103 const nextSuffix = new Map<string, number>();
104 const visit = (node: HeadingHastNode) => {
105 if (node.type === "element" && node.tagName && /^h[1-6]$/.test(node.tagName)) {
106 const slug = githubHeadingSlug(hastPlainTextDeep(node));
107 if (node.properties?.id === undefined && slug) {
108 let count = nextSuffix.get(slug) ?? 0;
109 let id = `${SANITIZED_FRAGMENT_PREFIX}${slug}`;
110 while (taken.has(id)) {
111 count += 1;
112 id = `${SANITIZED_FRAGMENT_PREFIX}${slug}-${count}`;
113 }
114 nextSuffix.set(slug, count);
115 taken.add(id);
116 node.properties = { ...node.properties, id };
117 }
118 return;
119 }
120 node.children?.forEach(visit);
121 };
122 visit(tree);
123 };