@folijs/view 0.1.0 → 0.3.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/src/clipboard.ts CHANGED
@@ -1,24 +1,43 @@
1
1
  import {
2
- type BlockJSON,
2
+ type Alignment,
3
+ copiedDefinitions,
3
4
  type DocJSON,
4
5
  Fragment,
5
6
  type InlineJSON,
7
+ isSafeHref,
6
8
  type MarkJSON,
7
- type MarkName,
8
9
  type Node as ModelNode,
9
- parseContent,
10
+ type ParagraphJSON,
11
+ type SimpleMarkName,
12
+ type WordContext,
13
+ type WordEnvelope,
10
14
  } from "@folijs/core";
11
- import { PAGE_BREAK_ATTR, renderBlock } from "./render.js";
15
+ import { PAGE_BREAK_ATTR } from "./render.js";
16
+ import { opaqueParagraphsText, parseOpaque } from "./word/blocks.js";
17
+ import { clipboardBlocks } from "./word/edit.js";
12
18
 
13
19
  /**
14
- * Clipboard type for Foli content, read back first on paste: `{ open, content }`, the copied
15
- * blocks as `DocJSON` and whether they were cut out of one block (see `Pasted.open`).
20
+ * Clipboard type for Foli content, read back first on paste: `{ open, content, word? }`, the
21
+ * copied blocks as `DocJSON`, whether they were cut out of one block (see `Pasted.open`), and
22
+ * from a schema v3 document the definitions they reference (`copiedDefinitions`).
16
23
  */
17
24
  export const FOLI_MIME = "application/x-foli+json";
18
25
 
26
+ /** One clipboard format's content, before validation. */
27
+ export interface Found {
28
+ content: unknown;
29
+ open: boolean;
30
+ /** Read from HTML: schema v2 content as `htmlToDoc` reads it. */
31
+ html?: boolean;
32
+ /** The definitions (styles, numbering, comments) a copy carries. */
33
+ word?: unknown;
34
+ }
35
+
19
36
  /** Validated clipboard content. */
