@folijs/view 0.0.0-stage → 0.2.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/CHANGELOG.md +44 -0
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/clipboard.d.ts +45 -0
- package/dist/clipboard.d.ts.map +1 -0
- package/dist/clipboard.js +668 -0
- package/dist/clipboard.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/layout/flow.d.ts +91 -0
- package/dist/layout/flow.d.ts.map +1 -0
- package/dist/layout/flow.js +200 -0
- package/dist/layout/flow.js.map +1 -0
- package/dist/render.d.ts +45 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/render.js +166 -0
- package/dist/render.js.map +1 -0
- package/dist/view.d.ts +261 -0
- package/dist/view.d.ts.map +1 -0
- package/dist/view.js +1810 -0
- package/dist/view.js.map +1 -0
- package/package.json +31 -3
- package/src/clipboard.ts +708 -0
- package/src/index.ts +2 -0
- package/src/layout/flow.ts +281 -0
- package/src/render.ts +197 -0
- package/src/view.ts +1885 -0
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
import { Fragment, isSafeHref, parseContent, } from "@folijs/core";
|
|
2
|
+
import { PAGE_BREAK_ATTR, renderTree } from "./render.js";
|
|
3
|
+
/**
|
|
4
|
+
* Clipboard type for Foli content, read back first on paste: `{ open, content }`, the copied
|
|
5
|
+
* blocks as `DocJSON` and whether they were cut out of one block (see `Pasted.open`).
|
|
6
|
+
*/
|
|
7
|
+
export const FOLI_MIME = "application/x-foli+json";
|
|
8
|
+
/** Serializes `from..to` of `doc` for the clipboard. Hard breaks and block ends become "\n". */
|
|
9
|
+
export function serializeRange(doc, from, to, ownerDocument) {
|
|
10
|
+
// A slice inside one textblock holds only inline content: wrap it back in its ancestors.
|
|
11
|
+
const $from = doc.resolve(from);
|
|
12
|
+
let content = doc.slice(from, to).content;
|
|
13
|
+
for (let depth = $from.sharedDepth(to); depth > 0; depth--)
|
|
14
|
+
content = Fragment.from($from.node(depth).copy(content));
|
|
15
|
+
// Not validated: a cut-open list item may lack its first paragraph. The JSON is validated
|
|
16
|
+
// when pasted; the HTML is only markup.
|
|
17
|
+
const blocks = doc.type.createOpen(null, content);
|
|
18
|
+
const container = ownerDocument.createElement("div");
|
|
19
|
+
// Built with createElement/textContent (render.ts); reading innerHTML only serializes it.
|
|
20
|
+
// A range inside one textblock is that block's text: its lists around it stay out of the HTML
|
|
21
|
+
// (a word copied from a list item must not paste as a one-item list); the JSON keeps them.
|
|
22
|
+
const $to = doc.resolve(to);
|
|
23
|
+
const inline = $from.parent.isTextblock && $from.sameParent($to);
|
|
24
|
+
const htmlBlocks = inline
|
|
25
|
+
? [$from.parent.copy(doc.slice(from, to).content)]
|
|
26
|
+
: blocks.content.content;
|
|
27
|
+
renderTree(htmlBlocks, container, ownerDocument);
|
|
28
|
+
// Keep repeated and leading spaces in other apps.
|
|
29
|
+
for (const block of container.querySelectorAll("p, h1, h2, h3, h4, h5, h6"))
|
|
30
|
+
block.style.whiteSpace = "pre-wrap";
|
|
31
|
+
// How other apps (and print) recognize a page break; the editor itself does not need it.
|
|
32
|
+
for (const br of container.querySelectorAll(`br[${PAGE_BREAK_ATTR}]`))
|
|
33
|
+
br.style.cssText = "page-break-before: always; break-before: page";
|
|
34
|
+
return {
|
|
35
|
+
text: doc.textBetween(from, to, "\n", "\n"),
|
|
36
|
+
html: container.innerHTML,
|
|
37
|
+
json: JSON.stringify({ open: $from.sharedDepth(to) > 0, content: blocks.toJSON() }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The content of clipboard data, validated, or null. Priority: Foli JSON, then HTML, then plain
|
|
42
|
+
* text. Every format is validated by the schema (`parseContent`); a format that fails falls
|
|
43
|
+
* through to the next. `marks` are given to plain text (the marks typing would get at the
|
|
44
|
+
* insertion point).
|
|
45
|
+
*/
|
|
46
|
+
export function docFromClipboard(data, marks = []) {
|
|
47
|
+
const json = data.getData(FOLI_MIME);
|
|
48
|
+
const html = data.getData("text/html");
|
|
49
|
+
const text = data.getData("text/plain");
|
|
50
|
+
const candidates = [
|
|
51
|
+
() => {
|
|
52
|
+
if (!json)
|
|
53
|
+
return null;
|
|
54
|
+
const value = JSON.parse(json);
|
|
55
|
+
if (typeof value !== "object" || value === null)
|
|
56
|
+
return null;
|
|
57
|
+
const { open, content } = value;
|
|
58
|
+
return { content, open: open === true };
|
|
59
|
+
},
|
|
60
|
+
() => (html ? readHTML(html) : null),
|
|
61
|
+
() => (text ? { content: textToDoc(text, marks), open: true } : null),
|
|
62
|
+
];
|
|
63
|
+
for (const candidate of candidates) {
|
|
64
|
+
try {
|
|
65
|
+
const found = candidate();
|
|
66
|
+
if (!found)
|
|
67
|
+
continue;
|
|
68
|
+
return { doc: parseContent(found.content), open: found.open };
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// Invalid or unreadable in this format: try the next one.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
/** Plain text: one paragraph per line. */
|
|
77
|
+
export function textToDoc(text, marks = []) {
|
|
78
|
+
const lines = text.replace(/\r\n?/g, "\n").split("\n");
|
|
79
|
+
return {
|
|
80
|
+
type: "doc",
|
|
81
|
+
content: lines.map((line) => ({
|
|
82
|
+
type: "paragraph",
|
|
83
|
+
...(line
|
|
84
|
+
? {
|
|
85
|
+
content: [{ type: "text", text: line, ...(marks.length ? { marks: [...marks] } : {}) }],
|
|
86
|
+
}
|
|
87
|
+
: {}),
|
|
88
|
+
})),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const BLOCK_TAGS = new Set([
|
|
92
|
+
"address",
|
|
93
|
+
"article",
|
|
94
|
+
"aside",
|
|
95
|
+
"blockquote",
|
|
96
|
+
"dd",
|
|
97
|
+
"div",
|
|
98
|
+
"dl",
|
|
99
|
+
"dt",
|
|
100
|
+
"figcaption",
|
|
101
|
+
"figure",
|
|
102
|
+
"footer",
|
|
103
|
+
"h1",
|
|
104
|
+
"h2",
|
|
105
|
+
"h3",
|
|
106
|
+
"h4",
|
|
107
|
+
"h5",
|
|
108
|
+
"h6",
|
|
109
|
+
"header",
|
|
110
|
+
"hr",
|
|
111
|
+
"li",
|
|
112
|
+
"main",
|
|
113
|
+
"nav",
|
|
114
|
+
"ol",
|
|
115
|
+
"p",
|
|
116
|
+
"pre",
|
|
117
|
+
"section",
|
|
118
|
+
"table",
|
|
119
|
+
"tbody",
|
|
120
|
+
"td",
|
|
121
|
+
"tfoot",
|
|
122
|
+
"th",
|
|
123
|
+
"thead",
|
|
124
|
+
"tr",
|
|
125
|
+
"ul",
|
|
126
|
+
]);
|
|
127
|
+
/** Elements whose content is never document text. */
|
|
128
|
+
const SKIPPED_TAGS = new Set([
|
|
129
|
+
"audio",
|
|
130
|
+
"button",
|
|
131
|
+
"canvas",
|
|
132
|
+
"embed",
|
|
133
|
+
"head",
|
|
134
|
+
"iframe",
|
|
135
|
+
"img",
|
|
136
|
+
"input",
|
|
137
|
+
"link",
|
|
138
|
+
"meta",
|
|
139
|
+
"noscript",
|
|
140
|
+
"object",
|
|
141
|
+
"script",
|
|
142
|
+
"select",
|
|
143
|
+
"style",
|
|
144
|
+
"svg",
|
|
145
|
+
"template",
|
|
146
|
+
"textarea",
|
|
147
|
+
"title",
|
|
148
|
+
"video",
|
|
149
|
+
]);
|
|
150
|
+
const TAG_MARKS = new Map([
|
|
151
|
+
["b", "bold"],
|
|
152
|
+
["strong", "bold"],
|
|
153
|
+
["i", "italic"],
|
|
154
|
+
["em", "italic"],
|
|
155
|
+
["u", "underline"],
|
|
156
|
+
["ins", "underline"],
|
|
157
|
+
["s", "strike"],
|
|
158
|
+
["strike", "strike"],
|
|
159
|
+
["del", "strike"],
|
|
160
|
+
]);
|
|
161
|
+
const NAMED_COLORS = {
|
|
162
|
+
black: "#000000",
|
|
163
|
+
white: "#ffffff",
|
|
164
|
+
red: "#ff0000",
|
|
165
|
+
green: "#008000",
|
|
166
|
+
blue: "#0000ff",
|
|
167
|
+
yellow: "#ffff00",
|
|
168
|
+
gray: "#808080",
|
|
169
|
+
grey: "#808080",
|
|
170
|
+
silver: "#c0c0c0",
|
|
171
|
+
maroon: "#800000",
|
|
172
|
+
navy: "#000080",
|
|
173
|
+
purple: "#800080",
|
|
174
|
+
teal: "#008080",
|
|
175
|
+
olive: "#808000",
|
|
176
|
+
orange: "#ffa500",
|
|
177
|
+
lime: "#00ff00",
|
|
178
|
+
aqua: "#00ffff",
|
|
179
|
+
cyan: "#00ffff",
|
|
180
|
+
fuchsia: "#ff00ff",
|
|
181
|
+
magenta: "#ff00ff",
|
|
182
|
+
};
|
|
183
|
+
const hex2 = (n) => Math.max(0, Math.min(255, Math.round(n)))
|
|
184
|
+
.toString(16)
|
|
185
|
+
.padStart(2, "0");
|
|
186
|
+
/**
|
|
187
|
+
* A CSS color as the schema stores it (lowercase `#rrggbb`), or null: transparent, unknown
|
|
188
|
+
* (system colors such as Word's `windowtext`) or empty. Hex (3 or 6 digits), `rgb()`/`rgba()`
|
|
189
|
+
* and the basic named colors.
|
|
190
|
+
*/
|
|
191
|
+
export function parseColor(value) {
|
|
192
|
+
const color = value.trim().toLowerCase();
|
|
193
|
+
const named = NAMED_COLORS[color];
|
|
194
|
+
if (named)
|
|
195
|
+
return named;
|
|
196
|
+
const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color);
|
|
197
|
+
if (short)
|
|
198
|
+
return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`;
|
|
199
|
+
if (/^#[0-9a-f]{6}$/.test(color))
|
|
200
|
+
return color;
|
|
201
|
+
// rgb(r, g, b), rgb(r g b), rgba(r, g, b, a), rgb(r g b / a): split, no backtracking regex.
|
|
202
|
+
const body = /^rgba?\(([^()]*)\)$/.exec(color)?.[1];
|
|
203
|
+
if (body === undefined)
|
|
204
|
+
return null;
|
|
205
|
+
const parts = body.trim().split(/\s*[,/]\s*|\s+/);
|
|
206
|
+
if (parts.length < 3 || parts.length > 4)
|
|
207
|
+
return null;
|
|
208
|
+
if (!parts.every((part) => /^\d+(?:\.\d+)?%?$/.test(part)))
|
|
209
|
+
return null;
|
|
210
|
+
const numbers = parts.map((part) => Number.parseFloat(part));
|
|
211
|
+
if (numbers[3] === 0)
|
|
212
|
+
return null; // fully transparent
|
|
213
|
+
const hex = `#${hex2(numbers[0])}${hex2(numbers[1])}${hex2(numbers[2])}`;
|
|
214
|
+
return hex;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Marks of an element on top of the inherited ones: tags first, then inline styles; a link
|
|
218
|
+
* from `a[href]` when the href is safe (`isSafeHref`; links inside the source page, `#…`, are
|
|
219
|
+
* dropped); text color and highlight from inline elements only (a page's colored containers
|
|
220
|
+
* are layout, not formatting), black text and white highlight being the defaults.
|
|
221
|
+
*/
|
|
222
|
+
function marksOf(element, inherited) {
|
|
223
|
+
const marks = new Map(inherited);
|
|
224
|
+
const tag = element.localName;
|
|
225
|
+
const tagMark = TAG_MARKS.get(tag);
|
|
226
|
+
if (tagMark)
|
|
227
|
+
marks.set(tagMark, { type: tagMark });
|
|
228
|
+
if (tag === "a") {
|
|
229
|
+
const href = element.getAttribute("href")?.trim().replace(/ /g, "%20");
|
|
230
|
+
if (href && !href.startsWith("#") && isSafeHref(href)) {
|
|
231
|
+
marks.set("link", { type: "link", attrs: { href } });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const style = element.style;
|
|
235
|
+
if (!style)
|
|
236
|
+
return marks;
|
|
237
|
+
const weight = style.fontWeight;
|
|
238
|
+
// Google Docs wraps everything in <b style="font-weight:normal">.
|
|
239
|
+
if (/^(bold|bolder|[6-9]00)$/.test(weight))
|
|
240
|
+
marks.set("bold", { type: "bold" });
|
|
241
|
+
else if (/^(normal|lighter|[1-5]00)$/.test(weight))
|
|
242
|
+
marks.delete("bold");
|
|
243
|
+
if (/^(italic|oblique)/.test(style.fontStyle))
|
|
244
|
+
marks.set("italic", { type: "italic" });
|
|
245
|
+
else if (style.fontStyle === "normal")
|
|
246
|
+
marks.delete("italic");
|
|
247
|
+
const decoration = `${style.textDecorationLine} ${style.textDecoration}`;
|
|
248
|
+
if (decoration.includes("underline"))
|
|
249
|
+
marks.set("underline", { type: "underline" });
|
|
250
|
+
if (decoration.includes("line-through"))
|
|
251
|
+
marks.set("strike", { type: "strike" });
|
|
252
|
+
// `text-decoration: none` on a child does not remove a parent's line in CSS: keep it.
|
|
253
|
+
if (!BLOCK_TAGS.has(tag)) {
|
|
254
|
+
const color = parseColor(style.color || (tag === "font" ? (element.getAttribute("color") ?? "") : ""));
|
|
255
|
+
// Black is the default; white text comes from dark pages and would be invisible.
|
|
256
|
+
if (color === "#000000" || color === "#ffffff")
|
|
257
|
+
marks.delete("textColor");
|
|
258
|
+
else if (color)
|
|
259
|
+
marks.set("textColor", { type: "textColor", attrs: { color } });
|
|
260
|
+
const background = parseColor(style.backgroundColor);
|
|
261
|
+
if (background === "#ffffff")
|
|
262
|
+
marks.delete("highlight");
|
|
263
|
+
else if (background) {
|
|
264
|
+
marks.set("highlight", { type: "highlight", attrs: { color: background } });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return marks;
|
|
268
|
+
}
|
|
269
|
+
/** A block's own alignment (`text-align`, or the old `align` attribute), or undefined. */
|
|
270
|
+
function alignOf(element) {
|
|
271
|
+
const value = (element.style?.textAlign ||
|
|
272
|
+
element.getAttribute("align") ||
|
|
273
|
+
"").toLowerCase();
|
|
274
|
+
if (value === "left" || value === "start")
|
|
275
|
+
return "start";
|
|
276
|
+
if (value === "center" || value === "-webkit-center")
|
|
277
|
+
return "center";
|
|
278
|
+
if (value === "right" || value === "end")
|
|
279
|
+
return "end";
|
|
280
|
+
if (value === "justify")
|
|
281
|
+
return "justify";
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* A page break in pasted HTML: Foli's own `<br data-page-break>`, or a `<br>` or `<hr>` styled
|
|
286
|
+
* to break the page (Word writes `<br clear=all style='page-break-before:always'>`, Google Docs
|
|
287
|
+
* `<hr style="page-break-before:always;display:none">`).
|
|
288
|
+
*
|
|
289
|
+
* shortcut: a block styled to break before or after it (`<p style="page-break-before:always">`) loses the break; map it when a real capture needs it.
|
|
290
|
+
*/
|
|
291
|
+
function isPageBreak(element) {
|
|
292
|
+
if (element.localName !== "br" && element.localName !== "hr")
|
|
293
|
+
return false;
|
|
294
|
+
if (element.hasAttribute(PAGE_BREAK_ATTR))
|
|
295
|
+
return true;
|
|
296
|
+
const style = element.getAttribute("style") ?? "";
|
|
297
|
+
// Anchored on a property start, so Word's `mso-column-break-before` (a column break) is not one.
|
|
298
|
+
return /(?:^|[;\s])(?:page-)?break-(?:before|after)\s*:\s*(?:always|page)/i.test(style);
|
|
299
|
+
}
|
|
300
|
+
/** Hidden text, Word's list bullets and empty-paragraph fillers. */
|
|
301
|
+
function isNoise(element) {
|
|
302
|
+
const style = element.getAttribute("style") ?? "";
|
|
303
|
+
if (/mso-list:\s*ignore|mso-hide:\s*all/i.test(style))
|
|
304
|
+
return true;
|
|
305
|
+
if (element.style?.display === "none" || element.hasAttribute("hidden")) {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
return element.localName === "o:p" && !element.textContent?.replace(/[\s ]/g, "");
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* A Word list paragraph (`style="mso-list:l0 level2 lfo1"`): its list and level, and from its
|
|
312
|
+
* marker (the `mso-list:Ignore` span Word adds for other apps) whether it is numbered and
|
|
313
|
+
* where the numbering starts. Best effort: a marker ending in "." or ")" is a number or
|
|
314
|
+
* letter (numbered); anything else ("·", "o", "§") a bullet.
|
|
315
|
+
*/
|
|
316
|
+
function wordListItem(element) {
|
|
317
|
+
const match = /mso-list:\s*(l\d+)\s+level(\d+)/i.exec(element.getAttribute("style") ?? "");
|
|
318
|
+
if (!match)
|
|
319
|
+
return null;
|
|
320
|
+
let marker = "";
|
|
321
|
+
for (const child of element.querySelectorAll("[style]")) {
|
|
322
|
+
if (/mso-list:\s*ignore/i.test(child.getAttribute("style") ?? "")) {
|
|
323
|
+
marker = (child.textContent ?? "").replace(/[\s ]+/g, "");
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
// "1.", "a)", "(iv)", and multi-level "1.2." or "1.2": numbered; its last part is its number.
|
|
328
|
+
const ordered = /^\(?[0-9a-zA-Z]{1,6}(?:\.[0-9]{1,6})*[.)]$|^\d{1,6}(?:\.\d{1,6})+$/.test(marker);
|
|
329
|
+
const number = /(\d+)[.)]?$/.exec(marker);
|
|
330
|
+
return {
|
|
331
|
+
list: match[1],
|
|
332
|
+
level: Number(match[2]),
|
|
333
|
+
ordered,
|
|
334
|
+
start: ordered && number ? Number(number[1]) : 1,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/** A list item must start with a paragraph: a heading becomes one, else one is added. */
|
|
338
|
+
function finishItem(item) {
|
|
339
|
+
if (!item.content)
|
|
340
|
+
item.content = [];
|
|
341
|
+
const content = item.content;
|
|
342
|
+
const first = content[0];
|
|
343
|
+
if (first?.type === "heading") {
|
|
344
|
+
first.type = "paragraph";
|
|
345
|
+
const align = first.attrs?.align;
|
|
346
|
+
if (align)
|
|
347
|
+
first.attrs = { align };
|
|
348
|
+
else
|
|
349
|
+
delete first.attrs;
|
|
350
|
+
}
|
|
351
|
+
else if (first?.type !== "paragraph") {
|
|
352
|
+
content.unshift({ type: "paragraph" });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Own HTML reader: maps known tags and inline styles to the schema (paragraphs, headings,
|
|
357
|
+
* lists, rules; bold, italic, underline, strike, links, colors; alignment), drops everything
|
|
358
|
+
* else. The HTML is parsed into an inert document and never inserted.
|
|
359
|
+
*/
|
|
360
|
+
export function htmlToDoc(html) {
|
|
361
|
+
return readHTML(html)?.content ?? null;
|
|
362
|
+
}
|
|
363
|
+
/** `htmlToDoc`, plus whether the HTML had no block elements (`Pasted.open`). */
|
|
364
|
+
function readHTML(html) {
|
|
365
|
+
const parsed = new DOMParser().parseFromString(html, "text/html");
|
|
366
|
+
const doc = { type: "doc", content: [] };
|
|
367
|
+
const stack = [{ node: doc, kind: "doc" }];
|
|
368
|
+
let inline = null;
|
|
369
|
+
let blockType = "paragraph";
|
|
370
|
+
let level = 1;
|
|
371
|
+
let blockAlign;
|
|
372
|
+
let blockPre = false;
|
|
373
|
+
let sawBlock = false;
|
|
374
|
+
let afterSpace = true; // collapse leading and repeated whitespace like HTML layout does
|
|
375
|
+
const top = () => stack[stack.length - 1];
|
|
376
|
+
/** Where blocks go now: the open item or the document (text directly in a list gets an item). */
|
|
377
|
+
const container = () => {
|
|
378
|
+
if (top().kind === "list") {
|
|
379
|
+
const item = { type: "listItem", content: [] };
|
|
380
|
+
top().node.content.push(item);
|
|
381
|
+
stack.push({ node: item, kind: "item", implicit: true });
|
|
382
|
+
}
|
|
383
|
+
return top().node.content;
|
|
384
|
+
};
|
|
385
|
+
const lastBlock = () => {
|
|
386
|
+
const blocks = top().node.content;
|
|
387
|
+
return blocks[blocks.length - 1];
|
|
388
|
+
};
|
|
389
|
+
const open = (type, headingLevel = 1, pre = false, align = undefined) => {
|
|
390
|
+
inline = [];
|
|
391
|
+
blockType = type;
|
|
392
|
+
level = headingLevel;
|
|
393
|
+
blockAlign = align;
|
|
394
|
+
blockPre = pre;
|
|
395
|
+
afterSpace = true;
|
|
396
|
+
};
|
|
397
|
+
const close = (keepEmpty) => {
|
|
398
|
+
if (!inline)
|
|
399
|
+
return;
|
|
400
|
+
const last = inline[inline.length - 1];
|
|
401
|
+
if (last?.type === "hardBreak")
|
|
402
|
+
inline.pop(); // a trailing <br> adds no line in HTML
|
|
403
|
+
const tail = inline[inline.length - 1];
|
|
404
|
+
if (tail?.type === "text" && !blockPre)
|
|
405
|
+
tail.text = tail.text.replace(/ +$/, "");
|
|
406
|
+
// Non-breaking spaces survive the trimming above, then become ordinary spaces.
|
|
407
|
+
for (const node of inline) {
|
|
408
|
+
if (node.type === "text")
|
|
409
|
+
node.text = node.text.replace(/ /g, " ");
|
|
410
|
+
}
|
|
411
|
+
const content = inline.filter((node) => node.type !== "text" || node.text);
|
|
412
|
+
inline = null;
|
|
413
|
+
if (!content.length && !keepEmpty)
|
|
414
|
+
return;
|
|
415
|
+
const attrs = {};
|
|
416
|
+
if (blockType === "heading")
|
|
417
|
+
attrs.level = level;
|
|
418
|
+
if (blockAlign && blockAlign !== "start")
|
|
419
|
+
attrs.align = blockAlign;
|
|
420
|
+
container().push({
|
|
421
|
+
type: blockType,
|
|
422
|
+
...(Object.keys(attrs).length ? { attrs } : {}),
|
|
423
|
+
...(content.length ? { content } : {}),
|
|
424
|
+
});
|
|
425
|
+
};
|
|
426
|
+
const addText = (raw, marks, pre) => {
|
|
427
|
+
// Source formatting between blocks ("</p>\n<br>\n<p>") is not content.
|
|
428
|
+
if (!inline && !pre && !/[^ \t\n\r\f]/.test(raw))
|
|
429
|
+
return;
|
|
430
|
+
if (!inline) {
|
|
431
|
+
// Text of its own after Word list paragraphs ends them (it is not part of an item).
|
|
432
|
+
if (stack.some((entry) => entry.word))
|
|
433
|
+
closeWordLists();
|
|
434
|
+
open("paragraph", 1, pre);
|
|
435
|
+
}
|
|
436
|
+
const lines = pre ? raw.replace(/\r\n?/g, "\n").split("\n") : [raw];
|
|
437
|
+
lines.forEach((line, i) => {
|
|
438
|
+
if (i > 0)
|
|
439
|
+
addBreak();
|
|
440
|
+
let text = pre ? line : line.replace(/[ \t\n\r\f]+/g, " ");
|
|
441
|
+
if (!pre && afterSpace)
|
|
442
|
+
text = text.replace(/^ /, "");
|
|
443
|
+
if (!text)
|
|
444
|
+
return;
|
|
445
|
+
afterSpace = !pre && text.endsWith(" ");
|
|
446
|
+
// A link's own look (Google Docs' blue underline) is the link's, not formatting.
|
|
447
|
+
const markJSON = [...marks.values()].filter((mark) => !marks.has("link") || (mark.type !== "underline" && mark.type !== "textColor"));
|
|
448
|
+
inline.push({
|
|
449
|
+
type: "text",
|
|
450
|
+
text,
|
|
451
|
+
...(markJSON.length ? { marks: markJSON } : {}),
|
|
452
|
+
});
|
|
453
|
+
});
|
|
454
|
+
};
|
|
455
|
+
/** An explicit page break: in the open block, else at the end of the previous textblock. */
|
|
456
|
+
const addPageBreak = () => {
|
|
457
|
+
const previous = lastBlock();
|
|
458
|
+
if (inline)
|
|
459
|
+
inline.push({ type: "pageBreak" });
|
|
460
|
+
else if (previous && (previous.type === "paragraph" || previous.type === "heading")) {
|
|
461
|
+
previous.content = [...(previous.content ?? []), { type: "pageBreak" }];
|
|
462
|
+
}
|
|
463
|
+
else {
|
|
464
|
+
open("paragraph");
|
|
465
|
+
inline?.push({ type: "pageBreak" });
|
|
466
|
+
}
|
|
467
|
+
afterSpace = true;
|
|
468
|
+
};
|
|
469
|
+
const addBreak = () => {
|
|
470
|
+
// A <br> between blocks is an empty line (Google Docs writes empty paragraphs this way).
|
|
471
|
+
if (!inline) {
|
|
472
|
+
container().push({ type: "paragraph" });
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const list = inline;
|
|
476
|
+
const tail = list[list.length - 1];
|
|
477
|
+
if (tail?.type === "text")
|
|
478
|
+
tail.text = tail.text.replace(/ +$/, "");
|
|
479
|
+
list.push({ type: "hardBreak" });
|
|
480
|
+
afterSpace = true;
|
|
481
|
+
};
|
|
482
|
+
/** Closes the top container: an item gets its first paragraph, a list goes to its parent. */
|
|
483
|
+
const pop = () => {
|
|
484
|
+
const container = stack.pop();
|
|
485
|
+
if (container.kind === "item" && container.implicit && !container.node.content?.length) {
|
|
486
|
+
// An item opened for content that never came (`<ul><ul></ul></ul>`): not an empty bullet.
|
|
487
|
+
const items = top().node.content;
|
|
488
|
+
items.splice(items.indexOf(container.node), 1);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (container.kind === "item")
|
|
492
|
+
finishItem(container.node);
|
|
493
|
+
if (container.kind === "list" && container.node.content?.length) {
|
|
494
|
+
container.parent?.push(container.node);
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
/** Opens a list; one directly inside a list (sloppy HTML, Google Docs) nests in its last item. */
|
|
498
|
+
const openList = (ordered, start, word) => {
|
|
499
|
+
close(false);
|
|
500
|
+
if (top().kind === "list") {
|
|
501
|
+
const items = top().node.content;
|
|
502
|
+
let item = items[items.length - 1];
|
|
503
|
+
if (!item) {
|
|
504
|
+
item = { type: "listItem", content: [] };
|
|
505
|
+
items.push(item);
|
|
506
|
+
}
|
|
507
|
+
stack.push({ node: item, kind: "item", implicit: true });
|
|
508
|
+
}
|
|
509
|
+
const node = {
|
|
510
|
+
type: ordered ? "orderedList" : "bulletList",
|
|
511
|
+
...(ordered && start !== 1 && Number.isInteger(start) && start >= 0 && start <= 99_999
|
|
512
|
+
? { attrs: { start } }
|
|
513
|
+
: {}),
|
|
514
|
+
content: [],
|
|
515
|
+
};
|
|
516
|
+
stack.push({
|
|
517
|
+
node,
|
|
518
|
+
kind: "list",
|
|
519
|
+
parent: top().node.content,
|
|
520
|
+
...(word && { word }),
|
|
521
|
+
});
|
|
522
|
+
};
|
|
523
|
+
const openItem = (word) => {
|
|
524
|
+
close(false);
|
|
525
|
+
while (top().kind === "item" && (top().implicit || word))
|
|
526
|
+
pop();
|
|
527
|
+
const item = { type: "listItem", content: [] };
|
|
528
|
+
top().node.content.push(item);
|
|
529
|
+
stack.push({ node: item, kind: "item", ...(word && { word }) });
|
|
530
|
+
};
|
|
531
|
+
/** Word lists are flat paragraphs with levels: open and close lists to nest them. */
|
|
532
|
+
const wordItem = (item) => {
|
|
533
|
+
close(false);
|
|
534
|
+
const wordList = () => {
|
|
535
|
+
for (let i = stack.length - 1; i > 0; i--) {
|
|
536
|
+
const entry = stack[i];
|
|
537
|
+
if (entry.kind === "list" && entry.word)
|
|
538
|
+
return { entry, index: i };
|
|
539
|
+
}
|
|
540
|
+
return null;
|
|
541
|
+
};
|
|
542
|
+
for (let found = wordList(); found; found = wordList()) {
|
|
543
|
+
const { word } = found.entry;
|
|
544
|
+
if (!word)
|
|
545
|
+
break;
|
|
546
|
+
const same = word.level === item.level && word.list === item.list && word.ordered === item.ordered;
|
|
547
|
+
if (word.level < item.level || (same && word.level === item.level))
|
|
548
|
+
break;
|
|
549
|
+
while (stack.length > found.index)
|
|
550
|
+
pop();
|
|
551
|
+
}
|
|
552
|
+
const current = wordList();
|
|
553
|
+
const word = { list: item.list, level: item.level, ordered: item.ordered };
|
|
554
|
+
if (!current || current.entry.word?.level !== item.level) {
|
|
555
|
+
openList(item.ordered, item.start, word);
|
|
556
|
+
}
|
|
557
|
+
else {
|
|
558
|
+
// A sibling item: close the previous one (and anything nested in it).
|
|
559
|
+
while (stack.length > current.index + 1)
|
|
560
|
+
pop();
|
|
561
|
+
}
|
|
562
|
+
openItem(word);
|
|
563
|
+
};
|
|
564
|
+
const closeWordLists = () => {
|
|
565
|
+
close(false);
|
|
566
|
+
while (stack.some((entry) => entry.word))
|
|
567
|
+
pop();
|
|
568
|
+
};
|
|
569
|
+
/** Walks `node`; returns whether it contained a block element. */
|
|
570
|
+
const walk = (node, context) => {
|
|
571
|
+
if (node.nodeType === 3) {
|
|
572
|
+
addText(node.data, context.marks, context.pre);
|
|
573
|
+
return false;
|
|
574
|
+
}
|
|
575
|
+
if (node.nodeType !== 1)
|
|
576
|
+
return false; // comments (Word's conditional comments), etc.
|
|
577
|
+
const element = node;
|
|
578
|
+
const tag = element.localName;
|
|
579
|
+
// Before the noise check: Google Docs hides its page-break <hr> (display: none).
|
|
580
|
+
if (isPageBreak(element)) {
|
|
581
|
+
addPageBreak();
|
|
582
|
+
return false;
|
|
583
|
+
}
|
|
584
|
+
if (SKIPPED_TAGS.has(tag) || isNoise(element))
|
|
585
|
+
return false;
|
|
586
|
+
if (tag === "br") {
|
|
587
|
+
// Chrome marks "the copied range ended with a line break" this way; it is not content.
|
|
588
|
+
if (!element.classList.contains("Apple-interchange-newline"))
|
|
589
|
+
addBreak();
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
const whiteSpace = element.style?.whiteSpace ?? "";
|
|
593
|
+
const child = {
|
|
594
|
+
marks: marksOf(element, context.marks),
|
|
595
|
+
pre: context.pre || tag === "pre" || whiteSpace.startsWith("pre"),
|
|
596
|
+
align: BLOCK_TAGS.has(tag) ? (alignOf(element) ?? context.align) : context.align,
|
|
597
|
+
};
|
|
598
|
+
const children = () => {
|
|
599
|
+
let hasBlock = false;
|
|
600
|
+
for (const node of element.childNodes)
|
|
601
|
+
hasBlock = walk(node, child) || hasBlock;
|
|
602
|
+
return hasBlock;
|
|
603
|
+
};
|
|
604
|
+
if (!BLOCK_TAGS.has(tag))
|
|
605
|
+
return children();
|
|
606
|
+
sawBlock = true;
|
|
607
|
+
// Word list paragraphs: <p> only (a numbered Word heading stays a heading), and not inside an
|
|
608
|
+
// HTML list (Outlook writes `<li style="mso-list:…">` in real lists).
|
|
609
|
+
const word = tag === "p" && !stack.some((entry) => entry.kind === "list" && !entry.word)
|
|
610
|
+
? wordListItem(element)
|
|
611
|
+
: null;
|
|
612
|
+
if (word) {
|
|
613
|
+
wordItem(word);
|
|
614
|
+
open("paragraph", 1, child.pre, child.align);
|
|
615
|
+
children();
|
|
616
|
+
close(true);
|
|
617
|
+
return true;
|
|
618
|
+
}
|
|
619
|
+
// Word wraps its content in a <div>: only a block of its own content ends Word lists.
|
|
620
|
+
if (!/^(div|body|section|article|main)$/.test(tag))
|
|
621
|
+
closeWordLists();
|
|
622
|
+
// A list or item closes everything opened inside it, so unbalanced input cannot leak.
|
|
623
|
+
const base = stack.length;
|
|
624
|
+
const closeTo = (height) => {
|
|
625
|
+
close(false);
|
|
626
|
+
while (stack.length > height)
|
|
627
|
+
pop();
|
|
628
|
+
};
|
|
629
|
+
if (tag === "ul" || tag === "ol") {
|
|
630
|
+
const start = Number.parseInt(element.getAttribute("start") ?? "", 10);
|
|
631
|
+
openList(tag === "ol", Number.isNaN(start) ? 1 : start);
|
|
632
|
+
children();
|
|
633
|
+
closeTo(base);
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
if (tag === "li" && stack.some((entry) => entry.kind === "list")) {
|
|
637
|
+
// Inside a list item that is itself still open, an <li> is a sibling: close down to a list.
|
|
638
|
+
while (top().kind === "item")
|
|
639
|
+
closeTo(stack.length - 1);
|
|
640
|
+
const height = stack.length;
|
|
641
|
+
openItem();
|
|
642
|
+
children();
|
|
643
|
+
closeTo(height);
|
|
644
|
+
return true;
|
|
645
|
+
}
|
|
646
|
+
if (tag === "hr") {
|
|
647
|
+
close(false);
|
|
648
|
+
container().push({ type: "horizontalRule" });
|
|
649
|
+
return true;
|
|
650
|
+
}
|
|
651
|
+
close(false);
|
|
652
|
+
const heading = /^h([1-6])$/.exec(tag);
|
|
653
|
+
open(heading ? "heading" : "paragraph", heading ? Number(heading[1]) : 1, child.pre, child.align);
|
|
654
|
+
const hasBlock = children();
|
|
655
|
+
// <p></p> is an empty line; a container such as <div><p>…</p></div> adds none.
|
|
656
|
+
close(!hasBlock && !/^(ol|ul|dl|table|tbody|thead|tfoot|tr|li)$/.test(tag));
|
|
657
|
+
return true;
|
|
658
|
+
};
|
|
659
|
+
walk(parsed.body, { marks: new Map(), pre: false, align: undefined });
|
|
660
|
+
close(false);
|
|
661
|
+
while (stack.length > 1)
|
|
662
|
+
pop();
|
|
663
|
+
const content = doc.content;
|
|
664
|
+
return content.length
|
|
665
|
+
? { content: { type: "doc", content }, open: !sawBlock }
|
|
666
|
+
: null;
|
|
667
|
+
}
|
|
668
|
+
//# sourceMappingURL=clipboard.js.map
|