@open-document/core 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Find text in the document.
3
+ *
4
+ * Matches are drawn with the CSS Custom Highlight API, which paints ranges held
5
+ * beside the DOM instead of wrapping anything in it. Wrapping would mean editing
6
+ * a tree React owns: the next render throws the marks away, or keeps them and
7
+ * loses the reader's place. Neither is recoverable from inside a highlighter.
8
+ *
9
+ * A browser without the API still gets working navigation — the view scrolls to
10
+ * each hit — it just cannot tint it. That is worth having; refusing to search at
11
+ * all because it cannot be coloured is not.
12
+ */
13
+
14
+ import { ChevronDown, ChevronUp, Search, X } from 'lucide-react';
15
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
16
+
17
+ const ALL = 'od-search';
18
+ const ACTIVE = 'od-search-active';
19
+
20
+ type Hit = { range: Range; page: number };
21
+
22
+ /* Case-insensitive, and accent-insensitive where the browser can be: a reader
23
+ searching for "resume" means the word, not the spelling with accents. Defined
24
+ outside the component so it is one function, not a new one every render —
25
+ which is also what stops it having to appear in a dependency list. */
26
+ const fold = (value: string): string => value.normalize('NFKD').toLowerCase();
27
+
28
+ const highlightsSupported = (): boolean =>
29
+ typeof CSS !== 'undefined' && 'highlights' in CSS && typeof Highlight !== 'undefined';
30
+
31
+ function clearHighlights(): void {
32
+ if (!highlightsSupported()) return;
33
+ CSS.highlights.delete(ALL);
34
+ CSS.highlights.delete(ACTIVE);
35
+ }
36
+
37
+ /**
38
+ * Every text node under `root`, in document order.
39
+ *
40
+ * Script and style hold text that is not the document's text; matching inside
41
+ * them would send the reader to a hit they cannot see.
42
+ */
43
+ function textNodes(root: HTMLElement): Text[] {
44
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
45
+ acceptNode(node) {
46
+ const parent = node.parentElement;
47
+ if (!parent) return NodeFilter.FILTER_REJECT;
48
+ if (parent.closest('script,style,[data-od-search-skip]')) return NodeFilter.FILTER_REJECT;
49
+ return node.nodeValue?.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
50
+ },
51
+ });
52
+ const out: Text[] = [];
53
+ let node = walker.nextNode();
54
+ while (node) {
55
+ out.push(node as Text);
56
+ node = walker.nextNode();
57
+ }
58
+ return out;
59
+ }
60
+
61
+ function pageOf(node: Node, frames: Element[]): number {
62
+ const element = node.parentElement;
63
+ if (!element) return 0;
64
+ for (let i = 0; i < frames.length; i++) {
65
+ if (frames[i]?.contains(element)) return i + 1;
66
+ }
67
+ return 0;
68
+ }
69
+
70
+ export function DocSearch({
71
+ scrollRef,
72
+ pagesRef,
73
+ onFoundPage,
74
+ }: {
75
+ scrollRef: React.RefObject<HTMLElement | null>;
76
+ pagesRef: React.RefObject<HTMLElement | null>;
77
+ onFoundPage?: (page: number) => void;
78
+ }) {
79
+ const [open, setOpen] = useState(false);
80
+ const [query, setQuery] = useState('');
81
+ const [hits, setHits] = useState<Hit[]>([]);
82
+ const [at, setAt] = useState(0);
83
+ const inputRef = useRef<HTMLInputElement>(null);
84
+
85
+ const supported = useMemo(highlightsSupported, []);
86
+
87
+ const search = useCallback(
88
+ (text: string) => {
89
+ const root = pagesRef.current;
90
+ if (!root || text.trim() === '') {
91
+ clearHighlights();
92
+ setHits([]);
93
+ setAt(0);
94
+ return;
95
+ }
96
+
97
+ const needle = fold(text);
98
+ const frames = Array.from(root.children);
99
+ const found: Hit[] = [];
100
+
101
+ for (const node of textNodes(root)) {
102
+ const haystack = fold(node.nodeValue ?? '');
103
+ let from = haystack.indexOf(needle);
104
+ while (from !== -1) {
105
+ const range = document.createRange();
106
+ try {
107
+ range.setStart(node, from);
108
+ range.setEnd(node, from + needle.length);
109
+ found.push({ range, page: pageOf(node, frames) });
110
+ } catch {
111
+ /* Folding can change length, which puts the offset past the node.
112
+ Skipping that hit is better than throwing away the whole search. */
113
+ }
114
+ from = haystack.indexOf(needle, from + needle.length);
115
+ }
116
+ }
117
+
118
+ setHits(found);
119
+ setAt(found.length > 0 ? 1 : 0);
120
+ },
121
+ [pagesRef],
122
+ );
123
+
124
+ /* Painting is a side effect of the hits and the cursor, not of typing —
125
+ otherwise the active hit stays tinted after the reader moves off it. */
126
+ useEffect(() => {
127
+ if (!supported) return;
128
+ if (hits.length === 0) {
129
+ clearHighlights();
130
+ return;
131
+ }
132
+ const active = hits[at - 1];
133
+ CSS.highlights.set(ALL, new Highlight(...hits.map((hit) => hit.range)));
134
+ if (active) CSS.highlights.set(ACTIVE, new Highlight(active.range));
135
+ return clearHighlights;
136
+ }, [hits, at, supported]);
137
+
138
+ const go = useCallback(
139
+ (step: number) => {
140
+ if (hits.length === 0) return;
141
+ const next = ((at - 1 + step + hits.length) % hits.length) + 1;
142
+ setAt(next);
143
+ const hit = hits[next - 1];
144
+ if (!hit) return;
145
+ const target = hit.range.startContainer.parentElement;
146
+ const root = scrollRef.current;
147
+ if (target && root) {
148
+ const offset = target.getBoundingClientRect().top - root.getBoundingClientRect().top;
149
+ root.scrollTo({ top: root.scrollTop + offset - 120, behavior: 'smooth' });
150
+ }
151
+ if (hit.page > 0) onFoundPage?.(hit.page);
152
+ },
153
+ [at, hits, scrollRef, onFoundPage],
154
+ );
155
+
156
+ const close = useCallback(() => {
157
+ setOpen(false);
158
+ setQuery('');
159
+ clearHighlights();
160
+ setHits([]);
161
+ setAt(0);
162
+ }, []);
163
+
164
+ /* No ⌘F: that is the browser's own find, and taking it would replace a
165
+ control the reader already trusts with one that only searches this pane. */
166
+ useEffect(() => {
167
+ if (!open) return;
168
+ const onKey = (event: KeyboardEvent) => {
169
+ if (event.key === 'Escape') close();
170
+ };
171
+ window.addEventListener('keydown', onKey);
172
+ return () => window.removeEventListener('keydown', onKey);
173
+ }, [open, close]);
174
+
175
+ useEffect(() => () => clearHighlights(), []);
176
+
177
+ if (!open) {
178
+ return (
179
+ <button
180
+ type="button"
181
+ aria-label="Find in document"
182
+ title="Find in document"
183
+ onClick={() => {
184
+ setOpen(true);
185
+ requestAnimationFrame(() => inputRef.current?.focus());
186
+ }}
187
+ className="flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
188
+ >
189
+ <Search className="size-3.5" />
190
+ </button>
191
+ );
192
+ }
193
+
194
+ return (
195
+ <div className="flex items-center gap-1 rounded-md border border-border px-1.5 py-0.5 focus-within:border-foreground/40">
196
+ <Search className="size-3.5 flex-none text-muted-foreground" />
197
+ <input
198
+ ref={inputRef}
199
+ value={query}
200
+ onChange={(event) => {
201
+ setQuery(event.target.value);
202
+ search(event.target.value);
203
+ }}
204
+ onKeyDown={(event) => {
205
+ if (event.key === 'Enter') {
206
+ event.preventDefault();
207
+ go(event.shiftKey ? -1 : 1);
208
+ }
209
+ }}
210
+ placeholder="Find"
211
+ aria-label="Find in document"
212
+ className="w-28 bg-transparent text-xs outline-none placeholder:text-muted-foreground"
213
+ />
214
+ <span className="flex-none font-mono text-[11px] text-muted-foreground tabular-nums">
215
+ {query === '' ? '' : hits.length === 0 ? '0' : `${at}/${hits.length}`}
216
+ </span>
217
+ <button
218
+ type="button"
219
+ aria-label="Previous match"
220
+ title="Previous match (⇧⏎)"
221
+ onClick={() => go(-1)}
222
+ disabled={hits.length === 0}
223
+ className="flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
224
+ >
225
+ <ChevronUp className="size-3.5" />
226
+ </button>
227
+ <button
228
+ type="button"
229
+ aria-label="Next match"
230
+ title="Next match (⏎)"
231
+ onClick={() => go(1)}
232
+ disabled={hits.length === 0}
233
+ className="flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
234
+ >
235
+ <ChevronDown className="size-3.5" />
236
+ </button>
237
+ <button
238
+ type="button"
239
+ aria-label="Close search"
240
+ title="Close search (Esc)"
241
+ onClick={close}
242
+ className="flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
243
+ >
244
+ <X className="size-3.5" />
245
+ </button>
246
+ </div>
247
+ );
248
+ }
@@ -1,6 +1,7 @@
1
1
  import { Check, Loader2, MessageSquarePlus, X } from 'lucide-react';
