dom.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /** Only http(s) and mailto links leave the document; everything else is blocked. */
  2. export function safeExternalUrl(href: string | null | undefined): string | null {
  3. if (!href) return null;
  4. try {
  5. const url = new URL(href, "https://invalid.invalid/");
  6. if (url.hostname === "invalid.invalid") return null;
  7. return url.protocol === "http:" || url.protocol === "https:" || url.protocol === "mailto:"
  8. ? url.href
  9. : null;
  10. } catch {
  11. return null;
  12. }
  13. }
  14. /**
  15. * Route clicks on links inside rendered documents: external links go to the host, in-document
  16. * anchors (`#bookmark`) are handled by `internal`, anything else is cancelled.
  17. */
  18. export function installLinkGuard(
  19. root: HTMLElement,
  20. external: (url: string) => void,
  21. internal?: (hash: string, link: Element) => boolean,
  22. ): () => void {
  23. const onClick = (event: MouseEvent) => {
  24. const link = event.target instanceof Element ? event.target.closest("a, [href]") : null;
  25. if (!link || !root.contains(link)) return;
  26. const href = link.getAttribute("href") ?? link.getAttribute("xlink:href");
  27. if (!href) return;
  28. event.preventDefault();
  29. if (href.startsWith("#")) {
  30. if (internal?.(href.slice(1), link)) event.stopPropagation();
  31. return;
  32. }
  33. const url = safeExternalUrl(href);
  34. if (url) {
  35. event.stopPropagation();
  36. external(url);
  37. }
  38. };
  39. root.addEventListener("click", onClick, true);
  40. return () => root.removeEventListener("click", onClick, true);
  41. }
  42. /** Text of the current DOM selection if it lies inside `root`. */
  43. export function selectionIn(root: HTMLElement): { text: string; range: Range } | null {
  44. const selection = document.getSelection();
  45. if (!selection || selection.isCollapsed || !selection.rangeCount) return null;
  46. const range = selection.getRangeAt(0);
  47. if (!root.contains(range.commonAncestorContainer)) return null;
  48. const text = selection.toString().replace(/\s+/g, " ").trim();
  49. return text ? { text, range } : null;
  50. }
  51. const normalise = (text: string) => text.replace(/\s+/g, " ").trim().toLowerCase();
  52. interface Flat {
  53. text: string;
  54. map: { node: Text; offset: number }[];
  55. }
  56. /** The text under `root`, lower-cased with whitespace collapsed, mapped back to (node, offset). */
  57. function flatten(root: Node): Flat {
  58. const nodes: Text[] = [];
  59. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  60. for (let node = walker.nextNode(); node; node = walker.nextNode()) nodes.push(node as Text);
  61. let text = "";
  62. const map: { node: Text; offset: number }[] = [];
  63. let lastSpace = true;
  64. for (const node of nodes) {
  65. const value = node.data;
  66. for (let i = 0; i < value.length; i++) {
  67. const char = value[i];
  68. if (/\s/.test(char)) {
  69. if (lastSpace) continue;
  70. text += " ";
  71. lastSpace = true;
  72. } else {
  73. text += char.toLowerCase();
  74. lastSpace = false;
  75. }
  76. map.push({ node, offset: i });
  77. }
  78. // Separate text nodes from different blocks (e.g. pdf.js spans without trailing spaces).
  79. if (!lastSpace) {
  80. text += " ";
  81. lastSpace = true;
  82. map.push({ node, offset: value.length });
  83. }
  84. }
  85. return { text, map };
  86. }
  87. function toRange(flat: Flat, span: [number, number]): Range {
  88. const start = flat.map[span[0]];
  89. const end = flat.map[Math.min(flat.map.length - 1, span[1])];
  90. const range = document.createRange();
  91. range.setStart(start.node, Math.min(start.node.data.length, start.offset));
  92. range.setEnd(end.node, Math.min(end.node.data.length, end.offset + 1));
  93. return range;
  94. }
  95. /**
  96. * Find `quote` in the text of `root` (whitespace- and case-insensitive) and return a DOM Range.
  97. */
  98. export function findTextRange(root: Node, quote: string): Range | null {
  99. const needle = normalise(quote);
  100. if (!needle) return null;
  101. const flat = flatten(root);
  102. const exact = flat.text.indexOf(needle);
  103. const span: [number, number] | null =
  104. exact >= 0 ? [exact, exact + needle.length - 1] : fuzzy(flat.text, needle);
  105. return span ? toRange(flat, span) : null;
  106. }
  107. /** Every occurrence of `query` under `root`, in document order (at most `limit`). */
  108. export function findAllRanges(root: Node, query: string, limit = 1000): Range[] {
  109. const needle = normalise(query);
  110. if (!needle) return [];
  111. const flat = flatten(root);
  112. const ranges: Range[] = [];
  113. for (
  114. let at = flat.text.indexOf(needle);
  115. at >= 0 && ranges.length < limit;
  116. at = flat.text.indexOf(needle, at + needle.length)
  117. )
  118. ranges.push(toRange(flat, [at, at + needle.length - 1]));
  119. return ranges;
  120. }
  121. /** Count occurrences of `query` in plain text the same way `findAllRanges` matches the DOM. */
  122. export function countMatches(text: string, query: string): number {
  123. const needle = normalise(query);
  124. if (!needle) return 0;
  125. const haystack = normalise(text);
  126. let count = 0;
  127. for (
  128. let at = haystack.indexOf(needle);
  129. at >= 0;
  130. at = haystack.indexOf(needle, at + needle.length)
  131. )
  132. count++;
  133. return count;
  134. }
  135. /** On-screen box of a range or element; null when it is detached or has no size. */
  136. export function boxOf(target: Range | Element | null | undefined): DOMRect | null {
  137. if (!target) return null;
  138. if (target instanceof Element && !target.isConnected) return null;
  139. if (target instanceof Range && !target.startContainer.isConnected) return null;
  140. const rect = target.getBoundingClientRect();
  141. return rect.width || rect.height ? rect : null;
  142. }
  143. /** Whether a client point falls on the boxes of a range or element (with a little slack). */
  144. export function pointOn(
  145. target: Range | Element | null | undefined,
  146. x: number,
  147. y: number,
  148. slack = 2,
  149. ): boolean {
  150. if (!target) return false;
  151. if (target instanceof Element ? !target.isConnected : !target.startContainer.isConnected)
  152. return false;
  153. for (const rect of target.getClientRects())
  154. if (
  155. x >= rect.left - slack &&
  156. x <= rect.right + slack &&
  157. y >= rect.top - slack &&
  158. y <= rect.bottom + slack
  159. )
  160. return true;
  161. return false;
  162. }
  163. /** Union of boxes, ignoring missing ones. */
  164. export function unionBox(boxes: (DOMRect | null)[]): DOMRect | null {
  165. const present = boxes.filter((box): box is DOMRect => Boolean(box));
  166. if (!present.length) return null;
  167. const left = Math.min(...present.map((box) => box.left));
  168. const top = Math.min(...present.map((box) => box.top));
  169. const right = Math.max(...present.map((box) => box.right));
  170. const bottom = Math.max(...present.map((box) => box.bottom));
  171. return new DOMRect(left, top, right - left, bottom - top);
  172. }
  173. /** Match ignoring spaces entirely (pdf.js often splits words into spans). Returns [start, end] in `flat`. */
  174. function fuzzy(flat: string, needle: string): [number, number] | null {
  175. const compactNeedle = needle.replace(/ /g, "");
  176. const positions: number[] = [];
  177. let compact = "";
  178. for (let i = 0; i < flat.length; i++) {
  179. if (flat[i] === " ") continue;
  180. compact += flat[i];
  181. positions.push(i);
  182. }
  183. const at = compactNeedle ? compact.indexOf(compactNeedle) : -1;
  184. return at < 0 ? null : [positions[at], positions[at + compactNeedle.length - 1]];
  185. }
  186. type HighlightRegistry = Map<string, unknown>;
  187. const registry = (): HighlightRegistry | null =>
  188. (globalThis as { CSS?: { highlights?: HighlightRegistry } }).CSS?.highlights ?? null;
  189. /** Paint ranges with the CSS Custom Highlight API under `name` (no DOM mutation). */
  190. export function paintRanges(name: string, ranges: Range[]) {
  191. const highlights = registry();
  192. const HighlightCtor = (globalThis as { Highlight?: new (...ranges: Range[]) => unknown })
  193. .Highlight;
  194. if (!highlights || !HighlightCtor) return;
  195. if (ranges.length) highlights.set(name, new HighlightCtor(...ranges));
  196. else highlights.delete(name);
  197. }
  198. /**
  199. * Scroll the viewer's own scroll container so `element` is visible. Never use scrollIntoView: it
  200. * also scrolls every ancestor (the app shell and the host frames), which pushes the toolbar away.
  201. */
  202. export function scrollToElement(element: Element, block: "start" | "center" | "upper" = "center") {
  203. const container = element.closest<HTMLElement>(".viewer-scroll");
  204. if (container) scrollToBox(container, element.getBoundingClientRect(), block);
  205. }
  206. /** Scroll the viewer that contains `range` so it sits 30% from the top ("upper"), as reveals do. */
  207. export function scrollToRange(range: Range, block: "start" | "center" | "upper" = "upper") {
  208. const container = range.startContainer.parentElement?.closest<HTMLElement>(".viewer-scroll");
  209. if (container) scrollToBox(container, range.getBoundingClientRect(), block);
  210. }
  211. function scrollToBox(container: HTMLElement, rect: DOMRect, block: "start" | "center" | "upper") {
  212. const box = container.getBoundingClientRect();
  213. let top = container.scrollTop + rect.top - box.top;
  214. top -=
  215. block === "center"
  216. ? Math.max(12, (box.height - rect.height) / 2)
  217. : block === "upper"
  218. ? Math.max(12, box.height * 0.3)
  219. : 12;
  220. let left = container.scrollLeft;
  221. if (rect.right > box.right || rect.left < box.left) left += rect.left - box.left - 12;
  222. container.scrollTo({ top: Math.max(0, top), left: Math.max(0, left), behavior: "smooth" });
  223. }
  224. /**
  225. * Watch which child of `container` is current; calls back with its key. The current child is the
  226. * one under the probe line (`probe` × the view height from the top, e.g. 1/3 for pages), else the
  227. * topmost one in view.
  228. */
  229. export function trackTopmost(
  230. container: HTMLElement,
  231. items: () => Iterable<HTMLElement>,
  232. key: (element: HTMLElement) => string | null,
  233. onChange: (key: string) => void,
  234. probe = 0,
  235. ): () => void {
  236. let last: string | null = null;
  237. let frame = 0;
  238. const check = () => {
  239. frame = 0;
  240. const top = container.getBoundingClientRect().top;
  241. const line = top + container.clientHeight * probe;
  242. let best: HTMLElement | null = null;
  243. let bestDistance = Infinity;
  244. for (const element of items()) {
  245. const rect = element.getBoundingClientRect();
  246. if (probe && rect.top <= line && rect.bottom >= line) {
  247. best = element;
  248. break;
  249. }
  250. if (rect.bottom < top + 8) continue;
  251. const distance = Math.abs(rect.top - top);
  252. if (distance < bestDistance) {
  253. bestDistance = distance;
  254. best = element;
  255. }
  256. if (rect.top > top + container.clientHeight) break;
  257. }
  258. const next = best ? key(best) : null;
  259. if (next && next !== last) {
  260. last = next;
  261. onChange(next);
  262. }
  263. };
  264. const schedule = () => {
  265. if (!frame) frame = requestAnimationFrame(check);
  266. };
  267. container.addEventListener("scroll", schedule, { passive: true });
  268. const observer = new ResizeObserver(schedule);
  269. observer.observe(container);
  270. schedule();
  271. return () => {
  272. container.removeEventListener("scroll", schedule);
  273. observer.disconnect();
  274. if (frame) cancelAnimationFrame(frame);
  275. };
  276. }