@openpresentation/opf 0.31.0 → 0.32.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.
Files changed (76) hide show
  1. package/README.md +1 -1
  2. package/dist/browser.js +18 -18
  3. package/dist/{chart-data-Ci9s_NDN.d.ts → chart-data-oIZQlFGi.d.ts} +4 -2
  4. package/dist/{chunk-UKWNHK62.js → chunk-2E6CDYL2.js} +23 -6
  5. package/dist/{chunk-HRKV43GC.js → chunk-BBVW5ZC2.js} +3 -3
  6. package/dist/{chunk-7UO6H32I.js → chunk-CLRYHWQN.js} +162 -22
  7. package/dist/chunk-DGS47ONG.js +1 -0
  8. package/dist/{chunk-F5QC7E2O.js → chunk-F7DN33UL.js} +28 -8
  9. package/dist/{chunk-KELC4K62.js → chunk-HKUV7NEN.js} +1 -1
  10. package/dist/{chunk-XG4JKFZ6.js → chunk-IT7FQKED.js} +6 -6
  11. package/dist/{chunk-SYCHWS7C.js → chunk-J63CIRIV.js} +4 -4
  12. package/dist/{chunk-5Q4IYLMW.js → chunk-LEF4X4KI.js} +274 -33
  13. package/dist/{chunk-5OMZW44K.js → chunk-NEJ32O7X.js} +1 -1
  14. package/dist/chunk-NVAJASOD.js +14764 -0
  15. package/dist/{chunk-XSCZZWYI.js → chunk-ONVFUVQ5.js} +99 -15
  16. package/dist/{chunk-M7YZU3DX.js → chunk-OXLA4HXQ.js} +615 -58
  17. package/dist/{chunk-P5E3FNYO.js → chunk-PB7ME64J.js} +1 -1
  18. package/dist/{chunk-ARFAQNOH.js → chunk-SW676APJ.js} +2 -2
  19. package/dist/{chunk-I6G32TB5.js → chunk-SZFO3MAJ.js} +5 -5
  20. package/dist/{chunk-W7KPMUJF.js → chunk-XFHXQCXL.js} +58 -5
  21. package/dist/{chunk-KOCXV7H3.js → chunk-XQO2CT6Q.js} +2 -2
  22. package/dist/{chunk-WHDOOLIO.js → chunk-YFJIIIOL.js} +3 -3
  23. package/dist/composition-Ds6WHyO7.d.ts +5620 -0
  24. package/dist/composition.d.ts +2 -2
  25. package/dist/composition.js +1 -1
  26. package/dist/conversion-5FUDQPED.js +24 -0
  27. package/dist/{conversion-Bh-skyMc.d.ts → conversion-CdzrTxib.d.ts} +56 -9
  28. package/dist/convert.d.ts +2 -2
  29. package/dist/convert.js +7 -7
  30. package/dist/data.d.ts +2 -2
  31. package/dist/data.js +2 -2
  32. package/dist/{deck-report-DQMsvyBI.d.ts → deck-report-CKDNQ2t4.d.ts} +2 -2
  33. package/dist/deck.d.ts +5 -5
  34. package/dist/deck.js +11 -11
  35. package/dist/diagram-engine-eager.js +6 -0
  36. package/dist/diagram-engine-lazy.js +2 -0
  37. package/dist/diff.js +4 -4
  38. package/dist/docs.js +25 -19
  39. package/dist/examples.js +4759 -995
  40. package/dist/format.js +2 -2
  41. package/dist/ids.js +4 -4
  42. package/dist/index.d.ts +15 -12
  43. package/dist/index.js +23 -22
  44. package/dist/markdown.d.ts +2 -2
  45. package/dist/markdown.js +8 -8
  46. package/dist/node-engine.d.ts +6 -6
  47. package/dist/node-engine.js +20 -20
  48. package/dist/{pagination-DyAKYpXu.d.ts → pagination-DRZ_JNFY.d.ts} +74 -4
  49. package/dist/pagination.d.ts +3 -3
  50. package/dist/pagination.js +4 -4
  51. package/dist/patch.js +3 -3
  52. package/dist/precompiled.js +2 -2
  53. package/dist/{presentation-8jLSTFqL.d.ts → presentation-DnD7mfmf.d.ts} +106 -27
  54. package/dist/repo-readme.js +1 -1
  55. package/dist/schema-engine-ajv.js +1 -1
  56. package/dist/schema-engine-precompiled.js +2 -2
  57. package/dist/schema.js +3 -3
  58. package/dist/schemas.d.ts +6 -0
  59. package/dist/schemas.js +1 -1
  60. package/dist/source.d.ts +4 -3
  61. package/dist/source.js +10 -10
  62. package/dist/spec/schemas/layout.schema.json +58 -8
  63. package/dist/spec/schemas/narrative.schema.json +2 -1
  64. package/dist/spec/schemas/opf.schema.json +122 -23
  65. package/dist/spec/schemas/theme.schema.json +9 -3
  66. package/dist/types.d.ts +69 -18
  67. package/dist/{validation-types-mNmfcY9A.d.ts → validation-types-DxyYPebs.d.ts} +1 -1
  68. package/dist/validator.d.ts +4 -4
  69. package/dist/validator.js +3 -3
  70. package/dist/yaml.d.ts +2 -2
  71. package/dist/yaml.js +7 -7
  72. package/package.json +15 -6
  73. package/dist/chunk-W3SEWSO5.js +0 -8043
  74. package/dist/chunk-ZROVYWGU.js +0 -1
  75. package/dist/composition-C-hd_Ci3.d.ts +0 -3207
  76. package/dist/conversion-7OPM5MMJ.js +0 -24
package/README.md CHANGED
@@ -89,7 +89,7 @@ The layout engine's names are not on the root. `composeSlide`, `fitText`, `layou
89
89
 
90
90
  ### Markdown and outlines
91
91
 
