@portone/docx-editor 0.6.2 → 0.6.4

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 (107) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/dist/DocxEditor.js +2 -2
  3. package/dist/docx/comments/writing.d.ts +8 -0
  4. package/dist/docx/comments/writing.js +9 -2
  5. package/dist/docx/headersFooters.d.ts +7 -0
  6. package/dist/docx/headersFooters.js +8 -15
  7. package/dist/docx/identities.d.ts +9 -2
  8. package/dist/docx/identities.js +45 -12
  9. package/dist/docx/importDocx.js +2 -0
  10. package/dist/docx/importParagraph.d.ts +4 -0
  11. package/dist/docx/importParagraph.js +2 -0
  12. package/dist/docx/importPolicy.d.ts +2 -2
  13. package/dist/docx/importPolicy.js +12 -5
  14. package/dist/docx/importPreserved.d.ts +3 -3
  15. package/dist/docx/importSdtBlock.d.ts +23 -0
  16. package/dist/docx/importSdtBlock.js +33 -0
  17. package/dist/docx/importTable.js +35 -24
  18. package/dist/docx/invariants.js +60 -3
  19. package/dist/docx/notes/numbering.js +4 -4
  20. package/dist/docx/notes/references.d.ts +0 -2
  21. package/dist/docx/notes/references.js +2 -7
  22. package/dist/docx/numberingPlanner.d.ts +3 -0
  23. package/dist/docx/numberingPlanner.js +8 -2
  24. package/dist/docx/packageParts.d.ts +9 -0
  25. package/dist/docx/packageParts.js +16 -0
  26. package/dist/docx/packagePrefixes.d.ts +12 -0
  27. package/dist/docx/packagePrefixes.js +18 -0
  28. package/dist/docx/partPlan.js +3 -5
  29. package/dist/docx/sdt.d.ts +79 -9
  30. package/dist/docx/sdt.js +121 -26
  31. package/dist/docx/sections.d.ts +13 -13
  32. package/dist/docx/sections.js +34 -20
  33. package/dist/docx/serializeBlock.js +10 -1
  34. package/dist/docx/serializeParagraph.d.ts +2 -1
  35. package/dist/docx/serializeParagraph.js +6 -1
  36. package/dist/docx/serializeSdtBlock.d.ts +16 -0
  37. package/dist/docx/serializeSdtBlock.js +11 -0
  38. package/dist/docx/serializeTable.d.ts +8 -2
  39. package/dist/docx/serializeTable.js +14 -20
  40. package/dist/docx/story.d.ts +10 -4
  41. package/dist/docx/story.js +25 -20
  42. package/dist/docx/storyBlocks.d.ts +32 -0
  43. package/dist/docx/storyBlocks.js +65 -0
  44. package/dist/docx/storyParts.d.ts +3 -0
  45. package/dist/docx/storyParts.js +4 -1
  46. package/dist/docx/wrappers.d.ts +33 -15
  47. package/dist/docx/wrappers.js +45 -26
  48. package/dist/editor/blockControlEdits.d.ts +15 -0
  49. package/dist/editor/blockControlEdits.js +79 -0
  50. package/dist/editor/clipboard/normalizers.js +1 -1
  51. package/dist/editor/commands/lockCommands.d.ts +5 -1
  52. package/dist/editor/commands/lockCommands.js +51 -23
  53. package/dist/editor/createEditor.js +4 -0
  54. package/dist/editor/inlineControlEdits.d.ts +20 -0
  55. package/dist/editor/inlineControlEdits.js +69 -0
  56. package/dist/editor/notes/noteSurface.js +4 -3
  57. package/dist/editor/plugins/controlLifecycle.d.ts +18 -0
  58. package/dist/editor/plugins/controlLifecycle.js +130 -0
  59. package/dist/editor/plugins/keymap.js +34 -5
  60. package/dist/editor/plugins/rowResize.js +2 -4
  61. package/dist/editor/stories/storyState.d.ts +2 -0
  62. package/dist/editor/stories/storyState.js +2 -0
  63. package/dist/ooxml/element.js +3 -2
  64. package/dist/ooxml/errors.d.ts +11 -0
  65. package/dist/ooxml/fragment.js +3 -2
  66. package/dist/ooxml/names.d.ts +4 -0
  67. package/dist/ooxml/names.js +8 -2
  68. package/dist/ooxml/partPrefixes.d.ts +21 -0
  69. package/dist/ooxml/partPrefixes.js +164 -0
  70. package/dist/ooxml/partSplice.d.ts +6 -1
  71. package/dist/ooxml/partSplice.js +30 -10
  72. package/dist/ooxml/tagScan.d.ts +24 -2
  73. package/dist/ooxml/tagScan.js +26 -7
  74. package/dist/ooxml/xml.d.ts +8 -0
  75. package/dist/ooxml/xml.js +27 -5
  76. package/dist/page/blockKinds.d.ts +24 -2
  77. package/dist/page/blockKinds.js +6 -1
  78. package/dist/page/kinds/index.d.ts +5 -0
  79. package/dist/page/kinds/index.js +2 -0
  80. package/dist/page/kinds/sdtBlockKind.d.ts +14 -0
  81. package/dist/page/kinds/sdtBlockKind.js +143 -0
  82. package/dist/page/measureBlocks.js +4 -2
  83. package/dist/page/pageDecorations.js +3 -2
  84. package/dist/page/pageLayout.d.ts +16 -15
  85. package/dist/page/pageLayout.js +134 -67
  86. package/dist/page/usePageLayout.d.ts +2 -2
  87. package/dist/page/usePageLayout.js +5 -5
  88. package/dist/schema/attrRoles.js +56 -1
  89. package/dist/schema/clipboard.js +11 -0
  90. package/dist/schema/controlAttrs.d.ts +119 -0
  91. package/dist/schema/controlAttrs.js +137 -0
  92. package/dist/schema/controlEdges.d.ts +22 -0
  93. package/dist/schema/controlEdges.js +50 -0
  94. package/dist/schema/docxSchema.d.ts +1 -1
  95. package/dist/schema/docxSchema.js +235 -37
  96. package/dist/schema/editGuard.d.ts +1 -1
  97. package/dist/schema/guards.js +2 -0
  98. package/dist/schema/locks.d.ts +56 -8
  99. package/dist/schema/locks.js +115 -56
  100. package/dist/styles/classNames.d.ts +10 -0
  101. package/dist/styles/classNames.js +10 -0
  102. package/dist/styles.css +44 -2
  103. package/dist/table/merge.js +11 -3
  104. package/dist/table/rowResize.d.ts +9 -0
  105. package/dist/table/rowResize.js +9 -5
  106. package/dist/ui/TextMenu.js +2 -0
  107. package/package.json +3 -3