20
37
  export interface Pasted {
21
38
  doc: ModelNode;
39
+ /** The target's envelope with what the content needs (styles, lists...), when it changed. */
40
+ envelope?: WordEnvelope;
22
41
  /**
23
42
  * True when no block boundary was copied (text from inside one block, plain text, inline
24
43
  * HTML): the content always joins the block it is pasted into, which keeps its type. Closed
@@ -33,65 +52,106 @@ export interface ClipboardContent {
33
52
  json: string;
34
53
  }
35
54
 
36
- /** Serializes `from..to` of `doc` for the clipboard. Hard breaks and block ends become "\n". */
55
+ /**
56
+ * Serializes `from..to` of `doc` for the clipboard. Hard breaks and block ends become "\n". The
57
+ * HTML is the document as its Word renderer draws it (`word`: its context and the fonts' line
58
+ * height ratios): resolved formatting as inline CSS, list numbers as Word's HTML has them.
59
+ */
37
60
  export function serializeRange(
38
61
  doc: ModelNode,
39
62
  from: number,
40
63
  to: number,
41
64
  ownerDocument: Document,
65
+ word: { context: WordContext; ratio: (family: string) => number },
42
66
  ): ClipboardContent {
43
67
  // A slice inside one textblock holds only inline content: wrap it back in its ancestors.
44
68
  const $from = doc.resolve(from);
45
69
  let content = doc.slice(from, to).content;
46
70
  for (let depth = $from.sharedDepth(to); depth > 0; depth--)
47
71
  content = Fragment.from($from.node(depth).copy(content));
48
- const blocks = doc.type.create(null, content);
72
+ // Not validated: the JSON is validated when pasted; the HTML is only markup.
73
+ const blocks = doc.type.createOpen(null, content);
49
74
  const container = ownerDocument.createElement("div");
50
- // Built with createElement/textContent (render.ts); reading innerHTML only serializes it.
51
- blocks.forEach((block) => {
52
- const { dom } = renderBlock(block, ownerDocument);
53
- dom.style.whiteSpace = "pre-wrap"; // keep repeated and leading spaces in other apps
54
- // How other apps (and print) recognize a page break; the editor itself does not need it.
55
- for (const br of dom.querySelectorAll(`br[${PAGE_BREAK_ATTR}]`))
56
- (br as HTMLElement).style.cssText = "page-break-before: always; break-before: page";
57
- container.append(dom);
58
- });
75
+ // Built with createElement/textContent (word/edit.ts); reading innerHTML only serializes it.
76
+ // A range inside one paragraph is that paragraph's text: its list number stays out of the HTML
77
+ // (a word copied from a list item must not paste as a one-item list); the JSON keeps it.
78
+ const $to = doc.resolve(to);
79
+ const inline = $from.parent.isTextblock && $from.sameParent($to);
80
+ const htmlBlocks = inline
81
+ ? [$from.parent.copy(doc.slice(from, to).content)]
82
+ : blocks.content.content;
83
+ const first = inline ? -1 : $from.index(0);
84
+ container.append(
85
+ ...clipboardBlocks(word.context, doc, htmlBlocks, first, ownerDocument, word.ratio),
86
+ );
87
+ // How other apps (and print) recognize a page break; the editor itself does not need it.
88
+ for (const br of container.querySelectorAll(`br[${PAGE_BREAK_ATTR}]`))
89
+ (br as HTMLElement).style.cssText = "page-break-before: always; break-before: page";
59
90
  return {
60
- text: doc.textBetween(from, to, "\n", "\n"),
91
+ text: doc.textBetween(from, to, "\n", (leaf) => leafText(leaf, ownerDocument)),
61
92
  html: container.innerHTML,
62
- json: JSON.stringify({ open: $from.sharedDepth(to) > 0, content: blocks.toJSON() }),
93
+ json: JSON.stringify({
94
+ open: $from.sharedDepth(to) > 0,
95
+ content: blocks.toJSON(),
96
+ word: copiedDefinitions(word.context, blocks),
97
+ }),
63
98
  };
64
99
  }
65
100
 
101
+ /**
102
+ * A leaf as plain text: breaks and rules as line feeds, a tab as a tab, opaque content as the
103
+ * text it shows (a field's result, a table's paragraphs on their lines), markers as nothing.
104
+ */
105
+ function leafText(leaf: ModelNode, doc: Document): string {
106
+ const name = leaf.type.name;
107
+ if (name === "tab") return "\t";
108
+ if (name === "opaqueInline" || name === "opaqueBlock") {
109
+ const xml = parseOpaque(String(leaf.attrs.xml ?? ""), doc);
110
+ const text = xml ? opaqueParagraphsText(xml) : "";
111
+ return leaf.isBlock ? `\n${text}` : text;
112
+ }
113
+ return leaf.isBlock || name === "hardBreak" || name === "pageBreak" || name === "columnBreak"
114
+ ? "\n"
115
+ : "";
116
+ }
117
+
66
118
  /**
67
119
  * The content of clipboard data, validated, or null. Priority: Foli JSON, then HTML, then plain
68
- * text. Every format is validated by the schema (`parseContent`); a format that fails falls
69
- * through to the next. `marks` are given to plain text (the marks typing would get at the
70
- * insertion point).
120
+ * text. Every format is validated and fitted to the document by `parse` (`fitPaste`,
121
+ * `fitPastedV2`); a format that fails falls through to the next. `marks` are given to plain text
122
+ * (the marks typing would get at the insertion point).
71
123
  */
72
124
  export function docFromClipboard(
73
125
  data: Pick<DataTransfer, "getData">,
74
- marks: readonly MarkJSON[] = [],
126
+ marks: readonly MarkJSON[],
127
+ parse: (found: Found) => Omit<Pasted, "open">,
75
128
  ): Pasted | null {
76
129
  const json = data.getData(FOLI_MIME);
77
130
  const html = data.getData("text/html");
78
131
  const text = data.getData("text/plain");
79
- const candidates: (() => { content: unknown; open: boolean } | null)[] = [
132
+ const candidates: (() => Found | null)[] = [
80
133
  () => {
81
134
  if (!json) return null;
82
135
  const value: unknown = JSON.parse(json);
83
136
  if (typeof value !== "object" || value === null) return null;
84
- const { open, content } = value as { open?: unknown; content?: unknown };
85
- return { content, open: open === true };
137
+ const { open, content, word } = value as {
138
+ open?: unknown;
139
+ content?: unknown;
140
+ word?: unknown;
141
+ };
142
+ return { content, open: open === true, word };
143
+ },
144
+ () => {
145
+ const read = html ? readHTML(html) : null;
146
+ return read && { ...read, html: true };
86
147
  },
87
- () => (html ? readHTML(html) : null),
88
148
  () => (text ? { content: textToDoc(text, marks), open: true } : null),
89
149
  ];
90
150
  for (const candidate of candidates) {
91
151
  try {
92
152
  const found = candidate();
93
153
  if (!found) continue;
94
- return { doc: parseContent(found.content), open: found.open };
154
+ return { ...parse(found), open: found.open };
95
155
  } catch {
96
156
  // Invalid or unreadable in this format: try the next one.
97
157
  }
@@ -111,7 +171,7 @@ export function textToDoc(text: string, marks: readonly MarkJSON[] = []): DocJSO
111
171
  content: [{ type: "text", text: line, ...(marks.length ? { marks: [...marks] } : {}) }],
112
172
  }
113
173
  : {}),
114
- })) as BlockJSON[],
174
+ })) as ParagraphJSON[],
115
175
  };
