@folijs/view 0.1.0 → 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/src/clipboard.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  import {
2
- type BlockJSON,
2
+ type Alignment,
3
3
  type DocJSON,
4
4
  Fragment,
5
5
  type InlineJSON,
6
+ isSafeHref,
6
7
  type MarkJSON,
7
- type MarkName,
8
8
  type Node as ModelNode,
9
+ type ParagraphJSON,
9
10
  parseContent,
11
+ type SimpleMarkName,
10
12
  } from "@folijs/core";
11
- import { PAGE_BREAK_ATTR, renderBlock } from "./render.js";
13
+ import { PAGE_BREAK_ATTR, renderTree } from "./render.js";
12
14
 
13
15
  /**
14
16
  * Clipboard type for Foli content, read back first on paste: `{ open, content }`, the copied
@@ -45,17 +47,25 @@ export function serializeRange(
45
47
  let content = doc.slice(from, to).content;
46
48
  for (let depth = $from.sharedDepth(to); depth > 0; depth--)
47
49
  content = Fragment.from($from.node(depth).copy(content));
48
- const blocks = doc.type.create(null, content);
50
+ // Not validated: a cut-open list item may lack its first paragraph. The JSON is validated
51
+ // when pasted; the HTML is only markup.
52
+ const blocks = doc.type.createOpen(null, content);
49
53
  const container = ownerDocument.createElement("div");
50
54
  // 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
- });
55
+ // A range inside one textblock is that block's text: its lists around it stay out of the HTML
56
+ // (a word copied from a list item must not paste as a one-item list); the JSON keeps them.
57
+ const $to = doc.resolve(to);
58
+ const inline = $from.parent.isTextblock && $from.sameParent($to);
59
+ const htmlBlocks = inline
60
+ ? [$from.parent.copy(doc.slice(from, to).content)]
61
+ : blocks.content.content;
62
+ renderTree(htmlBlocks, container, ownerDocument);
63
+ // Keep repeated and leading spaces in other apps.
64
+ for (const block of container.querySelectorAll("p, h1, h2, h3, h4, h5, h6"))
65
+ (block as HTMLElement).style.whiteSpace = "pre-wrap";
66
+ // How other apps (and print) recognize a page break; the editor itself does not need it.
67
+ for (const br of container.querySelectorAll(`br[${PAGE_BREAK_ATTR}]`))
68
+ (br as HTMLElement).style.cssText = "page-break-before: always; break-before: page";
59
69
  return {
60
70
  text: doc.textBetween(from, to, "\n", "\n"),
61
71
  html: container.innerHTML,
@@ -111,7 +121,7 @@ export function textToDoc(text: string, marks: readonly MarkJSON[] = []): DocJSO
111
121
  content: [{ type: "text", text: line, ...(marks.length ? { marks: [...marks] } : {}) }],
112
122
  }
113
123
  : {}),
114
- })) as BlockJSON[],
124
+ })) as ParagraphJSON[],
115
125
  };
116
126
  }
117
127
 
@@ -176,7 +186,7 @@ const SKIPPED_TAGS = new Set([
176
186
  "video",
177
187
  ]);
178
188
 
179
- const TAG_MARKS: ReadonlyMap<string, MarkName> = new Map([
189
+ const TAG_MARKS: ReadonlyMap<string, SimpleMarkName> = new Map([
180
190
  ["b", "bold"],
181
191
  ["strong", "bold"],
182
192
  ["i", "italic"],
@@ -188,26 +198,120 @@ const TAG_MARKS: ReadonlyMap<string, MarkName> = new Map([
188
198
  ["del", "strike"],
189
199
  ]);
190
200
 
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);
201
+ /** Marks by type: one of each (a link, a text color and a highlight carry attributes). */
202
+ type Marks = ReadonlyMap<string, MarkJSON>;
203
+
204
+ const NAMED_COLORS: Readonly<Record<string, string>> = {
205
+ black: "#000000",
206
+ white: "#ffffff",
207
+ red: "#ff0000",
208
+ green: "#008000",
209
+ blue: "#0000ff",
210
+ yellow: "#ffff00",
211
+ gray: "#808080",
212
+ grey: "#808080",
213
+ silver: "#c0c0c0",
214
+ maroon: "#800000",
215
+ navy: "#000080",
216
+ purple: "#800080",
217
+ teal: "#008080",
218
+ olive: "#808000",
219
+ orange: "#ffa500",
220
+ lime: "#00ff00",
221
+ aqua: "#00ffff",
222
+ cyan: "#00ffff",
223
+ fuchsia: "#ff00ff",
224
+ magenta: "#ff00ff",
225
+ };
226
+
227
+ const hex2 = (n: number) =>
228
+ Math.max(0, Math.min(255, Math.round(n)))
229
+ .toString(16)
230
+ .padStart(2, "0");
231
+
232
+ /**
233
+ * A CSS color as the schema stores it (lowercase `#rrggbb`), or null: transparent, unknown
234
+ * (system colors such as Word's `windowtext`) or empty. Hex (3 or 6 digits), `rgb()`/`rgba()`
235
+ * and the basic named colors.
236
+ */
237
+ export function parseColor(value: string): string | null {
238
+ const color = value.trim().toLowerCase();
239
+ const named = NAMED_COLORS[color];
240
+ if (named) return named;
241
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color);
242
+ if (short) return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`;
243
+ if (/^#[0-9a-f]{6}$/.test(color)) return color;
244
+ // rgb(r, g, b), rgb(r g b), rgba(r, g, b, a), rgb(r g b / a): split, no backtracking regex.
245
+ const body = /^rgba?\(([^()]*)\)$/.exec(color)?.[1];
246
+ if (body === undefined) return null;
247
+ const parts = body.trim().split(/\s*[,/]\s*|\s+/);
248
+ if (parts.length < 3 || parts.length > 4) return null;
249
+ if (!parts.every((part) => /^\d+(?:\.\d+)?%?$/.test(part))) return null;
250
+ const numbers = parts.map((part) => Number.parseFloat(part));
251
+ if (numbers[3] === 0) return null; // fully transparent
252
+ const hex = `#${hex2(numbers[0] as number)}${hex2(numbers[1] as number)}${hex2(numbers[2] as number)}`;
253
+ return hex;
254
+ }
255
+
256
+ /**
257
+ * Marks of an element on top of the inherited ones: tags first, then inline styles; a link
258
+ * from `a[href]` when the href is safe (`isSafeHref`; links inside the source page, `#…`, are
259
+ * dropped); text color and highlight from inline elements only (a page's colored containers
260
+ * are layout, not formatting), black text and white highlight being the defaults.
261
+ */
262
+ function marksOf(element: Element, inherited: Marks): Map<string, MarkJSON> {
263
+ const marks = new Map(inherited);
264
+ const tag = element.localName;
265
+ const tagMark = TAG_MARKS.get(tag);
266
+ if (tagMark) marks.set(tagMark, { type: tagMark });
267
+ if (tag === "a") {
268
+ const href = element.getAttribute("href")?.trim().replace(/ /g, "%20");
269
+ if (href && !href.startsWith("#") && isSafeHref(href)) {
270
+ marks.set("link", { type: "link", attrs: { href } } as MarkJSON);
271
+ }
272
+ }
196
273
  const style = (element as HTMLElement).style;
197
274
  if (!style) return marks;
198
275
  const weight = style.fontWeight;
199
276
  // Google Docs wraps everything in <b style="font-weight:normal">.
200
- if (/^(bold|bolder|[6-9]00)$/.test(weight)) marks.add("bold");
277
+ if (/^(bold|bolder|[6-9]00)$/.test(weight)) marks.set("bold", { type: "bold" });
201
278
  else if (/^(normal|lighter|[1-5]00)$/.test(weight)) marks.delete("bold");
202
- if (/^(italic|oblique)/.test(style.fontStyle)) marks.add("italic");
279
+ if (/^(italic|oblique)/.test(style.fontStyle)) marks.set("italic", { type: "italic" });
203
280
  else if (style.fontStyle === "normal") marks.delete("italic");
204
281
  const decoration = `${style.textDecorationLine} ${style.textDecoration}`;
205
- if (decoration.includes("underline")) marks.add("underline");
206
- if (decoration.includes("line-through")) marks.add("strike");
282
+ if (decoration.includes("underline")) marks.set("underline", { type: "underline" });
283
+ if (decoration.includes("line-through")) marks.set("strike", { type: "strike" });
207
284
  // `text-decoration: none` on a child does not remove a parent's line in CSS: keep it.
285
+ if (!BLOCK_TAGS.has(tag)) {
286
+ const color = parseColor(
287
+ style.color || (tag === "font" ? (element.getAttribute("color") ?? "") : ""),
288
+ );
289
+ // Black is the default; white text comes from dark pages and would be invisible.
290
+ if (color === "#000000" || color === "#ffffff") marks.delete("textColor");
291
+ else if (color) marks.set("textColor", { type: "textColor", attrs: { color } } as MarkJSON);
292
+ const background = parseColor(style.backgroundColor);
293
+ if (background === "#ffffff") marks.delete("highlight");
294
+ else if (background) {
295
+ marks.set("highlight", { type: "highlight", attrs: { color: background } } as MarkJSON);
296
+ }
297
+ }
208
298
  return marks;
209
299
  }
