@sofereditor/export-pdf 0.2.0 → 0.3.1

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/dist/index.cjs CHANGED
@@ -406,6 +406,7 @@ function serializePaginatedHtml(root, options = {}) {
406
406
  el.removeAttribute("contenteditable");
407
407
  });
408
408
  clone.querySelectorAll(".ed-image-overlay").forEach((el) => el.remove());
409
+ clone.querySelectorAll(".ed-remote-cursors").forEach((el) => el.remove());
409
410
  const cs = root.ownerDocument?.defaultView?.getComputedStyle(root);
410
411
  const pageSize = options.pageSize ?? cssPageSizeFromRoot(cs);
411
412
  const styles = collectStyles();
@@ -413,7 +414,7 @@ function serializePaginatedHtml(root, options = {}) {
413
414
  const extra = options.extraCss ?? "";
414
415
  return [
415
416
  "<!doctype html>",
416
- `<html><head><meta charset="utf-8"><title>${title}</title>`,
417
+ `<html><head><meta charset="utf-8"><meta name="ed-print-snapshot" content="1"><title>${title}</title>`,
417
418
  styles,
418
419
  `<style>
419
420
  html, body { margin: 0; padding: 0; background: white; }
@@ -453,6 +454,7 @@ async function printHtmlInIframe(html, _filename) {
453
454
  else iframe.addEventListener("load", () => resolve(), { once: true });
454
455
  });
455
456
  await waitForImages(docu);
457
+ await waitForFonts(docu);
456
458
  await new Promise((resolve) => {
457
459
  const cleanup = () => {
458
460
  win.removeEventListener("afterprint", cleanup);
@@ -494,6 +496,16 @@ async function waitForImages(docu) {
494
496
  )
495
497
  );
496
498
  }
499
+ async function waitForFonts(docu) {
500
+ const fonts = docu.fonts;
501
+ if (!fonts?.ready) return;
502
+ await Promise.race([
503
+ fonts.ready.then(() => void 0),
504
+ new Promise((resolve) => {
505
+ setTimeout(resolve, 3e3);
506
+ })
507
+ ]);
508
+ }
497
509
  var HTML_ESCAPES2 = {
498
510
  "&": "&amp;",
499
511
  "<": "&lt;",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/html.ts","../src/pdf.ts","../src/download.ts"],"sourcesContent":["export {\n documentToHtml,\n documentToHtmlFragment,\n documentToJson,\n} from \"./html\";\nexport type { DocumentToHtmlOptions } from \"./html\";\nexport {\n exportPdfFromDocument,\n exportPdfFromElement,\n serializePaginatedHtml,\n} from \"./pdf\";\nexport type {\n ExportPdfFromDocumentOptions,\n ExportPdfFromElementOptions,\n SerializePaginatedHtmlOptions,\n} from \"./pdf\";\nexport { downloadBlob, downloadString } from \"./download\";\n","import type {\n AlignValue,\n BlockAttrs,\n DeltaOp,\n DirValue,\n ImageEmbed,\n LegacySerializedDocument,\n ListKind,\n MarkAttrs,\n PageSettings,\n SerializedBlock,\n SerializedCell,\n SerializedDocument,\n} from \"@sofereditor/core\";\nimport { isImageEmbed, isLegacySerializedDocument, pxToMm } from \"@sofereditor/core\";\n\nfunction normalize(doc: SerializedDocument | LegacySerializedDocument): SerializedDocument {\n return isLegacySerializedDocument(doc) ? { blocks: doc } : doc;\n}\n\nexport interface DocumentToHtmlOptions {\n /** Document title (set on `<title>` and used as the file name hint). Default \"Documento\". */\n title?: string;\n /** When true (default) emits a full `<html>` document. When false emits only the body fragment. */\n standalone?: boolean;\n /** Extra CSS appended after the default print stylesheet. Only honored when `standalone`. */\n extraCss?: string;\n /** Page geometry hints injected into `@page`. Defaults to A4. */\n page?: {\n width: string;\n height: string;\n marginTop: string;\n marginBottom: string;\n marginLeft: string;\n marginRight: string;\n };\n}\n\nconst DEFAULT_PAGE = {\n width: \"210mm\",\n height: \"297mm\",\n marginTop: \"25mm\",\n marginBottom: \"25mm\",\n marginLeft: \"25mm\",\n marginRight: \"25mm\",\n};\n\n/**\n * Serialize a `SerializedDocument` to standalone HTML.\n *\n * Output structure mirrors what `@sofereditor/react` paints at runtime: each\n * top-level block becomes one element (`<p>`, `<h1..6>`, `<blockquote>`, `<pre>`,\n * `<table>`), consecutive `listItem` blocks are reconstructed into nested\n * `<ul>`/`<ol>` trees, and image embeds are emitted as `<img>` tags carrying the\n * embed's data URL (so the export is self-contained).\n *\n * NOT a fragment of the live editor DOM — this walks the model so the output is\n * editor-state agnostic (no caret artifacts, no zero-width phantom anchors).\n */\nexport function documentToHtml(\n doc: SerializedDocument | LegacySerializedDocument,\n options: DocumentToHtmlOptions = {},\n): string {\n const normalized = normalize(doc);\n const body = documentToHtmlFragment(normalized);\n if (options.standalone === false) return body;\n const page = options.page ?? pageFromSettings(normalized.pageSettings);\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n return [\n \"<!doctype html>\",\n `<html lang=\"pt-BR\"><head><meta charset=\"utf-8\"><title>${title}</title>`,\n `<style>${baseStylesheet(page)}${extra}</style>`,\n \"</head><body>\",\n body,\n \"</body></html>\",\n ].join(\"\");\n}\n\nfunction pageFromSettings(s: PageSettings | undefined): NonNullable<DocumentToHtmlOptions[\"page\"]> {\n if (!s) return DEFAULT_PAGE;\n const fmt = (px: number) => `${pxToMm(px).toFixed(2)}mm`;\n return {\n width: fmt(s.width),\n height: fmt(s.height),\n marginTop: fmt(s.marginTop),\n marginBottom: fmt(s.marginBottom),\n marginLeft: fmt(s.marginLeft),\n marginRight: fmt(s.marginRight),\n };\n}\n\n/** Body-only HTML for embedding in other documents. */\nexport function documentToHtmlFragment(\n doc: SerializedDocument | LegacySerializedDocument,\n): string {\n const blocks = normalize(doc).blocks;\n const out: string[] = [];\n let i = 0;\n while (i < blocks.length) {\n const block = blocks[i];\n if (block.type === \"listItem\") {\n const groupStart = i;\n const kind: ListKind = block.attrs.listKind === \"ordered\" ? \"ordered\" : \"bullet\";\n const items: SerializedBlock[] = [];\n while (\n i < blocks.length &&\n blocks[i].type === \"listItem\" &&\n (blocks[i].attrs.listKind ?? \"bullet\") === kind\n ) {\n items.push(blocks[i]);\n i++;\n }\n out.push(renderListGroup(items, kind, groupStart));\n continue;\n }\n out.push(renderBlock(block, i));\n i++;\n }\n return out.join(\"\");\n}\n\n/** JSON export — a stable serialization for save/load round-trips. */\nexport function documentToJson(\n doc: SerializedDocument | LegacySerializedDocument,\n pretty = true,\n): string {\n return JSON.stringify(normalize(doc), null, pretty ? 2 : 0);\n}\n\n// ---------- blocks ----------\n\nfunction renderBlock(block: SerializedBlock, index: number): string {\n switch (block.type) {\n case \"paragraph\":\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n case \"heading\": {\n const level = clampHeadingLevel(block.attrs.level);\n return `<h${level}${blockAttrs(`ed-heading ed-heading-${level}`, block.attrs)}>${renderInline(\n block.delta,\n )}</h${level}>`;\n }\n case \"blockquote\":\n return `<blockquote${blockAttrs(\"ed-blockquote\", block.attrs)}>${renderInline(\n block.delta,\n )}</blockquote>`;\n case \"codeBlock\": {\n const lang = block.attrs.language;\n const codeAttrs = lang ? ` class=\"language-${escapeAttr(lang)}\"` : \"\";\n return `<pre${blockAttrs(\"ed-codeblock\", block.attrs)}><code${codeAttrs}>${renderInline(\n block.delta,\n )}</code></pre>`;\n }\n case \"table\":\n return renderTable(block);\n default:\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n }\n}\n\nfunction renderListGroup(items: SerializedBlock[], kind: ListKind, key: number): string {\n // Tree-build using listLevel just like Editor.buildListTree.\n interface Node { item: SerializedBlock; children: Node[]; }\n const roots: Node[] = [];\n const stack: { children: Node[]; level: number }[] = [{ children: roots, level: -1 }];\n for (const it of items) {\n const level = clampListLevel(it.attrs.listLevel);\n while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();\n const node: Node = { item: it, children: [] };\n stack[stack.length - 1].children.push(node);\n stack.push({ children: node.children, level });\n }\n return renderListTree(roots, kind, `list-${key}`);\n}\n\nfunction renderListTree(nodes: { item: SerializedBlock; children: any[] }[], kind: ListKind, _key: string): string {\n const Tag = kind === \"ordered\" ? \"ol\" : \"ul\";\n const cls = `ed-list ed-list-${kind}`;\n const items = nodes\n .map((n) => {\n const inner = renderInline(n.item.delta);\n const nested =\n n.children.length > 0 ? renderListTree(n.children, kind, _key + \"n\") : \"\";\n return `<li${blockAttrs(\"ed-listitem\", n.item.attrs)}>${inner}${nested}</li>`;\n })\n .join(\"\");\n return `<${Tag} class=\"${cls}\" data-list-kind=\"${kind}\">${items}</${Tag}>`;\n}\n\nfunction renderTable(block: SerializedBlock): string {\n const rows = typeof block.attrs.rows === \"number\" ? block.attrs.rows : 0;\n const cols = typeof block.attrs.cols === \"number\" ? block.attrs.cols : 0;\n const cells = block.cells ?? [];\n if (rows <= 0 || cols <= 0) return \"\";\n\n const colGroup = renderColGroup(block.attrs.colWidths, cols);\n const trs: string[] = [];\n for (let r = 0; r < rows; r++) {\n const tds: string[] = [];\n for (let c = 0; c < cols; c++) {\n const cell = cells[r * cols + c];\n if (!cell) {\n tds.push(\"<td class=\\\"ed-cell\\\"></td>\");\n continue;\n }\n if (cell.attrs?.covered) continue;\n tds.push(renderCell(cell));\n }\n trs.push(`<tr>${tds.join(\"\")}</tr>`);\n }\n return `<div class=\"ed-table-wrap\"><table class=\"ed-table\">${colGroup}<tbody>${trs.join(\"\")}</tbody></table></div>`;\n}\n\nfunction renderColGroup(widths: number[] | undefined, cols: number): string {\n if (!widths || widths.length === 0) return \"\";\n const cells: string[] = [];\n for (let i = 0; i < cols; i++) {\n const w = widths[i];\n cells.push(typeof w === \"number\" ? `<col style=\"width:${w}px\">` : \"<col>\");\n }\n return `<colgroup>${cells.join(\"\")}</colgroup>`;\n}\n\nfunction renderCell(cell: SerializedCell): string {\n const rs = cell.attrs?.rowspan && cell.attrs.rowspan > 1\n ? ` rowspan=\"${cell.attrs.rowspan}\"`\n : \"\";\n const cs = cell.attrs?.colspan && cell.attrs.colspan > 1\n ? ` colspan=\"${cell.attrs.colspan}\"`\n : \"\";\n return `<td class=\"ed-cell\"${rs}${cs}>${renderInline(cell.delta)}</td>`;\n}\n\n// ---------- inline ----------\n\nfunction renderInline(delta: DeltaOp[]): string {\n if (delta.length === 0) return \"<br>\";\n const parts: string[] = [];\n // Floating wrap-left/wrap-right embeds are emitted FIRST so CSS float wraps\n // the following inline text — mirrors the in-editor renderer.\n const wraps: string[] = [];\n for (const op of delta) {\n if (typeof op.insert === \"string\") {\n if (op.insert.length === 0) continue;\n parts.push(applyMarks(escapeHtml(op.insert), op.attributes));\n } else if (isImageEmbed(op.insert)) {\n const layout = op.insert.layout ?? \"inline\";\n if (layout === \"wrap-left\" || layout === \"wrap-right\") {\n wraps.push(renderImg(op.insert));\n } else {\n parts.push(renderImg(op.insert));\n }\n }\n }\n if (wraps.length === 0 && parts.length === 0) return \"<br>\";\n return wraps.join(\"\") + parts.join(\"\");\n}\n\nfunction applyMarks(text: string, attrs: MarkAttrs | undefined): string {\n if (!attrs) return text;\n let html = text;\n if (attrs.bold) html = `<strong>${html}</strong>`;\n if (attrs.italic) html = `<em>${html}</em>`;\n if (attrs.underline) html = `<u>${html}</u>`;\n if (attrs.strike) html = `<s>${html}</s>`;\n const styles: string[] = [];\n if (attrs.color) styles.push(`color:${cssValue(attrs.color)}`);\n if (attrs.fontFamily) styles.push(`font-family:${cssValue(attrs.fontFamily)}`);\n if (attrs.fontSize) styles.push(`font-size:${cssValue(attrs.fontSize)}`);\n if (styles.length > 0) html = `<span style=\"${styles.join(\";\")}\">${html}</span>`;\n if (attrs.link?.href) {\n const t = attrs.link.title ? ` title=\"${escapeAttr(attrs.link.title)}\"` : \"\";\n html = `<a href=\"${escapeAttr(attrs.link.href)}\"${t} rel=\"noopener noreferrer\" target=\"_blank\">${html}</a>`;\n }\n if (attrs.comment?.markId) {\n html = `<span data-comment-id=\"${escapeAttr(attrs.comment.markId)}\">${html}</span>`;\n }\n return html;\n}\n\nfunction renderImg(embed: ImageEmbed): string {\n const layout = embed.layout ?? \"inline\";\n const align = embed.align;\n const ox = embed.offsetX ?? 0;\n const oy = embed.offsetY ?? 0;\n const hasCaption = !!embed.caption && embed.caption.length > 0;\n\n // The wrapper carries the positioning (float/absolute/inline-block/block).\n // The img keeps the intrinsic size when wrapped; when there's no caption we\n // keep the historical bare `<img>` output for unchanged DOM/CSS.\n const wrapperStyles: string[] = [];\n switch (layout) {\n case \"wrap-left\":\n wrapperStyles.push(\n \"float:left\",\n `width:${embed.width}px`,\n `margin-right:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"wrap-right\":\n wrapperStyles.push(\n \"float:right\",\n `width:${embed.width}px`,\n `margin-left:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"behind\":\n case \"front\":\n wrapperStyles.push(\n \"position:absolute\",\n `left:${ox}px`,\n `top:${oy}px`,\n `width:${embed.width}px`,\n `z-index:${layout === \"behind\" ? -1 : 2}`,\n );\n break;\n case \"inline\":\n default:\n if (align) {\n wrapperStyles.push(\n \"display:block\",\n `width:${embed.width}px`,\n `margin-left:${align === \"left\" ? \"0\" : \"auto\"}`,\n `margin-right:${align === \"right\" ? \"0\" : \"auto\"}`,\n );\n } else {\n wrapperStyles.push(\n \"display:inline-block\",\n \"vertical-align:text-bottom\",\n `width:${embed.width}px`,\n );\n }\n break;\n }\n\n const imgStyles: string[] = hasCaption\n ? [`width:${embed.width}px`, `height:${embed.height}px`, \"display:block\"]\n : wrapperStyles.concat(\n // Preserve old height when emitting bare <img>.\n `height:${embed.height}px`,\n );\n\n const imgHtml = `<img src=\"${escapeAttr(embed.src)}\" width=\"${embed.width}\" height=\"${embed.height}\" alt=\"${escapeAttr(embed.caption ?? \"\")}\" data-embed=\"image\" data-embed-layout=\"${layout}\"${\n align ? ` data-embed-align=\"${escapeAttr(align)}\"` : \"\"\n } style=\"${imgStyles.join(\";\")}\">`;\n\n if (!hasCaption) return imgHtml;\n\n const captionAlign = embed.captionAlign ?? \"center\";\n return `<figure class=\"ed-figure\" data-embed-figure=\"true\" data-embed-layout=\"${layout}\" style=\"${wrapperStyles.join(\";\")}\">${imgHtml}<figcaption class=\"ed-figcaption\" data-caption-align=\"${captionAlign}\" style=\"text-align:${captionAlign}\">${escapeHtml(\n embed.caption!,\n )}</figcaption></figure>`;\n}\n\n// ---------- helpers ----------\n\nfunction blockAttrs(baseClass: string, attrs: BlockAttrs): string {\n const classes = [baseClass, \"ed-block\"];\n const align = clampAlign(attrs.align);\n if (align) classes.push(`ed-align-${align}`);\n const dir = clampDir(attrs.dir);\n const dirAttr = dir ? ` dir=\"${dir}\"` : \"\";\n return ` class=\"${classes.join(\" \")}\"${dirAttr}`;\n}\n\nfunction clampHeadingLevel(l: unknown): 1 | 2 | 3 | 4 | 5 | 6 {\n if (typeof l !== \"number\") return 1;\n const n = Math.trunc(l);\n if (n < 1) return 1;\n if (n > 6) return 6;\n return n as 1 | 2 | 3 | 4 | 5 | 6;\n}\n\nfunction clampListLevel(l: unknown): number {\n if (typeof l !== \"number\" || !Number.isFinite(l)) return 0;\n return Math.max(0, Math.min(5, Math.trunc(l)));\n}\n\nfunction clampAlign(a: unknown): AlignValue | undefined {\n if (a === \"left\" || a === \"center\" || a === \"right\" || a === \"justify\") return a;\n return undefined;\n}\n\nfunction clampDir(d: unknown): DirValue | undefined {\n if (d === \"ltr\" || d === \"rtl\") return d;\n return undefined;\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\nfunction escapeAttr(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\n/** Allow only safe characters in CSS values — defense in depth against injected `</style>`. */\nfunction cssValue(v: string): string {\n return v.replace(/[<>\"';\\\\]/g, \"\");\n}\n\nfunction baseStylesheet(page: NonNullable<DocumentToHtmlOptions[\"page\"]>): string {\n // Margins are owned by `@page` only. Chromium honors that block both for\n // `window.print()` (client-side `exportPdfFromDocument`) and for\n // `page.pdf({ preferCSSPageSize: true })` (server-side `renderPdf` in\n // `@sofereditor/export-pdf-server`). Adding the same offsets via `body { padding }`\n // would compound and double the margin in the output PDF.\n return `\n@page {\n size: ${page.width} ${page.height};\n margin: ${page.marginTop} ${page.marginRight} ${page.marginBottom} ${page.marginLeft};\n}\nhtml, body { margin: 0; padding: 0; background: white; color: #1a1a1f; }\nbody {\n font-family: \"Arial\", \"Helvetica\", sans-serif;\n font-size: 11pt;\n line-height: 1.5;\n}\n.ed-paragraph { margin: 0 0 0.5em; min-height: 1.5em; }\n.ed-heading { margin: 0.5em 0 0.25em; font-weight: 600; line-height: 1.25; }\n.ed-heading-1 { font-size: 28pt; }\n.ed-heading-2 { font-size: 22pt; }\n.ed-heading-3 { font-size: 18pt; }\n.ed-heading-4 { font-size: 14pt; }\n.ed-heading-5 { font-size: 12pt; }\n.ed-heading-6 { font-size: 11pt; color: #6b7280; }\n.ed-blockquote {\n margin: 0 0 0.5em; padding: 0.25em 12px;\n border-inline-start: 3px solid #e5e7eb; color: #6b7280;\n}\n.ed-codeblock {\n margin: 0 0 0.5em; background: #0f172a; color: #e2e8f0;\n padding: 12px 14px; border-radius: 6px;\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11pt; white-space: pre-wrap;\n}\n.ed-codeblock code { font-family: inherit; background: transparent; color: inherit; }\n.ed-block[dir=\"rtl\"] { text-align: start; }\n.ed-align-left { text-align: left; }\n.ed-align-center { text-align: center; }\n.ed-align-right { text-align: right; }\n.ed-align-justify { text-align: justify; }\n.ed-list { margin: 0 0 0.5em; padding-inline-start: 28px; }\n.ed-list .ed-list { margin-block: 0; }\n.ed-list-bullet { list-style-type: disc; }\n.ed-list-bullet .ed-list-bullet { list-style-type: circle; }\n.ed-list-bullet .ed-list-bullet .ed-list-bullet { list-style-type: square; }\n.ed-list-ordered { list-style-type: decimal; }\n.ed-list-ordered .ed-list-ordered { list-style-type: lower-alpha; }\n.ed-list-ordered .ed-list-ordered .ed-list-ordered { list-style-type: lower-roman; }\n.ed-listitem { margin: 0; min-height: 1.5em; }\n.ed-table-wrap { margin: 0 0 0.5em; position: relative; }\n.ed-table { width: 100%; border-collapse: collapse; table-layout: fixed; }\n.ed-cell {\n border: 1px solid #cbd5e1; padding: 6px 8px;\n vertical-align: top; word-break: break-word; white-space: pre-wrap;\n}\nimg[data-embed=\"image\"] { max-width: 100%; }\n.ed-block { position: relative; isolation: isolate; }\na { color: #2563eb; }\n`;\n}\n","import type { LegacySerializedDocument, SerializedDocument } from \"@sofereditor/core\";\nimport { documentToHtml, type DocumentToHtmlOptions } from \"./html\";\n\nexport interface ExportPdfFromDocumentOptions extends DocumentToHtmlOptions {\n /** Suggested file name (used by the OS save dialog as the default). */\n filename?: string;\n}\n\n/**\n * Open the browser's print dialog for a `SerializedDocument`.\n *\n * Strategy: render the document to standalone HTML in a hidden iframe and call\n * `iframe.contentWindow.print()`. The user picks \"Save as PDF\" (or any printer)\n * from the native dialog. No external PDF library required.\n *\n * The returned promise resolves after the print dialog closes (`afterprint`).\n */\nexport async function exportPdfFromDocument(\n doc: SerializedDocument | LegacySerializedDocument,\n options: ExportPdfFromDocumentOptions = {},\n): Promise<void> {\n const html = documentToHtml(doc, { ...options, standalone: true });\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\nexport interface SerializePaginatedHtmlOptions {\n /** Document title (becomes `<title>` and is used as default filename). */\n title?: string;\n /** Extra CSS appended to the cloned styles (e.g. for headers/footers). */\n extraCss?: string;\n /**\n * Override the `@page { size }`. Default reads `--ed-page-width` /\n * `--ed-page-height` CSS variables off the root (set by `<Editor>` from the\n * current `PageSettings`); falls back to A4 if absent.\n */\n pageSize?: { width: string; height: string };\n}\n\nexport interface ExportPdfFromElementOptions extends SerializePaginatedHtmlOptions {\n /** Suggested file name. */\n filename?: string;\n}\n\nfunction cssPageSizeFromRoot(\n cs: CSSStyleDeclaration | undefined,\n): { width: string; height: string } {\n if (!cs) return { width: \"210mm\", height: \"297mm\" };\n const w = cs.getPropertyValue(\"--ed-page-width\").trim();\n const h = cs.getPropertyValue(\"--ed-page-height\").trim();\n if (!w || !h) return { width: \"210mm\", height: \"297mm\" };\n // CSS vars come back as e.g. \"794px\". `@page` accepts px directly.\n return { width: w, height: h };\n}\n\n/**\n * Serialize a live editor root (the `.ed-root` paginated DOM) into a\n * self-contained HTML string. The output preserves the in-editor pagination\n * decisions verbatim — each `.ed-page` becomes a fixed-size page in the final\n * print medium with no re-layout possible.\n *\n * The returned HTML inlines every accessible stylesheet from the host document\n * (or links it as a fallback for cross-origin sheets) so the layout survives\n * transplant to an iframe, a saved file, or a headless renderer.\n *\n * This is the building block for two paths:\n * - `exportPdfFromElement` (this file): writes the HTML into a hidden iframe\n * and calls `window.print()` for the local \"Save as PDF\" flow.\n * - Upload-to-server snapshots: POST the string to a backend that converts it\n * to PDF via Puppeteer's `setContent + page.pdf()` without re-running the\n * pagination engine.\n */\nexport function serializePaginatedHtml(\n root: HTMLElement,\n options: SerializePaginatedHtmlOptions = {},\n): string {\n const clone = root.cloneNode(true) as HTMLElement;\n // Strip interactive scaffolding that print styles can't see ahead of time.\n clone.querySelectorAll(\"[contenteditable]\").forEach((el) => {\n (el as HTMLElement).removeAttribute(\"contenteditable\");\n });\n clone.querySelectorAll(\".ed-image-overlay\").forEach((el) => el.remove());\n\n // Read the page size baked into the editor via `--ed-page-*` CSS variables.\n // The Editor component sets these on its root from the current PageSettings\n // (`packages/react/src/Editor.tsx`). Falls back to A4 if we can't read them.\n const cs = root.ownerDocument?.defaultView?.getComputedStyle(root);\n const pageSize = options.pageSize ?? cssPageSizeFromRoot(cs);\n\n const styles = collectStyles();\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n // The `@page { size }` and page-break rules live inside `@media print` so\n // they merge cleanly with any host-document print stylesheet that already\n // declares its own `@page` (e.g. `apps/playground/src/styles.css`). Putting\n // ours after the cloned `<style>`s gives our override last-write-wins.\n return [\n \"<!doctype html>\",\n `<html><head><meta charset=\"utf-8\"><title>${title}</title>`,\n styles,\n `<style>\n html, body { margin: 0; padding: 0; background: white; }\n @media print {\n @page { size: ${pageSize.width} ${pageSize.height}; margin: 0; }\n .ed-page { box-shadow: none !important; border: none !important; border-radius: 0 !important; margin: 0 !important; page-break-after: always; break-after: page; }\n .ed-page:last-child { page-break-after: auto; break-after: auto; }\n .ed-image-overlay { display: none !important; }\n }\n ${extra}\n </style>`,\n \"</head><body>\",\n clone.outerHTML,\n \"</body></html>\",\n ].join(\"\");\n}\n\n/**\n * Snapshot a live editor root element (the `.ed-root` paginated DOM) and open\n * the browser's print dialog. Preserves the in-editor pagination decisions\n * verbatim — no re-layout in the print frame.\n *\n * For the \"send the snapshot to a server\" use case, use\n * `serializePaginatedHtml` directly and POST the returned string.\n */\nexport async function exportPdfFromElement(\n root: HTMLElement,\n options: ExportPdfFromElementOptions = {},\n): Promise<void> {\n const html = serializePaginatedHtml(root, options);\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\n// ---------- internals ----------\n\nasync function printHtmlInIframe(html: string, _filename: string): Promise<void> {\n const iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"aria-hidden\", \"true\");\n iframe.style.cssText =\n \"position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;\";\n document.body.appendChild(iframe);\n\n const win = iframe.contentWindow;\n const docu = iframe.contentDocument ?? win?.document;\n if (!win || !docu) {\n iframe.remove();\n throw new Error(\"export-pdf: failed to access iframe document\");\n }\n\n docu.open();\n docu.write(html);\n docu.close();\n\n // Wait for the iframe to finish loading (images, fonts).\n await new Promise<void>((resolve) => {\n if (docu.readyState === \"complete\") resolve();\n else iframe.addEventListener(\"load\", () => resolve(), { once: true });\n });\n // Best-effort wait for embedded images: print dialogs that snapshot too early\n // miss late-loading data URIs (rare, but real).\n await waitForImages(docu);\n\n await new Promise<void>((resolve) => {\n const cleanup = () => {\n win.removeEventListener(\"afterprint\", cleanup);\n // Defer removal one tick so Safari's print queue doesn't choke.\n setTimeout(() => iframe.remove(), 0);\n resolve();\n };\n win.addEventListener(\"afterprint\", cleanup);\n win.focus();\n win.print();\n // Fallback in case afterprint never fires (older browsers).\n setTimeout(() => {\n if (iframe.isConnected) cleanup();\n }, 60_000);\n });\n}\n\nfunction collectStyles(): string {\n const parts: string[] = [];\n for (const sheet of Array.from(document.styleSheets)) {\n try {\n const rules = sheet.cssRules;\n if (!rules) continue;\n const css = Array.from(rules)\n .map((r) => r.cssText)\n .join(\"\\n\");\n if (css) parts.push(`<style>${css}</style>`);\n } catch {\n // Cross-origin sheet — fall back to linking it.\n const href = sheet.href;\n if (href) parts.push(`<link rel=\"stylesheet\" href=\"${escapeAttr(href)}\">`);\n }\n }\n return parts.join(\"\\n\");\n}\n\nasync function waitForImages(docu: Document): Promise<void> {\n const imgs = Array.from(docu.images);\n await Promise.all(\n imgs.map(\n (img) =>\n new Promise<void>((resolve) => {\n if (img.complete) return resolve();\n img.addEventListener(\"load\", () => resolve(), { once: true });\n img.addEventListener(\"error\", () => resolve(), { once: true });\n }),\n ),\n );\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\nfunction escapeAttr(s: string): string {\n return escapeHtml(s);\n}\n","/**\n * Trigger a browser download for an in-memory blob/string. Tiny utility — kept\n * in this package because PDF/HTML/JSON exporters all want it.\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.rel = \"noopener\";\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n setTimeout(() => {\n a.remove();\n URL.revokeObjectURL(url);\n }, 0);\n}\n\nexport function downloadString(\n text: string,\n filename: string,\n mimeType = \"text/plain;charset=utf-8\",\n): void {\n downloadB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ClB,WAAS,KAAK,YAAY,CAAC;AAC3B,IAAE,MAAM;AACR,aAAW,MAAM;AACf,MAAE,OAAO;AACT,QAAI,gBAAgB,GAAG;AAAA,EACzB,GAAG,CAAC;AACN;AAEO,SAAS,eACd,MACA,UACA,WAAW,4BACL;AACN,eAAa,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,SAAS,CAAC,GAAG,QAAQ;AAC7D;","names":["escapeHtml","escapeAttr","HTML_ESCAPES"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/html.ts","../src/pdf.ts","../src/download.ts"],"sourcesContent":["export {\n documentToHtml,\n documentToHtmlFragment,\n documentToJson,\n} from \"./html\";\nexport type { DocumentToHtmlOptions } from \"./html\";\nexport {\n exportPdfFromDocument,\n exportPdfFromElement,\n serializePaginatedHtml,\n} from \"./pdf\";\nexport type {\n ExportPdfFromDocumentOptions,\n ExportPdfFromElementOptions,\n SerializePaginatedHtmlOptions,\n} from \"./pdf\";\nexport { downloadBlob, downloadString } from \"./download\";\n","import type {\n AlignValue,\n BlockAttrs,\n DeltaOp,\n DirValue,\n ImageEmbed,\n LegacySerializedDocument,\n ListKind,\n MarkAttrs,\n PageSettings,\n SerializedBlock,\n SerializedCell,\n SerializedDocument,\n} from \"@sofereditor/core\";\nimport { isImageEmbed, isLegacySerializedDocument, pxToMm } from \"@sofereditor/core\";\n\nfunction normalize(doc: SerializedDocument | LegacySerializedDocument): SerializedDocument {\n return isLegacySerializedDocument(doc) ? { blocks: doc } : doc;\n}\n\nexport interface DocumentToHtmlOptions {\n /** Document title (set on `<title>` and used as the file name hint). Default \"Documento\". */\n title?: string;\n /** When true (default) emits a full `<html>` document. When false emits only the body fragment. */\n standalone?: boolean;\n /** Extra CSS appended after the default print stylesheet. Only honored when `standalone`. */\n extraCss?: string;\n /** Page geometry hints injected into `@page`. Defaults to A4. */\n page?: {\n width: string;\n height: string;\n marginTop: string;\n marginBottom: string;\n marginLeft: string;\n marginRight: string;\n };\n}\n\nconst DEFAULT_PAGE = {\n width: \"210mm\",\n height: \"297mm\",\n marginTop: \"25mm\",\n marginBottom: \"25mm\",\n marginLeft: \"25mm\",\n marginRight: \"25mm\",\n};\n\n/**\n * Serialize a `SerializedDocument` to standalone HTML.\n *\n * Output structure mirrors what `@sofereditor/react` paints at runtime: each\n * top-level block becomes one element (`<p>`, `<h1..6>`, `<blockquote>`, `<pre>`,\n * `<table>`), consecutive `listItem` blocks are reconstructed into nested\n * `<ul>`/`<ol>` trees, and image embeds are emitted as `<img>` tags carrying the\n * embed's data URL (so the export is self-contained).\n *\n * NOT a fragment of the live editor DOM — this walks the model so the output is\n * editor-state agnostic (no caret artifacts, no zero-width phantom anchors).\n */\nexport function documentToHtml(\n doc: SerializedDocument | LegacySerializedDocument,\n options: DocumentToHtmlOptions = {},\n): string {\n const normalized = normalize(doc);\n const body = documentToHtmlFragment(normalized);\n if (options.standalone === false) return body;\n const page = options.page ?? pageFromSettings(normalized.pageSettings);\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n return [\n \"<!doctype html>\",\n `<html lang=\"pt-BR\"><head><meta charset=\"utf-8\"><title>${title}</title>`,\n `<style>${baseStylesheet(page)}${extra}</style>`,\n \"</head><body>\",\n body,\n \"</body></html>\",\n ].join(\"\");\n}\n\nfunction pageFromSettings(s: PageSettings | undefined): NonNullable<DocumentToHtmlOptions[\"page\"]> {\n if (!s) return DEFAULT_PAGE;\n const fmt = (px: number) => `${pxToMm(px).toFixed(2)}mm`;\n return {\n width: fmt(s.width),\n height: fmt(s.height),\n marginTop: fmt(s.marginTop),\n marginBottom: fmt(s.marginBottom),\n marginLeft: fmt(s.marginLeft),\n marginRight: fmt(s.marginRight),\n };\n}\n\n/** Body-only HTML for embedding in other documents. */\nexport function documentToHtmlFragment(\n doc: SerializedDocument | LegacySerializedDocument,\n): string {\n const blocks = normalize(doc).blocks;\n const out: string[] = [];\n let i = 0;\n while (i < blocks.length) {\n const block = blocks[i];\n if (block.type === \"listItem\") {\n const groupStart = i;\n const kind: ListKind = block.attrs.listKind === \"ordered\" ? \"ordered\" : \"bullet\";\n const items: SerializedBlock[] = [];\n while (\n i < blocks.length &&\n blocks[i].type === \"listItem\" &&\n (blocks[i].attrs.listKind ?? \"bullet\") === kind\n ) {\n items.push(blocks[i]);\n i++;\n }\n out.push(renderListGroup(items, kind, groupStart));\n continue;\n }\n out.push(renderBlock(block, i));\n i++;\n }\n return out.join(\"\");\n}\n\n/** JSON export — a stable serialization for save/load round-trips. */\nexport function documentToJson(\n doc: SerializedDocument | LegacySerializedDocument,\n pretty = true,\n): string {\n return JSON.stringify(normalize(doc), null, pretty ? 2 : 0);\n}\n\n// ---------- blocks ----------\n\nfunction renderBlock(block: SerializedBlock, index: number): string {\n switch (block.type) {\n case \"paragraph\":\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n case \"heading\": {\n const level = clampHeadingLevel(block.attrs.level);\n return `<h${level}${blockAttrs(`ed-heading ed-heading-${level}`, block.attrs)}>${renderInline(\n block.delta,\n )}</h${level}>`;\n }\n case \"blockquote\":\n return `<blockquote${blockAttrs(\"ed-blockquote\", block.attrs)}>${renderInline(\n block.delta,\n )}</blockquote>`;\n case \"codeBlock\": {\n const lang = block.attrs.language;\n const codeAttrs = lang ? ` class=\"language-${escapeAttr(lang)}\"` : \"\";\n return `<pre${blockAttrs(\"ed-codeblock\", block.attrs)}><code${codeAttrs}>${renderInline(\n block.delta,\n )}</code></pre>`;\n }\n case \"table\":\n return renderTable(block);\n default:\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n }\n}\n\nfunction renderListGroup(items: SerializedBlock[], kind: ListKind, key: number): string {\n // Tree-build using listLevel just like Editor.buildListTree.\n interface Node { item: SerializedBlock; children: Node[]; }\n const roots: Node[] = [];\n const stack: { children: Node[]; level: number }[] = [{ children: roots, level: -1 }];\n for (const it of items) {\n const level = clampListLevel(it.attrs.listLevel);\n while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();\n const node: Node = { item: it, children: [] };\n stack[stack.length - 1].children.push(node);\n stack.push({ children: node.children, level });\n }\n return renderListTree(roots, kind, `list-${key}`);\n}\n\nfunction renderListTree(nodes: { item: SerializedBlock; children: any[] }[], kind: ListKind, _key: string): string {\n const Tag = kind === \"ordered\" ? \"ol\" : \"ul\";\n const cls = `ed-list ed-list-${kind}`;\n const items = nodes\n .map((n) => {\n const inner = renderInline(n.item.delta);\n const nested =\n n.children.length > 0 ? renderListTree(n.children, kind, _key + \"n\") : \"\";\n return `<li${blockAttrs(\"ed-listitem\", n.item.attrs)}>${inner}${nested}</li>`;\n })\n .join(\"\");\n return `<${Tag} class=\"${cls}\" data-list-kind=\"${kind}\">${items}</${Tag}>`;\n}\n\nfunction renderTable(block: SerializedBlock): string {\n const rows = typeof block.attrs.rows === \"number\" ? block.attrs.rows : 0;\n const cols = typeof block.attrs.cols === \"number\" ? block.attrs.cols : 0;\n const cells = block.cells ?? [];\n if (rows <= 0 || cols <= 0) return \"\";\n\n const colGroup = renderColGroup(block.attrs.colWidths, cols);\n const trs: string[] = [];\n for (let r = 0; r < rows; r++) {\n const tds: string[] = [];\n for (let c = 0; c < cols; c++) {\n const cell = cells[r * cols + c];\n if (!cell) {\n tds.push(\"<td class=\\\"ed-cell\\\"></td>\");\n continue;\n }\n if (cell.attrs?.covered) continue;\n tds.push(renderCell(cell));\n }\n trs.push(`<tr>${tds.join(\"\")}</tr>`);\n }\n return `<div class=\"ed-table-wrap\"><table class=\"ed-table\">${colGroup}<tbody>${trs.join(\"\")}</tbody></table></div>`;\n}\n\nfunction renderColGroup(widths: number[] | undefined, cols: number): string {\n if (!widths || widths.length === 0) return \"\";\n const cells: string[] = [];\n for (let i = 0; i < cols; i++) {\n const w = widths[i];\n cells.push(typeof w === \"number\" ? `<col style=\"width:${w}px\">` : \"<col>\");\n }\n return `<colgroup>${cells.join(\"\")}</colgroup>`;\n}\n\nfunction renderCell(cell: SerializedCell): string {\n const rs = cell.attrs?.rowspan && cell.attrs.rowspan > 1\n ? ` rowspan=\"${cell.attrs.rowspan}\"`\n : \"\";\n const cs = cell.attrs?.colspan && cell.attrs.colspan > 1\n ? ` colspan=\"${cell.attrs.colspan}\"`\n : \"\";\n return `<td class=\"ed-cell\"${rs}${cs}>${renderInline(cell.delta)}</td>`;\n}\n\n// ---------- inline ----------\n\nfunction renderInline(delta: DeltaOp[]): string {\n if (delta.length === 0) return \"<br>\";\n const parts: string[] = [];\n // Floating wrap-left/wrap-right embeds are emitted FIRST so CSS float wraps\n // the following inline text — mirrors the in-editor renderer.\n const wraps: string[] = [];\n for (const op of delta) {\n if (typeof op.insert === \"string\") {\n if (op.insert.length === 0) continue;\n parts.push(applyMarks(escapeHtml(op.insert), op.attributes));\n } else if (isImageEmbed(op.insert)) {\n const layout = op.insert.layout ?? \"inline\";\n if (layout === \"wrap-left\" || layout === \"wrap-right\") {\n wraps.push(renderImg(op.insert));\n } else {\n parts.push(renderImg(op.insert));\n }\n }\n }\n if (wraps.length === 0 && parts.length === 0) return \"<br>\";\n return wraps.join(\"\") + parts.join(\"\");\n}\n\nfunction applyMarks(text: string, attrs: MarkAttrs | undefined): string {\n if (!attrs) return text;\n let html = text;\n if (attrs.bold) html = `<strong>${html}</strong>`;\n if (attrs.italic) html = `<em>${html}</em>`;\n if (attrs.underline) html = `<u>${html}</u>`;\n if (attrs.strike) html = `<s>${html}</s>`;\n const styles: string[] = [];\n if (attrs.color) styles.push(`color:${cssValue(attrs.color)}`);\n if (attrs.fontFamily) styles.push(`font-family:${cssValue(attrs.fontFamily)}`);\n if (attrs.fontSize) styles.push(`font-size:${cssValue(attrs.fontSize)}`);\n if (styles.length > 0) html = `<span style=\"${styles.join(\";\")}\">${html}</span>`;\n if (attrs.link?.href) {\n const t = attrs.link.title ? ` title=\"${escapeAttr(attrs.link.title)}\"` : \"\";\n html = `<a href=\"${escapeAttr(attrs.link.href)}\"${t} rel=\"noopener noreferrer\" target=\"_blank\">${html}</a>`;\n }\n if (attrs.comment?.markId) {\n html = `<span data-comment-id=\"${escapeAttr(attrs.comment.markId)}\">${html}</span>`;\n }\n return html;\n}\n\nfunction renderImg(embed: ImageEmbed): string {\n const layout = embed.layout ?? \"inline\";\n const align = embed.align;\n const ox = embed.offsetX ?? 0;\n const oy = embed.offsetY ?? 0;\n const hasCaption = !!embed.caption && embed.caption.length > 0;\n\n // The wrapper carries the positioning (float/absolute/inline-block/block).\n // The img keeps the intrinsic size when wrapped; when there's no caption we\n // keep the historical bare `<img>` output for unchanged DOM/CSS.\n const wrapperStyles: string[] = [];\n switch (layout) {\n case \"wrap-left\":\n wrapperStyles.push(\n \"float:left\",\n `width:${embed.width}px`,\n `margin-right:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"wrap-right\":\n wrapperStyles.push(\n \"float:right\",\n `width:${embed.width}px`,\n `margin-left:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"behind\":\n case \"front\":\n wrapperStyles.push(\n \"position:absolute\",\n `left:${ox}px`,\n `top:${oy}px`,\n `width:${embed.width}px`,\n `z-index:${layout === \"behind\" ? -1 : 2}`,\n );\n break;\n case \"inline\":\n default:\n if (align) {\n wrapperStyles.push(\n \"display:block\",\n `width:${embed.width}px`,\n `margin-left:${align === \"left\" ? \"0\" : \"auto\"}`,\n `margin-right:${align === \"right\" ? \"0\" : \"auto\"}`,\n );\n } else {\n wrapperStyles.push(\n \"display:inline-block\",\n \"vertical-align:text-bottom\",\n `width:${embed.width}px`,\n );\n }\n break;\n }\n\n const imgStyles: string[] = hasCaption\n ? [`width:${embed.width}px`, `height:${embed.height}px`, \"display:block\"]\n : wrapperStyles.concat(\n // Preserve old height when emitting bare <img>.\n `height:${embed.height}px`,\n );\n\n const imgHtml = `<img src=\"${escapeAttr(embed.src)}\" width=\"${embed.width}\" height=\"${embed.height}\" alt=\"${escapeAttr(embed.caption ?? \"\")}\" data-embed=\"image\" data-embed-layout=\"${layout}\"${\n align ? ` data-embed-align=\"${escapeAttr(align)}\"` : \"\"\n } style=\"${imgStyles.join(\";\")}\">`;\n\n if (!hasCaption) return imgHtml;\n\n const captionAlign = embed.captionAlign ?? \"center\";\n return `<figure class=\"ed-figure\" data-embed-figure=\"true\" data-embed-layout=\"${layout}\" style=\"${wrapperStyles.join(\";\")}\">${imgHtml}<figcaption class=\"ed-figcaption\" data-caption-align=\"${captionAlign}\" style=\"text-align:${captionAlign}\">${escapeHtml(\n embed.caption!,\n )}</figcaption></figure>`;\n}\n\n// ---------- helpers ----------\n\nfunction blockAttrs(baseClass: string, attrs: BlockAttrs): string {\n const classes = [baseClass, \"ed-block\"];\n const align = clampAlign(attrs.align);\n if (align) classes.push(`ed-align-${align}`);\n const dir = clampDir(attrs.dir);\n const dirAttr = dir ? ` dir=\"${dir}\"` : \"\";\n return ` class=\"${classes.join(\" \")}\"${dirAttr}`;\n}\n\nfunction clampHeadingLevel(l: unknown): 1 | 2 | 3 | 4 | 5 | 6 {\n if (typeof l !== \"number\") return 1;\n const n = Math.trunc(l);\n if (n < 1) return 1;\n if (n > 6) return 6;\n return n as 1 | 2 | 3 | 4 | 5 | 6;\n}\n\nfunction clampListLevel(l: unknown): number {\n if (typeof l !== \"number\" || !Number.isFinite(l)) return 0;\n return Math.max(0, Math.min(5, Math.trunc(l)));\n}\n\nfunction clampAlign(a: unknown): AlignValue | undefined {\n if (a === \"left\" || a === \"center\" || a === \"right\" || a === \"justify\") return a;\n return undefined;\n}\n\nfunction clampDir(d: unknown): DirValue | undefined {\n if (d === \"ltr\" || d === \"rtl\") return d;\n return undefined;\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\nfunction escapeAttr(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\n/** Allow only safe characters in CSS values — defense in depth against injected `</style>`. */\nfunction cssValue(v: string): string {\n return v.replace(/[<>\"';\\\\]/g, \"\");\n}\n\nfunction baseStylesheet(page: NonNullable<DocumentToHtmlOptions[\"page\"]>): string {\n // Margins are owned by `@page` only. Chromium honors that block both for\n // `window.print()` (client-side `exportPdfFromDocument`) and for\n // `page.pdf({ preferCSSPageSize: true })` (server-side `renderPdf` in\n // `@sofereditor/export-pdf-server`). Adding the same offsets via `body { padding }`\n // would compound and double the margin in the output PDF.\n return `\n@page {\n size: ${page.width} ${page.height};\n margin: ${page.marginTop} ${page.marginRight} ${page.marginBottom} ${page.marginLeft};\n}\nhtml, body { margin: 0; padding: 0; background: white; color: #1a1a1f; }\nbody {\n font-family: \"Arial\", \"Helvetica\", sans-serif;\n font-size: 11pt;\n line-height: 1.5;\n}\n.ed-paragraph { margin: 0 0 0.5em; min-height: 1.5em; }\n.ed-heading { margin: 0.5em 0 0.25em; font-weight: 600; line-height: 1.25; }\n.ed-heading-1 { font-size: 28pt; }\n.ed-heading-2 { font-size: 22pt; }\n.ed-heading-3 { font-size: 18pt; }\n.ed-heading-4 { font-size: 14pt; }\n.ed-heading-5 { font-size: 12pt; }\n.ed-heading-6 { font-size: 11pt; color: #6b7280; }\n.ed-blockquote {\n margin: 0 0 0.5em; padding: 0.25em 12px;\n border-inline-start: 3px solid #e5e7eb; color: #6b7280;\n}\n.ed-codeblock {\n margin: 0 0 0.5em; background: #0f172a; color: #e2e8f0;\n padding: 12px 14px; border-radius: 6px;\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11pt; white-space: pre-wrap;\n}\n.ed-codeblock code { font-family: inherit; background: transparent; color: inherit; }\n.ed-block[dir=\"rtl\"] { text-align: start; }\n.ed-align-left { text-align: left; }\n.ed-align-center { text-align: center; }\n.ed-align-right { text-align: right; }\n.ed-align-justify { text-align: justify; }\n.ed-list { margin: 0 0 0.5em; padding-inline-start: 28px; }\n.ed-list .ed-list { margin-block: 0; }\n.ed-list-bullet { list-style-type: disc; }\n.ed-list-bullet .ed-list-bullet { list-style-type: circle; }\n.ed-list-bullet .ed-list-bullet .ed-list-bullet { list-style-type: square; }\n.ed-list-ordered { list-style-type: decimal; }\n.ed-list-ordered .ed-list-ordered { list-style-type: lower-alpha; }\n.ed-list-ordered .ed-list-ordered .ed-list-ordered { list-style-type: lower-roman; }\n.ed-listitem { margin: 0; min-height: 1.5em; }\n.ed-table-wrap { margin: 0 0 0.5em; position: relative; }\n.ed-table { width: 100%; border-collapse: collapse; table-layout: fixed; }\n.ed-cell {\n border: 1px solid #cbd5e1; padding: 6px 8px;\n vertical-align: top; word-break: break-word; white-space: pre-wrap;\n}\nimg[data-embed=\"image\"] { max-width: 100%; }\n.ed-block { position: relative; isolation: isolate; }\na { color: #2563eb; }\n`;\n}\n","import type { LegacySerializedDocument, SerializedDocument } from \"@sofereditor/core\";\nimport { documentToHtml, type DocumentToHtmlOptions } from \"./html\";\n\nexport interface ExportPdfFromDocumentOptions extends DocumentToHtmlOptions {\n /** Suggested file name (used by the OS save dialog as the default). */\n filename?: string;\n}\n\n/**\n * Open the browser's print dialog for a `SerializedDocument`.\n *\n * Strategy: render the document to standalone HTML in a hidden iframe and call\n * `iframe.contentWindow.print()`. The user picks \"Save as PDF\" (or any printer)\n * from the native dialog. No external PDF library required.\n *\n * The returned promise resolves after the print dialog closes (`afterprint`).\n */\nexport async function exportPdfFromDocument(\n doc: SerializedDocument | LegacySerializedDocument,\n options: ExportPdfFromDocumentOptions = {},\n): Promise<void> {\n const html = documentToHtml(doc, { ...options, standalone: true });\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\nexport interface SerializePaginatedHtmlOptions {\n /** Document title (becomes `<title>` and is used as default filename). */\n title?: string;\n /** Extra CSS appended to the cloned styles (e.g. for headers/footers). */\n extraCss?: string;\n /**\n * Override the `@page { size }`. Default reads `--ed-page-width` /\n * `--ed-page-height` CSS variables off the root (set by `<Editor>` from the\n * current `PageSettings`); falls back to A4 if absent.\n */\n pageSize?: { width: string; height: string };\n}\n\nexport interface ExportPdfFromElementOptions extends SerializePaginatedHtmlOptions {\n /** Suggested file name. */\n filename?: string;\n}\n\nfunction cssPageSizeFromRoot(\n cs: CSSStyleDeclaration | undefined,\n): { width: string; height: string } {\n if (!cs) return { width: \"210mm\", height: \"297mm\" };\n const w = cs.getPropertyValue(\"--ed-page-width\").trim();\n const h = cs.getPropertyValue(\"--ed-page-height\").trim();\n if (!w || !h) return { width: \"210mm\", height: \"297mm\" };\n // CSS vars come back as e.g. \"794px\". `@page` accepts px directly.\n return { width: w, height: h };\n}\n\n/**\n * Serialize a live editor root (the `.ed-root` paginated DOM) into a\n * self-contained HTML string. The output preserves the in-editor pagination\n * decisions verbatim — each `.ed-page` becomes a fixed-size page in the final\n * print medium with no re-layout possible.\n *\n * The returned HTML inlines every accessible stylesheet from the host document\n * (or links it as a fallback for cross-origin sheets) so the layout survives\n * transplant to an iframe, a saved file, or a headless renderer.\n *\n * This is the building block for two paths:\n * - `exportPdfFromElement` (this file): writes the HTML into a hidden iframe\n * and calls `window.print()` for the local \"Save as PDF\" flow.\n * - Upload-to-server snapshots: POST the string to a backend that converts it\n * to PDF via Puppeteer's `setContent + page.pdf()` without re-running the\n * pagination engine.\n */\nexport function serializePaginatedHtml(\n root: HTMLElement,\n options: SerializePaginatedHtmlOptions = {},\n): string {\n const clone = root.cloneNode(true) as HTMLElement;\n // Strip interactive scaffolding that print styles can't see ahead of time.\n clone.querySelectorAll(\"[contenteditable]\").forEach((el) => {\n (el as HTMLElement).removeAttribute(\"contenteditable\");\n });\n clone.querySelectorAll(\".ed-image-overlay\").forEach((el) => el.remove());\n clone.querySelectorAll(\".ed-remote-cursors\").forEach((el) => el.remove());\n\n // Read the page size baked into the editor via `--ed-page-*` CSS variables.\n // The Editor component sets these on its root from the current PageSettings\n // (`packages/react/src/Editor.tsx`). Falls back to A4 if we can't read them.\n const cs = root.ownerDocument?.defaultView?.getComputedStyle(root);\n const pageSize = options.pageSize ?? cssPageSizeFromRoot(cs);\n\n const styles = collectStyles();\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n // The `@page { size }` and page-break rules live inside `@media print` so\n // they merge cleanly with any host-document print stylesheet that already\n // declares its own `@page` (e.g. `apps/playground/src/styles.css`). Putting\n // ours after the cloned `<style>`s gives our override last-write-wins.\n return [\n \"<!doctype html>\",\n `<html><head><meta charset=\"utf-8\"><meta name=\"ed-print-snapshot\" content=\"1\"><title>${title}</title>`,\n styles,\n `<style>\n html, body { margin: 0; padding: 0; background: white; }\n @media print {\n @page { size: ${pageSize.width} ${pageSize.height}; margin: 0; }\n .ed-page { box-shadow: none !important; border: none !important; border-radius: 0 !important; margin: 0 !important; page-break-after: always; break-after: page; }\n .ed-page:last-child { page-break-after: auto; break-after: auto; }\n .ed-image-overlay { display: none !important; }\n }\n ${extra}\n </style>`,\n \"</head><body>\",\n clone.outerHTML,\n \"</body></html>\",\n ].join(\"\");\n}\n\n/**\n * Snapshot a live editor root element (the `.ed-root` paginated DOM) and open\n * the browser's print dialog. Preserves the in-editor pagination decisions\n * verbatim — no re-layout in the print frame.\n *\n * For the \"send the snapshot to a server\" use case, use\n * `serializePaginatedHtml` directly and POST the returned string.\n */\nexport async function exportPdfFromElement(\n root: HTMLElement,\n options: ExportPdfFromElementOptions = {},\n): Promise<void> {\n const html = serializePaginatedHtml(root, options);\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\n// ---------- internals ----------\n\nasync function printHtmlInIframe(html: string, _filename: string): Promise<void> {\n const iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"aria-hidden\", \"true\");\n iframe.style.cssText =\n \"position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;\";\n document.body.appendChild(iframe);\n\n const win = iframe.contentWindow;\n const docu = iframe.contentDocument ?? win?.document;\n if (!win || !docu) {\n iframe.remove();\n throw new Error(\"export-pdf: failed to access iframe document\");\n }\n\n docu.open();\n docu.write(html);\n docu.close();\n\n // Wait for the iframe document to finish loading (DOM, stylesheets, images).\n await new Promise<void>((resolve) => {\n if (docu.readyState === \"complete\") resolve();\n else iframe.addEventListener(\"load\", () => resolve(), { once: true });\n });\n // Best-effort wait for embedded images: print dialogs that snapshot too early\n // miss late-loading data URIs (rare, but real).\n await waitForImages(docu);\n // CRITICAL: wait for @font-face fonts to finish loading. The `load` event does\n // NOT wait for web fonts, so printing too early triggers FOIT (Flash of\n // Invisible Text): the browser hides every glyph until its font loads, while\n // text-decoration underlines still paint. Symptom seen in the wild: the\n // letterhead + field underlines printed but ALL text was missing. `fonts.ready`\n // resolves once all used fonts are loaded; cap the wait so a font that never\n // resolves can't hang the print.\n await waitForFonts(docu);\n\n await new Promise<void>((resolve) => {\n const cleanup = () => {\n win.removeEventListener(\"afterprint\", cleanup);\n // Defer removal one tick so Safari's print queue doesn't choke.\n setTimeout(() => iframe.remove(), 0);\n resolve();\n };\n win.addEventListener(\"afterprint\", cleanup);\n win.focus();\n win.print();\n // Fallback in case afterprint never fires (older browsers).\n setTimeout(() => {\n if (iframe.isConnected) cleanup();\n }, 60_000);\n });\n}\n\nfunction collectStyles(): string {\n const parts: string[] = [];\n for (const sheet of Array.from(document.styleSheets)) {\n try {\n const rules = sheet.cssRules;\n if (!rules) continue;\n const css = Array.from(rules)\n .map((r) => r.cssText)\n .join(\"\\n\");\n if (css) parts.push(`<style>${css}</style>`);\n } catch {\n // Cross-origin sheet — fall back to linking it.\n const href = sheet.href;\n if (href) parts.push(`<link rel=\"stylesheet\" href=\"${escapeAttr(href)}\">`);\n }\n }\n return parts.join(\"\\n\");\n}\n\nasync function waitForImages(docu: Document): Promise<void> {\n const imgs = Array.from(docu.images);\n await Promise.all(\n imgs.map(\n (img) =>\n new Promise<void>((resolve) => {\n if (img.complete) return resolve();\n img.addEventListener(\"load\", () => resolve(), { once: true });\n img.addEventListener(\"error\", () => resolve(), { once: true });\n }),\n ),\n );\n}\n\n/**\n * Wait for the iframe document's web fonts (`@font-face`) to finish loading,\n * capped so a font that never resolves can't hang the print. Without this the\n * print can fire mid-font-load and render invisible text (FOIT).\n */\nasync function waitForFonts(docu: Document): Promise<void> {\n const fonts = (docu as Document & { fonts?: FontFaceSet }).fonts;\n if (!fonts?.ready) return;\n await Promise.race([\n fonts.ready.then(() => undefined),\n new Promise<void>((resolve) => {\n setTimeout(resolve, 3000);\n }),\n ]);\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\nfunction escapeAttr(s: string): string {\n return escapeHtml(s);\n}\n","/**\n * Trigger a browser download for an in-memory blob/string. Tiny utility — kept\n * in this package because PDF/HTML/JSON exporters all want it.\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.rel = \"noopener\";\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n setTimeout(() => {\n a.remove();\n URL.revokeObjectURL(url);\n }, 0);\n}\n\nexport function downloadString(\n text: string,\n filename: string,\n mimeType = \"text/plain;charset=utf-8\",\n): void {\n downloadBlob(new Blob([text], { type: mimeType }), filename);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcA,kBAAiE;AAEjE,SAAS,UAAU,KAAwE;AACzF,aAAO,wCAA2B,GAAG,IAAI,EAAE,QAAQ,IAAI,IAAI;AAC7D;AAoBA,IAAM,eAAe;A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Ac,GAAG;AACpC,IAAE,OAAO;AACT,IAAE,WAAW;AACb,IAAE,MAAM;AACR,IAAE,MAAM,UAAU;AAClB,WAAS,KAAK,YAAY,CAAC;AAC3B,IAAE,MAAM;AACR,aAAW,MAAM;AACf,MAAE,OAAO;AACT,QAAI,gBAAgB,GAAG;AAAA,EACzB,GAAG,CAAC;AACN;AAEO,SAAS,eACd,MACA,UACA,WAAW,4BACL;AACN,eAAa,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,SAAS,CAAC,GAAG,QAAQ;AAC7D;","names":["escapeHtml","escapeAttr","HTML_ESCAPES"]}
package/dist/index.js CHANGED
@@ -373,6 +373,7 @@ function serializePaginatedHtml(root, options = {}) {
373
373
  el.removeAttribute("contenteditable");
374
374
  });
375
375
  clone.querySelectorAll(".ed-image-overlay").forEach((el) => el.remove());
376
+ clone.querySelectorAll(".ed-remote-cursors").forEach((el) => el.remove());
376
377
  const cs = root.ownerDocument?.defaultView?.getComputedStyle(root);
377
378
  const pageSize = options.pageSize ?? cssPageSizeFromRoot(cs);
378
379
  const styles = collectStyles();
@@ -380,7 +381,7 @@ function serializePaginatedHtml(root, options = {}) {
380
381
  const extra = options.extraCss ?? "";
381
382
  return [
382
383
  "<!doctype html>",
383
- `<html><head><meta charset="utf-8"><title>${title}</title>`,
384
+ `<html><head><meta charset="utf-8"><meta name="ed-print-snapshot" content="1"><title>${title}</title>`,
384
385
  styles,
385
386
  `<style>
386
387
  html, body { margin: 0; padding: 0; background: white; }
@@ -420,6 +421,7 @@ async function printHtmlInIframe(html, _filename) {
420
421
  else iframe.addEventListener("load", () => resolve(), { once: true });
421
422
  });
422
423
  await waitForImages(docu);
424
+ await waitForFonts(docu);
423
425
  await new Promise((resolve) => {
424
426
  const cleanup = () => {
425
427
  win.removeEventListener("afterprint", cleanup);
@@ -461,6 +463,16 @@ async function waitForImages(docu) {
461
463
  )
462
464
  );
463
465
  }
466
+ async function waitForFonts(docu) {
467
+ const fonts = docu.fonts;
468
+ if (!fonts?.ready) return;
469
+ await Promise.race([
470
+ fonts.ready.then(() => void 0),
471
+ new Promise((resolve) => {
472
+ setTimeout(resolve, 3e3);
473
+ })
474
+ ]);
475
+ }
464
476
  var HTML_ESCAPES2 = {
465
477
  "&": "&amp;",
466
478
  "<": "&lt;",
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/html.ts","../src/pdf.ts","../src/download.ts"],"sourcesContent":["import type {\n AlignValue,\n BlockAttrs,\n DeltaOp,\n DirValue,\n ImageEmbed,\n LegacySerializedDocument,\n ListKind,\n MarkAttrs,\n PageSettings,\n SerializedBlock,\n SerializedCell,\n SerializedDocument,\n} from \"@sofereditor/core\";\nimport { isImageEmbed, isLegacySerializedDocument, pxToMm } from \"@sofereditor/core\";\n\nfunction normalize(doc: SerializedDocument | LegacySerializedDocument): SerializedDocument {\n return isLegacySerializedDocument(doc) ? { blocks: doc } : doc;\n}\n\nexport interface DocumentToHtmlOptions {\n /** Document title (set on `<title>` and used as the file name hint). Default \"Documento\". */\n title?: string;\n /** When true (default) emits a full `<html>` document. When false emits only the body fragment. */\n standalone?: boolean;\n /** Extra CSS appended after the default print stylesheet. Only honored when `standalone`. */\n extraCss?: string;\n /** Page geometry hints injected into `@page`. Defaults to A4. */\n page?: {\n width: string;\n height: string;\n marginTop: string;\n marginBottom: string;\n marginLeft: string;\n marginRight: string;\n };\n}\n\nconst DEFAULT_PAGE = {\n width: \"210mm\",\n height: \"297mm\",\n marginTop: \"25mm\",\n marginBottom: \"25mm\",\n marginLeft: \"25mm\",\n marginRight: \"25mm\",\n};\n\n/**\n * Serialize a `SerializedDocument` to standalone HTML.\n *\n * Output structure mirrors what `@sofereditor/react` paints at runtime: each\n * top-level block becomes one element (`<p>`, `<h1..6>`, `<blockquote>`, `<pre>`,\n * `<table>`), consecutive `listItem` blocks are reconstructed into nested\n * `<ul>`/`<ol>` trees, and image embeds are emitted as `<img>` tags carrying the\n * embed's data URL (so the export is self-contained).\n *\n * NOT a fragment of the live editor DOM — this walks the model so the output is\n * editor-state agnostic (no caret artifacts, no zero-width phantom anchors).\n */\nexport function documentToHtml(\n doc: SerializedDocument | LegacySerializedDocument,\n options: DocumentToHtmlOptions = {},\n): string {\n const normalized = normalize(doc);\n const body = documentToHtmlFragment(normalized);\n if (options.standalone === false) return body;\n const page = options.page ?? pageFromSettings(normalized.pageSettings);\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n return [\n \"<!doctype html>\",\n `<html lang=\"pt-BR\"><head><meta charset=\"utf-8\"><title>${title}</title>`,\n `<style>${baseStylesheet(page)}${extra}</style>`,\n \"</head><body>\",\n body,\n \"</body></html>\",\n ].join(\"\");\n}\n\nfunction pageFromSettings(s: PageSettings | undefined): NonNullable<DocumentToHtmlOptions[\"page\"]> {\n if (!s) return DEFAULT_PAGE;\n const fmt = (px: number) => `${pxToMm(px).toFixed(2)}mm`;\n return {\n width: fmt(s.width),\n height: fmt(s.height),\n marginTop: fmt(s.marginTop),\n marginBottom: fmt(s.marginBottom),\n marginLeft: fmt(s.marginLeft),\n marginRight: fmt(s.marginRight),\n };\n}\n\n/** Body-only HTML for embedding in other documents. */\nexport function documentToHtmlFragment(\n doc: SerializedDocument | LegacySerializedDocument,\n): string {\n const blocks = normalize(doc).blocks;\n const out: string[] = [];\n let i = 0;\n while (i < blocks.length) {\n const block = blocks[i];\n if (block.type === \"listItem\") {\n const groupStart = i;\n const kind: ListKind = block.attrs.listKind === \"ordered\" ? \"ordered\" : \"bullet\";\n const items: SerializedBlock[] = [];\n while (\n i < blocks.length &&\n blocks[i].type === \"listItem\" &&\n (blocks[i].attrs.listKind ?? \"bullet\") === kind\n ) {\n items.push(blocks[i]);\n i++;\n }\n out.push(renderListGroup(items, kind, groupStart));\n continue;\n }\n out.push(renderBlock(block, i));\n i++;\n }\n return out.join(\"\");\n}\n\n/** JSON export — a stable serialization for save/load round-trips. */\nexport function documentToJson(\n doc: SerializedDocument | LegacySerializedDocument,\n pretty = true,\n): string {\n return JSON.stringify(normalize(doc), null, pretty ? 2 : 0);\n}\n\n// ---------- blocks ----------\n\nfunction renderBlock(block: SerializedBlock, index: number): string {\n switch (block.type) {\n case \"paragraph\":\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n case \"heading\": {\n const level = clampHeadingLevel(block.attrs.level);\n return `<h${level}${blockAttrs(`ed-heading ed-heading-${level}`, block.attrs)}>${renderInline(\n block.delta,\n )}</h${level}>`;\n }\n case \"blockquote\":\n return `<blockquote${blockAttrs(\"ed-blockquote\", block.attrs)}>${renderInline(\n block.delta,\n )}</blockquote>`;\n case \"codeBlock\": {\n const lang = block.attrs.language;\n const codeAttrs = lang ? ` class=\"language-${escapeAttr(lang)}\"` : \"\";\n return `<pre${blockAttrs(\"ed-codeblock\", block.attrs)}><code${codeAttrs}>${renderInline(\n block.delta,\n )}</code></pre>`;\n }\n case \"table\":\n return renderTable(block);\n default:\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n }\n}\n\nfunction renderListGroup(items: SerializedBlock[], kind: ListKind, key: number): string {\n // Tree-build using listLevel just like Editor.buildListTree.\n interface Node { item: SerializedBlock; children: Node[]; }\n const roots: Node[] = [];\n const stack: { children: Node[]; level: number }[] = [{ children: roots, level: -1 }];\n for (const it of items) {\n const level = clampListLevel(it.attrs.listLevel);\n while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();\n const node: Node = { item: it, children: [] };\n stack[stack.length - 1].children.push(node);\n stack.push({ children: node.children, level });\n }\n return renderListTree(roots, kind, `list-${key}`);\n}\n\nfunction renderListTree(nodes: { item: SerializedBlock; children: any[] }[], kind: ListKind, _key: string): string {\n const Tag = kind === \"ordered\" ? \"ol\" : \"ul\";\n const cls = `ed-list ed-list-${kind}`;\n const items = nodes\n .map((n) => {\n const inner = renderInline(n.item.delta);\n const nested =\n n.children.length > 0 ? renderListTree(n.children, kind, _key + \"n\") : \"\";\n return `<li${blockAttrs(\"ed-listitem\", n.item.attrs)}>${inner}${nested}</li>`;\n })\n .join(\"\");\n return `<${Tag} class=\"${cls}\" data-list-kind=\"${kind}\">${items}</${Tag}>`;\n}\n\nfunction renderTable(block: SerializedBlock): string {\n const rows = typeof block.attrs.rows === \"number\" ? block.attrs.rows : 0;\n const cols = typeof block.attrs.cols === \"number\" ? block.attrs.cols : 0;\n const cells = block.cells ?? [];\n if (rows <= 0 || cols <= 0) return \"\";\n\n const colGroup = renderColGroup(block.attrs.colWidths, cols);\n const trs: string[] = [];\n for (let r = 0; r < rows; r++) {\n const tds: string[] = [];\n for (let c = 0; c < cols; c++) {\n const cell = cells[r * cols + c];\n if (!cell) {\n tds.push(\"<td class=\\\"ed-cell\\\"></td>\");\n continue;\n }\n if (cell.attrs?.covered) continue;\n tds.push(renderCell(cell));\n }\n trs.push(`<tr>${tds.join(\"\")}</tr>`);\n }\n return `<div class=\"ed-table-wrap\"><table class=\"ed-table\">${colGroup}<tbody>${trs.join(\"\")}</tbody></table></div>`;\n}\n\nfunction renderColGroup(widths: number[] | undefined, cols: number): string {\n if (!widths || widths.length === 0) return \"\";\n const cells: string[] = [];\n for (let i = 0; i < cols; i++) {\n const w = widths[i];\n cells.push(typeof w === \"number\" ? `<col style=\"width:${w}px\">` : \"<col>\");\n }\n return `<colgroup>${cells.join(\"\")}</colgroup>`;\n}\n\nfunction renderCell(cell: SerializedCell): string {\n const rs = cell.attrs?.rowspan && cell.attrs.rowspan > 1\n ? ` rowspan=\"${cell.attrs.rowspan}\"`\n : \"\";\n const cs = cell.attrs?.colspan && cell.attrs.colspan > 1\n ? ` colspan=\"${cell.attrs.colspan}\"`\n : \"\";\n return `<td class=\"ed-cell\"${rs}${cs}>${renderInline(cell.delta)}</td>`;\n}\n\n// ---------- inline ----------\n\nfunction renderInline(delta: DeltaOp[]): string {\n if (delta.length === 0) return \"<br>\";\n const parts: string[] = [];\n // Floating wrap-left/wrap-right embeds are emitted FIRST so CSS float wraps\n // the following inline text — mirrors the in-editor renderer.\n const wraps: string[] = [];\n for (const op of delta) {\n if (typeof op.insert === \"string\") {\n if (op.insert.length === 0) continue;\n parts.push(applyMarks(escapeHtml(op.insert), op.attributes));\n } else if (isImageEmbed(op.insert)) {\n const layout = op.insert.layout ?? \"inline\";\n if (layout === \"wrap-left\" || layout === \"wrap-right\") {\n wraps.push(renderImg(op.insert));\n } else {\n parts.push(renderImg(op.insert));\n }\n }\n }\n if (wraps.length === 0 && parts.length === 0) return \"<br>\";\n return wraps.join(\"\") + parts.join(\"\");\n}\n\nfunction applyMarks(text: string, attrs: MarkAttrs | undefined): string {\n if (!attrs) return text;\n let html = text;\n if (attrs.bold) html = `<strong>${html}</strong>`;\n if (attrs.italic) html = `<em>${html}</em>`;\n if (attrs.underline) html = `<u>${html}</u>`;\n if (attrs.strike) html = `<s>${html}</s>`;\n const styles: string[] = [];\n if (attrs.color) styles.push(`color:${cssValue(attrs.color)}`);\n if (attrs.fontFamily) styles.push(`font-family:${cssValue(attrs.fontFamily)}`);\n if (attrs.fontSize) styles.push(`font-size:${cssValue(attrs.fontSize)}`);\n if (styles.length > 0) html = `<span style=\"${styles.join(\";\")}\">${html}</span>`;\n if (attrs.link?.href) {\n const t = attrs.link.title ? ` title=\"${escapeAttr(attrs.link.title)}\"` : \"\";\n html = `<a href=\"${escapeAttr(attrs.link.href)}\"${t} rel=\"noopener noreferrer\" target=\"_blank\">${html}</a>`;\n }\n if (attrs.comment?.markId) {\n html = `<span data-comment-id=\"${escapeAttr(attrs.comment.markId)}\">${html}</span>`;\n }\n return html;\n}\n\nfunction renderImg(embed: ImageEmbed): string {\n const layout = embed.layout ?? \"inline\";\n const align = embed.align;\n const ox = embed.offsetX ?? 0;\n const oy = embed.offsetY ?? 0;\n const hasCaption = !!embed.caption && embed.caption.length > 0;\n\n // The wrapper carries the positioning (float/absolute/inline-block/block).\n // The img keeps the intrinsic size when wrapped; when there's no caption we\n // keep the historical bare `<img>` output for unchanged DOM/CSS.\n const wrapperStyles: string[] = [];\n switch (layout) {\n case \"wrap-left\":\n wrapperStyles.push(\n \"float:left\",\n `width:${embed.width}px`,\n `margin-right:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"wrap-right\":\n wrapperStyles.push(\n \"float:right\",\n `width:${embed.width}px`,\n `margin-left:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"behind\":\n case \"front\":\n wrapperStyles.push(\n \"position:absolute\",\n `left:${ox}px`,\n `top:${oy}px`,\n `width:${embed.width}px`,\n `z-index:${layout === \"behind\" ? -1 : 2}`,\n );\n break;\n case \"inline\":\n default:\n if (align) {\n wrapperStyles.push(\n \"display:block\",\n `width:${embed.width}px`,\n `margin-left:${align === \"left\" ? \"0\" : \"auto\"}`,\n `margin-right:${align === \"right\" ? \"0\" : \"auto\"}`,\n );\n } else {\n wrapperStyles.push(\n \"display:inline-block\",\n \"vertical-align:text-bottom\",\n `width:${embed.width}px`,\n );\n }\n break;\n }\n\n const imgStyles: string[] = hasCaption\n ? [`width:${embed.width}px`, `height:${embed.height}px`, \"display:block\"]\n : wrapperStyles.concat(\n // Preserve old height when emitting bare <img>.\n `height:${embed.height}px`,\n );\n\n const imgHtml = `<img src=\"${escapeAttr(embed.src)}\" width=\"${embed.width}\" height=\"${embed.height}\" alt=\"${escapeAttr(embed.caption ?? \"\")}\" data-embed=\"image\" data-embed-layout=\"${layout}\"${\n align ? ` data-embed-align=\"${escapeAttr(align)}\"` : \"\"\n } style=\"${imgStyles.join(\";\")}\">`;\n\n if (!hasCaption) return imgHtml;\n\n const captionAlign = embed.captionAlign ?? \"center\";\n return `<figure class=\"ed-figure\" data-embed-figure=\"true\" data-embed-layout=\"${layout}\" style=\"${wrapperStyles.join(\";\")}\">${imgHtml}<figcaption class=\"ed-figcaption\" data-caption-align=\"${captionAlign}\" style=\"text-align:${captionAlign}\">${escapeHtml(\n embed.caption!,\n )}</figcaption></figure>`;\n}\n\n// ---------- helpers ----------\n\nfunction blockAttrs(baseClass: string, attrs: BlockAttrs): string {\n const classes = [baseClass, \"ed-block\"];\n const align = clampAlign(attrs.align);\n if (align) classes.push(`ed-align-${align}`);\n const dir = clampDir(attrs.dir);\n const dirAttr = dir ? ` dir=\"${dir}\"` : \"\";\n return ` class=\"${classes.join(\" \")}\"${dirAttr}`;\n}\n\nfunction clampHeadingLevel(l: unknown): 1 | 2 | 3 | 4 | 5 | 6 {\n if (typeof l !== \"number\") return 1;\n const n = Math.trunc(l);\n if (n < 1) return 1;\n if (n > 6) return 6;\n return n as 1 | 2 | 3 | 4 | 5 | 6;\n}\n\nfunction clampListLevel(l: unknown): number {\n if (typeof l !== \"number\" || !Number.isFinite(l)) return 0;\n return Math.max(0, Math.min(5, Math.trunc(l)));\n}\n\nfunction clampAlign(a: unknown): AlignValue | undefined {\n if (a === \"left\" || a === \"center\" || a === \"right\" || a === \"justify\") return a;\n return undefined;\n}\n\nfunction clampDir(d: unknown): DirValue | undefined {\n if (d === \"ltr\" || d === \"rtl\") return d;\n return undefined;\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\nfunction escapeAttr(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\n/** Allow only safe characters in CSS values — defense in depth against injected `</style>`. */\nfunction cssValue(v: string): string {\n return v.replace(/[<>\"';\\\\]/g, \"\");\n}\n\nfunction baseStylesheet(page: NonNullable<DocumentToHtmlOptions[\"page\"]>): string {\n // Margins are owned by `@page` only. Chromium honors that block both for\n // `window.print()` (client-side `exportPdfFromDocument`) and for\n // `page.pdf({ preferCSSPageSize: true })` (server-side `renderPdf` in\n // `@sofereditor/export-pdf-server`). Adding the same offsets via `body { padding }`\n // would compound and double the margin in the output PDF.\n return `\n@page {\n size: ${page.width} ${page.height};\n margin: ${page.marginTop} ${page.marginRight} ${page.marginBottom} ${page.marginLeft};\n}\nhtml, body { margin: 0; padding: 0; background: white; color: #1a1a1f; }\nbody {\n font-family: \"Arial\", \"Helvetica\", sans-serif;\n font-size: 11pt;\n line-height: 1.5;\n}\n.ed-paragraph { margin: 0 0 0.5em; min-height: 1.5em; }\n.ed-heading { margin: 0.5em 0 0.25em; font-weight: 600; line-height: 1.25; }\n.ed-heading-1 { font-size: 28pt; }\n.ed-heading-2 { font-size: 22pt; }\n.ed-heading-3 { font-size: 18pt; }\n.ed-heading-4 { font-size: 14pt; }\n.ed-heading-5 { font-size: 12pt; }\n.ed-heading-6 { font-size: 11pt; color: #6b7280; }\n.ed-blockquote {\n margin: 0 0 0.5em; padding: 0.25em 12px;\n border-inline-start: 3px solid #e5e7eb; color: #6b7280;\n}\n.ed-codeblock {\n margin: 0 0 0.5em; background: #0f172a; color: #e2e8f0;\n padding: 12px 14px; border-radius: 6px;\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11pt; white-space: pre-wrap;\n}\n.ed-codeblock code { font-family: inherit; background: transparent; color: inherit; }\n.ed-block[dir=\"rtl\"] { text-align: start; }\n.ed-align-left { text-align: left; }\n.ed-align-center { text-align: center; }\n.ed-align-right { text-align: right; }\n.ed-align-justify { text-align: justify; }\n.ed-list { margin: 0 0 0.5em; padding-inline-start: 28px; }\n.ed-list .ed-list { margin-block: 0; }\n.ed-list-bullet { list-style-type: disc; }\n.ed-list-bullet .ed-list-bullet { list-style-type: circle; }\n.ed-list-bullet .ed-list-bullet .ed-list-bullet { list-style-type: square; }\n.ed-list-ordered { list-style-type: decimal; }\n.ed-list-ordered .ed-list-ordered { list-style-type: lower-alpha; }\n.ed-list-ordered .ed-list-ordered .ed-list-ordered { list-style-type: lower-roman; }\n.ed-listitem { margin: 0; min-height: 1.5em; }\n.ed-table-wrap { margin: 0 0 0.5em; position: relative; }\n.ed-table { width: 100%; border-collapse: collapse; table-layout: fixed; }\n.ed-cell {\n border: 1px solid #cbd5e1; padding: 6px 8px;\n vertical-align: top; word-break: break-word; white-space: pre-wrap;\n}\nimg[data-embed=\"image\"] { max-width: 100%; }\n.ed-block { position: relative; isolation: isolate; }\na { color: #2563eb; }\n`;\n}\n","import type { LegacySerializedDocument, SerializedDocument } from \"@sofereditor/core\";\nimport { documentToHtml, type DocumentToHtmlOptions } from \"./html\";\n\nexport interface ExportPdfFromDocumentOptions extends DocumentToHtmlOptions {\n /** Suggested file name (used by the OS save dialog as the default). */\n filename?: string;\n}\n\n/**\n * Open the browser's print dialog for a `SerializedDocument`.\n *\n * Strategy: render the document to standalone HTML in a hidden iframe and call\n * `iframe.contentWindow.print()`. The user picks \"Save as PDF\" (or any printer)\n * from the native dialog. No external PDF library required.\n *\n * The returned promise resolves after the print dialog closes (`afterprint`).\n */\nexport async function exportPdfFromDocument(\n doc: SerializedDocument | LegacySerializedDocument,\n options: ExportPdfFromDocumentOptions = {},\n): Promise<void> {\n const html = documentToHtml(doc, { ...options, standalone: true });\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\nexport interface SerializePaginatedHtmlOptions {\n /** Document title (becomes `<title>` and is used as default filename). */\n title?: string;\n /** Extra CSS appended to the cloned styles (e.g. for headers/footers). */\n extraCss?: string;\n /**\n * Override the `@page { size }`. Default reads `--ed-page-width` /\n * `--ed-page-height` CSS variables off the root (set by `<Editor>` from the\n * current `PageSettings`); falls back to A4 if absent.\n */\n pageSize?: { width: string; height: string };\n}\n\nexport interface ExportPdfFromElementOptions extends SerializePaginatedHtmlOptions {\n /** Suggested file name. */\n filename?: string;\n}\n\nfunction cssPageSizeFromRoot(\n cs: CSSStyleDeclaration | undefined,\n): { width: string; height: string } {\n if (!cs) return { width: \"210mm\", height: \"297mm\" };\n const w = cs.getPropertyValue(\"--ed-page-width\").trim();\n const h = cs.getPropertyValue(\"--ed-page-height\").trim();\n if (!w || !h) return { width: \"210mm\", height: \"297mm\" };\n // CSS vars come back as e.g. \"794px\". `@page` accepts px directly.\n return { width: w, height: h };\n}\n\n/**\n * Serialize a live editor root (the `.ed-root` paginated DOM) into a\n * self-contained HTML string. The output preserves the in-editor pagination\n * decisions verbatim — each `.ed-page` becomes a fixed-size page in the final\n * print medium with no re-layout possible.\n *\n * The returned HTML inlines every accessible stylesheet from the host document\n * (or links it as a fallback for cross-origin sheets) so the layout survives\n * transplant to an iframe, a saved file, or a headless renderer.\n *\n * This is the building block for two paths:\n * - `exportPdfFromElement` (this file): writes the HTML into a hidden iframe\n * and calls `window.print()` for the local \"Save as PDF\" flow.\n * - Upload-to-server snapshots: POST the string to a backend that converts it\n * to PDF via Puppeteer's `setContent + page.pdf()` without re-running the\n * pagination engine.\n */\nexport function serializePaginatedHtml(\n root: HTMLElement,\n options: SerializePaginatedHtmlOptions = {},\n): string {\n const clone = root.cloneNode(true) as HTMLElement;\n // Strip interactive scaffolding that print styles can't see ahead of time.\n clone.querySelectorAll(\"[contenteditable]\").forEach((el) => {\n (el as HTMLElement).removeAttribute(\"contenteditable\");\n });\n clone.querySelectorAll(\".ed-image-overlay\").forEach((el) => el.remove());\n\n // Read the page size baked into the editor via `--ed-page-*` CSS variables.\n // The Editor component sets these on its root from the current PageSettings\n // (`packages/react/src/Editor.tsx`). Falls back to A4 if we can't read them.\n const cs = root.ownerDocument?.defaultView?.getComputedStyle(root);\n const pageSize = options.pageSize ?? cssPageSizeFromRoot(cs);\n\n const styles = collectStyles();\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n // The `@page { size }` and page-break rules live inside `@media print` so\n // they merge cleanly with any host-document print stylesheet that already\n // declares its own `@page` (e.g. `apps/playground/src/styles.css`). Putting\n // ours after the cloned `<style>`s gives our override last-write-wins.\n return [\n \"<!doctype html>\",\n `<html><head><meta charset=\"utf-8\"><title>${title}</title>`,\n styles,\n `<style>\n html, body { margin: 0; padding: 0; background: white; }\n @media print {\n @page { size: ${pageSize.width} ${pageSize.height}; margin: 0; }\n .ed-page { box-shadow: none !important; border: none !important; border-radius: 0 !important; margin: 0 !important; page-break-after: always; break-after: page; }\n .ed-page:last-child { page-break-after: auto; break-after: auto; }\n .ed-image-overlay { display: none !important; }\n }\n ${extra}\n </style>`,\n \"</head><body>\",\n clone.outerHTML,\n \"</body></html>\",\n ].join(\"\");\n}\n\n/**\n * Snapshot a live editor root element (the `.ed-root` paginated DOM) and open\n * the browser's print dialog. Preserves the in-editor pagination decisions\n * verbatim — no re-layout in the print frame.\n *\n * For the \"send the snapshot to a server\" use case, use\n * `serializePaginatedHtml` directly and POST the returned string.\n */\nexport async function exportPdfFromElement(\n root: HTMLElement,\n options: ExportPdfFromElementOptions = {},\n): Promise<void> {\n const html = serializePaginatedHtml(root, options);\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\n// ---------- internals ----------\n\nasync function printHtmlInIframe(html: string, _filename: string): Promise<void> {\n const iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"aria-hidden\", \"true\");\n iframe.style.cssText =\n \"position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;\";\n document.body.appendChild(iframe);\n\n const win = iframe.contentWindow;\n const docu = iframe.contentDocument ?? win?.document;\n if (!win || !docu) {\n iframe.remove();\n throw new Error(\"export-pdf: failed to access iframe document\");\n }\n\n docu.open();\n docu.write(html);\n docu.close();\n\n // Wait for the iframe to finish loading (images, fonts).\n await new Promise<void>((resolve) => {\n if (docu.readyState === \"complete\") resolve();\n else iframe.addEventListener(\"load\", () => resolve(), { once: true });\n });\n // Best-effort wait for embedded images: print dialogs that snapshot too early\n // miss late-loading data URIs (rare, but real).\n await waitForImages(docu);\n\n await new Promise<void>((resolve) => {\n const cleanup = () => {\n win.removeEventListener(\"afterprint\", cleanup);\n // Defer removal one tick so Safari's print queue doesn't choke.\n setTimeout(() => iframe.remove(), 0);\n resolve();\n };\n win.addEventListener(\"afterprint\", cleanup);\n win.focus();\n win.print();\n // Fallback in case afterprint never fires (older browsers).\n setTimeout(() => {\n if (iframe.isConnected) cleanup();\n }, 60_000);\n });\n}\n\nfunction collectStyles(): string {\n const parts: string[] = [];\n for (const sheet of Array.from(document.styleSheets)) {\n try {\n const rules = sheet.cssRules;\n if (!rules) continue;\n const css = Array.from(rules)\n .map((r) => r.cssText)\n .join(\"\\n\");\n if (css) parts.push(`<style>${css}</style>`);\n } catch {\n // Cross-origin sheet — fall back to linking it.\n const href = sheet.href;\n if (href) parts.push(`<link rel=\"stylesheet\" href=\"${escapeAttr(href)}\">`);\n }\n }\n return parts.join(\"\\n\");\n}\n\nasync function waitForImages(docu: Document): Promise<void> {\n const imgs = Array.from(docu.images);\n await Promise.all(\n imgs.map(\n (img) =>\n new Promise<void>((resolve) => {\n if (img.complete) return resolve();\n img.addEventListener(\"load\", () => resolve(), { once: true });\n img.addEventListener(\"error\", () => resolve(), { once: true });\n }),\n ),\n );\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\nfunction escapeAttr(s: string): string {\n return escapeHtml(s);\n}\n","/**\n * Trigger a browser download for an in-memory blob/string. Tiny utility — kept\n * in this package because PDF/HTML/JSON exporters all want it.\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.rel = \"noopener\";\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n setTimeout(() => {\n a.remove();\n URL.revokeObjectURL(url);\n }, 0);\n}\n\nexport function downloadString(\n text: string,\n filename: string,\n mimeType = \"text/plain;charset=utf-8\",\n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AE,OAAO;AACT,QAAI,gBAAgB,GAAG;AAAA,EACzB,GAAG,CAAC;AACN;AAEO,SAAS,eACd,MACA,UACA,WAAW,4BACL;AACN,eAAa,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,SAAS,CAAC,GAAG,QAAQ;AAC7D;","names":["escapeHtml","escapeAttr","HTML_ESCAPES"]}
1
+ {"version":3,"sources":["../src/html.ts","../src/pdf.ts","../src/download.ts"],"sourcesContent":["import type {\n AlignValue,\n BlockAttrs,\n DeltaOp,\n DirValue,\n ImageEmbed,\n LegacySerializedDocument,\n ListKind,\n MarkAttrs,\n PageSettings,\n SerializedBlock,\n SerializedCell,\n SerializedDocument,\n} from \"@sofereditor/core\";\nimport { isImageEmbed, isLegacySerializedDocument, pxToMm } from \"@sofereditor/core\";\n\nfunction normalize(doc: SerializedDocument | LegacySerializedDocument): SerializedDocument {\n return isLegacySerializedDocument(doc) ? { blocks: doc } : doc;\n}\n\nexport interface DocumentToHtmlOptions {\n /** Document title (set on `<title>` and used as the file name hint). Default \"Documento\". */\n title?: string;\n /** When true (default) emits a full `<html>` document. When false emits only the body fragment. */\n standalone?: boolean;\n /** Extra CSS appended after the default print stylesheet. Only honored when `standalone`. */\n extraCss?: string;\n /** Page geometry hints injected into `@page`. Defaults to A4. */\n page?: {\n width: string;\n height: string;\n marginTop: string;\n marginBottom: string;\n marginLeft: string;\n marginRight: string;\n };\n}\n\nconst DEFAULT_PAGE = {\n width: \"210mm\",\n height: \"297mm\",\n marginTop: \"25mm\",\n marginBottom: \"25mm\",\n marginLeft: \"25mm\",\n marginRight: \"25mm\",\n};\n\n/**\n * Serialize a `SerializedDocument` to standalone HTML.\n *\n * Output structure mirrors what `@sofereditor/react` paints at runtime: each\n * top-level block becomes one element (`<p>`, `<h1..6>`, `<blockquote>`, `<pre>`,\n * `<table>`), consecutive `listItem` blocks are reconstructed into nested\n * `<ul>`/`<ol>` trees, and image embeds are emitted as `<img>` tags carrying the\n * embed's data URL (so the export is self-contained).\n *\n * NOT a fragment of the live editor DOM — this walks the model so the output is\n * editor-state agnostic (no caret artifacts, no zero-width phantom anchors).\n */\nexport function documentToHtml(\n doc: SerializedDocument | LegacySerializedDocument,\n options: DocumentToHtmlOptions = {},\n): string {\n const normalized = normalize(doc);\n const body = documentToHtmlFragment(normalized);\n if (options.standalone === false) return body;\n const page = options.page ?? pageFromSettings(normalized.pageSettings);\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n return [\n \"<!doctype html>\",\n `<html lang=\"pt-BR\"><head><meta charset=\"utf-8\"><title>${title}</title>`,\n `<style>${baseStylesheet(page)}${extra}</style>`,\n \"</head><body>\",\n body,\n \"</body></html>\",\n ].join(\"\");\n}\n\nfunction pageFromSettings(s: PageSettings | undefined): NonNullable<DocumentToHtmlOptions[\"page\"]> {\n if (!s) return DEFAULT_PAGE;\n const fmt = (px: number) => `${pxToMm(px).toFixed(2)}mm`;\n return {\n width: fmt(s.width),\n height: fmt(s.height),\n marginTop: fmt(s.marginTop),\n marginBottom: fmt(s.marginBottom),\n marginLeft: fmt(s.marginLeft),\n marginRight: fmt(s.marginRight),\n };\n}\n\n/** Body-only HTML for embedding in other documents. */\nexport function documentToHtmlFragment(\n doc: SerializedDocument | LegacySerializedDocument,\n): string {\n const blocks = normalize(doc).blocks;\n const out: string[] = [];\n let i = 0;\n while (i < blocks.length) {\n const block = blocks[i];\n if (block.type === \"listItem\") {\n const groupStart = i;\n const kind: ListKind = block.attrs.listKind === \"ordered\" ? \"ordered\" : \"bullet\";\n const items: SerializedBlock[] = [];\n while (\n i < blocks.length &&\n blocks[i].type === \"listItem\" &&\n (blocks[i].attrs.listKind ?? \"bullet\") === kind\n ) {\n items.push(blocks[i]);\n i++;\n }\n out.push(renderListGroup(items, kind, groupStart));\n continue;\n }\n out.push(renderBlock(block, i));\n i++;\n }\n return out.join(\"\");\n}\n\n/** JSON export — a stable serialization for save/load round-trips. */\nexport function documentToJson(\n doc: SerializedDocument | LegacySerializedDocument,\n pretty = true,\n): string {\n return JSON.stringify(normalize(doc), null, pretty ? 2 : 0);\n}\n\n// ---------- blocks ----------\n\nfunction renderBlock(block: SerializedBlock, index: number): string {\n switch (block.type) {\n case \"paragraph\":\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n case \"heading\": {\n const level = clampHeadingLevel(block.attrs.level);\n return `<h${level}${blockAttrs(`ed-heading ed-heading-${level}`, block.attrs)}>${renderInline(\n block.delta,\n )}</h${level}>`;\n }\n case \"blockquote\":\n return `<blockquote${blockAttrs(\"ed-blockquote\", block.attrs)}>${renderInline(\n block.delta,\n )}</blockquote>`;\n case \"codeBlock\": {\n const lang = block.attrs.language;\n const codeAttrs = lang ? ` class=\"language-${escapeAttr(lang)}\"` : \"\";\n return `<pre${blockAttrs(\"ed-codeblock\", block.attrs)}><code${codeAttrs}>${renderInline(\n block.delta,\n )}</code></pre>`;\n }\n case \"table\":\n return renderTable(block);\n default:\n return `<p${blockAttrs(\"ed-paragraph\", block.attrs)}>${renderInline(block.delta)}</p>`;\n }\n}\n\nfunction renderListGroup(items: SerializedBlock[], kind: ListKind, key: number): string {\n // Tree-build using listLevel just like Editor.buildListTree.\n interface Node { item: SerializedBlock; children: Node[]; }\n const roots: Node[] = [];\n const stack: { children: Node[]; level: number }[] = [{ children: roots, level: -1 }];\n for (const it of items) {\n const level = clampListLevel(it.attrs.listLevel);\n while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();\n const node: Node = { item: it, children: [] };\n stack[stack.length - 1].children.push(node);\n stack.push({ children: node.children, level });\n }\n return renderListTree(roots, kind, `list-${key}`);\n}\n\nfunction renderListTree(nodes: { item: SerializedBlock; children: any[] }[], kind: ListKind, _key: string): string {\n const Tag = kind === \"ordered\" ? \"ol\" : \"ul\";\n const cls = `ed-list ed-list-${kind}`;\n const items = nodes\n .map((n) => {\n const inner = renderInline(n.item.delta);\n const nested =\n n.children.length > 0 ? renderListTree(n.children, kind, _key + \"n\") : \"\";\n return `<li${blockAttrs(\"ed-listitem\", n.item.attrs)}>${inner}${nested}</li>`;\n })\n .join(\"\");\n return `<${Tag} class=\"${cls}\" data-list-kind=\"${kind}\">${items}</${Tag}>`;\n}\n\nfunction renderTable(block: SerializedBlock): string {\n const rows = typeof block.attrs.rows === \"number\" ? block.attrs.rows : 0;\n const cols = typeof block.attrs.cols === \"number\" ? block.attrs.cols : 0;\n const cells = block.cells ?? [];\n if (rows <= 0 || cols <= 0) return \"\";\n\n const colGroup = renderColGroup(block.attrs.colWidths, cols);\n const trs: string[] = [];\n for (let r = 0; r < rows; r++) {\n const tds: string[] = [];\n for (let c = 0; c < cols; c++) {\n const cell = cells[r * cols + c];\n if (!cell) {\n tds.push(\"<td class=\\\"ed-cell\\\"></td>\");\n continue;\n }\n if (cell.attrs?.covered) continue;\n tds.push(renderCell(cell));\n }\n trs.push(`<tr>${tds.join(\"\")}</tr>`);\n }\n return `<div class=\"ed-table-wrap\"><table class=\"ed-table\">${colGroup}<tbody>${trs.join(\"\")}</tbody></table></div>`;\n}\n\nfunction renderColGroup(widths: number[] | undefined, cols: number): string {\n if (!widths || widths.length === 0) return \"\";\n const cells: string[] = [];\n for (let i = 0; i < cols; i++) {\n const w = widths[i];\n cells.push(typeof w === \"number\" ? `<col style=\"width:${w}px\">` : \"<col>\");\n }\n return `<colgroup>${cells.join(\"\")}</colgroup>`;\n}\n\nfunction renderCell(cell: SerializedCell): string {\n const rs = cell.attrs?.rowspan && cell.attrs.rowspan > 1\n ? ` rowspan=\"${cell.attrs.rowspan}\"`\n : \"\";\n const cs = cell.attrs?.colspan && cell.attrs.colspan > 1\n ? ` colspan=\"${cell.attrs.colspan}\"`\n : \"\";\n return `<td class=\"ed-cell\"${rs}${cs}>${renderInline(cell.delta)}</td>`;\n}\n\n// ---------- inline ----------\n\nfunction renderInline(delta: DeltaOp[]): string {\n if (delta.length === 0) return \"<br>\";\n const parts: string[] = [];\n // Floating wrap-left/wrap-right embeds are emitted FIRST so CSS float wraps\n // the following inline text — mirrors the in-editor renderer.\n const wraps: string[] = [];\n for (const op of delta) {\n if (typeof op.insert === \"string\") {\n if (op.insert.length === 0) continue;\n parts.push(applyMarks(escapeHtml(op.insert), op.attributes));\n } else if (isImageEmbed(op.insert)) {\n const layout = op.insert.layout ?? \"inline\";\n if (layout === \"wrap-left\" || layout === \"wrap-right\") {\n wraps.push(renderImg(op.insert));\n } else {\n parts.push(renderImg(op.insert));\n }\n }\n }\n if (wraps.length === 0 && parts.length === 0) return \"<br>\";\n return wraps.join(\"\") + parts.join(\"\");\n}\n\nfunction applyMarks(text: string, attrs: MarkAttrs | undefined): string {\n if (!attrs) return text;\n let html = text;\n if (attrs.bold) html = `<strong>${html}</strong>`;\n if (attrs.italic) html = `<em>${html}</em>`;\n if (attrs.underline) html = `<u>${html}</u>`;\n if (attrs.strike) html = `<s>${html}</s>`;\n const styles: string[] = [];\n if (attrs.color) styles.push(`color:${cssValue(attrs.color)}`);\n if (attrs.fontFamily) styles.push(`font-family:${cssValue(attrs.fontFamily)}`);\n if (attrs.fontSize) styles.push(`font-size:${cssValue(attrs.fontSize)}`);\n if (styles.length > 0) html = `<span style=\"${styles.join(\";\")}\">${html}</span>`;\n if (attrs.link?.href) {\n const t = attrs.link.title ? ` title=\"${escapeAttr(attrs.link.title)}\"` : \"\";\n html = `<a href=\"${escapeAttr(attrs.link.href)}\"${t} rel=\"noopener noreferrer\" target=\"_blank\">${html}</a>`;\n }\n if (attrs.comment?.markId) {\n html = `<span data-comment-id=\"${escapeAttr(attrs.comment.markId)}\">${html}</span>`;\n }\n return html;\n}\n\nfunction renderImg(embed: ImageEmbed): string {\n const layout = embed.layout ?? \"inline\";\n const align = embed.align;\n const ox = embed.offsetX ?? 0;\n const oy = embed.offsetY ?? 0;\n const hasCaption = !!embed.caption && embed.caption.length > 0;\n\n // The wrapper carries the positioning (float/absolute/inline-block/block).\n // The img keeps the intrinsic size when wrapped; when there's no caption we\n // keep the historical bare `<img>` output for unchanged DOM/CSS.\n const wrapperStyles: string[] = [];\n switch (layout) {\n case \"wrap-left\":\n wrapperStyles.push(\n \"float:left\",\n `width:${embed.width}px`,\n `margin-right:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"wrap-right\":\n wrapperStyles.push(\n \"float:right\",\n `width:${embed.width}px`,\n `margin-left:${Math.max(8, ox)}px`,\n `margin-top:${Math.max(0, oy)}px`,\n \"margin-bottom:4px\",\n );\n break;\n case \"behind\":\n case \"front\":\n wrapperStyles.push(\n \"position:absolute\",\n `left:${ox}px`,\n `top:${oy}px`,\n `width:${embed.width}px`,\n `z-index:${layout === \"behind\" ? -1 : 2}`,\n );\n break;\n case \"inline\":\n default:\n if (align) {\n wrapperStyles.push(\n \"display:block\",\n `width:${embed.width}px`,\n `margin-left:${align === \"left\" ? \"0\" : \"auto\"}`,\n `margin-right:${align === \"right\" ? \"0\" : \"auto\"}`,\n );\n } else {\n wrapperStyles.push(\n \"display:inline-block\",\n \"vertical-align:text-bottom\",\n `width:${embed.width}px`,\n );\n }\n break;\n }\n\n const imgStyles: string[] = hasCaption\n ? [`width:${embed.width}px`, `height:${embed.height}px`, \"display:block\"]\n : wrapperStyles.concat(\n // Preserve old height when emitting bare <img>.\n `height:${embed.height}px`,\n );\n\n const imgHtml = `<img src=\"${escapeAttr(embed.src)}\" width=\"${embed.width}\" height=\"${embed.height}\" alt=\"${escapeAttr(embed.caption ?? \"\")}\" data-embed=\"image\" data-embed-layout=\"${layout}\"${\n align ? ` data-embed-align=\"${escapeAttr(align)}\"` : \"\"\n } style=\"${imgStyles.join(\";\")}\">`;\n\n if (!hasCaption) return imgHtml;\n\n const captionAlign = embed.captionAlign ?? \"center\";\n return `<figure class=\"ed-figure\" data-embed-figure=\"true\" data-embed-layout=\"${layout}\" style=\"${wrapperStyles.join(\";\")}\">${imgHtml}<figcaption class=\"ed-figcaption\" data-caption-align=\"${captionAlign}\" style=\"text-align:${captionAlign}\">${escapeHtml(\n embed.caption!,\n )}</figcaption></figure>`;\n}\n\n// ---------- helpers ----------\n\nfunction blockAttrs(baseClass: string, attrs: BlockAttrs): string {\n const classes = [baseClass, \"ed-block\"];\n const align = clampAlign(attrs.align);\n if (align) classes.push(`ed-align-${align}`);\n const dir = clampDir(attrs.dir);\n const dirAttr = dir ? ` dir=\"${dir}\"` : \"\";\n return ` class=\"${classes.join(\" \")}\"${dirAttr}`;\n}\n\nfunction clampHeadingLevel(l: unknown): 1 | 2 | 3 | 4 | 5 | 6 {\n if (typeof l !== \"number\") return 1;\n const n = Math.trunc(l);\n if (n < 1) return 1;\n if (n > 6) return 6;\n return n as 1 | 2 | 3 | 4 | 5 | 6;\n}\n\nfunction clampListLevel(l: unknown): number {\n if (typeof l !== \"number\" || !Number.isFinite(l)) return 0;\n return Math.max(0, Math.min(5, Math.trunc(l)));\n}\n\nfunction clampAlign(a: unknown): AlignValue | undefined {\n if (a === \"left\" || a === \"center\" || a === \"right\" || a === \"justify\") return a;\n return undefined;\n}\n\nfunction clampDir(d: unknown): DirValue | undefined {\n if (d === \"ltr\" || d === \"rtl\") return d;\n return undefined;\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\nfunction escapeAttr(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\n\n/** Allow only safe characters in CSS values — defense in depth against injected `</style>`. */\nfunction cssValue(v: string): string {\n return v.replace(/[<>\"';\\\\]/g, \"\");\n}\n\nfunction baseStylesheet(page: NonNullable<DocumentToHtmlOptions[\"page\"]>): string {\n // Margins are owned by `@page` only. Chromium honors that block both for\n // `window.print()` (client-side `exportPdfFromDocument`) and for\n // `page.pdf({ preferCSSPageSize: true })` (server-side `renderPdf` in\n // `@sofereditor/export-pdf-server`). Adding the same offsets via `body { padding }`\n // would compound and double the margin in the output PDF.\n return `\n@page {\n size: ${page.width} ${page.height};\n margin: ${page.marginTop} ${page.marginRight} ${page.marginBottom} ${page.marginLeft};\n}\nhtml, body { margin: 0; padding: 0; background: white; color: #1a1a1f; }\nbody {\n font-family: \"Arial\", \"Helvetica\", sans-serif;\n font-size: 11pt;\n line-height: 1.5;\n}\n.ed-paragraph { margin: 0 0 0.5em; min-height: 1.5em; }\n.ed-heading { margin: 0.5em 0 0.25em; font-weight: 600; line-height: 1.25; }\n.ed-heading-1 { font-size: 28pt; }\n.ed-heading-2 { font-size: 22pt; }\n.ed-heading-3 { font-size: 18pt; }\n.ed-heading-4 { font-size: 14pt; }\n.ed-heading-5 { font-size: 12pt; }\n.ed-heading-6 { font-size: 11pt; color: #6b7280; }\n.ed-blockquote {\n margin: 0 0 0.5em; padding: 0.25em 12px;\n border-inline-start: 3px solid #e5e7eb; color: #6b7280;\n}\n.ed-codeblock {\n margin: 0 0 0.5em; background: #0f172a; color: #e2e8f0;\n padding: 12px 14px; border-radius: 6px;\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11pt; white-space: pre-wrap;\n}\n.ed-codeblock code { font-family: inherit; background: transparent; color: inherit; }\n.ed-block[dir=\"rtl\"] { text-align: start; }\n.ed-align-left { text-align: left; }\n.ed-align-center { text-align: center; }\n.ed-align-right { text-align: right; }\n.ed-align-justify { text-align: justify; }\n.ed-list { margin: 0 0 0.5em; padding-inline-start: 28px; }\n.ed-list .ed-list { margin-block: 0; }\n.ed-list-bullet { list-style-type: disc; }\n.ed-list-bullet .ed-list-bullet { list-style-type: circle; }\n.ed-list-bullet .ed-list-bullet .ed-list-bullet { list-style-type: square; }\n.ed-list-ordered { list-style-type: decimal; }\n.ed-list-ordered .ed-list-ordered { list-style-type: lower-alpha; }\n.ed-list-ordered .ed-list-ordered .ed-list-ordered { list-style-type: lower-roman; }\n.ed-listitem { margin: 0; min-height: 1.5em; }\n.ed-table-wrap { margin: 0 0 0.5em; position: relative; }\n.ed-table { width: 100%; border-collapse: collapse; table-layout: fixed; }\n.ed-cell {\n border: 1px solid #cbd5e1; padding: 6px 8px;\n vertical-align: top; word-break: break-word; white-space: pre-wrap;\n}\nimg[data-embed=\"image\"] { max-width: 100%; }\n.ed-block { position: relative; isolation: isolate; }\na { color: #2563eb; }\n`;\n}\n","import type { LegacySerializedDocument, SerializedDocument } from \"@sofereditor/core\";\nimport { documentToHtml, type DocumentToHtmlOptions } from \"./html\";\n\nexport interface ExportPdfFromDocumentOptions extends DocumentToHtmlOptions {\n /** Suggested file name (used by the OS save dialog as the default). */\n filename?: string;\n}\n\n/**\n * Open the browser's print dialog for a `SerializedDocument`.\n *\n * Strategy: render the document to standalone HTML in a hidden iframe and call\n * `iframe.contentWindow.print()`. The user picks \"Save as PDF\" (or any printer)\n * from the native dialog. No external PDF library required.\n *\n * The returned promise resolves after the print dialog closes (`afterprint`).\n */\nexport async function exportPdfFromDocument(\n doc: SerializedDocument | LegacySerializedDocument,\n options: ExportPdfFromDocumentOptions = {},\n): Promise<void> {\n const html = documentToHtml(doc, { ...options, standalone: true });\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\nexport interface SerializePaginatedHtmlOptions {\n /** Document title (becomes `<title>` and is used as default filename). */\n title?: string;\n /** Extra CSS appended to the cloned styles (e.g. for headers/footers). */\n extraCss?: string;\n /**\n * Override the `@page { size }`. Default reads `--ed-page-width` /\n * `--ed-page-height` CSS variables off the root (set by `<Editor>` from the\n * current `PageSettings`); falls back to A4 if absent.\n */\n pageSize?: { width: string; height: string };\n}\n\nexport interface ExportPdfFromElementOptions extends SerializePaginatedHtmlOptions {\n /** Suggested file name. */\n filename?: string;\n}\n\nfunction cssPageSizeFromRoot(\n cs: CSSStyleDeclaration | undefined,\n): { width: string; height: string } {\n if (!cs) return { width: \"210mm\", height: \"297mm\" };\n const w = cs.getPropertyValue(\"--ed-page-width\").trim();\n const h = cs.getPropertyValue(\"--ed-page-height\").trim();\n if (!w || !h) return { width: \"210mm\", height: \"297mm\" };\n // CSS vars come back as e.g. \"794px\". `@page` accepts px directly.\n return { width: w, height: h };\n}\n\n/**\n * Serialize a live editor root (the `.ed-root` paginated DOM) into a\n * self-contained HTML string. The output preserves the in-editor pagination\n * decisions verbatim — each `.ed-page` becomes a fixed-size page in the final\n * print medium with no re-layout possible.\n *\n * The returned HTML inlines every accessible stylesheet from the host document\n * (or links it as a fallback for cross-origin sheets) so the layout survives\n * transplant to an iframe, a saved file, or a headless renderer.\n *\n * This is the building block for two paths:\n * - `exportPdfFromElement` (this file): writes the HTML into a hidden iframe\n * and calls `window.print()` for the local \"Save as PDF\" flow.\n * - Upload-to-server snapshots: POST the string to a backend that converts it\n * to PDF via Puppeteer's `setContent + page.pdf()` without re-running the\n * pagination engine.\n */\nexport function serializePaginatedHtml(\n root: HTMLElement,\n options: SerializePaginatedHtmlOptions = {},\n): string {\n const clone = root.cloneNode(true) as HTMLElement;\n // Strip interactive scaffolding that print styles can't see ahead of time.\n clone.querySelectorAll(\"[contenteditable]\").forEach((el) => {\n (el as HTMLElement).removeAttribute(\"contenteditable\");\n });\n clone.querySelectorAll(\".ed-image-overlay\").forEach((el) => el.remove());\n clone.querySelectorAll(\".ed-remote-cursors\").forEach((el) => el.remove());\n\n // Read the page size baked into the editor via `--ed-page-*` CSS variables.\n // The Editor component sets these on its root from the current PageSettings\n // (`packages/react/src/Editor.tsx`). Falls back to A4 if we can't read them.\n const cs = root.ownerDocument?.defaultView?.getComputedStyle(root);\n const pageSize = options.pageSize ?? cssPageSizeFromRoot(cs);\n\n const styles = collectStyles();\n const title = escapeHtml(options.title ?? \"Documento\");\n const extra = options.extraCss ?? \"\";\n // The `@page { size }` and page-break rules live inside `@media print` so\n // they merge cleanly with any host-document print stylesheet that already\n // declares its own `@page` (e.g. `apps/playground/src/styles.css`). Putting\n // ours after the cloned `<style>`s gives our override last-write-wins.\n return [\n \"<!doctype html>\",\n `<html><head><meta charset=\"utf-8\"><meta name=\"ed-print-snapshot\" content=\"1\"><title>${title}</title>`,\n styles,\n `<style>\n html, body { margin: 0; padding: 0; background: white; }\n @media print {\n @page { size: ${pageSize.width} ${pageSize.height}; margin: 0; }\n .ed-page { box-shadow: none !important; border: none !important; border-radius: 0 !important; margin: 0 !important; page-break-after: always; break-after: page; }\n .ed-page:last-child { page-break-after: auto; break-after: auto; }\n .ed-image-overlay { display: none !important; }\n }\n ${extra}\n </style>`,\n \"</head><body>\",\n clone.outerHTML,\n \"</body></html>\",\n ].join(\"\");\n}\n\n/**\n * Snapshot a live editor root element (the `.ed-root` paginated DOM) and open\n * the browser's print dialog. Preserves the in-editor pagination decisions\n * verbatim — no re-layout in the print frame.\n *\n * For the \"send the snapshot to a server\" use case, use\n * `serializePaginatedHtml` directly and POST the returned string.\n */\nexport async function exportPdfFromElement(\n root: HTMLElement,\n options: ExportPdfFromElementOptions = {},\n): Promise<void> {\n const html = serializePaginatedHtml(root, options);\n await printHtmlInIframe(html, options.filename ?? options.title ?? \"Documento\");\n}\n\n// ---------- internals ----------\n\nasync function printHtmlInIframe(html: string, _filename: string): Promise<void> {\n const iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"aria-hidden\", \"true\");\n iframe.style.cssText =\n \"position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;\";\n document.body.appendChild(iframe);\n\n const win = iframe.contentWindow;\n const docu = iframe.contentDocument ?? win?.document;\n if (!win || !docu) {\n iframe.remove();\n throw new Error(\"export-pdf: failed to access iframe document\");\n }\n\n docu.open();\n docu.write(html);\n docu.close();\n\n // Wait for the iframe document to finish loading (DOM, stylesheets, images).\n await new Promise<void>((resolve) => {\n if (docu.readyState === \"complete\") resolve();\n else iframe.addEventListener(\"load\", () => resolve(), { once: true });\n });\n // Best-effort wait for embedded images: print dialogs that snapshot too early\n // miss late-loading data URIs (rare, but real).\n await waitForImages(docu);\n // CRITICAL: wait for @font-face fonts to finish loading. The `load` event does\n // NOT wait for web fonts, so printing too early triggers FOIT (Flash of\n // Invisible Text): the browser hides every glyph until its font loads, while\n // text-decoration underlines still paint. Symptom seen in the wild: the\n // letterhead + field underlines printed but ALL text was missing. `fonts.ready`\n // resolves once all used fonts are loaded; cap the wait so a font that never\n // resolves can't hang the print.\n await waitForFonts(docu);\n\n await new Promise<void>((resolve) => {\n const cleanup = () => {\n win.removeEventListener(\"afterprint\", cleanup);\n // Defer removal one tick so Safari's print queue doesn't choke.\n setTimeout(() => iframe.remove(), 0);\n resolve();\n };\n win.addEventListener(\"afterprint\", cleanup);\n win.focus();\n win.print();\n // Fallback in case afterprint never fires (older browsers).\n setTimeout(() => {\n if (iframe.isConnected) cleanup();\n }, 60_000);\n });\n}\n\nfunction collectStyles(): string {\n const parts: string[] = [];\n for (const sheet of Array.from(document.styleSheets)) {\n try {\n const rules = sheet.cssRules;\n if (!rules) continue;\n const css = Array.from(rules)\n .map((r) => r.cssText)\n .join(\"\\n\");\n if (css) parts.push(`<style>${css}</style>`);\n } catch {\n // Cross-origin sheet — fall back to linking it.\n const href = sheet.href;\n if (href) parts.push(`<link rel=\"stylesheet\" href=\"${escapeAttr(href)}\">`);\n }\n }\n return parts.join(\"\\n\");\n}\n\nasync function waitForImages(docu: Document): Promise<void> {\n const imgs = Array.from(docu.images);\n await Promise.all(\n imgs.map(\n (img) =>\n new Promise<void>((resolve) => {\n if (img.complete) return resolve();\n img.addEventListener(\"load\", () => resolve(), { once: true });\n img.addEventListener(\"error\", () => resolve(), { once: true });\n }),\n ),\n );\n}\n\n/**\n * Wait for the iframe document's web fonts (`@font-face`) to finish loading,\n * capped so a font that never resolves can't hang the print. Without this the\n * print can fire mid-font-load and render invisible text (FOIT).\n */\nasync function waitForFonts(docu: Document): Promise<void> {\n const fonts = (docu as Document & { fonts?: FontFaceSet }).fonts;\n if (!fonts?.ready) return;\n await Promise.race([\n fonts.ready.then(() => undefined),\n new Promise<void>((resolve) => {\n setTimeout(resolve, 3000);\n }),\n ]);\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"']/g, (c) => HTML_ESCAPES[c]);\n}\nfunction escapeAttr(s: string): string {\n return escapeHtml(s);\n}\n","/**\n * Trigger a browser download for an in-memory blob/string. Tiny utility — kept\n * in this package because PDF/HTML/JSON exporters all want it.\n */\nexport function downloadBlob(blob: Blob, filename: string): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.rel = \"noopener\";\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n setTimeout(() => {\n a.remove();\n URL.revokeObjectURL(url);\n }, 0);\n}\n\nexport function downloadString(\n text: string,\n filename: string,\n mimeType = \"text/plain;charset=utf-8\",\n): void {\n downloadBlob(new Blob([text], { type: mimeType }), filename);\n}\n"],"mappings":";AAcA,SAAS,cAAc,4BAA4B,cAAc;AAEjE,SAAS,UAAU,KAAwE;AACzF,SAAO,2BAA2B,GAAG,IAAI,EAAE,QAAQ,IAAI,IAAI;AAC7D;AAoBA,IAAM,eAAe;AAAA,EACnB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa;AACf;AAcO,SAAS,eACd,KACA,UAAiC,CAAC,GAC1B;AACR,QAAM,aAAa,UAAU,GAAG;AAChC,QAAM,OAAO,uBAAuB,UAAU;AAC9C,MAAI,QAAQ,eAAe,MAAO,QAAO;AACzC,QAAM,OAAO,QAAQ,QAAQ,iBAAiB,WAAW,YAAY;AACrE,QAAM,QAAQ,WAAW,QAAQ,SAAS,WAAW;AACrD,QAAM,QAAQ,QAAQ,YAAY;AAClC,SAAO;AAAA,IACL;AAAA,IACA,yDAAyD,KA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2
  "name": "@sofereditor/export-pdf",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "@sofereditor/export-pdf — Serialize the paginated Sofer DOM to self-contained HTML, ready for Puppeteer PDF rendering.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "author": "Rafael Marreca",
@@ -43,7 +43,7 @@
43
43
  "test": "vitest run"
44
44
  },
45
45
  "dependencies": {
46
- "@sofereditor/core": "^0.2.0"
46
+ "@sofereditor/core": "^0.3.1"
47
47
  },
48
48
  "devDependencies": {
49
49
  "typescript": "^5.7.2",