2
2
  import {
3
3
  type CSSProperties,
4
+ Fragment,
4
5
  useCallback,
5
6
  useEffect,
6
7
  useLayoutEffect,
@@ -42,7 +43,13 @@ function normalize(value: string): string {
42
43
  }
43
44
 
44
45
  function targetFrom(el: Element | null): InspectorTarget | null {
45
- const host = (el as HTMLElement | null)?.closest?.(`[${LOC_ATTR}]`) as HTMLElement | null;
46
+ // A contents row is generated from a heading and written nowhere; the words
47
+ // to edit are the heading's. Clicking the row selects that instead, so the
48
+ // list stays what it is — a view — and still answers to a click.
49
+ const row = (el as HTMLElement | null)?.closest?.('[data-od-toc-entry]') as HTMLElement | null;
50
+ const heading = row?.dataset.odTocEntry ? document.getElementById(row.dataset.odTocEntry) : null;
51
+ const from = heading ?? el;
52
+ const host = (from as HTMLElement | null)?.closest?.(`[${LOC_ATTR}]`) as HTMLElement | null;
46
53
  const raw = host?.getAttribute(LOC_ATTR);
47
54
  if (!host || !raw) return null;
48
55
  const [line, column] = raw.split(':').map(Number);
@@ -136,6 +143,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
136
143
  const [busy, setBusy] = useState(false);
137
144
  const [status, setStatus] = useState<string | null>(null);
138
145
  const panelRef = useRef<HTMLElement>(null);
146
+ const editorRef = useRef<HTMLDivElement>(null);
139
147
 
140
148
  useLayoutEffect(() => setContainer(containerRef.current), [containerRef]);
141
149
 
@@ -157,6 +165,12 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
157
165
  if (!target) return;
158
166
  e.preventDefault();
159
167
  e.stopPropagation();
168
+ // A contents row sends the selection to a heading pages away. Without
169
+ // this the panel fills in and the document sits where it was, which
170
+ // reads as nothing having happened.
171
+ if (!target.anchor.contains(e.target as Node)) {
172
+ target.anchor.scrollIntoView({ block: 'center', behavior: 'smooth' });
173
+ }
160
174
  setSelected(target);
161
175
  setStatus(null);
162
176
  setNote('');
@@ -250,7 +264,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
250
264
  );
251
265
 
252
266
  const saveText = async () => {
253
- if (!target || dirty.length === 0 || busy) return;
267
+ if (!target || !selected || dirty.length === 0 || busy) return;
254
268
  setBusy(true);
255
269
  try {
256
270
  for (const part of dirty) {
@@ -263,6 +277,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
263
277
  column: target.column,
264
278
  index: part.index,
265
279
  expected: part.value,
280
+ shown: normalize(selected.anchor.textContent ?? ''),
266
281
  text: drafts[part.index],
267
282
  }),
268
283
  });