@@ -0,0 +1,69 @@
1
+ // src/editor/inlineControlEdits.ts
2
+ import {
3
+ chainCommands,
4
+ joinBackward,
5
+ joinForward,
6
+ selectNodeBackward,
7
+ selectNodeForward
8
+ } from "prosemirror-commands";
9
+ import {
10
+ TextSelection
11
+ } from "prosemirror-state";
12
+ import { isEmptyInlineControl } from "../schema/controlAttrs.js";
13
+ import { guardedCommand } from "../schema/guards.js";
14
+ function beyondEmptyControls(doc, pos, dir) {
15
+ let at = pos;
16
+ for (; ; ) {
17
+ const $at = doc.resolve(at);
18
+ const sibling = dir < 0 ? $at.nodeBefore : $at.nodeAfter;
19
+ if (!sibling || !isEmptyInlineControl(sibling)) break;
20
+ at += dir * sibling.nodeSize;
21
+ }
22
+ return at === pos ? null : at;
23
+ }
24
+ function beyondRun(state, dir) {
25
+ const $cursor = state.selection instanceof TextSelection ? state.selection.$cursor : null;
26
+ return $cursor === null ? null : beyondEmptyControls(state.doc, $cursor.pos, dir);
27
+ }
28
+ function charSize(text, dir) {
29
+ const point = text.codePointAt(dir < 0 ? Math.max(text.length - 2, 0) : 0);
30
+ return point !== void 0 && point > 65535 ? 2 : 1;
31
+ }
32
+ function reachBeyond(doc, beyond, dir) {
33
+ const $beyond = doc.resolve(beyond);
34
+ const sibling = dir < 0 ? $beyond.nodeBefore : $beyond.nodeAfter;
35
+ if (!sibling) return null;
36
+ const size = sibling.isText ? charSize(sibling.text ?? "", dir) : sibling.nodeSize;
37
+ return dir < 0 ? { from: beyond - size, to: beyond } : { from: beyond, to: beyond + size };
38
+ }
39
+ function fromBlockEdge(state, beyond, atEdge) {
40
+ const moved = state.apply(
41
+ state.tr.setSelection(TextSelection.create(state.doc, beyond))
42
+ );
43
+ let built = null;
44
+ atEdge(moved, (tr) => {
45
+ built = tr;
46
+ });
47
+ return built;
48
+ }
49
+ function deleteBeyondEmptyControls(dir) {
50
+ const atEdge = dir < 0 ? chainCommands(joinBackward, selectNodeBackward) : chainCommands(joinForward, selectNodeForward);
51
+ const edit = guardedCommand((state) => {
52
+ const beyond = beyondRun(state, dir);
53
+ if (beyond === null) return null;
54
+ const reach = reachBeyond(state.doc, beyond, dir);
55
+ if (reach === null) return fromBlockEdge(state, beyond, atEdge);
56
+ return state.tr.delete(reach.from, reach.to).scrollIntoView();
57
+ });
58
+ return (state, dispatch, view) => (
59
+ // With nothing beyond the run to take, the key still may not take the control away, so it is
60
+ // reported handled and the document is left as it stood.
61
+ edit(state, dispatch, view) || beyondRun(state, dir) !== null
62
+ );
63
+ }
64
+ var deleteBeyondEmptyControlsBefore = deleteBeyondEmptyControls(-1);
65
+ var deleteBeyondEmptyControlsAfter = deleteBeyondEmptyControls(1);
66
+ export {
67
+ deleteBeyondEmptyControlsAfter,
68
+ deleteBeyondEmptyControlsBefore
69
+ };
@@ -6,6 +6,7 @@ import {
6
6
  } from "prosemirror-model";
