All files / src/shared/HFInputs/HFRichInput pastedContent.ts

90.9% Statements 270/297
79.71% Branches 169/212
97.61% Functions 41/42
96.34% Lines 237/246

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706                                                        45x 45x   45x 45x 45x 45x     45x                         45x                 45x                   45x                                                                   45x                                                 45x     45x       45x       45x 45x         45x   45x 2x 2x 2x 2x                       45x   45x 100x                           45x 510x         45x       85x 85x 85x         85x 85x 3x 3x 2x 1x 1x       85x 85x   85x       85x       85x       85x 85x   85x       45x 85x 85x 10x 10x 10x 10x 10x 10x   10x                     45x   45x   85x   85x                 45x 85x 85x   77x     77x   76x 76x 75x 75x 75x   74x                 45x 63x 31x   32x 32x 32x 32x 31x 31x           45x 29x   34x         45x     8x 15x   8x 8x 15x 15x 29x 29x   29x       29x   15x   8x       15x 15x   2x       8x 8x                                                             45x 55x 55x 1x       1x       1x                         45x   3x 3x 3x 3x 3x     3x                       45x 50x   31x 31x 43x 3x     31x     1x 1x 1x 3x 2x 2x     1x   1x 3x 3x 3x 3x 3x 3x 2x 1x                 45x                 45x 37x 37x 37x   37x 168x 55x 55x 55x     37x 71x   71x 63x 55x                   63x 63x 63x 63x 12x   63x 1x           63x 12x 12x 12x               37x 8x 8x     1x 2x 2x   1x   7x 7x                   37x 167x 69x 69x   98x   98x 98x   94x 8x 8x 8x     86x 1x 1x     85x 85x             85x 2x 2x 1x                 1x       85x 4x   4x 81x 5x 5x 76x 11x 11x 65x       40x   40x 38x 38x       85x 85x 110x 85x     37x 57x             37x   37x 37x     45x       37x   36x 36x 8x                 36x 36x 36x 6x     74x                     36x                 45x       38x   37x 37x       37x   37x               45x       4x 4x         4x    
import {
  DraftBlockType,
  DraftInlineStyleType,
  EditorState,
  Modifier,
  RawDraftContentBlock,
  RawDraftContentState,
  RawDraftEntity,
  convertFromRaw,
  genKey,
} from "draft-js";
import { TableData } from "./TableBlock";
 
// Pasting an authored document (Word / Google Docs / a web page) into the
// legal-document editor must keep the formatting the editor can model: heading
// levels, bold / italic / underline / strikethrough, alignment, lists, links
// and tables. Draft's own paste path runs with `stripPastedStyles`, which
// flattens everything to unstyled text — a Merchant Agreement pasted from Word
// then renders its headings at body size and weight, which is the reported bug.
//
// This module converts clipboard HTML into a RawDraftContentState the editor
// understands; HFRichInput inserts it as a fragment. Anything the editor cannot
// model is deliberately dropped rather than smuggled in as raw CSS — colors,
// font families and absolute font sizes would render as formatting the toolbar
// cannot subsequently change. Font sizes are instead read as *evidence* of
// heading level (see inferHeadings), so the document's structure survives even
// when its author sized the headings by hand instead of using heading styles.
 
const TEXT_NODE = 3;
const ELEMENT_NODE = 1;
 
const BOLD: DraftInlineStyleType = "BOLD";
const ITALIC: DraftInlineStyleType = "ITALIC";
const UNDERLINE: DraftInlineStyleType = "UNDERLINE";
const STRIKETHROUGH: DraftInlineStyleType = "STRIKETHROUGH";
 
// The inline styles the toolbar can toggle. Nothing else is imported.
const STYLE_BY_TAG: Record<string, DraftInlineStyleType> = {
  B: BOLD,
  STRONG: BOLD,
  I: ITALIC,
  EM: ITALIC,
  CITE: ITALIC,
  U: UNDERLINE,
  INS: UNDERLINE,
  S: STRIKETHROUGH,
  STRIKE: STRIKETHROUGH,
  DEL: STRIKETHROUGH,
};
 
const HEADING_BY_TAG: Record<string, DraftBlockType> = {
  H1: "header-one",
  H2: "header-two",
  H3: "header-three",
  H4: "header-four",
  H5: "header-five",
  H6: "header-six",
};
 