@@ -360,18 +375,70 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
360
375
  </div>
361
376
  ) : target.editable ? (
362
377
  <>
363
- <div className="mt-1 space-y-1.5">
364
- {target.parts.map((part, index) =>
365
- part.kind === 'markup' ? (
366
- <div
378
+ {/*
379
+ * One field, not one per run. A sentence interrupted by five
380
+ * <code> spans is still one sentence, and bordering each
381
+ * fragment turned a paragraph into eleven stacked boxes.
382
+ *
383
+ * The runs are laid out as the sentence reads, with the markup
384
+ * between them as inert chips. Nothing re-renders while typing:
385
+ * the children never change, so React leaves the DOM — and the
386
+ * caret — alone, and the text is read back out of it.
387
+ */}
388
+ {target.parts.length > 1 ? (
389
+ // biome-ignore lint/a11y/useSemanticElements: a textarea cannot hold the inert markup chips
390
+ <div
391
+ key={`${target.line}:${target.column}`}
392
+ ref={editorRef}
393
+ contentEditable
394
+ suppressContentEditableWarning
395
+ role="textbox"
396
+ tabIndex={0}
397
+ aria-label="Text"
398
+ onInput={() => {
399
+ const host = editorRef.current;
400
+ if (!host) return;
401
+ const next: Record<number, string> = {};
402
+ for (const run of host.querySelectorAll<HTMLElement>('[data-run]')) {
403
+ next[Number(run.dataset.run)] = run.textContent ?? '';
404
+ }
405
+ setDrafts(next);
406
+ }}
407
+ onKeyDown={(e) => {
408
+ // A newline would be a <br> the runs cannot carry.
409
+ if (e.key === 'Enter') {
410
+ e.preventDefault();
411
+ void saveText();
412
+ }
413
+ }}
414
+ className="mt-1 rounded border border-border px-2 py-1.5 text-xs leading-relaxed outline-none focus-within:border-foreground/40"
415
+ >
416
+ {target.parts.map((part, index) =>
417
+ part.kind === 'markup' ? (
418
+ // A chip carries no whitespace, so `real<code>/<code>`
419
+ // is one unbreakable word without these.
367
420
  // biome-ignore lint/suspicious/noArrayIndexKey: parts are positional
368
- key={`m${index}`}
369
- className="rounded border border-border border-dashed px-2 py-1 font-mono text-[10px] text-muted-foreground"
370
- title="Markup is kept as written"
371
- >
372
- {part.label}
373
- </div>
374
- ) : (
421
+ <Fragment key={`m${index}`}>
422
+ <wbr />
423
+ <span
424
+ contentEditable={false}
425
+ title="Markup is kept as written"
426
+ className="mx-0.5 select-none rounded bg-muted px-1 py-px font-mono text-[10px] text-muted-foreground"
427
+ >
428
+ {part.label}
429
+ </span>
430
+ <wbr />
431
+ </Fragment>
432
+ ) : (
433
+ <span key={`t${part.index}`} data-run={part.index}>
434
+ {part.value}
435
+ </span>
436
+ ),
437
+ )}
438
+ </div>
439
+ ) : (
440
+ target.parts.map((part) =>
441
+ part.kind === 'markup' ? null : (
375
442
  <textarea
376
443
  key={`t${part.index}`}
377
444
  value={drafts[part.index] ?? part.value}
@@ -382,14 +449,22 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
382
449
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void saveText();
383
450
  }}
384
451
  rows={Math.min(
385
- 6,
386
- Math.ceil((drafts[part.index] ?? part.value).length / 28) + 1,
452
+ 14,
453
+ Math.max(
454
+ 2,
455
+ (drafts[part.index] ?? part.value).split('\n').length,
456
+ Math.ceil((drafts[part.index] ?? part.value).length / 40),
457
+ ),
387
458
  )}
388
- className="w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none focus:border-foreground/40"
459
+ className={`mt-1 w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 outline-none focus:border-foreground/40 ${
460
+ selected?.tag === 'pre'
461
+ ? 'whitespace-pre font-mono text-[11px]'
462
+ : 'text-xs'
463
+ }`}
389
464
  />
390
465
  ),
391
- )}
392
- </div>
466
+ )
467
+ )}
393
468
  <button
