@harbour-enterprises/superdoc 0.13.2-rev1 → 0.13.2-rev11

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 (56) hide show
  1. package/dist/chunks/{eventemitter3-DfVviFzP.cjs → eventemitter3-CHxWXmuK.cjs} +1 -1
  2. package/dist/chunks/{eventemitter3-BrspJk8q.es.js → eventemitter3-KKY27oz-.es.js} +1 -1
  3. package/dist/chunks/{index-KzH9VKHh.es.js → index-BqLFjUHn.es.js} +2 -2
  4. package/dist/chunks/{index-B0t3i_io.cjs → index-CweAXNfB.cjs} +2 -2
  5. package/dist/chunks/{index-D_HUrFWV.es.js → index-DS3W0eVB.es.js} +4 -4
  6. package/dist/chunks/{index-Bk160jQ2.cjs → index-kOMfCfBT.cjs} +4 -4
  7. package/dist/chunks/{jszip-BTAcmbVg.cjs → jszip-9bCX1h2W.cjs} +1 -1
  8. package/dist/chunks/{jszip-DckFs3A7.es.js → jszip-Cl3s9njw.es.js} +1 -1
  9. package/dist/chunks/{super-editor.es-DyTkLKR1.es.js → super-editor.es-C0XuFRew.es.js} +1501 -1191
  10. package/dist/chunks/{super-editor.es--NMYzIh3.cjs → super-editor.es-DNcda5wa.cjs} +1501 -1191
  11. package/dist/chunks/{url-CWyTQ-Xy.cjs → url-B8LY3nwf.cjs} +2 -2
  12. package/dist/chunks/{url-DsBQArCl.es.js → url-Bq00tGvm.es.js} +2 -2
  13. package/dist/chunks/{vue-Bi1uWinj.es.js → vue-BBJVqxjL.es.js} +10 -3
  14. package/dist/chunks/{vue-HIY1g7dm.cjs → vue-BBjMeYfo.cjs} +10 -3
  15. package/dist/chunks/{xml-js-CdiD26MJ.es.js → xml-js-1F0lia4t.es.js} +2 -2
  16. package/dist/chunks/{xml-js-Bu1ZZzmb.cjs → xml-js-BuAdLsHD.cjs} +2 -2
  17. package/dist/core/SuperDoc.d.ts +5 -0
  18. package/dist/core/SuperDoc.d.ts.map +1 -1
  19. package/dist/style.css +2 -2
  20. package/dist/super-editor/ai-writer.es.js +2 -2
  21. package/dist/super-editor/chunks/{converter-CJ9kHtZx.js → converter-g7XDS8H8.js} +632 -52
  22. package/dist/super-editor/chunks/{docx-zipper-scQqOWXA.js → docx-zipper-VpCXV0uV.js} +1 -1
  23. package/dist/super-editor/chunks/{editor-DM6yaxu_.js → editor-B3V2UfZk.js} +444 -707
  24. package/dist/super-editor/chunks/{toolbar-CIHbdcnv.js → toolbar-DbwzVBvd.js} +2 -3
  25. package/dist/super-editor/converter.es.js +2 -2
  26. package/dist/super-editor/core/Editor.d.ts +17 -3
  27. package/dist/super-editor/core/Editor.d.ts.map +1 -1
  28. package/dist/super-editor/core/InputRule.d.ts +7 -0
  29. package/dist/super-editor/core/InputRule.d.ts.map +1 -1
  30. package/dist/super-editor/core/helpers/annotator.d.ts +4 -0
  31. package/dist/super-editor/core/helpers/annotator.d.ts.map +1 -1
  32. package/dist/super-editor/core/helpers/setImageNodeSelection.d.ts +2 -0
  33. package/dist/super-editor/core/helpers/setImageNodeSelection.d.ts.map +1 -0
  34. package/dist/super-editor/core/super-converter/exporter.d.ts.map +1 -1
  35. package/dist/super-editor/docx-zipper.es.js +2 -2
  36. package/dist/super-editor/editor.es.js +3 -3
  37. package/dist/super-editor/extensions/field-annotation/field-annotation.d.ts.map +1 -1
  38. package/dist/super-editor/extensions/field-annotation/fieldAnnotationHelpers/findRemovedFieldAnnotations.d.ts.map +1 -1
  39. package/dist/super-editor/extensions/image/imageHelpers/startImageUpload.d.ts.map +1 -1
  40. package/dist/super-editor/extensions/line-break/line-break.d.ts.map +1 -1
  41. package/dist/super-editor/extensions/noderesizer/noderesizer.d.ts.map +1 -1
  42. package/dist/super-editor/extensions/pagination/pagination-helpers.d.ts +6 -1
  43. package/dist/super-editor/extensions/pagination/pagination-helpers.d.ts.map +1 -1
  44. package/dist/super-editor/extensions/pagination/pagination.d.ts.map +1 -1
  45. package/dist/super-editor/extensions/paragraph/paragraph.d.ts.map +1 -1
  46. package/dist/super-editor/file-zipper.es.js +1 -1
  47. package/dist/super-editor/style.css +2 -2
  48. package/dist/super-editor/super-editor.es.js +7 -7
  49. package/dist/super-editor/toolbar.es.js +2 -2
  50. package/dist/super-editor.cjs +2 -2
  51. package/dist/super-editor.es.js +2 -2
  52. package/dist/superdoc.cjs +21 -9
  53. package/dist/superdoc.es.js +22 -10
  54. package/dist/superdoc.umd.js +1184 -855
  55. package/dist/superdoc.umd.js.map +1 -1
  56. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const vue = require("./vue-HIY1g7dm.cjs");
2
+ const vue = require("./vue-BBjMeYfo.cjs");
3
3
  const Y = require("yjs");
4
4
  function _interopNamespaceDefault(e) {
5
5
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
@@ -10958,7 +10958,7 @@ class NodeRange {
10958
10958
  }
10959
10959
  }
10960
10960
  const emptyAttrs = /* @__PURE__ */ Object.create(null);