92
- `@openpresentation/opf/markdown` reads and writes a deck as Markdown in a small documented dialect (YAML front matter, `---` between slides, `#` title, `##` subtitle, lists, quotes, tables, images, `chart`, `metric` and `timeline` fences, `Note:` speaker notes). `fromMarkdown(markdown, { split, defaults, validate })` returns `{ presentation, valid, findings, counts }` with findings (the shared `Finding` format) that carry the line and column of the Markdown; `toMarkdown(presentation, { unsupported })` writes any valid deck, embedding what the dialect has no syntax for as YAML (or dropping it into `report.loss`), and the Markdown it writes converts back to the same deck. Deterministic and offline. Reads front matter with the `yaml` package. See the [Markdown guide](../../docs/markdown.md). Not in releases before the one that lists it in the changelog.
92
+ `@openpresentation/opf/markdown` reads and writes a deck as Markdown in a small documented dialect (YAML front matter, `---` between slides, `#` title, `##` subtitle, lists, quotes, tables, images, `chart`, `metric`, `timeline` and `mermaid` (diagram) fences, `Note:` speaker notes). `fromMarkdown(markdown, { split, defaults, validate })` returns `{ presentation, valid, findings, counts }` with findings (the shared `Finding` format) that carry the line and column of the Markdown; `toMarkdown(presentation, { unsupported })` writes any valid deck, embedding what the dialect has no syntax for as YAML (or dropping it into `report.loss`), and the Markdown it writes converts back to the same deck. Deterministic and offline. Reads front matter with the `yaml` package. See the [Markdown guide](../../docs/markdown.md). Not in releases before the one that lists it in the changelog.
93
93
 
94
94
  ### Reading and writing a deck in any form
95
95
 
package/dist/browser.js CHANGED
@@ -1,25 +1,25 @@
1
- import { OPFApiError } from './chunk-I6G32TB5.js';
2
- export { OPFApiError, OPFExportError, OPFImportError, OPFMoveToCustomError, copySlides, edit, embed, fill, fillRecords, localAssetSources, moveToCustom, parseSlideSelection, sameRecord, stats, updateFromCatalog } from './chunk-I6G32TB5.js';
1
+ import { OPFApiError } from './chunk-SZFO3MAJ.js';
2
+ export { OPFApiError, OPFExportError, OPFImportError, OPFMoveToCustomError, copySlides, edit, embed, fill, fillRecords, localAssetSources, moveToCustom, parseSlideSelection, sameRecord, stats, updateFromCatalog } from './chunk-SZFO3MAJ.js';
3
3
  export { specFileEntries, specFileKinds, specFilePaths } from './chunk-UJSAR6GF.js';
4
4
  export { FONT_POLICY, applyFontPolicyDecisions, fontAvailabilityDiagnostics, fontPolicyFor } from './chunk-PJSPHHRK.js';
5
- export { OPFDataImportError, ingest, parseTabularData } from './chunk-P5E3FNYO.js';
6
- export { OPFPaginationError, paginate, paginateSlide } from './chunk-7UO6H32I.js';
7
- export { DECK_FORMATS, deckFormatOf, parse, stringify } from './chunk-SYCHWS7C.js';
8
- export { fromMarkdown, toMarkdown } from './chunk-F5QC7E2O.js';
9
- import './chunk-XG4JKFZ6.js';
10
- export { OPFFormatError, format } from './chunk-KELC4K62.js';
5
+ export { OPFDataImportError, ingest, parseTabularData } from './chunk-PB7ME64J.js';
6
+ export { OPFPaginationError, blockUnits, continuationPages, continueOverfull, paginate, paginateSlide } from './chunk-CLRYHWQN.js';
7
+ export { DECK_FORMATS, deckFormatOf, parse, stringify } from './chunk-J63CIRIV.js';
8
+ export { fromMarkdown, toMarkdown } from './chunk-F7DN33UL.js';
9
+ import './chunk-IT7FQKED.js';
10
+ export { OPFFormatError, format } from './chunk-HKUV7NEN.js';
11
11
  import './chunk-RYZPBJLB.js';
12
- export { explain } from './chunk-W7KPMUJF.js';
13
- import './chunk-UKWNHK62.js';
14
- import './chunk-5OMZW44K.js';
15
- export { OPFMarkdownError } from './chunk-HRKV43GC.js';
16
- import './chunk-KOCXV7H3.js';
17
- export { OPFIdError, assignIds, touches } from './chunk-ARFAQNOH.js';
18
- export { diff, merge } from './chunk-WHDOOLIO.js';
19
- export { CATALOG_SCHEMA, DEFAULT_VALIDATION_THRESHOLDS, OPFPatchError, OPFPatchHashError, OPFPatchValidationError, OPFValidationError, applyPatch, assertValid, assertValidCatalogRecord, catalogDisplayKinds, catalogSchemaNames, documentHash, findValidationRule, idToken, isIdToken, resolveDrawnFontFamilies, resolveIdPatch, resolveIdPointer, resolveSlideContext, toIdPatch, toIdPointer, validate, validateCatalogRecord, validationCategories, validationRules } from './chunk-M7YZU3DX.js';
12
+ export { explain } from './chunk-XFHXQCXL.js';
13
+ import './chunk-2E6CDYL2.js';
14
+ import './chunk-NEJ32O7X.js';
15
+ export { OPFMarkdownError } from './chunk-BBVW5ZC2.js';
16
+ import './chunk-XQO2CT6Q.js';
17
+ export { OPFIdError, assignIds, touches } from './chunk-SW676APJ.js';
18
+ export { diff, merge } from './chunk-YFJIIIOL.js';
19
+ export { CATALOG_SCHEMA, DEFAULT_VALIDATION_THRESHOLDS, OPFPatchError, OPFPatchHashError, OPFPatchValidationError, OPFValidationError, applyPatch, assertValid, assertValidCatalogRecord, catalogDisplayKinds, catalogSchemaNames, documentHash, findValidationRule, idToken, isIdToken, resolveDrawnFontFamilies, resolveIdPatch, resolveIdPointer, resolveSlideContext, toIdPatch, toIdPointer, validate, validateCatalogRecord, validationCategories, validationRules } from './chunk-OXLA4HXQ.js';
20
20
  import './chunk-JBARNYFR.js';