7
7
  import { Plugin, TextSelection } from "prosemirror-state";
8
8
  import { NOTE_NUMBER_ELEMENTS } from "../../docx/notes/newNote.js";
9
+ import { onlyStoryParagraph, storyParagraphs } from "../../docx/storyBlocks.js";
9
10
  import { docxSchema } from "../../schema/index.js";
10
11
  import { editShut, transactionAllowed } from "../../schema/guards.js";
11
12
  import { editsShut } from "../../schema/protectionState.js";
@@ -88,7 +89,7 @@ function returnToReference(main, key) {
88
89
  main.focus();
89
90
  }
90
91
  function leadingChipSize(story) {
91
- const first = story.firstChild?.firstChild ?? null;
92
+ const first = storyParagraphs(story).at(0)?.firstChild ?? null;
92
93
  return first !== null && isOwnMark(first) ? first.nodeSize : 0;
93
94
  }
94
95
  function ownMarkIn(story) {
@@ -175,8 +176,8 @@ function ownMarkFirst() {
175
176
  });
176
177
  }
177
178
  function holdsNothing(story) {
178
- const only = story.childCount === 1 ? story.firstChild : null;
179
- return only !== null && only.type === docxSchema.nodes.paragraph && only.content.size === leadingChipSize(story);
179
+ const only = onlyStoryParagraph(story);
180
+ return only !== null && only.content.size === leadingChipSize(story);
180
181
  }