const HEADING_BY_LEVEL: DraftBlockType[] = [
  "header-one",
  "header-two",
  "header-three",
  "header-four",
  "header-five",
  "header-six",
];
 
// Elements that open and close a block (one Draft block per element).
const BLOCK_TAGS = new Set([
  "ADDRESS",
  "ARTICLE",
  "ASIDE",
  "BLOCKQUOTE",
  "DD",
  "DIV",
  "DL",
  "DT",
  "FIGCAPTION",
  "FIGURE",
  "FOOTER",
  "H1",
  "H2",
  "H3",
  "H4",
  "H5",
  "H6",
  "HEADER",
  "HR",
  "LI",
  "MAIN",
  "NAV",
  "OL",
  "P",
  "PRE",
  "SECTION",
  "UL",
]);
 
// Non-content elements that turn up in clipboard HTML: Word ships a <style>
// block, VML fallbacks and <o:p> spacers inside the fragment, and embedded
// media has no place in a legal document — it would paste as an atomic block
// the document editor cannot render.
const SKIP_TAGS = new Set([
  "AUDIO",
  "BUTTON",
  "EMBED",
  "HEAD",
  "IFRAME",
  "IMG",
  "INPUT",
  "LINK",
  "META",
  "NOSCRIPT",
  "OBJECT",
  "O:P",
  "PICTURE",
  "SCRIPT",
  "SELECT",
  "STYLE",
  "SVG",
  "TEXTAREA",
  "TITLE",
  "VIDEO",
]);
 
// Word can carry absurd colspan values; padding is capped at the same column
// count the insert popover allows.
const MAX_COLSPAN = 10;
 
// Draft's list nesting cap.
const MAX_LIST_DEPTH = 4;
 
// A paragraph longer than this is prose, never a heading — the size-based
// inference below refuses to promote it however large its text is set.
const MAX_INFERRED_HEADING_LENGTH = 120;
 
// The size a relative unit (em / %) resolves against when no ancestor declared
// an absolute one. Only ever used for ratios; never emitted into the document.
const BASE_FONT_SIZE_PX = 16;
const PT_TO_PX = 96 / 72;
 
// Allow only safe schemes plus relative/anchor links — the same allowlist
// DocumentViewer applies when rendering stored content. Sanitizing here keeps
// a `javascript:` href out of the document in the first place.
const SAFE_URL_SCHEME = /^(https?:|mailto:|tel:)/i;
 
const sanitizeUrl = (url: string | null): string => {
  Iif (!url) return "";
  const trimmed = url.trim();
  Iif (trimmed.startsWith("/") || trimmed.startsWith("#")) return trimmed;
  return SAFE_URL_SCHEME.test(trimmed) ? trimmed : "";
};
 
// Word / Google Docs / PDF-derived clipboard HTML carries invisible characters
// that change where a line may break: a zero-width space or zero-width joiner
// opens a break opportunity INSIDE a word (the word then renders split across
// two lines with no hyphen), a soft hyphen breaks it with one, and a word
// joiner does the opposite — it welds a run into one unbreakable token that a
// wrapping container has to break at the margin. None of them carry meaning in
// a legal document, so they are dropped rather than pasted in. A no-break space
// becomes an ordinary one (`\s` already covers its U+2007 / U+202F / U+FEFF
// variants; U+00A0 is spelled out because it is the one Word emits everywhere).
const INVISIBLE_BREAK_CHARS = /[\u00ad\u200b\u200c\u200d\u2060]/g;
 
const collapseWhitespace = (text: string) =>
  text
    .replace(INVISIBLE_BREAK_CHARS, "")
    .replace(/ /g, " ")
    .replace(/\s+/g, " ");
 
/* ------------------------------------------------------------------ *
 * Element inspection
 * ------------------------------------------------------------------ */
 
// Read declarations off the style attribute by property name rather than
// through the camelCase accessors: jsdom's CSSStyleDeclaration only implements
// accessors for the properties it knows, but keeps every parsed declaration
// reachable by name — so `getPropertyValue` behaves the same in tests and in
// the browser.
const cssValue = (el: Element, property: string): string =>
  ((el as HTMLElement).style?.getPropertyValue?.(property) ?? "")
    .trim()
    .toLowerCase();
 