394
469
  type="button"
395
470
  onClick={saveText}
@@ -50,6 +50,10 @@ export function TableOfContents({
50
50
  {entries.map((entry) => (
51
51
  <div
52
52
  key={entry.id}
53
+ /* Which heading this line stands for. The inspector follows it: a
54
+ * contents row holds no text of its own, so clicking one has to land
55
+ * on the heading that produced it. */
56
+ data-od-toc-entry={entry.id}
53
57
  style={{
54
58
  display: 'flex',
55
59
  alignItems: 'baseline',
@@ -109,16 +109,19 @@ export function MenuItem({
109
109
  children,
110
110
  destructive = false,
111
111
  active = false,
112
+ disabled = false,
112
113
  }: {
113
114
  onClick: () => void;
114
115
  children: ReactNode;
115
116
  destructive?: boolean;
116
117
  active?: boolean;
118
+ disabled?: boolean;
117
119
  }) {
118
120
  return (
119
121
  <button
120
122
  type="button"
121
123
  role="menuitem"
124
+ disabled={disabled}
122
125
  onClick={(e) => {
123
126
  e.stopPropagation();
124
127
  onClick();
@@ -127,6 +130,7 @@ export function MenuItem({
127
130
  'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-accent',
128
131
  active && 'bg-accent',
129
132
  destructive && 'text-red-600 dark:text-red-400',
133
+ disabled && 'pointer-events-none opacity-40',
130
134
  )}
131
135
  >
132
136
  {children}
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Shared by both exporters so there is one way to draw the document offscreen.
3
+ * Two copies would drift on font waiting, scanning, or design variables, and the
4
+ * difference would only ever show up in an exported file.
5
+ */
6
+
7
+ import { createElement } from 'react';
8
+ import { createRoot, type Root } from 'react-dom/client';
9
+ import { designToCssVars } from './design';
10
+ import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
11
+ import { DocPageProvider } from './page-context';
12
+ import { nextFrame, waitForFonts, waitForImages } from './print-ready';
13
+ import { captureScan, restoreScan, scanDocument } from './scan';
14
+ import type { DocModule, PageGeometry } from './sdk';
15
+ import type { ExpandedPage } from './use-doc-pages';
16
+
17
+ export const ASSET_EXT_RE =
18
+ /\.(?:png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf)(?:\?[^#]*)?(?:#.*)?$/i;
19
+
20
+ export async function renderPagesToHtml(
21
+ pages: ExpandedPage[],
22
+ geometry: PageGeometry,
23
+ doc: DocModule,
24
+ ): Promise<string[]> {
25
+ const container = document.createElement('div');
26
+ container.setAttribute('aria-hidden', 'true');
27
+ Object.assign(container.style, {
28
+ position: 'fixed',
29
+ left: '-99999px',
30
+ top: '0',
31
+ pointerEvents: 'none',
32
+ });
33
+ document.body.appendChild(container);
34
+
35
+ const designVars = doc.design ? designToCssVars(doc.design) : null;
36
+ const roots: Root[] = [];
37
+ const hosts: HTMLElement[] = [];
38
+ const previousScan = captureScan();
39
+
40
+ try {
41
+ for (let i = 0; i < pages.length; i++) {
42
+ const page = pages[i];
43
+ if (!page) continue;
44
+ const host = document.createElement('div');
45
+ host.setAttribute(PAGE_ATTR, '');
46
+ host.setAttribute(PAGE_INDEX_ATTR, String(i));
47
+ host.style.width = `${geometry.width}px`;
48
+ host.style.height = `${geometry.height}px`;
49
+ if (designVars) {
50
+ for (const [k, v] of Object.entries(designVars)) host.style.setProperty(k, v);
51
+ }
52
+ container.appendChild(host);
53
+ hosts.push(host);
54
+ const root = createRoot(host);
55
+ root.render(createElement(DocPageProvider, { index: i, total: pages.length }, page.content));
56
+ roots.push(root);
57
+ }
58
+
59
+ await nextFrame();
60
+ await waitForFonts();
61
+ await waitForImages(container);
62
+ scanDocument(container, doc.meta);
63
+ await nextFrame();
64
+ await nextFrame();
65
+
66
+ return hosts.map((host) => host.innerHTML);
67
+ } finally {
68
+ for (const root of roots) root.unmount();
69
+ container.remove();
70
+ restoreScan(previousScan);
71
+ }
72
+ }
73
+ export function collectCss(): string {
74
+ const chunks: string[] = [];
75
+ for (const sheet of Array.from(document.styleSheets)) {
76
+ let rules: CSSRuleList | null = null;
77
+ try {
78
+ rules = sheet.cssRules;
79
+ } catch {
80
+ continue;
81
+ }
82
+ if (!rules) continue;
83
+ for (const rule of Array.from(rules)) chunks.push(rule.cssText);
84
+ }
85
+ return chunks.join('\n');
86
+ }
87
+ export function collectExternalStylesheetLinks(): string {
88
+ const links: string[] = [];
89
+ for (const sheet of Array.from(document.styleSheets)) {
90
+ try {
91
+ void sheet.cssRules;
92
+ } catch {
93
+ if (sheet.href) links.push(`<link rel="stylesheet" href="${escapeAttr(sheet.href)}">`);
94
+ }
95
+ }
96
+ return links.join('\n');
97
+ }
98
+ export function findHtmlAssetUrls(html: string): string[] {
99
+ const out: string[] = [];
100
+ for (const m of html.matchAll(/\s(?:src|href)="([^"]+)"/g)) {
101
+ if (looksLikeAsset(m[1])) out.push(m[1]);
102
+ }
103
+ for (const m of html.matchAll(/\ssrcset="([^"]+)"/g)) {
104
+ for (const part of m[1].split(',')) {
105
+ const url = part.trim().split(/\s+/)[0];
106
+ if (url && looksLikeAsset(url)) out.push(url);
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+ export function findCssAssetUrls(css: string): string[] {
112
+ const out: string[] = [];
113
+ for (const m of css.matchAll(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/g)) {
114
+ const url = m[2].trim();
115
+ if (looksLikeAsset(url)) out.push(url);
116
+ }
117
+ return out;
118
+ }
119
+ export function looksLikeAsset(url: string): boolean {
120
+ if (!url) return false;
121
+ if (url.startsWith('data:') || url.startsWith('blob:') || url.startsWith('#')) return false;
122
+ if (url.startsWith('mailto:') || url.startsWith('javascript:')) return false;
123
+ const abs = toAbsolute(url);
124
+ if (!abs) return false;
125
+ try {
126
+ if (new URL(abs).origin !== window.location.origin) return false;
127
+ } catch {
128
+ return false;
129
+ }
130
+ return ASSET_EXT_RE.test(url);
131
+ }
132
+ export function toAbsolute(url: string): string | null {
133
+ try {
134
+ return new URL(url, window.location.href).toString();
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+ export function uniqueAssetName(absoluteUrl: string, used: Set<string>): string {
140
+ let base = 'asset';
141
+ try {
142
+ base = new URL(absoluteUrl).pathname.split('/').pop() || 'asset';
143
+ } catch {}
144
+ if (!used.has(base)) {
145
+ used.add(base);
146
+ return base;
147
+ }
148
+ const hash = shortHash(absoluteUrl);
149
+ const dot = base.lastIndexOf('.');
150
+ const name = dot > 0 ? `${base.slice(0, dot)}-${hash}${base.slice(dot)}` : `${base}-${hash}`;
151
+ used.add(name);
152
+ return name;
153
+ }
154
+ export function shortHash(input: string): string {
155
+ let h = 2166136261;
156
+ for (let i = 0; i < input.length; i++) {
157
+ h ^= input.charCodeAt(i);
158
+ h = Math.imul(h, 16777619);
159
+ }
160
+ return (h >>> 0).toString(36).slice(0, 6);
161
+ }
162
+ export function downloadBlob(blob: Blob, filename: string): void {
163
+ const url = URL.createObjectURL(blob);
164
+ const a = document.createElement('a');
165
+ a.href = url;
166
+ a.download = filename;
167
+ a.rel = 'noopener';
168
+ document.body.appendChild(a);
169
+ a.click();
170
+ a.remove();
171
+ setTimeout(() => URL.revokeObjectURL(url), 0);
172
+ }
173
+ export function escapeHtml(s: string): string {
174
+ return s
175
+ .replace(/&/g, '&amp;')
176
+ .replace(/</g, '&lt;')
177
+ .replace(/>/g, '&gt;')
178
+ .replace(/"/g, '&quot;')
179
+ .replace(/'/g, '&#39;');
180
+ }
181
+ export function escapeAttr(s: string): string {
182
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
183
+ }