@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
@@ -9,12 +9,12 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
9
9
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
10
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
11
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
12
- 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;
12
+ 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;
13
13
  import * as Y from "yjs";
14
14
  import { UndoManager, Item as Item$1, ContentType, Text as Text$1, XmlElement, encodeStateAsUpdate } from "yjs";
15
- import { P as PluginKey, a as Plugin, M as Mapping, c as callOrGet, i as isEmptyObject, S as Schema$1, T as TextSelection, b as canSplit, l as liftTarget, A as AllSelection, d as canJoin, j as joinPoint, N as NodeSelection, r as replaceStep$1, e as Selection, F as Fragment, R as ReplaceAroundStep, f as Slice, o as objectIncludes, g as deleteProps, D as DOMParser$1, h as ReplaceStep, k as NodeRange, m as findWrapping, n as isMacOS, p as isIOS, q as generateDocxRandomId, s as minMax, t as generateRandom32BitHex, u as DOMSerializer, v as Mark$1, w as dropPoint, x as process$1, B as Buffer2, y as isRegExp, z as TrackDeleteMarkName, C as TrackInsertMarkName, E as v4, G as TrackFormatMarkName, H as comments_module_events, I as AddMarkStep, J as RemoveMarkStep, K as twipsToLines, L as pixelsToTwips, O as SuperConverter, Q as EditorState, U as hasSomeParentWithClass, V as parseSizeUnit, W as getLineHeightValueString, X as toKebabCase, Y as kebabCase, Z as getColStyleDeclaration, _ as SelectionRange, $ as Transform, a0 as createColGroup } from "./converter-CJ9kHtZx.js";
15
+ import { P as PluginKey, a as Plugin, M as Mapping, c as callOrGet, i as isEmptyObject, S as Schema$1, T as TextSelection, b as canSplit, l as liftTarget, A as AllSelection, d as canJoin, j as joinPoint, N as NodeSelection, r as replaceStep$1, e as Selection, F as Fragment, R as ReplaceAroundStep$1, f as Slice, o as objectIncludes, g as deleteProps, D as DOMParser$1, h as ReplaceStep, k as NodeRange, m as findWrapping, n as isMacOS, p as isIOS, q as generateDocxRandomId, s as minMax, t as chainableEditorState, u as generateRandom32BitHex, v as DOMSerializer, w as Mark$1, x as dropPoint, y as process$1, B as Buffer2, z as inputRulesPlugin, C as TrackDeleteMarkName, E as TrackInsertMarkName, G as v4, H as TrackFormatMarkName, I as comments_module_events, J as AddMarkStep, K as RemoveMarkStep, L as twipsToLines, O as pixelsToTwips, Q as CommandService, U as SuperConverter, V as EditorState, W as hasSomeParentWithClass, X as parseSizeUnit, Y as getLineHeightValueString, Z as InputRule, _ as toKebabCase, $ as kebabCase, a0 as getColStyleDeclaration, a1 as SelectionRange, a2 as Transform, a3 as createColGroup } from "./converter-g7XDS8H8.js";
16
16
  import { ref, computed, createElementBlock, openBlock, withModifiers, Fragment as Fragment$1, renderList, normalizeClass, createCommentVNode, toDisplayString, createElementVNode, createApp } from "vue";
17
- import { D as DocxZipper } from "./docx-zipper-scQqOWXA.js";
17
+ import { D as DocxZipper } from "./docx-zipper-VpCXV0uV.js";
18
18
  function getMarksFromSelection(state) {
19
19
  const { from: from2, to, empty: empty2 } = state.selection;
20
20
  const marks = [];
@@ -1203,164 +1203,6 @@ createMarksSchema_fn = function(markExtensions, attributes, editor) {
1203
1203
  };
1204
1204
  __privateAdd(_Schema, _Schema_static);
1205
1205
  let Schema = _Schema;
1206
- function chainableEditorState(transaction, state) {
1207
- let { selection, doc: doc2, storedMarks } = transaction;
1208
- return {
1209
- ...state,
1210
- apply: state.apply.bind(state),
1211
- applyTransaction: state.applyTransaction.bind(state),
1212
- plugins: state.plugins,
1213
- schema: state.schema,
1214
- reconfigure: state.reconfigure.bind(state),
1215
- toJSON: state.toJSON.bind(state),
1216
- get storedMarks() {
1217
- return storedMarks;
1218
- },
1219
- get selection() {
1220
- return selection;
1221
- },
1222
- get doc() {
1223
- return doc2;
1224
- },
1225
- get tr() {
1226
- selection = transaction.selection;
1227
- doc2 = transaction.doc;
1228
- storedMarks = transaction.storedMarks;
1229
- return transaction;
1230
- }
1231
- };
1232
- }
1233
- class CommandService {
1234
- constructor(props) {
1235
- __publicField(this, "editor");
1236
- __publicField(this, "rawCommands");
1237
- this.editor = props.editor;
1238
- this.rawCommands = this.editor.extensionService.commands;
1239
- }
1240
- /**
1241
- * Static method for creating a service.
1242
- * @param args Arguments for the constructor.
1243
- */
1244
- static create(...args) {
1245
- return new CommandService(...args);
1246
- }
1247
- /**
1248
- * Get editor state.
1249
- */
1250
- get state() {
1251
- return this.editor.state;
1252
- }
1253
- /**
1254
- * Get all commands with wrapped command method.
1255
- */
1256
- get commands() {
1257
- const { editor, state } = this;
1258
- const { view } = editor;
1259
- const { tr } = state;
1260
- const props = this.createProps(tr);
1261
- const entries = Object.entries(this.rawCommands).map(([name, command2]) => {
1262
- const method = (...args) => {
1263
- const fn2 = command2(...args)(props);
1264
- if (!tr.getMeta("preventDispatch")) {
1265
- view.dispatch(tr);
1266
- }
1267
- return fn2;
1268
- };
1269
- return [name, method];
1270
- });
1271
- return Object.fromEntries(entries);
1272
- }
1273
- /**
1274
- * Create a chain of commands to call multiple commands at once.
1275
- */
1276
- get chain() {
1277
- return () => this.createChain();
1278
- }
1279
- /**
1280
- * Check if a command or a chain of commands can be executed. Without executing it.
1281
- */
1282
- get can() {
1283
- return () => this.createCan();
1284
- }
1285
- /**
1286
- * Creates a chain of commands.
1287
- * @param startTr Start transaction.
1288
- * @param shouldDispatch Should dispatch or not.
1289
- */
1290
- createChain(startTr, shouldDispatch = true) {
1291
- const { editor, state, rawCommands } = this;
1292
- const { view } = editor;
1293
- const callbacks = [];
1294
- const hasStartTr = !!startTr;
1295
- const tr = startTr || state.tr;
1296
- const run2 = () => {
1297
- if (!hasStartTr && shouldDispatch && !tr.getMeta("preventDispatch")) {
1298
- view.dispatch(tr);
1299
- }
1300
- return callbacks.every((cb) => cb === true);
1301
- };
1302
- const entries = Object.entries(rawCommands).map(([name, command2]) => {
1303
- const chainedCommand = (...args) => {
1304
- const props = this.createProps(tr, shouldDispatch);
1305
- const callback = command2(...args)(props);
1306
- callbacks.push(callback);
1307
- return chain;
1308
- };
1309
- return [name, chainedCommand];
1310
- });
1311
- const chain = {
1312
- ...Object.fromEntries(entries),
1313
- run: run2
1314
- };
1315
- return chain;
1316
- }
1317
- /**
1318
- * Creates a can check for commands.
1319
- * @param startTr Start transaction.
1320
- */
1321
- createCan(startTr) {
1322
- const { rawCommands, state } = this;
1323
- const dispatch = false;
1324
- const tr = startTr || state.tr;
1325
- const props = this.createProps(tr, dispatch);
1326
- const commands2 = Object.fromEntries(
1327
- Object.entries(rawCommands).map(([name, command2]) => {
1328
- return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
1329
- })
1330
- );
1331
- return {
1332
- ...commands2,
1333
- chain: () => this.createChain(tr, dispatch)
1334
- };
1335
- }
1336
- /**
1337
- * Creates default props for the command method.
1338
- * @param {*} tr Transaction.
1339
- * @param {*} shouldDispatch Check if should dispatch.
1340
- * @returns Object with props.
1341
- */
1342
- createProps(tr, shouldDispatch = true) {
1343
- const { editor, state, rawCommands } = this;
1344
- const { view } = editor;
1345
- const props = {
1346
- tr,
1347
- editor,
1348
- view,
1349
- state: chainableEditorState(tr, state),
1350
- dispatch: shouldDispatch ? () => void 0 : void 0,
1351
- chain: () => this.createChain(tr, shouldDispatch),
1352
- can: () => this.createCan(tr),
1353
- get commands() {
1354
- return Object.fromEntries(
1355
- Object.entries(rawCommands).map(([name, command2]) => {
1356
- return [name, (...args) => command2(...args)(props)];
1357
- })
1358
- );
1359
- }
1360
- };
1361
- return props;
1362
- }
1363
- }
1364
1206
  const first = (commands2) => (props) => {
1365
1207
  const items = typeof commands2 === "function" ? commands2(props) : commands2;
1366
1208
  for (let i = 0; i < items.length; i += 1) {
@@ -1722,7 +1564,7 @@ function deleteBarrier(state, $cut, dispatch, dir) {
1722
1564
  for (let i = conn.length - 1; i >= 0; i--)
1723
1565
  wrap = Fragment.from(conn[i].create(null, wrap));
1724
1566
  wrap = Fragment.from(before.copy(wrap));
1725
- let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end2, $cut.pos, end2, new Slice(wrap, 1, 0), conn.length, true));
1567
+ let tr = state.tr.step(new ReplaceAroundStep$1($cut.pos - 1, end2, $cut.pos, end2, new Slice(wrap, 1, 0), conn.length, true));
1726
1568
  let $joinAt = tr.doc.resolve(end2 + 2 * conn.length);
1727
1569
  if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr.doc, $joinAt.pos))
1728
1570
  tr.join($joinAt.pos);
@@ -1753,7 +1595,7 @@ function deleteBarrier(state, $cut, dispatch, dir) {
1753
1595
  let end2 = Fragment.empty;
1754
1596
  for (let i = wrap.length - 1; i >= 0; i--)
1755
1597
  end2 = Fragment.from(wrap[i].copy(end2));
1756
- let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end2, wrap.length, 0), 0, true));
1598
+ let tr = state.tr.step(new ReplaceAroundStep$1($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end2, wrap.length, 0), 0, true));
1757
1599
  dispatch(tr.scrollIntoView());
1758
1600
  }
1759
1601
  return true;
@@ -2326,7 +2168,7 @@ function selectionToInsertionEnd(tr, startLen, bias) {
2326
2168
  return;
2327
2169
  }
2328
2170
  const step = tr.steps[last];