/** The inline styles active inside `el`, given those active around it. */
const stylesFor = (
  el: Element,
  inherited: DraftInlineStyleType[],
): DraftInlineStyleType[] => {
  const styles = new Set<DraftInlineStyleType>(inherited);
  const tagStyle = STYLE_BY_TAG[el.tagName];
  if (tagStyle) styles.add(tagStyle);
 
  // Word writes emphasis back out as CSS as often as it does as a tag, and
  // writes `normal` to *cancel* an inherited one (a non-bold run inside a bold
  // heading), so both directions have to be honoured.
  const weight = cssValue(el, "font-weight");
  if (weight) {
    const numeric = parseInt(weight, 10);
    if (weight === "bold" || weight === "bolder" || numeric >= 600) {
      styles.add(BOLD);
    } else Eif (weight === "normal" || weight === "lighter" || numeric) {
      styles.delete(BOLD);
    }
  }
 
  const fontStyle = cssValue(el, "font-style");
  Iif (fontStyle === "italic" || fontStyle === "oblique") {
    styles.add(ITALIC);
  } else Iif (fontStyle === "normal") {
    styles.delete(ITALIC);
  }
 
  const decoration = `${cssValue(el, "text-decoration")} ${cssValue(
    el,
    "text-decoration-line",
  )}`;
  Iif (decoration.includes("none")) {
    styles.delete(UNDERLINE);
    styles.delete(STRIKETHROUGH);
  }
  if (decoration.includes("underline")) styles.add(UNDERLINE);
  Iif (decoration.includes("line-through")) styles.add(STRIKETHROUGH);
 
  return Array.from(styles);
};
 
/** `el`'s font size in px, or the inherited one when it declares none. */
const fontSizeOf = (el: Element, inherited?: number): number | undefined => {
  const value = cssValue(el, "font-size");
  if (!value) return inherited;
  const match = /^([\d.]+)\s*(pt|px|em|rem|%)?$/.exec(value);
  Iif (!match) return inherited;
  const size = parseFloat(match[1]);
  Iif (!isFinite(size) || size <= 0) return inherited;
  const relativeTo = inherited || BASE_FONT_SIZE_PX;
  switch (match[2]) {
    case "pt":
      return size * PT_TO_PX;
    case "em":
    case "rem":
      return size * relativeTo;
    case "%":
      return (size / 100) * relativeTo;
    default:
      return size;
  }
};
 
const ALIGNMENTS = new Set(["left", "center", "right"]);
 
const alignOf = (el: Element): string | undefined => {
  const value =
    cssValue(el, "text-align") ||
    (el.getAttribute("align") ?? "").trim().toLowerCase();
  return ALIGNMENTS.has(value) ? value : undefined;
};
 
/**
 * The heading level `el` represents, if any. Real heading elements come first;
 * Word also emits its built-in heading styles as a plain paragraph carrying
 * `mso-outline-level` or an `MsoHeading*` / `MsoTitle` class, which reads as a
 * heading to everyone except the HTML parser.
 */
const headingTypeOf = (el: Element): DraftBlockType | undefined => {
  const byTag = HEADING_BY_TAG[el.tagName];
  if (byTag) return byTag;
 
  const outline = /mso-outline-level:\s*(\d)/i.exec(
    el.getAttribute("style") ?? "",
  );
  if (outline) return HEADING_BY_LEVEL[Number(outline[1]) - 1];
 
  const className = el.getAttribute("class") ?? "";
  if (/\bMsoTitle\b/i.test(className)) return "header-one";
  Iif (/\bMsoSubtitle\b/i.test(className)) return "header-two";
  const msoHeading = /\bMsoHeading(\d)\b/i.exec(className);
  if (msoHeading) return HEADING_BY_LEVEL[Number(msoHeading[1]) - 1];
 
  return undefined;
};
 
/* ------------------------------------------------------------------ *
 * Tables — same { columns, rows } entity contract as TableBlock's insert
 * ------------------------------------------------------------------ */
 
// textContent with HTML whitespace semantics: runs of whitespace collapse,
// <br> and block elements become newlines.
const textFromNode = (node: Node): string => {
  if (node.nodeType === TEXT_NODE) {
    return collapseWhitespace(node.textContent ?? "");
  }
  Iif (node.nodeType !== ELEMENT_NODE) return "";
  const el = node as Element;
  Iif (SKIP_TAGS.has(el.tagName)) return "";
  if (el.tagName === "BR") return "\n";
  const inner = Array.from(el.childNodes).map(textFromNode).join("");
  return BLOCK_TAGS.has(el.tagName) || el.tagName === "TR"
    ? `\n${inner}\n`
    : inner;
};
 
