odf.js 5.1.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,777 @@
1
+ import { parseOdfLength } from "./typed/shared/units.js";
2
+ import { attrValue, childrenWithTag, elementsWithTag, findChildElement, rootElement } from "./xml/query.js";
3
+ import { TableCursor, parseCellReference as parseCellReference$1 } from "./typed/shared/a1.js";
4
+ import { parseMargins, parsePageSize } from "./typed/shared/geometry.js";
5
+ import { findStyleElement, resolveStyleElementChain } from "./typed/shared/cascade.js";
6
+ import { readOdfMetadata } from "./typed/shared/metadata.js";
7
+ import { mintOdfListNumId, readOdfListParagraphs } from "./typed/shared/list.js";
8
+ import { collectOdfDataStyleDefinitions, collectOdfFieldMasterDefinitions, collectOdfFontFaceDefinitions, collectOdfNamedExpressions, collectOdfProvenanceRegions, insertOdfConstructMarkers, isOdfIndexWrapper, odfDivisionDescriptor, odfIndexControlDescriptor, odfMarkerHalfEventIndex, odfResidue, resolveOdfMarkerEvents } from "./typed/shared/constructs.js";
9
+ import { readOdfParagraph } from "./typed/shared/paragraph.js";
10
+ import { readCellStyleDecoration, readOdfTable } from "./typed/shared/table.js";
11
+ import { parseOdfTransform } from "./typed/shared/transform.js";
12
+ import { resolvePageLayoutProperties } from "./typed/shared/masterpage.js";
13
+ import { readDrawFrame } from "./typed/draw/shapes.js";
14
+ import { findMathRoot, readOdfFormulaContent } from "./typed/formula/read.js";
15
+ import { subDocumentPackage } from "./typed/odb/subdocument.js";
16
+ import { readOdgContent } from "./typed/odg/read.js";
17
+ import { readOdpContent } from "./typed/odp/read.js";
18
+ import { readOdfFormControlConstructs } from "./typed/shared/forms.js";
19
+ import { PAGE_SIZE_A4, assemblePackage } from "document-schema.js";
20
+ //#region src/typed/ods/read.ts
21
+ const CONTENT_PART$2 = "content.xml";
22
+ function parseKnownOdfLength$1(value) {
23
+ const parsed = parseOdfLength(value);
24
+ if (parsed === void 0) throw new Error(`readOdsContent: internal error -- "${value}" is not a valid ODF length literal`);
25
+ return parsed;
26
+ }
27
+ const DEFAULT_MARGIN_PT$1 = parseKnownOdfLength$1("2cm");
28
+ const DEFAULT_MARGINS$1 = {
29
+ topPt: DEFAULT_MARGIN_PT$1,
30
+ rightPt: DEFAULT_MARGIN_PT$1,
31
+ bottomPt: DEFAULT_MARGIN_PT$1,
32
+ leftPt: DEFAULT_MARGIN_PT$1
33
+ };
34
+ function readRepeatCount(element, attrName) {
35
+ const raw = attrValue(element, attrName);
36
+ if (raw === void 0) return 1;
37
+ const parsed = Number.parseInt(raw, 10);
38
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 1;
39
+ }
40
+ function isHidden(element) {
41
+ return attrValue(element, "table:visibility") === "collapse";
42
+ }
43
+ const DEFAULT_COLUMN_WIDTH_PT = 64;
44
+ const DEFAULT_ROW_HEIGHT_PT = 15;
45
+ function readColumnLayout(columnElement, pkg) {
46
+ const styleName = attrValue(columnElement, "table:style-name");
47
+ const styleElement = styleName === void 0 ? void 0 : findStyleElement(styleName, "table-column", pkg);
48
+ const properties = styleElement === void 0 ? void 0 : childrenWithTag(styleElement, "style:table-column-properties")[0];
49
+ const widthValue = properties === void 0 ? void 0 : attrValue(properties, "style:column-width");
50
+ return {
51
+ widthPt: widthValue === void 0 ? DEFAULT_COLUMN_WIDTH_PT : parseOdfLength(widthValue) ?? DEFAULT_COLUMN_WIDTH_PT,
52
+ manualBreak: (properties === void 0 ? void 0 : attrValue(properties, "fo:break-before")) === "page"
53
+ };
54
+ }
55
+ function readRowLayout(rowElement, pkg) {
56
+ const styleName = attrValue(rowElement, "table:style-name");
57
+ const styleElement = styleName === void 0 ? void 0 : findStyleElement(styleName, "table-row", pkg);
58
+ const properties = styleElement === void 0 ? void 0 : childrenWithTag(styleElement, "style:table-row-properties")[0];
59
+ const heightValue = properties === void 0 ? void 0 : attrValue(properties, "style:row-height");
60
+ return {
61
+ heightPt: heightValue === void 0 ? DEFAULT_ROW_HEIGHT_PT : parseOdfLength(heightValue) ?? DEFAULT_ROW_HEIGHT_PT,
62
+ manualBreak: (properties === void 0 ? void 0 : attrValue(properties, "fo:break-before")) === "page"
63
+ };
64
+ }
65
+ function readCellText(cellElement, pkg) {
66
+ const paragraphs = childrenWithTag(cellElement, "text:p");
67
+ const runs = [];
68
+ paragraphs.forEach((paragraph, index) => {
69
+ if (index > 0) runs.push({ text: "\n" });
70
+ runs.push(...readOdfParagraph(paragraph, pkg).runs);
71
+ });
72
+ return {
73
+ runs,
74
+ displayText: runs.map((run) => run.text).join("")
75
+ };
76
+ }
77
+ function readCellValue(cellElement, displayText) {
78
+ const valueType = attrValue(cellElement, "office:value-type");
79
+ const stringFallback = {
80
+ kind: "string",
81
+ value: displayText
82
+ };
83
+ switch (valueType) {
84
+ case "float": {
85
+ const value = parseRequiredNumber(attrValue(cellElement, "office:value"));
86
+ return value === void 0 ? stringFallback : {
87
+ kind: "number",
88
+ value
89
+ };
90
+ }
91
+ case "percentage": {
92
+ const value = parseRequiredNumber(attrValue(cellElement, "office:value"));
93
+ return value === void 0 ? stringFallback : {
94
+ kind: "percentage",
95
+ value
96
+ };
97
+ }
98
+ case "currency": {
99
+ const value = parseRequiredNumber(attrValue(cellElement, "office:value"));
100
+ if (value === void 0) return stringFallback;
101
+ const currency = attrValue(cellElement, "office:currency");
102
+ return currency === void 0 ? {
103
+ kind: "currency",
104
+ value
105
+ } : {
106
+ kind: "currency",
107
+ value,
108
+ currency
109
+ };
110
+ }
111
+ case "boolean": {
112
+ const raw = attrValue(cellElement, "office:boolean-value");
113
+ return raw === void 0 ? stringFallback : {
114
+ kind: "boolean",
115
+ value: raw === "true"
116
+ };
117
+ }
118
+ case "date": return {
119
+ kind: "date",
120
+ value: attrValue(cellElement, "office:date-value") ?? displayText
121
+ };
122
+ case "time": return {
123
+ kind: "time",
124
+ value: attrValue(cellElement, "office:time-value") ?? displayText
125
+ };
126
+ case "string": return {
127
+ kind: "string",
128
+ value: attrValue(cellElement, "office:string-value") ?? displayText
129
+ };
130
+ default: return { kind: "empty" };
131
+ }
132
+ }
133
+ function parseRequiredNumber(raw) {
134
+ if (raw === void 0) return;
135
+ const value = Number(raw);
136
+ return Number.isNaN(value) ? void 0 : value;
137
+ }
138
+ function parsePrintRanges(value) {
139
+ const first = value.split(" ").find((part) => part.length > 0);
140
+ if (first === void 0) return;
141
+ const separatorIndex = first.indexOf(":");
142
+ if (separatorIndex === -1) return;
143
+ const start = parseA1WithOptionalSheetPrefix(first.slice(0, separatorIndex));
144
+ const end = parseA1WithOptionalSheetPrefix(first.slice(separatorIndex + 1));
145
+ if (start === void 0 || end === void 0) return;
146
+ return {
147
+ startRow: start.row,
148
+ startColumn: start.column,
149
+ endRow: end.row,
150
+ endColumn: end.column
151
+ };
152
+ }
153
+ function parseA1WithOptionalSheetPrefix(cellPart) {
154
+ const dotIndex = cellPart.lastIndexOf(".");
155
+ const bareReference = dotIndex === -1 ? cellPart : cellPart.slice(dotIndex + 1);
156
+ return parseCellReference$1(bareReference);
157
+ }
158
+ function parseScalePercentage(value) {
159
+ const match = /^(\d+(?:\.\d+)?)%$/.exec(value);
160
+ if (match === null) return;
161
+ const numeric = match[1];
162
+ return numeric === void 0 ? void 0 : Number(numeric);
163
+ }
164
+ function parseNonNegativeInteger(value) {
165
+ if (value === void 0) return;
166
+ const parsed = Number.parseInt(value, 10);
167
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : void 0;
168
+ }
169
+ function collectAnchoredFrame(frameElement, groupFunctions, pkg, anchorRow, anchorColumn, images, embeddedObjects) {
170
+ const shape = readDrawFrame(frameElement, groupFunctions, pkg);
171
+ if (shape === void 0) return;
172
+ const reference = readDrawObjectReference(frameElement, pkg);
173
+ if (reference !== void 0) {
174
+ const { document, residue } = readEmbeddedObjectDocument(reference, shape.frame, "ods");
175
+ const object = {
176
+ objectKind: reference.objectKind,
177
+ document,
178
+ frame: shape.frame,
179
+ anchorRow,
180
+ anchorColumn,
181
+ offsetXPt: shape.frame.xPt,
182
+ offsetYPt: shape.frame.yPt
183
+ };
184
+ if (residue !== void 0) object.source = residue;
185
+ embeddedObjects.push(object);
186
+ return;
187
+ }
188
+ for (const block of shape.blocks) if (block.kind === "image") images.push({
189
+ ...block,
190
+ anchorRow,
191
+ anchorColumn,
192
+ offsetXPt: shape.frame.xPt,
193
+ offsetYPt: shape.frame.yPt
194
+ });
195
+ }
196
+ function collectAnchoredFrames(children, groupFunctions, pkg, anchorRow, anchorColumn, images, embeddedObjects) {
197
+ for (const child of children) {
198
+ if (child.type !== "element") continue;
199
+ if (child.tag === "draw:frame") collectAnchoredFrame(child, groupFunctions, pkg, anchorRow, anchorColumn, images, embeddedObjects);
200
+ else if (child.tag === "draw:g") {
201
+ const ownValue = attrValue(child, "draw:transform");
202
+ const ownFunctions = ownValue === void 0 ? [] : parseOdfTransform(ownValue);
203
+ const nested = ownFunctions.length === 0 ? groupFunctions : [...ownFunctions, ...groupFunctions];
204
+ collectAnchoredFrames(child.children, nested, pkg, anchorRow, anchorColumn, images, embeddedObjects);
205
+ }
206
+ }
207
+ }
208
+ function readTable(tableElement, pkg) {
209
+ const columns = [];
210
+ const rows = [];
211
+ const cells = [];
212
+ const images = [];
213
+ const embeddedObjects = [];
214
+ const manualBreakRows = [];
215
+ const manualBreakColumns = [];
216
+ let repeatColumns;
217
+ let repeatRows;
218
+ let columnCursor = 0;
219
+ const cursor = new TableCursor();
220
+ function processColumn(columnElement) {
221
+ const { widthPt, manualBreak } = readColumnLayout(columnElement, pkg);
222
+ columns.push({
223
+ index: columnCursor,
224
+ widthPt,
225
+ hidden: isHidden(columnElement) ? true : void 0
226
+ });
227
+ if (manualBreak) manualBreakColumns.push(columnCursor);
228
+ columnCursor += readRepeatCount(columnElement, "table:number-columns-repeated");
229
+ }
230
+ function processRowCells(rowElement) {
231
+ for (const child of rowElement.children) {
232
+ if (child.type !== "element") continue;
233
+ if (child.tag === "table:covered-table-cell") cursor.nextCell(readRepeatCount(child, "table:number-columns-repeated"));
234
+ else if (child.tag === "table:table-cell") {
235
+ const columnIndex = cursor.columnIndex;
236
+ const rowIndex = cursor.rowIndex;
237
+ cursor.nextCell(readRepeatCount(child, "table:number-columns-repeated"));
238
+ collectAnchoredFrames(child.children, [], pkg, rowIndex, columnIndex, images, embeddedObjects);
239
+ const formula = attrValue(child, "table:formula");
240
+ const { runs, displayText } = readCellText(child, pkg);
241
+ if (!(attrValue(child, "office:value-type") !== void 0) && formula === void 0 && displayText.length === 0) continue;
242
+ const value = readCellValue(child, displayText);
243
+ const colSpan = parseNonNegativeInteger(attrValue(child, "table:number-columns-spanned"));
244
+ const rowSpan = parseNonNegativeInteger(attrValue(child, "table:number-rows-spanned"));
245
+ const cell = {
246
+ row: rowIndex,
247
+ column: columnIndex,
248
+ value,
249
+ displayText
250
+ };
251
+ if (formula !== void 0) cell.formula = formula;
252
+ if (runs.length > 0) cell.runs = runs;
253
+ if (colSpan !== void 0) cell.colSpan = colSpan;
254
+ if (rowSpan !== void 0) cell.rowSpan = rowSpan;
255
+ const cellStyleName = attrValue(child, "table:style-name");
256
+ const { elements: cellStyleChain } = resolveStyleElementChain(cellStyleName, "table-cell", pkg);
257
+ const decoration = readCellStyleDecoration(cellStyleChain);
258
+ if (decoration.background !== void 0) cell.background = decoration.background;
259
+ if (decoration.borders !== void 0) cell.borders = decoration.borders;
260
+ if (decoration.alignment !== void 0) cell.alignment = decoration.alignment;
261
+ if (decoration.verticalAlignment !== void 0) cell.verticalAlignment = decoration.verticalAlignment;
262
+ cells.push(cell);
263
+ }
264
+ }
265
+ }
266
+ function processRow(rowElement) {
267
+ const startIndex = cursor.rowIndex;
268
+ processRowCells(rowElement);
269
+ const { heightPt, manualBreak } = readRowLayout(rowElement, pkg);
270
+ rows.push({
271
+ index: startIndex,
272
+ heightPt,
273
+ hidden: isHidden(rowElement) ? true : void 0
274
+ });
275
+ if (manualBreak) manualBreakRows.push(startIndex);
276
+ cursor.nextRow(readRepeatCount(rowElement, "table:number-rows-repeated"));
277
+ }
278
+ for (const child of tableElement.children) {
279
+ if (child.type !== "element") continue;
280
+ if (child.tag === "table:shapes") collectAnchoredFrames(child.children, [], pkg, 0, 0, images, embeddedObjects);
281
+ else if (child.tag === "table:table-column") processColumn(child);
282
+ else if (child.tag === "table:table-header-columns") {
283
+ const startIndex = columnCursor;
284
+ for (const headerChild of child.children) if (headerChild.type === "element" && headerChild.tag === "table:table-column") processColumn(headerChild);
285
+ if (columnCursor > startIndex) repeatColumns = {
286
+ start: startIndex,
287
+ end: columnCursor - 1
288
+ };
289
+ } else if (child.tag === "table:table-row") processRow(child);
290
+ else if (child.tag === "table:table-header-rows") {
291
+ const startIndex = cursor.rowIndex;
292
+ for (const headerChild of child.children) if (headerChild.type === "element" && headerChild.tag === "table:table-row") processRow(headerChild);
293
+ if (cursor.rowIndex > startIndex) repeatRows = {
294
+ start: startIndex,
295
+ end: cursor.rowIndex - 1
296
+ };
297
+ }
298
+ }
299
+ return {
300
+ columns,
301
+ rows,
302
+ cells,
303
+ images,
304
+ embeddedObjects,
305
+ repeatColumns,
306
+ repeatRows,
307
+ manualBreakRows,
308
+ manualBreakColumns
309
+ };
310
+ }
311
+ function readPrintSettings(tableElement, pkg, repeatColumns, repeatRows, manualBreakRows, manualBreakColumns) {
312
+ const tableStyleName = attrValue(tableElement, "table:style-name");
313
+ const tableStyleElement = tableStyleName === void 0 ? void 0 : findStyleElement(tableStyleName, "table", pkg);
314
+ const masterPageName = tableStyleElement === void 0 ? void 0 : attrValue(tableStyleElement, "style:master-page-name");
315
+ const layoutProperties = resolvePageLayoutProperties(pkg, masterPageName);
316
+ const pageSize = layoutProperties === void 0 ? void 0 : parsePageSize(layoutProperties);
317
+ const margins = layoutProperties === void 0 ? void 0 : parseMargins(layoutProperties);
318
+ const printTokens = new Set((layoutProperties === void 0 ? void 0 : attrValue(layoutProperties, "style:print"))?.split(" ").filter((token) => token.length > 0));
319
+ const pageOrder = (layoutProperties === void 0 ? void 0 : attrValue(layoutProperties, "style:print-page-order")) === "ltr" ? "overThenDown" : "downThenOver";
320
+ const scaleToRaw = layoutProperties === void 0 ? void 0 : attrValue(layoutProperties, "style:scale-to");
321
+ const scale = scaleToRaw === void 0 ? void 0 : parseScalePercentage(scaleToRaw);
322
+ const scaleToXRaw = layoutProperties === void 0 ? void 0 : attrValue(layoutProperties, "style:scale-to-X");
323
+ const scaleToYRaw = layoutProperties === void 0 ? void 0 : attrValue(layoutProperties, "style:scale-to-Y");
324
+ const fitWidth = parseNonNegativeInteger(scaleToXRaw);
325
+ const fitHeight = parseNonNegativeInteger(scaleToYRaw);
326
+ const fitToPages = fitWidth === void 0 || fitHeight === void 0 ? void 0 : {
327
+ width: fitWidth,
328
+ height: fitHeight
329
+ };
330
+ const printRangesRaw = attrValue(tableElement, "table:print-ranges");
331
+ const printRange = printRangesRaw === void 0 ? void 0 : parsePrintRanges(printRangesRaw);
332
+ const manualBreaks = manualBreakRows.length > 0 || manualBreakColumns.length > 0 ? {
333
+ rows: manualBreakRows,
334
+ columns: manualBreakColumns
335
+ } : void 0;
336
+ const settings = {
337
+ pageSize: pageSize ?? PAGE_SIZE_A4,
338
+ margins: margins ?? DEFAULT_MARGINS$1,
339
+ gridlines: printTokens.has("grid"),
340
+ headers: printTokens.has("headers"),
341
+ pageOrder
342
+ };
343
+ if (printRange !== void 0) settings.printRange = printRange;
344
+ if (scale !== void 0) settings.scalePercent = scale;
345
+ if (fitToPages !== void 0) settings.fitToPages = fitToPages;
346
+ if (repeatRows !== void 0) settings.repeatRows = repeatRows;
347
+ if (repeatColumns !== void 0) settings.repeatColumns = repeatColumns;
348
+ if (manualBreaks !== void 0) settings.manualBreaks = manualBreaks;
349
+ return settings;
350
+ }
351
+ function readSheet(tableElement, pkg) {
352
+ const name = attrValue(tableElement, "table:name");
353
+ if (name === void 0) return;
354
+ const { columns, rows, cells, images, embeddedObjects, repeatColumns, repeatRows, manualBreakRows, manualBreakColumns } = readTable(tableElement, pkg);
355
+ const sheet = {
356
+ name,
357
+ cells,
358
+ columns,
359
+ rows,
360
+ images,
361
+ printSettings: readPrintSettings(tableElement, pkg, repeatColumns, repeatRows, manualBreakRows, manualBreakColumns)
362
+ };
363
+ if (embeddedObjects.length > 0) sheet.embeddedObjects = embeddedObjects;
364
+ return sheet;
365
+ }
366
+ function readOdsContent(pkg) {
367
+ const contentPart = pkg.parts[CONTENT_PART$2];
368
+ const root = contentPart?.kind === "xml" ? rootElement(contentPart.nodes) : void 0;
369
+ const body = root === void 0 ? void 0 : findChildElement(root.children, "office:body");
370
+ const spreadsheet = body === void 0 ? void 0 : findChildElement(body.children, "office:spreadsheet");
371
+ const tables = spreadsheet === void 0 ? [] : childrenWithTag(spreadsheet, "table:table");
372
+ const sheets = [];
373
+ for (const table of tables) {
374
+ const sheet = readSheet(table, pkg);
375
+ if (sheet !== void 0) sheets.push(sheet);
376
+ }
377
+ const definitions = {};
378
+ if (spreadsheet !== void 0) collectOdfNamedExpressions(spreadsheet.children, definitions);
379
+ return {
380
+ metadata: readOdfMetadata(pkg),
381
+ sheets,
382
+ ...Object.keys(definitions).length > 0 ? { definitions } : {}
383
+ };
384
+ }
385
+ function readOds(pkg) {
386
+ const { metadata, sheets, definitions } = readOdsContent(pkg);
387
+ const assembled = assemblePackage({
388
+ kind: "spreadsheet",
389
+ metadata,
390
+ sheets
391
+ });
392
+ if (definitions !== void 0) assembled.definitions = definitions;
393
+ return assembled;
394
+ }
395
+ //#endregion
396
+ //#region src/typed/odt/read.ts
397
+ const CONTENT_PART$1 = "content.xml";
398
+ const STYLES_PART = "styles.xml";
399
+ const AUTOMATIC_STYLE_PARTS = [CONTENT_PART$1, STYLES_PART];
400
+ function readOutlineLevel(headingElement) {
401
+ const raw = attrValue(headingElement, "text:outline-level");
402
+ if (raw === void 0) return 1;
403
+ const parsed = Number.parseInt(raw, 10);
404
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 1;
405
+ }
406
+ function readParagraphOrHeading(element, paragraph) {
407
+ if (element.tag === "text:h") {
408
+ const outlineLevel = readOutlineLevel(element);
409
+ paragraph.styleId = `Heading${outlineLevel}`;
410
+ paragraph.headingLevel = outlineLevel;
411
+ }
412
+ return paragraph;
413
+ }
414
+ function readAnchoredFrameSources(paragraphElement, pkg, state) {
415
+ if (!state.liftFrames) return [];
416
+ const sources = [];
417
+ const readFrameInto = (blocks, frameElement) => {
418
+ const shape = readDrawFrame(frameElement, [], pkg, state.listIdState, true);
419
+ if (shape === void 0) return;
420
+ const reference = readDrawObjectReference(frameElement, pkg);
421
+ if (reference !== void 0) {
422
+ const { document, residue } = readEmbeddedObjectDocument(reference, shape.frame, "odt");
423
+ const embeddedBlock = {
424
+ kind: "embeddedObject",
425
+ objectKind: reference.objectKind,
426
+ document,
427
+ frame: shape.frame
428
+ };
429
+ if (residue !== void 0) embeddedBlock.source = residue;
430
+ blocks.push(embeddedBlock);
431
+ return;
432
+ }
433
+ blocks.push(...shape.blocks);
434
+ };
435
+ for (const child of paragraphElement.children) {
436
+ if (child.type !== "element") continue;
437
+ if (child.tag === "draw:frame") {
438
+ const blocks = [];
439
+ readFrameInto(blocks, child);
440
+ if (blocks.length > 0) sources.push({
441
+ child,
442
+ blocks
443
+ });
444
+ } else if (child.tag === "draw:g") {
445
+ const blocks = [];
446
+ for (const grandChild of child.children) if (grandChild.type === "element" && grandChild.tag === "draw:frame") readFrameInto(blocks, grandChild);
447
+ if (blocks.length > 0) sources.push({
448
+ child,
449
+ blocks
450
+ });
451
+ }
452
+ }
453
+ return sources;
454
+ }
455
+ function liftedBlocksBeforeHalf(read, half) {
456
+ const halfIndex = read.element.children.indexOf(half);
457
+ if (halfIndex === -1) return 0;
458
+ let count = 0;
459
+ for (const source of read.liftedSources) if (read.element.children.indexOf(source.child) < halfIndex) count += source.blocks.length;
460
+ return count;
461
+ }
462
+ function readBlocks(nodes, pkg, state, baseIndex = 0) {
463
+ const blocks = [];
464
+ const emitParagraphs = (reads) => {
465
+ let cursor = baseIndex + blocks.length;
466
+ for (const read of reads) {
467
+ const lifted = read.liftedSources.flatMap((source) => source.blocks);
468
+ for (const half of read.halves) {
469
+ const eventIndex = odfMarkerHalfEventIndex(half, read.element, cursor, liftedBlocksBeforeHalf(read, half.element));
470
+ if (eventIndex !== void 0) state.markerEvents.push({
471
+ kind: half.kind,
472
+ side: half.side,
473
+ key: half.key,
474
+ index: eventIndex,
475
+ qualified: true,
476
+ order: state.order++,
477
+ descriptor: half.descriptor,
478
+ element: half.element
479
+ });
480
+ }
481
+ blocks.push(read.paragraph);
482
+ for (const block of lifted) blocks.push(block);
483
+ cursor += 1 + lifted.length;
484
+ }
485
+ };
486
+ const readOneParagraph = (element) => {
487
+ const halves = [];
488
+ return {
489
+ element,
490
+ paragraph: readParagraphOrHeading(element, readOdfParagraph(element, pkg, {
491
+ provenanceRegions: state.provenanceRegions,
492
+ markersOut: halves,
493
+ definitions: state.definitions,
494
+ listIdState: state.listIdState,
495
+ format: "odt"
496
+ })),
497
+ halves,
498
+ liftedSources: readAnchoredFrameSources(element, pkg, state)
499
+ };
500
+ };
501
+ for (const node of nodes) {
502
+ if (node.type !== "element") continue;
503
+ if (node.tag === "text:p" || node.tag === "text:h") emitParagraphs([readOneParagraph(node)]);
504
+ else if (node.tag === "text:list") {
505
+ const numId = mintOdfListNumId(pkg, node, state.listIdState);
506
+ const reads = [];
507
+ readOdfListParagraphs(node, {
508
+ numId,
509
+ level: 0
510
+ }, (element) => {
511
+ const read = readOneParagraph(element);
512
+ reads.push(read);
513
+ return read.paragraph;
514
+ });
515
+ emitParagraphs(reads);
516
+ } else if (node.tag === "table:table") blocks.push(readOdfTable(node, pkg));
517
+ else if (node.tag === "text:section") {
518
+ const startIndex = baseIndex + blocks.length;
519
+ const order = state.order++;
520
+ blocks.push(...readBlocks(node.children, pkg, state, startIndex));
521
+ state.wrapperExtents.push({
522
+ startIndex,
523
+ endIndex: baseIndex + blocks.length,
524
+ order,
525
+ descriptor: odfDivisionDescriptor(node, pkg)
526
+ });
527
+ } else if (isOdfIndexWrapper(node)) {
528
+ const startIndex = baseIndex + blocks.length;
529
+ const order = state.order++;
530
+ const body = node.children.find((child) => child.type === "element" && child.tag === "text:index-body");
531
+ blocks.push(...body === void 0 ? [] : readBlocks(body.children, pkg, state, startIndex));
532
+ state.wrapperExtents.push({
533
+ startIndex,
534
+ endIndex: baseIndex + blocks.length,
535
+ order,
536
+ descriptor: odfIndexControlDescriptor(node)
537
+ });
538
+ } else if (node.tag === "text:index-title") blocks.push(...readBlocks(node.children, pkg, state, baseIndex + blocks.length));
539
+ else if (node.tag === "office:forms") blocks.push(...readOdfFormControlConstructs(node, "odt"));
540
+ }
541
+ return blocks;
542
+ }
543
+ function parseKnownOdfLength(value) {
544
+ const parsed = parseOdfLength(value);
545
+ if (parsed === void 0) throw new Error(`readOdtContent: internal error -- "${value}" is not a valid ODF length literal`);
546
+ return parsed;
547
+ }
548
+ const DEFAULT_MARGIN_PT = parseKnownOdfLength("2cm");
549
+ const DEFAULT_MARGINS = {
550
+ topPt: DEFAULT_MARGIN_PT,
551
+ rightPt: DEFAULT_MARGIN_PT,
552
+ bottomPt: DEFAULT_MARGIN_PT,
553
+ leftPt: DEFAULT_MARGIN_PT
554
+ };
555
+ function findPageLayoutElement(pkg, pageLayoutName) {
556
+ if (pageLayoutName === void 0) return;
557
+ for (const partPath of AUTOMATIC_STYLE_PARTS) {
558
+ const part = pkg.parts[partPath];
559
+ if (part?.kind !== "xml") continue;
560
+ const root = rootElement(part.nodes);
561
+ const automaticStyles = root === void 0 ? void 0 : findChildElement(root.children, "office:automatic-styles");
562
+ if (automaticStyles === void 0) continue;
563
+ const found = childrenWithTag(automaticStyles, "style:page-layout").find((element) => attrValue(element, "style:name") === pageLayoutName);
564
+ if (found !== void 0) return found;
565
+ }
566
+ }
567
+ function readFirstMasterPageGeometry(pkg) {
568
+ const stylesPart = pkg.parts[STYLES_PART];
569
+ const stylesRoot = stylesPart?.kind === "xml" ? rootElement(stylesPart.nodes) : void 0;
570
+ const masterStyles = stylesRoot === void 0 ? void 0 : findChildElement(stylesRoot.children, "office:master-styles");
571
+ const masterPage = masterStyles === void 0 ? void 0 : findChildElement(masterStyles.children, "style:master-page");
572
+ const layout = findPageLayoutElement(pkg, masterPage === void 0 ? void 0 : attrValue(masterPage, "style:page-layout-name"));
573
+ const properties = layout === void 0 ? void 0 : findChildElement(layout.children, "style:page-layout-properties");
574
+ const pageSize = properties === void 0 ? void 0 : parsePageSize(properties);
575
+ const margins = properties === void 0 ? void 0 : parseMargins(properties);
576
+ return {
577
+ pageSize: pageSize ?? PAGE_SIZE_A4,
578
+ margins: margins ?? DEFAULT_MARGINS
579
+ };
580
+ }
581
+ function readOdtContent(pkg, options = {}) {
582
+ const contentPart = pkg.parts[CONTENT_PART$1];
583
+ if (contentPart?.kind !== "xml") throw new Error(`readOdtContent: package has no ${CONTENT_PART$1} part`);
584
+ const contentRoot = rootElement(contentPart.nodes);
585
+ const body = contentRoot === void 0 ? void 0 : findChildElement(contentRoot.children, "office:body");
586
+ const textElement = body === void 0 ? void 0 : findChildElement(body.children, "office:text");
587
+ if (textElement === void 0) throw new Error(`readOdtContent: ${CONTENT_PART$1} has no office:body/office:text element`);
588
+ const metadata = readOdfMetadata(pkg);
589
+ const { pageSize, margins } = readFirstMasterPageGeometry(pkg);
590
+ const provenanceRegions = /* @__PURE__ */ new Map();
591
+ collectOdfProvenanceRegions(textElement.children, provenanceRegions);
592
+ const definitions = {
593
+ entries: {},
594
+ nextNoteOrdinal: 1,
595
+ nextAnnotationOrdinal: 1
596
+ };
597
+ collectOdfFieldMasterDefinitions(textElement.children, definitions.entries);
598
+ for (const partPath of AUTOMATIC_STYLE_PARTS) {
599
+ const part = pkg.parts[partPath];
600
+ if (part?.kind !== "xml") continue;
601
+ collectOdfDataStyleDefinitions(part.nodes, definitions.entries);
602
+ collectOdfFontFaceDefinitions(part.nodes, definitions.entries);
603
+ }
604
+ const state = {
605
+ listIdState: { next: 1 },
606
+ provenanceRegions,
607
+ definitions,
608
+ wrapperExtents: [],
609
+ markerEvents: [],
610
+ liftFrames: options.frames !== "none",
611
+ order: 0
612
+ };
613
+ const walked = readBlocks(textElement.children, pkg, state);
614
+ const { extents: markerExtents, paired } = resolveOdfMarkerEvents(state.markerEvents);
615
+ const extents = [...state.wrapperExtents, ...markerExtents];
616
+ for (const event of state.markerEvents) if (event.kind === "annotation" && event.side === "start" && !paired.has(event.element)) {
617
+ const descriptor = event.descriptor();
618
+ if (descriptor !== void 0) extents.push({
619
+ startIndex: event.index,
620
+ endIndex: event.index,
621
+ order: event.order,
622
+ descriptor
623
+ });
624
+ }
625
+ return {
626
+ metadata,
627
+ sections: [{
628
+ pageSize,
629
+ margins,
630
+ blocks: insertOdfConstructMarkers(walked, extents)
631
+ }],
632
+ ...Object.keys(definitions.entries).length > 0 ? { definitions: definitions.entries } : {}
633
+ };
634
+ }
635
+ function readOdt(pkg, options = {}) {
636
+ const { metadata, sections, definitions } = readOdtContent(pkg, options);
637
+ const assembled = assemblePackage({
638
+ kind: "wordprocessing",
639
+ metadata,
640
+ sections
641
+ });
642
+ if (definitions !== void 0) assembled.definitions = definitions;
643
+ return assembled;
644
+ }
645
+ //#endregion
646
+ //#region src/typed/draw/embedded.ts
647
+ const CONTENT_PART = "content.xml";
648
+ function embeddedKindFor(bodyChildTag) {
649
+ switch (bodyChildTag) {
650
+ case "office:text": return "wordprocessing";
651
+ case "office:spreadsheet": return "spreadsheet";
652
+ case "office:presentation": return "presentation";
653
+ case "office:drawing": return "drawing";
654
+ case "office:chart": return "chart";
655
+ default: return;
656
+ }
657
+ }
658
+ function readOdfChartContent(chartPackage, frame, format) {
659
+ const contentPart = chartPackage.parts[CONTENT_PART];
660
+ const contentRoot = contentPart?.kind === "xml" ? rootElement(contentPart.nodes) : void 0;
661
+ const chartElement = contentRoot === void 0 ? void 0 : elementsWithTag(contentRoot.children, "chart:chart")[0];
662
+ const localTable = chartElement === void 0 ? void 0 : elementsWithTag(chartElement.children, "table:table")[0];
663
+ const blocks = localTable === void 0 ? [] : [readOdfTable(localTable, chartPackage)];
664
+ return {
665
+ document: {
666
+ kind: "drawing",
667
+ metadata: {},
668
+ pages: [{
669
+ size: {
670
+ widthPt: frame.widthPt,
671
+ heightPt: frame.heightPt
672
+ },
673
+ shapes: [{
674
+ frame: {
675
+ xPt: 0,
676
+ yPt: 0,
677
+ widthPt: frame.widthPt,
678
+ heightPt: frame.heightPt
679
+ },
680
+ insetLeftPt: 0,
681
+ insetTopPt: 0,
682
+ insetRightPt: 0,
683
+ insetBottomPt: 0,
684
+ blocks
685
+ }],
686
+ vectors: []
687
+ }]
688
+ },
689
+ residue: chartElement === void 0 ? void 0 : odfResidue(format, chartElement)
690
+ };
691
+ }
692
+ function readEmbeddedObjectDocument(reference, frame, format) {
693
+ switch (reference.objectKind) {
694
+ case "wordprocessing": {
695
+ const { metadata, sections } = readOdtContent(reference.package);
696
+ return {
697
+ document: {
698
+ kind: "wordprocessing",
699
+ metadata,
700
+ sections
701
+ },
702
+ residue: void 0
703
+ };
704
+ }
705
+ case "presentation": {
706
+ const { metadata, slides } = readOdpContent(reference.package);
707
+ return {
708
+ document: {
709
+ kind: "presentation",
710
+ metadata,
711
+ slides
712
+ },
713
+ residue: void 0
714
+ };
715
+ }
716
+ case "drawing": {
717
+ const { metadata, pages } = readOdgContent(reference.package);
718
+ return {
719
+ document: {
720
+ kind: "drawing",
721
+ metadata,
722
+ pages
723
+ },
724
+ residue: void 0
725
+ };
726
+ }
727
+ case "spreadsheet": {
728
+ const { metadata, sheets } = readOdsContent(reference.package);
729
+ return {
730
+ document: {
731
+ kind: "spreadsheet",
732
+ metadata,
733
+ sheets
734
+ },
735
+ residue: void 0
736
+ };
737
+ }
738
+ case "formula": return {
739
+ document: readOdfFormulaContent(reference.package),
740
+ residue: void 0
741
+ };
742
+ case "chart": return readOdfChartContent(reference.package, frame, format);
743
+ }
744
+ }
745
+ function subDocumentKind(nodes) {
746
+ const root = rootElement(nodes);
747
+ const body = root === void 0 ? void 0 : findChildElement(root.children, "office:body");
748
+ const bodyChild = body === void 0 ? void 0 : rootElement(body.children);
749
+ const bodyKind = bodyChild === void 0 ? void 0 : embeddedKindFor(bodyChild.tag);
750
+ if (bodyKind !== void 0) return bodyKind;
751
+ return findMathRoot(nodes) === void 0 ? void 0 : "formula";
752
+ }
753
+ function normaliseObjectHref(raw) {
754
+ const withoutPrefix = raw.startsWith("./") ? raw.slice(2) : raw;
755
+ const trimmed = withoutPrefix.endsWith("/") ? withoutPrefix.slice(0, -1) : withoutPrefix;
756
+ if (trimmed.length === 0 || trimmed.startsWith("..") || trimmed.startsWith("/") || trimmed.includes("://")) return;
757
+ return trimmed;
758
+ }
759
+ function readDrawObjectReference(frame, pkg) {
760
+ const object = childrenWithTag(frame, "draw:object")[0];
761
+ if (object === void 0) return;
762
+ const rawHref = attrValue(object, "xlink:href");
763
+ const href = rawHref === void 0 ? void 0 : normaliseObjectHref(rawHref);
764
+ if (href === void 0) return;
765
+ const subPackage = subDocumentPackage(pkg, href, { allowMissingContent: true });
766
+ const contentPart = subPackage.parts[CONTENT_PART];
767
+ if (contentPart?.kind !== "xml") return;
768
+ const objectKind = subDocumentKind(contentPart.nodes);
769
+ if (objectKind === void 0) return;
770
+ return {
771
+ objectKind,
772
+ package: subPackage,
773
+ href
774
+ };
775
+ }
776
+ //#endregion
777
+ export { readOdtContent as a, readOdt as i, readEmbeddedObjectDocument as n, readOds as o, readOdfChartContent as r, readOdsContent as s, readDrawObjectReference as t };