@portone/docx-editor 0.6.1 → 0.6.3

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 (92) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/DocxEditor.js +2 -2
  3. package/dist/core.d.ts +4 -3
  4. package/dist/docx/exportDocx.d.ts +1 -1
  5. package/dist/docx/exportDocx.js +3 -1
  6. package/dist/docx/headersFooters.js +4 -14
  7. package/dist/docx/identities.d.ts +10 -2
  8. package/dist/docx/identities.js +32 -11
  9. package/dist/docx/importPolicy.d.ts +2 -2
  10. package/dist/docx/importPolicy.js +12 -5
  11. package/dist/docx/importPreserved.d.ts +3 -3
  12. package/dist/docx/importSdtBlock.d.ts +24 -0
  13. package/dist/docx/importSdtBlock.js +42 -0
  14. package/dist/docx/importTable.js +35 -24
  15. package/dist/docx/invariants.d.ts +13 -10
  16. package/dist/docx/invariants.js +269 -126
  17. package/dist/docx/newLists.js +12 -3
  18. package/dist/docx/notes/numbering.js +5 -12
  19. package/dist/docx/notes/references.d.ts +31 -0
  20. package/dist/docx/notes/references.js +32 -0
  21. package/dist/docx/notes/writing.js +5 -6
  22. package/dist/docx/sdt.d.ts +52 -9
  23. package/dist/docx/sdt.js +108 -26
  24. package/dist/docx/sections.d.ts +13 -13
  25. package/dist/docx/sections.js +34 -20
  26. package/dist/docx/serializeBlock.js +9 -1
  27. package/dist/docx/serializePreserved.d.ts +5 -1
  28. package/dist/docx/serializePreserved.js +24 -7
  29. package/dist/docx/serializeSdtBlock.d.ts +24 -0
  30. package/dist/docx/serializeSdtBlock.js +15 -0
  31. package/dist/docx/serializeTable.d.ts +8 -2
  32. package/dist/docx/serializeTable.js +14 -20
  33. package/dist/docx/story.d.ts +10 -4
  34. package/dist/docx/story.js +25 -20
  35. package/dist/docx/storyBlocks.d.ts +32 -0
  36. package/dist/docx/storyBlocks.js +65 -0
  37. package/dist/docx/storyParts.d.ts +29 -8
  38. package/dist/docx/storyParts.js +40 -15
  39. package/dist/docx/wrappers.d.ts +10 -7
  40. package/dist/docx/wrappers.js +15 -27
  41. package/dist/editor/blockControlEdits.d.ts +15 -0
  42. package/dist/editor/blockControlEdits.js +79 -0
  43. package/dist/editor/clipboard/normalizers.js +1 -1
  44. package/dist/editor/commands/exportQueries.d.ts +4 -3
  45. package/dist/editor/commands/index.d.ts +1 -1
  46. package/dist/editor/commands/lockCommands.d.ts +5 -1
  47. package/dist/editor/commands/lockCommands.js +27 -19
  48. package/dist/editor/createEditor.js +4 -0
  49. package/dist/editor/notes/noteSurface.js +4 -3
  50. package/dist/editor/plugins/controlLifecycle.d.ts +18 -0
  51. package/dist/editor/plugins/controlLifecycle.js +130 -0
  52. package/dist/editor/plugins/keymap.js +23 -5
  53. package/dist/editor/plugins/rowResize.js +2 -4
  54. package/dist/editor/stories/storyState.d.ts +2 -0
  55. package/dist/editor/stories/storyState.js +2 -0
  56. package/dist/index.d.ts +2 -2
  57. package/dist/ooxml/errors.d.ts +135 -2
  58. package/dist/ooxml/errors.js +6 -0
  59. package/dist/page/blockKinds.d.ts +24 -2
  60. package/dist/page/blockKinds.js +6 -1
  61. package/dist/page/kinds/index.d.ts +5 -0
  62. package/dist/page/kinds/index.js +2 -0
  63. package/dist/page/kinds/sdtBlockKind.d.ts +14 -0
  64. package/dist/page/kinds/sdtBlockKind.js +143 -0
  65. package/dist/page/measureBlocks.js +4 -2
  66. package/dist/page/pageDecorations.js +3 -2
  67. package/dist/page/pageLayout.d.ts +16 -15
  68. package/dist/page/pageLayout.js +134 -67
  69. package/dist/page/usePageLayout.d.ts +2 -2
  70. package/dist/page/usePageLayout.js +5 -5
  71. package/dist/schema/attrRoles.js +45 -1
  72. package/dist/schema/clipboard.js +9 -0
  73. package/dist/schema/controlAttrs.d.ts +105 -0
  74. package/dist/schema/controlAttrs.js +129 -0
  75. package/dist/schema/controlEdges.d.ts +22 -0
  76. package/dist/schema/controlEdges.js +50 -0
  77. package/dist/schema/docxSchema.d.ts +1 -1
  78. package/dist/schema/docxSchema.js +180 -37
  79. package/dist/schema/editGuard.d.ts +1 -1
  80. package/dist/schema/guards.js +2 -0
  81. package/dist/schema/locks.d.ts +22 -6
  82. package/dist/schema/locks.js +88 -47
  83. package/dist/schema/stories.d.ts +11 -3
  84. package/dist/schema/stories.js +9 -3
  85. package/dist/styles/classNames.d.ts +8 -0
  86. package/dist/styles/classNames.js +8 -0
  87. package/dist/styles.css +31 -2
  88. package/dist/table/merge.js +11 -3
  89. package/dist/table/rowResize.d.ts +9 -0
  90. package/dist/table/rowResize.js +9 -5
  91. package/dist/ui/TextMenu.js +2 -0
  92. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,83 @@
1
1
  # @portone/docx-editor
2
2
 