// Trim each line, collapse blank runs, drop leading/trailing empties.
const cleanMultiline = (raw: string): string =>
  raw
    .split("\n")
    .map((line) => line.trim())
    .join("\n")
    .replace(/\n{2,}/g, "\n")
    .trim();
 
const parseTable = (table: Element): TableData | null => {
  // closest() filter keeps rows of nested tables out of the outer table's
  // grid (the nested table is flattened into its host cell's text).
  const rowEls = Array.from(table.querySelectorAll("tr")).filter(
    (tr) => tr.closest("table") === table,
  );
  const grid: string[][] = [];
  for (const tr of rowEls) {
    const cells: string[] = [];
    for (const cell of Array.from(tr.children)) {
      Iif (cell.tagName !== "TD" && cell.tagName !== "TH") continue;
      cells.push(cleanMultiline(textFromNode(cell)));
      // Pad merged cells so later rows keep their column alignment.
      const colSpan = Math.min(
        parseInt(cell.getAttribute("colspan") ?? "1", 10) || 1,
        MAX_COLSPAN,
      );
      for (let i = 1; i < colSpan; i += 1) cells.push("");
    }
    Eif (cells.length) grid.push(cells);
  }
  Iif (!grid.length) return null;
 
  // Ragged rows (rowspan remainders, malformed markup) are padded to the
  // widest row so the TableData grid stays rectangular.
  const width = Math.max(...grid.map((row) => row.length));
  const padded = grid.map((row) => [
    ...row,
    ...Array.from({ length: width - row.length }, () => ""),
  ]);
  // TableData renders `columns` as the header row; the pasted table's first
  // row takes that role, matching how the table looked at its source.
  const [columns, ...rows] = padded;
  return { columns, rows };
};
 
/* ------------------------------------------------------------------ *
 * HTML → blocks
 * ------------------------------------------------------------------ */
 
type PastedRange = { offset: number; length: number };
 
type PastedBlock = {
  type: DraftBlockType;
  depth: number;
  text: string;
  align?: string;
  styleRanges: (PastedRange & { style: DraftInlineStyleType })[];
  entityRanges: (PastedRange & { key: number })[];
  /** px font size → characters set in it. Feeds heading inference only. */
  sizes: Map<number, number>;
};
 
type WalkContext = {
  styles: DraftInlineStyleType[];
  linkKey?: number;
  fontSize?: number;
  blockType: DraftBlockType;
  depth: number;
  align?: string;
  listType?: DraftBlockType;
  listDepth: number;
};
 
const trimTrailing = (block: PastedBlock): PastedBlock => {
  const text = block.text.replace(/\s+$/, "");
  if (text.length === block.text.length) return block;
  const clamp = <T extends PastedRange>(range: T): T => ({
    ...range,
    length: Math.min(range.length, text.length - range.offset),
  });
  return {
    ...block,
    text,
    styleRanges: block.styleRanges
      .filter((range) => range.offset < text.length)
      .map(clamp),
    entityRanges: block.entityRanges
      .filter((range) => range.offset < text.length)
      .map(clamp),
  };
};
 
/**
 * The most-used font size within a block, or undefined when the source
 * declared none. Ties resolve to the larger size — a heading is rarely the
 * smaller half of a tie.
 */
const dominantSize = (block: PastedBlock): number | undefined => {
  let best: number | undefined;
  let bestCount = 0;
  block.sizes.forEach((count, size) => {
    Eif (count > bestCount || (count === bestCount && size > (best ?? 0))) {
      best = size;
      bestCount = count;
    }
  });
  return best;
};
 
/**
 * Promotes short paragraphs set noticeably larger than the body to headings.
 *
 * Only runs when the source carried no heading markup at all: a document whose
 * author used Word's heading styles needs no guessing, while one whose author
 * only made the titles bigger would otherwise paste completely flat — the
 * reported bug. The ratios are deliberately conservative, and a document that
 * declares no font sizes at all (plain HTML) is left alone.
 */