21
- export { audience, chartType, colorScheme, fontScheme, language, layout, narrative, presentation, purpose, schemaEntries, schemaNames, schemas, socialPlatform, theme, tone } from './chunk-5Q4IYLMW.js';
22
- export { CATALOG_GROUP_PATTERN, CATALOG_REFERENCE_PATTERN, CHART_TYPES, DEFAULT_VARIABLE_DATE_FORMAT, ENGINE_DEFAULT_CHART_TYPES, ENGINE_DEFAULT_COLOR_SCHEME, ENGINE_DEFAULT_FONT_SCHEME, ENGINE_DEFAULT_THEME, LANGUAGES, LOGO_SHAPES, OPFCatalogsOptionError, OPFUnresolvedReferenceError, OPFVariableError, SLIDE_SCOPED_BUILTINS, SOCIAL_PLATFORMS, VARIABLE_KINDS, catalogGroupSource, catalogKinds, catalogRecords, catalogReferenceSites, chartNumber, coerceVariableValue, datasetDiagnostics, formatDataNumber, formatVariableNumber, fromExcelNumberFormat, hasContentVariables, inlineChartData, inlineDatasets, inlineTableData, isDatasetRef, isTemplate, isXYChartType, listBuiltinVariables, listVariables, normalizeLanguageFamily, numberFormatError, parseReference, resolveChartData, resolveDesignRecords, resolveFontScheme, resolveReference, resolveSlideVariables, resolveTableData, resolveVariables, suggestChartNumberFix, tableCellDisplayValue, toExcelNumberFormat, unresolvedReference, unusedDatasets, variableDeclarations } from './chunk-W3SEWSO5.js';
21
+ export { audience, chartType, colorScheme, fontScheme, language, layout, narrative, presentation, purpose, schemaEntries, schemaNames, schemas, socialPlatform, theme, tone } from './chunk-LEF4X4KI.js';
22
+ export { CATALOG_GROUP_PATTERN, CATALOG_REFERENCE_PATTERN, CHART_TYPES, DEFAULT_VARIABLE_DATE_FORMAT, ENGINE_DEFAULT_CHART_TYPES, ENGINE_DEFAULT_COLOR_SCHEME, ENGINE_DEFAULT_FONT_SCHEME, ENGINE_DEFAULT_THEME, LANGUAGES, LOGO_SHAPES, OPFCatalogsOptionError, OPFUnresolvedReferenceError, OPFVariableError, SLIDE_SCOPED_BUILTINS, SOCIAL_PLATFORMS, VARIABLE_KINDS, catalogGroupSource, catalogKinds, catalogRecords, catalogReferenceSites, chartDrawDiagnostics, chartDrawPlan, chartNumber, coerceVariableValue, datasetDiagnostics, diagramsPending, ensureDiagrams, formatDataNumber, formatVariableNumber, fromExcelNumberFormat, hasContentVariables, inlineChartData, inlineDatasets, inlineTableData, isDatasetRef, isPlaceLabel, isTemplate, isXYChartType, listBuiltinVariables, listVariables, markLabelColor, normalizeLanguageFamily, numberFormatError, parseReference, resolveChartData, resolveDesignRecords, resolveFontScheme, resolveReference, resolveSlideVariables, resolveTableData, resolveVariables, suggestChartNumberFix, tableCellDisplayValue, toExcelNumberFormat, unresolvedReference, unusedDatasets, variableDeclarations } from './chunk-NVAJASOD.js';
23
23
  import './chunk-GM7WFPGG.js';
24
24
 
25
25
  // src/browser.ts