3
+ ## 0.6.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [#158](https://github.com/portone-io/docx-editor/pull/158) [`c946c8c`](https://github.com/portone-io/docx-editor/commit/c946c8cf82ccd4765a3897e676b64cd5ef4fe5fa) Thanks [@Deea222](https://github.com/Deea222)! - Open a block-level content control as the blocks it holds.
8
+
9
+ A `w:sdt` standing under the body or inside a table cell used to open as a placeholder: a box saying the content was preserved, with the paragraphs and tables inside it neither readable on the page nor editable. It now opens as the content it wraps, so the text of a clause held in a rich text control reads and edits like any other text, and a control holding a table holds a table. The control's own opening XML - its id, its lock, its type, its data binding - is kept whole and written back untouched, and a control nobody edited still goes out as the bytes it arrived as.
10
+
11
+ Controls nest as the file nested them, so a `w:group` around a rich text control comes back that way round, and a control inside a table cell keeps the formatting the cell dressed it with. A control that is duplicated gets an id of its own on the way out, and its data binding stays with the first copy, so two controls never edit each other.
12
+
13
+ Two kinds are still preserved whole, because opening them would let an edit write a file Word reads differently: a `w:text` control, whose content may be no more than one paragraph, and a `w:picture` control, whose content may be no more than one picture.
14
+
15
+ Locks are read off a block control but not yet enforced against an edit, and a control does not yet break across a page.
16
+
17
+ - [#160](https://github.com/portone-io/docx-editor/pull/160) [`e62e154`](https://github.com/portone-io/docx-editor/commit/e62e154e616400b702e4516544bb2176e22f3036) Thanks [@Deea222](https://github.com/Deea222)! - Hold the edge of a block-level content control, and act on the two properties that say a control does not outlive an edit.
18
+
19
+ Backspace at the start of a control's first block and Delete at the end of its last one no longer carry a paragraph out of the control or pull the block after it in; they do nothing, and the caret stays where it was. A selection running from outside a control into it, or the other way round, is refused rather than closed by moving text across the boundary. A control left holding a single empty paragraph is removed whole instead, unless its lock says it may not be deleted.
20
+
21
+ A control carrying `w:temporary` now loses its wrapper on the first edit inside it, as the specification requires, and one carrying `w:showingPlcHdr` stops claiming that what it holds is placeholder text, so a document exported after typing into it no longer shows that text as a placeholder in Word. Both go into the history with the edit that caused them, so one undo takes them back together, and a comment left on a document changes neither.
22
+
23
+ Placeholder text itself is not selected or replaced when a control stops claiming it holds a placeholder, so it is edited and deleted like any other text.
24
+
25
+ - [#164](https://github.com/portone-io/docx-editor/pull/164) [`3054980`](https://github.com/portone-io/docx-editor/commit/30549809ae6675f22523a0b83b36e4e40d8422ff) Thanks [@Deea222](https://github.com/Deea222)! - Let a kept run inside a block-level content control go when no page can hold it.
26
+
27
+ Paragraphs inside a control that ask to be kept with the next one (`w:keepNext`) closed the boundaries between them for good, so a kept run longer than a page had nowhere to part and the control ran off the sheet. Such a boundary is now closed only while a page could hold what is kept together, and let go whole where none can, which is how a run of kept paragraphs outside a control has always been treated.
28
+
29
+ - [#159](https://github.com/portone-io/docx-editor/pull/159) [`6a41b2b`](https://github.com/portone-io/docx-editor/commit/6a41b2ba2d1aa954946f6ca14bf96b8fe0008df8) Thanks [@Deea222](https://github.com/Deea222)! - Enforce the lock a block-level content control carries, and refuse edits inside a group control.
30
+
31
+ A `w:sdt` standing under the body or inside a table cell was drawn as locked when its `w:lock` said so, and was then editable and deletable anyway. Its lock is now honored the way a wrapped cell's already was: where the control locks its contents, typing, formatting and deleting inside it are refused, a partial deletion that crosses its edge is refused with them, and so is an edit made in a table the control holds. A control locked against deletion is kept even when the selection covers it from end to end, while a `contentLocked` control may still be deleted whole and no less than whole. Unlocking from the editor now reaches a block control too, leaving the control itself standing under the id the file gave it.
32
+
33
+ A control that names `w:group` refuses edits to its contents even though it states no lock, which is what the specification asks of a group (§17.5.2.17). Its own paragraphs are refused, while a control standing inside it - a text control, a cell, or another block-level control - stays editable, and the group itself may still be deleted whole. There is no lock on such a control to lift, so the editor offers none, and `selectionLock` answers the new `shut` for a selection standing there rather than `none`.
34
+
35
+ A lock reaches every control standing inside the one that carries it, so text inside an open control held by a locked cell, by a locked block control or by a locked text control is refused as well.
36
+
37
+ - [#162](https://github.com/portone-io/docx-editor/pull/162) [`c3e5b75`](https://github.com/portone-io/docx-editor/commit/c3e5b75e301454b6950e9c1f78f0562aac5cf14b) Thanks [@Deea222](https://github.com/Deea222)! - Break a block-level content control across pages, read the sections written inside one, and draw the header text it holds.
38
+
39
+ A `w:sdt` opened as a container was measured as one unbreakable block, so a control longer than a page ran off the sheet, a page break written inside it only started a page after the whole control, and a table inside one lost the row-by-row pagination it has everywhere else. A control now pages as the blocks it holds do: a page opens between any two of them, a page break cuts where it stands, a held table keeps its rows and repeated headers, and a control inside a control is parted the same way one level down. A paragraph inside a control that asks for a page of its own now gets one at every level of nesting, a keep (`w:keepNext`) holds between two blocks a control holds as well as between the control and the block after it, and a held table still asks the page it starts on for its repeated headers and one body row. The control is drawn as one box around everything it holds, so a piece of it on a continued page still reads as standing inside the control.
40
+
41
+ A paragraph inside a control may end a section, since a control holds what the body holds (§17.5.2.34). Such a paragraph's `w:sectPr` was written back untouched but drawn as nothing: the paper, the margins, the headers and the footers of everything up to it were read off the next section instead. The break is now read, so the section it closes gets its own paper, its own header and footer stories, and note numbering restarting there where the section says so. A `w:sectPr` written inside a table cell is preserved rather than read, which is what Word makes of one.
42
+
43
+ Text modelled inside a control in a header or footer part now appears in the on-page header and footer preview, along with the page numbers its fields print, and the preview follows the alignment of the first paragraph even where a control stands around it.
44
+
45
+ - [#168](https://github.com/portone-io/docx-editor/pull/168) [`7c654c9`](https://github.com/portone-io/docx-editor/commit/7c654c98aff8e33580fd009005fb8213832ed885) Thanks [@Deea222](https://github.com/Deea222)! - End a section at the paragraph inside a content control that carries its break, and read every break a control holds.
46
+
47
+ A section break written on a paragraph inside a block-level `w:sdt` now ends its section at that paragraph, as it does for a paragraph outside a control, and every break a control holds is read.
48
+ What the control holds after a break starts the next section's page, on that section's paper and under its header and footer, as Word parts the control across the next sheets, while the control stays one control in the document.
49
+ Footnote and endnote numbering that restarts per section, and the width a table is fitted to, follow the section the paragraph is in.
50
+
51
+ - [#167](https://github.com/portone-io/docx-editor/pull/167) [`8442ce6`](https://github.com/portone-io/docx-editor/commit/8442ce6956fdce772d38b60191c5b7dec3e8f48c) Thanks [@Deea222](https://github.com/Deea222)! - Draw nothing for a content control with nothing inside it.
52
+
53
+ A `w:sdt` whose `w:sdtContent` was empty, or which wrote no content element at all, used to open as a grey box saying the content was preserved. A server that answers a failed condition by leaving a tagged control empty therefore drew a box for the clause that is not there, and the reader could neither open it nor take it away. Such a control now opens as a node of its own that holds nothing and takes no room on the page, so the clause reads as the nothing the file says it is.
54
+
55
+ Everything the control states about itself is kept: its tag, its id, its lock and its data binding all ride back out untouched, and a control nobody edited goes out as the bytes it arrived as. Backspace and Delete beside it pass over it, so it goes only when it is selected whole, and then only if its lock does not say otherwise; a copy of one gets an id of its own the way every other control does.
56
+
57
+ - [#161](https://github.com/portone-io/docx-editor/pull/161) [`1865d19`](https://github.com/portone-io/docx-editor/commit/1865d19f5c881d1a195b5603b8172bb8bd7391a7) Thanks [@Deea222](https://github.com/Deea222)! - Open a table whose row stands inside a content control, instead of standing the whole table down.
58
+
59
+ A `w:sdt` around a `w:tr` used to be markup nothing read, so one such control cost every row, cell, merge and paragraph of the table it stood in: the table opened as an uneditable placeholder. The control is now read onto the row it wraps, exactly as a control around a cell has always been read onto the cell, so the table is editable and the wrapper goes back around the same row on export. A table nobody edited still goes out byte for byte, and an edit in another row rewrites the table with the control back where it stood.
60
+
61
+ The lock such a control carries is honored on the row: typing anywhere in a locked row is refused, so is a paragraph or formatting command inside it and a change to its height, while a row beside it is edited as ever. A row deletion is the control being taken away whole, which a lock against deletion refuses; a column deletion reaches into what the control holds, which a lock over its contents refuses. A `w:group` shuts a row's contents without a lock, lifting a lock reaches a row, and a row inserted beside a wrapped one carries no control, so no second control claims the first one's `w:id`.
62
+
63
+ A control the row cannot carry back out still keeps the table whole: one holding more than the single row the specification describes, one holding another control instead of a row, and one around a row that only continues a vertical merge, since such a row is rebuilt on export rather than written from the document.
64
+
65
+ ## 0.6.2
66
+
67
+ ### Patch Changes
68
+
69
+ - [#143](https://github.com/portone-io/docx-editor/pull/143) [`2238131`](https://github.com/portone-io/docx-editor/commit/2238131792ecab86ad544545bc28eae24841cbca) Thanks [@Deea222](https://github.com/Deea222)! - Say which content blocks an export, and where it stands.
70
+
71
+ Every entry `exportProblems`, `documentExportProblems` and a `blocked` `downloadDocx` report now carries a `reason`: a discriminated union naming the situation met and the content it is about, such as `unwritten-story-change` with the story and what was done to it, or `missing-content-types` with the part. It tells apart the situations one code covers, so a host can write the sentence its own user reads instead of matching an English message. The codes and messages are unchanged, so a `switch` over `code` keeps working.
72
+
73
+ A problem about a footnote or an endnote now carries `pos` as well, the first reference to that note in the body, since the note's own text stands nowhere there. A note nothing refers to still has no position.
74
+
75
+ `DocxExportError` carries the entry it was raised for as `problem`, so a `catch` reads the same `reason` and `pos` without asking again. A refusal met while writing that the invariants did not predict leaves it absent.
76
+
77
+ The checks are now asked of every side story an edit reached - a footnote, an endnote, a header, a footer, a comment body - as well as of the body, so an unmatched bookmark, a vertical merge past its table, a placeholder that lost its XML or a paragraph in an undefined list is refused wherever it stands instead of going into the file unchecked. Each such reason carries a `story` saying where, `null` for the body. A story nobody touched goes out as it arrived and is not asked about.
78
+
79
+ Since 0.6.1, `exportBytes` and `exportDocx` refuse a document holding a change nothing writes back - a header or footer story added or removed, an edited footnote or endnote separator - instead of saving the file without it. Check `exportProblems` before writing, or catch `DocxExportError`.
80
+
3
81
  ## 0.6.1
4
82
 
5
83
  ### Patch Changes
@@ -13,7 +13,7 @@ import { exportDocx } from "./docx/exportDocx.js";
13
13
  import { variantsFor } from "./docx/headersFooters.js";
14
14
  import { importDocx } from "./docx/importDocx.js";
15
15
  import { exportProblems } from "./docx/invariants.js";
16
- import { sectionIn, sectionsOf } from "./docx/sections.js";
16
+ import { sectionsOf } from "./docx/sections.js";
17
17
  import { activeLinkSpan } from "./editor/commands/linkCommands.js";
18
18
  import { createEditorView, editorStateForSession } from "./editor/createEditor.js";
19
19
  import { sectionGeometryAt } from "./editor/documentStyles.js";
@@ -320,7 +320,7 @@ function DocxEditorSurface({
320
320
  (key) => storyNodeOf(doc, key)
321
321
  )
322
322
  );
323
- return (face) => shown[sectionIn(sections, doc, face.pos).index] ?? null;
323
+ return (face) => shown[face.section] ?? null;
324
324
  }, [doc, session, sections]);
325
325
  if (opened?.status === "rejected") {
326
326
  return renderImportError ? renderImportError(opened.error) : /* @__PURE__ */ jsx(ImportRejection, { error: opened.error });
package/dist/core.d.ts CHANGED
@@ -19,9 +19,10 @@ export type { ParagraphStyleOption } from "./docx/formatting";
19
19
  export type { DocxBytes, ImportOptions } from "./docx/importDocx";
20
20
  /**
21
21
  * What the writer would refuse the document over, asked ahead of the write. The first entry is
22
- * what `exportDocx` throws, so the two cannot disagree.
22
+ * what `exportDocx` throws, so the two cannot disagree. `reason` tells the situations one code
23
+ * covers apart and names the content each is about.
23
24
  */
24
- export type { ExportProblem } from "./docx/invariants";
25
+ export type { ExportPartName, ExportProblem, ExportProblemReason, ExportProblemStory, ExportStoryKind, } from "./docx/invariants";
25
26
  export { exportProblems } from "./docx/invariants";
26
27
  export type { DocxSession } from "./docx/session";
27
28
  export { documentNumbering, documentPartPath } from "./docx/session";
@@ -29,7 +30,7 @@ export type { CellFormat, CellVerticalAlign, DocumentDefaults, HighlightName, Li
29
30
  export { toCellFormat, toParagraphFormat, toRowFormat, toRunFormat, toTableFormat, toTableWidth, } from "./model/format";
30
31
  export type { LevelAlign, LevelIndent, LevelSuffix, NewList, NewListLevel, NumberFormat, Numbering, NumberingLevel, NumberingList, NumberingOptions, NumberingStyleLinks, ReadLevelRun, } from "./numbering/parseNumbering";
31
32
  export { parseNumbering } from "./numbering/parseNumbering";
32
- export type { DocxExportErrorCode, DocxImportErrorCode, } from "./ooxml/errors";
33
+ export type { DocxExportErrorCode, DocxExportErrorOptions, DocxImportErrorCode, } from "./ooxml/errors";
33
34
  export { DocxExportError, DocxImportError } from "./ooxml/errors";
34
35
  /**
35
36
  * An image node's size is written in EMU, the unit the document itself uses. A builder
@@ -36,7 +36,7 @@ export declare function exportDocx(doc: PMNode, session: DocxSession, options?:
36
36
  *
37
37
  * The first problem `exportProblems` reports is thrown before anything is written, so a refusal a
38
38
  * caller could have asked about ahead of time arrives with the same code and message it would
39
- * have read there.
39
+ * have read there, and carries that entry as the error's `problem`.
40
40
  */
41
41
  export declare function exportDocxReport(doc: PMNode, session: DocxSession, options?: ExportOptions): {
42
42
  bytes: Uint8Array;
@@ -116,7 +116,9 @@ function reportThrough(planners, doc, session, options) {
116
116
  return withXmlParser(options?.xmlParser, () => {
117
117
  const store = sessionOf(session);
118
118
  const problem = problemsOf(doc, store)[0];
119
- if (problem) throw new DocxExportError(problem.code, problem.message);
119
+ if (problem) {
120
+ throw new DocxExportError(problem.code, problem.message, { problem });
121
+ }
120
122
  const approximated = [];
121
123
  const bytes = writeDocx(
122
124
  doc,
@@ -6,7 +6,6 @@ import {
6
6
  } from "../ooxml/partSplice.js";
7
7
  import { isOnElement } from "../ooxml/units.js";
8
8
  import { decodeUtf8, encodeUtf8, parseXml, R_NS, W_NS } from "../ooxml/xml.js";
9
- import { docxSchema } from "../schema/index.js";
10
9
  import {
11
10
  HEADER_FOOTER_KINDS,
12
11
  storyKey
@@ -24,6 +23,7 @@ import {
24
23
  readStory,
25
24
  storyLeafText
26
25
  } from "./story.js";
26
+ import { storyParagraphs } from "./storyBlocks.js";
27
27
  import { storyChangesOf } from "./storyParts.js";
28
28
  var EMPTY_VARIANTS = {
29
29
  default: null,
@@ -86,12 +86,8 @@ function readHeaderFooterStories(parts, mainPartPath, referenced, depsFor) {
86
86
  };
87
87
  }
88
88
  function firstAlign(story) {
89
- for (let at = 0; at < story.childCount; at += 1) {
90
- const block = story.child(at);
91
- if (block.type !== docxSchema.nodes.paragraph) continue;
92
- return toParagraphFormat(block.attrs.format)?.align ?? null;
93
- }
94
- return null;
89
+ const first = storyParagraphs(story).at(0);
90
+ return first === void 0 ? null : toParagraphFormat(first.attrs.format)?.align ?? null;
95
91
  }
96
92
  function variantContent(ids, kind, refs, storyOf) {
97
93
  const variants = { ...EMPTY_VARIANTS };
@@ -164,13 +160,7 @@ function paragraphText(paragraph, page, totalPages) {
164
160
  return pieces.join("");
165
161
  }
166
162
  function headerFooterText(story, page, totalPages) {
167
- const lines = [];
168
- story.forEach((block) => {
169
- if (block.type === docxSchema.nodes.paragraph) {
170
- lines.push(paragraphText(block, page, totalPages));
171
- }
172
- });
173
- return lines.join("\n");
163
+ return storyParagraphs(story).map((paragraph) => paragraphText(paragraph, page, totalPages)).join("\n");
174
164
  }
175
165
  var HEADER_MARKUP = { namespaces: { w: NAMESPACES.w } };
176
166
  function writtenPart(imported, current, session, notes) {
@@ -48,8 +48,14 @@ export declare const paragraphIdRule: IdentityRule;
48
48
  /**
49
49
  * A content control cannot cross a paragraph, so splitting a paragraph in the middle of one leaves
50
50
  * that same control standing in two, and dropping unmarked text into the middle of one breaks it
51
- * in two within the paragraph. Each piece after the first opens as a copy with a `w:id` of its
52
- * own (see `docx/sdt` for what a copy must not carry along).
51
+ * in two within the paragraph. A control an edit left standing twice one level up - a copy of it
52
+ * pasted, or the container duplicated - is the same case, and the walker reaches a control nested
53
+ * inside another. Each piece after the first opens as a copy with a `w:id` of its own (see
54
+ * `docx/sdt` for what a copy must not carry along).
55
+ *
56
+ * Every carrier `schema/controlAttrs` knows is settled here, the block container and a wrapped
57
+ * cell or row alike, each read under its own attribute names: a second control claiming the first
58
+ * one's `w:id` is not a shape §17.5.2.18 allows, whichever of them carries it.
53
59
  */
54
60
  export declare const controlRule: IdentityRule;
55
61
  /**
@@ -61,6 +67,8 @@ export declare const IDENTITY_RULES: readonly IdentityRule[];
61
67
  export interface IdentityProblem {
62
68
  readonly code: DocxExportErrorCode;
63
69
  readonly message: string;
70
+ /** The node type standing twice, which `docx/invariants` names in the problem's reason */
71
+ readonly node: string;
64
72
  readonly pos: number;
65
73
  }
66
74
  /** The document with every later claimant of a name released, in document order */
@@ -4,9 +4,13 @@ import { DocxExportError } from "../ooxml/errors.js";
4
4
  import { qualify } from "../ooxml/names.js";
5
5
  import { parseAttrs } from "../ooxml/tagScan.js";
6
6
  import { docxSchema } from "../schema/index.js";
7
+ import {
8
+ controlAttrsOf,
9
+ OWN_CONTROL_ATTRS
10
+ } from "../schema/controlAttrs.js";
7
11
  import { wrappersOf } from "../schema/wrappers.js";
8
12
  import { withoutParagraphIds } from "./cloning.js";
9
- import { wrapperKindOf } from "./wrappers.js";
13
+ import { copiedControlPrefix, newControlId } from "./sdt.js";
10
14
  var sourceBlockRule = {
11
15
  name: "sourceBlock",
12
16
  visit(block, written) {
@@ -55,19 +59,25 @@ var paragraphIdRule = {
55
59
  function sdtMarksOf(node) {
56
60
  return wrappersOf(node, docxSchema.marks.sdt);
57
61
  }
58
- function controlName(mark) {
59
- const key = mark.attrs.key;
60
- const prefix = mark.attrs.sdtPrefix;
62
+ function controlName(attrs, names) {
63
+ const key = attrs.key;
64
+ const prefix = attrs[names.prefix];
61
65
  return `${typeof key === "number" ? key : 0} ${typeof prefix === "string" ? prefix : ""}`;
62
66
  }
63
- function copiedMark(mark) {
64
- return wrapperKindOf(mark).copy?.(mark) ?? mark;
67
+ function claimedPrefix(attrs, names, written) {
68
+ const name = controlName(attrs, names);
69
+ const claimed = written.has(name);
70
+ written.add(name);
71
+ const prefix = attrs[names.prefix];
72
+ if (!claimed || typeof prefix !== "string") return null;
73
+ return copiedControlPrefix(prefix, newControlId());
65
74
  }
66
75
  function claim(mark, written) {
67
- const name = controlName(mark);
68
- const copy = written.has(name) ? copiedMark(mark) : null;
69
- written.add(name);
70
- return { mark, copy };
76
+ const prefix = claimedPrefix(mark.attrs, OWN_CONTROL_ATTRS, written);
77
+ return {
78
+ mark,
79
+ copy: prefix === null ? null : mark.type.create({ ...mark.attrs, sdtPrefix: prefix })
80
+ };
71
81
  }
72
82
  function rewriteParagraph(paragraph, written) {
73
83
  const inline = [];
@@ -91,7 +101,17 @@ function rewriteParagraph(paragraph, written) {
91
101
  var controlRule = {
92
102
  name: "control",
93
103
  visit(block, written) {
94
- return block.type === docxSchema.nodes.paragraph ? rewriteParagraph(block, written) : block;
104
+ if (block.type === docxSchema.nodes.paragraph) {
105
+ return rewriteParagraph(block, written);
106
+ }
107
+ const names = controlAttrsOf(block);
108
+ if (!names) return block;
109
+ const prefix = claimedPrefix(block.attrs, names, written);
110
+ return prefix === null ? block : block.type.create(
111
+ { ...block.attrs, [names.prefix]: prefix },
112
+ block.content,
113
+ block.marks
114
+ );
95
115
  }
96
116
  };
97
117
  var IDENTITY_RULES = [
@@ -103,6 +123,7 @@ function refusalOf(block, pos) {
103
123
  return {
104
124
  code: "unsupported-content",
105
125
  message: `a preserved block stands in two places (${block.type.name})`,
126
+ node: block.type.name,
106
127
  pos
107
128
  };
108
129
  }
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * A level is a content model of `wml.xsd` rather than an element name, because the same name means
16
16
  * different things in different places: `sdt` is a control the paragraph reader unwraps, a cell
17
- * wrapper under `tr`, a block placeholder under the body, and a row wrapper nothing reads. Keys are
17
+ * wrapper under `tr`, a row wrapper under `tbl`, and a block container under the body. Keys are
18
18
  * Clark names (`{namespace}localName`) so that `m:oMath` and `w:sdt` sit in one map.
19
19
  */
20
20
  import type { PreservedDisplay } from "../schema";
@@ -51,7 +51,7 @@ export type DemotionPolicy = {
51
51
  readonly tier: "demote";
52
52
  };
53
53
  /** The levels a reader walks. Each is a content model of its own in `wml.xsd` */
54
- export type ContentLevel = "body" | "tbl" | "tr" | "tc" | "p" | "wrapper" | "r";
54
+ export type ContentLevel = "body" | "sdtContent" | "tbl" | "tr" | "tc" | "p" | "wrapper" | "r";
55
55
  export declare function clarkName(el: Element): string;
56
56
  export declare const WML_POLICY: Readonly<Record<ContentLevel, ReadonlyMap<string, ElementPolicy>>>;
57
57
  /** The levels that have a node of their own to keep a stranger in */
@@ -110,24 +110,29 @@ var WRAPPER_LEVEL = new Map([
110
110
  ...MATH.map((name) => [name, INLINE_CHIP])
111
111
  ]);
112
112
  var BLOCK_CHILDREN = [
113
- [["p", "tbl"], MODEL],
113
+ [["p", "tbl", "sdt"], MODEL],
114
114
  [RANGE_MARKERS, HIDDEN_MARKER],
115
115
  [COMMENT_RANGE_MARKERS, HIDDEN_MARKER],
116
116
  [PERMISSION_MARKERS, HIDDEN_MARKER],
117
117
  [["proofErr"], IGNORABLE],
118
118
  [REVISION_CONTAINERS, BLOCK_CHIP],
119
- [["sdt", "customXml", "altChunk"], BLOCK_CHIP]
119
+ [["customXml"], BLOCK_CHIP]
120
120
  ];
121
+ var BLOCK_LEVEL_ELTS = [...BLOCK_CHILDREN, [["altChunk"], BLOCK_CHIP]];
121
122
  var BODY_LEVEL = new Map([
122
- ...rules([...BLOCK_CHILDREN, [["sectPr"], BLOCK_CHIP]]),
123
+ ...rules([...BLOCK_LEVEL_ELTS, [["sectPr"], BLOCK_CHIP]]),
123
124
  ...MATH.map((name) => [name, BLOCK_CHIP])
124
125
  ]);
125
126
  var CELL_LEVEL = new Map([
126
- ...rules([...BLOCK_CHILDREN, [["tcPr"], MODEL]]),
127
+ ...rules([...BLOCK_LEVEL_ELTS, [["tcPr"], MODEL]]),
128
+ ...MATH.map((name) => [name, BLOCK_CHIP])
129
+ ]);
130
+ var SDT_CONTENT_LEVEL = new Map([
131
+ ...rules(BLOCK_CHILDREN),
127
132
  ...MATH.map((name) => [name, BLOCK_CHIP])
128
133
  ]);
129
134
  var TABLE_LEVEL = rules([
130
- [["tblPr", "tblGrid", "tr"], MODEL],
135
+ [["tblPr", "tblGrid", "tr", "sdt"], MODEL],
131
136
  [RANGE_MARKERS, HIDDEN_MARKER],
132
137
  [COMMENT_RANGE_MARKERS, HIDDEN_MARKER],
133
138
  [PERMISSION_MARKERS, HIDDEN_MARKER],
@@ -145,6 +150,7 @@ var WML_POLICY = {
145
150
  p: PARAGRAPH_LEVEL,
146
151
  wrapper: WRAPPER_LEVEL,
147
152
  body: BODY_LEVEL,
153
+ sdtContent: SDT_CONTENT_LEVEL,
148
154
  tc: CELL_LEVEL,
149
155
  tbl: TABLE_LEVEL,
150
156
  tr: ROW_LEVEL
@@ -154,6 +160,7 @@ var LEVEL_PRESERVATION = {
154
160
  p: INLINE_CHIP,
155
161
  wrapper: INLINE_CHIP,
156
162
  body: BLOCK_CHIP,
163
+ sdtContent: BLOCK_CHIP,
157
164
  tc: BLOCK_CHIP
158
165
  };
159
166
  function defaultPreservation(level) {
@@ -24,7 +24,7 @@ export declare function buildPreservedInline(el: Element, wrappers: readonly Mar
24
24
  * One block kept as it came, standing where it stood.
25
25
  *
26
26
  * A body block is one of the fragments the session holds, so it names that fragment and the bytes
27
- * it arrived as go back out untouched. A block inside a cell was never a fragment of its own, so
28
- * it carries its XML along with it.
27
+ * it arrived as go back out untouched. A block inside a cell or inside a content control was never
28
+ * a fragment of its own, so it carries its XML along with it.
29
29
  */
30
- export declare function buildPreservedBlock(el: Element, srcId: string | null, level: "body" | "tc"): PMNode;
30
+ export declare function buildPreservedBlock(el: Element, srcId: string | null, level: "body" | "tc" | "sdtContent"): PMNode;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Reading a block-level content control (`w:sdt` under the body, a cell, or another control) as a
3
+ * container of the blocks it holds, or as the node a control holding nothing stands as.
4
+ *
5
+ * The blocks inside a control are the ones the level around it takes, so the caller hands over the
6
+ * reader for its own level rather than this module reaching for one: a control may hold a table
7
+ * while a table may hold a control, and neither may import the other.
8
+ *
9
+ * null leaves the control to whatever held it, which preserves it whole as it was before.
10
+ */
11
+ import type { Node as PMNode } from "prosemirror-model";
12
+ /** How the level around a control reads one block of it */
13
+ export type BlockReader = (el: Element) => PMNode;
14
+ /**
15
+ * One `w:sdt` as a container node, or null for a control this editor keeps whole.
16
+ *
17
+ * `srcId` names the fragment of the session the control was sliced as; a control inside a cell or
18
+ * inside another control was never a fragment of its own and is handed null, as a nested table is.
19
+ *
20
+ * A control holding nothing is read as the atom that draws nothing: an empty `w:sdtContent` and a
21
+ * control that writes no content element at all say the same thing, since §17.5.2.34 makes that
22
+ * element a cache of what stood inside rather than the statement itself.
23
+ */
24
+ export declare function buildSdtBlock(el: Element, srcId: string | null, readBlock: BlockReader): PMNode | null;
@@ -0,0 +1,42 @@
1
+ // src/docx/importSdtBlock.ts
2
+ import { elementChildren } from "../ooxml/xml.js";
3
+ import { docxSchema } from "../schema/index.js";
4
+ import {
5
+ controlAttrs,
6
+ OWN_CONTROL_ATTRS
7
+ } from "../schema/controlAttrs.js";
8
+ import {
9
+ controlFactsFrom,
10
+ modelsBlockContent,
11
+ readEmptySdt,
12
+ readSdtWrapper
13
+ } from "./sdt.js";
14
+ import { nextKey } from "./wrappers.js";
15
+ function controlNodeAttrs(el, srcId, facts) {
16
+ return {
17
+ srcId,
18
+ key: nextKey(docxSchema.marks.sdt.name, el),
19
+ ...controlAttrs(OWN_CONTROL_ATTRS, facts)
20
+ };
21
+ }
22
+ function buildSdtBlock(el, srcId, readBlock) {
23
+ if (!modelsBlockContent(el)) return null;
24
+ const wrapper = readSdtWrapper(el);
25
+ if (!wrapper) {
26
+ const facts = readEmptySdt(el);
27
+ return facts === null ? null : docxSchema.nodes.sdtEmpty.create(controlNodeAttrs(el, srcId, facts));
28
+ }
29
+ const children = elementChildren(wrapper.content);
30
+ if (children.length === 0) {
31
+ return docxSchema.nodes.sdtEmpty.create(
32
+ controlNodeAttrs(el, srcId, controlFactsFrom(wrapper))
33
+ );
34
+ }
35
+ return docxSchema.nodes.sdtBlock.create(
36
+ controlNodeAttrs(el, srcId, controlFactsFrom(wrapper)),
37
+ children.map(readBlock)
38
+ );
39
+ }
40
+ export {
41
+ buildSdtBlock
42
+ };
@@ -7,6 +7,11 @@ import {
7
7
  serializeXml
8
8
  } from "../ooxml/xml.js";
9
9
  import { docxSchema } from "../schema/index.js";
10
+ import {
11
+ controlAttrs,
12
+ NO_CONTROL,
13
+ WRAPPED_CONTROL_ATTRS
14
+ } from "../schema/controlAttrs.js";
10
15
  import {
11
16
  layerTableFormat,
12
17
  NO_FORMATTING,
@@ -20,7 +25,8 @@ import {
20
25
  } from "./importParagraph.js";
21
26
  import { policyFor } from "./importPolicy.js";
22
27
  import { buildPreservedBlock } from "./importPreserved.js";
23
- import { readSdtWrapper } from "./sdt.js";
28
+ import { buildSdtBlock } from "./importSdtBlock.js";
29
+ import { controlFactsFrom, readSdtWrapper } from "./sdt.js";
24
30
  import {
25
31
  cellConditionsOf,
26
32
  cellDefaultsFor,
@@ -58,23 +64,20 @@ function readVerticalMerge(tcPr) {
58
64
  if (!vMerge) return null;
59
65
  return wAttr(vMerge, "val") === "restart" ? "restart" : "continue";
60
66
  }
61
- function readSdtCell(el) {
67
+ function readSdtSingle(el, localName) {
62
68
  const wrapper = readSdtWrapper(el);
63
69
  if (!wrapper) return null;
64
70
  const inner = elementChildren(wrapper.content);
65
- const tc = inner[0];
66
- if (inner.length !== 1 || tc.localName !== "tc") return null;
67
- if (readVerticalMerge(childByLocalName(tc, "tcPr")) === "continue") {
68
- return null;
69
- }
70
- return {
71
- el: tc,
72
- control: {
73
- prefix: wrapper.prefix,
74
- contentsLocked: wrapper.contentsLocked,
75
- deletionLocked: wrapper.deletionLocked
76
- }
77
- };
71
+ if (inner.length !== 1 || inner[0].localName !== localName) return null;
72
+ return { el: inner[0], control: controlFactsFrom(wrapper) };
73
+ }
74
+ function readSdtCell(el) {
75
+ const cell = readSdtSingle(el, "tc");
76
+ if (!cell) return null;
77
+ return readVerticalMerge(childByLocalName(cell.el, "tcPr")) === "continue" ? null : cell;
78
+ }
79
+ function readSdtRow(el) {
80
+ return readSdtSingle(el, "tr");
78
81
  }
79
82
  function trailCell(cells, gathered) {
80
83
  const xml = takeGathered(gathered);
@@ -84,7 +87,7 @@ function trailCell(cells, gathered) {
84
87
  last.trailingXml = (last.trailingXml ?? "") + xml;
85
88
  return true;
86
89
  }
87
- function readRow(el) {
90
+ function readRow(el, control) {
88
91
  const cells = [];
89
92
  const gathered = [];
90
93
  let tblPrEx = null;
@@ -114,7 +117,7 @@ function readRow(el) {
114
117
  });
115
118
  }
116
119
  if (cells.length === 0 || !trailCell(cells, gathered)) return null;
117
- return { el, tblPrEx, cells, leadingXml, trailingXml: null };
120
+ return { el, tblPrEx, cells, control, leadingXml, trailingXml: null };
118
121
  }
119
122
  function gridRevisionXml(grid) {
120
123
  const revision = childByLocalName(grid, "tblGridChange");
@@ -150,8 +153,9 @@ function readTableParts(el) {
150
153
  gathered.push(serializeXml(child));
151
154
  continue;
152
155
  }
153
- if (child.localName !== "tr") return null;
154
- const row = readRow(child);
156
+ const sdt = child.localName === "sdt" ? readSdtRow(child) : null;
157
+ if (!sdt && child.localName !== "tr") return null;
158
+ const row = readRow(sdt?.el ?? child, sdt?.control ?? null);
155
159
  if (!row) return null;
156
160
  const previous = rows.at(-1);
157
161
  if (previous) previous.trailingXml = takeGathered(gathered);
@@ -205,7 +209,7 @@ function gridWidthOf(rows) {
205
209
  const first = widths[0];
206
210
  return widths.every((width) => width === first) ? first : null;
207
211
  }
208
- function buildCellBlock(el, sources, context, placement) {
212
+ function buildCellBlock(el, sources, context, placement, level = "tc") {
209
213
  if (el.localName === "p") {
210
214
  return styledParagraph(
211
215
  buildParagraph(el, null, sources),
@@ -213,7 +217,15 @@ function buildCellBlock(el, sources, context, placement) {
213
217
  placement
214
218
  );
215
219
  }
216
- return buildPreservedBlock(el, null, "tc");
220
+ if (el.localName === "sdt") {
221
+ const control = buildSdtBlock(
222
+ el,
223
+ null,
224
+ (child) => buildCellBlock(child, sources, context, placement, "sdtContent")
225
+ );
226
+ if (control) return control;
227
+ }
228
+ return buildPreservedBlock(el, null, level);
217
229
  }
218
230
  function cellRect(draft) {
219
231
  return {
@@ -241,9 +253,7 @@ function buildCell(draft, table, sources, context) {
241
253
  tcPr: tcPr ? serializeXml(tcPr) : null,
242
254
  tcW: readTableWidth(tcPr, "tcW"),
243
255
  format: readCellFormat(tcPr, defaults),
244
- sdtPrefix: draft.control?.prefix ?? null,
245
- sdtContentsLocked: draft.control?.contentsLocked ?? false,
246
- sdtDeletionLocked: draft.control?.deletionLocked ?? false,
256
+ ...controlAttrs(WRAPPED_CONTROL_ATTRS, draft.control ?? NO_CONTROL),
247
257
  trailingXml: draft.trailingXml
248
258
  },
249
259
  blocks
@@ -263,6 +273,7 @@ function buildRow(row, drafts, table, sources, context) {
263
273
  tblPrEx: row.tblPrEx ? serializeXml(row.tblPrEx) : null,
264
274
  trPr: trPr ? serializeXml(trPr) : null,
265
275
  format: readRowFormat(trPr),
276
+ ...controlAttrs(WRAPPED_CONTROL_ATTRS, row.control ?? NO_CONTROL),
266
277
  leadingXml: row.leadingXml,
267
278
  trailingXml: row.trailingXml
268
279
  },
@@ -5,27 +5,30 @@
5
5
  * would throw, so a screen can ask at edit time what `exportDocx` would say. The list is walked in
6
6
  * order and `exportDocx` throws its first entry, which is what keeps the two from disagreeing.
7
7
  *
8
+ * A code covers several situations, so each entry also carries the `ExportProblemReason`
9
+ * (`ooxml/errors`) naming the one that was met and the content it is about. Every place a problem
10
+ * is built names its own, rather than a reader telling them apart by the message.
11
+ *
12
+ * What the writer puts out block by block is the body and every side story a part writer rewrites
13
+ * (`exportScopes`), so the invariants over content are asked of each of those in turn: markup
14
+ * refused in the body is refused just the same out of a footnote or a header.
15
+ *
8
16
  * The checks inspect model attrs and preserved XML without running the writers. Bookmark
9
17
  * fragments and list definitions use the export parser. `assertBookmarkPairs` in `./exportDocx`
10
18
  * and `assertPartsParse` in `./partPlan` remain the final checks over the parts as actually written.
11
19
  */
12
20
  import type { Node as PMNode } from "prosemirror-model";
13
- import type { DocxExportErrorCode } from "../ooxml/errors";
21
+ import type { ExportProblem } from "../ooxml/errors";
14
22
  import type { ExportOptions } from "./exportDocx";
15
23
  import { type DocxSession, type SessionStore } from "./session";
16
- /** One reason the document cannot be written back, with the code `exportDocx` would throw it under */
17
- export interface ExportProblem {
18
- readonly code: DocxExportErrorCode;
19
- readonly message: string;
20
- /** Where the problem stands in the document. Absent for a problem of the package, of the session, or of a side story */
21
- readonly pos?: number;
22
- }
24
+ export type { ExportPartName, ExportProblem, ExportProblemReason, ExportProblemStory, ExportStoryKind, } from "../ooxml/errors";
23
25
  /** The problems as the writer sees them, for a caller already inside the writer's parser scope */
24
26
  export declare function problemsOf(doc: PMNode, session: SessionStore): readonly ExportProblem[];
25
27
  /**
26
28
  * Known reasons writing this document back would be refused, in the order `exportDocx` would
27
- * raise them. An empty list does not rule out failures while writing. Each entry carries the code and message the
28
- * `DocxExportError` would carry, and the position in the document where there is one.
29
+ * raise them. An empty list does not rule out failures while writing. Each entry carries the code
30
+ * and message the `DocxExportError` would carry, the `reason` naming what the refusal is about,
31
+ * and the position in the document where there is one.
29
32
  *
30
33
  * The list definitions are read to tell a new list from one the document already had, so this
31
34
  * needs an XML parser the way `exportDocx` does and takes the same option.