const inferHeadings = (blocks: PastedBlock[]): void => {
  if (blocks.some((block) => block.type.startsWith("header-"))) return;
 
  const totals = new Map<number, number>();
  blocks.forEach((block) =>
    block.sizes.forEach((count, size) =>
      totals.set(size, (totals.get(size) ?? 0) + count),
    ),
  );
  if (!totals.size) return;
 
  // Body size = the size most of the document's characters are set in.
  let bodySize = 0;
  let bodyCount = 0;
  totals.forEach((count, size) => {
    if (count > bodyCount) {
      bodySize = size;
      bodyCount = count;
    }
  });
  Iif (!bodySize) return;
 
  blocks.forEach((block) => {
    Iif (block.type !== "unstyled") return;
    Iif (block.text.length > MAX_INFERRED_HEADING_LENGTH) return;
    const size = dominantSize(block);
    Iif (!size) return;
    const ratio = size / bodySize;
    if (ratio >= 1.5) block.type = "header-one";
    else if (ratio >= 1.25) block.type = "header-two";
    else Iif (ratio >= 1.1) block.type = "header-three";
  });
};
 
type ParseResult = {
  blocks: PastedBlock[];
  entities: RawDraftEntity[];
};
 
const emptyParagraph = (): PastedBlock => ({
  type: "unstyled",
  depth: 0,
  text: "",
  styleRanges: [],
  entityRanges: [],
  sizes: new Map(),
});
 
const parseBody = (body: HTMLElement, allowTables: boolean): ParseResult => {
  const blocks: PastedBlock[] = [];
  const entities: RawDraftEntity[] = [];
  let current: PastedBlock | null = null;
 
  const flush = () => {
    if (!current) return;
    const block = trimTrailing(current);
    current = null;
    Eif (block.text) blocks.push(block);
  };
 
  const append = (text: string, ctx: WalkContext) => {
    Iif (!text) return;
    // Whitespace between two block elements must not open a block of its own.
    if (!current && !text.trim()) return;
    if (!current) {
      current = {
        type: ctx.blockType,
        depth: ctx.depth,
        align: ctx.align,
        text: "",
        styleRanges: [],
        entityRanges: [],
        sizes: new Map(),
      };
    }
    const block = current;
    const offset = block.text.length;
    block.text += text;
    ctx.styles.forEach((style) =>
      block.styleRanges.push({ offset, length: text.length, style }),
    );
    if (ctx.linkKey !== undefined) {
      block.entityRanges.push({
        offset,
        length: text.length,
        key: ctx.linkKey,
      });
    }
    if (ctx.fontSize) {
      const weight = text.trim().length;
      Eif (weight) {
        block.sizes.set(
          ctx.fontSize,
          (block.sizes.get(ctx.fontSize) ?? 0) + weight,
        );
      }
    }
  };
 
  const appendTable = (data: TableData, ctx: WalkContext) => {
    flush();
    if (!allowTables) {
      // Editors without the table control still get the cell text, one block
      // per row — the shape the plain-text paste produced.
      [data.columns, ...data.rows].forEach((row) => {
        append(row.filter(Boolean).join(" "), ctx);
        flush();
      });
      return;
    }
    entities.push({ type: "TABLE", mutability: "IMMUTABLE", data });
    blocks.push({
      type: "atomic",
      depth: 0,
      text: " ",
      styleRanges: [],
      entityRanges: [{ offset: 0, length: 1, key: entities.length - 1 }],
      sizes: new Map(),
    });
  };
 
  const walk = (node: Node, ctx: WalkContext) => {
    if (node.nodeType === TEXT_NODE) {
      append(collapseWhitespace(node.textContent ?? ""), ctx);
      return;
    }
    Iif (node.nodeType !== ELEMENT_NODE) return;
 
    const el = node as Element;
    if (SKIP_TAGS.has(el.tagName)) return;
 
    if (el.tagName === "TABLE") {
      const data = parseTable(el);
      Eif (data) appendTable(data, ctx);
      return;
    }
    // A line break ends the block; the next text reopens one of the same type.
    if (el.tagName === "BR") {
      flush();
      return;
    }
 
    const heading = headingTypeOf(el);
    const childCtx: WalkContext = {
      ...ctx,
      styles: stylesFor(el, ctx.styles),
      fontSize: fontSizeOf(el, ctx.fontSize),
      align: alignOf(el) ?? ctx.align,
    };
 
    if (el.tagName === "A") {
      const url = sanitizeUrl(el.getAttribute("href"));
      if (url) {
        entities.push({
          type: "LINK",
          mutability: "MUTABLE",
          data: {
            url,
            targetOption:
              el.getAttribute("target") === "_blank" ? "_blank" : "_self",
          },
        });
        childCtx.linkKey = entities.length - 1;
      }
    }
 
    if (el.tagName === "UL" || el.tagName === "OL") {
      childCtx.listType =
        el.tagName === "OL" ? "ordered-list-item" : "unordered-list-item";
      childCtx.listDepth = ctx.listDepth + 1;
    } else if (el.tagName === "LI") {
      childCtx.blockType = ctx.listType ?? "unordered-list-item";
      childCtx.depth = Math.min(Math.max(ctx.listDepth - 1, 0), MAX_LIST_DEPTH);
    } else if (heading) {
      childCtx.blockType = heading;
      childCtx.depth = 0;
    } else if (BLOCK_TAGS.has(el.tagName)) {
      // Google Docs wraps each list item's text in its own <p>. That opens a
      // block, but it must stay the list item it sits in or the bullet is lost.
      const inListItem =
        ctx.blockType === "ordered-list-item" ||
        ctx.blockType === "unordered-list-item";
      if (!inListItem) {
        childCtx.blockType = "unstyled";
        childCtx.depth = 0;
      }
    }
 
    const isBlock = BLOCK_TAGS.has(el.tagName) || heading !== undefined;
    if (isBlock) flush();
    Array.from(el.childNodes).forEach((child) => walk(child, childCtx));
    if (isBlock) flush();
  };
 
  Array.from(body.childNodes).forEach((child) =>
    walk(child, {
      styles: [],
      blockType: "unstyled",
      depth: 0,
      listDepth: 0,
    }),
  );
  flush();
 
  inferHeadings(blocks);
  return { blocks, entities };
};
 