2329
- if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
2171
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep$1)) {
2330
2172
  return;
2331
2173
  }
2332
2174
  const map2 = tr.mapping.maps[last];
@@ -2472,7 +2314,7 @@ function doWrapInList(tr, range, wrappers, joinBefore, listType) {
2472
2314
  let content = Fragment.empty;
2473
2315
  for (let i = wrappers.length - 1; i >= 0; i--)
2474
2316
  content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
2475
- tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));
2317
+ tr.step(new ReplaceAroundStep$1(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));
2476
2318
  let found = 0;
2477
2319
  for (let i = 0; i < wrappers.length; i++)
2478
2320
  if (wrappers[i].type == listType)
@@ -2505,7 +2347,7 @@ function liftListItem$1(itemType) {
2505
2347
  function liftToOuterList(state, dispatch, itemType, range) {
2506
2348
  let tr = state.tr, end2 = range.end, endOfList = range.$to.end(range.depth);
2507
2349
  if (end2 < endOfList) {
2508
- tr.step(new ReplaceAroundStep(end2 - 1, endOfList, end2, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
2350
+ tr.step(new ReplaceAroundStep$1(end2 - 1, endOfList, end2, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
2509
2351
  range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);
2510
2352
  }
2511
2353
  const target = liftTarget(range);
@@ -2532,7 +2374,7 @@ function liftOutOfList(state, dispatch, range) {
2532
2374
  if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))
2533
2375
  return false;
2534
2376
  let start2 = $start.pos, end2 = start2 + item.nodeSize;
2535
- 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));
2377
+ 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));
2536
2378
  dispatch(tr.scrollIntoView());
2537
2379
  return true;
2538
2380
  }
@@ -2553,7 +2395,7 @@ function sinkListItem$1(itemType) {
2553
2395
  let inner = Fragment.from(nestedBefore ? itemType.create() : null);
2554
2396
  let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
2555
2397
  let before = range.start, after = range.end;
2556
- dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
2398
+ dispatch(state.tr.step(new ReplaceAroundStep$1(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
2557
2399
  }
2558
2400
  return true;
2559
2401
  };
@@ -10146,7 +9988,8 @@ const restoreRelativeSelection = (tr, relSel, binding) => {
10146
9988
  binding.mapping
10147
9989
  );
10148
9990
  if (anchor !== null && head !== null) {
10149
- tr.setSelection(TextSelection.between(tr.doc.resolve(anchor), tr.doc.resolve(head)));
9991
+ const sel = TextSelection.between(tr.doc.resolve(anchor), tr.doc.resolve(head));
9992
+ tr.setSelection(sel);
10150
9993
  }
10151
9994
  }
10152
9995
  }
@@ -10927,7 +10770,7 @@ const setMeta = (view, key, value) => {
10927
10770
  };