181
182
  function deleteEmptyNote(main, key) {
182
183
  return (state, dispatch) => {
@@ -0,0 +1,18 @@
1
+ /**
2
+ * What a content control says about outliving an edit of its contents, appended to the edit that
3
+ * caused it (`spec/notes/contentControls.md`).
4
+ *
5
+ * Neither `w:temporary` nor `w:showingPlcHdr` can be answered by preserving the control's opening
6
+ * XML, so the first edit inside a control carrying one lifts the wrapper or rewrites that XML
7
+ * without the flag. Appending it is what puts it in the history beside the edit, so one undo takes
8
+ * the two back together.
9
+ */
10
+ import { Plugin } from "prosemirror-state";
11
+ /**
12
+ * Applies both properties after every change that reached inside a control carrying one.
13
+ *
14
+ * The appended transaction carries the pass that lets a wrapper be lifted at all
15
+ * (`schema/locks`): a control's edge and its lock both stand against the step that removes it,
16
+ * and this is the one change neither speaks to.
17
+ */
18
+ export declare function controlLifecycle(): Plugin;
@@ -0,0 +1,130 @@
1
+ // src/editor/plugins/controlLifecycle.ts
2
+ import { Slice } from "prosemirror-model";
3
+ import { Plugin } from "prosemirror-state";
4
+ import { Mapping, ReplaceAroundStep } from "prosemirror-transform";
5
+ import { editSdtPrefix } from "../../docx/sdt.js";
6
+ import {
7
+ controlAttrs,
8
+ controlAttrsOf,
9
+ controlFactsOf,
10
+ isBlockControl,
11
+ NO_CONTROL,
12
+ OWN_CONTROL_ATTRS
13
+ } from "../../schema/controlAttrs.js";
14
+ import { displayOnly } from "../../schema/displayDerivation.js";
15
+ import { controlLifted, controlSpans, historyReplay } from "../../schema/locks.js";
16
+ import { changesOnlyComments } from "../../schema/protection.js";
17
+ function rewritten(transactions) {
18
+ const whole = new Mapping();
19
+ for (const transaction of transactions)
20
+ whole.appendMapping(transaction.mapping);
21
+ const ranges = [];
22
+ let index = 0;
23
+ for (const transaction of transactions) {
24
+ for (const map of transaction.mapping.maps) {
25
+ const rest = whole.slice(index + 1);
26
+ map.forEach((_from, _to, start, end) => {
27
+ ranges.push({ from: rest.map(start, -1), to: rest.map(end, 1) });
28
+ });
29
+ index += 1;
30
+ }
31
+ }
32
+ return ranges;
33
+ }
34
+ function edited(ranges, from, to) {
35
+ return ranges.some((range) => range.from <= to && range.to >= from);
36
+ }
37
+ function withoutPlaceholderFlag(prefix) {
38
+ return prefix === null ? null : editSdtPrefix(prefix, [["showingPlcHdr", null]]);
39
+ }
40
+ function acts(control) {
41
+ return control.temporary || control.showingPlaceholder;
42
+ }
43
+ function lifts(control) {
44
+ return control.temporary && !control.deletionLocked;
45
+ }
46
+ function settleContainer(tr, node, pos, names, control) {
47
+ const at = tr.mapping.map(pos);
48
+ const end = tr.mapping.map(pos + node.nodeSize);
49
+ if (lifts(control)) {
50
+ if (isBlockControl(node)) {
51
+ tr.step(
52
+ new ReplaceAroundStep(at, end, at + 1, end - 1, Slice.empty, 0, true)
53
+ );
54
+ return;
55
+ }
56
+ tr.setNodeMarkup(at, void 0, {
57
+ ...node.attrs,
58
+ ...controlAttrs(names, NO_CONTROL)
59
+ });
60
+ return;
61
+ }
62
+ if (!control.showingPlaceholder) return;
63
+ const prefix = withoutPlaceholderFlag(control.prefix);
64
+ if (prefix === null) return;
65
+ tr.setNodeMarkup(at, void 0, {
66
+ ...node.attrs,
67
+ ...controlAttrs(names, { ...control, prefix, showingPlaceholder: false })
68
+ });
69
+ }
70
+ function settleMark(tr, span, control) {
71
+ const from = tr.mapping.map(span.from);
72
+ const to = tr.mapping.map(span.to);
73
+ if (lifts(control)) {
74
+ tr.removeMark(from, to, span.mark);
75
+ return;
76
+ }
77
+ if (!control.showingPlaceholder) return;
78
+ const prefix = withoutPlaceholderFlag(control.prefix);
79
+ if (prefix === null) return;
80
+ tr.removeMark(from, to, span.mark);
81
+ tr.addMark(
82
+ from,
83
+ to,
84
+ span.mark.type.create({
85
+ ...span.mark.attrs,
86
+ ...controlAttrs(OWN_CONTROL_ATTRS, {
87
+ ...control,
88
+ prefix,
89
+ showingPlaceholder: false
90
+ })
91
+ })
92
+ );
93
+ }
94
+ function settleDocument(tr, doc, ranges) {
95
+ doc.descendants((node, pos) => {
96
+ const names = node.content.size > 0 ? controlAttrsOf(node) : null;
97
+ if (names) {
98
+ const container = controlFactsOf(names, node.attrs);
99
+ if (acts(container) && edited(ranges, pos + 1, pos + node.nodeSize - 1)) {
100
+ settleContainer(tr, node, pos, names, container);
101
+ }
102
+ }
103
+ if (!node.isTextblock) return true;
104
+ for (const span of controlSpans({ node, start: pos + 1 })) {
105
+ const inline = controlFactsOf(OWN_CONTROL_ATTRS, span.mark.attrs);
106
+ if (!acts(inline)) continue;
107
+ if (edited(ranges, span.from, span.to)) settleMark(tr, span, inline);
108
+ }
109
+ return false;
110
+ });
111
+ }
112
+ var NOT_AN_EDIT = [historyReplay, displayOnly, controlLifted];
113
+ function anEdit(transaction) {
114
+ return transaction.docChanged && !NOT_AN_EDIT.some((pass) => transaction.getMeta(pass) === true);
115
+ }
116
+ function controlLifecycle() {
117
+ return new Plugin({
118
+ appendTransaction(transactions, oldState, newState) {
119
+ const changed = transactions.filter(anEdit);
120
+ if (changed.length === 0) return null;
121
+ const tr = newState.tr.setMeta(controlLifted, true);
122
+ settleDocument(tr, newState.doc, rewritten(changed));
123
+ if (!tr.docChanged) return null;
124
+ return changesOnlyComments(oldState.doc, newState.doc) ? null : tr;
125
+ }
126
+ });
127
+ }
128
+ export {
129
+ controlLifecycle
130
+ };
@@ -8,6 +8,12 @@ import { canSplit } from "prosemirror-transform";
8
8
  import { splitParagraphAttrs } from "../../docx/cloning.js";
9
9
  import { toParagraphFormat } from "../../model/format.js";
10
10
  import { docxSchema } from "../../schema/index.js";
11
+ import { isBlockControl } from "../../schema/controlAttrs.js";
12
+ import {
13
+ removeEmptyBlockControl,
14
+ skipEmptyBlockControlAfter,
15
+ skipEmptyBlockControlBefore
16
+ } from "../blockControlEdits.js";
11
17
  import { insertLineBreak, insertPageBreak } from "../commands/breakCommands.js";
12
18
  import {
13
19
  toggleBold,
@@ -24,6 +30,10 @@ import {
24
30
  } from "../commands/listCommands.js";
25
31
  import { insertEndnote, insertFootnote } from "../commands/noteCommands.js";
26
32
  import { insertTab, moveAcrossTab } from "../commands/tabCommands.js";
33
+ import {
34
+ deleteBeyondEmptyControlsAfter,
35
+ deleteBeyondEmptyControlsBefore
36
+ } from "../inlineControlEdits.js";
27
37
  import { openLinkPanel } from "./linkPanel.js";
28
38
  var insertTabFromKeyboard = (state, dispatch, view) => {
29
39
  if (!state.selection.empty && activeLinkSpan(state)) return false;
@@ -67,11 +77,13 @@ function keptEveryAttr(paragraph, attrs) {
67
77
  }
68
78
  var preserveTableFollowingParagraph = (state) => {
69
79
  const { $from } = state.selection;
70
- if (!state.selection.empty || $from.depth !== 1 || $from.parent.type !== docxSchema.nodes.paragraph || $from.parent.content.size !== 0 || $from.parentOffset !== 0) {
80
+ if (!state.selection.empty || $from.parent.type !== docxSchema.nodes.paragraph || $from.parent.content.size !== 0 || $from.parentOffset !== 0) {
71
81
  return false;
72
82
  }
73
- const paragraphIndex = $from.index(0);
74
- return paragraphIndex > 0 && state.doc.child(paragraphIndex - 1).type.spec.tableRole === "table";
83
+ const container = $from.node(-1);
84
+ const holdsBlocks = container.type === docxSchema.nodes.doc || isBlockControl(container);
85
+ const paragraphIndex = $from.index(-1);
86
+ return holdsBlocks && paragraphIndex > 0 && container.child(paragraphIndex - 1).type.spec.tableRole === "table";
75
87
  };
76
88
  var historyKeymap = {
77
89
  "Mod-z": undo,
@@ -104,8 +116,25 @@ var docxKeymap = {
104
116
  "Shift-Enter": insertLineBreak,
105
117
  // Word and Google Docs both put a page break on this key, so it needs no learning
106
118
  "Mod-Enter": insertPageBreak,
107
- // The paragraph keeps adjacent tables separate without changing imported documents.
108
- Backspace: chainCommands(preserveTableFollowingParagraph, undoInputRule),
119
+ // `undoInputRule` comes first because it answers false unless the last transaction was an input
120
+ // rule, and the commands after it report the key handled wherever a control stands beside the
121
+ // caret. Then: a control holding nothing is never taken away by the key - between blocks the
122
+ // caret passes to the line beyond it, inside a paragraph the key passes over it and takes what
123
+ // stands beyond instead - a control holding one empty paragraph goes whole rather than being
124
+ // opened up, and the empty paragraph after a table keeps adjacent tables separate without
125
+ // changing imported documents.
126
+ Backspace: chainCommands(
127
+ undoInputRule,
128
+ skipEmptyBlockControlBefore,
129
+ deleteBeyondEmptyControlsBefore,
130
+ removeEmptyBlockControl,
131
+ preserveTableFollowingParagraph
132
+ ),
133
+ Delete: chainCommands(
134
+ skipEmptyBlockControlAfter,
135
+ deleteBeyondEmptyControlsAfter,
136
+ removeEmptyBlockControl
137
+ ),
109
138
  ...historyKeymap,
110
139
  "Mod-b": toggleBold,
111
140
  "Mod-i": toggleItalic,
@@ -2,11 +2,11 @@
2
2
  import { Plugin, PluginKey } from "prosemirror-state";
3
3
  import { TableMap } from "prosemirror-tables";
4
4
  import { Decoration, DecorationSet } from "prosemirror-view";
5
- import { isLockedCell } from "../../schema/locks.js";
6
5
  import { editorClassNames } from "../../styles/classNames.js";
7
6
  import { pageScaleAround } from "../../styles/visualScale.js";
8
7
  import {
9
8
  buildResizeRowTransaction,
9
+ isRowResizable,
10
10
  resizedRowHeight,
11
11
  rowPositionAt
12
12
  } from "../../table/rowResize.js";
@@ -45,9 +45,7 @@ function edgeUnder(view, event) {
45
45
  const spot = cellSpotAt(view, td);
46
46
  if (!spot) return null;
47
47
  const hit = rowEdgeAt(event.clientY, td.getBoundingClientRect(), spot);
48
- if (!hit || hit.row < 0 || hit.row >= spot.table.childCount) return null;
49
- const row = spot.table.child(hit.row);
50
- if (row.children.some(isLockedCell)) return null;
48
+ if (!hit || !isRowResizable(spot.table, hit.row)) return null;
51
49
  const rowPos = rowPositionAt(spot.tablePos, spot.table, hit.row);
52
50
  const rowDom = view.nodeDOM(rowPos);
53
51
  if (!(rowDom instanceof HTMLTableRowElement)) return null;
@@ -6,6 +6,8 @@
6
6
  * own, so the ones that answer for a whole document stay out - the history, which the main
7
7
  * document keeps for both (`./storyView`), the note and comment plugins, whose subjects a story
8
8
  * does not hold, and the page decorations, since a story is drawn wherever its host puts it.
9
+ * The control lifecycle is among the ones that stay: a story reaches the main state as a document
10
+ * attribute (`schema/stories`), so a control inside a footnote settles here or nowhere.
9
11
  *
10
12
  * The snapshot handed in is the main document's, which is what makes a run resolve here as it
11
13
  * would in the body. Its caller narrows the two values a story answers differently: a story has
@@ -7,6 +7,7 @@ import { tableEditing } from "prosemirror-tables";
7
7
  import { docxClipboard } from "../clipboard/plugin.js";
8
8
  import { editorDocument } from "../editorDocument.js";
9
9
  import { compositionSelection } from "../plugins/compositionSelection.js";
10
+ import { controlLifecycle } from "../plugins/controlLifecycle.js";
10
11
  import {
11
12
  displayDerivation,
12
13
  withDerivedDisplay
@@ -64,6 +65,7 @@ function storyEditorState({
64
65
  tabPointer(),
65
66
  tabLayout(),
66
67
  tabCaret(),
68
+ controlLifecycle(),
67
69
  displayDerivation(),
68
70
  numberingMarkers()
69
71
  ]
@@ -3,7 +3,8 @@ import {
3
3
  NAMESPACES,
4
4
  qualify,
5
5
  W_PREFIX,
6
- wName
6
+ wName,
7
+ xmlnsName
7
8
  } from "./names.js";
8
9
  import { escapeXml, localPart } from "./xml.js";
9
10
  function attrsText(attrs) {
@@ -16,7 +17,7 @@ function elementXml(name, attrs, children = []) {
16
17
  return `${open}>${children.join("")}</${name}>`;
17
18
  }
18
19
  function xmlnsAttr(prefix) {
19
- return [`xmlns:${prefix}`, NAMESPACES[prefix]];
20
+ return [xmlnsName(prefix), NAMESPACES[prefix]];
20
21
  }
21
22
  function localNameUnder(prefix, name) {
22
23
  if (!name.includes(":")) return name;
@@ -94,6 +94,17 @@ export type ExportProblemReason =
94
94
  readonly kind: "unwritable-part-root";
95
95
  readonly part: ExportPartName;
96
96
  }
97
+ /**
98
+ * A part a change is written into binds a prefix the writer spells to a namespace of its own, so
99
+ * the declaration the write adds would contradict the part (`unsupported-content`)
100
+ */
101
+ | {
102
+ readonly kind: "conflicting-part-prefix";
103
+ /** Where the part sits in the package */
104
+ readonly path: string;
105
+ /** The prefix the part binds to something other than what the writer spells it for */
106
+ readonly prefix: string;
107
+ }
97
108
  /** A cell's vertical merge covers rows its table does not have (`invalid-table`) */
98
109
  | {
99
110
  readonly kind: "vertical-merge-past-table";
@@ -1,4 +1,5 @@
1
1
  // src/ooxml/fragment.ts
2
+ import { XMLNS, xmlnsName } from "./names.js";
2
3
  import {
3
4
  elementChildren,
4
5
  namespaceDecls,
@@ -29,7 +30,7 @@ function loneElement(xml) {
29
30
  }
30
31
  function isNamed(el, names) {
31
32
  if (!names.includes(el.localName)) return false;
32
- const declaration = el.prefix === null ? "xmlns" : `xmlns:${el.prefix}`;
33
+ const declaration = el.prefix === null ? XMLNS : xmlnsName(el.prefix);
33
34
  for (let scope = el; scope.parentElement !== null; scope = scope.parentElement) {
34
35
  if (scope.hasAttribute(declaration)) return el.namespaceURI === W_NS;
35
36
  }
@@ -47,7 +48,7 @@ function holdsHeadAlone(el, shape) {
47
48
  }
48
49
  function rebindsReservedPrefix(el) {
49
50
  return Array.from(el.attributes).some((attr) => {
50
- if (attr.prefix !== "xmlns") return false;
51
+ if (attr.prefix !== XMLNS) return false;
51
52
  const reserved = RESERVED_PREFIXES.get(attr.localName);
52
53
  return reserved !== void 0 && reserved !== attr.value;
53
54
  }) || elementChildren(el).some(rebindsReservedPrefix);
@@ -38,5 +38,9 @@ export declare function isKnownPrefix(prefix: string): prefix is KnownPrefix;
38
38
  export declare function qualify(prefix: KnownPrefix, local: string): string;
39
39
  /** `wName("val")` -> `w:val`. The one place the written WordprocessingML prefix is decided */
40
40
  export declare function wName(local: string): string;
41
+ /** The attribute name a namespace declaration stands under, on its own for the default one */
42
+ export declare const XMLNS = "xmlns";
43
+ /** The name a declaration of one prefix is written under (`xmlnsName("w")` -> `xmlns:w`) */
44
+ export declare function xmlnsName(prefix: string): string;
41
45
  /** The declaration a part root carries for one prefix, ready to write inside an opening tag */
42
46
  export declare function xmlnsDecl(prefix: KnownPrefix): string;
@@ -22,8 +22,12 @@ function qualify(prefix, local) {
22
22
  function wName(local) {
23
23
  return qualify(W_PREFIX, local);
24
24
  }
25
+ var XMLNS = "xmlns";
26
+ function xmlnsName(prefix) {
27
+ return `${XMLNS}:${prefix}`;
28
+ }
25
29
  function xmlnsDecl(prefix) {
26
- return `xmlns:${prefix}="${NAMESPACES[prefix]}"`;
30
+ return `${xmlnsName(prefix)}="${NAMESPACES[prefix]}"`;
27
31
  }
28
32
  export {
29
33
  M_NS,
@@ -31,8 +35,10 @@ export {
31
35
  R_NS,
32
36
  W_NS,
33
37
  W_PREFIX,
38
+ XMLNS,
34
39
  isKnownPrefix,
35
40
  qualify,
36
41
  wName,
37
- xmlnsDecl
42
+ xmlnsDecl,
43
+ xmlnsName
38
44
  };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Spelling the namespaces of an arrived part under the prefixes this package writes.
3
+ * `spec/notes/conformance.md` holds the decision and what it rests on.
4
+ *
5
+ * Names alone are rewritten: element names, attribute names, the namespace declarations
6
+ * themselves, and the prefix tokens of the markup-compatibility attributes that carry a prefix or
7
+ * QName list (§17.2.1-2, §17.2.4-5). No WordprocessingML attribute value holds a QName, so no
8
+ * other value is looked at, and text, CDATA, comments and processing instructions are copied byte
9
+ * for byte - a `w:p` a document wrote inside a `w:t` is its text, not its markup.
10
+ *
11
+ * Nothing here turns a part down. One whose rewrite would not be unambiguous is handed back as it
12
+ * arrived, and what refuses it then is what refused it before this rewrite existed: the reader
13
+ * that needs the prefix (`docx/importDocx`) or the write about to spell it (`ooxml/partSplice`).
14
+ */
15
+ /**
16
+ * The part text with every namespace this package knows spelled the way it writes it.
17
+ *
18
+ * A part that comes back unrewritten comes back as the same string by identity, so a package no
19
+ * producer wrote foreign prefixes into is never re-encoded and still exports byte for byte.
20
+ */
21
+ export declare function withEditorPrefixes(xml: string): string;
@@ -0,0 +1,164 @@
1
+ // src/ooxml/partPrefixes.ts
2
+ import {
3
+ isKnownPrefix,
4
+ NAMESPACES,
5
+ qualify,
6
+ XMLNS,
7
+ xmlnsName
8
+ } from "./names.js";
9
+ import {
10
+ attrSpans,
11
+ parseAttrs,
12
+ readTag,
13
+ rootTagAt
14
+ } from "./tagScan.js";
15
+ var CANONICAL_PREFIX = new Map(
16
+ Object.keys(NAMESPACES).filter(isKnownPrefix).map((prefix) => [NAMESPACES[prefix], prefix])
17
+ );
18
+ var MCE_PREFIX_LISTS = new Set(
19
+ [
20
+ "Ignorable",
21
+ "MustUnderstand",
22
+ "ProcessContent",
23
+ "PreserveElements",
24
+ "PreserveAttributes"
25
+ ].map((local) => qualify("mc", local))
26
+ );
27
+ var MCE_ALTERNATE_CONTENT = new Set(
28
+ ["Choice", "Fallback"].map((local) => qualify("mc", local))
29
+ );
30
+ var DECL = `${XMLNS}:`;
31
+ function prefixMapOf(rootAttrs) {
32
+ const bound = /* @__PURE__ */ new Map();
33
+ const mapped = /* @__PURE__ */ new Map();
34
+ let defaultTo = null;
35
+ for (const [name, namespace] of rootAttrs) {
36
+ if (name === XMLNS) {
37
+ defaultTo = CANONICAL_PREFIX.get(namespace) ?? null;
38
+ continue;
39
+ }
40
+ if (!name.startsWith(DECL)) continue;
41
+ const prefix = name.slice(DECL.length);
42
+ bound.set(prefix, namespace);
43
+ const canonical = CANONICAL_PREFIX.get(namespace);
44
+ if (canonical !== void 0 && canonical !== prefix)
45
+ mapped.set(prefix, canonical);
46
+ }
47
+ const targets = new Set(mapped.values());
48
+ if (defaultTo !== null) targets.add(defaultTo);
49
+ for (const target of targets) {
50
+ const already = bound.get(target);
51
+ if (already !== void 0 && already !== NAMESPACES[target]) return null;
52
+ }
53
+ return { mapped, defaultTo, targets };
54
+ }
55
+ var underDefault = (name, map) => map.defaultTo === null ? name : qualify(map.defaultTo, name);
56
+ var inNoNamespace = (name) => name;
57
+ var asPrefix = (token, map) => map.mapped.get(token) ?? token;
58
+ function mappedName(name, map, unprefixed) {
59
+ const colon = name.indexOf(":");
60
+ if (colon === -1) return unprefixed(name, map);
61
+ const canonical = map.mapped.get(name.slice(0, colon));
62
+ return canonical === void 0 ? name : canonical + name.slice(colon);
63
+ }
64
+ function rewriteAttrName(name, map) {
65
+ if (name === XMLNS) {
66
+ return map.defaultTo === null ? name : xmlnsName(map.defaultTo);
67
+ }
68
+ if (name.startsWith(DECL)) {
69
+ const canonical = map.mapped.get(name.slice(DECL.length));
70
+ return canonical === void 0 ? name : xmlnsName(canonical);
71
+ }
72
+ if (name.startsWith("xml:")) return name;
73
+ return mappedName(name, map, inNoNamespace);
74
+ }
75
+ function isDeclaration(name) {
76
+ return name === XMLNS || name.startsWith(DECL);
77
+ }
78
+ function namesPrefixes(elementName, attrName) {
79
+ return MCE_PREFIX_LISTS.has(attrName) || attrName === "Requires" && MCE_ALTERNATE_CONTENT.has(elementName);
80
+ }
81
+ function rewriteTokens(value, map) {
82
+ return value.replace(/\S+/g, (token) => mappedName(token, map, asPrefix));
83
+ }
84
+ function spelledNamespace(prefix, map) {
85
+ const canonical = map.mapped.get(prefix);
86
+ if (canonical !== void 0) return NAMESPACES[canonical];
87
+ if (!isKnownPrefix(prefix) || !map.targets.has(prefix)) return void 0;
88
+ return NAMESPACES[prefix];
89
+ }
90
+ function rebindsSpelledPrefix(raw, spans, map) {
91
+ return spans.some((span) => {
92
+ const name = raw.slice(span.nameStart, span.nameEnd);
93
+ if (!isDeclaration(name)) return false;
94
+ const namespace = raw.slice(span.valueStart, span.valueEnd);
95
+ if (name === XMLNS) {
96
+ return map.defaultTo !== null && namespace !== NAMESPACES[map.defaultTo];
97
+ }
98
+ const spelled = spelledNamespace(name.slice(DECL.length), map);
99
+ return spelled !== void 0 && namespace !== spelled;
100
+ });
101
+ }
102
+ function rewriteAttrs(raw, elementName, map) {
103
+ const spans = attrSpans(raw);
104
+ if (spans === null) return null;
105
+ if (raw.includes(XMLNS) && rebindsSpelledPrefix(raw, spans, map)) return null;
106
+ const declared = new Set(
107
+ spans.map((span) => raw.slice(span.nameStart, span.nameEnd))
108
+ );
109
+ const written = /* @__PURE__ */ new Set();
110
+ let out = "";
111
+ let at = 0;
112
+ for (const span of spans) {
113
+ const name = raw.slice(span.nameStart, span.nameEnd);
114
+ const rewritten = rewriteAttrName(name, map);
115
+ if (rewritten !== name && isDeclaration(rewritten) && (declared.has(rewritten) || written.has(rewritten))) {
116
+ at = span.valueEnd + 1;
117
+ continue;
118
+ }
119
+ written.add(rewritten);
120
+ const value = raw.slice(span.valueStart, span.valueEnd);
121
+ out += raw.slice(at, span.nameStart) + rewritten + raw.slice(span.nameEnd, span.valueStart) + (namesPrefixes(elementName, rewritten) ? rewriteTokens(value, map) : value) + span.quote;
122
+ at = span.valueEnd + 1;
123
+ }
124
+ return out + raw.slice(at);
125
+ }
126
+ function rewriteTag(xml, tag, map) {
127
+ const closeLength = tag.kind === "empty" ? 2 : 1;
128
+ const name = mappedName(tag.name, map, underDefault);
129
+ const raw = xml.slice(tag.nameEnd, tag.end - closeLength);
130
+ const attrs = tag.kind === "close" ? raw : rewriteAttrs(raw, name, map);
131
+ if (attrs === null) return null;
132
+ return (tag.kind === "close" ? "</" : "<") + name + attrs + xml.slice(tag.end - closeLength, tag.end);
133
+ }
134
+ function withEditorPrefixes(xml) {
135
+ const rootAt = rootTagAt(xml);
136
+ if (rootAt === -1) return xml;
137
+ const root = readTag(xml, rootAt);
138
+ if (root === null || root.kind === "close") return xml;
139
+ const rootAttrs = parseAttrs(
140
+ xml.slice(root.nameEnd, root.end - (root.kind === "empty" ? 2 : 1))
141
+ );
142
+ if (rootAttrs === null) return xml;
143
+ const map = prefixMapOf(rootAttrs);
144
+ if (map === null) return xml;
145
+ if (map.mapped.size === 0 && map.defaultTo === null) return xml;
146
+ const out = [];
147
+ let at = 0;
148
+ for (; ; ) {
149
+ const lt = xml.indexOf("<", at);
150
+ if (lt === -1) break;
151
+ const tag = readTag(xml, lt);
152
+ if (tag === null) return xml;
153
+ const rewritten = tag.kind === "other" ? xml.slice(lt, tag.end) : rewriteTag(xml, tag, map);
154
+ if (rewritten === null) return xml;
155
+ out.push(xml.slice(at, lt));
156
+ out.push(rewritten);
157
+ at = tag.end;
158
+ }
159
+ out.push(xml.slice(at));
160
+ return out.join("");
161
+ }
162
+ export {
163
+ withEditorPrefixes
164
+ };
@@ -8,7 +8,7 @@
8
8
  * comment for the end of the part, and miss the root altogether when it is written under a
9
9
  * prefix or closes on itself.
10
10
  */
11
- import type { KnownPrefix } from "./names";
11
+ import { type KnownPrefix } from "./names";
12
12
  /** One child to put into a part, named by the local part of its tag so the child order can place it */
13
13
  export interface PartChild {
14
14
  name: string;
@@ -60,6 +60,11 @@ export interface RootDeclarations {
60
60
  /** The tokens `mc:Ignorable` has to name, added to the ones it names already */
61
61
  ignorable?: readonly string[];
62
62
  }
63
+ /**
64
+ * Which prefix `ensureRootDeclarations` would refuse this part over, and null for a part it would
65
+ * write into, so an invariant can ask before anything is written what the write would answer.
66
+ */
67
+ export declare function rootBindingConflict(xml: string, declarations: RootDeclarations): string | null;
63
68
  /**
64
69
  * The part with its root binding every prefix named and its `mc:Ignorable` naming every token
65
70
  * asked for, each declared once: a matching declaration is preserved, and a conflicting binding is refused.