Repository navigation
Expand file tree
/
Copy pathcapture.js
More file actions
288 lines (288 loc) · 9.97 KB
/
Copy pathcapture.js
File metadata and controls
288 lines (288 loc) · 9.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/* Runs in the isolated content world. Page scripts never receive credentials. */
(() => {
const escape = (value) => value.replace(/[\\`*_[\]<>]/g, "\\$&");
const safeUrl = (value) => {
try {
const url = new URL(value, document.baseURI);
return ["https:", "http:", "mailto:"].includes(url.protocol)
? url.href
: null;
} catch {
return null;
}
};
function capture(mode, savedRange) {
if (!["page", "selection"].includes(mode))
throw Error("clipper_invalid_input");
const images = [],
knownImages = new Map(),
warnings = [];
let source, originals;
if (mode === "selection") {
const selection = window.getSelection(),
range =
savedRange ||
(selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : null);
if (!range || range.collapsed) throw Error("clipper_selection_missing");
source = document.createElement("div");
source.append(range.cloneContents());
originals = [...document.images].filter((image) =>
range.intersectsNode(image),
);
} else {
source = document.body.cloneNode(true);
originals = [...document.images];
// Hidden menus/modals can contain another full article or reference list.
// Use the original page's computed display before removing styles from
// the clone. Descendants of a display:none ancestor cannot be visible.
const elements = [...document.body.querySelectorAll("*")],
copies = [...source.querySelectorAll("*")],
hidden = new Set();
for (let i = 0; i < copies.length; i++) {
const original = elements[i];
if (!original) continue;
if (hidden.has(original.parentElement)) {
hidden.add(original);
continue;
}
// SVG styles/defs are not displayed themselves, but are required when
// serializing the complete visible SVG as an image.
if (
original.namespaceURI === "http://www.w3.org/2000/svg" &&
original.localName !== "svg"
)
continue;
if (window.getComputedStyle(original).display === "none") {
copies[i].setAttribute("hidden", "");
hidden.add(original);
}
}
}
const copies = [...source.querySelectorAll("img")];
for (let i = 0; i < copies.length; i++) {
const original = originals[i],
image = copies[i];
if (original)
image.setAttribute(
"src",
original.currentSrc || original.src || original.dataset.src || "",
);
if (original) {
const style = window.getComputedStyle(original);
if (style.display === "none" || style.visibility === "hidden")
image.hidden = true;
}
}
source
.querySelectorAll(
"script,style,noscript,template,form,input,textarea,select,button,[data-doca-capture-ui],[hidden],[aria-hidden='true']",
)
.forEach((node) => {
if (node.localName === "style" && node.closest("svg")) return;
node.remove();
});
let nodes = 0;
function walk(node, depth = 0) {
try {
return convertNode(node, depth);
} catch (error) {
if (
["clipper_content_too_large", "clipper_too_many_images"].includes(
error?.message,
)
)
throw error;
const name = node.nodeName?.toLowerCase() || "content";
warnings.push({
code: "contentConversionFailed",
message: `${name}: content preserved as plain text after a conversion failure`,
});
return `\n\n[Content not fully converted: ${name}]\n\n${escape(node.textContent || "")}\n\n`;
}
}
function convertNode(node, depth) {
if (++nodes > 100000 || depth > 60)
throw Error("clipper_content_too_large");
if (node.nodeType === Node.TEXT_NODE)
return escape(node.textContent.replace(/\s+/g, " "));
if (node.nodeType !== Node.ELEMENT_NODE) return "";
const tag = node.tagName.toLowerCase(),
children = () =>
[...node.childNodes].map((child) => walk(child, depth + 1)).join("");
if (tag === "br") return "\n";
if (tag === "svg") {
const image = document.createElement("img");
image.src =
"data:image/svg+xml;charset=utf-8," +
encodeURIComponent(new XMLSerializer().serializeToString(node));
image.alt =
node.getAttribute("aria-label") ||
node.querySelector("title")?.textContent ||
"SVG";
return walk(image, depth + 1);
}
if (tag === "img") {
let url = node.getAttribute("src");
if (!url) return node.alt ? escape(node.alt) : "";
try {
url = new URL(url, document.baseURI).href;
} catch {
url = "invalid:";
}
let id = knownImages.get(url);
if (!id) {
if (images.length >= 100) throw Error("clipper_too_many_images");
id = crypto.randomUUID();
knownImages.set(url, id);
const filename = (() => {
try {
if (/^data:image\/svg\+xml/i.test(url)) return "image.svg";
return decodeURIComponent(
new URL(url).pathname.split("/").pop() || "image",
)
.replace(/[\x00-\x1f/\\]/g, "_")
.slice(0, 200);
} catch {
return "image";
}
})();
images.push({ id, url, name: filename || "image" });
}
const alt =
(node.alt || "image").replace(/\s+/g, " ").trim() || "image";
return ``;
}
if (tag === "pre") {
const text = node.textContent,
fence = text.includes("```") ? "~~~~" : "```";
return `\n\n${fence}\n${text}\n${fence}\n\n`;
}
if (tag === "code")
return "`" + node.textContent.replaceAll("`", "\\`") + "`";
if (tag === "a") {
const url = safeUrl(node.getAttribute("href") || "");
const label = children();
if (!url) return label;
const target = url.replace(/[()<>\s]/g, (character) =>
encodeURIComponent(character),
);
// Keep media outside link labels: the document converter cannot parse
// nested image/link Markdown. Preserve the image and its target link.
const media = node.querySelector("img,svg");
if (media) {
const textOnly = node.cloneNode(true);
textOnly
.querySelectorAll("img,svg")
.forEach((image) => image.remove());
const text =
textOnly.textContent.trim().replace(/\s+/g, " ") ||
node.getAttribute("aria-label")?.replace(/\s+/g, " ").trim() ||
media.getAttribute("alt")?.replace(/\s+/g, " ").trim() ||
media
.querySelector("title")
?.textContent?.replace(/\s+/g, " ")
.trim() ||
url;
return `\n\n${label.trim()}\n\n[${escape(text)}](${target})\n\n`;
}
return `[${label || escape(url)}](${target})`;
}
if (["strong", "b"].includes(tag)) return `**${children()}**`;
if (["em", "i"].includes(tag)) return `*${children()}*`;
if (/^h[1-6]$/.test(tag))
return `\n\n${"#".repeat(Number(tag[1]))} ${children().trim()}\n\n`;
if (tag === "blockquote")
return (
"\n\n" +
children()
.trim()
.split("\n")
.map((line) => "> " + line)
.join("\n") +
"\n\n"
);
if (tag === "li") {
const prefix =
node.parentElement?.tagName === "OL"
? `${[...node.parentElement.children].indexOf(node) + 1}. `
: "- ";
return "\n" + prefix + children().trim();
}
if (tag === "table") {
const rows = [...node.querySelectorAll("tr")].map((row) =>
[...row.children]
.filter((cell) => ["TD", "TH"].includes(cell.tagName))
.map((cell) =>
walk(cell, depth + 1)
.trim()
.replaceAll("|", "\\|")
.replace(/\n+/g, " "),
),
);
const width = Math.max(0, ...rows.map((row) => row.length));
if (!width) return "";
const line = (row) =>
"| " +
Array.from({ length: width }, (_, i) => row[i] || "").join(" | ") +
" |";
return (
"\n\n" +
[
line(rows[0]),
line(Array(width).fill("---")),
...rows.slice(1).map(line),
].join("\n") +
"\n\n"
);
}
if (["iframe", "canvas", "video", "audio"].includes(tag)) {
const url = safeUrl(node.getAttribute("src") || "");
const label = `Embedded ${tag} not saved`;
warnings.push({
code: "embeddedContentSkipped",
message: url ? `${label}: ${url}` : label,
});
return `\n\n${
url
? `[${label}](${url.replace(/[()<>\s]/g, (character) => encodeURIComponent(character))})`
: `[${label}]`
}\n\n${children()}\n\n`;
}
const text = children();
return [
"p",
"div",
"section",
"article",
"main",
"header",
"footer",
"nav",
"ul",
"ol",
"figure",
"figcaption",
"hr",
].includes(tag)
? `\n\n${text}\n\n`
: text;
}
const markdown = walk(source)
.replace(/\n[ \t]+/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
if (!markdown) throw Error("clipper_content_empty");
if (new TextEncoder().encode(markdown).length > 512 * 1024)
throw Error("clipper_content_too_large");
return {
mode,
url: location.href,
title: (document.title || location.hostname).slice(0, 160),
capturedAt: new Date().toISOString(),
markdown,
images,
...(warnings.length ? { warnings } : {}),
};
}
globalThis.DocaCapture = { capture };
})();