10928
10771
  const absolutePositionToRelativePosition = (pos, type, mapping) => {
10929
10772
  if (pos === 0) {
10930
- return Y.createRelativePositionFromTypeIndex(type, 0, -1);
10773
+ return Y.createRelativePositionFromTypeIndex(type, 0, type.length === 0 ? -1 : 0);
10931
10774
  }
10932
10775
  let n = type._first === null ? null : (
10933
10776
  /** @type {Y.ContentType} */
@@ -10936,7 +10779,7 @@ const absolutePositionToRelativePosition = (pos, type, mapping) => {
10936
10779
  while (n !== null && type !== n) {
10937
10780
  if (n instanceof Y.XmlText) {
10938
10781
  if (n._length >= pos) {
10939
- return Y.createRelativePositionFromTypeIndex(n, pos, -1);
10782
+ return Y.createRelativePositionFromTypeIndex(n, pos, type.length === 0 ? -1 : 0);
10940
10783
  } else {
10941
10784
  pos -= n._length;
10942
10785
  }
@@ -11000,7 +10843,7 @@ const absolutePositionToRelativePosition = (pos, type, mapping) => {
11000
10843
  return createRelativePosition(n._item.parent, n._item);
11001
10844
  }
11002
10845
  }
11003
- return Y.createRelativePositionFromTypeIndex(type, type._length, -1);
10846
+ return Y.createRelativePositionFromTypeIndex(type, type._length, type.length === 0 ? -1 : 0);
11004
10847
  };
11005
10848
  const createRelativePosition = (type, item) => {
11006
10849
  let typeid = null;
@@ -11597,409 +11440,6 @@ function isExtensionRulesEnabled(extension, enabled) {
11597
11440
  }
11598
11441
  return enabled;
11599
11442
  }
11600
- function getHTMLFromFragment(fragment, schema) {
11601
- const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment);
11602
- const temporaryDocument = document.implementation.createHTMLDocument();
11603
- const container = temporaryDocument.createElement("div");
11604
- container.appendChild(documentFragment);
11605
- return container.innerHTML;
11606
- }
11607
- const getTextContentFromNodes = ($from, maxMatch = 500) => {
11608
- let textBefore = "";
11609
- const sliceEndPos = $from.parentOffset;
11610
- $from.parent.nodesBetween(
11611
- Math.max(0, sliceEndPos - maxMatch),
11612
- sliceEndPos,
11613
- (node, pos, parent, index2) => {
11614
- const chunk = node.type.spec.toText?.({
11615
- node,
11616
- pos,
11617
- parent,
11618
- index: index2
11619
- }) || node.textContent || "%leaf%";
11620
- textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));
11621
- }
11622
- );
11623
- return textBefore;
11624
- };
11625
- const handleDocxPaste = (html, editor, view, plugin) => {
11626
- const { converter } = editor;
11627
- if (!converter || !converter.convertedXml) return handleHtmlPaste(html, editor, view, plugin);
11628
- let cleanedHtml = convertEmToPt(html);
11629
- cleanedHtml = cleanHtmlUnnecessaryTags(cleanedHtml);
11630
- const tempDiv = document.createElement("div");
11631
- tempDiv.innerHTML = cleanedHtml;
11632
- const paragraphs = tempDiv.querySelectorAll("p");
11633
- paragraphs.forEach((p) => {
11634
- const innerHTML3 = p.innerHTML;
11635
- if (!innerHTML3.includes("<!--[if !supportLists]")) return;
11636
- const styleAttr = p.getAttribute("style") || "";
11637
- const msoListMatch = styleAttr.match(/mso-list:\s*l(\d+)\s+level(\d+)/);
11638
- if (msoListMatch) {
11639
- const [, abstractId, level] = msoListMatch;
11640
- const listNumId = getListNumIdFromAbstract(abstractId, editor);
11641
- if (!listNumId) return;
11642
- const abstractDefinition = getListAbstractDefinition(abstractId, editor);
11643
- const { lvlText, start: start2, numFmt } = getLevelDefinition(abstractDefinition, level - 1);
11644
- p.setAttribute("data-num-id", listNumId);
11645
- p.setAttribute("data-list-level", level - 1);
11646
- p.setAttribute("data-start", start2);
11647
- p.setAttribute("data-lvl-text", lvlText);
11648
- p.setAttribute("data-num-fmt", numFmt);
11649
- }
11650
- extractAndRemoveConditionalPrefix(p);
11651
- });
11652
- transformWordLists(tempDiv);
11653
- const doc2 = DOMParser$1.fromSchema(editor.schema).parse(tempDiv);
11654
- tempDiv.remove();
11655
- const { dispatch } = editor.view;
11656
- if (!dispatch) return false;
11657
- dispatch(view.state.tr.replaceSelectionWith(doc2, true));
11658
- return true;
11659
- };
11660
- const getLevelDefinition = (abstractDefinition, level) => {
11661
- if (!abstractDefinition || !abstractDefinition.elements) return null;
11662
- const levelElement = abstractDefinition.elements.find((el) => {
11663
- return el.name === "w:lvl" && el.attributes?.["w:ilvl"] == level;
11664
- });
11665
- if (!levelElement) return null;
11666
- const { elements } = levelElement;
11667
- const lvlText = elements.find((el) => el.name === "w:lvlText")?.attributes?.["w:val"];
11668
- const start2 = elements.find((el) => el.name === "w:start")?.attributes?.["w:val"];
11669
- const numFmt = elements.find((el) => el.name === "w:numFmt")?.attributes?.["w:val"];
11670
- return { lvlText, start: start2, numFmt, elements };
11671
- };
11672
- const getListNumIdFromAbstract = (abstractId, editor) => {
11673
- const { definitions } = editor?.converter?.numbering;
11674
- if (!definitions) return null;
11675
- const matchedDefinition = Object.values(definitions).find((def) => {
11676
- return def.elements.some((el) => el.name === "w:abstractNumId" && el.attributes?.["w:val"] == abstractId);
11677
- });
11678
- return matchedDefinition?.attributes?.["w:numId"];
11679
- };
11680
- const getListAbstractDefinition = (abstractId, editor) => {
11681
- const { abstracts = {} } = editor?.converter?.numbering;
11682
- return abstracts[abstractId] || null;
11683
- };
11684
- const transformWordLists = (container) => {
11685
- const paragraphs = Array.from(container.querySelectorAll("p[data-num-id]"));
11686
- const listMap = /* @__PURE__ */ new Map();
11687
- const listLevels = {};
11688
- for (const p of paragraphs) {
11689
- const listId = p.getAttribute("data-num-id");
11690
- const level = parseInt(p.getAttribute("data-list-level"));
11691
- const numFmt = p.getAttribute("data-num-fmt");
11692
- const start2 = p.getAttribute("data-start");
11693
- const lvlText = p.getAttribute("data-lvl-text");
11694
- if (!listMap.has(listId)) listMap.set(listId, []);
11695
- listMap.get(listId).push({ p, level, numFmt, start: start2, lvlText });
11696
- }
11697
- for (const [id, items] of listMap.entries()) {
11698
- if (!listLevels[id]) {
11699
- listLevels[id] = {
11700
- stack: [],
11701
- counts: {},
11702
- prevLevel: null
11703
- };
11704
- }
11705
- const parentStack = [];
11706
- items.forEach(({ p, level, numFmt, start: start2, lvlText }, index2) => {
11707
- const listLevel = generateListNestingPath(listLevels, id, level);
11708
- const li = document.createElement("li");
11709
- li.innerHTML = p.innerHTML;
11710
- li.setAttribute("data-list-level", JSON.stringify(listLevel));
11711
- li.setAttribute("data-num-id", id);
11712
- li.setAttribute("data-lvl-text", lvlText);
11713
- li.setAttribute("data-num-fmt", numFmt);
11714
- if (p.hasAttribute("data-font-family")) {
11715
- li.setAttribute("data-font-family", p.getAttribute("data-font-family"));
11716
- }
11717
- if (p.hasAttribute("data-font-size")) {
11718
- li.setAttribute("data-font-size", p.getAttribute("data-font-size"));
11719
- }
11720
- const parentNode2 = p.parentNode;
11721
- let listForLevel = parentStack[level];
11722
- if (!listForLevel) {
11723
- const newList = document.createElement("ol");
11724
- newList.setAttribute("data-list-id", id);
11725
- newList.level = level;
11726
- if (level > 0) {
11727
- const parentLi = parentStack[level - 1]?.querySelector("li:last-child");
11728
- if (parentLi) parentLi.appendChild(newList);
11729
- } else {
11730
- parentNode2.insertBefore(newList, p);
11731
- }
11732
- parentStack[level] = newList;
11733
- parentStack.length = level + 1;
11734
- listForLevel = newList;
11735
- }
11736
- listForLevel.appendChild(li);
11737
- p.remove();
11738
- });
11739
- }
11740
- };
11741
- function generateListNestingPath(listLevels, listId, currentLevel) {
11742
- const levelState = listLevels[listId];
11743
- if (!levelState.stack) levelState.stack = [];
11744
- if (levelState.prevLevel === void 0) levelState.prevLevel = null;
11745
- if (levelState.prevLevel === null) {
11746
- levelState.stack = Array(currentLevel).fill(1).concat(1);
11747
- } else {
11748
- if (currentLevel > levelState.prevLevel) {
11749
- levelState.stack.push(1);
11750
- } else if (currentLevel === levelState.prevLevel) {
11751
- levelState.stack[levelState.stack.length - 1]++;
11752
- } else {
11753
- levelState.stack = levelState.stack.slice(0, currentLevel + 1);
11754
- levelState.stack[currentLevel] = (levelState.stack[currentLevel] || 1) + 1;
11755
- }
11756
- }
11757
- levelState.prevLevel = currentLevel;
11758
- return [...levelState.stack];
11759
- }
11760
- function extractAndRemoveConditionalPrefix(p) {
11761
- const nodes = Array.from(p.childNodes);
11762
- let fontFamily = null;
11763
- let fontSize = null;
11764
- let start2 = -1, end2 = -1;
11765
- nodes.forEach((node, index2) => {
11766
- if (node.nodeType === Node.COMMENT_NODE && node.nodeValue.includes("[if !supportLists]")) {
11767
- start2 = index2;
11768
- }
11769
- if (start2 !== -1 && node.nodeType === Node.COMMENT_NODE && node.nodeValue.includes("[endif]")) {
11770
- end2 = index2;
11771
- }
11772
- });
11773
- if (start2 !== -1 && end2 !== -1) {
11774
- for (let i = start2 + 1; i < end2; i++) {
11775
- const node = nodes[i];
11776
- if (node.nodeType === Node.ELEMENT_NODE && node.style) {
11777
- fontFamily = fontFamily || node.style.fontFamily;
11778
- fontSize = fontSize || node.style.fontSize;
11779
- }
11780
- }
11781
- for (let i = end2; i >= start2; i--) {
11782
- p.removeChild(p.childNodes[i]);
11783
- }
11784
- if (fontFamily) p.setAttribute("data-font-family", fontFamily);
11785
- if (fontSize) p.setAttribute("data-font-size", fontSize);
11786
- }
11787
- }
11788
- class InputRule {
11789
- constructor(config) {
11790
- __publicField(this, "match");
11791
- __publicField(this, "handler");
11792
- this.match = config.match;
11793
- this.handler = config.handler;
11794
- }
11795
- }
11796
- const inputRuleMatcherHandler = (text, match) => {
11797
- if (isRegExp(match)) {
11798
- return match.exec(text);
11799
- }
11800
- const inputRuleMatch = match(text);
11801
- if (!inputRuleMatch) {
11802
- return null;
11803
- }
11804
- const result = [inputRuleMatch.text];
11805
- result.index = inputRuleMatch.index;
11806
- result.input = text;
11807
- result.data = inputRuleMatch.data;
11808
- if (inputRuleMatch.replaceWith) {
11809
- if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
11810
- console.warn(
11811
- '[super-editor warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'
11812
- );
11813
- }
11814
- result.push(inputRuleMatch.replaceWith);
11815
- }
11816
- return result;
11817
- };
11818
- const run = (config) => {
11819
- const {
11820
- editor,
11821
- from: from2,
11822
- to,
11823
- text,
11824
- rules,
11825
- plugin
11826
- } = config;
11827
- const { view } = editor;
11828
- if (view.composing) {
11829
- return false;
11830
- }
11831
- const $from = view.state.doc.resolve(from2);
11832
- if ($from.parent.type.spec.code || !!($from.nodeBefore || $from.nodeAfter)?.marks.find((mark) => mark.type.spec.code)) {
11833
- return false;
11834
- }
11835
- let matched = false;
11836
- const textBefore = getTextContentFromNodes($from) + text;
11837
- rules.forEach((rule) => {
11838
- if (matched) {
11839
- return;
11840
- }
11841
- const match = inputRuleMatcherHandler(textBefore, rule.match);
11842
- if (!match) {
11843
- return;
11844
- }
11845
- const tr = view.state.tr;
11846
- const state = chainableEditorState(tr, view.state);
11847
- const range = {
11848
- from: from2 - (match[0].length - text.length),
11849
- to
11850
- };
11851
- const { commands: commands2, chain, can } = new CommandService({
11852
- editor,
11853
- state
11854
- });
11855
- const handler = rule.handler({
11856
- state,
11857
- range,
11858
- match,
11859
- commands: commands2,
11860
- chain,
11861
- can
11862
- });
11863
- if (handler === null || !tr.steps.length) {
11864
- return;
11865
- }
11866
- tr.setMeta(plugin, {
11867
- transform: tr,
11868
- from: from2,
11869
- to,
11870
- text
11871
- });
11872
- view.dispatch(tr);
11873
- matched = true;
11874
- });
11875
- return matched;
11876
- };
11877
- const inputRulesPlugin = ({ editor, rules }) => {
11878
- const plugin = new Plugin({
11879
- key: new PluginKey("inputRulesPlugin"),
11880
- state: {
11881
- init() {
11882
- return null;
11883
- },
11884
- apply(tr, prev, state) {
11885
- const stored = tr.getMeta(plugin);
11886
- if (stored) {
11887
- return stored;
11888
- }
11889
- const simulatedInputMeta = tr.getMeta("applyInputRules");
11890
- const isSimulatedInput = !!simulatedInputMeta;
11891
- if (isSimulatedInput) {
11892
- setTimeout(() => {
11893
- let { text } = simulatedInputMeta;
11894
- if (typeof text !== "string") {
11895
- text = getHTMLFromFragment(Fragment.from(text), state.schema);
11896
- }
11897
- const { from: from2 } = simulatedInputMeta;
11898
- const to = from2 + text.length;
11899
- run({
11900
- editor,
11901
- from: from2,
11902
- to,
11903
- text,
11904
- rules,
11905
- plugin
11906
- });
11907
- });
11908
- }
11909
- return tr.selectionSet || tr.docChanged ? null : prev;
11910
- }
11911
- },
11912
- props: {
11913
- handleTextInput(view, from2, to, text) {
11914
- return run({
11915
- editor,
11916
- from: from2,
11917
- to,
11918
- text,
11919
- rules,
11920
- plugin
11921
- });
11922
- },
11923
- // add support for input rules to trigger on enter
11924
- // this is useful for example for code blocks
11925
- handleKeyDown(view, event) {
11926
- if (event.key !== "Enter") {
11927
- return false;
11928
- }
11929
- const { $cursor } = view.state.selection;
11930
- if ($cursor) {
11931
- return run({
11932
- editor,
11933
- from: $cursor.pos,
11934
- to: $cursor.pos,
11935
- text: "\n",
11936
- rules,
11937
- plugin
11938
- });
11939
- }
11940
- return false;
11941
- },
11942
- // Paste handler
11943
- handlePaste(view, event, slice2) {
11944
- const clipboard = event.clipboardData;
11945
- const html = clipboard.getData("text/html");
11946
- clipboard.getData("text/plain");
11947
- const fieldAnnotationContent = slice2.content.content.filter((item) => item.type.name === "fieldAnnotation");
11948
- if (fieldAnnotationContent.length) {
11949
- return false;
11950
- }
11951
- let source;
11952
- if (!html) {
11953
- source = "plain-text";
11954
- } else if (isWordHtml(html)) {
11955
- source = "word-html";
11956
- } else {
11957
- source = "browser-html";
11958
- }
11959
- switch (source) {
11960
- case "plain-text":
11961
- break;
11962
- case "word-html":
11963
- if (editor.options.mode === "docx") {
11964
- return handleDocxPaste(html, editor, view, plugin);
11965
- }
11966
- case "browser-html":
11967
- return handleHtmlPaste$1(html, editor);
11968
- }
11969
- return false;
11970
- }
11971
- },
11972
- isInputRules: true
11973
- });
11974
- return plugin;
11975
- };
11976
- function isWordHtml(html) {
11977
- return /class=["']?Mso|xmlns:o=["']?urn:schemas-microsoft-com|<!--\[if gte mso|<meta[^>]+name=["']?Generator["']?[^>]+Word/i.test(html);
11978
- }
11979
- const handleHtmlPaste$1 = (html, editor, plugin) => {
11980
- const cleanedHtml = convertEmToPt(html);
11981
- const tempDiv = document.createElement("div");
11982
- tempDiv.innerHTML = cleanedHtml;
11983
- const doc2 = DOMParser$1.fromSchema(editor.schema).parse(tempDiv);
11984
- tempDiv.remove();
11985
- const { dispatch } = editor.view;
11986
- if (!dispatch) return false;
11987
- dispatch(editor.view.state.tr.replaceSelectionWith(doc2, true));
11988
- return true;
11989
- };
11990
- const convertEmToPt = (html) => {
11991
- return html.replace(
11992
- /font-size\s*:\s*([\d.]+)em/gi,
11993
- (_, emValue) => {
11994
- const em = parseFloat(emValue);
11995
- const pt = Math.round(em * 12 * 100) / 100;
11996
- return `font-size: ${pt}pt`;
11997
- }
11998
- );
11999
- };
12000
- function cleanHtmlUnnecessaryTags(html) {
12001
- return html.replace(/<o:p>.*?<\/o:p>/gi, "").replace(/&nbsp;/gi, " ").replace(/<span[^>]*>\s*<\/span>/gi, "").replace(/<p[^>]*>\s*<\/p>/gi, "").trim();
12002
- }
12003
11443
  const _ExtensionService = class _ExtensionService {
12004
11444
  constructor(extensions, userExtensions, editor) {
12005
11445
  __privateAdd(this, _ExtensionService_instances);
@@ -12837,6 +12277,8 @@ const createHeaderFooterEditor = ({
12837
12277
  });
12838
12278
  if (appendToBody) document.body.appendChild(editorContainer);
12839
12279
  const headerFooterEditor = new Editor({
12280
+ documentMode: editor.options.documentMode,
12281
+ role: editor.options.role,
12840
12282
  loadFromSchema: true,
12841
12283
  mode: "docx",
12842
12284
  element: editorContainer,
@@ -12847,6 +12289,7 @@ const createHeaderFooterEditor = ({
12847
12289
  mediaFiles: editor.storage.image.media,
12848
12290
  fonts: editor.options.fonts,
12849
12291
  isHeaderOrFooter: true,
12292
+ isHeadless: editor.options.isHeadless,
12850
12293
  annotations: true,
12851
12294
  currentPageNumber,
12852
12295
  parentEditor: editor,
@@ -12854,13 +12297,15 @@ const createHeaderFooterEditor = ({
12854
12297
  onBlur: (evt) => onHeaderFooterDataUpdate(evt, editor, sectionId, type)
12855
12298
  });
12856
12299
  const pm = editorContainer.querySelector(".ProseMirror");
12857
- pm.style.maxHeight = "100%";
12858
- pm.style.minHeight = "100%";
12859
- pm.style.outline = "none";
12860
- pm.style.border = "none";
12861
- pm.setAttribute("role", "textbox");
12862
- pm.setAttribute("aria-multiline", true);
12863
- pm.setAttribute("aria-label", `${type} content area. Double click to start typing.`);
12300
+ if (pm) {
12301
+ pm.style.maxHeight = "100%";
12302
+ pm.style.minHeight = "100%";
12303
+ pm.style.outline = "none";
12304
+ pm.style.border = "none";
12305
+ pm.setAttribute("role", "textbox");
12306
+ pm.setAttribute("aria-multiline", true);
12307
+ pm.setAttribute("aria-label", `${type} content area. Double click to start typing.`);
12308
+ }
12864
12309
  return headerFooterEditor;
12865
12310
  };
12866
12311
  const broadcastEditorEvents = (editor, sectionEditor) => {
@@ -12879,14 +12324,16 @@ const broadcastEditorEvents = (editor, sectionEditor) => {
12879
12324
  });
12880
12325
  });
12881
12326
  };
12882
- const toggleHeaderFooterEditMode = (editor, focusedSectionEditor, isEditMode) => {
12327
+ const toggleHeaderFooterEditMode = ({ editor, focusedSectionEditor, isEditMode, documentMode }) => {
12883
12328
  editor.converter.headerEditors.forEach((item) => {
12884
12329
  item.editor.setEditable(isEditMode, false);
12885
12330
  item.editor.view.dom.setAttribute("aria-readonly", !isEditMode);
12331
+ item.editor.view.dom.setAttribute("documentmode", documentMode);
12886
12332
  });
12887
12333
  editor.converter.footerEditors.forEach((item) => {
12888
12334
  item.editor.setEditable(isEditMode, false);
12889
12335
  item.editor.view.dom.setAttribute("aria-readonly", !isEditMode);
12336
+ item.editor.view.dom.setAttribute("documentmode", documentMode);
12890
12337
  });
12891
12338
  if (isEditMode) {
12892
12339
  const pm = document.querySelector(".ProseMirror");
@@ -13967,6 +13414,19 @@ const deleteHeaderFooterFieldAnnotations = ({ editor, fieldIdOrArray }) => {
13967
13414
  );
13968
13415
  });
13969
13416
  };
13417
+ const resetHeaderFooterFieldAnnotations = ({ editor }) => {
13418
+ if (!editor) return;
13419
+ const sectionEditors = getAllHeaderFooterEditors(editor);
13420
+ sectionEditors.forEach(({ editor: sectionEditor, sectionId, type }) => {
13421
+ sectionEditor.commands.resetFieldAnnotations();
13422
+ onHeaderFooterDataUpdate(
13423
+ { editor: sectionEditor },
13424
+ editor,
13425
+ sectionId,
13426
+ type
13427
+ );
13428
+ });
13429
+ };
13970
13430
  const cleanUpListsWithAnnotations = (fieldsToDelete = [], editor) => {
13971
13431
  if (!Array.isArray(fieldsToDelete)) fieldsToDelete = [fieldsToDelete];
13972
13432
  const { doc: doc2 } = editor.state;
@@ -14037,6 +13497,7 @@ const AnnotatorHelpers = {
14037
13497
  getAllHeaderFooterEditors,
14038
13498
  updateHeaderFooterFieldAnnotations,
14039
13499
  deleteHeaderFooterFieldAnnotations,
13500
+ resetHeaderFooterFieldAnnotations,
14040
13501
  cleanUpListsWithAnnotations
14041
13502
  };
14042
13503
  const CollaborationPluginKey = new PluginKey("collaboration");
@@ -14216,6 +13677,16 @@ const setWordSelection = (view, pos) => {
14216
13677
  const tr = state.tr.setSelection(TextSelection.create(state.doc, word.from, word.to));
14217
13678
  dispatch(tr);
14218
13679
  };
13680
+ const setImageNodeSelection = (view, pos) => {
13681
+ const { doc: doc2 } = view.state;
13682
+ const node = doc2.nodeAt(pos);
13683
+ if (node && node.type.name === "image") {
13684
+ const tr = view.state.tr.setSelection(NodeSelection.create(doc2, pos));
13685
+ view.dispatch(tr);
13686
+ return true;
13687
+ }
13688
+ return false;
13689
+ };
14219
13690
  const _Editor = class _Editor extends EventEmitter {
14220
13691
  /**
14221
13692
  * Create a new Editor instance
@@ -14342,6 +13813,19 @@ const _Editor = class _Editor extends EventEmitter {
14342
13813
  this.setHighContrastMode = setHighContrastMode;
14343
13814
  initMode();
14344
13815
  }
13816
+ mount(el) {
13817
+ __privateMethod(this, _Editor_instances, createView_fn).call(this, el);
13818
+ window.setTimeout(() => {
13819
+ if (this.isDestroyed) return;
13820
+ this.emit("create", { editor: this });
13821
+ }, 0);
13822
+ }
13823
+ unmount() {
13824
+ if (this.view) {
13825
+ this.view.destroy();
13826
+ }
13827
+ this.view = null;
13828
+ }
14345
13829
  /**
14346
13830
  * Set the toolbar for this editor
14347
13831
  * @param {Object} toolbar - The toolbar instance
@@ -14390,7 +13874,7 @@ const _Editor = class _Editor extends EventEmitter {
14390
13874
  * @returns {boolean}
14391
13875
  */
14392
13876
  get isDestroyed() {
14393
- return this.view.isDestroyed;
13877
+ return this.view?.isDestroyed ?? true;
14394
13878
  }
14395
13879
  /**
14396
13880
  * Get the editor element
@@ -14433,7 +13917,12 @@ const _Editor = class _Editor extends EventEmitter {
14433
13917
  this.commands.toggleTrackChangesShowOriginal();
14434
13918
  this.setEditable(false, false);
14435
13919
  this.setOptions({ documentMode: "viewing" });
14436
- toggleHeaderFooterEditMode(this, null, false);
13920
+ toggleHeaderFooterEditMode({
13921
+ editor: this,
13922
+ focusedSectionEditor: null,
13923
+ isEditMode: false,
13924
+ documentMode: cleanedMode
13925
+ });
14437
13926
  } else if (cleanedMode === "suggesting") {
14438
13927
  __privateMethod(this, _Editor_instances, registerPluginByNameIfNotExists_fn).call(this, "TrackChangesBase");
14439
13928
  this.commands.disableTrackChangesShowOriginal();
@@ -14446,7 +13935,12 @@ const _Editor = class _Editor extends EventEmitter {
14446
13935
  this.commands.disableTrackChanges();
14447
13936
  this.setEditable(true, false);
14448
13937
  this.setOptions({ documentMode: "editing" });
14449
- toggleHeaderFooterEditMode(this, null, false);
13938
+ toggleHeaderFooterEditMode({
13939
+ editor: this,
13940
+ focusedSectionEditor: null,
13941
+ isEditMode: false,
13942
+ documentMode: cleanedMode
13943
+ });
14450
13944
  }
14451
13945
  }
14452
13946
  /**
@@ -14544,10 +14038,10 @@ const _Editor = class _Editor extends EventEmitter {
14544
14038
  }
14545
14039
  /**
14546
14040
  * Unregister a PM plugin
14547
- * @param {string|Object} nameOrPlugin - Plugin name or plugin instance
14041
+ * @param {string|Object} nameOrPluginKey - Plugin name or plugin instance
14548
14042
  * @returns {void}
14549
14043
  */
14550
- unregisterPlugin(nameOrPlugin) {
14044
+ unregisterPlugin(nameOrPluginKey) {
14551
14045
  if (this.isDestroyed) return;
14552
14046
  const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key;
14553
14047
  const state = this.state.reconfigure({
@@ -14623,29 +14117,26 @@ const _Editor = class _Editor extends EventEmitter {
14623
14117
  };
14624
14118
  }
14625
14119
  /**
14626
- * Initialize default styles for the editor container and ProseMirror.
14627
- * Get page size and margins from the converter.
14628
- * Set document default font and font size.
14629
- *
14630
- * @param {HTMLElement} [element=this.element] - The DOM element to apply styles to
14631
- * @returns {void}
14632
- */
14633
- initDefaultStyles(element = this.element) {
14634
- if (this.options.isHeadless || this.options.suppressDefaultDocxStyles) return;
14635
- const proseMirror = element?.querySelector(".ProseMirror");
14120
+ * Attach styles and attributes to the editor element
14121
+ */
14122
+ updateEditorStyles(element, proseMirror, hasPaginationEnabled = true) {
14636
14123
  const { pageSize, pageMargins } = this.converter.pageStyles ?? {};
14637
- if (!proseMirror || !pageSize || !pageMargins) {
14124
+ if (!proseMirror || !element) {
14638
14125
  return;
14639
14126
  }
14640
14127
  proseMirror.setAttribute("role", "document");
14641
14128
  proseMirror.setAttribute("aria-multiline", true);
14642
14129
  proseMirror.setAttribute("aria-label", "Main content area, start typing to enter text.");
14643
14130
  proseMirror.setAttribute("aria-description", "");
14644
- element.style.width = pageSize.width + "in";
14645
- element.style.minWidth = pageSize.width + "in";
14646
- element.style.minHeight = pageSize.height + "in";
14647
- element.style.paddingLeft = pageMargins.left + "in";
14648
- element.style.paddingRight = pageMargins.right + "in";
14131
+ if (pageSize) {
14132
+ element.style.width = pageSize.width + "in";
14133
+ element.style.minWidth = pageSize.width + "in";
14134
+ element.style.minHeight = pageSize.height + "in";
14135
+ }
14136
+ if (pageMargins) {
14137
+ element.style.paddingLeft = pageMargins.left + "in";
14138
+ element.style.paddingRight = pageMargins.right + "in";
14139
+ }
14649
14140
  element.style.boxSizing = "border-box";
14650
14141
  element.style.isolation = "isolate";
14651
14142
  proseMirror.style.outline = "none";
@@ -14662,10 +14153,26 @@ const _Editor = class _Editor extends EventEmitter {
14662
14153
  element.style.webkitOverflowScrolling = "touch";
14663
14154
  const defaultLineHeight = 1.2;
14664
14155
  proseMirror.style.lineHeight = defaultLineHeight;
14665
- if (!this.options.extensions.find((e) => e.name === "pagination")) {
14156
+ if (!hasPaginationEnabled) {
14666
14157
  proseMirror.style.paddingTop = "1in";
14667
14158
  proseMirror.style.paddingBottom = "1in";
14159
+ } else {
14160
+ proseMirror.style.paddingTop = "0";
14161
+ proseMirror.style.paddingBottom = "0";
14668
14162
  }
14163
+ }
14164
+ /**
14165
+ * Initialize default styles for the editor container and ProseMirror.
14166
+ * Get page size and margins from the converter.
14167
+ * Set document default font and font size.
14168
+ *
14169
+ * @param {HTMLElement} [element=this.element] - The DOM element to apply styles to
14170
+ * @returns {void}
14171
+ */
14172
+ initDefaultStyles(element = this.element, isPaginationEnabled = true) {
14173
+ if (this.options.isHeadless || this.options.suppressDefaultDocxStyles) return;
14174
+ const proseMirror = element?.querySelector(".ProseMirror");
14175
+ this.updateEditorStyles(element, proseMirror, isPaginationEnabled);
14669
14176
  this.initMobileStyles(element);
14670
14177
  }
14671
14178
  /**
@@ -14713,6 +14220,26 @@ const _Editor = class _Editor extends EventEmitter {
14713
14220
  }
14714
14221
  window.addEventListener("resize", () => handleResize);
14715
14222
  }
14223
+ /**
14224
+ * Initialize pagination, if the pagination extension is enabled.
14225
+ * @private
14226
+ * @async
14227
+ * @returns {Promise<void>}
14228
+ */
14229
+ async initPagination() {
14230
+ if (this.options.isHeadless || !this.extensionService || this.options.isHeaderOrFooter) {
14231
+ return;
14232
+ }
14233
+ const pagination = this.options.extensions.find((e) => e.name === "pagination");
14234
+ if (pagination && this.options.pagination) {
14235
+ console.debug("🔗 [super-editor] Initializing pagination");
14236
+ const sectionData = await initPaginationData(this);
14237
+ this.storage.pagination.sectionData = sectionData;
14238
+ const { state, dispatch } = this.view;
14239
+ const tr = state.tr.setMeta(PaginationPluginKey, { isReadyToInit: true });
14240
+ dispatch(tr);
14241
+ }
14242
+ }
14716
14243
  /**
14717
14244
  * Get attrs of the currently selected node or mark.
14718
14245
  * @param {String} nameOrType
@@ -14877,10 +14404,25 @@ const _Editor = class _Editor extends EventEmitter {
14877
14404
  */
14878
14405
  destroy() {
14879
14406
  this.emit("destroy");
14880
- if (this.view) this.view.destroy();
14407
+ this.unmount();
14408
+ this.destroyHeaderFooterEditors();
14881
14409
  __privateMethod(this, _Editor_instances, endCollaboration_fn).call(this);
14882
14410
  this.removeAllListeners();
14883
14411
  }
14412
+ destroyHeaderFooterEditors() {
14413
+ try {
14414
+ const editors = [
14415
+ ...this.converter.headerEditors,
14416
+ ...this.converter.footerEditors
14417
+ ];
14418
+ for (let editorData of editors) {
14419
+ editorData.editor.destroy();
14420
+ }
14421
+ this.converter.headerEditors.length = 0;
14422
+ this.converter.footerEditors.length = 0;
14423
+ } catch (error) {
14424
+ }
14425
+ }
14884
14426
  /**
14885
14427
  * Check if migrations are needed for the data
14886
14428
  * @static
@@ -14898,7 +14440,7 @@ const _Editor = class _Editor extends EventEmitter {
14898
14440
  * @returns {Object | void} Migration results
14899
14441
  */
14900
14442
  processCollaborationMigrations() {
14901
- console.debug("[checkVersionMigrations] Current editor version", "0.13.2-rev1");
14443
+ console.debug("[checkVersionMigrations] Current editor version", "0.13.2-rev11");
14902
14444
  if (!this.options.ydoc) return;
14903
14445
  const metaMap = this.options.ydoc.getMap("meta");
14904
14446
  let docVersion = metaMap.get("version");
@@ -14948,7 +14490,7 @@ const _Editor = class _Editor extends EventEmitter {
14948
14490
  __privateMethod(this, _Editor_instances, insertNewFileData_fn).call(this);
14949
14491
  }
14950
14492
  if (!this.options.ydoc) {
14951
- __privateMethod(this, _Editor_instances, initPagination_fn).call(this);
14493
+ this.initPagination();
14952
14494
  __privateMethod(this, _Editor_instances, initComments_fn).call(this);
14953
14495
  }
14954
14496
  }
@@ -15106,9 +14648,7 @@ init_fn = function(options) {
15106
14648
  this.emit("beforeCreate", { editor: this });
15107
14649
  this.on("contentError", this.options.onContentError);
15108
14650
  this.on("exception", this.options.onException);
15109
- __privateMethod(this, _Editor_instances, createView_fn).call(this);
15110
- this.initDefaultStyles();
15111
- this.setDocumentMode(options.documentMode);
14651
+ this.mount(this.options.element);
15112
14652
  if (this.options.isHeadless) return;
15113
14653
  this.on("create", this.options.onCreate);
15114
14654
  this.on("update", this.options.onUpdate);
@@ -15126,14 +14666,12 @@ init_fn = function(options) {
15126
14666
  this.on("paginationUpdate", this.options.onPaginationUpdate);
15127
14667
  this.on("comment-positions", this.options.onCommentLocationsUpdate);
15128
14668
  this.initializeCollaborationData();
14669
+ this.initDefaultStyles();
14670
+ this.setDocumentMode(this.options.documentMode);
15129
14671
  if (!this.options.ydoc) {
15130
- __privateMethod(this, _Editor_instances, initPagination_fn).call(this);
14672
+ this.initPagination();
15131
14673
  __privateMethod(this, _Editor_instances, initComments_fn).call(this);
15132
14674
  }
15133
- window.setTimeout(() => {
15134
- if (this.isDestroyed) return;
15135
- this.emit("create", { editor: this });
15136
- }, 0);
15137
14675
  };
15138
14676
  /**
15139
14677
  * Initialize the editor in rich text mode
@@ -15151,7 +14689,7 @@ initRichText_fn = function(options) {
15151
14689
  this.on("beforeCreate", this.options.onBeforeCreate);
15152
14690
  this.emit("beforeCreate", { editor: this });
15153
14691
  this.on("contentError", this.options.onContentError);
15154
- __privateMethod(this, _Editor_instances, createView_fn).call(this);
14692
+ this.mount(this.options.element);
15155
14693
  this.on("create", this.options.onCreate);
15156
14694
  this.on("update", this.options.onUpdate);
15157
14695
  this.on("selectionUpdate", this.options.onSelectionUpdate);
@@ -15162,10 +14700,6 @@ initRichText_fn = function(options) {
15162
14700
  this.on("commentsLoaded", this.options.onCommentsLoaded);
15163
14701
  this.on("commentClick", this.options.onCommentClicked);
15164
14702
  this.on("locked", this.options.onDocumentLocked);
15165
- window.setTimeout(() => {
15166
- if (this.isDestroyed) return;
15167
- this.emit("create", { editor: this });
15168
- }, 0);
15169
14703
  };
15170
14704
  /**
15171
14705
  *
@@ -15211,7 +14745,7 @@ insertNewFileData_fn = function() {
15211
14745
  const tr = this.state.tr.replaceWith(0, this.state.doc.content.size, doc2);
15212
14746
  this.view.dispatch(tr);
15213
14747
  setTimeout(() => {
15214
- __privateMethod(this, _Editor_instances, initPagination_fn).call(this);
14748
+ this.initPagination();
15215
14749
  __privateMethod(this, _Editor_instances, initComments_fn).call(this);
15216
14750
  }, 50);
15217
14751
  };
@@ -15364,14 +14898,15 @@ createDocFromHTML_fn = function(content) {
15364
14898
  * @private
15365
14899
  * @returns {void}
15366
14900
  */
15367
- createView_fn = function() {
14901
+ createView_fn = function(element) {
15368
14902
  let doc2 = __privateMethod(this, _Editor_instances, generatePmData_fn).call(this);
15369
14903
  const state = { schema: this.schema };
15370
14904
  if (!this.options.ydoc) state.doc = doc2;
15371
- this.view = new EditorView(this.options.element, {
14905
+ this.view = new EditorView(element, {
15372
14906
  ...this.options.editorProps,
15373
14907
  dispatchTransaction: __privateMethod(this, _Editor_instances, dispatchTransaction_fn).bind(this),
15374
14908
  state: EditorState.create(state),
14909
+ handleClick: __privateMethod(this, _Editor_instances, handleNodeSelection_fn).bind(this),
15375
14910
  handleDoubleClick: async (view, pos, event) => {
15376
14911
  if (this.options.documentMode !== "editing") return;
15377
14912
  const isHeader = hasSomeParentWithClass(event.target, "pagination-section-header");
@@ -15385,7 +14920,12 @@ createView_fn = function() {
15385
14920
  event.stopPropagation();
15386
14921
  if (!this.options.editable) {
15387
14922
  this.setEditable(true, false);
15388
- toggleHeaderFooterEditMode(this, null, false);
14923
+ toggleHeaderFooterEditMode({
14924
+ editor: this,
14925
+ focusedSectionEditor: null,
14926
+ isEditMode: false,
14927
+ documentMode: this.options.documentMode
14928
+ });
15389
14929
  const pm = document.querySelector(".ProseMirror");
15390
14930
  pm.classList.remove("header-footer-edit");
15391
14931
  pm.setAttribute("aria-readonly", false);
@@ -15398,8 +14938,6 @@ createView_fn = function() {
15398
14938
  });
15399
14939
  this.view.updateState(newState);
15400
14940
  this.createNodeViews();
15401
- const dom = this.view.dom;
15402
- dom.editor = this;
15403
14941
  this.options.telemetry?.sendReport();
15404
14942
  };
15405
14943
  /**
@@ -15418,7 +14956,7 @@ onCollaborationReady_fn = function({ editor, ydoc }) {
15418
14956
  this.options.onCollaborationReady({ editor, ydoc });
15419
14957
  this.options.collaborationIsReady = true;
15420
14958
  if (!this.options.isNewFile) {
15421
- __privateMethod(this, _Editor_instances, initPagination_fn).call(this);
14959
+ this.initPagination();
15422
14960
  __privateMethod(this, _Editor_instances, initComments_fn).call(this);
15423
14961
  }
15424
14962
  };
@@ -15440,25 +14978,13 @@ initComments_fn = function() {
15440
14978
  dispatch(tr);
15441
14979
  }, 50);
15442
14980
  };
15443
- initPagination_fn = async function() {
15444
- if (this.options.isHeadless || !this.extensionService) return;
15445
- const pagination = this.options.extensions.find((e) => e.name === "pagination");
15446
- if (pagination && this.options.pagination) {
15447
- console.debug("🔗 [super-editor] Initializing pagination");
15448
- const sectionData = await initPaginationData(this);
15449
- this.storage.pagination.sectionData = sectionData;
15450
- const { state, dispatch } = this.view;
15451
- const tr = state.tr.setMeta(PaginationPluginKey, { isReadyToInit: true });
15452
- dispatch(tr);
15453
- }
15454
- };
15455
14981
  /**
15456
14982
  * Dispatch a transaction to update the editor state
15457
14983
  * @private
15458
14984
  * @param {Object} transaction - ProseMirror transaction
15459
14985
  */
15460
14986
  dispatchTransaction_fn = function(transaction) {
15461
- if (this.view.isDestroyed) return;
14987
+ if (this.isDestroyed) return;
15462
14988
  let state;
15463
14989
  try {
15464
14990
  const trackChangesState = TrackChangesBasePluginKey.getState(this.view.state);
@@ -15510,6 +15036,14 @@ dispatchTransaction_fn = function(transaction) {
15510
15036
  transaction
15511
15037
  });
15512
15038
  };
15039
+ /**
15040
+ * Handles image node selection for header/footer editor
15041
+ */
15042
+ handleNodeSelection_fn = function(view, pos) {
15043
+ if (this.options.isHeaderOrFooter) {
15044
+ return setImageNodeSelection(view, pos);
15045
+ }
15046
+ };
15513
15047
  /**
15514
15048
  * Perform any post conversion pre prosemirror import processing.
15515
15049
  * Comments are processed here.
@@ -17870,7 +17404,7 @@ const Paragraph = Node$1.create({
17870
17404
  },
17871
17405
  addPmPlugins() {
17872
17406
  const { view } = this.editor;
17873
- const dropcapPlugin = new Plugin({
17407
+ new Plugin({
17874
17408
  name: "dropcapPlugin",
17875
17409
  key: new PluginKey("dropcapPlugin"),
17876
17410
  state: {
@@ -17890,7 +17424,7 @@ const Paragraph = Node$1.create({
17890
17424
  }
17891
17425
  }
17892
17426
  });
17893
- return [dropcapPlugin];
17427
+ return [];
17894
17428
  }
17895
17429
  });
17896
17430
  const getDropcapDecorations = (state, view) => {
@@ -18243,7 +17777,16 @@ const HardBreak = Node$1.create({
18243
17777
  };
18244
17778
  },
18245
17779
  parseDOM() {
18246
- return [{ tag: "span" }];
17780
+ return [{
17781
+ tag: 'span[linebreaktype="page"]',
17782
+ getAttrs: (dom) => {
17783
+ if (!(dom instanceof HTMLElement)) return false;
17784
+ return {
17785
+ pageBreakSource: dom.getAttribute("pagebreaksource") || null,
17786
+ pageBreakType: dom.getAttribute("linebreaktype") || null
17787
+ };
17788
+ }
17789
+ }];
18247
17790
  },
18248
17791
  renderDOM({ htmlAttributes }) {
18249
17792
  return ["span", Attribute.mergeAttributes(this.options.htmlAttributes, htmlAttributes)];
@@ -21240,6 +20783,8 @@ function findRemovedFieldAnnotations(tr) {
21240
20783
  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) {
21241
20784
  return removedNodes;
21242
20785
  }
20786
+ const hasDeletion = transactionDeletedAnything(tr);
20787
+ if (!hasDeletion) return removedNodes;
21243
20788
  tr.steps.forEach((step, stepIndex) => {
21244
20789
  if (step instanceof ReplaceStep && step.from !== step.to) {
21245
20790
  let mapping = tr.mapping.maps[stepIndex];
@@ -21256,6 +20801,14 @@ function findRemovedFieldAnnotations(tr) {
21256
20801
  });
21257
20802
  return removedNodes;
21258
20803
  }
20804
+ function transactionDeletedAnything(tr) {
20805
+ return tr.steps.some((step) => {
20806
+ if (step instanceof ReplaceStep || step instanceof ReplaceAroundStep) {
20807
+ return step.from !== step.to;
20808
+ }
20809
+ return false;
20810
+ });
20811
+ }
21259
20812
  function trackFieldAnnotationsDeletion(editor, tr) {
21260
20813
  let removedAnnotations = [];
21261
20814
  try {
@@ -21651,8 +21204,18 @@ const FieldAnnotation = Node$1.create({
21651
21204
  };
21652
21205
  }
21653
21206
  },
21207
+ defaultDisplayLabel: {
21208
+ default: "",
21209
+ parseDOM: (elem) => elem.getAttribute("data-default-display-label"),
21210
+ renderDOM: (attrs) => {
21211
+ if (!attrs.defaultDisplayLabel) return {};
21212
+ return {
21213
+ "data-default-display-label": attrs.defaultDisplayLabel
21214
+ };
21215
+ }
21216
+ },
21654
21217
  displayLabel: {
21655
- default: "Text field",
21218
+ default: "",
21656
21219
  parseDOM: (elem) => elem.getAttribute("data-display-label"),
21657
21220
  renderDOM: (attrs) => {
21658
21221
  if (!attrs.displayLabel) return {};
@@ -21968,6 +21531,7 @@ const FieldAnnotation = Node$1.create({
21968
21531
  return renderer();
21969
21532
  },
21970
21533
  addCommands() {
21534
+ const annotationTypes = this.options.types;
21971
21535
  return {
21972
21536
  /**
21973
21537
  * Add field annotation.
@@ -21989,7 +21553,12 @@ const FieldAnnotation = Node$1.create({
21989
21553
  let currentMarks = $pos.marks();
21990
21554
  currentMarks = currentMarks.length ? [...currentMarks] : null;
21991
21555
  let formatAttrs = getFormatAttrsFromMarks(currentMarks);
21992
- let node = schema.nodes[this.name].create({ ...attrs, ...formatAttrs }, null, null);
21556
+ let defaultDisplayLabel = attrs.defaultDisplayLabel ? attrs.defaultDisplayLabel : attrs.displayLabel || "";
21557
+ let node = schema.nodes[this.name].create({
21558
+ ...attrs,
21559
+ ...formatAttrs,
21560
+ defaultDisplayLabel
21561
+ }, null, null);
21993
21562
  state.tr.insert(newPos, node).setSelection(Selection.near(tr.doc.resolve(newPos + node.nodeSize)));
21994
21563
  if (editorFocus) {
21995
21564
  this.editor.view.focus();
@@ -21997,9 +21566,9 @@ const FieldAnnotation = Node$1.create({
21997
21566
  }
21998
21567
  return true;
21999
21568
  },
22000
- addFieldAnnotationAtSelection: (attrs = {}, editorFocus = false) => ({ editor, dispatch, state, tr, commands: commands2 }) => {
21569
+ addFieldAnnotationAtSelection: (attrs = {}, editorFocus = false) => ({ state, commands: commands2 }) => {
22001
21570
  const { from: from2 } = state.selection;
22002
- commands2.addFieldAnnotation(from2, attrs, editorFocus);
21571
+ return commands2.addFieldAnnotation(from2, attrs, editorFocus);
22003
21572
  },
22004
21573
  /**
22005
21574
  * Replace field annotation.
@@ -22009,24 +21578,113 @@ const FieldAnnotation = Node$1.create({
22009
21578
  * from: 20,
22010
21579
  * to: 45,
22011
21580
  * attrs: {
22012
- * fieldType: 'TEXTINPUT'
22013
- * fieldColor: '#980043'
21581
+ * fieldType: 'TEXTINPUT'
21582
+ * fieldColor: '#980043'
22014
21583
  * }
22015
21584
  * ])
22016
21585
  */
22017
- replaceWithFieldAnnotation: (fieldsArray) => ({ editor, dispatch, state, tr }) => {
21586
+ replaceWithFieldAnnotation: (fieldsArray) => ({ editor, dispatch, tr }) => {
22018
21587
  if (!dispatch) return true;
22019
- tr.setMeta("fieldAnnotationReplace", true);
22020
21588
  fieldsArray.forEach((annotation) => {
22021
21589
  let { from: from2, to, attrs } = annotation;
22022
21590
  let { schema } = editor;
22023
21591
  let newPosFrom = tr.mapping.map(from2);
22024
21592
  let newPosTo = tr.mapping.map(to);
22025
- let node = schema.nodes[this.name].create({ ...attrs }, null, null);
21593
+ let defaultDisplayLabel = attrs.defaultDisplayLabel ? attrs.defaultDisplayLabel : attrs.displayLabel || "";
21594
+ let node = schema.nodes[this.name].create({
21595
+ ...attrs,
21596
+ defaultDisplayLabel
21597
+ }, null, null);
22026
21598
  tr.replaceWith(newPosFrom, newPosTo, node);
22027
21599
  });
22028
21600
  return true;
22029
21601
  },
21602
+ /**
21603
+ * Replace annotations with a label (as text node) in selection.
21604
+ * @param options Additional options.
21605
+ * @example
21606
+ * editor.commands.replaceFieldAnnotationsWithLabelInSelection()
21607
+ */
21608
+ replaceFieldAnnotationsWithLabelInSelection: (options = {}) => ({ commands: commands2 }) => {
21609
+ return commands2.replaceFieldAnnotationsWithLabel(null, {
21610
+ ...options,
21611
+ isInSelection: true
21612
+ });
21613
+ },
21614
+ /**
21615
+ * Replace annotations with a label (as text node).
21616
+ * @param fieldIdOrArray The field ID or array of field IDs.
21617
+ * @param options.isInSelection Find in selection instead of field IDs.
21618
+ * @param options.addToHistory Add to history or not.
21619
+ * @param options.types Annotation types to replace.
21620
+ * @example
21621
+ * editor.commands.replaceFieldAnnotationsWithLabel(['1', '2'])
21622
+ */
21623
+ replaceFieldAnnotationsWithLabel: (fieldIdOrArray, {
21624
+ isInSelection = false,
21625
+ addToHistory = false,
21626
+ types = annotationTypes
21627
+ } = {}) => ({ dispatch, state, tr }) => {
21628
+ let { from: from2, to } = state.selection;
21629
+ let annotations = isInSelection ? findFieldAnnotationsBetween(from2, to, state.doc) : findFieldAnnotationsByFieldId(fieldIdOrArray, state);
21630
+ annotations = types.length ? annotations.filter(({ node }) => types.includes(node.attrs.type)) : annotations;
21631
+ if (!annotations.length) {
21632
+ return true;
21633
+ }
21634
+ if (!addToHistory) {
21635
+ tr.setMeta("addToHistory", false);
21636
+ }
21637
+ if (dispatch) {
21638
+ annotations.forEach((annotation) => {
21639
+ let { pos, node } = annotation;
21640
+ let newPosFrom = tr.mapping.map(pos);
21641
+ let newPosTo = tr.mapping.map(pos + node.nodeSize);
21642
+ let currentNode = tr.doc.nodeAt(newPosFrom);
21643
+ let nodeEqual = node.attrs.fieldId === currentNode?.attrs?.fieldId;
21644
+ let $newPosFrom = tr.doc.resolve(newPosFrom);
21645
+ let currentMarks = $newPosFrom.marks();
21646
+ currentMarks = currentMarks.length ? [...currentMarks] : null;
21647
+ if (nodeEqual) {
21648
+ let label = node.attrs.displayLabel || " ";
21649
+ let textNode = state.schema.text(label, currentMarks);
21650
+ tr.replaceWith(newPosFrom, newPosTo, textNode);
21651
+ }
21652
+ });
21653
+ }
21654
+ return true;
21655
+ },
21656
+ /**
21657
+ * Resets all annotations to default values.
21658
+ * @example
21659
+ * editor.commands.resetFieldAnnotations()
21660
+ */
21661
+ resetFieldAnnotations: () => ({ dispatch, state, tr }) => {
21662
+ let annotations = getAllFieldAnnotations(state);
21663
+ if (!annotations.length) {
21664
+ return true;
21665
+ }
21666
+ tr.setMeta("fieldAnnotationUpdate", true);
21667
+ if (dispatch) {
21668
+ annotations.forEach(({ pos, node }) => {
21669
+ let newPos = tr.mapping.map(pos);
21670
+ let currentNode = tr.doc.nodeAt(newPos);
21671
+ let nodeEqual = node.attrs.fieldId === currentNode?.attrs?.fieldId;
21672
+ if (nodeEqual) {
21673
+ let displayLabel = node.attrs.defaultDisplayLabel || node.attrs.displayLabel || "";
21674
+ tr.setNodeMarkup(newPos, void 0, {
21675
+ ...node.attrs,
21676
+ // reset displayLabel to default.
21677
+ displayLabel,
21678
+ // reset attrs ​​for specific types.
21679
+ imageSrc: null,
21680
+ rawHtml: null,
21681
+ linkUrl: null
21682
+ });
21683
+ }
21684
+ });
21685
+ }
21686
+ return true;
21687
+ },
22030
21688
  /**
22031
21689
  * Update annotations associated with a field.
22032
21690
  * @param fieldIdOrArray The field ID or array of field IDs.
@@ -22781,12 +22439,16 @@ const startImageUpload = async ({ editor, view, file }) => {
22781
22439
  }
22782
22440
  let id = {};
22783
22441
  let { tr, schema } = view.state;
22784
- if (!tr.selection.empty) {
22442
+ let { selection } = tr;
22443
+ if (editor.options.isHeaderOrFooter) {
22444
+ selection = editor.options.lastSelection;
22445
+ }
22446
+ if (!selection.empty && !editor.options.isHeaderOrFooter) {
22785
22447
  tr.deleteSelection();
22786
22448
  }
22787
22449
  let imageMeta = {
22788
22450
  type: "add",
22789
- pos: tr.selection.from,
22451
+ pos: selection.from,
22790
22452
  id
22791
22453
  };
22792
22454
  tr.setMeta(ImagePlaceholderPluginKey, imageMeta);
@@ -28035,7 +27697,8 @@ const Pagination = Extension.create({
28035
27697
  addStorage() {
28036
27698
  return {
28037
27699
  height: 0,
28038
- sectionData: null
27700
+ sectionData: null,
27701
+ headerFooterEditors: /* @__PURE__ */ new Map()
28039
27702
  };
28040
27703
  },
28041
27704
  addCommands() {
@@ -28044,6 +27707,19 @@ const Pagination = Extension.create({
28044
27707
  return commands2.insertContent({
28045
27708
  type: "hardBreak"
28046
27709
  });
27710
+ },
27711
+ /**
27712
+ * Toggle pagination on/off
27713
+ * @returns {void}
27714
+ */
27715
+ togglePagination: () => ({ tr, state, dispatch, editor }) => {
27716
+ const isEnabled = PaginationPluginKey.getState(state)?.isEnabled;
27717
+ tr.setMeta(PaginationPluginKey, { isEnabled: !isEnabled });
27718
+ if (dispatch) {
27719
+ dispatch(tr);
27720
+ editor.initDefaultStyles(editor.element, !isEnabled);
27721
+ return true;
27722
+ }
28047
27723
  }
28048
27724
  };
28049
27725
  },
@@ -28069,22 +27745,33 @@ const Pagination = Extension.create({
28069
27745
  return {
28070
27746
  isReadyToInit: false,
28071
27747
  decorations: DecorationSet.empty,
28072
- isDebugging
27748
+ isDebugging,
27749
+ isEnabled: editor.options.pagination
28073
27750
  };
28074
27751
  },
28075
27752
  apply(tr, oldState, prevEditorState, newEditorState) {
28076
27753
  const meta = tr.getMeta(PaginationPluginKey);
27754
+ if (meta && "isEnabled" in meta) {
27755
+ const newEnabled = meta.isEnabled;
27756
+ if (newEnabled) shouldUpdate = true;
27757
+ return {
27758
+ ...oldState,
27759
+ decorations: newEnabled ? oldState.decorations : DecorationSet.empty,
27760
+ isEnabled: newEnabled
27761
+ };
27762
+ }
28077
27763
  if (meta && meta.isReadyToInit) {
28078
27764
  shouldUpdate = true;
28079
27765
  shouldInitialize = meta.isReadyToInit;
28080
27766
  }
27767
+ const syncMeta = tr.getMeta("y-sync$");
27768
+ if (syncMeta && syncMeta.isChangeOrigin) {
27769
+ return { ...oldState };
27770
+ }
28081
27771
  const imagePluginTransaction = tr.getMeta(ImagePlaceholderPluginKey);
28082
27772
  if (imagePluginTransaction) {
28083
27773
  if (imagePluginTransaction.type === "remove") {
28084
- const imagePos = imagePluginTransaction.pos;
28085
- const domImage = editor.view.domAtPos(imagePos).node.querySelector("img");
28086
- if (domImage.complete) onImageLoad(editor);
28087
- else domImage.onload = () => onImageLoad(editor);
27774
+ onImageLoad(editor);
28088
27775
  }
28089
27776
  return { ...oldState };
28090
27777
  }
@@ -28111,6 +27798,7 @@ const Pagination = Extension.create({
28111
27798
  if (isForceUpdate) shouldUpdate = true;
28112
27799
  return {
28113
27800
  ...oldState,
27801
+ decorations: meta?.decorations?.map(tr.mapping, tr.doc) || DecorationSet.empty,
28114
27802
  isReadyToInit: shouldInitialize
28115
27803
  };
28116
27804
  }
@@ -28120,6 +27808,7 @@ const Pagination = Extension.create({
28120
27808
  let previousDecorations = DecorationSet.empty;
28121
27809
  return {
28122
27810
  update: (view2, prevState) => {
27811
+ if (!PaginationPluginKey.getState(view2.state)?.isEnabled) return;
28123
27812
  if (!shouldUpdate || isUpdating) return;
28124
27813
  isUpdating = true;
28125
27814
  hasInitialized = true;
@@ -28131,7 +27820,8 @@ const Pagination = Extension.create({
28131
27820
  },
28132
27821
  props: {
28133
27822
  decorations(state) {
28134
- return PaginationPluginKey.getState(state).decorations;
27823
+ const pluginState = PaginationPluginKey.getState(state);
27824
+ return pluginState.isEnabled ? pluginState.decorations : DecorationSet.empty;
28135
27825
  }
28136
27826
  }
28137
27827
  });
@@ -28139,6 +27829,10 @@ const Pagination = Extension.create({
28139
27829
  },
28140
27830
  onDestroy() {
28141
27831
  cleanupFloatingSeparators();
27832
+ const { headerFooterEditors } = this.editor.storage.pagination;
27833
+ if (headerFooterEditors) {
27834
+ headerFooterEditors.clear();
27835
+ }
28142
27836
  }
28143
27837
  });
28144
27838
  const getHeaderFooterId = (currentPageNumber, sectionType, editor, node = null) => {
@@ -28199,6 +27893,7 @@ const performUpdate = (editor, view, previousDecorations) => {
28199
27893
  const calculatePageBreaks = (view, editor, sectionData) => {
28200
27894
  if (!editor.converter) return DecorationSet.empty;
28201
27895
  const pageSize = editor.converter.pageStyles?.pageSize;
27896
+ if (!pageSize) return DecorationSet.empty;
28202
27897
  const { width, height } = pageSize;
28203
27898
  if (!width || !height) return DecorationSet.empty;
28204
27899
  const ignorePlugins = [CollaborationPluginKey, PaginationPluginKey];
@@ -28237,11 +27932,13 @@ function generateInternalPageBreaks(doc2, view, editor, sectionData) {
28237
27932
  let pageHeightThreshold = pageHeight;
28238
27933
  let footer = null, header = null;
28239
27934
  const firstHeaderId = getHeaderFooterId(currentPageNumber, "headerIds", editor);
28240
- const firstHeader = createHeader(pageMargins, pageSize, sectionData, firstHeaderId, editor, currentPageNumber);
27935
+ const isFirstHeader = true;
27936
+ const firstHeader = createHeader(pageMargins, pageSize, sectionData, firstHeaderId, editor, currentPageNumber, isFirstHeader);
28241
27937
  const pageBreak = createPageBreak({ editor, header: firstHeader, isFirstHeader: true });
28242
27938
  decorations.push(Decoration.widget(0, pageBreak, { key: "stable-key" }));
28243
27939
  const lastFooterId = getHeaderFooterId(currentPageNumber, "footerIds", editor);
28244
- const lastFooter = createFooter(pageMargins, pageSize, sectionData, lastFooterId, editor, currentPageNumber);
27940
+ const isLastFooter = true;
27941
+ const lastFooter = createFooter(pageMargins, pageSize, sectionData, lastFooterId, editor, currentPageNumber, isLastFooter);
28245
27942
  pageHeightThreshold -= firstHeader.headerHeight + lastFooter.footerHeight;
28246
27943
  let coords = view?.coordsAtPos(doc2.content.size);
28247
27944
  if (!coords) return [];
@@ -28260,7 +27957,8 @@ function generateInternalPageBreaks(doc2, view, editor, sectionData) {
28260
27957
  if (currentPageNumber === 1) {
28261
27958
  const headerId2 = getHeaderFooterId(currentPageNumber, "headerIds", editor, currentNode);
28262
27959
  decorations.pop();
28263
- const newFirstHeader = createHeader(pageMargins, pageSize, sectionData, headerId2, editor, currentPageNumber - 1);
27960
+ const isFirstHeader2 = true;
27961
+ const newFirstHeader = createHeader(pageMargins, pageSize, sectionData, headerId2, editor, currentPageNumber, isFirstHeader2);
28264
27962
  const pageBreak2 = createPageBreak({ editor, header: newFirstHeader, isFirstHeader: true });
28265
27963
  decorations.push(Decoration.widget(0, pageBreak2, { key: "stable-key" }));
28266
27964
  }
@@ -28334,15 +28032,15 @@ function createFinalPagePadding(bufferHeight) {
28334
28032
  div2.style.height = bufferHeight + "px";
28335
28033
  return { nodeHeight: bufferHeight, node: div2 };
28336
28034
  }
28337
- function createHeader(pageMargins, pageSize, sectionData, headerId, editor, currentPageNumber) {
28338
- const headerDef = sectionData.headers?.[headerId];
28035
+ function createHeader(pageMargins, pageSize, sectionData, headerId, editor, currentPageNumber, isFirstHeader = false) {
28036
+ const headerDef = sectionData?.headers?.[headerId];
28339
28037
  const minHeaderHeight = pageMargins.top * 96;
28340
28038
  const headerMargin = pageMargins.header * 96;
28341
28039
  const hasHeaderOffset = headerDef?.height > minHeaderHeight - headerMargin;
28342
28040
  const headerOffset = hasHeaderOffset ? headerMargin : 0;
28343
28041
  const headerHeight = Math.max(headerDef?.height || 0, minHeaderHeight) + headerOffset;
28344
28042
  const availableHeight = headerHeight - headerMargin;
28345
- const editorContainer = document.createElement("div");
28043
+ let editorContainer = document.createElement("div");
28346
28044
  if (!headerId && !editor?.converter?.headerIds?.["default"]) {
28347
28045
  headerId = "rId" + generateDocxRandomId();
28348
28046
  editor.converter.headerIds["default"] = headerId;
@@ -28354,23 +28052,31 @@ function createHeader(pageMargins, pageSize, sectionData, headerId, editor, curr
28354
28052
  };
28355
28053
  }
28356
28054
  const data = editor.converter.headers[headerId];
28357
- const editorSection = createHeaderFooterEditor({
28358
- editor,
28359
- data,
28360
- editorContainer,
28361
- appendToBody: false,
28362
- sectionId: headerId,
28363
- type: "header",
28364
- availableHeight,
28365
- currentPageNumber
28366
- });
28367
- editor.converter.headerEditors.push({
28368
- id: headerId,
28369
- editor: editorSection
28370
- });
28055
+ const pageNumberIndex = currentPageNumber - 1;
28056
+ const editorKey = getHeaderFooterEditorKey({ pageNumber: pageNumberIndex, isHeader: true, isFirstHeader });
28057
+ let editorSection = null;
28058
+ const { headerFooterEditors } = editor.storage.pagination;
28059
+ if (headerFooterEditors.has(editorKey) && editor.converter.headerEditors[pageNumberIndex]) {
28060
+ const editorData = headerFooterEditors.get(editorKey);
28061
+ editorSection = editorData.editor;
28062
+ editorContainer = editorSection.element;
28063
+ } else {
28064
+ editorSection = createHeaderFooterEditor({
28065
+ editor,
28066
+ data,
28067
+ editorContainer,
28068
+ appendToBody: false,
28069
+ sectionId: headerId,
28070
+ type: "header",
28071
+ availableHeight,
28072
+ currentPageNumber
28073
+ });
28074
+ editor.converter.headerEditors.push({ id: headerId, editor: editorSection });
28075
+ headerFooterEditors.set(editorKey, { editor: editorSection });
28076
+ broadcastEditorEvents(editor, editorSection);
28077
+ }
28371
28078
  editorSection.setEditable(false, false);
28372
- broadcastEditorEvents(editor, editorSection);
28373
- editorContainer.className = "pagination-section-header";
28079
+ editorContainer.classList.add("pagination-section-header");
28374
28080
  editorContainer.style.paddingTop = headerMargin + "px";
28375
28081
  editorContainer.style.paddingLeft = pageMargins.left * 96 + "px";
28376
28082
  editorContainer.style.paddingRight = pageMargins.right * 96 + "px";
@@ -28383,12 +28089,12 @@ function createHeader(pageMargins, pageSize, sectionData, headerId, editor, curr
28383
28089
  headerHeight
28384
28090
  };
28385
28091
  }
28386
- function createFooter(pageMargins, pageSize, sectionData, footerId, editor, currentPageNumber) {
28387
- const footerDef = sectionData.footers?.[footerId];
28092
+ function createFooter(pageMargins, pageSize, sectionData, footerId, editor, currentPageNumber, isLastFooter = false) {
28093
+ const footerDef = sectionData?.footers?.[footerId];
28388
28094
  const minFooterHeight = pageMargins.bottom * 96;
28389
28095
  const footerPaddingFromEdge = pageMargins.footer * 96;
28390
28096
  const footerHeight = Math.max(footerDef?.height || 0, minFooterHeight - footerPaddingFromEdge);
28391
- const editorContainer = document.createElement("div");
28097
+ let editorContainer = document.createElement("div");
28392
28098
  if (!footerId && !editor.converter.footerIds["default"]) {
28393
28099
  footerId = "rId" + generateDocxRandomId();
28394
28100
  editor.converter.footerIds["default"] = footerId;
@@ -28400,23 +28106,31 @@ function createFooter(pageMargins, pageSize, sectionData, footerId, editor, curr
28400
28106
  };
28401
28107
  }
28402
28108
  const data = editor.converter.footers[footerId];
28403
- const editorSection = createHeaderFooterEditor({
28404
- editor,
28405
- data,
28406
- editorContainer,
28407
- appendToBody: false,
28408
- sectionId: footerId,
28409
- type: "footer",
28410
- availableHeight: footerHeight,
28411
- currentPageNumber
28412
- });
28413
- editor.converter.footerEditors.push({
28414
- id: footerId,
28415
- editor: editorSection
28416
- });
28109
+ const pageNumberIndex = currentPageNumber - 1;
28110
+ const editorKey = getHeaderFooterEditorKey({ pageNumber: pageNumberIndex, isFooter: true, isLastFooter });
28111
+ let editorSection = null;
28112
+ const { headerFooterEditors } = editor.storage.pagination;
28113
+ if (headerFooterEditors.has(editorKey) && editor.converter.footerEditors[pageNumberIndex]) {
28114
+ const editorData = headerFooterEditors.get(editorKey);
28115
+ editorSection = editorData.editor;
28116
+ editorContainer = editorSection.element;
28117
+ } else {
28118
+ editorSection = createHeaderFooterEditor({
28119
+ editor,
28120
+ data,
28121
+ editorContainer,
28122
+ appendToBody: false,
28123
+ sectionId: footerId,
28124
+ type: "footer",
28125
+ availableHeight: footerHeight,
28126
+ currentPageNumber
28127
+ });
28128
+ editor.converter.footerEditors.push({ id: footerId, editor: editorSection });
28129
+ headerFooterEditors.set(editorKey, { editor: editorSection });
28130
+ broadcastEditorEvents(editor, editorSection);
28131
+ }
28417
28132
  editorSection.setEditable(false, false);
28418
- broadcastEditorEvents(editor, editorSection);
28419
- editorContainer.className = "pagination-section-footer";
28133
+ editorContainer.classList.add("pagination-section-footer");
28420
28134
  editorContainer.style.height = footerHeight + "px";
28421
28135
  editorContainer.style.marginBottom = footerPaddingFromEdge + "px";
28422
28136
  editorContainer.style.paddingLeft = pageMargins.left * 96 + "px";
@@ -28429,10 +28143,28 @@ function createFooter(pageMargins, pageSize, sectionData, footerId, editor, curr
28429
28143
  footerHeight: footerHeight + footerPaddingFromEdge
28430
28144
  };
28431
28145
  }
28146
+ const getHeaderFooterEditorKey = ({
28147
+ pageNumber,
28148
+ isHeader,
28149
+ isFooter,
28150
+ isFirstHeader = false,
28151
+ isLastFooter = false
28152
+ }) => {
28153
+ if (isFirstHeader) return `first-header-${pageNumber}`;
28154
+ if (isLastFooter) return `last-footer-${pageNumber}`;
28155
+ if (isHeader) return `header-${pageNumber}`;
28156
+ if (isFooter) return `footer-${pageNumber}`;
28157
+ return void 0;
28158
+ };
28432
28159
  const onHeaderFooterDblClick = (editor, currentFocusedSectionEditor) => {
28433
28160
  if (editor.options.documentMode !== "editing") return;
28434
28161
  editor.setEditable(false, false);
28435
- toggleHeaderFooterEditMode(editor, currentFocusedSectionEditor, true);
28162
+ toggleHeaderFooterEditMode({
28163
+ editor,
28164
+ focusedSectionEditor: currentFocusedSectionEditor,
28165
+ isEditMode: true,
28166
+ documentMode: editor.options.documentMode
28167
+ });
28436
28168
  };
28437
28169
  function createPageBreak({ editor, header, footer, footerBottom = null, isFirstHeader, isLastFooter, isInTable: isInTable2 = false }) {
28438
28170
  const { pageSize, pageMargins } = editor.converter.pageStyles;
@@ -28987,7 +28719,7 @@ const Search = Extension.create({
28987
28719
  }
28988
28720
  });
28989
28721
  const NodeResizerKey = new PluginKey("node-resizer");
28990
- const nodeResizer = (nodeNames = ["image"]) => {
28722
+ const nodeResizer = (nodeNames = ["image"], editor) => {
28991
28723
  let resizeState = {
28992
28724
  dragging: false,
28993
28725
  startX: 0,
@@ -29012,8 +28744,13 @@ const nodeResizer = (nodeNames = ["image"]) => {
29012
28744
  if (tr.getMeta(NodeResizerKey)) {
29013
28745
  return oldState;
29014
28746
  }
29015
- const decorations = [];
28747
+ if (typeof document === "undefined" || editor.options.isHeadless) return oldState;
29016
28748
  const { selection } = newState;
28749
+ const node = selection.node;
28750
+ if (!node || !nodeNames.includes(node.type.name)) {
28751
+ return DecorationSet.empty;
28752
+ }
28753
+ const decorations = [];
29017
28754
  if (nodeNames.includes(selection.node?.type.name)) {
29018
28755
  decorations.push(
29019
28756
  Decoration.node(selection.from, selection.to, {
@@ -29216,7 +28953,7 @@ const nodeResizer = (nodeNames = ["image"]) => {
29216
28953
  const NodeResizer = Extension.create({
29217
28954
  name: "nodeResizer",
29218
28955
  addPmPlugins() {
29219
- return [nodeResizer(["image"])];
28956
+ return [nodeResizer(["image"], this.editor)];
29220
28957
  }
29221
28958
  });
29222
28959
  const getRichTextExtensions = () => {