10961
- let Node$2 = class Node2 {
10961
+ let Node$1$1 = class Node2 {
10962
10962
  /**
10963
10963
  @internal
10964
10964
  */
@@ -11359,8 +11359,8 @@ let Node$2 = class Node2 {
11359
11359
  return node2;
11360
11360
  }
11361
11361
  };
11362
- Node$2.prototype.text = void 0;
11363
- class TextNode extends Node$2 {
11362
+ Node$1$1.prototype.text = void 0;
11363
+ class TextNode extends Node$1$1 {
11364
11364
  /**
11365
11365
  @internal
11366
11366
  */
@@ -11947,7 +11947,7 @@ let NodeType$1 = class NodeType {
11947
11947
  create(attrs = null, content, marks) {
11948
11948
  if (this.isText)
11949
11949
  throw new Error("NodeType.create can't construct text nodes");
11950
- return new Node$2(this, this.computeAttrs(attrs), Fragment.from(content), Mark$1.setFrom(marks));
11950
+ return new Node$1$1(this, this.computeAttrs(attrs), Fragment.from(content), Mark$1.setFrom(marks));
11951
11951
  }
11952
11952
  /**
11953
11953
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
@@ -11957,7 +11957,7 @@ let NodeType$1 = class NodeType {
11957
11957
  createChecked(attrs = null, content, marks) {
11958
11958
  content = Fragment.from(content);
11959
11959
  this.checkContent(content);
11960
- return new Node$2(this, this.computeAttrs(attrs), content, Mark$1.setFrom(marks));
11960
+ return new Node$1$1(this, this.computeAttrs(attrs), content, Mark$1.setFrom(marks));
11961
11961
  }
11962
11962
  /**
11963
11963
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
@@ -11980,7 +11980,7 @@ let NodeType$1 = class NodeType {
11980
11980
  let after = matched && matched.fillBefore(Fragment.empty, true);
11981
11981
  if (!after)
11982
11982
  return null;
11983
- return new Node$2(this, attrs, content.append(after), Mark$1.setFrom(marks));
11983
+ return new Node$1$1(this, attrs, content.append(after), Mark$1.setFrom(marks));
11984
11984
  }
11985
11985
  /**
11986
11986
  Returns true if the given fragment is valid content for this node
@@ -12217,7 +12217,7 @@ let Schema$1 = class Schema {
12217
12217
  bound.
12218
12218
  */
12219
12219
  nodeFromJSON(json) {
12220
- return Node$2.fromJSON(this, json);
12220
+ return Node$1$1.fromJSON(this, json);
12221
12221
  }
12222
12222
  /**
12223
12223
  Deserialize a mark from its JSON representation. This method is
@@ -13743,7 +13743,7 @@ class ReplaceStep extends Step {
13743
13743
  }
13744
13744
  }
13745
13745
  Step.jsonID("replace", ReplaceStep);
13746
- class ReplaceAroundStep extends Step {
13746
+ let ReplaceAroundStep$1 = class ReplaceAroundStep2 extends Step {
13747
13747
  /**
13748
13748
  Create a replace-around step with the given range and gap.
13749
13749
  `insert` should be the point in the slice into which the content
@@ -13783,7 +13783,7 @@ class ReplaceAroundStep extends Step {
13783
13783
  }
13784
13784
  invert(doc2) {
13785
13785
  let gap = this.gapTo - this.gapFrom;
13786
- return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
13786
+ return new ReplaceAroundStep2(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
13787
13787
  }
13788
13788
  map(mapping) {
13789
13789
  let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
@@ -13791,7 +13791,7 @@ class ReplaceAroundStep extends Step {
13791
13791
  let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);
13792
13792
  if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos)
13793
13793
  return null;
13794
- return new ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
13794
+ return new ReplaceAroundStep2(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
13795
13795
  }
13796
13796
  toJSON() {
13797
13797
  let json = {
@@ -13814,10 +13814,10 @@ class ReplaceAroundStep extends Step {
13814
13814
  static fromJSON(schema, json) {
13815
13815
  if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
13816
13816
  throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
13817
- return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
13817
+ return new ReplaceAroundStep2(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
13818
13818
  }
13819
- }
13820
- Step.jsonID("replaceAround", ReplaceAroundStep);
13819
+ };
13820
+ Step.jsonID("replaceAround", ReplaceAroundStep$1);
13821
13821
  function contentBetween(doc2, from2, to) {
13822
13822
  let $from = doc2.resolve(from2), dist2 = to - from2, depth = $from.depth;
13823
13823
  while (dist2 > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
@@ -13970,7 +13970,7 @@ function lift(tr, range2, target) {
13970
13970
  } else {
13971
13971
  end2++;
13972
13972
  }
13973
- tr.step(new ReplaceAroundStep(start2, end2, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
13973
+ tr.step(new ReplaceAroundStep$1(start2, end2, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
13974
13974
  }
13975
13975
  function findWrapping(range2, nodeType, attrs = null, innerRange = range2) {
13976
13976
  let around = findWrappingOutside(range2, nodeType);
@@ -14015,7 +14015,7 @@ function wrap(tr, range2, wrappers) {
14015
14015
  content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
14016
14016
  }
14017
14017
  let start2 = range2.start, end2 = range2.end;
14018
- tr.step(new ReplaceAroundStep(start2, end2, start2, end2, new Slice(content, 0, 0), wrappers.length, true));
14018
+ tr.step(new ReplaceAroundStep$1(start2, end2, start2, end2, new Slice(content, 0, 0), wrappers.length, true));
14019
14019
  }
14020
14020
  function setBlockType$1(tr, from2, to, type2, attrs) {
14021
14021
  if (!type2.isTextblock)
@@ -14037,7 +14037,7 @@ function setBlockType$1(tr, from2, to, type2, attrs) {
14037
14037
  clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type2, void 0, convertNewlines === null);
14038
14038
  let mapping = tr.mapping.slice(mapFrom);
14039
14039
  let startM = mapping.map(pos, 1), endM = mapping.map(pos + node2.nodeSize, 1);
14040
- tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type2.create(attrsHere, null, node2.marks)), 0, 0), 1, true));
14040
+ tr.step(new ReplaceAroundStep$1(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type2.create(attrsHere, null, node2.marks)), 0, 0), 1, true));
14041
14041
  if (convertNewlines === true)
14042
14042
  replaceNewlines(tr, node2, pos, mapFrom);
14043
14043
  return false;
@@ -14078,7 +14078,7 @@ function setNodeMarkup(tr, pos, type2, attrs, marks) {
14078
14078
  return tr.replaceWith(pos, pos + node2.nodeSize, newNode);
14079
14079
  if (!type2.validContent(node2.content))
14080
14080
  throw new RangeError("Invalid content for node type " + type2.name);
14081
- tr.step(new ReplaceAroundStep(pos, pos + node2.nodeSize, pos + 1, pos + node2.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
14081
+ tr.step(new ReplaceAroundStep$1(pos, pos + node2.nodeSize, pos + 1, pos + node2.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
14082
14082
  }
14083
14083
  function canSplit(doc2, pos, depth = 1, typesAfter) {
14084
14084
  let $pos = doc2.resolve(pos), base2 = $pos.depth - depth;
@@ -14279,7 +14279,7 @@ class Fitter {
14279
14279
  }
14280
14280
  let slice2 = new Slice(content, openStart, openEnd);
14281
14281
  if (moveInline > -1)
14282
- return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize);
14282
+ return new ReplaceAroundStep$1($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize);
14283
14283
  if (slice2.size || $from.pos != this.$to.pos)
14284
14284
  return new ReplaceStep($from.pos, $to.pos, slice2);
14285
14285
  return null;
@@ -15362,7 +15362,7 @@ function selectionToInsertionEnd$1(tr, startLen, bias) {
15362
15362
  if (last < startLen)
15363
15363
  return;
15364
15364
  let step = tr.steps[last];
15365
- if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
15365
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep$1))
15366
15366
  return;
15367
15367
  let map3 = tr.mapping.maps[last], end2;
15368
15368
  map3.forEach((_from, _to, _newFrom, newTo) => {
@@ -15777,7 +15777,7 @@ class EditorState {
15777
15777
  let instance = new EditorState($config);
15778
15778
  $config.fields.forEach((field) => {
15779
15779
  if (field.name == "doc") {
15780
- instance.doc = Node$2.fromJSON(config.schema, json.doc);
15780
+ instance.doc = Node$1$1.fromJSON(config.schema, json.doc);
15781
15781
  } else if (field.name == "selection") {
15782
15782
  instance.selection = Selection.fromJSON(instance.doc, json.selection);
15783
15783
  } else if (field.name == "storedMarks") {
@@ -18838,210 +18838,787 @@ const createColGroup = (node2, cellMinWidth, overrideCol, overrideValue) => {
18838
18838
  colgroupValues
18839
18839
  };
18840
18840
  };
18841
- function exportSchemaToJson(params2) {
18842
- const { type: type2 } = params2.node || {};
18843
- const router = {
18844
- doc: translateDocumentNode,
18845
- body: translateBodyNode,
18846
- paragraph: translateParagraphNode,
18847
- text: translateTextNode,
18848
- bulletList: translateList,
18849
- orderedList: translateList,
18850
- lineBreak: translateLineBreak,
18851
- table: translateTable,
18852
- tableRow: translateTableRow,
18853
- tableCell: translateTableCell,
18854
- bookmarkStart: translateBookmarkStart,
18855
- fieldAnnotation: translateFieldAnnotation,
18856
- tab: translateTab,
18857
- image: translateImageNode,
18858
- hardBreak: translateHardBreak,
18859
- commentRangeStart: () => translateCommentNode(params2, "Start"),
18860
- commentRangeEnd: () => translateCommentNode(params2, "End"),
18861
- commentReference: () => null,
18862
- shapeContainer: translateShapeContainer,
18863
- shapeTextbox: translateShapeTextbox,
18864
- contentBlock: translateContentBlock,
18865
- structuredContent: translateStructuredContent,
18866
- "page-number": translatePageNumberNode,
18867
- "total-page-number": translateTotalPageNumberNode
18841
+ function chainableEditorState(transaction, state2) {
18842
+ let { selection, doc: doc2, storedMarks } = transaction;
18843
+ return {
18844
+ ...state2,
18845
+ apply: state2.apply.bind(state2),
18846
+ applyTransaction: state2.applyTransaction.bind(state2),
18847
+ plugins: state2.plugins,
18848
+ schema: state2.schema,
18849
+ reconfigure: state2.reconfigure.bind(state2),
18850
+ toJSON: state2.toJSON.bind(state2),
18851
+ get storedMarks() {
18852
+ return storedMarks;
18853
+ },
18854
+ get selection() {
18855
+ return selection;
18856
+ },
18857
+ get doc() {
18858
+ return doc2;
18859
+ },
18860
+ get tr() {
18861
+ selection = transaction.selection;
18862
+ doc2 = transaction.doc;
18863
+ storedMarks = transaction.storedMarks;
18864
+ return transaction;
18865
+ }
18868
18866
  };
18869
- if (!router[type2]) {
18870
- console.error("No translation function found for node type:", type2);
18871
- return null;
18872
- }
18873
- return router[type2](params2);
18874
18867
  }
18875
- function translateBodyNode(params2) {
18876
- let sectPr = params2.bodyNode?.elements.find((n) => n.name === "w:sectPr") || {};
18877
- if (params2.converter) {
18878
- const hasHeader = sectPr?.elements?.some((n) => n.name === "w:headerReference");
18879
- const hasDefaultHeader = params2.converter.headerIds?.default;
18880
- if (!hasHeader && hasDefaultHeader && !params2.editor.options.isHeaderOrFooter) {
18881
- const defaultHeader = generateDefaultHeaderFooter("header", params2.converter.headerIds?.default);
18882
- sectPr.elements.push(defaultHeader);
18883
- }
18884
- const hasFooter = sectPr?.elements?.some((n) => n.name === "w:footerReference");
18885
- const hasDefaultFooter = params2.converter.footerIds?.default;
18886
- if (!hasFooter && hasDefaultFooter && !params2.editor.options.isHeaderOrFooter) {
18887
- const defaultFooter = generateDefaultHeaderFooter("footer", params2.converter.footerIds?.default);
18888
- sectPr.elements.push(defaultFooter);
18889
- }
18890
- const newMargins = params2.converter.pageStyles.pageMargins;
18891
- const sectPrMargins = sectPr.elements.find((n) => n.name === "w:pgMar");
18892
- const { attributes } = sectPrMargins;
18893
- Object.entries(newMargins).forEach(([key, value]) => {
18894
- const convertedValue = inchesToTwips(value);
18895
- attributes[`w:${key}`] = convertedValue;
18896
- });
18897
- sectPrMargins.attributes = attributes;
18868
+ class CommandService {
18869
+ constructor(props) {
18870
+ __publicField$2(this, "editor");
18871
+ __publicField$2(this, "rawCommands");
18872
+ this.editor = props.editor;
18873
+ this.rawCommands = this.editor.extensionService.commands;
18898
18874
  }
18899
- const elements = translateChildNodes(params2);
18900
- if (params2.isHeaderFooter) {
18901
- return {
18902
- name: "w:body",
18903
- elements: [...elements]
18904
- };
18875
+ /**
18876
+ * Static method for creating a service.
18877
+ * @param args Arguments for the constructor.
18878
+ */
18879
+ static create(...args) {
18880
+ return new CommandService(...args);
18905
18881
  }
18906
- return {
18907
- name: "w:body",
18908
- elements: [...elements, sectPr]
18909
- };
18910
- }
18911
- const generateDefaultHeaderFooter = (type2, id) => {
18912
- return {
18913
- "type": "element",
18914
- "name": `w:${type2}Reference`,
18915
- "attributes": {
18916
- "w:type": "default",
18917
- "r:id": id
18918
- }
18919
- };
18920
- };
18921
- function translateParagraphNode(params2) {
18922
- const elements = translateChildNodes(params2);
18923
- const htmlAnnotationChild = elements.find((element) => element.name === "htmlAnnotation");
18924
- if (htmlAnnotationChild) {
18925
- return htmlAnnotationChild.elements;
18882
+ /**
18883
+ * Get editor state.
18884
+ */
18885
+ get state() {
18886
+ return this.editor.state;
18926
18887
  }
18927
- const pPr = generateParagraphProperties(params2.node);
18928
- if (pPr) elements.unshift(pPr);
18929
- let attributes = {};
18930
- if (params2.node.attrs?.rsidRDefault) {
18931
- attributes["w:rsidRDefault"] = params2.node.attrs.rsidRDefault;
18888
+ /**
18889
+ * Get all commands with wrapped command method.
18890
+ */
18891
+ get commands() {
18892
+ const { editor, state: state2 } = this;
18893
+ const { view } = editor;
18894
+ const { tr } = state2;
18895
+ const props = this.createProps(tr);
18896
+ const entries = Object.entries(this.rawCommands).map(([name, command2]) => {
18897
+ const method = (...args) => {
18898
+ const fn2 = command2(...args)(props);
18899
+ if (!tr.getMeta("preventDispatch")) {
18900
+ view.dispatch(tr);
18901
+ }
18902
+ return fn2;
18903
+ };
18904
+ return [name, method];
18905
+ });
18906
+ return Object.fromEntries(entries);
18932
18907
  }
18933
- return {
18934
- name: "w:p",
18935
- elements,
18936
- attributes
18937
- };
18938
- }
18939
- function generateParagraphProperties(node2) {
18940
- const { attrs = {} } = node2;
18941
- const pPrElements = [];
18942
- const { styleId } = attrs;
18943
- if (styleId) pPrElements.push({ name: "w:pStyle", attributes: { "w:val": styleId } });
18944
- const { spacing, indent, textAlign, textIndent, lineHeight: lineHeight2, marksAttrs, keepLines, keepNext, dropcap } = attrs;
18945
- if (spacing) {
18946
- const { lineSpaceBefore, lineSpaceAfter, line, lineRule } = spacing;
18947
- const attributes = {};
18948
- if (lineSpaceBefore >= 0) attributes["w:before"] = pixelsToTwips(lineSpaceBefore);
18949
- if (lineSpaceAfter >= 0) attributes["w:after"] = pixelsToTwips(lineSpaceAfter);
18950
- if (lineRule === "exact") {
18951
- if (lineHeight2) attributes["w:line"] = ptToTwips(parseFloat(lineHeight2));
18952
- } else {
18953
- if (lineHeight2) attributes["w:line"] = linesToTwips(lineHeight2);
18954
- }
18955
- attributes["w:lineRule"] = lineRule || "auto";
18956
- const spacingElement = {
18957
- name: "w:spacing",
18958
- attributes
18959
- };
18960
- pPrElements.push(spacingElement);
18908
+ /**
18909
+ * Create a chain of commands to call multiple commands at once.
18910
+ */
18911
+ get chain() {
18912
+ return () => this.createChain();
18961
18913
  }
18962
- if (lineHeight2 && !spacing) {
18963
- const spacingElement = {
18964
- name: "w:spacing",
18965
- attributes: {
18966
- "w:line": linesToTwips(lineHeight2)
18914
+ /**
18915
+ * Check if a command or a chain of commands can be executed. Without executing it.
18916
+ */
18917
+ get can() {
18918
+ return () => this.createCan();
18919
+ }
18920
+ /**
18921
+ * Creates a chain of commands.
18922
+ * @param startTr Start transaction.
18923
+ * @param shouldDispatch Should dispatch or not.
18924
+ */
18925
+ createChain(startTr, shouldDispatch = true) {
18926
+ const { editor, state: state2, rawCommands } = this;
18927
+ const { view } = editor;
18928
+ const callbacks2 = [];
18929
+ const hasStartTr = !!startTr;
18930
+ const tr = startTr || state2.tr;
18931
+ const run2 = () => {
18932
+ if (!hasStartTr && shouldDispatch && !tr.getMeta("preventDispatch")) {
18933
+ view.dispatch(tr);
18967
18934
  }
18935
+ return callbacks2.every((cb) => cb === true);
18968
18936
  };
18969
- pPrElements.push(spacingElement);
18970
- }
18971
- if (indent) {
18972
- const { left: left2, right: right2, firstLine, hanging } = indent;
18973
- const attributes = {};
18974
- if (left2 || left2 === 0) attributes["w:left"] = pixelsToTwips(left2);
18975
- if (right2 || right2 === 0) attributes["w:right"] = pixelsToTwips(right2);
18976
- if (firstLine || firstLine === 0) attributes["w:firstLine"] = pixelsToTwips(firstLine);
18977
- if (hanging || hanging === 0) attributes["w:hanging"] = pixelsToTwips(hanging);
18978
- if (textIndent && !attributes["w:left"]) {
18979
- attributes["w:left"] = inchesToTwips(textIndent);
18980
- }
18981
- const indentElement = {
18982
- name: "w:ind",
18983
- attributes
18937
+ const entries = Object.entries(rawCommands).map(([name, command2]) => {
18938
+ const chainedCommand = (...args) => {
18939
+ const props = this.createProps(tr, shouldDispatch);
18940
+ const callback = command2(...args)(props);
18941
+ callbacks2.push(callback);
18942
+ return chain;
18943
+ };
18944
+ return [name, chainedCommand];
18945
+ });
18946
+ const chain = {
18947
+ ...Object.fromEntries(entries),
18948
+ run: run2
18984
18949
  };
18985
- pPrElements.push(indentElement);
18986
- } else if (textIndent) {
18987
- const indentElement = {
18988
- name: "w:ind",
18989
- attributes: {
18990
- "w:left": inchesToTwips(textIndent)
18991
- }
18950
+ return chain;
18951
+ }
18952
+ /**
18953
+ * Creates a can check for commands.
18954
+ * @param startTr Start transaction.
18955
+ */
18956
+ createCan(startTr) {
18957
+ const { rawCommands, state: state2 } = this;
18958
+ const dispatch = false;
18959
+ const tr = startTr || state2.tr;
18960
+ const props = this.createProps(tr, dispatch);
18961
+ const commands2 = Object.fromEntries(
18962
+ Object.entries(rawCommands).map(([name, command2]) => {
18963
+ return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
18964
+ })
18965
+ );
18966
+ return {
18967
+ ...commands2,
18968
+ chain: () => this.createChain(tr, dispatch)
18992
18969
  };
18993
- pPrElements.push(indentElement);
18994
18970
  }
18995
- if (textAlign) {
18996
- const textAlignElement = {
18997
- name: "w:jc",
18998
- attributes: { "w:val": textAlign === "justify" ? "both" : textAlign }
18971
+ /**
18972
+ * Creates default props for the command method.
18973
+ * @param {*} tr Transaction.
18974
+ * @param {*} shouldDispatch Check if should dispatch.
18975
+ * @returns Object with props.
18976
+ */
18977
+ createProps(tr, shouldDispatch = true) {
18978
+ const { editor, state: state2, rawCommands } = this;
18979
+ const { view } = editor;
18980
+ const props = {
18981
+ tr,
18982
+ editor,
18983
+ view,
18984
+ state: chainableEditorState(tr, state2),
18985
+ dispatch: shouldDispatch ? () => void 0 : void 0,
18986
+ chain: () => this.createChain(tr, shouldDispatch),
18987
+ can: () => this.createCan(tr),
18988
+ get commands() {
18989
+ return Object.fromEntries(
18990
+ Object.entries(rawCommands).map(([name, command2]) => {
18991
+ return [name, (...args) => command2(...args)(props)];
18992
+ })
18993
+ );
18994
+ }
18999
18995
  };
19000
- pPrElements.push(textAlignElement);
18996
+ return props;
19001
18997
  }
19002
- if (marksAttrs) {
19003
- const outputMarks = processOutputMarks(marksAttrs);
19004
- const rPrElement = generateRunProps(outputMarks);
19005
- pPrElements.push(rPrElement);
18998
+ }
18999
+ function getHTMLFromFragment(fragment, schema) {
19000
+ const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment);
19001
+ const temporaryDocument = document.implementation.createHTMLDocument();
19002
+ const container = temporaryDocument.createElement("div");
19003
+ container.appendChild(documentFragment);
19004
+ return container.innerHTML;
19005
+ }
19006
+ const getTextContentFromNodes = ($from, maxMatch = 500) => {
19007
+ let textBefore = "";
19008
+ const sliceEndPos = $from.parentOffset;
19009
+ $from.parent.nodesBetween(
19010
+ Math.max(0, sliceEndPos - maxMatch),
19011
+ sliceEndPos,
19012
+ (node2, pos, parent, index2) => {
19013
+ const chunk = node2.type.spec.toText?.({
19014
+ node: node2,
19015
+ pos,
19016
+ parent,
19017
+ index: index2
19018
+ }) || node2.textContent || "%leaf%";
19019
+ textBefore += node2.isAtom && !node2.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));
19020
+ }
19021
+ );
19022
+ return textBefore;
19023
+ };
19024
+ const handleDocxPaste = (html, editor, view, plugin2) => {
19025
+ const { converter } = editor;
19026
+ if (!converter || !converter.convertedXml) return handleHtmlPaste(html, editor, view, plugin2);
19027
+ let cleanedHtml = convertEmToPt(html);
19028
+ cleanedHtml = cleanHtmlUnnecessaryTags(cleanedHtml);
19029
+ const tempDiv = document.createElement("div");
19030
+ tempDiv.innerHTML = cleanedHtml;
19031
+ const paragraphs = tempDiv.querySelectorAll("p");
19032
+ paragraphs.forEach((p) => {
19033
+ const innerHTML3 = p.innerHTML;
19034
+ if (!innerHTML3.includes("<!--[if !supportLists]")) return;
19035
+ const styleAttr = p.getAttribute("style") || "";
19036
+ const msoListMatch = styleAttr.match(/mso-list:\s*l(\d+)\s+level(\d+)/);
19037
+ if (msoListMatch) {
19038
+ const [, abstractId, level] = msoListMatch;
19039
+ const listNumId = getListNumIdFromAbstract(abstractId, editor);
19040
+ if (!listNumId) return;
19041
+ const abstractDefinition = getListAbstractDefinition(abstractId, editor);
19042
+ const { lvlText, start: start2, numFmt } = getLevelDefinition(abstractDefinition, level - 1);
19043
+ p.setAttribute("data-num-id", listNumId);
19044
+ p.setAttribute("data-list-level", level - 1);
19045
+ p.setAttribute("data-start", start2);
19046
+ p.setAttribute("data-lvl-text", lvlText);
19047
+ p.setAttribute("data-num-fmt", numFmt);
19048
+ }
19049
+ extractAndRemoveConditionalPrefix(p);
19050
+ });
19051
+ transformWordLists(tempDiv);
19052
+ const doc2 = DOMParser$1.fromSchema(editor.schema).parse(tempDiv);
19053
+ tempDiv.remove();
19054
+ const { dispatch } = editor.view;
19055
+ if (!dispatch) return false;
19056
+ dispatch(view.state.tr.replaceSelectionWith(doc2, true));
19057
+ return true;
19058
+ };
19059
+ const getLevelDefinition = (abstractDefinition, level) => {
19060
+ if (!abstractDefinition || !abstractDefinition.elements) return null;
19061
+ const levelElement = abstractDefinition.elements.find((el) => {
19062
+ return el.name === "w:lvl" && el.attributes?.["w:ilvl"] == level;
19063
+ });
19064
+ if (!levelElement) return null;
19065
+ const { elements } = levelElement;
19066
+ const lvlText = elements.find((el) => el.name === "w:lvlText")?.attributes?.["w:val"];
19067
+ const start2 = elements.find((el) => el.name === "w:start")?.attributes?.["w:val"];
19068
+ const numFmt = elements.find((el) => el.name === "w:numFmt")?.attributes?.["w:val"];
19069
+ return { lvlText, start: start2, numFmt, elements };
19070
+ };
19071
+ const getListNumIdFromAbstract = (abstractId, editor) => {
19072
+ const { definitions } = editor?.converter?.numbering;
19073
+ if (!definitions) return null;
19074
+ const matchedDefinition = Object.values(definitions).find((def) => {
19075
+ return def.elements.some((el) => el.name === "w:abstractNumId" && el.attributes?.["w:val"] == abstractId);
19076
+ });
19077
+ return matchedDefinition?.attributes?.["w:numId"];
19078
+ };
19079
+ const getListAbstractDefinition = (abstractId, editor) => {
19080
+ const { abstracts = {} } = editor?.converter?.numbering;
19081
+ return abstracts[abstractId] || null;
19082
+ };
19083
+ const transformWordLists = (container) => {
19084
+ const paragraphs = Array.from(container.querySelectorAll("p[data-num-id]"));
19085
+ const listMap = /* @__PURE__ */ new Map();
19086
+ const listLevels = {};
19087
+ for (const p of paragraphs) {
19088
+ const listId = p.getAttribute("data-num-id");
19089
+ const level = parseInt(p.getAttribute("data-list-level"));
19090
+ const numFmt = p.getAttribute("data-num-fmt");
19091
+ const start2 = p.getAttribute("data-start");
19092
+ const lvlText = p.getAttribute("data-lvl-text");
19093
+ if (!listMap.has(listId)) listMap.set(listId, []);
19094
+ listMap.get(listId).push({ p, level, numFmt, start: start2, lvlText });
19006
19095
  }
19007
- if (keepLines) {
19008
- pPrElements.push({
19009
- name: "w:keepLines",
19010
- attributes: { "w:val": keepLines }
19096
+ for (const [id, items] of listMap.entries()) {
19097
+ if (!listLevels[id]) {
19098
+ listLevels[id] = {
19099
+ stack: [],
19100
+ counts: {},
19101
+ prevLevel: null
19102
+ };
19103
+ }
19104
+ const parentStack = [];
19105
+ items.forEach(({ p, level, numFmt, start: start2, lvlText }, index2) => {
19106
+ const listLevel = generateListNestingPath(listLevels, id, level);
19107
+ const li = document.createElement("li");
19108
+ li.innerHTML = p.innerHTML;
19109
+ li.setAttribute("data-list-level", JSON.stringify(listLevel));
19110
+ li.setAttribute("data-num-id", id);
19111
+ li.setAttribute("data-lvl-text", lvlText);
19112
+ li.setAttribute("data-num-fmt", numFmt);
19113
+ if (p.hasAttribute("data-font-family")) {
19114
+ li.setAttribute("data-font-family", p.getAttribute("data-font-family"));
19115
+ }
19116
+ if (p.hasAttribute("data-font-size")) {
19117
+ li.setAttribute("data-font-size", p.getAttribute("data-font-size"));
19118
+ }
19119
+ const parentNode2 = p.parentNode;
19120
+ let listForLevel = parentStack[level];
19121
+ if (!listForLevel) {
19122
+ const newList = document.createElement("ol");
19123
+ newList.setAttribute("data-list-id", id);
19124
+ newList.level = level;
19125
+ if (level > 0) {
19126
+ const parentLi = parentStack[level - 1]?.querySelector("li:last-child");
19127
+ if (parentLi) parentLi.appendChild(newList);
19128
+ } else {
19129
+ parentNode2.insertBefore(newList, p);
19130
+ }
19131
+ parentStack[level] = newList;
19132
+ parentStack.length = level + 1;
19133
+ listForLevel = newList;
19134
+ }
19135
+ listForLevel.appendChild(li);
19136
+ p.remove();
19011
19137
  });
19012
19138
  }
19013
- if (keepNext) {
19014
- pPrElements.push({
19015
- name: "w:keepNext",
19016
- attributes: { "w:val": keepNext }
19017
- });
19139
+ };
19140
+ function generateListNestingPath(listLevels, listId, currentLevel) {
19141
+ const levelState = listLevels[listId];
19142
+ if (!levelState.stack) levelState.stack = [];
19143
+ if (levelState.prevLevel === void 0) levelState.prevLevel = null;
19144
+ if (levelState.prevLevel === null) {
19145
+ levelState.stack = Array(currentLevel).fill(1).concat(1);
19146
+ } else {
19147
+ if (currentLevel > levelState.prevLevel) {
19148
+ levelState.stack.push(1);
19149
+ } else if (currentLevel === levelState.prevLevel) {
19150
+ levelState.stack[levelState.stack.length - 1]++;
19151
+ } else {
19152
+ levelState.stack = levelState.stack.slice(0, currentLevel + 1);
19153
+ levelState.stack[currentLevel] = (levelState.stack[currentLevel] || 1) + 1;
19154
+ }
19018
19155
  }
19019
- if (dropcap) {
19020
- pPrElements.push({
19021
- name: "w:framePr",
19022
- attributes: {
19023
- "w:dropCap": dropcap.type,
19024
- "w:lines": dropcap.lines,
19025
- "w:wrap": dropcap.wrap,
19026
- "w:vAnchor": dropcap.vAnchor,
19027
- "w:hAnchor": dropcap.hAnchor
19156
+ levelState.prevLevel = currentLevel;
19157
+ return [...levelState.stack];
19158
+ }
19159
+ function extractAndRemoveConditionalPrefix(p) {
19160
+ const nodes = Array.from(p.childNodes);
19161
+ let fontFamily2 = null;
19162
+ let fontSize2 = null;
19163
+ let start2 = -1, end2 = -1;
19164
+ nodes.forEach((node2, index2) => {
19165
+ if (node2.nodeType === Node.COMMENT_NODE && node2.nodeValue.includes("[if !supportLists]")) {
19166
+ start2 = index2;
19167
+ }
19168
+ if (start2 !== -1 && node2.nodeType === Node.COMMENT_NODE && node2.nodeValue.includes("[endif]")) {
19169
+ end2 = index2;
19170
+ }
19171
+ });
19172
+ if (start2 !== -1 && end2 !== -1) {
19173
+ for (let i = start2 + 1; i < end2; i++) {
19174
+ const node2 = nodes[i];
19175
+ if (node2.nodeType === Node.ELEMENT_NODE && node2.style) {
19176
+ fontFamily2 = fontFamily2 || node2.style.fontFamily;
19177
+ fontSize2 = fontSize2 || node2.style.fontSize;
19028
19178
  }
19029
- });
19179
+ }
19180
+ for (let i = end2; i >= start2; i--) {
19181
+ p.removeChild(p.childNodes[i]);
19182
+ }
19183
+ if (fontFamily2) p.setAttribute("data-font-family", fontFamily2);
19184
+ if (fontSize2) p.setAttribute("data-font-size", fontSize2);
19030
19185
  }
19031
- const sectPr = node2.attrs?.paragraphProperties?.sectPr;
19032
- if (sectPr) {
19033
- pPrElements.push(sectPr);
19186
+ }
19187
+ class InputRule {
19188
+ constructor(config) {
19189
+ __publicField$2(this, "match");
19190
+ __publicField$2(this, "handler");
19191
+ this.match = config.match;
19192
+ this.handler = config.handler;
19034
19193
  }
19035
- if (!pPrElements.length) return null;
19036
- return {
19037
- name: "w:pPr",
19038
- elements: pPrElements
19039
- };
19040
19194
  }
19041
- function translateDocumentNode(params2) {
19042
- const bodyNode = {
19043
- type: "body",
19044
- content: params2.node.content
19195
+ const inputRuleMatcherHandler = (text, match) => {
19196
+ if (isRegExp(match)) {
19197
+ return match.exec(text);
19198
+ }
19199
+ const inputRuleMatch = match(text);
19200
+ if (!inputRuleMatch) {
19201
+ return null;
19202
+ }
19203
+ const result = [inputRuleMatch.text];
19204
+ result.index = inputRuleMatch.index;
19205
+ result.input = text;
19206
+ result.data = inputRuleMatch.data;
19207
+ if (inputRuleMatch.replaceWith) {
19208
+ if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
19209
+ console.warn(
19210
+ '[super-editor warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'
19211
+ );
19212
+ }
19213
+ result.push(inputRuleMatch.replaceWith);
19214
+ }
19215
+ return result;
19216
+ };
19217
+ const run = (config) => {
19218
+ const {
19219
+ editor,
19220
+ from: from2,
19221
+ to,
19222
+ text,
19223
+ rules,
19224
+ plugin: plugin2
19225
+ } = config;
19226
+ const { view } = editor;
19227
+ if (view.composing) {
19228
+ return false;
19229
+ }
19230
+ const $from = view.state.doc.resolve(from2);
19231
+ if ($from.parent.type.spec.code || !!($from.nodeBefore || $from.nodeAfter)?.marks.find((mark) => mark.type.spec.code)) {
19232
+ return false;
19233
+ }
19234
+ let matched = false;
19235
+ const textBefore = getTextContentFromNodes($from) + text;
19236
+ rules.forEach((rule) => {
19237
+ if (matched) {
19238
+ return;
19239
+ }
19240
+ const match = inputRuleMatcherHandler(textBefore, rule.match);
19241
+ if (!match) {
19242
+ return;
19243
+ }
19244
+ const tr = view.state.tr;
19245
+ const state2 = chainableEditorState(tr, view.state);
19246
+ const range2 = {
19247
+ from: from2 - (match[0].length - text.length),
19248
+ to
19249
+ };
19250
+ const { commands: commands2, chain, can } = new CommandService({
19251
+ editor,
19252
+ state: state2
19253
+ });
19254
+ const handler = rule.handler({
19255
+ state: state2,
19256
+ range: range2,
19257
+ match,
19258
+ commands: commands2,
19259
+ chain,
19260
+ can
19261
+ });
19262
+ if (handler === null || !tr.steps.length) {
19263
+ return;
19264
+ }
19265
+ tr.setMeta(plugin2, {
19266
+ transform: tr,
19267
+ from: from2,
19268
+ to,
19269
+ text
19270
+ });
19271
+ view.dispatch(tr);
19272
+ matched = true;
19273
+ });
19274
+ return matched;
19275
+ };
19276
+ const inputRulesPlugin = ({ editor, rules }) => {
19277
+ const plugin2 = new Plugin({
19278
+ key: new PluginKey("inputRulesPlugin"),
19279
+ state: {
19280
+ init() {
19281
+ return null;
19282
+ },
19283
+ apply(tr, prev, state2) {
19284
+ const stored = tr.getMeta(plugin2);
19285
+ if (stored) {
19286
+ return stored;
19287
+ }
19288
+ const simulatedInputMeta = tr.getMeta("applyInputRules");
19289
+ const isSimulatedInput = !!simulatedInputMeta;
19290
+ if (isSimulatedInput) {
19291
+ setTimeout(() => {
19292
+ let { text } = simulatedInputMeta;
19293
+ if (typeof text !== "string") {
19294
+ text = getHTMLFromFragment(Fragment.from(text), state2.schema);
19295
+ }
19296
+ const { from: from2 } = simulatedInputMeta;
19297
+ const to = from2 + text.length;
19298
+ run({
19299
+ editor,
19300
+ from: from2,
19301
+ to,
19302
+ text,
19303
+ rules,
19304
+ plugin: plugin2
19305
+ });
19306
+ });
19307
+ }
19308
+ return tr.selectionSet || tr.docChanged ? null : prev;
19309
+ }
19310
+ },
19311
+ props: {
19312
+ handleTextInput(view, from2, to, text) {
19313
+ return run({
19314
+ editor,
19315
+ from: from2,
19316
+ to,
19317
+ text,
19318
+ rules,
19319
+ plugin: plugin2
19320
+ });
19321
+ },
19322
+ // add support for input rules to trigger on enter
19323
+ // this is useful for example for code blocks
19324
+ handleKeyDown(view, event) {
19325
+ if (event.key !== "Enter") {
19326
+ return false;
19327
+ }
19328
+ const { $cursor } = view.state.selection;
19329
+ if ($cursor) {
19330
+ return run({
19331
+ editor,
19332
+ from: $cursor.pos,
19333
+ to: $cursor.pos,
19334
+ text: "\n",
19335
+ rules,
19336
+ plugin: plugin2
19337
+ });
19338
+ }
19339
+ return false;
19340
+ },
19341
+ // Paste handler
19342
+ handlePaste(view, event, slice2) {
19343
+ const clipboard = event.clipboardData;
19344
+ const html = clipboard.getData("text/html");
19345
+ clipboard.getData("text/plain");
19346
+ const fieldAnnotationContent = slice2.content.content.filter((item) => item.type.name === "fieldAnnotation");
19347
+ if (fieldAnnotationContent.length) {
19348
+ return false;
19349
+ }
19350
+ let source;
19351
+ if (!html) {
19352
+ source = "plain-text";
19353
+ } else if (isWordHtml(html)) {
19354
+ source = "word-html";
19355
+ } else {
19356
+ source = "browser-html";
19357
+ }
19358
+ switch (source) {
19359
+ case "plain-text":
19360
+ break;
19361
+ case "word-html":
19362
+ if (editor.options.mode === "docx") {
19363
+ return handleDocxPaste(html, editor, view, plugin2);
19364
+ }
19365
+ case "browser-html":
19366
+ return handleHtmlPaste$1(html, editor);
19367
+ }
19368
+ return false;
19369
+ }
19370
+ },
19371
+ isInputRules: true
19372
+ });
19373
+ return plugin2;
19374
+ };
19375
+ function isWordHtml(html) {
19376
+ return /class=["']?Mso|xmlns:o=["']?urn:schemas-microsoft-com|<!--\[if gte mso|<meta[^>]+name=["']?Generator["']?[^>]+Word/i.test(html);
19377
+ }
19378
+ const handleHtmlPaste$1 = (html, editor, plugin2) => {
19379
+ const htmlWithPtSizing = convertEmToPt(html);
19380
+ const cleanedHtml = sanitizeHtml(htmlWithPtSizing);
19381
+ const doc2 = DOMParser$1.fromSchema(editor.schema).parse(cleanedHtml);
19382
+ const { dispatch } = editor.view;
19383
+ if (!dispatch) return false;
19384
+ dispatch(editor.view.state.tr.replaceSelectionWith(doc2, true));
19385
+ return true;
19386
+ };
19387
+ const convertEmToPt = (html) => {
19388
+ return html.replace(
19389
+ /font-size\s*:\s*([\d.]+)em/gi,
19390
+ (_, emValue) => {
19391
+ const em = parseFloat(emValue);
19392
+ const pt = Math.round(em * 12 * 100) / 100;
19393
+ return `font-size: ${pt}pt`;
19394
+ }
19395
+ );
19396
+ };
19397
+ function cleanHtmlUnnecessaryTags(html) {
19398
+ return html.replace(/<o:p>.*?<\/o:p>/gi, "").replace(/&nbsp;/gi, " ").replace(/<span[^>]*>\s*<\/span>/gi, "").replace(/<p[^>]*>\s*<\/p>/gi, "").trim();
19399
+ }
19400
+ function sanitizeHtml(html, forbiddenTags = ["meta", "svg", "script", "style", "button"]) {
19401
+ const container = document.createElement("div");
19402
+ container.innerHTML = html;
19403
+ const walkAndClean = (node2) => {
19404
+ for (const child of [...node2.children]) {
19405
+ if (forbiddenTags.includes(child.tagName.toLowerCase())) {
19406
+ child.remove();
19407
+ continue;
19408
+ }
19409
+ if (child.hasAttribute("linebreaktype")) {
19410
+ child.removeAttribute("linebreaktype");
19411
+ }
19412
+ walkAndClean(child);
19413
+ }
19414
+ };
19415
+ walkAndClean(container);
19416
+ return container;
19417
+ }
19418
+ function exportSchemaToJson(params2) {
19419
+ const { type: type2 } = params2.node || {};
19420
+ const router = {
19421
+ doc: translateDocumentNode,
19422
+ body: translateBodyNode,
19423
+ paragraph: translateParagraphNode,
19424
+ text: translateTextNode,
19425
+ bulletList: translateList,
19426
+ orderedList: translateList,
19427
+ lineBreak: translateLineBreak,
19428
+ table: translateTable,
19429
+ tableRow: translateTableRow,
19430
+ tableCell: translateTableCell,
19431
+ bookmarkStart: translateBookmarkStart,
19432
+ fieldAnnotation: translateFieldAnnotation,
19433
+ tab: translateTab,
19434
+ image: translateImageNode,
19435
+ hardBreak: translateHardBreak,
19436
+ commentRangeStart: () => translateCommentNode(params2, "Start"),
19437
+ commentRangeEnd: () => translateCommentNode(params2, "End"),
19438
+ commentReference: () => null,
19439
+ shapeContainer: translateShapeContainer,
19440
+ shapeTextbox: translateShapeTextbox,
19441
+ contentBlock: translateContentBlock,
19442
+ structuredContent: translateStructuredContent,
19443
+ "page-number": translatePageNumberNode,
19444
+ "total-page-number": translateTotalPageNumberNode
19445
+ };
19446
+ if (!router[type2]) {
19447
+ console.error("No translation function found for node type:", type2);
19448
+ return null;
19449
+ }
19450
+ return router[type2](params2);
19451
+ }
19452
+ function translateBodyNode(params2) {
19453
+ let sectPr = params2.bodyNode?.elements.find((n) => n.name === "w:sectPr") || {};
19454
+ if (params2.converter) {
19455
+ const hasHeader = sectPr?.elements?.some((n) => n.name === "w:headerReference");
19456
+ const hasDefaultHeader = params2.converter.headerIds?.default;
19457
+ if (!hasHeader && hasDefaultHeader && !params2.editor.options.isHeaderOrFooter) {
19458
+ const defaultHeader = generateDefaultHeaderFooter("header", params2.converter.headerIds?.default);
19459
+ sectPr.elements.push(defaultHeader);
19460
+ }
19461
+ const hasFooter = sectPr?.elements?.some((n) => n.name === "w:footerReference");
19462
+ const hasDefaultFooter = params2.converter.footerIds?.default;
19463
+ if (!hasFooter && hasDefaultFooter && !params2.editor.options.isHeaderOrFooter) {
19464
+ const defaultFooter = generateDefaultHeaderFooter("footer", params2.converter.footerIds?.default);
19465
+ sectPr.elements.push(defaultFooter);
19466
+ }
19467
+ const newMargins = params2.converter.pageStyles.pageMargins;
19468
+ const sectPrMargins = sectPr.elements.find((n) => n.name === "w:pgMar");
19469
+ const { attributes } = sectPrMargins;
19470
+ Object.entries(newMargins).forEach(([key, value]) => {
19471
+ const convertedValue = inchesToTwips(value);
19472
+ attributes[`w:${key}`] = convertedValue;
19473
+ });
19474
+ sectPrMargins.attributes = attributes;
19475
+ }
19476
+ const elements = translateChildNodes(params2);
19477
+ if (params2.isHeaderFooter) {
19478
+ return {
19479
+ name: "w:body",
19480
+ elements: [...elements]
19481
+ };
19482
+ }
19483
+ return {
19484
+ name: "w:body",
19485
+ elements: [...elements, sectPr]
19486
+ };
19487
+ }
19488
+ const generateDefaultHeaderFooter = (type2, id) => {
19489
+ return {
19490
+ "type": "element",
19491
+ "name": `w:${type2}Reference`,
19492
+ "attributes": {
19493
+ "w:type": "default",
19494
+ "r:id": id
19495
+ }
19496
+ };
19497
+ };
19498
+ function translateParagraphNode(params2) {
19499
+ const elements = translateChildNodes(params2);
19500
+ const htmlAnnotationChild = elements.find((element) => element.name === "htmlAnnotation");
19501
+ if (htmlAnnotationChild) {
19502
+ return htmlAnnotationChild.elements;
19503
+ }
19504
+ const pPr = generateParagraphProperties(params2.node);
19505
+ if (pPr) elements.unshift(pPr);
19506
+ let attributes = {};
19507
+ if (params2.node.attrs?.rsidRDefault) {
19508
+ attributes["w:rsidRDefault"] = params2.node.attrs.rsidRDefault;
19509
+ }
19510
+ return {
19511
+ name: "w:p",
19512
+ elements,
19513
+ attributes
19514
+ };
19515
+ }
19516
+ function generateParagraphProperties(node2) {
19517
+ const { attrs = {} } = node2;
19518
+ const pPrElements = [];
19519
+ const { styleId } = attrs;
19520
+ if (styleId) pPrElements.push({ name: "w:pStyle", attributes: { "w:val": styleId } });
19521
+ const { spacing, indent, textAlign, textIndent, lineHeight: lineHeight2, marksAttrs, keepLines, keepNext, dropcap } = attrs;
19522
+ if (spacing) {
19523
+ const { lineSpaceBefore, lineSpaceAfter, line, lineRule } = spacing;
19524
+ const attributes = {};
19525
+ if (lineSpaceBefore >= 0) attributes["w:before"] = pixelsToTwips(lineSpaceBefore);
19526
+ if (lineSpaceAfter >= 0) attributes["w:after"] = pixelsToTwips(lineSpaceAfter);
19527
+ if (lineRule === "exact") {
19528
+ if (lineHeight2) attributes["w:line"] = ptToTwips(parseFloat(lineHeight2));
19529
+ } else {
19530
+ if (lineHeight2) attributes["w:line"] = linesToTwips(lineHeight2);
19531
+ }
19532
+ attributes["w:lineRule"] = lineRule || "auto";
19533
+ const spacingElement = {
19534
+ name: "w:spacing",
19535
+ attributes
19536
+ };
19537
+ pPrElements.push(spacingElement);
19538
+ }
19539
+ if (lineHeight2 && !spacing) {
19540
+ const spacingElement = {
19541
+ name: "w:spacing",
19542
+ attributes: {
19543
+ "w:line": linesToTwips(lineHeight2)
19544
+ }
19545
+ };
19546
+ pPrElements.push(spacingElement);
19547
+ }
19548
+ if (indent) {
19549
+ const { left: left2, right: right2, firstLine, hanging } = indent;
19550
+ const attributes = {};
19551
+ if (left2 || left2 === 0) attributes["w:left"] = pixelsToTwips(left2);
19552
+ if (right2 || right2 === 0) attributes["w:right"] = pixelsToTwips(right2);
19553
+ if (firstLine || firstLine === 0) attributes["w:firstLine"] = pixelsToTwips(firstLine);
19554
+ if (hanging || hanging === 0) attributes["w:hanging"] = pixelsToTwips(hanging);
19555
+ if (textIndent && !attributes["w:left"]) {
19556
+ attributes["w:left"] = inchesToTwips(textIndent);
19557
+ }
19558
+ const indentElement = {
19559
+ name: "w:ind",
19560
+ attributes
19561
+ };
19562
+ pPrElements.push(indentElement);
19563
+ } else if (textIndent) {
19564
+ const indentElement = {
19565
+ name: "w:ind",
19566
+ attributes: {
19567
+ "w:left": inchesToTwips(textIndent)
19568
+ }
19569
+ };
19570
+ pPrElements.push(indentElement);
19571
+ }
19572
+ if (textAlign) {
19573
+ const textAlignElement = {
19574
+ name: "w:jc",
19575
+ attributes: { "w:val": textAlign === "justify" ? "both" : textAlign }
19576
+ };
19577
+ pPrElements.push(textAlignElement);
19578
+ }
19579
+ if (marksAttrs) {
19580
+ const outputMarks = processOutputMarks(marksAttrs);
19581
+ const rPrElement = generateRunProps(outputMarks);
19582
+ pPrElements.push(rPrElement);
19583
+ }
19584
+ if (keepLines) {
19585
+ pPrElements.push({
19586
+ name: "w:keepLines",
19587
+ attributes: { "w:val": keepLines }
19588
+ });
19589
+ }
19590
+ if (keepNext) {
19591
+ pPrElements.push({
19592
+ name: "w:keepNext",
19593
+ attributes: { "w:val": keepNext }
19594
+ });
19595
+ }
19596
+ if (dropcap) {
19597
+ pPrElements.push({
19598
+ name: "w:framePr",
19599
+ attributes: {
19600
+ "w:dropCap": dropcap.type,
19601
+ "w:lines": dropcap.lines,
19602
+ "w:wrap": dropcap.wrap,
19603
+ "w:vAnchor": dropcap.vAnchor,
19604
+ "w:hAnchor": dropcap.hAnchor
19605
+ }
19606
+ });
19607
+ }
19608
+ const sectPr = node2.attrs?.paragraphProperties?.sectPr;
19609
+ if (sectPr) {
19610
+ pPrElements.push(sectPr);
19611
+ }
19612
+ if (!pPrElements.length) return null;
19613
+ return {
19614
+ name: "w:pPr",
19615
+ elements: pPrElements
19616
+ };
19617
+ }
19618
+ function translateDocumentNode(params2) {
19619
+ const bodyNode = {
19620
+ type: "body",
19621
+ content: params2.node.content
19045
19622
  };
19046
19623
  const translatedBodyNode = exportSchemaToJson({ ...params2, node: bodyNode });
19047
19624
  const node2 = {
@@ -20181,12 +20758,11 @@ function prepareHtmlAnnotation(params2) {
20181
20758
  node: { attrs = {}, marks = [] },
20182
20759
  editorSchema
20183
20760
  } = params2;
20184
- const parser = new window.DOMParser();
20185
- const paragraphHtml = parser.parseFromString(attrs.rawHtml || attrs.displayLabel, "text/html");
20761
+ const paragraphHtmlContainer = sanitizeHtml(attrs.rawHtml);
20186
20762
  const marksFromAttrs = translateFieldAttrsToMarks(attrs);
20187
20763
  const allMarks = [...marks, ...marksFromAttrs];
20188
20764
  let state2 = EditorState.create({
20189
- doc: DOMParser$1.fromSchema(editorSchema).parse(paragraphHtml)
20765
+ doc: DOMParser$1.fromSchema(editorSchema).parse(paragraphHtmlContainer)
20190
20766
  });
20191
20767
  if (allMarks.length) {
20192
20768
  state2 = applyMarksToHtmlAnnotation(state2, allMarks);
@@ -23251,6 +23827,7 @@ const importHeadersFooters = (docx, converter, mainEditor) => {
23251
23827
  const footers = elements.filter((el) => el.attributes["Type"] === footerType);
23252
23828
  const sectPr = findSectPr(docx["word/document.xml"]) || [];
23253
23829
  const allSectPrElements = sectPr.flatMap((el) => el.elements);
23830
+ if (!mainEditor) return;
23254
23831
  const editor = { ...mainEditor };
23255
23832
  editor.options.annotations = true;
23256
23833
  headers.forEach((header) => {
@@ -23412,7 +23989,7 @@ const _SuperConverter = class _SuperConverter2 {
23412
23989
  return;
23413
23990
  }
23414
23991
  }
23415
- static updateDocumentVersion(docx = this.convertedXml, version2 = "0.13.2-rev1") {
23992
+ static updateDocumentVersion(docx = this.convertedXml, version2 = "0.13.2-rev11") {
23416
23993
  const customLocation = "docProps/custom.xml";
23417
23994
  if (!docx[customLocation]) {
23418
23995
  docx[customLocation] = generateCustomXml();
@@ -23879,7 +24456,7 @@ function storeSuperdocVersion(docx) {
23879
24456
  function generateCustomXml() {
23880
24457
  return DEFAULT_CUSTOM_XML;
23881
24458
  }
23882
- function generateSuperdocVersion(pid = 2, version2 = "0.13.2-rev1") {
24459
+ function generateSuperdocVersion(pid = 2, version2 = "0.13.2-rev11") {
23883
24460
  return {
23884
24461
  type: "element",
23885
24462
  name: "property",
@@ -26412,7 +26989,7 @@ var __privateGet$1 = (obj, member, getter) => (__accessCheck$1(obj, member, "rea
26412
26989
  var __privateAdd$1 = (obj, member, value) => member.has(obj) ? __typeError$1("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
26413
26990
  var __privateSet = (obj, member, value, setter) => (__accessCheck$1(obj, member, "write to private field"), member.set(obj, value), value);
26414
26991
  var __privateMethod$1 = (obj, member, method) => (__accessCheck$1(obj, member, "access private method"), method);
26415
- var _Attribute_static, getGlobalAttributes_fn, getNodeAndMarksAttributes_fn, _Schema_static, createNodesSchema_fn, createMarksSchema_fn, _events, _ExtensionService_instances, setupExtensions_fn, attachEditorEvents_fn, _commandService, _css, _Editor_instances, initContainerElement_fn, init_fn, initRichText_fn, onFocus_fn, checkHeadless_fn, insertNewFileData_fn, registerPluginByNameIfNotExists_fn, createExtensionService_fn, createCommandService_fn, createConverter_fn, initMedia_fn, initFonts_fn, createSchema_fn, generatePmData_fn, createDocFromHTML_fn, createView_fn, onCollaborationReady_fn, initComments_fn, initPagination_fn, dispatchTransaction_fn, prepareDocumentForImport_fn, prepareDocumentForExport_fn, endCollaboration_fn, _FieldAnnotationView_instances, createAnnotation_fn, _AutoPageNumberNodeView_instances, renderDom_fn, scheduleUpdateNodeStyle_fn;
26992
+ var _Attribute_static, getGlobalAttributes_fn, getNodeAndMarksAttributes_fn, _Schema_static, createNodesSchema_fn, createMarksSchema_fn, _events, _ExtensionService_instances, setupExtensions_fn, attachEditorEvents_fn, _commandService, _css, _Editor_instances, initContainerElement_fn, init_fn, initRichText_fn, onFocus_fn, checkHeadless_fn, insertNewFileData_fn, registerPluginByNameIfNotExists_fn, createExtensionService_fn, createCommandService_fn, createConverter_fn, initMedia_fn, initFonts_fn, createSchema_fn, generatePmData_fn, createDocFromHTML_fn, createView_fn, onCollaborationReady_fn, initComments_fn, dispatchTransaction_fn, handleNodeSelection_fn, prepareDocumentForImport_fn, prepareDocumentForExport_fn, endCollaboration_fn, _FieldAnnotationView_instances, createAnnotation_fn, _AutoPageNumberNodeView_instances, renderDom_fn, scheduleUpdateNodeStyle_fn;
26416
26993
  function getMarksFromSelection(state2) {
26417
26994
  const { from: from2, to, empty: empty2 } = state2.selection;
26418
26995
  const marks = [];
@@ -27601,164 +28178,6 @@ createMarksSchema_fn = function(markExtensions, attributes, editor) {
27601
28178
  };
27602
28179
  __privateAdd$1(_Schema, _Schema_static);
27603
28180
  let Schema2 = _Schema;
27604
- function chainableEditorState(transaction, state2) {
27605
- let { selection, doc: doc2, storedMarks } = transaction;
27606
- return {
27607
- ...state2,
27608
- apply: state2.apply.bind(state2),
27609
- applyTransaction: state2.applyTransaction.bind(state2),
27610
- plugins: state2.plugins,
27611
- schema: state2.schema,
27612
- reconfigure: state2.reconfigure.bind(state2),
27613
- toJSON: state2.toJSON.bind(state2),
27614
- get storedMarks() {
27615
- return storedMarks;
27616
- },
27617
- get selection() {
27618
- return selection;
27619
- },
27620
- get doc() {
27621
- return doc2;
27622
- },
27623
- get tr() {
27624
- selection = transaction.selection;
27625
- doc2 = transaction.doc;
27626
- storedMarks = transaction.storedMarks;
27627
- return transaction;
27628
- }
27629
- };
27630
- }
27631
- class CommandService {
27632
- constructor(props) {
27633
- __publicField$1(this, "editor");
27634
- __publicField$1(this, "rawCommands");
27635
- this.editor = props.editor;
27636
- this.rawCommands = this.editor.extensionService.commands;
27637
- }
27638
- /**
27639
- * Static method for creating a service.
27640
- * @param args Arguments for the constructor.
27641
- */
27642
- static create(...args) {
27643
- return new CommandService(...args);
27644
- }
27645
- /**
27646
- * Get editor state.
27647
- */
27648
- get state() {
27649
- return this.editor.state;
27650
- }
27651
- /**
27652
- * Get all commands with wrapped command method.
27653
- */
27654
- get commands() {
27655
- const { editor, state: state2 } = this;
27656
- const { view } = editor;
27657
- const { tr } = state2;
27658
- const props = this.createProps(tr);
27659
- const entries = Object.entries(this.rawCommands).map(([name, command2]) => {
27660
- const method = (...args) => {
27661
- const fn2 = command2(...args)(props);
27662
- if (!tr.getMeta("preventDispatch")) {
27663
- view.dispatch(tr);
27664
- }
27665
- return fn2;
27666
- };
27667
- return [name, method];
27668
- });
27669
- return Object.fromEntries(entries);
27670
- }
27671
- /**
27672
- * Create a chain of commands to call multiple commands at once.
27673
- */
27674
- get chain() {
27675
- return () => this.createChain();
27676
- }
27677
- /**
27678
- * Check if a command or a chain of commands can be executed. Without executing it.
27679
- */
27680
- get can() {
27681
- return () => this.createCan();
27682
- }
27683
- /**
27684
- * Creates a chain of commands.
27685
- * @param startTr Start transaction.
27686
- * @param shouldDispatch Should dispatch or not.
27687
- */
27688
- createChain(startTr, shouldDispatch = true) {
27689
- const { editor, state: state2, rawCommands } = this;
27690
- const { view } = editor;
27691
- const callbacks2 = [];
27692
- const hasStartTr = !!startTr;
27693
- const tr = startTr || state2.tr;
27694
- const run2 = () => {
27695
- if (!hasStartTr && shouldDispatch && !tr.getMeta("preventDispatch")) {
27696
- view.dispatch(tr);
27697
- }
27698
- return callbacks2.every((cb) => cb === true);
27699
- };
27700
- const entries = Object.entries(rawCommands).map(([name, command2]) => {
27701
- const chainedCommand = (...args) => {
27702
- const props = this.createProps(tr, shouldDispatch);
27703
- const callback = command2(...args)(props);
27704
- callbacks2.push(callback);
27705
- return chain;
27706
- };
27707
- return [name, chainedCommand];
27708
- });
27709
- const chain = {
27710
- ...Object.fromEntries(entries),
27711
- run: run2
27712
- };
27713
- return chain;
27714
- }
27715
- /**
27716
- * Creates a can check for commands.
27717
- * @param startTr Start transaction.
27718
- */
27719
- createCan(startTr) {
27720
- const { rawCommands, state: state2 } = this;
27721
- const dispatch = false;
27722
- const tr = startTr || state2.tr;
27723
- const props = this.createProps(tr, dispatch);
27724
- const commands2 = Object.fromEntries(
27725
- Object.entries(rawCommands).map(([name, command2]) => {
27726
- return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
27727
- })
27728
- );
27729
- return {
27730
- ...commands2,
27731
- chain: () => this.createChain(tr, dispatch)
27732
- };
27733
- }
27734
- /**
27735
- * Creates default props for the command method.
27736
- * @param {*} tr Transaction.
27737
- * @param {*} shouldDispatch Check if should dispatch.
27738
- * @returns Object with props.
27739
- */
27740
- createProps(tr, shouldDispatch = true) {
27741
- const { editor, state: state2, rawCommands } = this;
27742
- const { view } = editor;
27743
- const props = {
27744
- tr,
27745
- editor,
27746
- view,
27747
- state: chainableEditorState(tr, state2),
27748
- dispatch: shouldDispatch ? () => void 0 : void 0,
27749
- chain: () => this.createChain(tr, shouldDispatch),
27750
- can: () => this.createCan(tr),
27751
- get commands() {
27752
- return Object.fromEntries(
27753
- Object.entries(rawCommands).map(([name, command2]) => {
27754
- return [name, (...args) => command2(...args)(props)];
27755
- })
27756
- );
27757
- }
27758
- };
27759
- return props;
27760
- }
27761
- }
27762
28181
  const first = (commands2) => (props) => {
27763
28182
  const items = typeof commands2 === "function" ? commands2(props) : commands2;
27764
28183
  for (let i = 0; i < items.length; i += 1) {
@@ -28120,7 +28539,7 @@ function deleteBarrier(state2, $cut, dispatch, dir) {
28120
28539
  for (let i = conn.length - 1; i >= 0; i--)
28121
28540
  wrap2 = Fragment.from(conn[i].create(null, wrap2));
28122
28541
  wrap2 = Fragment.from(before.copy(wrap2));
28123
- let tr = state2.tr.step(new ReplaceAroundStep($cut.pos - 1, end2, $cut.pos, end2, new Slice(wrap2, 1, 0), conn.length, true));
28542
+ let tr = state2.tr.step(new ReplaceAroundStep$1($cut.pos - 1, end2, $cut.pos, end2, new Slice(wrap2, 1, 0), conn.length, true));
28124
28543
  let $joinAt = tr.doc.resolve(end2 + 2 * conn.length);
28125
28544
  if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr.doc, $joinAt.pos))
28126
28545
  tr.join($joinAt.pos);
@@ -28151,7 +28570,7 @@ function deleteBarrier(state2, $cut, dispatch, dir) {
28151
28570
  let end2 = Fragment.empty;
28152
28571
  for (let i = wrap2.length - 1; i >= 0; i--)
28153
28572
  end2 = Fragment.from(wrap2[i].copy(end2));
28154
- let tr = state2.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end2, wrap2.length, 0), 0, true));
28573
+ let tr = state2.tr.step(new ReplaceAroundStep$1($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end2, wrap2.length, 0), 0, true));
28155
28574
  dispatch(tr.scrollIntoView());
28156
28575
  }
28157
28576
  return true;
@@ -28724,7 +29143,7 @@ function selectionToInsertionEnd(tr, startLen, bias) {
28724
29143
  return;
28725
29144
  }
28726
29145
  const step = tr.steps[last];
28727
- if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
29146
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep$1)) {
28728
29147
  return;
28729
29148
  }
28730
29149
  const map22 = tr.mapping.maps[last];
@@ -28870,7 +29289,7 @@ function doWrapInList(tr, range2, wrappers, joinBefore, listType) {
28870
29289
  let content = Fragment.empty;
28871
29290
  for (let i = wrappers.length - 1; i >= 0; i--)
28872
29291
  content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
28873
- tr.step(new ReplaceAroundStep(range2.start - (joinBefore ? 2 : 0), range2.end, range2.start, range2.end, new Slice(content, 0, 0), wrappers.length, true));
29292
+ tr.step(new ReplaceAroundStep$1(range2.start - (joinBefore ? 2 : 0), range2.end, range2.start, range2.end, new Slice(content, 0, 0), wrappers.length, true));
28874
29293
  let found2 = 0;
28875
29294
  for (let i = 0; i < wrappers.length; i++)
28876
29295
  if (wrappers[i].type == listType)
@@ -28903,7 +29322,7 @@ function liftListItem$1(itemType) {
28903
29322
  function liftToOuterList(state2, dispatch, itemType, range2) {
28904
29323
  let tr = state2.tr, end2 = range2.end, endOfList = range2.$to.end(range2.depth);
28905
29324
  if (end2 < endOfList) {
28906
- tr.step(new ReplaceAroundStep(end2 - 1, endOfList, end2, endOfList, new Slice(Fragment.from(itemType.create(null, range2.parent.copy())), 1, 0), 1, true));
29325
+ tr.step(new ReplaceAroundStep$1(end2 - 1, endOfList, end2, endOfList, new Slice(Fragment.from(itemType.create(null, range2.parent.copy())), 1, 0), 1, true));
28907
29326
  range2 = new NodeRange(tr.doc.resolve(range2.$from.pos), tr.doc.resolve(endOfList), range2.depth);
28908
29327
  }
28909
29328
  const target = liftTarget(range2);
@@ -28930,7 +29349,7 @@ function liftOutOfList(state2, dispatch, range2) {
28930
29349
  if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))
28931
29350
  return false;
28932
29351
  let start2 = $start.pos, end2 = start2 + item.nodeSize;
28933
- tr.step(new ReplaceAroundStep(start2 - (atStart ? 1 : 0), end2 + (atEnd ? 1 : 0), start2 + 1, end2 - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
29352
+ tr.step(new ReplaceAroundStep$1(start2 - (atStart ? 1 : 0), end2 + (atEnd ? 1 : 0), start2 + 1, end2 - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
28934
29353
  dispatch(tr.scrollIntoView());
28935
29354
  return true;
28936
29355
  }
@@ -28951,7 +29370,7 @@ function sinkListItem$1(itemType) {
28951
29370
  let inner = Fragment.from(nestedBefore ? itemType.create() : null);
28952
29371
  let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
28953
29372
  let before = range2.start, after = range2.end;
28954
- dispatch(state2.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
29373
+ dispatch(state2.tr.step(new ReplaceAroundStep$1(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
28955
29374
  }
28956
29375
  return true;
28957
29376
  };
@@ -36544,7 +36963,8 @@ const restoreRelativeSelection = (tr, relSel, binding) => {
36544
36963
  binding.mapping
36545
36964
  );
36546
36965
  if (anchor !== null && head !== null) {
36547
- tr.setSelection(TextSelection.between(tr.doc.resolve(anchor), tr.doc.resolve(head)));
36966
+ const sel = TextSelection.between(tr.doc.resolve(anchor), tr.doc.resolve(head));
36967
+ tr.setSelection(sel);
36548
36968
  }
36549
36969
  }
36550
36970
  }
@@ -37325,7 +37745,7 @@ const setMeta = (view, key, value) => {
37325
37745
  };
37326
37746
  const absolutePositionToRelativePosition = (pos, type2, mapping) => {
37327
37747
  if (pos === 0) {
37328
- return Y__namespace.createRelativePositionFromTypeIndex(type2, 0, -1);
37748
+ return Y__namespace.createRelativePositionFromTypeIndex(type2, 0, type2.length === 0 ? -1 : 0);
37329
37749
  }
37330
37750
  let n = type2._first === null ? null : (
37331
37751
  /** @type {Y.ContentType} */
@@ -37334,7 +37754,7 @@ const absolutePositionToRelativePosition = (pos, type2, mapping) => {
37334
37754
  while (n !== null && type2 !== n) {
37335
37755
  if (n instanceof Y__namespace.XmlText) {
37336
37756
  if (n._length >= pos) {
37337
- return Y__namespace.createRelativePositionFromTypeIndex(n, pos, -1);
37757
+ return Y__namespace.createRelativePositionFromTypeIndex(n, pos, type2.length === 0 ? -1 : 0);
37338
37758
  } else {
37339
37759
  pos -= n._length;
37340
37760
  }
@@ -37398,7 +37818,7 @@ const absolutePositionToRelativePosition = (pos, type2, mapping) => {
37398
37818
  return createRelativePosition(n._item.parent, n._item);
37399
37819
  }
37400
37820
  }
37401
- return Y__namespace.createRelativePositionFromTypeIndex(type2, type2._length, -1);
37821
+ return Y__namespace.createRelativePositionFromTypeIndex(type2, type2._length, type2.length === 0 ? -1 : 0);
37402
37822
  };
37403
37823
  const createRelativePosition = (type2, item) => {
37404
37824
  let typeid = null;
@@ -37710,693 +38130,290 @@ const yUndoPlugin = ({ protectedNodes = defaultProtectedNodes, trackedOrigins =
37710
38130
  } else {
37711
38131
  if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) {
37712
38132
  return Object.assign({}, val, {
37713
- hasUndoOps: undoManager2.undoStack.length > 0,
37714
- hasRedoOps: undoManager2.redoStack.length > 0
37715
- });
37716
- } else {
37717
- return val;
37718
- }
37719
- }
37720
- }
37721
- },
37722
- view: (view) => {
37723
- const ystate = ySyncPluginKey.getState(view.state);
37724
- const undoManager2 = yUndoPluginKey.getState(view.state).undoManager;
37725
- undoManager2.on("stack-item-added", ({ stackItem }) => {
37726
- const binding = ystate.binding;
37727
- if (binding) {
37728
- stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel);
37729
- }
37730
- });
37731
- undoManager2.on("stack-item-popped", ({ stackItem }) => {
37732
- const binding = ystate.binding;
37733
- if (binding) {
37734
- binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection;
37735
- }
37736
- });
37737
- return {
37738
- destroy: () => {
37739
- undoManager2.destroy();
37740
- }
37741
- };
37742
- }
37743
- });
37744
- let EventEmitter$1 = class EventEmitter {
37745
- constructor() {
37746
- __privateAdd$1(this, _events, /* @__PURE__ */ new Map());
37747
- }
37748
- /**
37749
- * Subscribe to the event.
37750
- * @param {string} name Event name.
37751
- * @param {(...args: any[]) => void} fn Callback.
37752
- * @returns {void}
37753
- */
37754
- on(name, fn2) {
37755
- const callbacks2 = __privateGet$1(this, _events).get(name);
37756
- if (callbacks2) callbacks2.push(fn2);
37757
- else __privateGet$1(this, _events).set(name, [fn2]);
37758
- }
37759
- /**
37760
- * Emit event.
37761
- * @param {string} name Event name.
37762
- * @param {...any} args – Arguments to pass to each listener.
37763
- * @returns {void}
37764
- */
37765
- emit(name, ...args) {
37766
- const callbacks2 = __privateGet$1(this, _events).get(name);
37767
- if (!callbacks2) return;
37768
- for (const fn2 of callbacks2) {
37769
- fn2.apply(this, args);
37770
- }
37771
- }
37772
- /**
37773
- * Remove a specific callback from event
37774
- * or all event subscriptions.
37775
- * @param {string} name Event name.
37776
- * @param {(...args: any[]) => void} fn Callback.
37777
- * @returns {void}
37778
- */
37779
- off(name, fn2) {
37780
- const callbacks2 = __privateGet$1(this, _events).get(name);
37781
- if (!callbacks2) return;
37782
- if (fn2) {
37783
- __privateGet$1(this, _events).set(
37784
- name,
37785
- callbacks2.filter((cb) => cb !== fn2)
37786
- );
37787
- } else {
37788
- __privateGet$1(this, _events).delete(name);
37789
- }
37790
- }
37791
- /**
37792
- * Subscribe to an event that will be called only once.
37793
- * @param {string} name Event name.
37794
- * @param {(...args: any[]) => void} fn Callback.
37795
- * @returns {void}
37796
- */
37797
- once(name, fn2) {
37798
- const wrapper = (...args) => {
37799
- this.off(name, wrapper);
37800
- fn2.apply(this, args);
37801
- };
37802
- this.on(name, wrapper);
37803
- }
37804
- /**
37805
- * Remove all registered events and subscriptions.
37806
- */
37807
- removeAllListeners() {
37808
- __privateSet(this, _events, /* @__PURE__ */ new Map());
37809
- }
37810
- };
37811
- _events = /* @__PURE__ */ new WeakMap();
37812
- var base$1 = {
37813
- 8: "Backspace",
37814
- 9: "Tab",
37815
- 10: "Enter",
37816
- 12: "NumLock",
37817
- 13: "Enter",
37818
- 16: "Shift",
37819
- 17: "Control",
37820
- 18: "Alt",
37821
- 20: "CapsLock",
37822
- 27: "Escape",
37823
- 32: " ",
37824
- 33: "PageUp",
37825
- 34: "PageDown",
37826
- 35: "End",
37827
- 36: "Home",
37828
- 37: "ArrowLeft",
37829
- 38: "ArrowUp",
37830
- 39: "ArrowRight",
37831
- 40: "ArrowDown",
37832
- 44: "PrintScreen",
37833
- 45: "Insert",
37834
- 46: "Delete",
37835
- 59: ";",
37836
- 61: "=",
37837
- 91: "Meta",
37838
- 92: "Meta",
37839
- 106: "*",
37840
- 107: "+",
37841
- 108: ",",
37842
- 109: "-",
37843
- 110: ".",
37844
- 111: "/",
37845
- 144: "NumLock",
37846
- 145: "ScrollLock",
37847
- 160: "Shift",
37848
- 161: "Shift",
37849
- 162: "Control",
37850
- 163: "Control",
37851
- 164: "Alt",
37852
- 165: "Alt",
37853
- 173: "-",
37854
- 186: ";",
37855
- 187: "=",
37856
- 188: ",",
37857
- 189: "-",
37858
- 190: ".",
37859
- 191: "/",
37860
- 192: "`",
37861
- 219: "[",
37862
- 220: "\\",
37863
- 221: "]",
37864
- 222: "'"
37865
- };
37866
- var shift = {
37867
- 48: ")",
37868
- 49: "!",
37869
- 50: "@",
37870
- 51: "#",
37871
- 52: "$",
37872
- 53: "%",
37873
- 54: "^",
37874
- 55: "&",
37875
- 56: "*",
37876
- 57: "(",
37877
- 59: ":",
37878
- 61: "+",
37879
- 173: "_",
37880
- 186: ":",
37881
- 187: "+",
37882
- 188: "<",
37883
- 189: "_",
37884
- 190: ">",
37885
- 191: "?",
37886
- 192: "~",
37887
- 219: "{",
37888
- 220: "|",
37889
- 221: "}",
37890
- 222: '"'
37891
- };
37892
- var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
37893
- var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
37894
- for (var i = 0; i < 10; i++) base$1[48 + i] = base$1[96 + i] = String(i);
37895
- for (var i = 1; i <= 24; i++) base$1[i + 111] = "F" + i;
37896
- for (var i = 65; i <= 90; i++) {
37897
- base$1[i] = String.fromCharCode(i + 32);
37898
- shift[i] = String.fromCharCode(i);
37899
- }
37900
- for (var code in base$1) if (!shift.hasOwnProperty(code)) shift[code] = base$1[code];
37901
- function keyName(event) {
37902
- var ignoreKey = mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
37903
- var name = !ignoreKey && event.key || (event.shiftKey ? shift : base$1)[event.keyCode] || event.key || "Unidentified";
37904
- if (name == "Esc") name = "Escape";
37905
- if (name == "Del") name = "Delete";
37906
- if (name == "Left") name = "ArrowLeft";
37907
- if (name == "Up") name = "ArrowUp";
37908
- if (name == "Right") name = "ArrowRight";
37909
- if (name == "Down") name = "ArrowDown";
37910
- return name;
37911
- }
37912
- const mac = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
37913
- const windows = typeof navigator != "undefined" && /Win/.test(navigator.platform);
37914
- function normalizeKeyName(name) {
37915
- let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];
37916
- if (result == "Space")
37917
- result = " ";
37918
- let alt, ctrl, shift2, meta;
37919
- for (let i = 0; i < parts.length - 1; i++) {
37920
- let mod = parts[i];
37921
- if (/^(cmd|meta|m)$/i.test(mod))
37922
- meta = true;
37923
- else if (/^a(lt)?$/i.test(mod))
37924
- alt = true;
37925
- else if (/^(c|ctrl|control)$/i.test(mod))
37926
- ctrl = true;
37927
- else if (/^s(hift)?$/i.test(mod))
37928
- shift2 = true;
37929
- else if (/^mod$/i.test(mod)) {
37930
- if (mac)
37931
- meta = true;
37932
- else
37933
- ctrl = true;
37934
- } else
37935
- throw new Error("Unrecognized modifier name: " + mod);
37936
- }
37937
- if (alt)
37938
- result = "Alt-" + result;
37939
- if (ctrl)
37940
- result = "Ctrl-" + result;
37941
- if (meta)
37942
- result = "Meta-" + result;
37943
- if (shift2)
37944
- result = "Shift-" + result;
37945
- return result;
37946
- }
37947
- function normalize(map22) {
37948
- let copy2 = /* @__PURE__ */ Object.create(null);
37949
- for (let prop in map22)
37950
- copy2[normalizeKeyName(prop)] = map22[prop];
37951
- return copy2;
37952
- }
37953
- function modifiers(name, event, shift2 = true) {
37954
- if (event.altKey)
37955
- name = "Alt-" + name;
37956
- if (event.ctrlKey)
37957
- name = "Ctrl-" + name;
37958
- if (event.metaKey)
37959
- name = "Meta-" + name;
37960
- if (shift2 && event.shiftKey)
37961
- name = "Shift-" + name;
37962
- return name;
37963
- }
37964
- function keymap(bindings) {
37965
- return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
37966
- }
37967
- function keydownHandler(bindings) {
37968
- let map22 = normalize(bindings);
37969
- return function(view, event) {
37970
- let name = keyName(event), baseName, direct = map22[modifiers(name, event)];
37971
- if (direct && direct(view.state, view.dispatch, view))
37972
- return true;
37973
- if (name.length == 1 && name != " ") {
37974
- if (event.shiftKey) {
37975
- let noShift = map22[modifiers(name, event, false)];
37976
- if (noShift && noShift(view.state, view.dispatch, view))
37977
- return true;
37978
- }
37979
- if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
37980
- !(windows && event.ctrlKey && event.altKey) && (baseName = base$1[event.keyCode]) && baseName != name) {
37981
- let fromCode = map22[modifiers(baseName, event)];
37982
- if (fromCode && fromCode(view.state, view.dispatch, view))
37983
- return true;
37984
- }
37985
- }
37986
- return false;
37987
- };
37988
- }
37989
- function isExtensionRulesEnabled(extension, enabled) {
37990
- if (Array.isArray(enabled)) {
37991
- return enabled.some((enabledExtension) => {
37992
- const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name;
37993
- return name === extension.name;
37994
- });
37995
- }
37996
- return enabled;
37997
- }
37998
- function getHTMLFromFragment(fragment, schema) {
37999
- const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment);
38000
- const temporaryDocument = document.implementation.createHTMLDocument();
38001
- const container = temporaryDocument.createElement("div");
38002
- container.appendChild(documentFragment);
38003
- return container.innerHTML;
38004
- }
38005
- const getTextContentFromNodes = ($from, maxMatch = 500) => {
38006
- let textBefore = "";
38007
- const sliceEndPos = $from.parentOffset;
38008
- $from.parent.nodesBetween(
38009
- Math.max(0, sliceEndPos - maxMatch),
38010
- sliceEndPos,
38011
- (node2, pos, parent, index2) => {
38012
- const chunk = node2.type.spec.toText?.({
38013
- node: node2,
38014
- pos,
38015
- parent,
38016
- index: index2
38017
- }) || node2.textContent || "%leaf%";
38018
- textBefore += node2.isAtom && !node2.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));
38019
- }
38020
- );
38021
- return textBefore;
38022
- };
38023
- const handleDocxPaste = (html, editor, view, plugin2) => {
38024
- const { converter } = editor;
38025
- if (!converter || !converter.convertedXml) return handleHtmlPaste(html, editor, view, plugin2);
38026
- let cleanedHtml = convertEmToPt(html);
38027
- cleanedHtml = cleanHtmlUnnecessaryTags(cleanedHtml);
38028
- const tempDiv = document.createElement("div");
38029
- tempDiv.innerHTML = cleanedHtml;
38030
- const paragraphs = tempDiv.querySelectorAll("p");
38031
- paragraphs.forEach((p) => {
38032
- const innerHTML3 = p.innerHTML;
38033
- if (!innerHTML3.includes("<!--[if !supportLists]")) return;
38034
- const styleAttr = p.getAttribute("style") || "";
38035
- const msoListMatch = styleAttr.match(/mso-list:\s*l(\d+)\s+level(\d+)/);
38036
- if (msoListMatch) {
38037
- const [, abstractId, level] = msoListMatch;
38038
- const listNumId = getListNumIdFromAbstract(abstractId, editor);
38039
- if (!listNumId) return;
38040
- const abstractDefinition = getListAbstractDefinition(abstractId, editor);
38041
- const { lvlText, start: start2, numFmt } = getLevelDefinition(abstractDefinition, level - 1);
38042
- p.setAttribute("data-num-id", listNumId);
38043
- p.setAttribute("data-list-level", level - 1);
38044
- p.setAttribute("data-start", start2);
38045
- p.setAttribute("data-lvl-text", lvlText);
38046
- p.setAttribute("data-num-fmt", numFmt);
38047
- }
38048
- extractAndRemoveConditionalPrefix(p);
38049
- });
38050
- transformWordLists(tempDiv);
38051
- const doc2 = DOMParser$1.fromSchema(editor.schema).parse(tempDiv);
38052
- tempDiv.remove();
38053
- const { dispatch } = editor.view;
38054
- if (!dispatch) return false;
38055
- dispatch(view.state.tr.replaceSelectionWith(doc2, true));
38056
- return true;
38057
- };
38058
- const getLevelDefinition = (abstractDefinition, level) => {
38059
- if (!abstractDefinition || !abstractDefinition.elements) return null;
38060
- const levelElement = abstractDefinition.elements.find((el) => {
38061
- return el.name === "w:lvl" && el.attributes?.["w:ilvl"] == level;
38062
- });
38063
- if (!levelElement) return null;
38064
- const { elements } = levelElement;
38065
- const lvlText = elements.find((el) => el.name === "w:lvlText")?.attributes?.["w:val"];
38066
- const start2 = elements.find((el) => el.name === "w:start")?.attributes?.["w:val"];
38067
- const numFmt = elements.find((el) => el.name === "w:numFmt")?.attributes?.["w:val"];
38068
- return { lvlText, start: start2, numFmt, elements };
38069
- };
38070
- const getListNumIdFromAbstract = (abstractId, editor) => {
38071
- const { definitions } = editor?.converter?.numbering;
38072
- if (!definitions) return null;
38073
- const matchedDefinition = Object.values(definitions).find((def) => {
38074
- return def.elements.some((el) => el.name === "w:abstractNumId" && el.attributes?.["w:val"] == abstractId);
38075
- });
38076
- return matchedDefinition?.attributes?.["w:numId"];
38077
- };
38078
- const getListAbstractDefinition = (abstractId, editor) => {
38079
- const { abstracts = {} } = editor?.converter?.numbering;
38080
- return abstracts[abstractId] || null;
38081
- };
38082
- const transformWordLists = (container) => {
38083
- const paragraphs = Array.from(container.querySelectorAll("p[data-num-id]"));
38084
- const listMap = /* @__PURE__ */ new Map();
38085
- const listLevels = {};
38086
- for (const p of paragraphs) {
38087
- const listId = p.getAttribute("data-num-id");
38088
- const level = parseInt(p.getAttribute("data-list-level"));
38089
- const numFmt = p.getAttribute("data-num-fmt");
38090
- const start2 = p.getAttribute("data-start");
38091
- const lvlText = p.getAttribute("data-lvl-text");
38092
- if (!listMap.has(listId)) listMap.set(listId, []);
38093
- listMap.get(listId).push({ p, level, numFmt, start: start2, lvlText });
38094
- }
38095
- for (const [id, items] of listMap.entries()) {
38096
- if (!listLevels[id]) {
38097
- listLevels[id] = {
38098
- stack: [],
38099
- counts: {},
38100
- prevLevel: null
38101
- };
38102
- }
38103
- const parentStack = [];
38104
- items.forEach(({ p, level, numFmt, start: start2, lvlText }, index2) => {
38105
- const listLevel = generateListNestingPath(listLevels, id, level);
38106
- const li = document.createElement("li");
38107
- li.innerHTML = p.innerHTML;
38108
- li.setAttribute("data-list-level", JSON.stringify(listLevel));
38109
- li.setAttribute("data-num-id", id);
38110
- li.setAttribute("data-lvl-text", lvlText);
38111
- li.setAttribute("data-num-fmt", numFmt);
38112
- if (p.hasAttribute("data-font-family")) {
38113
- li.setAttribute("data-font-family", p.getAttribute("data-font-family"));
38114
- }
38115
- if (p.hasAttribute("data-font-size")) {
38116
- li.setAttribute("data-font-size", p.getAttribute("data-font-size"));
38117
- }
38118
- const parentNode2 = p.parentNode;
38119
- let listForLevel = parentStack[level];
38120
- if (!listForLevel) {
38121
- const newList = document.createElement("ol");
38122
- newList.setAttribute("data-list-id", id);
38123
- newList.level = level;
38124
- if (level > 0) {
38125
- const parentLi = parentStack[level - 1]?.querySelector("li:last-child");
38126
- if (parentLi) parentLi.appendChild(newList);
38127
- } else {
38128
- parentNode2.insertBefore(newList, p);
38129
- }
38130
- parentStack[level] = newList;
38131
- parentStack.length = level + 1;
38132
- listForLevel = newList;
38133
- }
38134
- listForLevel.appendChild(li);
38135
- p.remove();
38136
- });
38137
- }
38138
- };
38139
- function generateListNestingPath(listLevels, listId, currentLevel) {
38140
- const levelState = listLevels[listId];
38141
- if (!levelState.stack) levelState.stack = [];
38142
- if (levelState.prevLevel === void 0) levelState.prevLevel = null;
38143
- if (levelState.prevLevel === null) {
38144
- levelState.stack = Array(currentLevel).fill(1).concat(1);
38145
- } else {
38146
- if (currentLevel > levelState.prevLevel) {
38147
- levelState.stack.push(1);
38148
- } else if (currentLevel === levelState.prevLevel) {
38149
- levelState.stack[levelState.stack.length - 1]++;
38150
- } else {
38151
- levelState.stack = levelState.stack.slice(0, currentLevel + 1);
38152
- levelState.stack[currentLevel] = (levelState.stack[currentLevel] || 1) + 1;
38153
- }
38154
- }
38155
- levelState.prevLevel = currentLevel;
38156
- return [...levelState.stack];
38157
- }
38158
- function extractAndRemoveConditionalPrefix(p) {
38159
- const nodes = Array.from(p.childNodes);
38160
- let fontFamily2 = null;
38161
- let fontSize2 = null;
38162
- let start2 = -1, end2 = -1;
38163
- nodes.forEach((node2, index2) => {
38164
- if (node2.nodeType === Node.COMMENT_NODE && node2.nodeValue.includes("[if !supportLists]")) {
38165
- start2 = index2;
38166
- }
38167
- if (start2 !== -1 && node2.nodeType === Node.COMMENT_NODE && node2.nodeValue.includes("[endif]")) {
38168
- end2 = index2;
38169
- }
38170
- });
38171
- if (start2 !== -1 && end2 !== -1) {
38172
- for (let i = start2 + 1; i < end2; i++) {
38173
- const node2 = nodes[i];
38174
- if (node2.nodeType === Node.ELEMENT_NODE && node2.style) {
38175
- fontFamily2 = fontFamily2 || node2.style.fontFamily;
38176
- fontSize2 = fontSize2 || node2.style.fontSize;
38177
- }
38178
- }
38179
- for (let i = end2; i >= start2; i--) {
38180
- p.removeChild(p.childNodes[i]);
38181
- }
38182
- if (fontFamily2) p.setAttribute("data-font-family", fontFamily2);
38183
- if (fontSize2) p.setAttribute("data-font-size", fontSize2);
38184
- }
38185
- }
38186
- class InputRule {
38187
- constructor(config) {
38188
- __publicField$1(this, "match");
38189
- __publicField$1(this, "handler");
38190
- this.match = config.match;
38191
- this.handler = config.handler;
38192
- }
38193
- }
38194
- const inputRuleMatcherHandler = (text, match) => {
38195
- if (isRegExp(match)) {
38196
- return match.exec(text);
38197
- }
38198
- const inputRuleMatch = match(text);
38199
- if (!inputRuleMatch) {
38200
- return null;
38201
- }
38202
- const result = [inputRuleMatch.text];
38203
- result.index = inputRuleMatch.index;
38204
- result.input = text;
38205
- result.data = inputRuleMatch.data;
38206
- if (inputRuleMatch.replaceWith) {
38207
- if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
38208
- console.warn(
38209
- '[super-editor warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'
38210
- );
38211
- }
38212
- result.push(inputRuleMatch.replaceWith);
38213
- }
38214
- return result;
38215
- };
38216
- const run = (config) => {
38217
- const {
38218
- editor,
38219
- from: from2,
38220
- to,
38221
- text,
38222
- rules,
38223
- plugin: plugin2
38224
- } = config;
38225
- const { view } = editor;
38226
- if (view.composing) {
38227
- return false;
38228
- }
38229
- const $from = view.state.doc.resolve(from2);
38230
- if ($from.parent.type.spec.code || !!($from.nodeBefore || $from.nodeAfter)?.marks.find((mark) => mark.type.spec.code)) {
38231
- return false;
38232
- }
38233
- let matched = false;
38234
- const textBefore = getTextContentFromNodes($from) + text;
38235
- rules.forEach((rule) => {
38236
- if (matched) {
38237
- return;
38238
- }
38239
- const match = inputRuleMatcherHandler(textBefore, rule.match);
38240
- if (!match) {
38241
- return;
38242
- }
38243
- const tr = view.state.tr;
38244
- const state2 = chainableEditorState(tr, view.state);
38245
- const range2 = {
38246
- from: from2 - (match[0].length - text.length),
38247
- to
38248
- };
38249
- const { commands: commands2, chain, can } = new CommandService({
38250
- editor,
38251
- state: state2
38252
- });
38253
- const handler = rule.handler({
38254
- state: state2,
38255
- range: range2,
38256
- match,
38257
- commands: commands2,
38258
- chain,
38259
- can
38260
- });
38261
- if (handler === null || !tr.steps.length) {
38262
- return;
38263
- }
38264
- tr.setMeta(plugin2, {
38265
- transform: tr,
38266
- from: from2,
38267
- to,
38268
- text
38269
- });
38270
- view.dispatch(tr);
38271
- matched = true;
38272
- });
38273
- return matched;
38274
- };
38275
- const inputRulesPlugin = ({ editor, rules }) => {
38276
- const plugin2 = new Plugin({
38277
- key: new PluginKey("inputRulesPlugin"),
38278
- state: {
38279
- init() {
38280
- return null;
38281
- },
38282
- apply(tr, prev, state2) {
38283
- const stored = tr.getMeta(plugin2);
38284
- if (stored) {
38285
- return stored;
38286
- }
38287
- const simulatedInputMeta = tr.getMeta("applyInputRules");
38288
- const isSimulatedInput = !!simulatedInputMeta;
38289
- if (isSimulatedInput) {
38290
- setTimeout(() => {
38291
- let { text } = simulatedInputMeta;
38292
- if (typeof text !== "string") {
38293
- text = getHTMLFromFragment(Fragment.from(text), state2.schema);
38294
- }
38295
- const { from: from2 } = simulatedInputMeta;
38296
- const to = from2 + text.length;
38297
- run({
38298
- editor,
38299
- from: from2,
38300
- to,
38301
- text,
38302
- rules,
38303
- plugin: plugin2
38304
- });
38305
- });
38306
- }
38307
- return tr.selectionSet || tr.docChanged ? null : prev;
38308
- }
38309
- },
38310
- props: {
38311
- handleTextInput(view, from2, to, text) {
38312
- return run({
38313
- editor,
38314
- from: from2,
38315
- to,
38316
- text,
38317
- rules,
38318
- plugin: plugin2
38319
- });
38320
- },
38321
- // add support for input rules to trigger on enter
38322
- // this is useful for example for code blocks
38323
- handleKeyDown(view, event) {
38324
- if (event.key !== "Enter") {
38325
- return false;
38326
- }
38327
- const { $cursor } = view.state.selection;
38328
- if ($cursor) {
38329
- return run({
38330
- editor,
38331
- from: $cursor.pos,
38332
- to: $cursor.pos,
38333
- text: "\n",
38334
- rules,
38335
- plugin: plugin2
38133
+ hasUndoOps: undoManager2.undoStack.length > 0,
38134
+ hasRedoOps: undoManager2.redoStack.length > 0
38336
38135
  });
38337
- }
38338
- return false;
38339
- },
38340
- // Paste handler
38341
- handlePaste(view, event, slice2) {
38342
- const clipboard = event.clipboardData;
38343
- const html = clipboard.getData("text/html");
38344
- clipboard.getData("text/plain");
38345
- const fieldAnnotationContent = slice2.content.content.filter((item) => item.type.name === "fieldAnnotation");
38346
- if (fieldAnnotationContent.length) {
38347
- return false;
38348
- }
38349
- let source;
38350
- if (!html) {
38351
- source = "plain-text";
38352
- } else if (isWordHtml(html)) {
38353
- source = "word-html";
38354
38136
  } else {
38355
- source = "browser-html";
38356
- }
38357
- switch (source) {
38358
- case "plain-text":
38359
- break;
38360
- case "word-html":
38361
- if (editor.options.mode === "docx") {
38362
- return handleDocxPaste(html, editor, view, plugin2);
38363
- }
38364
- case "browser-html":
38365
- return handleHtmlPaste$1(html, editor);
38137
+ return val;
38366
38138
  }
38367
- return false;
38368
38139
  }
38369
- },
38370
- isInputRules: true
38371
- });
38372
- return plugin2;
38140
+ }
38141
+ },
38142
+ view: (view) => {
38143
+ const ystate = ySyncPluginKey.getState(view.state);
38144
+ const undoManager2 = yUndoPluginKey.getState(view.state).undoManager;
38145
+ undoManager2.on("stack-item-added", ({ stackItem }) => {
38146
+ const binding = ystate.binding;
38147
+ if (binding) {
38148
+ stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel);
38149
+ }
38150
+ });
38151
+ undoManager2.on("stack-item-popped", ({ stackItem }) => {
38152
+ const binding = ystate.binding;
38153
+ if (binding) {
38154
+ binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection;
38155
+ }
38156
+ });
38157
+ return {
38158
+ destroy: () => {
38159
+ undoManager2.destroy();
38160
+ }
38161
+ };
38162
+ }
38163
+ });
38164
+ let EventEmitter$1 = class EventEmitter {
38165
+ constructor() {
38166
+ __privateAdd$1(this, _events, /* @__PURE__ */ new Map());
38167
+ }
38168
+ /**
38169
+ * Subscribe to the event.
38170
+ * @param {string} name Event name.
38171
+ * @param {(...args: any[]) => void} fn Callback.
38172
+ * @returns {void}
38173
+ */
38174
+ on(name, fn2) {
38175
+ const callbacks2 = __privateGet$1(this, _events).get(name);
38176
+ if (callbacks2) callbacks2.push(fn2);
38177
+ else __privateGet$1(this, _events).set(name, [fn2]);
38178
+ }
38179
+ /**
38180
+ * Emit event.
38181
+ * @param {string} name Event name.
38182
+ * @param {...any} args – Arguments to pass to each listener.
38183
+ * @returns {void}
38184
+ */
38185
+ emit(name, ...args) {
38186
+ const callbacks2 = __privateGet$1(this, _events).get(name);
38187
+ if (!callbacks2) return;
38188
+ for (const fn2 of callbacks2) {
38189
+ fn2.apply(this, args);
38190
+ }
38191
+ }
38192
+ /**
38193
+ * Remove a specific callback from event
38194
+ * or all event subscriptions.
38195
+ * @param {string} name Event name.
38196
+ * @param {(...args: any[]) => void} fn Callback.
38197
+ * @returns {void}
38198
+ */
38199
+ off(name, fn2) {
38200
+ const callbacks2 = __privateGet$1(this, _events).get(name);
38201
+ if (!callbacks2) return;
38202
+ if (fn2) {
38203
+ __privateGet$1(this, _events).set(
38204
+ name,
38205
+ callbacks2.filter((cb) => cb !== fn2)
38206
+ );
38207
+ } else {
38208
+ __privateGet$1(this, _events).delete(name);
38209
+ }
38210
+ }
38211
+ /**
38212
+ * Subscribe to an event that will be called only once.
38213
+ * @param {string} name Event name.
38214
+ * @param {(...args: any[]) => void} fn Callback.
38215
+ * @returns {void}
38216
+ */
38217
+ once(name, fn2) {
38218
+ const wrapper = (...args) => {
38219
+ this.off(name, wrapper);
38220
+ fn2.apply(this, args);
38221
+ };
38222
+ this.on(name, wrapper);
38223
+ }
38224
+ /**
38225
+ * Remove all registered events and subscriptions.
38226
+ */
38227
+ removeAllListeners() {
38228
+ __privateSet(this, _events, /* @__PURE__ */ new Map());
38229
+ }
38373
38230
  };
38374
- function isWordHtml(html) {
38375
- return /class=["']?Mso|xmlns:o=["']?urn:schemas-microsoft-com|<!--\[if gte mso|<meta[^>]+name=["']?Generator["']?[^>]+Word/i.test(html);
38376
- }
38377
- const handleHtmlPaste$1 = (html, editor, plugin2) => {
38378
- const cleanedHtml = convertEmToPt(html);
38379
- const tempDiv = document.createElement("div");
38380
- tempDiv.innerHTML = cleanedHtml;
38381
- const doc2 = DOMParser$1.fromSchema(editor.schema).parse(tempDiv);
38382
- tempDiv.remove();
38383
- const { dispatch } = editor.view;
38384
- if (!dispatch) return false;
38385
- dispatch(editor.view.state.tr.replaceSelectionWith(doc2, true));
38386
- return true;
38231
+ _events = /* @__PURE__ */ new WeakMap();
38232
+ var base$1 = {
38233
+ 8: "Backspace",
38234
+ 9: "Tab",
38235
+ 10: "Enter",
38236
+ 12: "NumLock",
38237
+ 13: "Enter",
38238
+ 16: "Shift",
38239
+ 17: "Control",
38240
+ 18: "Alt",
38241
+ 20: "CapsLock",
38242
+ 27: "Escape",
38243
+ 32: " ",
38244
+ 33: "PageUp",
38245
+ 34: "PageDown",
38246
+ 35: "End",
38247
+ 36: "Home",
38248
+ 37: "ArrowLeft",
38249
+ 38: "ArrowUp",
38250
+ 39: "ArrowRight",
38251
+ 40: "ArrowDown",
38252
+ 44: "PrintScreen",
38253
+ 45: "Insert",
38254
+ 46: "Delete",
38255
+ 59: ";",
38256
+ 61: "=",
38257
+ 91: "Meta",
38258
+ 92: "Meta",
38259
+ 106: "*",
38260
+ 107: "+",
38261
+ 108: ",",
38262
+ 109: "-",
38263
+ 110: ".",
38264
+ 111: "/",
38265
+ 144: "NumLock",
38266
+ 145: "ScrollLock",
38267
+ 160: "Shift",
38268
+ 161: "Shift",
38269
+ 162: "Control",
38270
+ 163: "Control",
38271
+ 164: "Alt",
38272
+ 165: "Alt",
38273
+ 173: "-",
38274
+ 186: ";",
38275
+ 187: "=",
38276
+ 188: ",",
38277
+ 189: "-",
38278
+ 190: ".",
38279
+ 191: "/",
38280
+ 192: "`",
38281
+ 219: "[",
38282
+ 220: "\\",
38283
+ 221: "]",
38284
+ 222: "'"
38387
38285
  };
38388
- const convertEmToPt = (html) => {
38389
- return html.replace(
38390
- /font-size\s*:\s*([\d.]+)em/gi,
38391
- (_, emValue) => {
38392
- const em = parseFloat(emValue);
38393
- const pt = Math.round(em * 12 * 100) / 100;
38394
- return `font-size: ${pt}pt`;
38395
- }
38396
- );
38286
+ var shift = {
38287
+ 48: ")",
38288
+ 49: "!",
38289
+ 50: "@",
38290
+ 51: "#",
38291
+ 52: "$",
38292
+ 53: "%",
38293
+ 54: "^",
38294
+ 55: "&",
38295
+ 56: "*",
38296
+ 57: "(",
38297
+ 59: ":",
38298
+ 61: "+",
38299
+ 173: "_",
38300
+ 186: ":",
38301
+ 187: "+",
38302
+ 188: "<",
38303
+ 189: "_",
38304
+ 190: ">",
38305
+ 191: "?",
38306
+ 192: "~",
38307
+ 219: "{",
38308
+ 220: "|",
38309
+ 221: "}",
38310
+ 222: '"'
38397
38311
  };
38398
- function cleanHtmlUnnecessaryTags(html) {
38399
- return html.replace(/<o:p>.*?<\/o:p>/gi, "").replace(/&nbsp;/gi, " ").replace(/<span[^>]*>\s*<\/span>/gi, "").replace(/<p[^>]*>\s*<\/p>/gi, "").trim();
38312
+ var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
38313
+ var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
38314
+ for (var i = 0; i < 10; i++) base$1[48 + i] = base$1[96 + i] = String(i);
38315
+ for (var i = 1; i <= 24; i++) base$1[i + 111] = "F" + i;
38316
+ for (var i = 65; i <= 90; i++) {
38317
+ base$1[i] = String.fromCharCode(i + 32);
38318
+ shift[i] = String.fromCharCode(i);
38319
+ }
38320
+ for (var code in base$1) if (!shift.hasOwnProperty(code)) shift[code] = base$1[code];
38321
+ function keyName(event) {
38322
+ var ignoreKey = mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
38323
+ var name = !ignoreKey && event.key || (event.shiftKey ? shift : base$1)[event.keyCode] || event.key || "Unidentified";
38324
+ if (name == "Esc") name = "Escape";
38325
+ if (name == "Del") name = "Delete";
38326
+ if (name == "Left") name = "ArrowLeft";
38327
+ if (name == "Up") name = "ArrowUp";
38328
+ if (name == "Right") name = "ArrowRight";
38329
+ if (name == "Down") name = "ArrowDown";
38330
+ return name;
38331
+ }
38332
+ const mac = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
38333
+ const windows = typeof navigator != "undefined" && /Win/.test(navigator.platform);
38334
+ function normalizeKeyName(name) {
38335
+ let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];
38336
+ if (result == "Space")
38337
+ result = " ";
38338
+ let alt, ctrl, shift2, meta;
38339
+ for (let i = 0; i < parts.length - 1; i++) {
38340
+ let mod = parts[i];
38341
+ if (/^(cmd|meta|m)$/i.test(mod))
38342
+ meta = true;
38343
+ else if (/^a(lt)?$/i.test(mod))
38344
+ alt = true;
38345
+ else if (/^(c|ctrl|control)$/i.test(mod))
38346
+ ctrl = true;
38347
+ else if (/^s(hift)?$/i.test(mod))
38348
+ shift2 = true;
38349
+ else if (/^mod$/i.test(mod)) {
38350
+ if (mac)
38351
+ meta = true;
38352
+ else
38353
+ ctrl = true;
38354
+ } else
38355
+ throw new Error("Unrecognized modifier name: " + mod);
38356
+ }
38357
+ if (alt)
38358
+ result = "Alt-" + result;
38359
+ if (ctrl)
38360
+ result = "Ctrl-" + result;
38361
+ if (meta)
38362
+ result = "Meta-" + result;
38363
+ if (shift2)
38364
+ result = "Shift-" + result;
38365
+ return result;
38366
+ }
38367
+ function normalize(map22) {
38368
+ let copy2 = /* @__PURE__ */ Object.create(null);
38369
+ for (let prop in map22)
38370
+ copy2[normalizeKeyName(prop)] = map22[prop];
38371
+ return copy2;
38372
+ }
38373
+ function modifiers(name, event, shift2 = true) {
38374
+ if (event.altKey)
38375
+ name = "Alt-" + name;
38376
+ if (event.ctrlKey)
38377
+ name = "Ctrl-" + name;
38378
+ if (event.metaKey)
38379
+ name = "Meta-" + name;
38380
+ if (shift2 && event.shiftKey)
38381
+ name = "Shift-" + name;
38382
+ return name;
38383
+ }
38384
+ function keymap(bindings) {
38385
+ return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
38386
+ }
38387
+ function keydownHandler(bindings) {
38388
+ let map22 = normalize(bindings);
38389
+ return function(view, event) {
38390
+ let name = keyName(event), baseName, direct = map22[modifiers(name, event)];
38391
+ if (direct && direct(view.state, view.dispatch, view))
38392
+ return true;
38393
+ if (name.length == 1 && name != " ") {
38394
+ if (event.shiftKey) {
38395
+ let noShift = map22[modifiers(name, event, false)];
38396
+ if (noShift && noShift(view.state, view.dispatch, view))
38397
+ return true;
38398
+ }
38399
+ if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
38400
+ !(windows && event.ctrlKey && event.altKey) && (baseName = base$1[event.keyCode]) && baseName != name) {
38401
+ let fromCode = map22[modifiers(baseName, event)];
38402
+ if (fromCode && fromCode(view.state, view.dispatch, view))
38403
+ return true;
38404
+ }
38405
+ }
38406
+ return false;
38407
+ };
38408
+ }
38409
+ function isExtensionRulesEnabled(extension, enabled) {
38410
+ if (Array.isArray(enabled)) {
38411
+ return enabled.some((enabledExtension) => {
38412
+ const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name;
38413
+ return name === extension.name;
38414
+ });
38415
+ }
38416
+ return enabled;
38400
38417
  }
38401
38418
  const _ExtensionService = class _ExtensionService2 {
38402
38419
  constructor(extensions, userExtensions, editor) {
@@ -39226,6 +39243,8 @@ const createHeaderFooterEditor = ({
39226
39243
  });
39227
39244
  if (appendToBody) document.body.appendChild(editorContainer);
39228
39245
  const headerFooterEditor = new Editor({
39246
+ documentMode: editor.options.documentMode,
39247
+ role: editor.options.role,
39229
39248
  loadFromSchema: true,
39230
39249
  mode: "docx",
39231
39250
  element: editorContainer,
@@ -39236,6 +39255,7 @@ const createHeaderFooterEditor = ({
39236
39255
  mediaFiles: editor.storage.image.media,
39237
39256
  fonts: editor.options.fonts,
39238
39257
  isHeaderOrFooter: true,
39258
+ isHeadless: editor.options.isHeadless,
39239
39259
  annotations: true,
39240
39260
  currentPageNumber,
39241
39261
  parentEditor: editor,
@@ -39243,13 +39263,15 @@ const createHeaderFooterEditor = ({
39243
39263
  onBlur: (evt) => onHeaderFooterDataUpdate(evt, editor, sectionId, type2)
39244
39264
  });
39245
39265
  const pm = editorContainer.querySelector(".ProseMirror");
39246
- pm.style.maxHeight = "100%";
39247
- pm.style.minHeight = "100%";
39248
- pm.style.outline = "none";
39249
- pm.style.border = "none";
39250
- pm.setAttribute("role", "textbox");
39251
- pm.setAttribute("aria-multiline", true);
39252
- pm.setAttribute("aria-label", `${type2} content area. Double click to start typing.`);
39266
+ if (pm) {
39267
+ pm.style.maxHeight = "100%";
39268
+ pm.style.minHeight = "100%";
39269
+ pm.style.outline = "none";
39270
+ pm.style.border = "none";
39271
+ pm.setAttribute("role", "textbox");
39272
+ pm.setAttribute("aria-multiline", true);
39273
+ pm.setAttribute("aria-label", `${type2} content area. Double click to start typing.`);
39274
+ }
39253
39275
  return headerFooterEditor;
39254
39276
  };
39255
39277
  const broadcastEditorEvents = (editor, sectionEditor) => {
@@ -39268,14 +39290,16 @@ const broadcastEditorEvents = (editor, sectionEditor) => {
39268
39290
  });
39269
39291
  });
39270
39292
  };
39271
- const toggleHeaderFooterEditMode = (editor, focusedSectionEditor, isEditMode) => {
39293
+ const toggleHeaderFooterEditMode = ({ editor, focusedSectionEditor, isEditMode, documentMode }) => {
39272
39294
  editor.converter.headerEditors.forEach((item) => {
39273
39295
  item.editor.setEditable(isEditMode, false);
39274
39296
  item.editor.view.dom.setAttribute("aria-readonly", !isEditMode);
39297
+ item.editor.view.dom.setAttribute("documentmode", documentMode);
39275
39298
  });
39276
39299
  editor.converter.footerEditors.forEach((item) => {
39277
39300
  item.editor.setEditable(isEditMode, false);
39278
39301
  item.editor.view.dom.setAttribute("aria-readonly", !isEditMode);
39302
+ item.editor.view.dom.setAttribute("documentmode", documentMode);
39279
39303
  });
39280
39304
  if (isEditMode) {
39281
39305
  const pm = document.querySelector(".ProseMirror");
@@ -40356,6 +40380,19 @@ const deleteHeaderFooterFieldAnnotations = ({ editor, fieldIdOrArray }) => {
40356
40380
  );
40357
40381
  });
40358
40382
  };
40383
+ const resetHeaderFooterFieldAnnotations = ({ editor }) => {
40384
+ if (!editor) return;
40385
+ const sectionEditors = getAllHeaderFooterEditors(editor);
40386
+ sectionEditors.forEach(({ editor: sectionEditor, sectionId, type: type2 }) => {
40387
+ sectionEditor.commands.resetFieldAnnotations();
40388
+ onHeaderFooterDataUpdate(
40389
+ { editor: sectionEditor },
40390
+ editor,
40391
+ sectionId,
40392
+ type2
40393
+ );
40394
+ });
40395
+ };
40359
40396
  const cleanUpListsWithAnnotations = (fieldsToDelete = [], editor) => {
40360
40397
  if (!Array.isArray(fieldsToDelete)) fieldsToDelete = [fieldsToDelete];
40361
40398
  const { doc: doc2 } = editor.state;
@@ -40426,6 +40463,7 @@ const AnnotatorHelpers = {
40426
40463
  getAllHeaderFooterEditors,
40427
40464
  updateHeaderFooterFieldAnnotations,
40428
40465
  deleteHeaderFooterFieldAnnotations,
40466
+ resetHeaderFooterFieldAnnotations,
40429
40467
  cleanUpListsWithAnnotations
40430
40468
  };
40431
40469
  const CollaborationPluginKey = new PluginKey("collaboration");
@@ -40605,6 +40643,16 @@ const setWordSelection = (view, pos) => {
40605
40643
  const tr = state2.tr.setSelection(TextSelection.create(state2.doc, word.from, word.to));
40606
40644
  dispatch(tr);
40607
40645
  };
40646
+ const setImageNodeSelection = (view, pos) => {
40647
+ const { doc: doc2 } = view.state;
40648
+ const node2 = doc2.nodeAt(pos);
40649
+ if (node2 && node2.type.name === "image") {
40650
+ const tr = view.state.tr.setSelection(NodeSelection.create(doc2, pos));
40651
+ view.dispatch(tr);
40652
+ return true;
40653
+ }
40654
+ return false;
40655
+ };
40608
40656
  const _Editor = class _Editor2 extends EventEmitter$1 {
40609
40657
  /**
40610
40658
  * Create a new Editor instance
@@ -40703,6 +40751,19 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
40703
40751
  this.setHighContrastMode = setHighContrastMode;
40704
40752
  initMode();
40705
40753
  }
40754
+ mount(el) {
40755
+ __privateMethod$1(this, _Editor_instances, createView_fn).call(this, el);
40756
+ window.setTimeout(() => {
40757
+ if (this.isDestroyed) return;
40758
+ this.emit("create", { editor: this });
40759
+ }, 0);
40760
+ }
40761
+ unmount() {
40762
+ if (this.view) {
40763
+ this.view.destroy();
40764
+ }
40765
+ this.view = null;
40766
+ }
40706
40767
  /**
40707
40768
  * Set the toolbar for this editor
40708
40769
  * @param {Object} toolbar - The toolbar instance
@@ -40751,7 +40812,7 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
40751
40812
  * @returns {boolean}
40752
40813
  */
40753
40814
  get isDestroyed() {
40754
- return this.view.isDestroyed;
40815
+ return this.view?.isDestroyed ?? true;
40755
40816
  }
40756
40817
  /**
40757
40818
  * Get the editor element
@@ -40794,7 +40855,12 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
40794
40855
  this.commands.toggleTrackChangesShowOriginal();
40795
40856
  this.setEditable(false, false);
40796
40857
  this.setOptions({ documentMode: "viewing" });
40797
- toggleHeaderFooterEditMode(this, null, false);
40858
+ toggleHeaderFooterEditMode({
40859
+ editor: this,
40860
+ focusedSectionEditor: null,
40861
+ isEditMode: false,
40862
+ documentMode: cleanedMode
40863
+ });
40798
40864
  } else if (cleanedMode === "suggesting") {
40799
40865
  __privateMethod$1(this, _Editor_instances, registerPluginByNameIfNotExists_fn).call(this, "TrackChangesBase");
40800
40866
  this.commands.disableTrackChangesShowOriginal();
@@ -40807,7 +40873,12 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
40807
40873
  this.commands.disableTrackChanges();
40808
40874
  this.setEditable(true, false);
40809
40875
  this.setOptions({ documentMode: "editing" });
40810
- toggleHeaderFooterEditMode(this, null, false);
40876
+ toggleHeaderFooterEditMode({
40877
+ editor: this,
40878
+ focusedSectionEditor: null,
40879
+ isEditMode: false,
40880
+ documentMode: cleanedMode
40881
+ });
40811
40882
  }
40812
40883
  }
40813
40884
  /**
@@ -40905,10 +40976,10 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
40905
40976
  }
40906
40977
  /**
40907
40978
  * Unregister a PM plugin
40908
- * @param {string|Object} nameOrPlugin - Plugin name or plugin instance
40979
+ * @param {string|Object} nameOrPluginKey - Plugin name or plugin instance
40909
40980
  * @returns {void}
40910
40981
  */
40911
- unregisterPlugin(nameOrPlugin) {
40982
+ unregisterPlugin(nameOrPluginKey) {
40912
40983
  if (this.isDestroyed) return;
40913
40984
  const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key;
40914
40985
  const state2 = this.state.reconfigure({
@@ -40984,29 +41055,26 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
40984
41055
  };
40985
41056
  }
40986
41057
  /**
40987
- * Initialize default styles for the editor container and ProseMirror.
40988
- * Get page size and margins from the converter.
40989
- * Set document default font and font size.
40990
- *
40991
- * @param {HTMLElement} [element=this.element] - The DOM element to apply styles to
40992
- * @returns {void}
40993
- */
40994
- initDefaultStyles(element = this.element) {
40995
- if (this.options.isHeadless || this.options.suppressDefaultDocxStyles) return;
40996
- const proseMirror = element?.querySelector(".ProseMirror");
41058
+ * Attach styles and attributes to the editor element
41059
+ */
41060
+ updateEditorStyles(element, proseMirror, hasPaginationEnabled = true) {
40997
41061
  const { pageSize, pageMargins } = this.converter.pageStyles ?? {};
40998
- if (!proseMirror || !pageSize || !pageMargins) {
41062
+ if (!proseMirror || !element) {
40999
41063
  return;
41000
41064
  }
41001
41065
  proseMirror.setAttribute("role", "document");
41002
41066
  proseMirror.setAttribute("aria-multiline", true);
41003
41067
  proseMirror.setAttribute("aria-label", "Main content area, start typing to enter text.");
41004
41068
  proseMirror.setAttribute("aria-description", "");
41005
- element.style.width = pageSize.width + "in";
41006
- element.style.minWidth = pageSize.width + "in";
41007
- element.style.minHeight = pageSize.height + "in";
41008
- element.style.paddingLeft = pageMargins.left + "in";
41009
- element.style.paddingRight = pageMargins.right + "in";
41069
+ if (pageSize) {
41070
+ element.style.width = pageSize.width + "in";
41071
+ element.style.minWidth = pageSize.width + "in";
41072
+ element.style.minHeight = pageSize.height + "in";
41073
+ }
41074
+ if (pageMargins) {
41075
+ element.style.paddingLeft = pageMargins.left + "in";
41076
+ element.style.paddingRight = pageMargins.right + "in";
41077
+ }
41010
41078
  element.style.boxSizing = "border-box";
41011
41079
  element.style.isolation = "isolate";
41012
41080
  proseMirror.style.outline = "none";
@@ -41023,10 +41091,26 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
41023
41091
  element.style.webkitOverflowScrolling = "touch";
41024
41092
  const defaultLineHeight = 1.2;
41025
41093
  proseMirror.style.lineHeight = defaultLineHeight;
41026
- if (!this.options.extensions.find((e) => e.name === "pagination")) {
41094
+ if (!hasPaginationEnabled) {
41027
41095
  proseMirror.style.paddingTop = "1in";
41028
41096
  proseMirror.style.paddingBottom = "1in";
41097
+ } else {
41098
+ proseMirror.style.paddingTop = "0";
41099
+ proseMirror.style.paddingBottom = "0";
41029
41100
  }
41101
+ }
41102
+ /**
41103
+ * Initialize default styles for the editor container and ProseMirror.
41104
+ * Get page size and margins from the converter.
41105
+ * Set document default font and font size.
41106
+ *
41107
+ * @param {HTMLElement} [element=this.element] - The DOM element to apply styles to
41108
+ * @returns {void}
41109
+ */
41110
+ initDefaultStyles(element = this.element, isPaginationEnabled = true) {
41111
+ if (this.options.isHeadless || this.options.suppressDefaultDocxStyles) return;
41112
+ const proseMirror = element?.querySelector(".ProseMirror");
41113
+ this.updateEditorStyles(element, proseMirror, isPaginationEnabled);
41030
41114
  this.initMobileStyles(element);
41031
41115
  }
41032
41116
  /**
@@ -41074,6 +41158,26 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
41074
41158
  }
41075
41159
  window.addEventListener("resize", () => handleResize);
41076
41160
  }
41161
+ /**
41162
+ * Initialize pagination, if the pagination extension is enabled.
41163
+ * @private
41164
+ * @async
41165
+ * @returns {Promise<void>}
41166
+ */
41167
+ async initPagination() {
41168
+ if (this.options.isHeadless || !this.extensionService || this.options.isHeaderOrFooter) {
41169
+ return;
41170
+ }
41171
+ const pagination = this.options.extensions.find((e) => e.name === "pagination");
41172
+ if (pagination && this.options.pagination) {
41173
+ console.debug("🔗 [super-editor] Initializing pagination");
41174
+ const sectionData = await initPaginationData(this);
41175
+ this.storage.pagination.sectionData = sectionData;
41176
+ const { state: state2, dispatch } = this.view;
41177
+ const tr = state2.tr.setMeta(PaginationPluginKey, { isReadyToInit: true });
41178
+ dispatch(tr);
41179
+ }
41180
+ }
41077
41181
  /**
41078
41182
  * Get attrs of the currently selected node or mark.
41079
41183
  * @param {String} nameOrType
@@ -41238,10 +41342,25 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
41238
41342
  */
41239
41343
  destroy() {
41240
41344
  this.emit("destroy");
41241
- if (this.view) this.view.destroy();
41345
+ this.unmount();
41346
+ this.destroyHeaderFooterEditors();
41242
41347
  __privateMethod$1(this, _Editor_instances, endCollaboration_fn).call(this);
41243
41348
  this.removeAllListeners();
41244
41349
  }
41350
+ destroyHeaderFooterEditors() {
41351
+ try {
41352
+ const editors = [
41353
+ ...this.converter.headerEditors,
41354
+ ...this.converter.footerEditors
41355
+ ];
41356
+ for (let editorData of editors) {
41357
+ editorData.editor.destroy();
41358
+ }
41359
+ this.converter.headerEditors.length = 0;
41360
+ this.converter.footerEditors.length = 0;
41361
+ } catch (error) {
41362
+ }
41363
+ }
41245
41364
  /**
41246
41365
  * Check if migrations are needed for the data
41247
41366
  * @static
@@ -41259,7 +41378,7 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
41259
41378
  * @returns {Object | void} Migration results
41260
41379
  */
41261
41380
  processCollaborationMigrations() {
41262
- console.debug("[checkVersionMigrations] Current editor version", "0.13.2-rev1");
41381
+ console.debug("[checkVersionMigrations] Current editor version", "0.13.2-rev11");
41263
41382
  if (!this.options.ydoc) return;
41264
41383
  const metaMap = this.options.ydoc.getMap("meta");
41265
41384
  let docVersion = metaMap.get("version");
@@ -41309,7 +41428,7 @@ const _Editor = class _Editor2 extends EventEmitter$1 {
41309
41428
  __privateMethod$1(this, _Editor_instances, insertNewFileData_fn).call(this);
41310
41429
  }
41311
41430
  if (!this.options.ydoc) {
41312
- __privateMethod$1(this, _Editor_instances, initPagination_fn).call(this);
41431
+ this.initPagination();
41313
41432
  __privateMethod$1(this, _Editor_instances, initComments_fn).call(this);
41314
41433
  }
41315
41434
  }
@@ -41455,9 +41574,7 @@ init_fn = function(options2) {
41455
41574
  this.emit("beforeCreate", { editor: this });
41456
41575
  this.on("contentError", this.options.onContentError);
41457
41576
  this.on("exception", this.options.onException);
41458
- __privateMethod$1(this, _Editor_instances, createView_fn).call(this);
41459
- this.initDefaultStyles();
41460
- this.setDocumentMode(options2.documentMode);
41577
+ this.mount(this.options.element);
41461
41578
  if (this.options.isHeadless) return;
41462
41579
  this.on("create", this.options.onCreate);
41463
41580
  this.on("update", this.options.onUpdate);
@@ -41475,14 +41592,12 @@ init_fn = function(options2) {
41475
41592
  this.on("paginationUpdate", this.options.onPaginationUpdate);
41476
41593
  this.on("comment-positions", this.options.onCommentLocationsUpdate);
41477
41594
  this.initializeCollaborationData();
41595
+ this.initDefaultStyles();
41596
+ this.setDocumentMode(this.options.documentMode);
41478
41597
  if (!this.options.ydoc) {
41479
- __privateMethod$1(this, _Editor_instances, initPagination_fn).call(this);
41598
+ this.initPagination();
41480
41599
  __privateMethod$1(this, _Editor_instances, initComments_fn).call(this);
41481
41600
  }
41482
- window.setTimeout(() => {
41483
- if (this.isDestroyed) return;
41484
- this.emit("create", { editor: this });
41485
- }, 0);
41486
41601
  };
41487
41602
  initRichText_fn = function(options2) {
41488
41603
  if (!options2.extensions || !options2.extensions.length) {
@@ -41494,7 +41609,7 @@ initRichText_fn = function(options2) {
41494
41609
  this.on("beforeCreate", this.options.onBeforeCreate);
41495
41610
  this.emit("beforeCreate", { editor: this });
41496
41611
  this.on("contentError", this.options.onContentError);
41497
- __privateMethod$1(this, _Editor_instances, createView_fn).call(this);
41612
+ this.mount(this.options.element);
41498
41613
  this.on("create", this.options.onCreate);
41499
41614
  this.on("update", this.options.onUpdate);
41500
41615
  this.on("selectionUpdate", this.options.onSelectionUpdate);
@@ -41505,10 +41620,6 @@ initRichText_fn = function(options2) {
41505
41620
  this.on("commentsLoaded", this.options.onCommentsLoaded);
41506
41621
  this.on("commentClick", this.options.onCommentClicked);
41507
41622
  this.on("locked", this.options.onDocumentLocked);
41508
- window.setTimeout(() => {
41509
- if (this.isDestroyed) return;
41510
- this.emit("create", { editor: this });
41511
- }, 0);
41512
41623
  };
41513
41624
  onFocus_fn = function({ editor, event }) {
41514
41625
  this.toolbar?.setActiveEditor(editor);
@@ -41531,7 +41642,7 @@ insertNewFileData_fn = function() {
41531
41642
  const tr = this.state.tr.replaceWith(0, this.state.doc.content.size, doc2);
41532
41643
  this.view.dispatch(tr);
41533
41644
  setTimeout(() => {
41534
- __privateMethod$1(this, _Editor_instances, initPagination_fn).call(this);
41645
+ this.initPagination();
41535
41646
  __privateMethod$1(this, _Editor_instances, initComments_fn).call(this);
41536
41647
  }, 50);
41537
41648
  };
@@ -41629,14 +41740,15 @@ createDocFromHTML_fn = function(content) {
41629
41740
  }
41630
41741
  return DOMParser$1.fromSchema(this.schema).parse(parsedContent);
41631
41742
  };
41632
- createView_fn = function() {
41743
+ createView_fn = function(element) {
41633
41744
  let doc2 = __privateMethod$1(this, _Editor_instances, generatePmData_fn).call(this);
41634
41745
  const state2 = { schema: this.schema };
41635
41746
  if (!this.options.ydoc) state2.doc = doc2;
41636
- this.view = new EditorView(this.options.element, {
41747
+ this.view = new EditorView(element, {
41637
41748
  ...this.options.editorProps,
41638
41749
  dispatchTransaction: __privateMethod$1(this, _Editor_instances, dispatchTransaction_fn).bind(this),
41639
41750
  state: EditorState.create(state2),
41751
+ handleClick: __privateMethod$1(this, _Editor_instances, handleNodeSelection_fn).bind(this),
41640
41752
  handleDoubleClick: async (view, pos, event) => {
41641
41753
  if (this.options.documentMode !== "editing") return;
41642
41754
  const isHeader = hasSomeParentWithClass(event.target, "pagination-section-header");
@@ -41650,7 +41762,12 @@ createView_fn = function() {
41650
41762
  event.stopPropagation();
41651
41763
  if (!this.options.editable) {
41652
41764
  this.setEditable(true, false);
41653
- toggleHeaderFooterEditMode(this, null, false);
41765
+ toggleHeaderFooterEditMode({
41766
+ editor: this,
41767
+ focusedSectionEditor: null,
41768
+ isEditMode: false,
41769
+ documentMode: this.options.documentMode
41770
+ });
41654
41771
  const pm = document.querySelector(".ProseMirror");
41655
41772
  pm.classList.remove("header-footer-edit");
41656
41773
  pm.setAttribute("aria-readonly", false);
@@ -41663,8 +41780,6 @@ createView_fn = function() {
41663
41780
  });
41664
41781
  this.view.updateState(newState);
41665
41782
  this.createNodeViews();
41666
- const dom = this.view.dom;
41667
- dom.editor = this;
41668
41783
  this.options.telemetry?.sendReport();
41669
41784
  };
41670
41785
  onCollaborationReady_fn = function({ editor, ydoc }) {
@@ -41673,7 +41788,7 @@ onCollaborationReady_fn = function({ editor, ydoc }) {
41673
41788
  this.options.onCollaborationReady({ editor, ydoc });
41674
41789
  this.options.collaborationIsReady = true;
41675
41790
  if (!this.options.isNewFile) {
41676
- __privateMethod$1(this, _Editor_instances, initPagination_fn).call(this);
41791
+ this.initPagination();
41677
41792
  __privateMethod$1(this, _Editor_instances, initComments_fn).call(this);
41678
41793
  }
41679
41794
  };
@@ -41690,20 +41805,8 @@ initComments_fn = function() {
41690
41805
  dispatch(tr);
41691
41806
  }, 50);
41692
41807
  };
41693
- initPagination_fn = async function() {
41694
- if (this.options.isHeadless || !this.extensionService) return;
41695
- const pagination = this.options.extensions.find((e) => e.name === "pagination");
41696
- if (pagination && this.options.pagination) {
41697
- console.debug("🔗 [super-editor] Initializing pagination");
41698
- const sectionData = await initPaginationData(this);
41699
- this.storage.pagination.sectionData = sectionData;
41700
- const { state: state2, dispatch } = this.view;
41701
- const tr = state2.tr.setMeta(PaginationPluginKey, { isReadyToInit: true });
41702
- dispatch(tr);
41703
- }
41704
- };
41705
41808
  dispatchTransaction_fn = function(transaction) {
41706
- if (this.view.isDestroyed) return;
41809
+ if (this.isDestroyed) return;
41707
41810
  let state2;
41708
41811
  try {
41709
41812
  const trackChangesState = TrackChangesBasePluginKey.getState(this.view.state);
@@ -41755,6 +41858,11 @@ dispatchTransaction_fn = function(transaction) {
41755
41858
  transaction
41756
41859
  });
41757
41860
  };
41861
+ handleNodeSelection_fn = function(view, pos) {
41862
+ if (this.options.isHeaderOrFooter) {
41863
+ return setImageNodeSelection(view, pos);
41864
+ }
41865
+ };
41758
41866
  prepareDocumentForImport_fn = function(doc2) {
41759
41867
  const newState = EditorState.create({
41760
41868
  schema: this.schema,
@@ -44097,7 +44205,7 @@ const Paragraph = Node$1.create({
44097
44205
  },
44098
44206
  addPmPlugins() {
44099
44207
  const { view } = this.editor;
44100
- const dropcapPlugin = new Plugin({
44208
+ new Plugin({
44101
44209
  name: "dropcapPlugin",
44102
44210
  key: new PluginKey("dropcapPlugin"),
44103
44211
  state: {
@@ -44117,7 +44225,7 @@ const Paragraph = Node$1.create({
44117
44225
  }
44118
44226
  }
44119
44227
  });
44120
- return [dropcapPlugin];
44228
+ return [];
44121
44229
  }
44122
44230
  });
44123
44231
  const getDropcapDecorations = (state2, view) => {
@@ -44470,7 +44578,16 @@ const HardBreak = Node$1.create({
44470
44578
  };
44471
44579
  },
44472
44580
  parseDOM() {
44473
- return [{ tag: "span" }];
44581
+ return [{
44582
+ tag: 'span[linebreaktype="page"]',
44583
+ getAttrs: (dom) => {
44584
+ if (!(dom instanceof HTMLElement)) return false;
44585
+ return {
44586
+ pageBreakSource: dom.getAttribute("pagebreaksource") || null,
44587
+ pageBreakType: dom.getAttribute("linebreaktype") || null
44588
+ };
44589
+ }
44590
+ }];
44474
44591
  },
44475
44592
  renderDOM({ htmlAttributes }) {
44476
44593
  return ["span", Attribute2.mergeAttributes(this.options.htmlAttributes, htmlAttributes)];
@@ -47467,6 +47584,8 @@ function findRemovedFieldAnnotations(tr) {
47467
47584
  if (!tr.steps.length || tr.meta && !Object.keys(tr.meta).every((meta) => ["inputType", "uiEvent", "paste"].includes(meta)) || ["historyUndo", "historyRedo"].includes(tr.getMeta("inputType")) || ["drop"].includes(tr.getMeta("uiEvent")) || tr.getMeta("fieldAnnotationUpdate") === true) {
47468
47585
  return removedNodes;
47469
47586
  }
47587
+ const hasDeletion = transactionDeletedAnything(tr);
47588
+ if (!hasDeletion) return removedNodes;
47470
47589
  tr.steps.forEach((step, stepIndex) => {
47471
47590
  if (step instanceof ReplaceStep && step.from !== step.to) {
47472
47591
  let mapping = tr.mapping.maps[stepIndex];
@@ -47483,6 +47602,14 @@ function findRemovedFieldAnnotations(tr) {
47483
47602
  });
47484
47603
  return removedNodes;
47485
47604
  }
47605
+ function transactionDeletedAnything(tr) {
47606
+ return tr.steps.some((step) => {
47607
+ if (step instanceof ReplaceStep || step instanceof ReplaceAroundStep) {
47608
+ return step.from !== step.to;
47609
+ }
47610
+ return false;
47611
+ });
47612
+ }
47486
47613
  function trackFieldAnnotationsDeletion(editor, tr) {
47487
47614
  let removedAnnotations = [];
47488
47615
  try {
@@ -47878,8 +48005,18 @@ const FieldAnnotation = Node$1.create({
47878
48005
  };
47879
48006
  }
47880
48007
  },
48008
+ defaultDisplayLabel: {
48009
+ default: "",
48010
+ parseDOM: (elem) => elem.getAttribute("data-default-display-label"),
48011
+ renderDOM: (attrs) => {
48012
+ if (!attrs.defaultDisplayLabel) return {};
48013
+ return {
48014
+ "data-default-display-label": attrs.defaultDisplayLabel
48015
+ };
48016
+ }
48017
+ },
47881
48018
  displayLabel: {
47882
- default: "Text field",
48019
+ default: "",
47883
48020
  parseDOM: (elem) => elem.getAttribute("data-display-label"),
47884
48021
  renderDOM: (attrs) => {
47885
48022
  if (!attrs.displayLabel) return {};
@@ -48195,6 +48332,7 @@ const FieldAnnotation = Node$1.create({
48195
48332
  return renderer();
48196
48333
  },
48197
48334
  addCommands() {
48335
+ const annotationTypes = this.options.types;
48198
48336
  return {
48199
48337
  /**
48200
48338
  * Add field annotation.
@@ -48216,7 +48354,12 @@ const FieldAnnotation = Node$1.create({
48216
48354
  let currentMarks = $pos.marks();
48217
48355
  currentMarks = currentMarks.length ? [...currentMarks] : null;
48218
48356
  let formatAttrs = getFormatAttrsFromMarks(currentMarks);
48219
- let node2 = schema.nodes[this.name].create({ ...attrs, ...formatAttrs }, null, null);
48357
+ let defaultDisplayLabel = attrs.defaultDisplayLabel ? attrs.defaultDisplayLabel : attrs.displayLabel || "";
48358
+ let node2 = schema.nodes[this.name].create({
48359
+ ...attrs,
48360
+ ...formatAttrs,
48361
+ defaultDisplayLabel
48362
+ }, null, null);
48220
48363
  state2.tr.insert(newPos, node2).setSelection(Selection.near(tr.doc.resolve(newPos + node2.nodeSize)));
48221
48364
  if (editorFocus) {
48222
48365
  this.editor.view.focus();
@@ -48224,9 +48367,9 @@ const FieldAnnotation = Node$1.create({
48224
48367
  }
48225
48368
  return true;
48226
48369
  },
48227
- addFieldAnnotationAtSelection: (attrs = {}, editorFocus = false) => ({ editor, dispatch, state: state2, tr, commands: commands2 }) => {
48370
+ addFieldAnnotationAtSelection: (attrs = {}, editorFocus = false) => ({ state: state2, commands: commands2 }) => {
48228
48371
  const { from: from2 } = state2.selection;
48229
- commands2.addFieldAnnotation(from2, attrs, editorFocus);
48372
+ return commands2.addFieldAnnotation(from2, attrs, editorFocus);
48230
48373
  },
48231
48374
  /**
48232
48375
  * Replace field annotation.
@@ -48236,24 +48379,113 @@ const FieldAnnotation = Node$1.create({
48236
48379
  * from: 20,
48237
48380
  * to: 45,
48238
48381
  * attrs: {
48239
- * fieldType: 'TEXTINPUT'
48240
- * fieldColor: '#980043'
48382
+ * fieldType: 'TEXTINPUT'
48383
+ * fieldColor: '#980043'
48241
48384
  * }
48242
48385
  * ])
48243
48386
  */
48244
- replaceWithFieldAnnotation: (fieldsArray) => ({ editor, dispatch, state: state2, tr }) => {
48387
+ replaceWithFieldAnnotation: (fieldsArray) => ({ editor, dispatch, tr }) => {
48245
48388
  if (!dispatch) return true;
48246
- tr.setMeta("fieldAnnotationReplace", true);
48247
48389
  fieldsArray.forEach((annotation) => {
48248
48390
  let { from: from2, to, attrs } = annotation;
48249
48391
  let { schema } = editor;
48250
48392
  let newPosFrom = tr.mapping.map(from2);
48251
48393
  let newPosTo = tr.mapping.map(to);
48252
- let node2 = schema.nodes[this.name].create({ ...attrs }, null, null);
48394
+ let defaultDisplayLabel = attrs.defaultDisplayLabel ? attrs.defaultDisplayLabel : attrs.displayLabel || "";
48395
+ let node2 = schema.nodes[this.name].create({
48396
+ ...attrs,
48397
+ defaultDisplayLabel
48398
+ }, null, null);
48253
48399
  tr.replaceWith(newPosFrom, newPosTo, node2);
48254
48400
  });
48255
48401
  return true;
48256
48402
  },
48403
+ /**
48404
+ * Replace annotations with a label (as text node) in selection.
48405
+ * @param options Additional options.
48406
+ * @example
48407
+ * editor.commands.replaceFieldAnnotationsWithLabelInSelection()
48408
+ */
48409
+ replaceFieldAnnotationsWithLabelInSelection: (options2 = {}) => ({ commands: commands2 }) => {
48410
+ return commands2.replaceFieldAnnotationsWithLabel(null, {
48411
+ ...options2,
48412
+ isInSelection: true
48413
+ });
48414
+ },
48415
+ /**
48416
+ * Replace annotations with a label (as text node).
48417
+ * @param fieldIdOrArray The field ID or array of field IDs.
48418
+ * @param options.isInSelection Find in selection instead of field IDs.
48419
+ * @param options.addToHistory Add to history or not.
48420
+ * @param options.types Annotation types to replace.
48421
+ * @example
48422
+ * editor.commands.replaceFieldAnnotationsWithLabel(['1', '2'])
48423
+ */
48424
+ replaceFieldAnnotationsWithLabel: (fieldIdOrArray, {
48425
+ isInSelection = false,
48426
+ addToHistory = false,
48427
+ types: types2 = annotationTypes
48428
+ } = {}) => ({ dispatch, state: state2, tr }) => {
48429
+ let { from: from2, to } = state2.selection;
48430
+ let annotations = isInSelection ? findFieldAnnotationsBetween(from2, to, state2.doc) : findFieldAnnotationsByFieldId(fieldIdOrArray, state2);
48431
+ annotations = types2.length ? annotations.filter(({ node: node2 }) => types2.includes(node2.attrs.type)) : annotations;
48432
+ if (!annotations.length) {
48433
+ return true;
48434
+ }
48435
+ if (!addToHistory) {
48436
+ tr.setMeta("addToHistory", false);
48437
+ }
48438
+ if (dispatch) {
48439
+ annotations.forEach((annotation) => {
48440
+ let { pos, node: node2 } = annotation;
48441
+ let newPosFrom = tr.mapping.map(pos);
48442
+ let newPosTo = tr.mapping.map(pos + node2.nodeSize);
48443
+ let currentNode = tr.doc.nodeAt(newPosFrom);
48444
+ let nodeEqual = node2.attrs.fieldId === currentNode?.attrs?.fieldId;
48445
+ let $newPosFrom = tr.doc.resolve(newPosFrom);
48446
+ let currentMarks = $newPosFrom.marks();
48447
+ currentMarks = currentMarks.length ? [...currentMarks] : null;
48448
+ if (nodeEqual) {
48449
+ let label = node2.attrs.displayLabel || " ";
48450
+ let textNode = state2.schema.text(label, currentMarks);
48451
+ tr.replaceWith(newPosFrom, newPosTo, textNode);
48452
+ }
48453
+ });
48454
+ }
48455
+ return true;
48456
+ },
48457
+ /**
48458
+ * Resets all annotations to default values.
48459
+ * @example
48460
+ * editor.commands.resetFieldAnnotations()
48461
+ */
48462
+ resetFieldAnnotations: () => ({ dispatch, state: state2, tr }) => {
48463
+ let annotations = getAllFieldAnnotations(state2);
48464
+ if (!annotations.length) {
48465
+ return true;
48466
+ }
48467
+ tr.setMeta("fieldAnnotationUpdate", true);
48468
+ if (dispatch) {
48469
+ annotations.forEach(({ pos, node: node2 }) => {
48470
+ let newPos = tr.mapping.map(pos);
48471
+ let currentNode = tr.doc.nodeAt(newPos);
48472
+ let nodeEqual = node2.attrs.fieldId === currentNode?.attrs?.fieldId;
48473
+ if (nodeEqual) {
48474
+ let displayLabel = node2.attrs.defaultDisplayLabel || node2.attrs.displayLabel || "";
48475
+ tr.setNodeMarkup(newPos, void 0, {
48476
+ ...node2.attrs,
48477
+ // reset displayLabel to default.
48478
+ displayLabel,
48479
+ // reset attrs ​​for specific types.
48480
+ imageSrc: null,
48481
+ rawHtml: null,
48482
+ linkUrl: null
48483
+ });
48484
+ }
48485
+ });
48486
+ }
48487
+ return true;
48488
+ },
48257
48489
  /**
48258
48490
  * Update annotations associated with a field.
48259
48491
  * @param fieldIdOrArray The field ID or array of field IDs.
@@ -49008,12 +49240,16 @@ const startImageUpload = async ({ editor, view, file }) => {
49008
49240
  }
49009
49241
  let id = {};
49010
49242
  let { tr, schema } = view.state;
49011
- if (!tr.selection.empty) {
49243
+ let { selection } = tr;
49244
+ if (editor.options.isHeaderOrFooter) {
49245
+ selection = editor.options.lastSelection;
49246
+ }
49247
+ if (!selection.empty && !editor.options.isHeaderOrFooter) {
49012
49248
  tr.deleteSelection();
49013
49249
  }
49014
49250
  let imageMeta = {
49015
49251
  type: "add",
49016
- pos: tr.selection.from,
49252
+ pos: selection.from,
49017
49253
  id
49018
49254
  };
49019
49255
  tr.setMeta(ImagePlaceholderPluginKey, imageMeta);
@@ -54262,7 +54498,8 @@ const Pagination = Extension.create({
54262
54498
  addStorage() {
54263
54499
  return {
54264
54500
  height: 0,
54265
- sectionData: null
54501
+ sectionData: null,
54502
+ headerFooterEditors: /* @__PURE__ */ new Map()
54266
54503
  };
54267
54504
  },
54268
54505
  addCommands() {
@@ -54271,6 +54508,19 @@ const Pagination = Extension.create({
54271
54508
  return commands2.insertContent({
54272
54509
  type: "hardBreak"
54273
54510
  });
54511
+ },
54512
+ /**
54513
+ * Toggle pagination on/off
54514
+ * @returns {void}
54515
+ */
54516
+ togglePagination: () => ({ tr, state: state2, dispatch, editor }) => {
54517
+ const isEnabled = PaginationPluginKey.getState(state2)?.isEnabled;
54518
+ tr.setMeta(PaginationPluginKey, { isEnabled: !isEnabled });
54519
+ if (dispatch) {
54520
+ dispatch(tr);
54521
+ editor.initDefaultStyles(editor.element, !isEnabled);
54522
+ return true;
54523
+ }
54274
54524
  }
54275
54525
  };
54276
54526
  },
@@ -54296,22 +54546,33 @@ const Pagination = Extension.create({
54296
54546
  return {
54297
54547
  isReadyToInit: false,
54298
54548
  decorations: DecorationSet.empty,
54299
- isDebugging
54549
+ isDebugging,
54550
+ isEnabled: editor.options.pagination
54300
54551
  };
54301
54552
  },
54302
54553
  apply(tr, oldState, prevEditorState, newEditorState) {
54303
54554
  const meta = tr.getMeta(PaginationPluginKey);
54555
+ if (meta && "isEnabled" in meta) {
54556
+ const newEnabled = meta.isEnabled;
54557
+ if (newEnabled) shouldUpdate = true;
54558
+ return {
54559
+ ...oldState,
54560
+ decorations: newEnabled ? oldState.decorations : DecorationSet.empty,
54561
+ isEnabled: newEnabled
54562
+ };
54563
+ }
54304
54564
  if (meta && meta.isReadyToInit) {
54305
54565
  shouldUpdate = true;
54306
54566
  shouldInitialize = meta.isReadyToInit;
54307
54567
  }
54568
+ const syncMeta = tr.getMeta("y-sync$");
54569
+ if (syncMeta && syncMeta.isChangeOrigin) {
54570
+ return { ...oldState };
54571
+ }
54308
54572
  const imagePluginTransaction = tr.getMeta(ImagePlaceholderPluginKey);
54309
54573
  if (imagePluginTransaction) {
54310
54574
  if (imagePluginTransaction.type === "remove") {
54311
- const imagePos = imagePluginTransaction.pos;
54312
- const domImage = editor.view.domAtPos(imagePos).node.querySelector("img");
54313
- if (domImage.complete) onImageLoad(editor);
54314
- else domImage.onload = () => onImageLoad(editor);
54575
+ onImageLoad(editor);
54315
54576
  }
54316
54577
  return { ...oldState };
54317
54578
  }
@@ -54338,6 +54599,7 @@ const Pagination = Extension.create({
54338
54599
  if (isForceUpdate) shouldUpdate = true;
54339
54600
  return {
54340
54601
  ...oldState,
54602
+ decorations: meta?.decorations?.map(tr.mapping, tr.doc) || DecorationSet.empty,
54341
54603
  isReadyToInit: shouldInitialize
54342
54604
  };
54343
54605
  }
@@ -54347,6 +54609,7 @@ const Pagination = Extension.create({
54347
54609
  let previousDecorations = DecorationSet.empty;
54348
54610
  return {
54349
54611
  update: (view2, prevState) => {
54612
+ if (!PaginationPluginKey.getState(view2.state)?.isEnabled) return;
54350
54613
  if (!shouldUpdate || isUpdating) return;
54351
54614
  isUpdating = true;
54352
54615
  hasInitialized = true;
@@ -54358,7 +54621,8 @@ const Pagination = Extension.create({
54358
54621
  },
54359
54622
  props: {
54360
54623
  decorations(state2) {
54361
- return PaginationPluginKey.getState(state2).decorations;
54624
+ const pluginState = PaginationPluginKey.getState(state2);
54625
+ return pluginState.isEnabled ? pluginState.decorations : DecorationSet.empty;
54362
54626
  }
54363
54627
  }
54364
54628
  });
@@ -54366,6 +54630,10 @@ const Pagination = Extension.create({
54366
54630
  },
54367
54631
  onDestroy() {
54368
54632
  cleanupFloatingSeparators();
54633
+ const { headerFooterEditors } = this.editor.storage.pagination;
54634
+ if (headerFooterEditors) {
54635
+ headerFooterEditors.clear();
54636
+ }
54369
54637
  }
54370
54638
  });
54371
54639
  const getHeaderFooterId = (currentPageNumber, sectionType, editor, node2 = null) => {
@@ -54426,6 +54694,7 @@ const performUpdate = (editor, view, previousDecorations) => {
54426
54694
  const calculatePageBreaks = (view, editor, sectionData) => {
54427
54695
  if (!editor.converter) return DecorationSet.empty;
54428
54696
  const pageSize = editor.converter.pageStyles?.pageSize;
54697
+ if (!pageSize) return DecorationSet.empty;
54429
54698
  const { width, height } = pageSize;
54430
54699
  if (!width || !height) return DecorationSet.empty;
54431
54700
  const ignorePlugins = [CollaborationPluginKey, PaginationPluginKey];
@@ -54464,11 +54733,13 @@ function generateInternalPageBreaks(doc2, view, editor, sectionData) {
54464
54733
  let pageHeightThreshold = pageHeight;
54465
54734
  let footer = null, header = null;
54466
54735
  const firstHeaderId = getHeaderFooterId(currentPageNumber, "headerIds", editor);
54467
- const firstHeader = createHeader(pageMargins, pageSize, sectionData, firstHeaderId, editor, currentPageNumber);
54736
+ const isFirstHeader = true;
54737
+ const firstHeader = createHeader(pageMargins, pageSize, sectionData, firstHeaderId, editor, currentPageNumber, isFirstHeader);
54468
54738
  const pageBreak = createPageBreak({ editor, header: firstHeader, isFirstHeader: true });
54469
54739
  decorations.push(Decoration.widget(0, pageBreak, { key: "stable-key" }));
54470
54740
  const lastFooterId = getHeaderFooterId(currentPageNumber, "footerIds", editor);
54471
- const lastFooter = createFooter(pageMargins, pageSize, sectionData, lastFooterId, editor, currentPageNumber);
54741
+ const isLastFooter = true;
54742
+ const lastFooter = createFooter(pageMargins, pageSize, sectionData, lastFooterId, editor, currentPageNumber, isLastFooter);
54472
54743
  pageHeightThreshold -= firstHeader.headerHeight + lastFooter.footerHeight;
54473
54744
  let coords = view?.coordsAtPos(doc2.content.size);
54474
54745
  if (!coords) return [];
@@ -54487,7 +54758,8 @@ function generateInternalPageBreaks(doc2, view, editor, sectionData) {
54487
54758
  if (currentPageNumber === 1) {
54488
54759
  const headerId2 = getHeaderFooterId(currentPageNumber, "headerIds", editor, currentNode);
54489
54760
  decorations.pop();
54490
- const newFirstHeader = createHeader(pageMargins, pageSize, sectionData, headerId2, editor, currentPageNumber - 1);
54761
+ const isFirstHeader2 = true;
54762
+ const newFirstHeader = createHeader(pageMargins, pageSize, sectionData, headerId2, editor, currentPageNumber, isFirstHeader2);
54491
54763
  const pageBreak2 = createPageBreak({ editor, header: newFirstHeader, isFirstHeader: true });
54492
54764
  decorations.push(Decoration.widget(0, pageBreak2, { key: "stable-key" }));
54493
54765
  }
@@ -54561,15 +54833,15 @@ function createFinalPagePadding(bufferHeight) {
54561
54833
  div2.style.height = bufferHeight + "px";
54562
54834
  return { nodeHeight: bufferHeight, node: div2 };
54563
54835
  }
54564
- function createHeader(pageMargins, pageSize, sectionData, headerId, editor, currentPageNumber) {
54565
- const headerDef = sectionData.headers?.[headerId];
54836
+ function createHeader(pageMargins, pageSize, sectionData, headerId, editor, currentPageNumber, isFirstHeader = false) {
54837
+ const headerDef = sectionData?.headers?.[headerId];
54566
54838
  const minHeaderHeight = pageMargins.top * 96;
54567
54839
  const headerMargin = pageMargins.header * 96;
54568
54840
  const hasHeaderOffset = headerDef?.height > minHeaderHeight - headerMargin;
54569
54841
  const headerOffset = hasHeaderOffset ? headerMargin : 0;
54570
54842
  const headerHeight = Math.max(headerDef?.height || 0, minHeaderHeight) + headerOffset;
54571
54843
  const availableHeight = headerHeight - headerMargin;
54572
- const editorContainer = document.createElement("div");
54844
+ let editorContainer = document.createElement("div");
54573
54845
  if (!headerId && !editor?.converter?.headerIds?.["default"]) {
54574
54846
  headerId = "rId" + generateDocxRandomId();
54575
54847
  editor.converter.headerIds["default"] = headerId;
@@ -54581,23 +54853,31 @@ function createHeader(pageMargins, pageSize, sectionData, headerId, editor, curr
54581
54853
  };
54582
54854
  }
54583
54855
  const data = editor.converter.headers[headerId];
54584
- const editorSection = createHeaderFooterEditor({
54585
- editor,
54586
- data,
54587
- editorContainer,
54588
- appendToBody: false,
54589
- sectionId: headerId,
54590
- type: "header",
54591
- availableHeight,
54592
- currentPageNumber
54593
- });
54594
- editor.converter.headerEditors.push({
54595
- id: headerId,
54596
- editor: editorSection
54597
- });
54856
+ const pageNumberIndex = currentPageNumber - 1;
54857
+ const editorKey = getHeaderFooterEditorKey({ pageNumber: pageNumberIndex, isHeader: true, isFirstHeader });
54858
+ let editorSection = null;
54859
+ const { headerFooterEditors } = editor.storage.pagination;
54860
+ if (headerFooterEditors.has(editorKey) && editor.converter.headerEditors[pageNumberIndex]) {
54861
+ const editorData = headerFooterEditors.get(editorKey);
54862
+ editorSection = editorData.editor;
54863
+ editorContainer = editorSection.element;
54864
+ } else {
54865
+ editorSection = createHeaderFooterEditor({
54866
+ editor,
54867
+ data,
54868
+ editorContainer,
54869
+ appendToBody: false,
54870
+ sectionId: headerId,
54871
+ type: "header",
54872
+ availableHeight,
54873
+ currentPageNumber
54874
+ });
54875
+ editor.converter.headerEditors.push({ id: headerId, editor: editorSection });
54876
+ headerFooterEditors.set(editorKey, { editor: editorSection });
54877
+ broadcastEditorEvents(editor, editorSection);
54878
+ }
54598
54879
  editorSection.setEditable(false, false);
54599
- broadcastEditorEvents(editor, editorSection);
54600
- editorContainer.className = "pagination-section-header";
54880
+ editorContainer.classList.add("pagination-section-header");
54601
54881
  editorContainer.style.paddingTop = headerMargin + "px";
54602
54882
  editorContainer.style.paddingLeft = pageMargins.left * 96 + "px";
54603
54883
  editorContainer.style.paddingRight = pageMargins.right * 96 + "px";
@@ -54610,12 +54890,12 @@ function createHeader(pageMargins, pageSize, sectionData, headerId, editor, curr
54610
54890
  headerHeight
54611
54891
  };
54612
54892
  }
54613
- function createFooter(pageMargins, pageSize, sectionData, footerId, editor, currentPageNumber) {
54614
- const footerDef = sectionData.footers?.[footerId];
54893
+ function createFooter(pageMargins, pageSize, sectionData, footerId, editor, currentPageNumber, isLastFooter = false) {
54894
+ const footerDef = sectionData?.footers?.[footerId];
54615
54895
  const minFooterHeight = pageMargins.bottom * 96;
54616
54896
  const footerPaddingFromEdge = pageMargins.footer * 96;
54617
54897
  const footerHeight = Math.max(footerDef?.height || 0, minFooterHeight - footerPaddingFromEdge);
54618
- const editorContainer = document.createElement("div");
54898
+ let editorContainer = document.createElement("div");
54619
54899
  if (!footerId && !editor.converter.footerIds["default"]) {
54620
54900
  footerId = "rId" + generateDocxRandomId();
54621
54901
  editor.converter.footerIds["default"] = footerId;
@@ -54627,23 +54907,31 @@ function createFooter(pageMargins, pageSize, sectionData, footerId, editor, curr
54627
54907
  };
54628
54908
  }
54629
54909
  const data = editor.converter.footers[footerId];
54630
- const editorSection = createHeaderFooterEditor({
54631
- editor,
54632
- data,
54633
- editorContainer,
54634
- appendToBody: false,
54635
- sectionId: footerId,
54636
- type: "footer",
54637
- availableHeight: footerHeight,
54638
- currentPageNumber
54639
- });
54640
- editor.converter.footerEditors.push({
54641
- id: footerId,
54642
- editor: editorSection
54643
- });
54910
+ const pageNumberIndex = currentPageNumber - 1;
54911
+ const editorKey = getHeaderFooterEditorKey({ pageNumber: pageNumberIndex, isFooter: true, isLastFooter });
54912
+ let editorSection = null;
54913
+ const { headerFooterEditors } = editor.storage.pagination;
54914
+ if (headerFooterEditors.has(editorKey) && editor.converter.footerEditors[pageNumberIndex]) {
54915
+ const editorData = headerFooterEditors.get(editorKey);
54916
+ editorSection = editorData.editor;
54917
+ editorContainer = editorSection.element;
54918
+ } else {
54919
+ editorSection = createHeaderFooterEditor({
54920
+ editor,
54921
+ data,
54922
+ editorContainer,
54923
+ appendToBody: false,
54924
+ sectionId: footerId,
54925
+ type: "footer",
54926
+ availableHeight: footerHeight,
54927
+ currentPageNumber
54928
+ });
54929
+ editor.converter.footerEditors.push({ id: footerId, editor: editorSection });
54930
+ headerFooterEditors.set(editorKey, { editor: editorSection });
54931
+ broadcastEditorEvents(editor, editorSection);
54932
+ }
54644
54933
  editorSection.setEditable(false, false);
54645
- broadcastEditorEvents(editor, editorSection);
54646
- editorContainer.className = "pagination-section-footer";
54934
+ editorContainer.classList.add("pagination-section-footer");
54647
54935
  editorContainer.style.height = footerHeight + "px";
54648
54936
  editorContainer.style.marginBottom = footerPaddingFromEdge + "px";
54649
54937
  editorContainer.style.paddingLeft = pageMargins.left * 96 + "px";
@@ -54656,10 +54944,28 @@ function createFooter(pageMargins, pageSize, sectionData, footerId, editor, curr
54656
54944
  footerHeight: footerHeight + footerPaddingFromEdge
54657
54945
  };
54658
54946
  }
54947
+ const getHeaderFooterEditorKey = ({
54948
+ pageNumber,
54949
+ isHeader,
54950
+ isFooter,
54951
+ isFirstHeader = false,
54952
+ isLastFooter = false
54953
+ }) => {
54954
+ if (isFirstHeader) return `first-header-${pageNumber}`;
54955
+ if (isLastFooter) return `last-footer-${pageNumber}`;
54956
+ if (isHeader) return `header-${pageNumber}`;
54957
+ if (isFooter) return `footer-${pageNumber}`;
54958
+ return void 0;
54959
+ };
54659
54960
  const onHeaderFooterDblClick = (editor, currentFocusedSectionEditor) => {
54660
54961
  if (editor.options.documentMode !== "editing") return;
54661
54962
  editor.setEditable(false, false);
54662
- toggleHeaderFooterEditMode(editor, currentFocusedSectionEditor, true);
54963
+ toggleHeaderFooterEditMode({
54964
+ editor,
54965
+ focusedSectionEditor: currentFocusedSectionEditor,
54966
+ isEditMode: true,
54967
+ documentMode: editor.options.documentMode
54968
+ });
54663
54969
  };
54664
54970
  function createPageBreak({ editor, header, footer, footerBottom = null, isFirstHeader, isLastFooter, isInTable: isInTable2 = false }) {
54665
54971
  const { pageSize, pageMargins } = editor.converter.pageStyles;
@@ -55214,7 +55520,7 @@ const Search = Extension.create({
55214
55520
  }
55215
55521
  });
55216
55522
  const NodeResizerKey = new PluginKey("node-resizer");
55217
- const nodeResizer = (nodeNames = ["image"]) => {
55523
+ const nodeResizer = (nodeNames = ["image"], editor) => {
55218
55524
  let resizeState = {
55219
55525
  dragging: false,
55220
55526
  startX: 0,
@@ -55239,8 +55545,13 @@ const nodeResizer = (nodeNames = ["image"]) => {
55239
55545
  if (tr.getMeta(NodeResizerKey)) {
55240
55546
  return oldState;
55241
55547
  }
55242
- const decorations = [];
55548
+ if (typeof document === "undefined" || editor.options.isHeadless) return oldState;
55243
55549
  const { selection } = newState;
55550
+ const node2 = selection.node;
55551
+ if (!node2 || !nodeNames.includes(node2.type.name)) {
55552
+ return DecorationSet.empty;
55553
+ }
55554
+ const decorations = [];
55244
55555
  if (nodeNames.includes(selection.node?.type.name)) {
55245
55556
  decorations.push(
55246
55557
  Decoration.node(selection.from, selection.to, {
@@ -55443,7 +55754,7 @@ const nodeResizer = (nodeNames = ["image"]) => {
55443
55754
  const NodeResizer = Extension.create({
55444
55755
  name: "nodeResizer",
55445
55756
  addPmPlugins() {
55446
- return [nodeResizer(["image"])];
55757
+ return [nodeResizer(["image"], this.editor)];
55447
55758
  }
55448
55759
  });
55449
55760
  const getRichTextExtensions = () => {
@@ -64119,7 +64430,6 @@ const style$2 = cB("icon", `
64119
64430
  display: inline-block;
64120
64431
  position: relative;
64121
64432
  fill: currentColor;
64122
- transform: translateZ(0);
64123
64433
  `, [cM("color-transition", {
64124
64434
  transition: "color .3s var(--n-bezier)"
64125
64435
  }), cM("depth", {