@open-document/core 0.4.0 → 0.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -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
+ }
@@ -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
+ }
@@ -1,17 +1,22 @@
1
- import { createElement } from 'react';
2
- import { createRoot, type Root } from 'react-dom/client';
3
1
  import { designToCssVars } from './design';
2
+ import {
3
+ collectCss,
4
+ collectExternalStylesheetLinks,
5
+ downloadBlob,
6
+ escapeAttr,
7
+ escapeHtml,
8
+ findCssAssetUrls,
9
+ findHtmlAssetUrls,
10
+ renderPagesToHtml,
11
+ toAbsolute,
12
+ uniqueAssetName,
13
+ } from './export-dom';
4
14
  import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
5
- import { DocPageProvider } from './page-context';
6
- import { nextFrame, waitForFonts, waitForImages } from './print-ready';
7
- import { captureScan, restoreScan, scanDocument } from './scan';
8
15
  import { type DocModule, type PageGeometry, resolvePageGeometry } from './sdk';
9
16
  import type { ExpandedPage } from './use-doc-pages';
10
17
 
11
18
  type AssetEntry = { name: string; bytes: Uint8Array };
12
19
 
13
- const ASSET_EXT_RE = /\.(?:png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf)(?:\?[^#]*)?(?:#.*)?$/i;
14
-
15
20
  export type HtmlBundle = {
16
21
  filename: string;
17
22
  mimeType: 'text/html' | 'application/zip';
@@ -93,157 +98,6 @@ export async function exportDocAsHtml(
93
98
  downloadBlob(new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }), bundle.filename);
94
99
  }
95
100
 
96
- async function renderPagesToHtml(
97
- pages: ExpandedPage[],
98
- geometry: PageGeometry,
99
- doc: DocModule,
100
- ): Promise<string[]> {
101
- const container = document.createElement('div');
102
- container.setAttribute('aria-hidden', 'true');
103
- Object.assign(container.style, {
104
- position: 'fixed',
105
- left: '-99999px',
106
- top: '0',
107
- pointerEvents: 'none',
108
- });
109
- document.body.appendChild(container);
110
-
111
- const designVars = doc.design ? designToCssVars(doc.design) : null;
112
- const roots: Root[] = [];
113
- const hosts: HTMLElement[] = [];
114
- const previousScan = captureScan();
115
-
116
- try {
117
- for (let i = 0; i < pages.length; i++) {
118
- const page = pages[i];
119
- if (!page) continue;
120
- const host = document.createElement('div');
121
- host.setAttribute(PAGE_ATTR, '');
122
- host.setAttribute(PAGE_INDEX_ATTR, String(i));
123
- host.style.width = `${geometry.width}px`;
124
- host.style.height = `${geometry.height}px`;
125
- if (designVars) {
126
- for (const [k, v] of Object.entries(designVars)) host.style.setProperty(k, v);
127
- }
128
- container.appendChild(host);
129
- hosts.push(host);
130
- const root = createRoot(host);
131
- root.render(createElement(DocPageProvider, { index: i, total: pages.length }, page.content));
132
- roots.push(root);
133
- }
134
-
135
- await nextFrame();
136
- await waitForFonts();
137
- await waitForImages(container);
138
- scanDocument(container, doc.meta);
139
- await nextFrame();
140
- await nextFrame();
141
-
142
- return hosts.map((host) => host.innerHTML);
143
- } finally {
144
- for (const root of roots) root.unmount();
145
- container.remove();
146
- restoreScan(previousScan);
147
- }
148
- }
149
-
150
- function collectCss(): string {
151
- const chunks: string[] = [];
152
- for (const sheet of Array.from(document.styleSheets)) {
153
- let rules: CSSRuleList | null = null;
154
- try {
155
- rules = sheet.cssRules;
156
- } catch {
157
- continue;
158
- }
159
- if (!rules) continue;
160
- for (const rule of Array.from(rules)) chunks.push(rule.cssText);
161
- }
162
- return chunks.join('\n');
163
- }
164
-
165
- function collectExternalStylesheetLinks(): string {
166
- const links: string[] = [];
167
- for (const sheet of Array.from(document.styleSheets)) {
168
- try {
169
- void sheet.cssRules;
170
- } catch {
171
- if (sheet.href) links.push(`<link rel="stylesheet" href="${escapeAttr(sheet.href)}">`);
172
- }
173
- }
174
- return links.join('\n');
175
- }
176
-
177
- function findHtmlAssetUrls(html: string): string[] {
178
- const out: string[] = [];
179
- for (const m of html.matchAll(/\s(?:src|href)="([^"]+)"/g)) {
180
- if (looksLikeAsset(m[1])) out.push(m[1]);
181
- }
182
- for (const m of html.matchAll(/\ssrcset="([^"]+)"/g)) {
183
- for (const part of m[1].split(',')) {
184
- const url = part.trim().split(/\s+/)[0];
185
- if (url && looksLikeAsset(url)) out.push(url);
186
- }
187
- }
188
- return out;
189
- }
190
-
191
- function findCssAssetUrls(css: string): string[] {
192
- const out: string[] = [];
193
- for (const m of css.matchAll(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/g)) {
194
- const url = m[2].trim();
195
- if (looksLikeAsset(url)) out.push(url);
196
- }
197
- return out;
198
- }
199
-
200
- function looksLikeAsset(url: string): boolean {
201
- if (!url) return false;
202
- if (url.startsWith('data:') || url.startsWith('blob:') || url.startsWith('#')) return false;
203
- if (url.startsWith('mailto:') || url.startsWith('javascript:')) return false;
204
- const abs = toAbsolute(url);
205
- if (!abs) return false;
206
- try {
207
- if (new URL(abs).origin !== window.location.origin) return false;
208
- } catch {
209
- return false;
210
- }
211
- return ASSET_EXT_RE.test(url);
212
- }
213
-
214
- function toAbsolute(url: string): string | null {
215
- try {
216
- return new URL(url, window.location.href).toString();
217
- } catch {
218
- return null;
219
- }
220
- }
221
-
222
- function uniqueAssetName(absoluteUrl: string, used: Set<string>): string {
223
- let base = 'asset';
224
- try {
225
- base = new URL(absoluteUrl).pathname.split('/').pop() || 'asset';
226
- } catch {}
227
- if (!used.has(base)) {
228
- used.add(base);
229
- return base;
230
- }
231
- const hash = shortHash(absoluteUrl);
232
- const dot = base.lastIndexOf('.');
233
- const name = dot > 0 ? `${base.slice(0, dot)}-${hash}${base.slice(dot)}` : `${base}-${hash}`;
234
- used.add(name);
235
- return name;
236
- }
237
-
238
- function shortHash(input: string): string {
239
- let h = 2166136261;
240
- for (let i = 0; i < input.length; i++) {
241
- h ^= input.charCodeAt(i);
242
- h = Math.imul(h, 16777619);
243
- }
244
- return (h >>> 0).toString(36).slice(0, 6);
245
- }
246
-
247
101
  function rewriteUrls(
248
102
  source: string,
249
103
  assets: Map<string, AssetEntry>,
@@ -306,28 +160,3 @@ ${pagesMarkup}
306
160
  </body>
307
161
  </html>`;
308
162
  }
309
-
310
- function escapeHtml(s: string): string {
311
- return s
312
- .replace(/&/g, '&amp;')
313
- .replace(/</g, '&lt;')
314
- .replace(/>/g, '&gt;')
315
- .replace(/"/g, '&quot;')
316
- .replace(/'/g, '&#39;');
317
- }
318
-
319
- function escapeAttr(s: string): string {
320
- return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
321
- }
322
-
323
- function downloadBlob(blob: Blob, filename: string): void {
324
- const url = URL.createObjectURL(blob);
325
- const a = document.createElement('a');
326
- a.href = url;
327
- a.download = filename;
328
- a.rel = 'noopener';
329
- document.body.appendChild(a);
330
- a.click();
331
- a.remove();
332
- setTimeout(() => URL.revokeObjectURL(url), 0);
333
- }