@@ -57,7 +57,7 @@ interface DataStyledCell {
57
57
  type DataTableCell = DataTableValue | DataStyledCell;
58
58
  /** A table column header: a cell, or a DataColumn. */
59
59
  type DataTableHeader = DataTableCell | DataColumn;
60
- type DataDiagnosticCode = 'chart-value-not-numeric' | 'dataset-unknown' | 'dataset-field-unknown' | 'data-column-duplicate' | 'chart-mapping-unknown-column' | 'chart-mapping-adapted' | 'chart-highlight-unknown-name' | 'chart-highlight-adapted' | 'number-format-invalid';
60
+ type DataDiagnosticCode = 'chart-value-not-numeric' | 'dataset-unknown' | 'dataset-field-unknown' | 'data-column-duplicate' | 'chart-mapping-unknown-column' | 'chart-mapping-adapted' | 'chart-highlight-unknown-name' | 'chart-highlight-adapted' | 'chart-series-dropped' | 'table-highlight-unknown-name' | 'number-format-invalid';
61
61
  interface DataDiagnostic {
62
62
  code: DataDiagnosticCode;
63
63
  severity: 'error' | 'warning';
@@ -182,8 +182,10 @@ interface ChartNumberFixOptions extends DataResolveOptions {
182
182
  declare function suggestChartNumberFix(chart: unknown, document?: unknown, options?: ChartNumberFixOptions): ChartNumberFix | undefined;
183
183
  /** Resolve a table (inline or dataset-backed) to headers, rows and per-column formats. */
184
184
  declare function resolveTableData(table: unknown, document?: unknown, options?: DataResolveOptions): ResolvedTableData;
185
+ /** LH-113: the text of a table cell as its key (the first column): a string, a number, rich runs or a styled cell's value. */
186
+ declare function tableKeyText(cell: unknown): string;
185
187
  /** Display value of a table cell: a number with a format (cell, else column) becomes formatted text; anything else is returned unchanged. */
186
188
  declare function tableCellDisplayValue(cell: DataTableCell, columnFormat?: string): DataTableCell;
187
189
 
188
- export { resolveChartData as A, resolveTableData as B, suggestChartNumberFix as E, tableCellDisplayValue as F, toExcelNumberFormat as G, unusedDatasets as H, chartNumber as q, datasetDiagnostics as r, formatDataNumber as s, fromExcelNumberFormat as t, inlineChartData as u, inlineDatasets as v, inlineTableData as w, isDatasetRef as x, isXYChartType as y, numberFormatError as z };
190
+ export { resolveChartData as A, resolveTableData as B, suggestChartNumberFix as E, tableCellDisplayValue as F, toExcelNumberFormat as G, unusedDatasets as H, tableKeyText as J, chartNumber as q, datasetDiagnostics as r, formatDataNumber as s, fromExcelNumberFormat as t, inlineChartData as u, inlineDatasets as v, inlineTableData as w, isDatasetRef as x, isXYChartType as y, numberFormatError as z };
189
191
  export type { ChartMapping as C, DataCellValue as D, ChartComboSeries as I, ResolvedChartData as R, ChartNumberFix as a, ChartNumberFixOperation as b, ChartNumberFixOptions as c, DataColumn as d, DataDiagnostic as e, DataDiagnosticCode as f, DataResolveOptions as g, DataSourceRef as h, DataStyledCell as i, DataTableCell as j, DataTableHeader as k, DataTableValue as l, DataTextRun as m, Dataset as n, DatasetRef as o, ResolvedTableData as p };
@@ -1,8 +1,8 @@
1
- import { parseQuoteLines, levelsFromIndents, parseCodeFence, splitWhen } from './chunk-5OMZW44K.js';
2
- import { Ctx, splitLines, lineRange, readYamlMapping, readCsv, DECIMAL } from './chunk-HRKV43GC.js';
3
- import { runText, isRecord, FORMATTING } from './chunk-KOCXV7H3.js';
4
- import { METRIC_KEYS, nearest, BLOCK_AS_VALUES, SLIDE_OPTION_KEYS, BLOCK_OPTION_KEYS } from './chunk-M7YZU3DX.js';
5
- import { PROMOTED_REGION_KEY } from './chunk-W3SEWSO5.js';
1
+ import { parseQuoteLines, levelsFromIndents, parseCodeFence, splitWhen } from './chunk-NEJ32O7X.js';
2
+ import { Ctx, splitLines, lineRange, readYamlMapping, readCsv, DECIMAL } from './chunk-BBVW5ZC2.js';
3
+ import { runText, isRecord, FORMATTING } from './chunk-XQO2CT6Q.js';
4
+ import { METRIC_KEYS, nearest, BLOCK_AS_VALUES, SLIDE_OPTION_KEYS, BLOCK_OPTION_KEYS } from './chunk-OXLA4HXQ.js';
5
+ import { PROMOTED_REGION_KEY } from './chunk-NVAJASOD.js';
6
6
 
7
7
  // src/markdown/inline.ts
8
8
  var PUNCT = /[\p{P}\p{S}]/u;
@@ -955,6 +955,7 @@ var SlideParser = class {
955
955
  if (word === "chart") this.chart(rest, bodyText, range);
956
956
  else if (word === "metric") this.metric(body, range);
957
957
  else if (word === "timeline") this.timeline(rest, body, range);
958
+ else if (word === "mermaid") this.diagram(rest, bodyText, range);
958
959
  else if (word === "opf-slide") this.embeddedSlide(bodyText, bodyStart, range);
959
960
  else if (word === "opf-block") this.embeddedBlock(bodyText, bodyStart, range);
960
961
  else {
@@ -970,6 +971,22 @@ var SlideParser = class {
970
971
  this.native("code", hasMeta ? value : parsed.source, range);
971
972
  }
972
973
  }
974
+ // A ```mermaid fence is a diagram payload; `alt="..."` after the word is its text alternative.
975
+ diagram(rest, text, range) {
976
+ const { ctx } = this;
977
+ const { pairs, error } = parseAttributes(rest);
978
+ let alt;
979
+ if (error) ctx.error("diagram-attributes", error, 'Write ```mermaid alt="What the diagram shows" (alt is optional).', range, this.path);
980
+ for (const [key, value] of pairs) {
981
+ if (key === "alt" && typeof value === "string") alt = value;
982
+ else ctx.error("diagram-attributes", `Unknown diagram attribute ${JSON.stringify(key)}.`, "A mermaid fence takes alt, a text alternative in double quotes.", range, this.path);
983
+ }
984
+ if (!text.trim()) {
985
+ ctx.error("diagram-source", "A mermaid block has no source.", "Write the Mermaid diagram between the fences, starting with its type (flowchart LR, sequenceDiagram, mindmap, ...).", range, this.path);
986
+ return;
987
+ }
988
+ this.native("diagram", alt === void 0 ? text : { source: text, alt }, range);
989
+ }
973
990
  chart(rest, text, range) {
974
991
  const { ctx } = this;
975
992
  const type = /^[^\s]+/.exec(rest)?.[0];
@@ -1164,7 +1181,7 @@ var SlideParser = class {
1164
1181
  return slide;
1165
1182
  }
1166
1183
  };
1167
- var CONTENT = /* @__PURE__ */ new Set(["text", "items", "bullets", "image", "video", "chart", "table", "code", "metric", "quote", "timeline"]);
1184
+ var CONTENT = /* @__PURE__ */ new Set(["text", "items", "bullets", "image", "video", "chart", "table", "code", "metric", "quote", "timeline", "diagram"]);
1168
1185
  var isContentKey = (key) => CONTENT.has(key);
1169
1186
  function splitRow(text) {
1170
1187
  let s = text.trim();
@@ -1,5 +1,5 @@
1
- import { isRecord, same } from './chunk-KOCXV7H3.js';
2
- import { createLocator } from './chunk-M7YZU3DX.js';
1
+ import { isRecord, same } from './chunk-XQO2CT6Q.js';
2
+ import { createLocator } from './chunk-OXLA4HXQ.js';
3
3
  import { parseDocument, isMap, isSeq, isScalar, YAMLMap, Scalar, stringify, visit } from 'yaml';
4
4
 
5
5
  var sentence = (text) => text.charAt(0).toUpperCase() + text.slice(1);
@@ -439,7 +439,7 @@ function describeYamlErrors(text, doc, errors, limit = 5) {
439
439
  }
440
440
  return out;
441
441
  }
442
- var SLIDE_KEYS = /* @__PURE__ */ new Set(["title", "subtitle", "items", "text", "layout", "blocks", "image", "chart", "table", "quote", "code", "metric", "timeline", "notes"]);
442
+ var SLIDE_KEYS = /* @__PURE__ */ new Set(["title", "subtitle", "items", "text", "layout", "blocks", "image", "chart", "table", "quote", "code", "metric", "timeline", "diagram", "notes"]);
443
443
  function analyzeYamlSyntax(text, options = {}) {
444
444
  const bom = text.startsWith("\uFEFF") ? 1 : 0;
445
445
  const body = text.slice(bom);
@@ -1,5 +1,5 @@
1
- import { assertValid, resolveSlideScriptMeasurement, resolveDrawnFontFamilies, resolveSlideContext } from './chunk-M7YZU3DX.js';
2
- import { resolveSlideVariables, checkCatalogsOption, usesSlideBuiltin, composeSlide, codeHighlightSlice, tableRowBoundaries, visitContentPayloads, regionAccepts, slideTokenSpans, sliceNumberedItems } from './chunk-W3SEWSO5.js';
1
+ import { assertValid, resolveSlideScriptMeasurement, resolveDrawnFontFamilies, resolveSlideContext } from './chunk-OXLA4HXQ.js';
2
+ import { composeSlide, resolveSlideVariables, OPFCompositionError, checkCatalogsOption, usesSlideBuiltin, codeHighlightSlice, tableRowBoundaries, visitContentPayloads, regionAccepts, slideTokenSpans, sliceNumberedItems } from './chunk-NVAJASOD.js';
3
3
 
4
4
  // src/pagination.ts
5
5
  var OPFPaginationError = class extends Error {
@@ -11,7 +11,7 @@ var OPFPaginationError = class extends Error {
11
11
  diagnostics;
12
12
  code = "pagination-unresolved";
13
13
  };
14
- var contentFields = /* @__PURE__ */ new Set(["text", "items", "bullets", "image", "video", "chart", "table", "code", "metric", "quote", "timeline"]);
14
+ var contentFields = /* @__PURE__ */ new Set(["text", "items", "bullets", "image", "video", "chart", "table", "code", "metric", "quote", "timeline", "diagram"]);
15
15
  var headingFields = /* @__PURE__ */ new Set(["title", "subtitle", "tag"]);
16
16
  var isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
17
17
  var clone = (value) => structuredClone(value);
@@ -34,6 +34,16 @@ function sliceRichText(value, start, end) {
34
34
  return [typeof run === "string" ? text.slice(left, right) : { ...run, text: text.slice(left, right) }];
35
35
  });
36
36
  }
37
+ function sentenceEnds(text) {
38
+ const ends = [];
39
+ let from = 0;
40
+ for (const match of text.matchAll(/[.!?][”"')]*\s+|\n\s*\n/gu)) {
41
+ if (/^(\d{1,3}|\p{L})$/u.test(text.slice(from, match.index).trim())) continue;
42
+ ends.push(match.index + match[0].length);
43
+ from = match.index + match[0].length;
44
+ }
45
+ return ends;
46
+ }
37
47
  var deckContext = (presentation) => {
38
48
  const deck = isRecord(presentation) ? presentation : {};
39
49
  return { ...Array.isArray(deck.references) ? { references: deck.references } : {}, ...isRecord(deck.datasets) ? { datasets: deck.datasets } : {} };
@@ -81,20 +91,33 @@ function leafFor(path, field, value) {
81
91
  }
82
92
  return leaf;
83
93
  }
94
+ function bodySizes(composed) {
95
+ const scale = Math.min(composed.width, composed.height) / 720, sizes = /* @__PURE__ */ new Map();
96
+ const add = (kind, size) => {
97
+ if (size !== void 0 && Number.isFinite(size) && size > 0) sizes.set(kind, Math.max(sizes.get(kind) ?? 0, Math.round(size / scale * 100) / 100));
98
+ };
99
+ for (const item of composed.items) {
100
+ if (headingFields.has(item.field) || item.eyebrow) continue;
101
+ const layout = item.quoteLayout ?? item.metricLayout ?? item.timelineLayout;
102
+ if (layout) add(item.field, Math.max(0, ...layout.parts.flatMap((part) => part.visible === false || !part.fit ? [] : [part.fit.fontSize])));
103
+ else if (item.text && !item.codeLayout && (item.field === "text" || item.field === "items" || item.field === "bullets")) add(item.field === "text" ? "text" : "list", item.text.fontSize);
104
+ }
105
+ return sizes;
106
+ }
84
107
  function paginateSlide(input, options = {}) {
85
108
  assertValid({ ...deckContext(options.presentation), slides: [input] }, { only: ["format"] });
86
109
  let source = clone(input);
87
110
  const maxSlides = options.maxSlides ?? 100;
88
111
  if (!Number.isInteger(maxSlides) || maxSlides < 1 || maxSlides > 1e4) throw new RangeError("maxSlides must be an integer between 1 and 10000.");
89
- const minFontSize = options.minFontSize ?? 24;
90
- if (!Number.isFinite(minFontSize) || minFontSize < 8 || minFontSize > 32) throw new RangeError("Pagination minFontSize must be between 8 and 32.");
112
+ const minFontSize = options.minFontSize ?? (options.wholeBlocks ? void 0 : 24);
113
+ if (minFontSize !== void 0 && (!Number.isFinite(minFontSize) || minFontSize < 8 || minFontSize > 32)) throw new RangeError("Pagination minFontSize must be between 8 and 32.");
91
114
  const sourceIndex = options.slideIndex ?? 0, sourceBase = `slides.${sourceIndex}`;
92
115
  const withReadability = (slide, warn = false) => {
93
116
  const result = clone(slide);
94
- const rootMinimum = Math.max(minFontSize, result.composition?.minFontSize ?? options.layout?.composition?.minFontSize ?? 16);
117
+ const rootMinimum = Math.max(minFontSize ?? 0, result.composition?.minFontSize ?? options.layout?.composition?.minFontSize ?? 16);
95
118
  result.composition = { ...result.composition, minFontSize: rootMinimum };
96
119
  const visit = (node, inheritedMinimum) => {
97
- const minimum = Math.max(minFontSize, node.composition?.minFontSize ?? inheritedMinimum);
120
+ const minimum = Math.max(minFontSize ?? 0, node.composition?.minFontSize ?? inheritedMinimum);
98
121
  if (node.composition) node.composition = { ...node.composition, minFontSize: minimum, ...warn ? { overflow: "warn" } : {} };
99
122
  if (Array.isArray(node.blocks)) node.blocks.forEach((child) => {
100
123
  visit(child, minimum);
@@ -104,7 +127,7 @@ function paginateSlide(input, options = {}) {
104
127
  for (const [key, value] of Object.entries(result)) if (isRecord(value) && /^(top|middle|bottom|left|center|right)([+:]|$)/.test(key)) visit(value, rootMinimum);
105
128
  return result;
106
129
  };
107
- source = withReadability(source);
130
+ if (minFontSize !== void 0) source = withReadability(source);
108
131
  let evaluations = 0;
109
132
  const { fonts, catalogs, minFontSize: _minFontSize, maxSlides: _maxSlides, reservedIds: _reservedIds, ...engineOptions } = options;
110
133
  const textMeasurement = fonts?.textMeasurement && options.presentation !== void 0 ? resolveSlideScriptMeasurement(options.presentation, sourceIndex, fonts.textMeasurement, { ...catalogs !== void 0 ? { catalogs } : {}, ...options.fontFamilies ? { fontFamilies: options.fontFamilies } : {} }) : fonts?.textMeasurement;
@@ -117,6 +140,11 @@ function paginateSlide(input, options = {}) {
117
140
  const slideNumber = (options.slideNumber ?? sourceIndex + 1) + pageIndex;
118
141
  return composeSlide(resolveSlideVariables(withReadability(slide, true), { slideNumber, ...slideCount !== void 0 ? { slideCount } : {}, ...logoContext }), { ...composeOptions, slideNumber });
119
142
  };
143
+ if (options.wholeBlocks) {
144
+ const slideNumber = options.slideNumber ?? sourceIndex + 1;
145
+ const drawn = composeSlide(resolveSlideVariables(source, { slideNumber, ...slideCount !== void 0 ? { slideCount } : {}, ...logoContext }), { ...composeOptions, slideNumber });
146
+ if (!drawn.diagnostics.some((issue) => issue.code === "text-overflow" || issue.code === "small-cell")) return { slides: [source], pages: [{ slideIndex: sourceIndex, mappings: drawn.items.map((item) => ({ sourcePath: item.path, outputPath: item.path })) }] };
147
+ }
120
148
  const initial = geometry(source);
121
149
  const movable = (issue) => {
122
150
  if (issue.region !== void 0) return true;
@@ -199,7 +227,7 @@ function paginateSlide(input, options = {}) {
199
227
  value.forEach((child, index) => {
200
228
  const projected = visit(child, `${childPath}.${index}`, `${outputPath}.${children.length}`);
201
229
  if (!projected) return;
202
- const region = root && pageIndex > 0 && projected.region === void 0 ? regionOfBlock.get(index) : void 0;
230
+ const region = root && pageIndex > 0 && !options.wholeBlocks && projected.region === void 0 ? regionOfBlock.get(index) : void 0;
203
231
  if (region && regionAccepts(region, projected)) projected.region = region.name;
204
232
  children.push(projected);
205
233
  });
@@ -222,11 +250,16 @@ function paginateSlide(input, options = {}) {
222
250
  return { slide, mappings };
223
251
  };
224
252
  const diagnosticsFor = (portions) => fit(geometry(project(portions, slides.length).slide, slides.length).diagnostics);
253
+ let firstSizes;
254
+ const kindOf = (field) => field === "items" || field === "bullets" ? "list" : field;
225
255
  const finish = () => {
226
256
  if (!selected.size) return;
227
257
  if (slides.length >= maxSlides) throw new OPFPaginationError(`Pagination needs more than ${maxSlides} slides. No partial result was returned.`);
228
258
  const { slide, mappings } = project(selected, slides.length);
229
- const issues = fit(geometry(slide, slides.length).diagnostics);
259
+ const cap = firstSizes && Math.max(0, ...[...selected.values()].map((portion) => firstSizes.get(kindOf(portion.leaf.field)) ?? 0));
260
+ if (cap) slide.composition = { ...slide.composition, maxFontSize: Math.min(Math.max(8, cap), 200, slide.composition?.maxFontSize ?? Infinity) };
261
+ const drawn = geometry(slide, slides.length), issues = fit(drawn.diagnostics);
262
+ if (!firstSizes) firstSizes = bodySizes(drawn);
230
263
  if (issues.length) throw new OPFPaginationError("A continuation page does not fit at its final page number. No partial result was returned.", issues);
231
264
  assignPageIds(slide, slides.length);
232
265
  assertValid({ ...deckContext(options.presentation), slides: [slide] }, { only: ["format"] });
@@ -234,6 +267,42 @@ function paginateSlide(input, options = {}) {
234
267
  pages.push({ slideIndex: sourceIndex + slides.length - 1, mappings, ...initial.furniture ? { repeatedMappings: repeatedMappings(slides.length - 1) } : {} });
235
268
  selected = /* @__PURE__ */ new Map();
236
269
  };
270
+ if (options.wholeBlocks) {
271
+ const unitOf = /* @__PURE__ */ new Map();
272
+ for (const [unit, indices] of (blockUnits(source)?.units ?? []).entries()) for (const index of indices) unitOf.set(index, unit);
273
+ const units = [];
274
+ let previous;
275
+ for (const leaf of leaves) {
276
+ const index = blockIndex(leaf.path);
277
+ if (index < 0) throw new OPFPaginationError(`Content at ${leaf.path} is not in a root block; a whole-block split moves root blocks only.`, initial.diagnostics);
278
+ const unit = unitOf.get(index) ?? -1 - index;
279
+ if (units.length && unit === previous) units.at(-1).push(leaf);
280
+ else units.push([leaf]);
281
+ previous = unit;
282
+ }
283
+ const portions = (from, to) => new Map(units.slice(from, to).flat().map((leaf) => [leaf.path, { leaf, start: 0, end: (leaf.boundaries ?? [0, 1]).at(-1), value: leaf.value }]));
284
+ const issuesOf = (from, to, pageIndex) => fit(geometry(project(portions(from, to), pageIndex).slide, pageIndex).diagnostics);
285
+ const greedy = [];
286
+ for (let start = 0; start < units.length; ) {
287
+ const alone = issuesOf(start, start + 1, greedy.length);
288
+ if (alone.length) throw new OPFPaginationError(`The block at ${units[start][0].path} cannot fit on an otherwise empty slide.`, alone);
289
+ let end = start + 1;
290
+ while (end < units.length && !issuesOf(start, end + 1, greedy.length).length) end++;
291
+ greedy.push([start, end]);
292
+ start = end;
293
+ }
294
+ const count = greedy.length, base = Math.floor(units.length / count), extra = units.length % count;
295
+ const balanced = Array.from({ length: count }, (_, page) => {
296
+ const start = page * base + Math.min(page, extra);
297
+ return [start, start + base + (page < extra ? 1 : 0)];
298
+ });
299
+ const ranges = balanced.every(([from, to], page) => !issuesOf(from, to, page).length) ? balanced : greedy;
300
+ for (const [from, to] of ranges) {
301
+ selected = portions(from, to);
302
+ finish();
303
+ }
304
+ return { slides, pages };
305
+ }
237
306
  for (const leaf of leaves) {
238
307
  const boundaries = leaf.boundaries ?? [0, 1];
239
308
  const end = boundaries.at(-1);
@@ -260,13 +329,15 @@ function paginateSlide(input, options = {}) {
260
329
  if (best > start && leaf.unit === "utf16" && leaf.field !== "code") {
261
330
  const text = textOf(leaf.field === "quote" ? typeof leaf.value === "string" ? leaf.value : leaf.value.text : leaf.value);
262
331
  const prefix = text.slice(start, best);
263
- const sentences = [...prefix.matchAll(/[.!?][”"')]*\s+|\n\s*\n/gu)];
264
- const lastSentence = sentences.at(-1);
265
- const sentenceEnd = lastSentence ? start + lastSentence.index + lastSentence[0].length : start;
332
+ const ends = sentenceEnds(text), sentenceEnd = ends.filter((offset) => offset > start && offset <= best).at(-1) ?? start;
266
333
  const match = /\s+\S*$/u.exec(prefix);
267
334
  const wordEnd = match ? start + match.index + match[0].length - match[0].trimStart().length : best;
268
- const preferred = sentenceEnd > start + (best - start) * 0.6 ? sentenceEnd : wordEnd;
269
- if (preferred > start && boundaries.includes(preferred) && !diagnosticsFor(new Map(selected).set(leaf.path, make(preferred))).length) best = preferred;
335
+ const stop = ends.find((offset) => offset > start) ?? end;
336
+ if (sentenceEnd <= start && selected.size && boundaries.includes(stop) && !diagnosticsFor((/* @__PURE__ */ new Map()).set(leaf.path, make(stop))).length) best = start;
337
+ else {
338
+ const preferred = sentenceEnd > start ? sentenceEnd : wordEnd;
339
+ if (preferred > start && boundaries.includes(preferred) && !diagnosticsFor(new Map(selected).set(leaf.path, make(preferred))).length) best = preferred;
340
+ }
270
341
  }
271
342
  }
272
343
  if (best > start) {
@@ -282,15 +353,78 @@ function paginateSlide(input, options = {}) {
282
353
  return { slides, pages };
283
354
  }
284
355
  function paginate(input, options = {}) {
285
- checkCatalogsOption(options.catalogs, "paginate");
356
+ const { presentation, pages } = paginateSlides(input, options, "paginate", options.maxSlides ?? 100, (slide, slideOptions) => paginateSlide(slide, slideOptions));
357
+ return { presentation, pages, layout: options.fonts ? "measured" : "estimated" };
358
+ }
359
+ var promotedKey = /^(top|middle|bottom|left|center|right)([+:]|$)/;
360
+ function blockUnits(slide) {
361
+ if (!isRecord(slide) || !Array.isArray(slide.blocks) || slide.blocks.length < 2) return void 0;
362
+ if (Object.keys(slide).some((key) => contentFields.has(key) || promotedKey.test(key))) return void 0;
363
+ const kinds = [];
364
+ for (const block of slide.blocks) {
365
+ const fields = isRecord(block) && !Array.isArray(block.blocks) ? Object.keys(block).filter((key) => contentFields.has(key)) : [];
366
+ if (fields.length !== 1) return void 0;
367
+ kinds.push(fields[0]);
368
+ }
369
+ const kind = kinds[0], units = [];
370
+ kinds.forEach((blockKind, index) => {
371
+ if (blockKind === kind) units.push([index]);
372
+ else units.at(-1).push(index);
373
+ });
374
+ return units.length >= 2 ? { kind, units } : void 0;
375
+ }
376
+ function continueOverfull(input, options = {}) {
377
+ const layout = options.fonts ? "measured" : "estimated";
378
+ const found = /* @__PURE__ */ new Map();
379
+ let result;
380
+ try {
381
+ result = paginateSlides(input, options, "continueOverfull", options.maxSlides ?? 1e4, (slide, slideOptions, index) => {
382
+ const units = blockUnits(slide);
383
+ if (!units) return void 0;
384
+ try {
385
+ const split = paginateSlide(slide, { ...slideOptions, wholeBlocks: true, minFontSize: options.minFontSize });
386
+ if (split.slides.length < 2) return void 0;
387
+ found.set(index, units);
388
+ return split;
389
+ } catch (error) {
390
+ if (error instanceof OPFPaginationError || error instanceof OPFCompositionError) return void 0;
391
+ throw error;
392
+ }
393
+ });
394
+ } catch (error) {
395
+ if (error instanceof OPFPaginationError) return { presentation: clone(input), continued: [], layout };
396
+ throw error;
397
+ }
398
+ const continued = result.splits.map(({ sourceSlideIndex, outputStart, count }) => {
399
+ const pages = result.pages.filter((page) => page.sourceSlideIndex === sourceSlideIndex);
400
+ const blocks = pages.map((page) => [...new Set(page.mappings.map((mapping) => /^slides\.\d+\.blocks\.(\d+)/.exec(mapping.sourcePath)?.[1]).filter((value) => value !== void 0).map(Number))]);
401
+ const { kind, units } = found.get(sourceSlideIndex);
402
+ return { sourceSlideIndex, slideIndices: Array.from({ length: count }, (_, page) => outputStart + page), kind, blocks, units: blocks.map((page) => units.filter((unit) => page.includes(unit[0])).length), pages };
403
+ });
404
+ return { presentation: result.presentation, continued, layout };
405
+ }
406
+ function continuationPages(result, slideCount) {
407
+ if (!Number.isInteger(slideCount) || slideCount < 0) throw new RangeError("slideCount must be a whole number of source slides.");
408
+ const bySource = new Map(result.continued.map((entry) => [entry.sourceSlideIndex, entry.slideIndices]));
409
+ const pages = [];
410
+ let output = 0;
411
+ for (let index = 0; index < slideCount; index++) {
412
+ const indices = bySource.get(index) ?? [output];
413
+ pages.push([...indices]);
414
+ output = indices.at(-1) + 1;
415
+ }
416
+ return pages;
417
+ }
418
+ function paginateSlides(input, options, name, maxSlides, split) {
419
+ checkCatalogsOption(options.catalogs, name);
286
420
  assertValid(input, { only: ["format"] });
287
421
  const presentation = clone(input);
288
- const maxSlides = options.maxSlides ?? 100;
289
422
  if (!Number.isInteger(maxSlides) || maxSlides < 1 || maxSlides > 1e4) throw new RangeError("maxSlides must be an integer between 1 and 10000.");
290
423
  const authoredIds = presentation.slides.flatMap((slide) => slideIds(slide));
291
424
  const reported = /* @__PURE__ */ new Set();
292
425
  const run = (slideCount2) => {
293
426
  const output2 = [], pages2 = [], reservedIds = [...authoredIds];
427
+ const splits2 = [];
294
428
  presentation.slides.forEach((slide, index) => {
295
429
  const context = resolveSlideContext(presentation, index, { slideNumber: output2.length + 1, slideCount: slideCount2, date: options.date, ...options.catalogs ? { catalogs: options.catalogs } : {}, ...options.strictReferences ? { strictReferences: true } : {} });
296
430
  for (const diagnostic of context.diagnostics) {
@@ -301,8 +435,14 @@ function paginate(input, options = {}) {
301
435
  }
302
436
  }
303
437
  if (output2.length >= maxSlides) throw new OPFPaginationError(`Pagination needs more than ${maxSlides} slides. No partial result was returned.`);
304
- const result2 = paginateSlide(slide, { ...context.options, textRasterPadding: options.textRasterPadding, fonts: options.fonts, ...options.catalogs ? { catalogs: options.catalogs } : {}, presentation, slideIndex: index, slideNumber: output2.length + 1, slideCount: slideCount2, date: options.date, maxSlides: maxSlides - output2.length, minFontSize: options.minFontSize, reservedIds });
438
+ const slideOptions = { ...context.options, textRasterPadding: options.textRasterPadding, fonts: options.fonts, ...options.catalogs ? { catalogs: options.catalogs } : {}, presentation, slideIndex: index, slideNumber: output2.length + 1, slideCount: slideCount2, date: options.date, maxSlides: maxSlides - output2.length, minFontSize: options.minFontSize, reservedIds };
439
+ const result2 = split(slide, slideOptions, index);
440
+ if (!result2) {
441
+ output2.push(slide);
442
+ return;
443
+ }
305
444
  const outputStart = output2.length;
445
+ if (result2.slides.length > 1) splits2.push({ sourceSlideIndex: index, outputStart, count: result2.slides.length });
306
446
  result2.pages.forEach((page, pageIndex) => {
307
447
  const remap = (mapping) => ({ ...mapping, outputPath: mapping.outputPath.replace(/^slides\.\d+/, `slides.${outputStart + pageIndex}`) });
308
448
  pages2.push({ sourceSlideIndex: index, slideIndex: outputStart + pageIndex, mappings: page.mappings.map(remap), ...page.repeatedMappings ? { repeatedMappings: page.repeatedMappings.map(remap) } : {} });
@@ -310,7 +450,7 @@ function paginate(input, options = {}) {
310
450
  output2.push(...result2.slides);
311
451
  reservedIds.push(...result2.slides.flatMap((slide2) => slideIds(slide2)));
312
452
  });
313
- return { output: output2, pages: pages2 };
453
+ return { output: output2, pages: pages2, splits: splits2 };
314
454
  };
315
455
  const usesSlideCount = usesSlideBuiltin(presentation, "deck.slideCount");
316
456
  let slideCount = presentation.slides.length, result = run(slideCount);
@@ -319,10 +459,10 @@ function paginate(input, options = {}) {
319
459
  slideCount = result.output.length;
320
460
  result = run(slideCount);
321
461
  }
322
- const { output, pages } = result;
462
+ const { output, pages, splits } = result;
323
463
  presentation.slides = output;
324
464
  assertValid(presentation, { only: ["format"] });
325
- return { presentation, pages, layout: options.fonts ? "measured" : "estimated" };
465
+ return { presentation, pages, splits };
326
466
  }
327
467
 
328
- export { OPFPaginationError, paginate, paginateSlide };
468
+ export { OPFPaginationError, blockUnits, continuationPages, continueOverfull, paginate, paginateSlide };