const toRawContent = ({
  blocks,
  entities,
}: ParseResult): RawDraftContentState | null => {
  if (!blocks.length) return null;
 
  const entityMap: Record<string, RawDraftEntity> = {};
  entities.forEach((entity, index) => {
    entityMap[String(index)] = entity;
  });
 
  // Draft merges a fragment's first and last blocks into the blocks either
  // side of the caret, which an atomic block cannot survive: it would be
  // folded into a text block as a lone space carrying the TABLE entity. Pad
  // the fragment with an empty paragraph on any edge that holds one, so the
  // table always lands as a block of its own (the same padding
  // AtomicBlockUtils.insertAtomicBlock applies).
  const padded = [...blocks];
  if (padded[0].type === "atomic") padded.unshift(emptyParagraph());
  if (padded[padded.length - 1].type === "atomic") {
    padded.push(emptyParagraph());
  }
 
  const rawBlocks: RawDraftContentBlock[] = padded.map((block) => ({
    key: genKey(),
    type: block.type,
    text: block.text,
    depth: block.depth,
    inlineStyleRanges: block.styleRanges,
    entityRanges: block.entityRanges,
    // The block-data key the Alignment control writes (blockStyle.ts).
    data: block.align ? { "text-align": block.align } : {},
  }));
 
  return { blocks: rawBlocks, entityMap };
};
 
/**
 * Converts clipboard HTML into content the editor can hold, keeping heading
 * levels, bold / italic / underline / strikethrough, alignment, lists, links
 * and — when `tables` is enabled — tables. Returns null when the HTML carries
 * nothing to insert, so the caller can fall through to the default paste.
 */
export const parsePastedHtml = (
  html: string,
  { tables = true }: { tables?: boolean } = {},
): RawDraftContentState | null => {
  if (!html || typeof DOMParser === "undefined") return null;
  let body: HTMLElement;
  try {
    body = new DOMParser().parseFromString(html, "text/html").body;
  } catch {
    return null;
  }
  Iif (!body) return null;
 
  return toRawContent(parseBody(body, tables));
};
 
/**
 * Inserts parsed content at the current selection as a Draft fragment, so the
 * pasted blocks keep their own types, styles and entities instead of being
 * folded into the block the caret sits in.
 */
export const insertPastedContent = (
  editorState: EditorState,
  raw: RawDraftContentState,
): EditorState => {
  const fragment = convertFromRaw(raw).getBlockMap();
  const content = Modifier.replaceWithFragment(
    editorState.getCurrentContent(),
    editorState.getSelection(),
    fragment,
  );
  return EditorState.push(editorState, content, "insert-fragment");
};