210
300
 
301
+ /** A block's own alignment (`text-align`, or the old `align` attribute), or undefined. */
302
+ function alignOf(element: Element): Alignment | undefined {
303
+ const value = (
304
+ (element as HTMLElement).style?.textAlign ||
305
+ element.getAttribute("align") ||
306
+ ""
307
+ ).toLowerCase();
308
+ if (value === "left" || value === "start") return "start";
309
+ if (value === "center" || value === "-webkit-center") return "center";
310
+ if (value === "right" || value === "end") return "end";
311
+ if (value === "justify") return "justify";
312
+ return undefined;
313
+ }
314
+
211
315
  /**
212
316
  * A page break in pasted HTML: Foli's own `<br data-page-break>`, or a `<br>` or `<hr>` styled
213
317
  * to break the page (Word writes `<br clear=all style='page-break-before:always'>`, Google Docs
@@ -230,12 +334,75 @@ function isNoise(element: Element): boolean {
230
334
  if ((element as HTMLElement).style?.display === "none" || element.hasAttribute("hidden")) {
231
335
  return true;
232
336
  }
233
- return element.localName === "o:p" && !element.textContent?.replace(/[\s ]/g, "");
337
+ return element.localName === "o:p" && !element.textContent?.replace(/[\s ]/g, "");
234
338
  }
235
339
 
236
340
  /**
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.
341
+ * A Word list paragraph (`style="mso-list:l0 level2 lfo1"`): its list and level, and from its
342
+ * marker (the `mso-list:Ignore` span Word adds for other apps) whether it is numbered and
343
+ * where the numbering starts. Best effort: a marker ending in "." or ")" is a number or
344
+ * letter (numbered); anything else ("·", "o", "§") a bullet.
345
+ */
346
+ function wordListItem(
347
+ element: Element,
348
+ ): { list: string; level: number; ordered: boolean; start: number } | null {
349
+ const match = /mso-list:\s*(l\d+)\s+level(\d+)/i.exec(element.getAttribute("style") ?? "");
350
+ if (!match) return null;
351
+ let marker = "";
352
+ for (const child of element.querySelectorAll("[style]")) {
353
+ if (/mso-list:\s*ignore/i.test(child.getAttribute("style") ?? "")) {
354
+ marker = (child.textContent ?? "").replace(/[\s ]+/g, "");
355
+ break;
356
+ }
357
+ }
358
+ // "1.", "a)", "(iv)", and multi-level "1.2." or "1.2": numbered; its last part is its number.
359
+ const ordered = /^\(?[0-9a-zA-Z]{1,6}(?:\.[0-9]{1,6})*[.)]$|^\d{1,6}(?:\.\d{1,6})+$/.test(marker);
360
+ const number = /(\d+)[.)]?$/.exec(marker);
361
+ return {
362
+ list: match[1] as string,
363
+ level: Number(match[2]),
364
+ ordered,
365
+ start: ordered && number ? Number(number[1]) : 1,
366
+ };
367
+ }
368
+
369
+ /** Loose block JSON while reading (validated by the schema afterwards). */
370
+ interface BlockNode {
371
+ type: string;
372
+ attrs?: Record<string, unknown>;
373
+ content?: (BlockNode | InlineJSON)[];
374
+ }
375
+
376
+ interface Container {
377
+ node: BlockNode;
378
+ kind: "doc" | "list" | "item";
379
+ /** An item the reader opened itself (text directly in a list, a list nested in a list). */
380
+ implicit?: boolean;
381
+ /** Where a list goes when it closes (lists with no items are dropped). */
382
+ parent?: BlockNode[];
383
+ /** A Word list paragraph's list and level (Word lists are flat paragraphs). */
384
+ word?: { list: string; level: number; ordered: boolean };
385
+ }
386
+
387
+ /** A list item must start with a paragraph: a heading becomes one, else one is added. */
388
+ function finishItem(item: BlockNode): void {
389
+ if (!item.content) item.content = [];
390
+ const content = item.content as BlockNode[];
391
+ const first = content[0];
392
+ if (first?.type === "heading") {
393
+ first.type = "paragraph";
394
+ const align = first.attrs?.align;
395
+ if (align) first.attrs = { align };
396
+ else delete first.attrs;
397
+ } else if (first?.type !== "paragraph") {
398
+ content.unshift({ type: "paragraph" });
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Own HTML reader: maps known tags and inline styles to the schema (paragraphs, headings,
404
+ * lists, rules; bold, italic, underline, strike, links, colors; alignment), drops everything
405
+ * else. The HTML is parsed into an inert document and never inserted.
239
406
  */
240
407
  export function htmlToDoc(html: string): DocJSON | null {
241
408
  return readHTML(html)?.content ?? null;
@@ -244,18 +411,41 @@ export function htmlToDoc(html: string): DocJSON | null {
244
411
  /** `htmlToDoc`, plus whether the HTML had no block elements (`Pasted.open`). */
245
412
  function readHTML(html: string): { content: DocJSON; open: boolean } | null {
246
413
  const parsed = new DOMParser().parseFromString(html, "text/html");
247
- const blocks: BlockJSON[] = [];
414
+ const doc: BlockNode = { type: "doc", content: [] };
415
+ const stack: Container[] = [{ node: doc, kind: "doc" }];
248
416
  let inline: InlineJSON[] | null = null;
249
- let blockType: BlockJSON["type"] = "paragraph";
417
+ let blockType: "paragraph" | "heading" = "paragraph";
250
418
  let level = 1;
419
+ let blockAlign: Alignment | undefined;
251
420
  let blockPre = false;
252
421
  let sawBlock = false;
253
422
  let afterSpace = true; // collapse leading and repeated whitespace like HTML layout does
254
423
 
255
- const open = (type: BlockJSON["type"], headingLevel = 1, pre = false) => {
424
+ const top = () => stack[stack.length - 1] as Container;
425
+ /** Where blocks go now: the open item or the document (text directly in a list gets an item). */
426
+ const container = (): BlockNode[] => {
427
+ if (top().kind === "list") {
428
+ const item: BlockNode = { type: "listItem", content: [] };
429
+ (top().node.content as BlockNode[]).push(item);
430
+ stack.push({ node: item, kind: "item", implicit: true });
431
+ }
432
+ return top().node.content as BlockNode[];
433
+ };
434
+ const lastBlock = (): BlockNode | undefined => {
435
+ const blocks = top().node.content as BlockNode[];
436
+ return blocks[blocks.length - 1];
437
+ };
438
+
439
+ const open = (
440
+ type: "paragraph" | "heading",
441
+ headingLevel = 1,
442
+ pre = false,
443
+ align: Alignment | undefined = undefined,
444
+ ) => {
256
445
  inline = [];
257
446
  blockType = type;
258
447
  level = headingLevel;
448
+ blockAlign = align;
259
449
  blockPre = pre;
260
450
  afterSpace = true;
261
451
  };
@@ -267,22 +457,28 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
267
457
  if (tail?.type === "text" && !blockPre) tail.text = tail.text.replace(/ +$/, "");
268
458
  // Non-breaking spaces survive the trimming above, then become ordinary spaces.
269
459
  for (const node of inline) {
270
- if (node.type === "text") node.text = node.text.replace(/\u00a0/g, " ");
460
+ if (node.type === "text") node.text = node.text.replace(/ /g, " ");
271
461
  }
272
462
  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
463
  inline = null;
464
+ if (!content.length && !keepEmpty) return;
465
+ const attrs: Record<string, unknown> = {};
466
+ if (blockType === "heading") attrs.level = level;
467
+ if (blockAlign && blockAlign !== "start") attrs.align = blockAlign;
468
+ container().push({
469
+ type: blockType,
470
+ ...(Object.keys(attrs).length ? { attrs } : {}),
471
+ ...(content.length ? { content } : {}),
472
+ });
281
473
  };
282
- const addText = (raw: string, marks: ReadonlySet<MarkName>, pre: boolean) => {
474
+ const addText = (raw: string, marks: Marks, pre: boolean) => {
283
475
  // Source formatting between blocks ("</p>\n<br>\n<p>") is not content.
284
476
  if (!inline && !pre && !/[^ \t\n\r\f]/.test(raw)) return;
285
- if (!inline) open("paragraph", 1, pre);
477
+ if (!inline) {
478
+ // Text of its own after Word list paragraphs ends them (it is not part of an item).
479
+ if (stack.some((entry) => entry.word)) closeWordLists();
480
+ open("paragraph", 1, pre);
481
+ }
286
482
  const lines = pre ? raw.replace(/\r\n?/g, "\n").split("\n") : [raw];
287
483
  lines.forEach((line, i) => {
288
484
  if (i > 0) addBreak();
@@ -290,7 +486,10 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
290
486
  if (!pre && afterSpace) text = text.replace(/^ /, "");
291
487
  if (!text) return;
292
488
  afterSpace = !pre && text.endsWith(" ");
293
- const markJSON = [...marks].map((type) => ({ type }));
489
+ // A link's own look (Google Docs' blue underline) is the link's, not formatting.
490
+ const markJSON = [...marks.values()].filter(
491
+ (mark) => !marks.has("link") || (mark.type !== "underline" && mark.type !== "textColor"),
492
+ );
294
493
  (inline as InlineJSON[]).push({
295
494
  type: "text",
296
495
  text,
@@ -298,12 +497,13 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
298
497
  } as InlineJSON);
299
498
  });
300
499
  };
301
- /** An explicit page break: in the open block, else at the end of the previous one. */
500
+ /** An explicit page break: in the open block, else at the end of the previous textblock. */
302
501
  const addPageBreak = () => {
303
- const previous = blocks[blocks.length - 1];
502
+ const previous = lastBlock();
304
503
  if (inline) inline.push({ type: "pageBreak" });
305
- else if (previous) previous.content = [...(previous.content ?? []), { type: "pageBreak" }];
306
- else {
504
+ else if (previous && (previous.type === "paragraph" || previous.type === "heading")) {
505
+ previous.content = [...(previous.content ?? []), { type: "pageBreak" }];
506
+ } else {
307
507
  open("paragraph");
308
508
  (inline as InlineJSON[] | null)?.push({ type: "pageBreak" });
309
509
  }
@@ -312,7 +512,7 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
312
512
  const addBreak = () => {
313
513
  // A <br> between blocks is an empty line (Google Docs writes empty paragraphs this way).
314
514
  if (!inline) {
315
- blocks.push({ type: "paragraph" } as BlockJSON);
515
+ container().push({ type: "paragraph" });
316
516
  return;
317
517
  }
318
518
  const list = inline as InlineJSON[];
@@ -322,10 +522,97 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
322
522
  afterSpace = true;
323
523
  };
324
524
 
525
+ /** Closes the top container: an item gets its first paragraph, a list goes to its parent. */
526
+ const pop = () => {
527
+ const container = stack.pop() as Container;
528
+ if (container.kind === "item" && container.implicit && !container.node.content?.length) {
529
+ // An item opened for content that never came (`<ul><ul></ul></ul>`): not an empty bullet.
530
+ const items = top().node.content as BlockNode[];
531
+ items.splice(items.indexOf(container.node), 1);
532
+ return;
533
+ }
534
+ if (container.kind === "item") finishItem(container.node);
535
+ if (container.kind === "list" && container.node.content?.length) {
536
+ container.parent?.push(container.node);
537
+ }
538
+ };
539
+ /** Opens a list; one directly inside a list (sloppy HTML, Google Docs) nests in its last item. */
540
+ const openList = (ordered: boolean, start: number, word?: Container["word"]) => {
541
+ close(false);
542
+ if (top().kind === "list") {
543
+ const items = top().node.content as BlockNode[];
544
+ let item = items[items.length - 1];
545
+ if (!item) {
546
+ item = { type: "listItem", content: [] };
547
+ items.push(item);
548
+ }
549
+ stack.push({ node: item, kind: "item", implicit: true });
550
+ }
551
+ const node: BlockNode = {
552
+ type: ordered ? "orderedList" : "bulletList",
553
+ ...(ordered && start !== 1 && Number.isInteger(start) && start >= 0 && start <= 99_999
554
+ ? { attrs: { start } }
555
+ : {}),
556
+ content: [],
557
+ };
558
+ stack.push({
559
+ node,
560
+ kind: "list",
561
+ parent: top().node.content as BlockNode[],
562
+ ...(word && { word }),
563
+ });
564
+ };
565
+ const openItem = (word?: Container["word"]) => {
566
+ close(false);
567
+ while (top().kind === "item" && (top().implicit || word)) pop();
568
+ const item: BlockNode = { type: "listItem", content: [] };
569
+ (top().node.content as BlockNode[]).push(item);
570
+ stack.push({ node: item, kind: "item", ...(word && { word }) });
571
+ };
572
+
573
+ /** Word lists are flat paragraphs with levels: open and close lists to nest them. */
574
+ const wordItem = (item: NonNullable<ReturnType<typeof wordListItem>>) => {
575
+ close(false);
576
+ const wordList = () => {
577
+ for (let i = stack.length - 1; i > 0; i--) {
578
+ const entry = stack[i] as Container;
579
+ if (entry.kind === "list" && entry.word) return { entry, index: i };
580
+ }
581
+ return null;
582
+ };
583
+ for (let found = wordList(); found; found = wordList()) {
584
+ const { word } = found.entry;
585
+ if (!word) break;
586
+ const same =
587
+ word.level === item.level && word.list === item.list && word.ordered === item.ordered;
588
+ if (word.level < item.level || (same && word.level === item.level)) break;
589
+ while (stack.length > found.index) pop();
590
+ }
591
+ const current = wordList();
592
+ const word = { list: item.list, level: item.level, ordered: item.ordered };
593
+ if (!current || current.entry.word?.level !== item.level) {
594
+ openList(item.ordered, item.start, word);
595
+ } else {
596
+ // A sibling item: close the previous one (and anything nested in it).
597
+ while (stack.length > current.index + 1) pop();
598
+ }
599
+ openItem(word);
600
+ };
601
+ const closeWordLists = () => {
602
+ close(false);
603
+ while (stack.some((entry) => entry.word)) pop();
604
+ };
605
+
606
+ interface Context {
607
+ marks: Marks;
608
+ pre: boolean;
609
+ align: Alignment | undefined;
610
+ }
611
+
325
612
  /** Walks `node`; returns whether it contained a block element. */
326
- const walk = (node: Node, marks: ReadonlySet<MarkName>, pre: boolean): boolean => {
613
+ const walk = (node: Node, context: Context): boolean => {
327
614
  if (node.nodeType === 3) {
328
- addText((node as Text).data, marks, pre);
615
+ addText((node as Text).data, context.marks, context.pre);
329
616
  return false;
330
617
  }
331
618
  if (node.nodeType !== 1) return false; // comments (Word's conditional comments), etc.
@@ -342,28 +629,80 @@ function readHTML(html: string): { content: DocJSON; open: boolean } | null {
342
629
  if (!element.classList.contains("Apple-interchange-newline")) addBreak();
343
630
  return false;
344
631
  }
345
- const childMarks = marksOf(element, marks);
346
632
  const whiteSpace = (element as HTMLElement).style?.whiteSpace ?? "";
347
- const childPre = pre || tag === "pre" || whiteSpace.startsWith("pre");
348
- if (!BLOCK_TAGS.has(tag)) {
633
+ const child: Context = {
634
+ marks: marksOf(element, context.marks),
635
+ pre: context.pre || tag === "pre" || whiteSpace.startsWith("pre"),
636
+ align: BLOCK_TAGS.has(tag) ? (alignOf(element) ?? context.align) : context.align,
637
+ };
638
+ const children = () => {
349
639
  let hasBlock = false;
350
- for (const child of element.childNodes)
351
- hasBlock = walk(child, childMarks, childPre) || hasBlock;
640
+ for (const node of element.childNodes) hasBlock = walk(node, child) || hasBlock;
352
641
  return hasBlock;
353
- }
642
+ };
643
+ if (!BLOCK_TAGS.has(tag)) return children();
354
644
  sawBlock = true;
645
+ // Word list paragraphs: <p> only (a numbered Word heading stays a heading), and not inside an
646
+ // HTML list (Outlook writes `<li style="mso-list:…">` in real lists).
647
+ const word =
648
+ tag === "p" && !stack.some((entry) => entry.kind === "list" && !entry.word)
649
+ ? wordListItem(element)
650
+ : null;
651
+ if (word) {
652
+ wordItem(word);
653
+ open("paragraph", 1, child.pre, child.align);
654
+ children();
655
+ close(true);
656
+ return true;
657
+ }
658
+ // Word wraps its content in a <div>: only a block of its own content ends Word lists.
659
+ if (!/^(div|body|section|article|main)$/.test(tag)) closeWordLists();
660
+ // A list or item closes everything opened inside it, so unbalanced input cannot leak.
661
+ const base = stack.length;
662
+ const closeTo = (height: number) => {
663
+ close(false);
664
+ while (stack.length > height) pop();
665
+ };
666
+ if (tag === "ul" || tag === "ol") {
667
+ const start = Number.parseInt(element.getAttribute("start") ?? "", 10);
668
+ openList(tag === "ol", Number.isNaN(start) ? 1 : start);
669
+ children();
670
+ closeTo(base);
671
+ return true;
672
+ }
673
+ if (tag === "li" && stack.some((entry) => entry.kind === "list")) {
674
+ // Inside a list item that is itself still open, an <li> is a sibling: close down to a list.
675
+ while (top().kind === "item") closeTo(stack.length - 1);
676
+ const height = stack.length;
677
+ openItem();
678
+ children();
679
+ closeTo(height);
680
+ return true;
681
+ }
682
+ if (tag === "hr") {
683
+ close(false);
684
+ container().push({ type: "horizontalRule" });
685
+ return true;
686
+ }
355
687
  close(false);
356
688
  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;
689
+ open(
690
+ heading ? "heading" : "paragraph",
691
+ heading ? Number(heading[1]) : 1,
692
+ child.pre,
693
+ child.align,
694
+ );
695
+ const hasBlock = children();
361
696
  // <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));
697
+ close(!hasBlock && !/^(ol|ul|dl|table|tbody|thead|tfoot|tr|li)$/.test(tag));
363
698
  return true;
364
699
  };
365
700
 
366
- walk(parsed.body, new Set(), false);
701
+ walk(parsed.body, { marks: new Map(), pre: false, align: undefined });
367
702
  close(false);
368
- return blocks.length ? { content: { type: "doc", content: blocks }, open: !sawBlock } : null;
703
+ while (stack.length > 1) pop();
704
+ const content = doc.content as BlockNode[];
705
+ return content.length
706
+ ? { content: { type: "doc", content } as unknown as DocJSON, open: !sawBlock }
707
+ : null;
369
708
  }