116
176
  }
117
177
 
@@ -176,7 +236,7 @@ const SKIPPED_TAGS = new Set([
176
236
  "video",
177
237
  ]);
178
238
 
179
- const TAG_MARKS: ReadonlyMap<string, MarkName> = new Map([
239
+ const TAG_MARKS: ReadonlyMap<string, SimpleMarkName> = new Map([
180
240
  ["b", "bold"],
181
241
  ["strong", "bold"],
182
242
  ["i", "italic"],
@@ -188,26 +248,120 @@ const TAG_MARKS: ReadonlyMap<string, MarkName> = new Map([
188
248
  ["del", "strike"],
189
249
  ]);
190
250
 
191
- /** Marks of an element on top of the inherited ones: tags first, then inline styles. */
192
- function marksOf(element: Element, inherited: ReadonlySet<MarkName>): Set<MarkName> {
193
- const marks = new Set(inherited);
194
- const tagMark = TAG_MARKS.get(element.localName);
195
- if (tagMark) marks.add(tagMark);
251
+ /** Marks by type: one of each (a link, a text color and a highlight carry attributes). */
252
+ type Marks = ReadonlyMap<string, MarkJSON>;
253
+
254
+ const NAMED_COLORS: Readonly<Record<string, string>> = {
255
+ black: "#000000",
256
+ white: "#ffffff",
257
+ red: "#ff0000",
258
+ green: "#008000",
259
+ blue: "#0000ff",
260
+ yellow: "#ffff00",
261
+ gray: "#808080",
262
+ grey: "#808080",
263
+ silver: "#c0c0c0",
264
+ maroon: "#800000",
265
+ navy: "#000080",
266
+ purple: "#800080",
267
+ teal: "#008080",
268
+ olive: "#808000",
269
+ orange: "#ffa500",
270
+ lime: "#00ff00",
271
+ aqua: "#00ffff",
272
+ cyan: "#00ffff",
273
+ fuchsia: "#ff00ff",
274
+ magenta: "#ff00ff",
275
+ };
276
+
277
+ const hex2 = (n: number) =>
278
+ Math.max(0, Math.min(255, Math.round(n)))
279
+ .toString(16)
280
+ .padStart(2, "0");
281
+
282
+ /**
283
+ * A CSS color as the schema stores it (lowercase `#rrggbb`), or null: transparent, unknown
284
+ * (system colors such as Word's `windowtext`) or empty. Hex (3 or 6 digits), `rgb()`/`rgba()`
285
+ * and the basic named colors.
286
+ */
287
+ export function parseColor(value: string): string | null {
288
+ const color = value.trim().toLowerCase();
289
+ const named = NAMED_COLORS[color];
290
+ if (named) return named;
291
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color);
292
+ if (short) return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`;
293
+ if (/^#[0-9a-f]{6}$/.test(color)) return color;
294
+ // rgb(r, g, b), rgb(r g b), rgba(r, g, b, a), rgb(r g b / a): split, no backtracking regex.
295
+ const body = /^rgba?\(([^()]*)\)$/.exec(color)?.[1];
296
+ if (body === undefined) return null;
297
+ const parts = body.trim().split(/\s*[,/]\s*|\s+/);
298
+ if (parts.length < 3 || parts.length > 4) return null;
299
+ if (!parts.every((part) => /^\d+(?:\.\d+)?%?$/.test(part))) return null;
300
+ const numbers = parts.map((part) => Number.parseFloat(part));
301
+ if (numbers[3] === 0) return null; // fully transparent
302
+ const hex = `#${hex2(numbers[0] as number)}${hex2(numbers[1] as number)}${hex2(numbers[2] as number)}`;
303
+ return hex;
304
+ }
305
+
306
+ /**
307
+ * Marks of an element on top of the inherited ones: tags first, then inline styles; a link
308
+ * from `a[href]` when the href is safe (`isSafeHref`; links inside the source page, `#…`, are
309
+ * dropped); text color and highlight from inline elements only (a page's colored containers
310
+ * are layout, not formatting), black text and white highlight being the defaults.
311
+ */
312
+ function marksOf(element: Element, inherited: Marks): Map<string, MarkJSON> {
313
+ const marks = new Map(inherited);
314
+ const tag = element.localName;
315
+ const tagMark = TAG_MARKS.get(tag);
316
+ if (tagMark) marks.set(tagMark, { type: tagMark });
317
+ if (tag === "a") {
318
+ const href = element.getAttribute("href")?.trim().replace(/ /g, "%20");
319
+ if (href && !href.startsWith("#") && isSafeHref(href)) {
320
+ marks.set("link", { type: "link", attrs: { href } } as MarkJSON);
321
+ }
322
+ }
196
323
  const style = (element as HTMLElement).style;
197
324
  if (!style) return marks;
198
325
  const weight = style.fontWeight;
199
326
  // Google Docs wraps everything in <b style="font-weight:normal">.
200
- if (/^(bold|bolder|[6-9]00)$/.test(weight)) marks.add("bold");
327
+ if (/^(bold|bolder|[6-9]00)$/.test(weight)) marks.set("bold", { type: "bold" });
201
328
  else if (/^(normal|lighter|[1-5]00)$/.test(weight)) marks.delete("bold");
202
- if (/^(italic|oblique)/.test(style.fontStyle)) marks.add("italic");
329
+ if (/^(italic|oblique)/.test(style.fontStyle)) marks.set("italic", { type: "italic" });
203
330
  else if (style.fontStyle === "normal") marks.delete("italic");
204
331
  const decoration = `${style.textDecorationLine} ${style.textDecoration}`;
205
- if (decoration.includes("underline")) marks.add("underline");
206
- if (decoration.includes("line-through")) marks.add("strike");
332
+ if (decoration.includes("underline")) marks.set("underline", { type: "underline" });
333
+ if (decoration.includes("line-through")) marks.set("strike", { type: "strike" });
207
334
  // `text-decoration: none` on a child does not remove a parent's line in CSS: keep it.
335
+ if (!BLOCK_TAGS.has(tag)) {
336
+ const color = parseColor(
337
+ style.color || (tag === "font" ? (element.getAttribute("color") ?? "") : ""),
338
+ );
339
+ // Black is the default; white text comes from dark pages and would be invisible.
340
+ if (color === "#000000" || color === "#ffffff") marks.delete("textColor");
341
+ else if (color) marks.set("textColor", { type: "textColor", attrs: { color } } as MarkJSON);
342
+ const background = parseColor(style.backgroundColor);
343
+ if (background === "#ffffff") marks.delete("highlight");
344
+ else if (background) {
345
+ marks.set("highlight", { type: "highlight", attrs: { color: background } } as MarkJSON);
346
+ }
347
+ }
208
348
  return marks;
209
349
  }
210
350
 
351
+ /** A block's own alignment (`text-align`, or the old `align` attribute), or undefined. */
352
+ function alignOf(element: Element): Alignment | undefined {
353
+ const value = (
354
+ (element as HTMLElement).style?.textAlign ||
355
+ element.getAttribute("align") ||
356
+ ""
357
+ ).toLowerCase();
358
+ if (value === "left" || value === "start") return "start";
359
+ if (value === "center" || value === "-webkit-center") return "center";
360
+ if (value === "right" || value === "end") return "end";
361
+ if (value === "justify") return "justify";
362
+ return undefined;
363
+ }
364
+
211
365
  /**
212
366
  * A page break in pasted HTML: Foli's own `<br data-page-break>`, or a `<br>` or `<hr>` styled
213
367
  * to break the page (Word writes `<br clear=all style='page-break-before:always'>`, Google Docs
@@ -230,12 +384,75 @@ function isNoise(element: Element): boolean {
230
384
  if ((element as HTMLElement).style?.display === "none" || element.hasAttribute("hidden")) {
231
385
  return true;
232
386
  }
233
- return element.localName === "o:p" && !element.textContent?.replace(/[\s ]/g, "");
387
+ return element.localName === "o:p" && !element.textContent?.replace(/[\s ]/g, "");
388
+ }
389
+
390
+ /**
391
+ * A Word list paragraph (`style="mso-list:l0 level2 lfo1"`): its list and level, and from its
392
+ * marker (the `mso-list:Ignore` span Word adds for other apps) whether it is numbered and
393
+ * where the numbering starts. Best effort: a marker ending in "." or ")" is a number or
394
+ * letter (numbered); anything else ("·", "o", "§") a bullet.
395
+ */
396
+ function wordListItem(
397
+ element: Element,
398
+ ): { list: string; level: number; ordered: boolean; start: number } | null {
399
+ const match = /mso-list:\s*(l\d+)\s+level(\d+)/i.exec(element.getAttribute("style") ?? "");
400
+ if (!match) return null;
401
+ let marker = "";
402
+ for (const child of element.querySelectorAll("[style]")) {
403
+ if (/mso-list:\s*ignore/i.test(child.getAttribute("style") ?? "")) {
404
+ marker = (child.textContent ?? "").replace(/[\s ]+/g, "");
405
+ break;
406
+ }
407
+ }
408
+ // "1.", "a)", "(iv)", and multi-level "1.2." or "1.2": numbered; its last part is its number.
409
+ const ordered = /^\(?[0-9a-zA-Z]{1,6}(?:\.[0-9]{1,6})*[.)]$|^\d{1,6}(?:\.\d{1,6})+$/.test(marker);
410
+ const number = /(\d+)[.)]?$/.exec(marker);
411
+ return {
412
+ list: match[1] as string,
413
+ level: Number(match[2]),
414
+ ordered,
415
+ start: ordered && number ? Number(number[1]) : 1,
416
+ };
417
+ }
418
+
419
+ /** Loose block JSON while reading (validated by the schema afterwards). */
420
+ interface BlockNode {
421
+ type: string;
422
+ attrs?: Record<string, unknown>;
423
+ content?: (BlockNode | InlineJSON)[];
424
+ }
425
+
426
+ interface Container {
427
+ node: BlockNode;
428
+ kind: "doc" | "list" | "item";
429
+ /** An item the reader opened itself (text directly in a list, a list nested in a list). */
430
+ implicit?: boolean;
431
+ /** Where a list goes when it closes (lists with no items are dropped). */
432
+ parent?: BlockNode[];
433
+ /** A Word list paragraph's list and level (Word lists are flat paragraphs). */
434
+ word?: { list: string; level: number; ordered: boolean };
435
+ }
436
+
437
+ /** A list item must start with a paragraph: a heading becomes one, else one is added. */
438
+ function finishItem(item: BlockNode): void {
439
+ if (!item.content) item.content = [];
440
+ const content = item.content as BlockNode[];
441
+ const first = content[0];
442
+ if (first?.type === "heading") {
443
+ first.type = "paragraph";
444
+ const align = first.attrs?.align;
445
+ if (align) first.attrs = { align };
446
+ else delete first.attrs;
447
+ } else if (first?.type !== "paragraph") {
448
+ content.unshift({ type: "paragraph" });
449
+ }
234
450
  }
235
451
 
236
452
  /**
237
- * Own HTML reader: maps known tags and inline styles to schema v1, drops everything else
238
- * (links keep their text). The HTML is parsed into an inert document and never inserted.
453
+ * Own HTML reader: maps known tags and inline styles to the schema (paragraphs, headings,
454
+ * lists, rules; bold, italic, underline, strike, links, colors; alignment), drops everything
455
+ * else. The HTML is parsed into an inert document and never inserted.
239
456
  */
240
457
  export function htmlToDoc(html: string): DocJSON | null {
241
458
  return readHTML(html)?.content ?? null;
@@ -244,18 +461,41 @@ export function htmlToDoc(html: string): DocJSON | null {
244
461
  /** `htmlToDoc`, plus whether the HTML had no block elements (`Pasted.open`). */
245
462
  function readHTML(html: string): { content: DocJSON; open: boolean } | null {
246
463
  const parsed = new DOMParser().parseFromString(html, "text/html");
247
- const blocks: BlockJSON[] = [];
464
+ const doc: BlockNode = { type: "doc", content: [] };
465
+ const stack: Container[] = [{ node: doc, kind: "doc" }];
248
466
  let inline: InlineJSON[] | null = null;
249
- let blockType: BlockJSON["type"] = "paragraph";
467
+ let blockType: "paragraph" | "heading" = "paragraph";
250
468
  let level = 1;
469
+ let blockAlign: Alignment | undefined;
251
470
  let blockPre = false;
252
471
  let sawBlock = false;
253
472
  let afterSpace = true; // collapse leading and repeated whitespace like HTML layout does
254
473
 
255
- const open = (type: BlockJSON["type"], headingLevel = 1, pre = false) => {
474
+ const top = () => stack[stack.length - 1] as Container;
475
+ /** Where blocks go now: the open item or the document (text directly in a list gets an item). */
476
+ const container = (): BlockNode[] => {
477
+ if (top().kind === "list") {
478
+ const item: BlockNode = { type: "listItem", content: [] };
479
+ (top().node.content as BlockNode[]).push(item);
480
+ stack.push({ node: item, kind: "item", implicit: true });
481
+ }
482
+ return top().node.content as BlockNode[];
483
+ };
484
+ const lastBlock = (): BlockNode | undefined => {
485
+ const blocks = top().node.content as BlockNode[];
486
+ return blocks[blocks.length - 1];
487
+ };
488
+
489
+ const open = (
490
+ type: "paragraph" | "heading",
491
+ headingLevel = 1,
492
+ pre = false,
493
+ align: Alignment | undefined = undefined,
494
+ ) => {
256
495
  inline = [];
257
496
  blockType = type;
258
497
  level = headingLevel;
498
+ blockAlign = align;
259
499
  blockPre = pre;
260
500
  afterSpace = true;
261
501
  };
@@ -267,22 +507,28 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
267
507
  if (tail?.type === "text" && !blockPre) tail.text = tail.text.replace(/ +$/, "");
268
508
  // Non-breaking spaces survive the trimming above, then become ordinary spaces.
269
509
  for (const node of inline) {
270
- if (node.type === "text") node.text = node.text.replace(/\u00a0/g, " ");
510
+ if (node.type === "text") node.text = node.text.replace(/ /g, " ");
271
511
  }
272
512
  const content = inline.filter((node) => node.type !== "text" || node.text);
273
- if (content.length || keepEmpty) {
274
- blocks.push(
275
- blockType === "heading"
276
- ? ({ type: "heading", attrs: { level }, content } as BlockJSON)
277
- : ({ type: "paragraph", content } as BlockJSON),
278
- );
279
- }
280
513
  inline = null;
514
+ if (!content.length && !keepEmpty) return;
515
+ const attrs: Record<string, unknown> = {};
516
+ if (blockType === "heading") attrs.level = level;
517
+ if (blockAlign && blockAlign !== "start") attrs.align = blockAlign;
518
+ container().push({
519
+ type: blockType,
520
+ ...(Object.keys(attrs).length ? { attrs } : {}),
521
+ ...(content.length ? { content } : {}),
522
+ });
281
523
  };
282
- const addText = (raw: string, marks: ReadonlySet<MarkName>, pre: boolean) => {
524
+ const addText = (raw: string, marks: Marks, pre: boolean) => {
283
525
  // Source formatting between blocks ("</p>\n<br>\n<p>") is not content.
284
526
  if (!inline && !pre && !/[^ \t\n\r\f]/.test(raw)) return;
285
- if (!inline) open("paragraph", 1, pre);
527
+ if (!inline) {
528
+ // Text of its own after Word list paragraphs ends them (it is not part of an item).
529
+ if (stack.some((entry) => entry.word)) closeWordLists();
530
+ open("paragraph", 1, pre);
531
+ }
286
532
  const lines = pre ? raw.replace(/\r\n?/g, "\n").split("\n") : [raw];
287
533
  lines.forEach((line, i) => {
288
534
  if (i > 0) addBreak();
@@ -290,7 +536,10 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
290
536
  if (!pre && afterSpace) text = text.replace(/^ /, "");
291
537
  if (!text) return;
292
538
  afterSpace = !pre && text.endsWith(" ");
293
- const markJSON = [...marks].map((type) => ({ type }));
539
+ // A link's own look (Google Docs' blue underline) is the link's, not formatting.
540
+ const markJSON = [...marks.values()].filter(
541
+ (mark) => !marks.has("link") || (mark.type !== "underline" && mark.type !== "textColor"),
542
+ );
294
543
  (inline as InlineJSON[]).push({
295
544
  type: "text",
296
545
  text,
@@ -298,12 +547,13 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
298
547
  } as InlineJSON);
299
548
  });
300
549
  };
301
- /** An explicit page break: in the open block, else at the end of the previous one. */
550
+ /** An explicit page break: in the open block, else at the end of the previous textblock. */
302
551
  const addPageBreak = () => {
303
- const previous = blocks[blocks.length - 1];
552
+ const previous = lastBlock();
304
553
  if (inline) inline.push({ type: "pageBreak" });
305
- else if (previous) previous.content = [...(previous.content ?? []), { type: "pageBreak" }];
306
- else {
554
+ else if (previous && (previous.type === "paragraph" || previous.type === "heading")) {
555
+ previous.content = [...(previous.content ?? []), { type: "pageBreak" }];
556
+ } else {
307
557
  open("paragraph");
308
558
  (inline as InlineJSON[] | null)?.push({ type: "pageBreak" });
309
559
  }
@@ -312,7 +562,7 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
312
562
  const addBreak = () => {
313
563
  // A <br> between blocks is an empty line (Google Docs writes empty paragraphs this way).
314
564
  if (!inline) {
315
- blocks.push({ type: "paragraph" } as BlockJSON);
565
+ container().push({ type: "paragraph" });
316
566
  return;
317
567
  }
318
568
  const list = inline as InlineJSON[];
@@ -322,10 +572,97 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
322
572
  afterSpace = true;
323
573
  };
324
574
 
575
+ /** Closes the top container: an item gets its first paragraph, a list goes to its parent. */
576
+ const pop = () => {
577
+ const container = stack.pop() as Container;
578
+ if (container.kind === "item" && container.implicit && !container.node.content?.length) {
579
+ // An item opened for content that never came (`<ul><ul></ul></ul>`): not an empty bullet.
580
+ const items = top().node.content as BlockNode[];
581
+ items.splice(items.indexOf(container.node), 1);
582
+ return;
583
+ }
584
+ if (container.kind === "item") finishItem(container.node);
585
+ if (container.kind === "list" && container.node.content?.length) {
586
+ container.parent?.push(container.node);
587
+ }
588
+ };
589
+ /** Opens a list; one directly inside a list (sloppy HTML, Google Docs) nests in its last item. */
590
+ const openList = (ordered: boolean, start: number, word?: Container["word"]) => {
591
+ close(false);
592
+ if (top().kind === "list") {
593
+ const items = top().node.content as BlockNode[];
594
+ let item = items[items.length - 1];
595
+ if (!item) {
596
+ item = { type: "listItem", content: [] };
597
+ items.push(item);
598
+ }
599
+ stack.push({ node: item, kind: "item", implicit: true });
600
+ }
601
+ const node: BlockNode = {
602
+ type: ordered ? "orderedList" : "bulletList",
603
+ ...(ordered && start !== 1 && Number.isInteger(start) && start >= 0 && start <= 99_999
604
+ ? { attrs: { start } }
605
+ : {}),
606
+ content: [],
607
+ };
608
+ stack.push({
609
+ node,
610
+ kind: "list",
611
+ parent: top().node.content as BlockNode[],
612
+ ...(word && { word }),
613
+ });
614
+ };
615
+ const openItem = (word?: Container["word"]) => {
616
+ close(false);
617
+ while (top().kind === "item" && (top().implicit || word)) pop();
618
+ const item: BlockNode = { type: "listItem", content: [] };
619
+ (top().node.content as BlockNode[]).push(item);
620
+ stack.push({ node: item, kind: "item", ...(word && { word }) });
621
+ };
622
+
623
+ /** Word lists are flat paragraphs with levels: open and close lists to nest them. */
624
+ const wordItem = (item: NonNullable<ReturnType<typeof wordListItem>>) => {
625
+ close(false);
626
+ const wordList = () => {
627
+ for (let i = stack.length - 1; i > 0; i--) {
628
+ const entry = stack[i] as Container;
629
+ if (entry.kind === "list" && entry.word) return { entry, index: i };
630
+ }
631
+ return null;
632
+ };
633
+ for (let found = wordList(); found; found = wordList()) {
634
+ const { word } = found.entry;
635
+ if (!word) break;
636
+ const same =
637
+ word.level === item.level && word.list === item.list && word.ordered === item.ordered;
638
+ if (word.level < item.level || (same && word.level === item.level)) break;
639
+ while (stack.length > found.index) pop();
640
+ }
641
+ const current = wordList();
642
+ const word = { list: item.list, level: item.level, ordered: item.ordered };
643
+ if (!current || current.entry.word?.level !== item.level) {
644
+ openList(item.ordered, item.start, word);
645
+ } else {
646
+ // A sibling item: close the previous one (and anything nested in it).
647
+ while (stack.length > current.index + 1) pop();
648
+ }
649
+ openItem(word);
650
+ };
651
+ const closeWordLists = () => {
652
+ close(false);
653
+ while (stack.some((entry) => entry.word)) pop();
654
+ };
655
+
656
+ interface Context {
657
+ marks: Marks;
658
+ pre: boolean;
659
+ align: Alignment | undefined;
660
+ }
661
+
325
662
  /** Walks `node`; returns whether it contained a block element. */
326
- const walk = (node: Node, marks: ReadonlySet<MarkName>, pre: boolean): boolean => {
663
+ const walk = (node: Node, context: Context): boolean => {
327
664
  if (node.nodeType === 3) {
328
- addText((node as Text).data, marks, pre);
665
+ addText((node as Text).data, context.marks, context.pre);
329
666
  return false;
330
667
  }
331
668
  if (node.nodeType !== 1) return false; // comments (Word's conditional comments), etc.
@@ -342,28 +679,80 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
342
679
  if (!element.classList.contains("Apple-interchange-newline")) addBreak();
343
680
  return false;
344
681
  }
345
- const childMarks = marksOf(element, marks);
346
682
  const whiteSpace = (element as HTMLElement).style?.whiteSpace ?? "";
347
- const childPre = pre || tag === "pre" || whiteSpace.startsWith("pre");
348
- if (!BLOCK_TAGS.has(tag)) {
683
+ const child: Context = {
684
+ marks: marksOf(element, context.marks),
685
+ pre: context.pre || tag === "pre" || whiteSpace.startsWith("pre"),
686
+ align: BLOCK_TAGS.has(tag) ? (alignOf(element) ?? context.align) : context.align,
687
+ };
688
+ const children = () => {
349
689
  let hasBlock = false;
350
- for (const child of element.childNodes)
351
- hasBlock = walk(child, childMarks, childPre) || hasBlock;
690
+ for (const node of element.childNodes) hasBlock = walk(node, child) || hasBlock;
352
691
  return hasBlock;
353
- }
692
+ };
693
+ if (!BLOCK_TAGS.has(tag)) return children();
354
694
  sawBlock = true;
695
+ // Word list paragraphs: <p> only (a numbered Word heading stays a heading), and not inside an
696
+ // HTML list (Outlook writes `<li style="mso-list:…">` in real lists).
697
+ const word =
698
+ tag === "p" && !stack.some((entry) => entry.kind === "list" && !entry.word)
699
+ ? wordListItem(element)
700
+ : null;
701
+ if (word) {
702
+ wordItem(word);
703
+ open("paragraph", 1, child.pre, child.align);
704
+ children();
705
+ close(true);
706
+ return true;
707
+ }
708
+ // Word wraps its content in a <div>: only a block of its own content ends Word lists.
709
+ if (!/^(div|body|section|article|main)$/.test(tag)) closeWordLists();
710
+ // A list or item closes everything opened inside it, so unbalanced input cannot leak.
711
+ const base = stack.length;
712
+ const closeTo = (height: number) => {
713
+ close(false);
714
+ while (stack.length > height) pop();
715
+ };
716
+ if (tag === "ul" || tag === "ol") {
717
+ const start = Number.parseInt(element.getAttribute("start") ?? "", 10);
718
+ openList(tag === "ol", Number.isNaN(start) ? 1 : start);
719
+ children();
720
+ closeTo(base);
721
+ return true;
722
+ }
723
+ if (tag === "li" && stack.some((entry) => entry.kind === "list")) {
724
+ // Inside a list item that is itself still open, an <li> is a sibling: close down to a list.
725
+ while (top().kind === "item") closeTo(stack.length - 1);
726
+ const height = stack.length;
727
+ openItem();
728
+ children();
729
+ closeTo(height);
730
+ return true;
731
+ }
732
+ if (tag === "hr") {
733
+ close(false);
734
+ container().push({ type: "horizontalRule" });
735
+ return true;
736
+ }
355
737
  close(false);
356
738
  const heading = /^h([1-6])$/.exec(tag);
357
- open(heading ? "heading" : "paragraph", heading ? Number(heading[1]) : 1, childPre);
358
- let hasBlock = false;
359
- for (const child of element.childNodes)
360
- hasBlock = walk(child, childMarks, childPre) || hasBlock;
739
+ open(
740
+ heading ? "heading" : "paragraph",
741
+ heading ? Number(heading[1]) : 1,
742
+ child.pre,
743
+ child.align,
744
+ );
745
+ const hasBlock = children();
361
746
  // <p></p> is an empty line; a container such as <div><p>…</p></div> adds none.
362
- close(!hasBlock && tag !== "hr" && !/^(ol|ul|dl|table|tbody|thead|tfoot|tr)$/.test(tag));
747
+ close(!hasBlock && !/^(ol|ul|dl|table|tbody|thead|tfoot|tr|li)$/.test(tag));
363
748
  return true;
364
749
  };
365
750
 
366
- walk(parsed.body, new Set(), false);
751
+ walk(parsed.body, { marks: new Map(), pre: false, align: undefined });
367
752
  close(false);
368
- return blocks.length ? { content: { type: "doc", content: blocks }, open: !sawBlock } : null;
753
+ while (stack.length > 1) pop();
754
+ const content = doc.content as BlockNode[];
755
+ return content.length
756
+ ? { content: { type: "doc", content } as unknown as DocJSON, open: !sawBlock }
757
+ : null;
369
758
  }