@harbour-enterprises/superdoc 1.0.0-beta.99 → 1.0.0-next.1

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 (28) hide show
  1. package/dist/chunks/{PdfViewer-DF-v5Yrr.es.js → PdfViewer-BKujh9gl.es.js} +1 -1
  2. package/dist/chunks/{PdfViewer-BtuTHUW7.cjs → PdfViewer-Cu04k0JZ.cjs} +1 -1
  3. package/dist/chunks/{index-BBu9BBvp.cjs → index-CZ4149Px.cjs} +3 -3
  4. package/dist/chunks/{index-CJy3FxL7.es.js → index-Cl0tjE1C.es.js} +3 -3
  5. package/dist/chunks/{index-BB0msI45-DUPBw4Bh.es.js → index-Dlj3l0Hk-BuYH_UIe.es.js} +1 -1
  6. package/dist/chunks/{index-BB0msI45-CPU6Ak2R.cjs → index-Dlj3l0Hk-CJ0YBOja.cjs} +1 -1
  7. package/dist/chunks/{super-editor.es-C04sFzVD.cjs → super-editor.es-CjRtsxTt.cjs} +973 -178
  8. package/dist/chunks/{super-editor.es-BiaFIbw-.es.js → super-editor.es-D0WByw5h.es.js} +973 -178
  9. package/dist/packages/superdoc/src/core/SuperDoc.d.ts.map +1 -1
  10. package/dist/super-editor/ai-writer.es.js +2 -2
  11. package/dist/super-editor/chunks/{converter-B_cVJPnh.js → converter-BS4FD8AG.js} +12 -6
  12. package/dist/super-editor/chunks/{docx-zipper-fPWx7kV0.js → docx-zipper-DpiCpt0d.js} +1 -1
  13. package/dist/super-editor/chunks/{editor-DS9z42Je.js → editor-BeacbTQe.js} +963 -170
  14. package/dist/super-editor/chunks/{index-BB0msI45.js → index-Dlj3l0Hk.js} +1 -1
  15. package/dist/super-editor/chunks/{toolbar-aIFlIr6h.js → toolbar-BNQDvBCn.js} +2 -2
  16. package/dist/super-editor/converter.es.js +1 -1
  17. package/dist/super-editor/docx-zipper.es.js +2 -2
  18. package/dist/super-editor/editor.es.js +3 -3
  19. package/dist/super-editor/file-zipper.es.js +1 -1
  20. package/dist/super-editor/super-editor.es.js +10 -10
  21. package/dist/super-editor/toolbar.es.js +2 -2
  22. package/dist/super-editor.cjs +1 -1
  23. package/dist/super-editor.es.js +1 -1
  24. package/dist/superdoc.cjs +2 -2
  25. package/dist/superdoc.es.js +2 -2
  26. package/dist/superdoc.umd.js +975 -180
  27. package/dist/superdoc.umd.js.map +1 -1
  28. package/package.json +10 -1
@@ -9,11 +9,11 @@ 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, _editor, _stateValidators, _xmlValidators, _requiredNodeTypes, _requiredMarkTypes, _SuperValidator_instances, initializeValidators_fn, collectValidatorRequirements_fn, analyzeDocument_fn, dispatchWithFallback_fn, _commandService, _Editor_instances, initContainerElement_fn, init_fn, initRichText_fn, onFocus_fn, checkHeadless_fn, registerCopyHandler_fn, insertNewFileData_fn, getPluginKeyName_fn, createExtensionService_fn, createCommandService_fn, createConverter_fn, initMedia_fn, initFonts_fn, checkFonts_fn, determineUnsupportedFonts_fn, createSchema_fn, generatePmData_fn, createView_fn, onCollaborationReady_fn, initComments_fn, dispatchTransaction_fn, handleNodeSelection_fn, prepareDocumentForImport_fn, prepareDocumentForExport_fn, endCollaboration_fn, validateDocumentInit_fn, validateDocumentExport_fn, initDevTools_fn, _map, _editor2, _descriptors, _collections, _editorEntries, _maxCachedEditors, _editorAccessOrder, _pendingCreations, _cacheHits, _cacheMisses, _evictions, _HeaderFooterEditorManager_instances, hasConverter_fn, extractCollections_fn, collectDescriptors_fn, teardownMissingEditors_fn, teardownEditors_fn, createEditor_fn, createEditorContainer_fn, registerConverterEditor_fn, unregisterConverterEditor_fn, updateAccessOrder_fn, enforceCacheSizeLimit_fn, _manager, _mediaFiles, _blockCache, _HeaderFooterLayoutAdapter_instances, getBlocks_fn, getConverterContext_fn, _selectionOverlay, _activeEditorHost, _activeDecorationContainer, _activeRegion, _borderLine, _dimmingOverlay, _EditorOverlayManager_instances, findDecorationContainer_fn, ensureEditorHost_fn, positionEditorHost_fn, hideDimmingOverlay_fn, showHeaderFooterBorder_fn, hideHeaderFooterBorder_fn, _instances, _options, _editor3, _visibleHost, _viewportHost, _painterHost, _selectionOverlay2, _hiddenHost, _layoutOptions, _layoutState, _domPainter, _dragHandlerCleanup, _layoutError, _layoutErrorState, _errorBanner, _errorBannerMessage, _telemetryEmitter, _renderScheduled, _pendingDocChange, _isRerendering, _selectionUpdateScheduled, _remoteCursorUpdateScheduled, _rafHandle, _editorListeners, _sectionMetadata, _documentMode, _inputBridge, _trackedChangesMode, _trackedChangesEnabled, _trackedChangesOverrides, _headerFooterManager, _headerFooterAdapter, _headerFooterIdentifier, _multiSectionIdentifier, _headerLayoutResults, _footerLayoutResults, _headerLayoutsByRId, _footerLayoutsByRId, _headerDecorationProvider, _footerDecorationProvider, _headerFooterManagerCleanups, _headerRegions, _footerRegions, _session, _activeHeaderFooterEditor, _overlayManager, _hoverOverlay, _hoverTooltip, _modeBanner, _ariaLiveRegion, _hoverRegion, _clickCount, _lastClickTime, _lastClickPosition, _lastSelectedImageBlockId, _dragAnchor, _isDragging, _dragExtensionMode, _cellAnchor, _cellDragMode, _remoteCursorState, _remoteCursorElements, _remoteCursorDirty, _remoteCursorOverlay, _localSelectionLayer, _awarenessCleanup, _scrollCleanup, _scrollTimeout, _lastRemoteCursorRenderTime, _remoteCursorThrottleTimeout, _PresentationEditor_instances, collectCommentPositions_fn, aggregateLayoutBounds_fn, safeCleanup_fn, setupEditorListeners_fn, setupCollaborationCursors_fn, updateLocalAwarenessCursor_fn, normalizeAwarenessStates_fn, getFallbackColor_fn, getValidatedColor_fn, scheduleRemoteCursorUpdate_fn, scheduleRemoteCursorReRender_fn, updateRemoteCursors_fn, renderRemoteCursors_fn, renderRemoteCaret_fn, renderRemoteCursorLabel_fn, renderRemoteSelection_fn, setupPointerHandlers_fn, setupDragHandlers_fn, focusEditorAfterImageSelection_fn, setupInputBridge_fn, initHeaderFooterRegistry_fn, _handlePointerDown, getFirstTextPosition_fn, registerPointerClick_fn, getCellPosFromTableHit_fn, getTablePosFromHit_fn, shouldUseCellSelection_fn, setCellAnchor_fn, clearCellAnchor_fn, hitTestTable_fn, selectWordAt_fn, selectParagraphAt_fn, calculateExtendedSelection_fn, isWordCharacter_fn, _handlePointerMove, _handlePointerLeave, _handlePointerUp, _handleDragOver, _handleDrop, _handleDoubleClick, _handleKeyDown, focusHeaderFooterShortcut_fn, scheduleRerender_fn, flushRerenderQueue_fn, rerender_fn, ensurePainter_fn, scheduleSelectionUpdate_fn, updateSelection_fn, resolveLayoutOptions_fn, buildHeaderFooterInput_fn, computeHeaderFooterConstraints_fn, layoutPerRIdHeaderFooters_fn, updateDecorationProviders_fn, createDecorationProvider_fn, findHeaderFooterPageForPageNumber_fn, computeDecorationBox_fn, computeExpectedSectionType_fn, rebuildHeaderFooterRegions_fn, hitTestHeaderFooterRegion_fn, pointInRegion_fn, activateHeaderFooterRegion_fn, enterHeaderFooterMode_fn, exitHeaderFooterMode_fn, getActiveDomTarget_fn, emitHeaderFooterModeChanged_fn, emitHeaderFooterEditingContext_fn, updateAwarenessSession_fn, updateModeBanner_fn, announce_fn, validateHeaderFooterEditPermission_fn, emitHeaderFooterEditBlocked_fn, resolveDescriptorForRegion_fn, createDefaultHeaderFooter_fn, getPageElement_fn, scrollPageIntoView_fn, computeAnchorMap_fn, waitForPageMount_fn, getBodyPageHeight_fn, getHeaderFooterPageHeight_fn, applyDomCorrectionToRects_fn, renderCellSelectionOverlay_fn, renderSelectionRects_fn, renderHoverRegion_fn, clearHoverRegion_fn, renderCaretOverlay_fn, getHeaderFooterContext_fn, computeHeaderFooterSelectionRects_fn, syncTrackedChangesPreferences_fn, deriveTrackedChangesMode_fn, deriveTrackedChangesEnabled_fn, getTrackChangesPluginState_fn, computeDefaultLayoutDefaults_fn, parseColumns_fn, inchesToPx_fn, applyZoom_fn, createLayoutMetrics_fn, getPageOffsetX_fn, convertPageLocalToOverlayCoords_fn, computeDomCaretPageLocal_fn, normalizeClientPoint_fn, computeCaretLayoutRectGeometry_fn, computeCaretLayoutRect_fn, computeCaretLayoutRectFromDOM_fn, computeTableCaretLayoutRect_fn, findLineContainingPos_fn, lineHeightBeforeIndex_fn, getCurrentPageIndex_fn, findRegionForPage_fn, handleLayoutError_fn, decorateError_fn, showLayoutErrorBanner_fn, dismissErrorBanner_fn, createHiddenHost_fn, _windowRoot, _layoutSurfaces, _getTargetDom, _isEditable, _onTargetChanged, _listeners, _currentTarget, _destroyed, _useWindowFallback, _PresentationInputBridge_instances, addListener_fn, dispatchToTarget_fn, forwardKeyboardEvent_fn, forwardTextEvent_fn, forwardCompositionEvent_fn, forwardContextMenu_fn, isEventOnActiveTarget_fn, shouldSkipSurface_fn, isInLayoutSurface_fn, getListenerTargets_fn, isPlainCharacterKey_fn, _DocumentSectionView_instances, init_fn2, addToolTip_fn, _ParagraphNodeView_instances, checkShouldUpdate_fn, updateHTMLAttributes_fn, updateDOMStyles_fn, resolveNeighborParagraphProperties_fn, updateListStyles_fn, initList_fn, checkIsList_fn, createMarker_fn, createSeparator_fn, calculateTabSeparatorStyle_fn, calculateMarkerStyle_fn, removeList_fn, getParagraphContext_fn, scheduleAnimation_fn, cancelScheduledAnimation_fn, _FieldAnnotationView_instances, createAnnotation_fn, _AutoPageNumberNodeView_instances, renderDom_fn, scheduleUpdateNodeStyle_fn, _VectorShapeView_instances, ensureParentPositioned_fn, _ShapeGroupView_instances, ensureParentPositioned_fn2;
12
+ var _Attribute_static, getGlobalAttributes_fn, getNodeAndMarksAttributes_fn, _Schema_static, createNodesSchema_fn, createMarksSchema_fn, _events, _ExtensionService_instances, setupExtensions_fn, attachEditorEvents_fn, _editor, _stateValidators, _xmlValidators, _requiredNodeTypes, _requiredMarkTypes, _SuperValidator_instances, initializeValidators_fn, collectValidatorRequirements_fn, analyzeDocument_fn, dispatchWithFallback_fn, _commandService, _Editor_instances, initContainerElement_fn, init_fn, initRichText_fn, onFocus_fn, checkHeadless_fn, registerCopyHandler_fn, insertNewFileData_fn, getPluginKeyName_fn, createExtensionService_fn, createCommandService_fn, createConverter_fn, initMedia_fn, initFonts_fn, checkFonts_fn, determineUnsupportedFonts_fn, createSchema_fn, generatePmData_fn, createView_fn, onCollaborationReady_fn, initComments_fn, dispatchTransaction_fn, handleNodeSelection_fn, prepareDocumentForImport_fn, prepareDocumentForExport_fn, endCollaboration_fn, validateDocumentInit_fn, validateDocumentExport_fn, initDevTools_fn, _map, _editor2, _descriptors, _collections, _editorEntries, _maxCachedEditors, _editorAccessOrder, _pendingCreations, _cacheHits, _cacheMisses, _evictions, _HeaderFooterEditorManager_instances, hasConverter_fn, extractCollections_fn, collectDescriptors_fn, teardownMissingEditors_fn, teardownEditors_fn, createEditor_fn, createEditorContainer_fn, registerConverterEditor_fn, unregisterConverterEditor_fn, updateAccessOrder_fn, enforceCacheSizeLimit_fn, _manager, _mediaFiles, _blockCache, _HeaderFooterLayoutAdapter_instances, getBlocks_fn, getConverterContext_fn, _selectionOverlay, _activeEditorHost, _activeDecorationContainer, _activeRegion, _borderLine, _dimmingOverlay, _EditorOverlayManager_instances, findDecorationContainer_fn, ensureEditorHost_fn, positionEditorHost_fn, hideDimmingOverlay_fn, showHeaderFooterBorder_fn, hideHeaderFooterBorder_fn, _instances, _options, _editor3, _visibleHost, _viewportHost, _painterHost, _selectionOverlay2, _hiddenHost, _layoutOptions, _layoutState, _domPainter, _pageGeometryHelper, _dragHandlerCleanup, _layoutError, _layoutErrorState, _errorBanner, _errorBannerMessage, _telemetryEmitter, _renderScheduled, _pendingDocChange, _isRerendering, _selectionUpdateScheduled, _remoteCursorUpdateScheduled, _rafHandle, _editorListeners, _sectionMetadata, _documentMode, _inputBridge, _trackedChangesMode, _trackedChangesEnabled, _trackedChangesOverrides, _headerFooterManager, _headerFooterAdapter, _headerFooterIdentifier, _multiSectionIdentifier, _headerLayoutResults, _footerLayoutResults, _headerLayoutsByRId, _footerLayoutsByRId, _headerDecorationProvider, _footerDecorationProvider, _headerFooterManagerCleanups, _headerRegions, _footerRegions, _session, _activeHeaderFooterEditor, _overlayManager, _hoverOverlay, _hoverTooltip, _modeBanner, _ariaLiveRegion, _hoverRegion, _clickCount, _lastClickTime, _lastClickPosition, _lastSelectedImageBlockId, _dragAnchor, _isDragging, _dragExtensionMode, _cellAnchor, _cellDragMode, _remoteCursorState, _remoteCursorElements, _remoteCursorDirty, _remoteCursorOverlay, _localSelectionLayer, _awarenessCleanup, _scrollCleanup, _scrollTimeout, _lastRemoteCursorRenderTime, _remoteCursorThrottleTimeout, _PresentationEditor_instances, collectCommentPositions_fn, aggregateLayoutBounds_fn, safeCleanup_fn, setupEditorListeners_fn, setupCollaborationCursors_fn, updateLocalAwarenessCursor_fn, normalizeAwarenessStates_fn, getFallbackColor_fn, getValidatedColor_fn, scheduleRemoteCursorUpdate_fn, scheduleRemoteCursorReRender_fn, updateRemoteCursors_fn, renderRemoteCursors_fn, renderRemoteCaret_fn, renderRemoteCursorLabel_fn, renderRemoteSelection_fn, setupPointerHandlers_fn, setupDragHandlers_fn, focusEditorAfterImageSelection_fn, setupInputBridge_fn, initHeaderFooterRegistry_fn, _handlePointerDown, getFirstTextPosition_fn, registerPointerClick_fn, getCellPosFromTableHit_fn, getTablePosFromHit_fn, shouldUseCellSelection_fn, setCellAnchor_fn, clearCellAnchor_fn, hitTestTable_fn, selectWordAt_fn, selectParagraphAt_fn, calculateExtendedSelection_fn, isWordCharacter_fn, _handlePointerMove, _handlePointerLeave, _handlePointerUp, _handleDragOver, _handleDrop, _handleDoubleClick, _handleKeyDown, focusHeaderFooterShortcut_fn, scheduleRerender_fn, flushRerenderQueue_fn, rerender_fn, ensurePainter_fn, scheduleSelectionUpdate_fn, updateSelection_fn, resolveLayoutOptions_fn, buildHeaderFooterInput_fn, computeHeaderFooterConstraints_fn, layoutPerRIdHeaderFooters_fn, updateDecorationProviders_fn, createDecorationProvider_fn, findHeaderFooterPageForPageNumber_fn, computeDecorationBox_fn, computeExpectedSectionType_fn, rebuildHeaderFooterRegions_fn, hitTestHeaderFooterRegion_fn, pointInRegion_fn, activateHeaderFooterRegion_fn, enterHeaderFooterMode_fn, exitHeaderFooterMode_fn, getActiveDomTarget_fn, emitHeaderFooterModeChanged_fn, emitHeaderFooterEditingContext_fn, updateAwarenessSession_fn, updateModeBanner_fn, announce_fn, validateHeaderFooterEditPermission_fn, emitHeaderFooterEditBlocked_fn, resolveDescriptorForRegion_fn, createDefaultHeaderFooter_fn, getPageElement_fn, scrollPageIntoView_fn, computeAnchorMap_fn, waitForPageMount_fn, getEffectivePageGap_fn, getBodyPageHeight_fn, getHeaderFooterPageHeight_fn, applyDomCorrectionToRects_fn, renderCellSelectionOverlay_fn, renderSelectionRects_fn, renderHoverRegion_fn, clearHoverRegion_fn, renderCaretOverlay_fn, getHeaderFooterContext_fn, computeHeaderFooterSelectionRects_fn, syncTrackedChangesPreferences_fn, deriveTrackedChangesMode_fn, deriveTrackedChangesEnabled_fn, getTrackChangesPluginState_fn, computeDefaultLayoutDefaults_fn, parseColumns_fn, inchesToPx_fn, applyZoom_fn, createLayoutMetrics_fn, getPageOffsetX_fn, convertPageLocalToOverlayCoords_fn, computeDomCaretPageLocal_fn, normalizeClientPoint_fn, computeCaretLayoutRectGeometry_fn, computeCaretLayoutRect_fn, computeCaretLayoutRectFromDOM_fn, computeTableCaretLayoutRect_fn, findLineContainingPos_fn, lineHeightBeforeIndex_fn, getCurrentPageIndex_fn, findRegionForPage_fn, handleLayoutError_fn, decorateError_fn, showLayoutErrorBanner_fn, dismissErrorBanner_fn, createHiddenHost_fn, _windowRoot, _layoutSurfaces, _getTargetDom, _isEditable, _onTargetChanged, _listeners, _currentTarget, _destroyed, _useWindowFallback, _PresentationInputBridge_instances, addListener_fn, dispatchToTarget_fn, forwardKeyboardEvent_fn, forwardTextEvent_fn, forwardCompositionEvent_fn, forwardContextMenu_fn, isEventOnActiveTarget_fn, shouldSkipSurface_fn, isInLayoutSurface_fn, getListenerTargets_fn, isPlainCharacterKey_fn, _DocumentSectionView_instances, init_fn2, addToolTip_fn, _ParagraphNodeView_instances, checkShouldUpdate_fn, updateHTMLAttributes_fn, updateDOMStyles_fn, resolveNeighborParagraphProperties_fn, updateListStyles_fn, initList_fn, checkIsList_fn, createMarker_fn, createSeparator_fn, calculateTabSeparatorStyle_fn, calculateMarkerStyle_fn, removeList_fn, getParagraphContext_fn, scheduleAnimation_fn, cancelScheduledAnimation_fn, _FieldAnnotationView_instances, createAnnotation_fn, _AutoPageNumberNodeView_instances, renderDom_fn, scheduleUpdateNodeStyle_fn, _VectorShapeView_instances, ensureParentPositioned_fn, _ShapeGroupView_instances, ensureParentPositioned_fn2;
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, N as NodeSelection, S as Selection, T as TextSelection, b as Slice, D as DOMSerializer, F as Fragment, c as DOMParser$1, d as Mark$1, e as dropPoint, A as AllSelection, p as process$1, B as Buffer2, f as callOrGet, g as getExtensionConfigField, h as getMarkType, i as getMarksFromSelection, j as getNodeType, k as getSchemaTypeNameByName, l as Schema$1, m as cleanSchemaItem, n as canSplit, o as defaultBlockAt$1, q as liftTarget, r as canJoin, s as joinPoint, t as replaceStep$1, R as ReplaceAroundStep$1, u as isTextSelection, v as getMarkRange, w as isMarkActive, x as isNodeActive, y as deleteProps, z as processContent, C as htmlHandler, E as ReplaceStep, G as twipsToInches, H as inchesToTwips, I as ptToTwips, J as getResolvedParagraphProperties, K as linesToTwips, L as changeListLevel, O as findParentNode, Q as isList, U as updateNumberingProperties, V as ListHelpers, W as isMacOS, X as isIOS, Y as getSchemaTypeByName, Z as inputRulesPlugin, _ as TrackDeleteMarkName$1, $ as TrackInsertMarkName$1, a0 as v4, a1 as TrackFormatMarkName$1, a2 as comments_module_events, a3 as findMark, a4 as objectIncludes, a5 as AddMarkStep, a6 as RemoveMarkStep, a7 as twipsToLines, a8 as pixelsToTwips, a9 as helpers, aa as posToDOMRect, ab as CommandService, ac as SuperConverter, ad as createDocument, ae as createDocFromMarkdown, af as createDocFromHTML, ag as EditorState, ah as isActive, ai as unflattenListsInHtml, aj as SelectionRange, ak as Transform, al as resolveParagraphProperties, am as _getReferencedTableStyles, an as parseSizeUnit, ao as minMax, ap as updateDOMAttributes, aq as findChildren$5, ar as generateRandomSigned32BitIntStrId, as as decodeRPrFromMarks, at as calculateResolvedParagraphProperties, au as resolveRunProperties, av as encodeCSSFromPPr, aw as twipsToPixels$2, ax as encodeCSSFromRPr, ay as generateOrderedListIndex, az as docxNumberingHelpers, aA as InputRule, aB as convertSizeToCSS, aC as findParentNodeClosestToPos, aD as isInTable$1, aE as generateDocxRandomId, aF as insertNewRelationship, aG as inchesToPixels, aH as kebabCase, aI as getUnderlineCssString } from "./converter-B_cVJPnh.js";
16
- import { D as DocxZipper } from "./docx-zipper-fPWx7kV0.js";
15
+ import { P as PluginKey, a as Plugin, M as Mapping, N as NodeSelection, S as Selection, T as TextSelection, b as Slice, D as DOMSerializer, F as Fragment, c as DOMParser$1, d as Mark$1, e as dropPoint, A as AllSelection, p as process$1, B as Buffer2, f as callOrGet, g as getExtensionConfigField, h as getMarkType, i as getMarksFromSelection, j as getNodeType, k as getSchemaTypeNameByName, l as Schema$1, m as cleanSchemaItem, n as canSplit, o as defaultBlockAt$1, q as liftTarget, r as canJoin, s as joinPoint, t as replaceStep$1, R as ReplaceAroundStep$1, u as isTextSelection, v as getMarkRange, w as isMarkActive, x as isNodeActive, y as deleteProps, z as processContent, C as htmlHandler, E as ReplaceStep, G as twipsToInches, H as inchesToTwips, I as ptToTwips, J as getResolvedParagraphProperties, K as linesToTwips, L as changeListLevel, O as findParentNode, Q as isList, U as updateNumberingProperties, V as ListHelpers, W as isMacOS, X as isIOS, Y as getSchemaTypeByName, Z as inputRulesPlugin, _ as TrackDeleteMarkName$1, $ as TrackInsertMarkName$1, a0 as v4, a1 as TrackFormatMarkName$1, a2 as comments_module_events, a3 as findMark, a4 as objectIncludes, a5 as AddMarkStep, a6 as RemoveMarkStep, a7 as twipsToLines, a8 as pixelsToTwips, a9 as helpers, aa as posToDOMRect, ab as CommandService, ac as SuperConverter, ad as createDocument, ae as createDocFromMarkdown, af as createDocFromHTML, ag as EditorState, ah as isActive, ai as unflattenListsInHtml, aj as SelectionRange, ak as Transform, al as resolveParagraphProperties, am as _getReferencedTableStyles, an as parseSizeUnit, ao as minMax, ap as updateDOMAttributes, aq as findChildren$5, ar as generateRandomSigned32BitIntStrId, as as decodeRPrFromMarks, at as calculateResolvedParagraphProperties, au as resolveRunProperties, av as encodeCSSFromPPr, aw as twipsToPixels$2, ax as encodeCSSFromRPr, ay as generateOrderedListIndex, az as docxNumberingHelpers, aA as InputRule, aB as convertSizeToCSS, aC as findParentNodeClosestToPos, aD as isInTable$1, aE as generateDocxRandomId, aF as insertNewRelationship, aG as inchesToPixels, aH as kebabCase, aI as getUnderlineCssString } from "./converter-BS4FD8AG.js";
16
+ import { D as DocxZipper } from "./docx-zipper-DpiCpt0d.js";
17
17
  import { ref, computed, createElementBlock, openBlock, withModifiers, Fragment as Fragment$1, renderList, normalizeClass, createCommentVNode, toDisplayString, createElementVNode, createApp } from "vue";
18
18
  var GOOD_LEAF_SIZE = 200;
19
19
  var RopeSequence = function RopeSequence2() {
@@ -9098,6 +9098,14 @@ const toggleNode = (typeOrName, toggleTypeOrName, attrs = {}) => ({ state, comma
9098
9098
  const selectAll = () => ({ state, dispatch }) => selectAll$1(state, dispatch);
9099
9099
  const deleteSelection = () => ({ state, tr, dispatch }) => {
9100
9100
  const { from: from2, to, empty: empty2 } = state.selection;
9101
+ if (typeof document !== "undefined" && document.getSelection) {
9102
+ const currentDomSelection = document.getSelection();
9103
+ const selectedLength = currentDomSelection?.toString?.().length;
9104
+ const isCollapsed = currentDomSelection?.isCollapsed;
9105
+ if (!isCollapsed && selectedLength === 1) {
9106
+ return false;
9107
+ }
9108
+ }
9101
9109
  if (empty2) {
9102
9110
  return deleteSelection$1(state, dispatch);
9103
9111
  }
@@ -11406,12 +11414,14 @@ const prepareCommentsForImport = (doc2, tr, schema, converter) => {
11406
11414
  importedId: node.attrs["w:id"]
11407
11415
  });
11408
11416
  if (type.name === "commentRangeStart") {
11409
- toMark.push({
11410
- commentId: resolvedCommentId,
11411
- importedId,
11412
- internal,
11413
- start: pos
11414
- });
11417
+ if (!matchingImportedComment?.isDone) {
11418
+ toMark.push({
11419
+ commentId: resolvedCommentId,
11420
+ importedId,
11421
+ internal,
11422
+ start: pos
11423
+ });
11424
+ }
11415
11425
  ensureFallbackComment({
11416
11426
  converter,
11417
11427
  matchingImportedComment,
@@ -13952,7 +13962,7 @@ const isHeadless = (editor) => {
13952
13962
  const shouldSkipNodeView = (editor) => {
13953
13963
  return isHeadless(editor);
13954
13964
  };
13955
- const summaryVersion = "1.0.0-beta.99";
13965
+ const summaryVersion = "1.0.0-next.1";
13956
13966
  const nodeKeys = ["group", "content", "marks", "inline", "atom", "defining", "code", "tableRole", "summary"];
13957
13967
  const markKeys = ["group", "inclusive", "excludes", "spanning", "code"];
13958
13968
  function mapAttributes(attrs) {
@@ -14315,11 +14325,11 @@ const _Editor = class _Editor extends EventEmitter {
14315
14325
  if (!this.options.isNewFile || !this.options.collaborationProvider) return;
14316
14326
  const provider = this.options.collaborationProvider;
14317
14327
  const postSyncInit = () => {
14318
- provider.off("synced", postSyncInit);
14328
+ provider.off?.("synced", postSyncInit);
14319
14329
  __privateMethod(this, _Editor_instances, insertNewFileData_fn).call(this);
14320
14330
  };
14321
14331
  if (provider.synced) __privateMethod(this, _Editor_instances, insertNewFileData_fn).call(this);
14322
- else provider.on("synced", postSyncInit);
14332
+ else provider.on?.("synced", postSyncInit);
14323
14333
  }
14324
14334
  /**
14325
14335
  * Replace content of editor that was created with loadFromSchema option
@@ -14744,7 +14754,7 @@ const _Editor = class _Editor extends EventEmitter {
14744
14754
  { default: remarkStringify },
14745
14755
  { default: remarkGfm }
14746
14756
  ] = await Promise.all([
14747
- import("./index-BB0msI45.js"),
14757
+ import("./index-Dlj3l0Hk.js"),
14748
14758
  import("./index-DRCvimau.js"),
14749
14759
  import("./index-C_x_N6Uh.js"),
14750
14760
  import("./index-D_sWOSiG.js"),
@@ -14949,7 +14959,7 @@ const _Editor = class _Editor extends EventEmitter {
14949
14959
  * Process collaboration migrations
14950
14960
  */
14951
14961
  processCollaborationMigrations() {
14952
- console.debug("[checkVersionMigrations] Current editor version", "1.0.0-beta.99");
14962
+ console.debug("[checkVersionMigrations] Current editor version", "1.0.0-next.1");
14953
14963
  if (!this.options.ydoc) return;
14954
14964
  const metaMap = this.options.ydoc.getMap("meta");
14955
14965
  let docVersion = metaMap.get("version");
@@ -18152,6 +18162,7 @@ function hydrateImageBlocks(blocks, mediaFiles) {
18152
18162
  if (cellChanged) {
18153
18163
  return {
18154
18164
  ...cell,
18165
+ // Cast to expected type - hydrateBlock preserves block kinds, just hydrates image sources
18155
18166
  blocks: hydratedBlocks.length > 0 ? hydratedBlocks : cell.blocks,
18156
18167
  paragraph: hydratedParagraph
18157
18168
  };
@@ -21772,7 +21783,7 @@ const computeParagraphAttrs = (para, styleContext, listCounterContext, converter
21772
21783
  };
21773
21784
  }
21774
21785
  const hasValidNumbering = rawNumberingProps && isValidNumberingId(rawNumberingProps.numId);
21775
- if (hasValidNumbering) {
21786
+ if (hasValidNumbering && rawNumberingProps) {
21776
21787
  const numberingProps = rawNumberingProps;
21777
21788
  const numId = numberingProps.numId;
21778
21789
  const ilvl = Number.isFinite(numberingProps.ilvl) ? Math.max(0, Math.floor(Number(numberingProps.ilvl))) : 0;
@@ -21812,6 +21823,8 @@ const computeParagraphAttrs = (para, styleContext, listCounterContext, converter
21812
21823
  const resolvedCounterValue = path[path.length - 1] ?? counterValue;
21813
21824
  const enrichedNumberingProps = {
21814
21825
  ...numberingProps,
21826
+ numId: numberingProps.numId,
21827
+ ilvl: numberingProps.ilvl,
21815
21828
  path,
21816
21829
  counterValue: resolvedCounterValue
21817
21830
  };
@@ -23908,7 +23921,7 @@ const parseTableCell = (args) => {
23908
23921
  context.nextBlockId,
23909
23922
  context.positions
23910
23923
  );
23911
- if (drawingBlock) {
23924
+ if (drawingBlock && drawingBlock.kind === "drawing") {
23912
23925
  blocks.push(drawingBlock);
23913
23926
  }
23914
23927
  continue;
@@ -23919,7 +23932,7 @@ const parseTableCell = (args) => {
23919
23932
  context.nextBlockId,
23920
23933
  context.positions
23921
23934
  );
23922
- if (drawingBlock) {
23935
+ if (drawingBlock && drawingBlock.kind === "drawing") {
23923
23936
  blocks.push(drawingBlock);
23924
23937
  }
23925
23938
  continue;
@@ -23930,7 +23943,7 @@ const parseTableCell = (args) => {
23930
23943
  context.nextBlockId,
23931
23944
  context.positions
23932
23945
  );
23933
- if (drawingBlock) {
23946
+ if (drawingBlock && drawingBlock.kind === "drawing") {
23934
23947
  blocks.push(drawingBlock);
23935
23948
  }
23936
23949
  continue;
@@ -23941,7 +23954,7 @@ const parseTableCell = (args) => {
23941
23954
  context.nextBlockId,
23942
23955
  context.positions
23943
23956
  );
23944
- if (drawingBlock) {
23957
+ if (drawingBlock && drawingBlock.kind === "drawing") {
23945
23958
  blocks.push(drawingBlock);
23946
23959
  }
23947
23960
  }
@@ -24396,7 +24409,19 @@ function toFlowBlocks(pmDoc, options) {
24396
24409
  bookmarks2,
24397
24410
  hyperlinkConfig2,
24398
24411
  themeColorsParam ?? themeColors,
24399
- paragraphConverter
24412
+ paragraphConverter,
24413
+ converterCtx ?? converterContext,
24414
+ {
24415
+ listCounterContext: { getListCounter, incrementListCounter, resetListCounter },
24416
+ converters: {
24417
+ paragraphToFlowBlocks: paragraphConverter,
24418
+ imageNodeToBlock,
24419
+ vectorShapeNodeToDrawingBlock,
24420
+ shapeGroupNodeToDrawingBlock,
24421
+ shapeContainerNodeToDrawingBlock,
24422
+ shapeTextboxNodeToDrawingBlock
24423
+ }
24424
+ }
24400
24425
  );
24401
24426
  const handlerContext = {
24402
24427
  blocks,
@@ -24417,6 +24442,7 @@ function toFlowBlocks(pmDoc, options) {
24417
24442
  currentParagraphIndex: 0
24418
24443
  },
24419
24444
  converters: {
24445
+ // Type assertion needed due to signature mismatch between actual function and type definition
24420
24446
  paragraphToFlowBlocks: paragraphConverter,
24421
24447
  tableNodeToBlock: tableConverter,
24422
24448
  imageNodeToBlock,
@@ -24512,6 +24538,7 @@ function paragraphToFlowBlocks(para, nextBlockId, positions, defaultFont, defaul
24512
24538
  {
24513
24539
  listCounterContext,
24514
24540
  converters: {
24541
+ // Type assertion needed due to signature mismatch between actual function and type definition
24515
24542
  paragraphToFlowBlocks: paragraphToFlowBlocks$1,
24516
24543
  imageNodeToBlock,
24517
24544
  vectorShapeNodeToDrawingBlock,
@@ -24525,7 +24552,7 @@ function paragraphToFlowBlocks(para, nextBlockId, positions, defaultFont, defaul
24525
24552
  converterContext
24526
24553
  );
24527
24554
  }
24528
- function tableNodeToBlock(node, nextBlockId, positions, defaultFont, defaultSize, styleContext, trackedChanges, bookmarks, hyperlinkConfig, themeColors, converterContext) {
24555
+ function tableNodeToBlock(node, nextBlockId, positions, defaultFont, defaultSize, styleContext, trackedChanges, bookmarks, hyperlinkConfig, themeColors, _paragraphToFlowBlocksParam, converterContext, options) {
24529
24556
  return tableNodeToBlock$1(
24530
24557
  node,
24531
24558
  nextBlockId,
@@ -24539,8 +24566,9 @@ function tableNodeToBlock(node, nextBlockId, positions, defaultFont, defaultSize
24539
24566
  themeColors,
24540
24567
  paragraphToFlowBlocks,
24541
24568
  converterContext,
24542
- {
24569
+ options ?? {
24543
24570
  converters: {
24571
+ // Type assertion needed due to signature mismatch between actual function and type definition
24544
24572
  paragraphToFlowBlocks: paragraphToFlowBlocks$1,
24545
24573
  imageNodeToBlock,
24546
24574
  vectorShapeNodeToDrawingBlock,
@@ -27120,7 +27148,7 @@ const containerStyles = {
27120
27148
  alignItems: "center",
27121
27149
  background: "transparent",
27122
27150
  padding: "0",
27123
- gap: "24px",
27151
+ // gap is set dynamically by renderer based on pageGap option (default: 24px)
27124
27152
  overflowY: "auto"
27125
27153
  };
27126
27154
  const containerStylesHorizontal = {
@@ -27130,7 +27158,7 @@ const containerStylesHorizontal = {
27130
27158
  justifyContent: "safe center",
27131
27159
  background: "transparent",
27132
27160
  padding: "0",
27133
- gap: "20px",
27161
+ // gap is set dynamically by renderer based on pageGap option (default: 20px for horizontal)
27134
27162
  overflowX: "auto",
27135
27163
  minHeight: "100%"
27136
27164
  };
@@ -28844,6 +28872,49 @@ const hashParagraphBorders$1 = (borders) => {
28844
28872
  if (borders.left) parts.push(`l:[${hashParagraphBorder$1(borders.left)}]`);
28845
28873
  return parts.join(";");
28846
28874
  };
28875
+ const isNoneBorder$1 = (value) => {
28876
+ return typeof value === "object" && value !== null && "none" in value && value.none === true;
28877
+ };
28878
+ const isBorderSpec$1 = (value) => {
28879
+ return typeof value === "object" && value !== null && !("none" in value);
28880
+ };
28881
+ const hashBorderSpec$1 = (border) => {
28882
+ const parts = [];
28883
+ if (border.style !== void 0) parts.push(`s:${border.style}`);
28884
+ if (border.width !== void 0) parts.push(`w:${border.width}`);
28885
+ if (border.color !== void 0) parts.push(`c:${border.color}`);
28886
+ if (border.space !== void 0) parts.push(`sp:${border.space}`);
28887
+ return parts.join(",");
28888
+ };
28889
+ const hashTableBorderValue$1 = (borderValue) => {
28890
+ if (borderValue === void 0) return "";
28891
+ if (borderValue === null) return "null";
28892
+ if (isNoneBorder$1(borderValue)) return "none";
28893
+ if (isBorderSpec$1(borderValue)) {
28894
+ return hashBorderSpec$1(borderValue);
28895
+ }
28896
+ return "";
28897
+ };
28898
+ const hashTableBorders$1 = (borders) => {
28899
+ if (!borders) return "";
28900
+ const parts = [];
28901
+ if (borders.top !== void 0) parts.push(`t:[${hashTableBorderValue$1(borders.top)}]`);
28902
+ if (borders.right !== void 0) parts.push(`r:[${hashTableBorderValue$1(borders.right)}]`);
28903
+ if (borders.bottom !== void 0) parts.push(`b:[${hashTableBorderValue$1(borders.bottom)}]`);
28904
+ if (borders.left !== void 0) parts.push(`l:[${hashTableBorderValue$1(borders.left)}]`);
28905
+ if (borders.insideH !== void 0) parts.push(`ih:[${hashTableBorderValue$1(borders.insideH)}]`);
28906
+ if (borders.insideV !== void 0) parts.push(`iv:[${hashTableBorderValue$1(borders.insideV)}]`);
28907
+ return parts.join(";");
28908
+ };
28909
+ const hashCellBorders$1 = (borders) => {
28910
+ if (!borders) return "";
28911
+ const parts = [];
28912
+ if (borders.top) parts.push(`t:[${hashBorderSpec$1(borders.top)}]`);
28913
+ if (borders.right) parts.push(`r:[${hashBorderSpec$1(borders.right)}]`);
28914
+ if (borders.bottom) parts.push(`b:[${hashBorderSpec$1(borders.bottom)}]`);
28915
+ if (borders.left) parts.push(`l:[${hashBorderSpec$1(borders.left)}]`);
28916
+ return parts.join(";");
28917
+ };
28847
28918
  const hasStringProp = (run, prop) => {
28848
28919
  return prop in run && typeof run[prop] === "string";
28849
28920
  };
@@ -28933,6 +29004,7 @@ function isMinimalWordLayout(value) {
28933
29004
  const LIST_MARKER_GAP$1 = 8;
28934
29005
  const DEFAULT_TAB_INTERVAL_PX$1 = 48;
28935
29006
  const DEFAULT_PAGE_HEIGHT_PX = 1056;
29007
+ const DEFAULT_VIRTUALIZED_PAGE_GAP$1 = 72;
28936
29008
  const COMMENT_EXTERNAL_COLOR = "#B1124B";
28937
29009
  const COMMENT_INTERNAL_COLOR = "#078383";
28938
29010
  const COMMENT_INACTIVE_ALPHA = "22";
@@ -29062,10 +29134,11 @@ const _DomPainter = class _DomPainter {
29062
29134
  this.totalPages = 0;
29063
29135
  this.linkIdCounter = 0;
29064
29136
  this.pendingTooltips = /* @__PURE__ */ new WeakMap();
29137
+ this.pageGap = 24;
29065
29138
  this.virtualEnabled = false;
29066
29139
  this.virtualWindow = 5;
29067
29140
  this.virtualOverscan = 0;
29068
- this.virtualGap = 72;
29141
+ this.virtualGap = DEFAULT_VIRTUALIZED_PAGE_GAP$1;
29069
29142
  this.virtualPaddingTop = null;
29070
29143
  this.topSpacerEl = null;
29071
29144
  this.bottomSpacerEl = null;
@@ -29084,13 +29157,14 @@ const _DomPainter = class _DomPainter {
29084
29157
  this.blockLookup = this.buildBlockLookup(blocks, measures);
29085
29158
  this.headerProvider = options.headerProvider;
29086
29159
  this.footerProvider = options.footerProvider;
29160
+ const defaultGap = this.layoutMode === "horizontal" ? 20 : 24;
29161
+ this.pageGap = typeof options.pageGap === "number" && Number.isFinite(options.pageGap) ? Math.max(0, options.pageGap) : defaultGap;
29087
29162
  if (this.layoutMode === "vertical" && options.virtualization?.enabled) {
29088
29163
  this.virtualEnabled = true;
29089
29164
  this.virtualWindow = Math.max(1, options.virtualization.window ?? 5);
29090
29165
  this.virtualOverscan = Math.max(0, options.virtualization.overscan ?? 0);
29091
- if (typeof options.virtualization.gap === "number" && Number.isFinite(options.virtualization.gap)) {
29092
- this.virtualGap = Math.max(0, options.virtualization.gap);
29093
- }
29166
+ const hasExplicitVirtualGap = typeof options.virtualization.gap === "number" && Number.isFinite(options.virtualization.gap);
29167
+ this.virtualGap = hasExplicitVirtualGap ? Math.max(0, options.virtualization.gap) : DEFAULT_VIRTUALIZED_PAGE_GAP$1;
29094
29168
  if (typeof options.virtualization.paddingTop === "number" && Number.isFinite(options.virtualization.paddingTop)) {
29095
29169
  this.virtualPaddingTop = Math.max(0, options.virtualization.paddingTop);
29096
29170
  }
@@ -29191,6 +29265,7 @@ const _DomPainter = class _DomPainter {
29191
29265
  const mode = this.layoutMode;
29192
29266
  if (mode === "horizontal") {
29193
29267
  applyStyles$2(mount, containerStylesHorizontal);
29268
+ mount.style.gap = `${this.pageGap}px`;
29194
29269
  this.renderHorizontal(layout, mount);
29195
29270
  this.currentLayout = layout;
29196
29271
  this.pageStates = [];
@@ -29213,6 +29288,7 @@ const _DomPainter = class _DomPainter {
29213
29288
  this.changedBlocks.clear();
29214
29289
  return;
29215
29290
  }
29291
+ mount.style.gap = `${this.pageGap}px`;
29216
29292
  if (!this.currentLayout || this.pageStates.length === 0) {
29217
29293
  this.fullRender(layout);
29218
29294
  } else {
@@ -29537,9 +29613,15 @@ const _DomPainter = class _DomPainter {
29537
29613
  const container = existing ?? this.doc.createElement("div");
29538
29614
  container.className = className;
29539
29615
  container.innerHTML = "";
29540
- const offset2 = data.offset ?? (kind === "footer" ? pageEl.clientHeight - data.height : 0);
29616
+ const baseOffset = data.offset ?? (kind === "footer" ? pageEl.clientHeight - data.height : 0);
29541
29617
  const marginLeft = data.marginLeft ?? 0;
29542
29618
  const marginRight = page.margins?.right ?? 0;
29619
+ let effectiveHeight = data.height;
29620
+ let effectiveOffset = baseOffset;
29621
+ if (kind === "footer" && typeof data.contentHeight === "number" && Number.isFinite(data.contentHeight) && data.contentHeight > 0 && data.contentHeight > data.height) {
29622
+ effectiveHeight = data.contentHeight;
29623
+ effectiveOffset = baseOffset - (data.contentHeight - data.height);
29624
+ }
29543
29625
  container.style.position = "absolute";
29544
29626
  container.style.left = `${marginLeft}px`;
29545
29627
  if (typeof data.contentWidth === "number") {
@@ -29548,8 +29630,8 @@ const _DomPainter = class _DomPainter {
29548
29630
  container.style.width = `calc(100% - ${marginLeft + marginRight}px)`;
29549
29631
  }
29550
29632
  container.style.pointerEvents = "none";
29551
- container.style.height = `${data.height}px`;
29552
- container.style.top = `${Math.max(0, offset2)}px`;
29633
+ container.style.height = `${effectiveHeight}px`;
29634
+ container.style.top = `${Math.max(0, effectiveOffset)}px`;
29553
29635
  container.style.zIndex = "1";
29554
29636
  container.style.overflow = "visible";
29555
29637
  let footerYOffset = 0;
@@ -29558,7 +29640,7 @@ const _DomPainter = class _DomPainter {
29558
29640
  const fragHeight = "height" in f2 && typeof f2.height === "number" ? f2.height : this.estimateFragmentHeight(f2);
29559
29641
  return Math.max(max2, f2.y + Math.max(0, fragHeight));
29560
29642
  }, 0);
29561
- footerYOffset = Math.max(0, data.height - contentHeight);
29643
+ footerYOffset = Math.max(0, effectiveHeight - contentHeight);
29562
29644
  }
29563
29645
  const context = {
29564
29646
  pageNumber: page.number,
@@ -32048,6 +32130,25 @@ const deriveBlockVersion = (block) => {
32048
32130
  hash2 = hashNumber(hash2, cellBlocks.length);
32049
32131
  hash2 = hashNumber(hash2, cell.rowSpan ?? 1);
32050
32132
  hash2 = hashNumber(hash2, cell.colSpan ?? 1);
32133
+ if (cell.attrs) {
32134
+ const cellAttrs = cell.attrs;
32135
+ if (cellAttrs.borders) {
32136
+ hash2 = hashString(hash2, hashCellBorders$1(cellAttrs.borders));
32137
+ }
32138
+ if (cellAttrs.padding) {
32139
+ const p = cellAttrs.padding;
32140
+ hash2 = hashNumber(hash2, p.top ?? 0);
32141
+ hash2 = hashNumber(hash2, p.right ?? 0);
32142
+ hash2 = hashNumber(hash2, p.bottom ?? 0);
32143
+ hash2 = hashNumber(hash2, p.left ?? 0);
32144
+ }
32145
+ if (cellAttrs.verticalAlign) {
32146
+ hash2 = hashString(hash2, cellAttrs.verticalAlign);
32147
+ }
32148
+ if (cellAttrs.background) {
32149
+ hash2 = hashString(hash2, cellAttrs.background);
32150
+ }
32151
+ }
32051
32152
  for (const cellBlock of cellBlocks) {
32052
32153
  hash2 = hashString(hash2, cellBlock?.kind ?? "unknown");
32053
32154
  if (cellBlock?.kind === "paragraph") {
@@ -32093,6 +32194,18 @@ const deriveBlockVersion = (block) => {
32093
32194
  }
32094
32195
  }
32095
32196
  }
32197
+ if (tableBlock.attrs) {
32198
+ const tblAttrs = tableBlock.attrs;
32199
+ if (tblAttrs.borders) {
32200
+ hash2 = hashString(hash2, hashTableBorders$1(tblAttrs.borders));
32201
+ }
32202
+ if (tblAttrs.borderCollapse) {
32203
+ hash2 = hashString(hash2, tblAttrs.borderCollapse);
32204
+ }
32205
+ if (tblAttrs.cellSpacing !== void 0) {
32206
+ hash2 = hashNumber(hash2, tblAttrs.cellSpacing);
32207
+ }
32208
+ }
32096
32209
  return [block.id, tableBlock.rows.length, hash2.toString(16)].join("|");
32097
32210
  }
32098
32211
  return block.id;
@@ -32426,6 +32539,7 @@ const createDomPainter = (options) => {
32426
32539
  const painter = new DomPainter(options.blocks, options.measures, {
32427
32540
  pageStyles: options.pageStyles,
32428
32541
  layoutMode: options.layoutMode,
32542
+ pageGap: options.pageGap,
32429
32543
  headerProvider: options.headerProvider,
32430
32544
  footerProvider: options.footerProvider,
32431
32545
  virtualization: options.virtualization,
@@ -32844,7 +32958,7 @@ function isListItem(markerWidth, block) {
32844
32958
  return false;
32845
32959
  }
32846
32960
  const wordLayout = getWordLayoutConfig(block);
32847
- const hasListAttrs = block.attrs?.listItem != null || wordLayout?.marker != null;
32961
+ const hasListAttrs = block.attrs?.listItem != null || block.attrs?.numberingProperties != null || wordLayout?.marker != null;
32848
32962
  if (hasListAttrs) {
32849
32963
  return true;
32850
32964
  }
@@ -33274,7 +33388,7 @@ function computeNextSectionPropsAtBreak(blocks) {
33274
33388
  });
33275
33389
  return nextSectionPropsAtBreak;
33276
33390
  }
33277
- function scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight = 0) {
33391
+ function scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight = 0, maxFooterContentHeight = 0) {
33278
33392
  const next = { ...state };
33279
33393
  const calcRequiredTopMargin = (headerDistance, baseTop) => {
33280
33394
  if (maxHeaderContentHeight > 0) {
@@ -33282,6 +33396,12 @@ function scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight
33282
33396
  }
33283
33397
  return Math.max(baseTop, headerDistance);
33284
33398
  };
33399
+ const calcRequiredBottomMargin = (footerDistance, baseBottom) => {
33400
+ if (maxFooterContentHeight > 0) {
33401
+ return Math.max(baseBottom, footerDistance + maxFooterContentHeight);
33402
+ }
33403
+ return Math.max(baseBottom, footerDistance);
33404
+ };
33285
33405
  if (block.attrs?.isFirstSection && !next.hasAnyPages) {
33286
33406
  if (block.pageSize) {
33287
33407
  next.activePageSize = { w: block.pageSize.w, h: block.pageSize.h };
@@ -33302,7 +33422,7 @@ function scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight
33302
33422
  const footerDistance = Math.max(0, block.margins.footer);
33303
33423
  next.activeFooterDistance = footerDistance;
33304
33424
  next.pendingFooterDistance = footerDistance;
33305
- next.activeBottomMargin = Math.max(baseMargins.bottom, footerDistance);
33425
+ next.activeBottomMargin = calcRequiredBottomMargin(footerDistance, baseMargins.bottom);
33306
33426
  next.pendingBottomMargin = next.activeBottomMargin;
33307
33427
  }
33308
33428
  if (block.columns) {
@@ -33325,8 +33445,14 @@ function scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight
33325
33445
  next.pendingTopMargin = nextTop;
33326
33446
  next.pendingHeaderDistance = nextHeader;
33327
33447
  }
33328
- next.pendingBottomMargin = typeof footerPx === "number" ? Math.max(baseMargins.bottom, footerPx) : nextBottom;
33329
- next.pendingFooterDistance = typeof footerPx === "number" ? Math.max(0, footerPx) : nextFooter;
33448
+ if (typeof footerPx === "number") {
33449
+ const newFooterDist = Math.max(0, footerPx);
33450
+ next.pendingFooterDistance = newFooterDist;
33451
+ next.pendingBottomMargin = calcRequiredBottomMargin(newFooterDist, baseMargins.bottom);
33452
+ } else {
33453
+ next.pendingBottomMargin = nextBottom;
33454
+ next.pendingFooterDistance = nextFooter;
33455
+ }
33330
33456
  if (block.pageSize) {
33331
33457
  next.pendingPageSize = { w: block.pageSize.w, h: block.pageSize.h };
33332
33458
  }
@@ -34926,7 +35052,7 @@ function layoutDocument(blocks, measures, options = {}) {
34926
35052
  if (contentWidth <= 0) {
34927
35053
  throw new Error("layoutDocument: pageSize and margins yield non-positive content area");
34928
35054
  }
34929
- const validateHeaderHeight = (height) => {
35055
+ const validateContentHeight = (height) => {
34930
35056
  if (height === void 0) return 0;
34931
35057
  if (!Number.isFinite(height) || height < 0) return 0;
34932
35058
  return height;
@@ -34934,15 +35060,25 @@ function layoutDocument(blocks, measures, options = {}) {
34934
35060
  const headerContentHeights = options.headerContentHeights;
34935
35061
  const maxHeaderContentHeight = headerContentHeights ? Math.max(
34936
35062
  0,
34937
- validateHeaderHeight(headerContentHeights.default),
34938
- validateHeaderHeight(headerContentHeights.first),
34939
- validateHeaderHeight(headerContentHeights.even),
34940
- validateHeaderHeight(headerContentHeights.odd)
35063
+ validateContentHeight(headerContentHeights.default),
35064
+ validateContentHeight(headerContentHeights.first),
35065
+ validateContentHeight(headerContentHeights.even),
35066
+ validateContentHeight(headerContentHeights.odd)
34941
35067
  ) : 0;
34942
35068
  const headerDistance = margins.header ?? margins.top;
34943
35069
  const effectiveTopMargin = maxHeaderContentHeight > 0 ? Math.max(margins.top, headerDistance + maxHeaderContentHeight) : margins.top;
35070
+ const footerContentHeights = options.footerContentHeights;
35071
+ const maxFooterContentHeight = footerContentHeights ? Math.max(
35072
+ 0,
35073
+ validateContentHeight(footerContentHeights.default),
35074
+ validateContentHeight(footerContentHeights.first),
35075
+ validateContentHeight(footerContentHeights.even),
35076
+ validateContentHeight(footerContentHeights.odd)
35077
+ ) : 0;
35078
+ const footerDistance = margins.footer ?? margins.bottom;
35079
+ const effectiveBottomMargin = maxFooterContentHeight > 0 ? Math.max(margins.bottom, footerDistance + maxFooterContentHeight) : margins.bottom;
34944
35080
  let activeTopMargin = effectiveTopMargin;
34945
- let activeBottomMargin = margins.bottom;
35081
+ let activeBottomMargin = effectiveBottomMargin;
34946
35082
  let pendingTopMargin = null;
34947
35083
  let pendingBottomMargin = null;
34948
35084
  let activeHeaderDistance = margins.header ?? margins.top;
@@ -34965,7 +35101,7 @@ function layoutDocument(blocks, measures, options = {}) {
34965
35101
  const nextSectionPropsAtBreak = computeNextSectionPropsAtBreak(blocks);
34966
35102
  const scheduleSectionBreakCompat = (block, state, baseMargins) => {
34967
35103
  if (typeof scheduleSectionBreak === "function") {
34968
- return scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight);
35104
+ return scheduleSectionBreak(block, state, baseMargins, maxHeaderContentHeight, maxFooterContentHeight);
34969
35105
  }
34970
35106
  const next = { ...state };
34971
35107
  if (block.attrs?.isFirstSection && !next.hasAnyPages) {
@@ -34986,10 +35122,11 @@ function layoutDocument(blocks, measures, options = {}) {
34986
35122
  next.pendingTopMargin = next.activeTopMargin;
34987
35123
  }
34988
35124
  if (block.margins?.footer !== void 0) {
34989
- const footerDistance = Math.max(0, block.margins.footer);
34990
- next.activeFooterDistance = footerDistance;
34991
- next.pendingFooterDistance = footerDistance;
34992
- next.activeBottomMargin = Math.max(baseMargins.bottom, footerDistance);
35125
+ const footerDistance2 = Math.max(0, block.margins.footer);
35126
+ next.activeFooterDistance = footerDistance2;
35127
+ next.pendingFooterDistance = footerDistance2;
35128
+ const requiredBottom = maxFooterContentHeight > 0 ? footerDistance2 + maxFooterContentHeight : footerDistance2;
35129
+ next.activeBottomMargin = Math.max(baseMargins.bottom, requiredBottom);
34993
35130
  next.pendingBottomMargin = next.activeBottomMargin;
34994
35131
  }
34995
35132
  if (block.columns) {
@@ -35034,7 +35171,13 @@ function layoutDocument(blocks, measures, options = {}) {
35034
35171
  } else {
35035
35172
  next.pendingTopMargin = nextTop;
35036
35173
  }
35037
- next.pendingBottomMargin = typeof footerPx === "number" ? Math.max(baseMargins.bottom, footerPx) : nextBottom;
35174
+ if (typeof footerPx === "number") {
35175
+ const sectionFooter = next.pendingFooterDistance;
35176
+ const requiredBottom = maxFooterContentHeight > 0 ? sectionFooter + maxFooterContentHeight : sectionFooter;
35177
+ next.pendingBottomMargin = Math.max(baseMargins.bottom, requiredBottom);
35178
+ } else {
35179
+ next.pendingBottomMargin = nextBottom;
35180
+ }
35038
35181
  if (block.pageSize) next.pendingPageSize = { w: block.pageSize.w, h: block.pageSize.h };
35039
35182
  if (block.orientation) next.pendingOrientation = block.orientation;
35040
35183
  const sectionType = block.type ?? "continuous";
@@ -35801,6 +35944,49 @@ const hashParagraphBorders = (borders) => {
35801
35944
  if (borders.left) parts.push(`l:[${hashParagraphBorder(borders.left)}]`);
35802
35945
  return parts.join(";");
35803
35946
  };
35947
+ function isNoneBorder(value) {
35948
+ return typeof value === "object" && value !== null && "none" in value && value.none === true;
35949
+ }
35950
+ function isBorderSpec(value) {
35951
+ return typeof value === "object" && value !== null && !("none" in value);
35952
+ }
35953
+ const hashBorderSpec = (border) => {
35954
+ const parts = [];
35955
+ if (border.style !== void 0) parts.push(`s:${border.style}`);
35956
+ if (border.width !== void 0) parts.push(`w:${border.width}`);
35957
+ if (border.color !== void 0) parts.push(`c:${border.color}`);
35958
+ if (border.space !== void 0) parts.push(`sp:${border.space}`);
35959
+ return parts.join(",");
35960
+ };
35961
+ const hashTableBorderValue = (borderValue) => {
35962
+ if (borderValue === void 0) return "";
35963
+ if (borderValue === null) return "null";
35964
+ if (isNoneBorder(borderValue)) return "none";
35965
+ if (isBorderSpec(borderValue)) {
35966
+ return hashBorderSpec(borderValue);
35967
+ }
35968
+ return "";
35969
+ };
35970
+ const hashTableBorders = (borders) => {
35971
+ if (!borders) return "";
35972
+ const parts = [];
35973
+ if (borders.top !== void 0) parts.push(`t:[${hashTableBorderValue(borders.top)}]`);
35974
+ if (borders.right !== void 0) parts.push(`r:[${hashTableBorderValue(borders.right)}]`);
35975
+ if (borders.bottom !== void 0) parts.push(`b:[${hashTableBorderValue(borders.bottom)}]`);
35976
+ if (borders.left !== void 0) parts.push(`l:[${hashTableBorderValue(borders.left)}]`);
35977
+ if (borders.insideH !== void 0) parts.push(`ih:[${hashTableBorderValue(borders.insideH)}]`);
35978
+ if (borders.insideV !== void 0) parts.push(`iv:[${hashTableBorderValue(borders.insideV)}]`);
35979
+ return parts.join(";");
35980
+ };
35981
+ const hashCellBorders = (borders) => {
35982
+ if (!borders) return "";
35983
+ const parts = [];
35984
+ if (borders.top) parts.push(`t:[${hashBorderSpec(borders.top)}]`);
35985
+ if (borders.right) parts.push(`r:[${hashBorderSpec(borders.right)}]`);
35986
+ if (borders.bottom) parts.push(`b:[${hashBorderSpec(borders.bottom)}]`);
35987
+ if (borders.left) parts.push(`l:[${hashBorderSpec(borders.left)}]`);
35988
+ return parts.join(";");
35989
+ };
35804
35990
  const MAX_CACHE_SIZE$1 = 1e4;
35805
35991
  const BYTES_PER_ENTRY_ESTIMATE = 5e3;
35806
35992
  const NORMALIZED_WHITESPACE = /\s+/g;
@@ -35828,6 +36014,26 @@ const hashRuns = (block) => {
35828
36014
  continue;
35829
36015
  }
35830
36016
  for (const cell of row.cells) {
36017
+ if (cell.attrs) {
36018
+ const cellAttrs = cell.attrs;
36019
+ const cellAttrParts = [];
36020
+ if (cellAttrs.borders) {
36021
+ cellAttrParts.push(`cb:${hashCellBorders(cellAttrs.borders)}`);
36022
+ }
36023
+ if (cellAttrs.padding) {
36024
+ const p = cellAttrs.padding;
36025
+ cellAttrParts.push(`cp:${p.top ?? 0}:${p.right ?? 0}:${p.bottom ?? 0}:${p.left ?? 0}`);
36026
+ }
36027
+ if (cellAttrs.verticalAlign) {
36028
+ cellAttrParts.push(`va:${cellAttrs.verticalAlign}`);
36029
+ }
36030
+ if (cellAttrs.background) {
36031
+ cellAttrParts.push(`bg:${cellAttrs.background}`);
36032
+ }
36033
+ if (cellAttrParts.length > 0) {
36034
+ cellHashes.push(`ca:${cellAttrParts.join(":")}`);
36035
+ }
36036
+ }
35831
36037
  const cellBlocks = cell.blocks ?? (cell.paragraph ? [cell.paragraph] : []);
35832
36038
  for (const cellBlock of cellBlocks) {
35833
36039
  const paragraphBlock = cellBlock;
@@ -35894,8 +36100,25 @@ const hashRuns = (block) => {
35894
36100
  }
35895
36101
  }
35896
36102
  }
36103
+ let tableAttrsKey = "";
36104
+ if (tableBlock.attrs) {
36105
+ const tblAttrs = tableBlock.attrs;
36106
+ const tableAttrParts = [];
36107
+ if (tblAttrs.borders) {
36108
+ tableAttrParts.push(`tb:${hashTableBorders(tblAttrs.borders)}`);
36109
+ }
36110
+ if (tblAttrs.borderCollapse) {
36111
+ tableAttrParts.push(`bc:${tblAttrs.borderCollapse}`);
36112
+ }
36113
+ if (tblAttrs.cellSpacing !== void 0) {
36114
+ tableAttrParts.push(`cs:${tblAttrs.cellSpacing}`);
36115
+ }
36116
+ if (tableAttrParts.length > 0) {
36117
+ tableAttrsKey = `|ta:${tableAttrParts.join(":")}`;
36118
+ }
36119
+ }
35897
36120
  const contentHash = cellHashes.join("|");
35898
- return `${block.id}:table:${contentHash}`;
36121
+ return `${block.id}:table:${contentHash}${tableAttrsKey}`;
35899
36122
  }
35900
36123
  if (block.kind !== "paragraph") return block.id;
35901
36124
  const trackedMode = block.attrs && "trackedChangesMode" in block.attrs && block.attrs.trackedChangesMode || "review";
@@ -37417,17 +37640,67 @@ async function incrementalLayout(previousBlocks, _previousLayout, nextBlocks, op
37417
37640
  for (const [type, value] of Object.entries(preHeaderLayouts)) {
37418
37641
  if (!isValidHeaderType(type)) continue;
37419
37642
  if (value?.layout && typeof value.layout.height === "number") {
37420
- headerContentHeights[type] = value.layout.height;
37643
+ const height = value.layout.height;
37644
+ if (Number.isFinite(height) && height >= 0) {
37645
+ headerContentHeights[type] = height;
37646
+ }
37421
37647
  }
37422
37648
  }
37423
37649
  const hfPreEnd = performance.now();
37424
37650
  perfLog(`[Perf] 4.1.5 Pre-layout headers for height: ${(hfPreEnd - hfPreStart).toFixed(2)}ms`);
37425
37651
  }
37652
+ let footerContentHeights;
37653
+ if (headerFooter?.constraints && headerFooter.footerBlocks) {
37654
+ const footerPreStart = performance.now();
37655
+ const measureFn = headerFooter.measure ?? measureBlock2;
37656
+ if (!headerFooter.headerBlocks) {
37657
+ invalidateHeaderFooterCache(
37658
+ headerMeasureCache,
37659
+ headerFooterCacheState,
37660
+ headerFooter.headerBlocks,
37661
+ headerFooter.footerBlocks,
37662
+ headerFooter.constraints,
37663
+ options.sectionMetadata
37664
+ );
37665
+ }
37666
+ const FOOTER_PRELAYOUT_PLACEHOLDER_PAGE_COUNT = 1;
37667
+ try {
37668
+ const preFooterLayouts = await layoutHeaderFooterWithCache(
37669
+ headerFooter.footerBlocks,
37670
+ headerFooter.constraints,
37671
+ measureFn,
37672
+ headerMeasureCache,
37673
+ FOOTER_PRELAYOUT_PLACEHOLDER_PAGE_COUNT,
37674
+ void 0
37675
+ // No page resolver needed for height calculation
37676
+ );
37677
+ const isValidFooterType = (key2) => {
37678
+ return ["default", "first", "even", "odd"].includes(key2);
37679
+ };
37680
+ footerContentHeights = {};
37681
+ for (const [type, value] of Object.entries(preFooterLayouts)) {
37682
+ if (!isValidFooterType(type)) continue;
37683
+ if (value?.layout && typeof value.layout.height === "number") {
37684
+ const height = value.layout.height;
37685
+ if (Number.isFinite(height) && height >= 0) {
37686
+ footerContentHeights[type] = height;
37687
+ }
37688
+ }
37689
+ }
37690
+ } catch (error) {
37691
+ console.error("[Layout] Footer pre-layout failed:", error);
37692
+ footerContentHeights = void 0;
37693
+ }
37694
+ const footerPreEnd = performance.now();
37695
+ perfLog(`[Perf] 4.1.6 Pre-layout footers for height: ${(footerPreEnd - footerPreStart).toFixed(2)}ms`);
37696
+ }
37426
37697
  const layoutStart = performance.now();
37427
37698
  let layout = layoutDocument(nextBlocks, measures, {
37428
37699
  ...options,
37429
37700
  headerContentHeights,
37430
37701
  // Pass header heights to prevent overlap
37702
+ footerContentHeights,
37703
+ // Pass footer heights to prevent overlap
37431
37704
  remeasureParagraph: (block, maxWidth, firstLineIndent) => remeasureParagraph(block, maxWidth, firstLineIndent)
37432
37705
  });
37433
37706
  const layoutEnd = performance.now();
@@ -37476,6 +37749,8 @@ async function incrementalLayout(previousBlocks, _previousLayout, nextBlocks, op
37476
37749
  ...options,
37477
37750
  headerContentHeights,
37478
37751
  // Pass header heights to prevent overlap
37752
+ footerContentHeights,
37753
+ // Pass footer heights to prevent overlap
37479
37754
  remeasureParagraph: (block, maxWidth, firstLineIndent) => remeasureParagraph(block, maxWidth, firstLineIndent)
37480
37755
  });
37481
37756
  const relayoutEnd = performance.now();
@@ -37642,6 +37917,285 @@ async function remeasureAffectedBlocks(blocks, measures, affectedBlockIds, const
37642
37917
  }
37643
37918
  return updatedMeasures;
37644
37919
  }
37920
+ class PageGeometryHelper {
37921
+ /**
37922
+ * Creates a new PageGeometryHelper instance.
37923
+ *
37924
+ * @param config - Page geometry configuration
37925
+ */
37926
+ constructor(config) {
37927
+ this.cache = null;
37928
+ this.config = config;
37929
+ }
37930
+ /**
37931
+ * Updates the layout and invalidates the cache.
37932
+ *
37933
+ * Call this whenever the layout changes (new pages, different heights, etc.)
37934
+ *
37935
+ * @param layout - New layout data
37936
+ * @param pageGap - Optional new page gap (if not provided, uses current gap)
37937
+ */
37938
+ updateLayout(layout, pageGap) {
37939
+ this.config.layout = layout;
37940
+ if (pageGap !== void 0) {
37941
+ this.config.pageGap = pageGap;
37942
+ }
37943
+ this.cache = null;
37944
+ }
37945
+ /**
37946
+ * Updates the page gap and invalidates the cache.
37947
+ *
37948
+ * @param pageGap - New gap between pages in pixels
37949
+ */
37950
+ updatePageGap(pageGap) {
37951
+ if (this.config.pageGap !== pageGap) {
37952
+ this.config.pageGap = pageGap;
37953
+ this.cache = null;
37954
+ }
37955
+ }
37956
+ /**
37957
+ * Gets the cumulative Y position (top edge) of a page in container space.
37958
+ *
37959
+ * The returned value is the distance from the top of the container to the
37960
+ * top of the specified page, accounting for all previous pages and gaps.
37961
+ *
37962
+ * @param pageIndex - Zero-based page index
37963
+ * @returns Y position in pixels, or 0 if page index is invalid
37964
+ *
37965
+ * @example
37966
+ * ```typescript
37967
+ * // Get Y position of page 0 (first page)
37968
+ * const y0 = helper.getPageTop(0); // Returns 0
37969
+ *
37970
+ * // Get Y position of page 2 (third page)
37971
+ * // Assumes page 0 height = 1000, page 1 height = 1200, gap = 24
37972
+ * const y2 = helper.getPageTop(2); // Returns 1000 + 24 + 1200 + 24 = 2248
37973
+ * ```
37974
+ */
37975
+ getPageTop(pageIndex) {
37976
+ this.ensureCache();
37977
+ if (pageIndex < 0 || pageIndex >= this.cache.cumulativeY.length) {
37978
+ return 0;
37979
+ }
37980
+ return this.cache.cumulativeY[pageIndex];
37981
+ }
37982
+ /**
37983
+ * Gets the height of a specific page.
37984
+ *
37985
+ * Uses per-page height if available (from layout.pages[i].size?.h),
37986
+ * otherwise falls back to layout.pageSize.h.
37987
+ *
37988
+ * @param pageIndex - Zero-based page index
37989
+ * @returns Page height in pixels, or 0 if page index is invalid
37990
+ *
37991
+ * @example
37992
+ * ```typescript
37993
+ * const height = helper.getPageHeight(0); // Returns page-specific height
37994
+ * ```
37995
+ */
37996
+ getPageHeight(pageIndex) {
37997
+ this.ensureCache();
37998
+ if (pageIndex < 0 || pageIndex >= this.cache.pageHeights.length) {
37999
+ return 0;
38000
+ }
38001
+ return this.cache.pageHeights[pageIndex];
38002
+ }
38003
+ /**
38004
+ * Gets the gap between pages.
38005
+ *
38006
+ * @returns Gap in pixels
38007
+ *
38008
+ * @example
38009
+ * ```typescript
38010
+ * const gap = helper.getPageGap(); // Returns 24
38011
+ * ```
38012
+ */
38013
+ getPageGap() {
38014
+ this.ensureCache();
38015
+ return this.cache.pageGap;
38016
+ }
38017
+ /**
38018
+ * Gets the total height of all pages including gaps.
38019
+ *
38020
+ * Total height = sum of all page heights + (pageCount - 1) * gap
38021
+ *
38022
+ * @returns Total height in pixels
38023
+ *
38024
+ * @example
38025
+ * ```typescript
38026
+ * // 3 pages: heights [1000, 1200, 1000], gap = 24
38027
+ * const total = helper.getTotalHeight();
38028
+ * // Returns 1000 + 24 + 1200 + 24 + 1000 = 3248
38029
+ * ```
38030
+ */
38031
+ getTotalHeight() {
38032
+ this.ensureCache();
38033
+ return this.cache.totalHeight;
38034
+ }
38035
+ /**
38036
+ * Gets the number of pages in the layout.
38037
+ *
38038
+ * @returns Page count
38039
+ */
38040
+ getPageCount() {
38041
+ return this.config.layout.pages.length;
38042
+ }
38043
+ /**
38044
+ * Finds the page index containing a given Y coordinate.
38045
+ *
38046
+ * This performs a linear search through cached cumulative positions.
38047
+ * For large documents, consider adding binary search optimization.
38048
+ *
38049
+ * @param containerY - Y coordinate in container space
38050
+ * @returns Page index, or null if Y is outside all pages
38051
+ *
38052
+ * @example
38053
+ * ```typescript
38054
+ * // Find which page contains Y = 1500
38055
+ * const pageIndex = helper.getPageIndexAtY(1500);
38056
+ * // Returns 1 (second page) if first page ends at Y=1024
38057
+ * ```
38058
+ */
38059
+ getPageIndexAtY(containerY) {
38060
+ this.ensureCache();
38061
+ const cache2 = this.cache;
38062
+ for (let i = 0; i < cache2.cumulativeY.length; i++) {
38063
+ const pageTop = cache2.cumulativeY[i];
38064
+ const pageBottom = pageTop + cache2.pageHeights[i];
38065
+ if (containerY >= pageTop && containerY < pageBottom) {
38066
+ return i;
38067
+ }
38068
+ }
38069
+ return null;
38070
+ }
38071
+ /**
38072
+ * Finds the nearest page index to a given Y coordinate (snap-to-nearest).
38073
+ *
38074
+ * Returns the page containing Y when inside a page; otherwise returns the
38075
+ * closest page based on distance to page center. Useful for dragging through
38076
+ * page gaps where getPageIndexAtY would return null.
38077
+ *
38078
+ * @param containerY - Y coordinate in container space
38079
+ * @returns Nearest page index, or null if there are no pages
38080
+ */
38081
+ getNearestPageIndex(containerY) {
38082
+ this.ensureCache();
38083
+ const cache2 = this.cache;
38084
+ const pageCount = cache2.pageHeights.length;
38085
+ if (pageCount === 0) return null;
38086
+ const direct = this.getPageIndexAtY(containerY);
38087
+ if (direct !== null) return direct;
38088
+ let nearestIndex = 0;
38089
+ let nearestDistance = Infinity;
38090
+ for (let i = 0; i < pageCount; i++) {
38091
+ const top2 = cache2.cumulativeY[i];
38092
+ const height = cache2.pageHeights[i];
38093
+ const center = top2 + height / 2;
38094
+ const distance = Math.abs(containerY - center);
38095
+ if (distance < nearestDistance) {
38096
+ nearestDistance = distance;
38097
+ nearestIndex = i;
38098
+ }
38099
+ }
38100
+ return nearestIndex;
38101
+ }
38102
+ /**
38103
+ * Ensures the cache is built and up-to-date.
38104
+ * Validates cache state and rebuilds if needed.
38105
+ * @private
38106
+ * @throws Never throws - handles errors gracefully with fallback values
38107
+ */
38108
+ ensureCache() {
38109
+ if (this.cache !== null) {
38110
+ if (!Array.isArray(this.cache.cumulativeY) || !Array.isArray(this.cache.pageHeights)) {
38111
+ console.warn("[PageGeometryHelper] Cache corruption detected, rebuilding cache");
38112
+ this.cache = null;
38113
+ } else {
38114
+ return;
38115
+ }
38116
+ }
38117
+ this.buildCache();
38118
+ }
38119
+ /**
38120
+ * Builds the geometry cache from current layout data.
38121
+ * Handles errors gracefully by providing fallback values.
38122
+ * @private
38123
+ * @throws Never throws - catches all errors and provides safe defaults
38124
+ */
38125
+ buildCache() {
38126
+ try {
38127
+ const layout = this.config.layout;
38128
+ if (!layout || !Array.isArray(layout.pages)) {
38129
+ throw new Error("Invalid layout: missing or invalid pages array");
38130
+ }
38131
+ const pageGap = this.config.pageGap ?? layout.pageGap ?? 0;
38132
+ const pageCount = layout.pages.length;
38133
+ if (!Number.isFinite(pageGap) || pageGap < 0) {
38134
+ throw new Error(`Invalid pageGap: ${pageGap} (must be non-negative finite number)`);
38135
+ }
38136
+ const cumulativeY = new Array(pageCount);
38137
+ const pageHeights = new Array(pageCount);
38138
+ let currentY = 0;
38139
+ for (let i = 0; i < pageCount; i++) {
38140
+ const page = layout.pages[i];
38141
+ if (!page) {
38142
+ throw new Error(`Invalid page at index ${i}: page is null or undefined`);
38143
+ }
38144
+ const pageHeight = page.size?.h ?? layout.pageSize.h;
38145
+ if (!Number.isFinite(pageHeight) || pageHeight < 0) {
38146
+ throw new Error(`Invalid page height at index ${i}: ${pageHeight} (must be non-negative finite number)`);
38147
+ }
38148
+ cumulativeY[i] = currentY;
38149
+ pageHeights[i] = pageHeight;
38150
+ currentY += pageHeight;
38151
+ if (i < pageCount - 1) {
38152
+ currentY += pageGap;
38153
+ }
38154
+ }
38155
+ const totalHeight = currentY;
38156
+ this.cache = {
38157
+ cumulativeY,
38158
+ pageHeights,
38159
+ pageGap,
38160
+ totalHeight,
38161
+ layoutVersion: 0
38162
+ // Placeholder for future version tracking
38163
+ };
38164
+ } catch (error) {
38165
+ const errorMessage = error instanceof Error ? error.message : String(error);
38166
+ console.error(`[PageGeometryHelper] Cache build failed: ${errorMessage}. Using fallback empty cache.`);
38167
+ this.cache = {
38168
+ cumulativeY: [],
38169
+ pageHeights: [],
38170
+ pageGap: 0,
38171
+ totalHeight: 0,
38172
+ layoutVersion: 0
38173
+ };
38174
+ }
38175
+ }
38176
+ /**
38177
+ * Clears the cache, forcing recalculation on next access.
38178
+ * Useful for testing or manual cache invalidation.
38179
+ */
38180
+ clearCache() {
38181
+ this.cache = null;
38182
+ }
38183
+ /**
38184
+ * Gets debug information about the current cache state.
38185
+ * @internal
38186
+ */
38187
+ getDebugInfo() {
38188
+ this.ensureCache();
38189
+ return {
38190
+ isCached: this.cache !== null,
38191
+ pageCount: this.config.layout.pages.length,
38192
+ pageGap: this.cache.pageGap,
38193
+ totalHeight: this.cache.totalHeight,
38194
+ cumulativeY: [...this.cache.cumulativeY],
38195
+ pageHeights: [...this.cache.pageHeights]
38196
+ };
38197
+ }
38198
+ }
37645
38199
  var Priority = /* @__PURE__ */ ((Priority2) => {
37646
38200
  Priority2[Priority2["P0"] = 0] = "P0";
37647
38201
  Priority2[Priority2["P1"] = 1] = "P1";
@@ -37935,18 +38489,41 @@ const rangesOverlap = (startA, endA, startB, endB) => {
37935
38489
  const effectiveEndA = endA ?? startA + 1;
37936
38490
  return effectiveEndA > startB && startA < endB;
37937
38491
  };
37938
- function hitTestPage(layout, point) {
38492
+ function hitTestPage(layout, point, geometryHelper) {
38493
+ if (geometryHelper) {
38494
+ const pageIndex = geometryHelper.getPageIndexAtY(point.y);
38495
+ if (pageIndex !== null) {
38496
+ return { pageIndex, page: layout.pages[pageIndex] };
38497
+ }
38498
+ const nearest = geometryHelper.getNearestPageIndex(point.y);
38499
+ if (nearest !== null) {
38500
+ return { pageIndex: nearest, page: layout.pages[nearest] };
38501
+ }
38502
+ return null;
38503
+ }
37939
38504
  const pageGap = layout.pageGap ?? 0;
37940
38505
  let cursorY = 0;
38506
+ let nearestIndex = null;
38507
+ let nearestDistance = Infinity;
37941
38508
  for (let pageIndex = 0; pageIndex < layout.pages.length; pageIndex += 1) {
37942
38509
  const page = layout.pages[pageIndex];
38510
+ const pageHeight = page.size?.h ?? layout.pageSize.h;
37943
38511
  const top2 = cursorY;
37944
- const bottom2 = top2 + layout.pageSize.h;
38512
+ const bottom2 = top2 + pageHeight;
37945
38513
  if (point.y >= top2 && point.y < bottom2) {
37946
38514
  return { pageIndex, page };
37947
38515
  }
38516
+ const center = top2 + pageHeight / 2;
38517
+ const distance = Math.abs(point.y - center);
38518
+ if (distance < nearestDistance) {
38519
+ nearestDistance = distance;
38520
+ nearestIndex = pageIndex;
38521
+ }
37948
38522
  cursorY = bottom2 + pageGap;
37949
38523
  }
38524
+ if (nearestIndex !== null) {
38525
+ return { pageIndex: nearestIndex, page: layout.pages[nearestIndex] };
38526
+ }
37950
38527
  return null;
37951
38528
  }
37952
38529
  function hitTestFragment(layout, pageHit, blocks, measures, point) {
@@ -38107,7 +38684,7 @@ const hitTestTableFragment = (pageHit, blocks, measures, point) => {
38107
38684
  }
38108
38685
  return null;
38109
38686
  };
38110
- function clickToPosition(layout, blocks, measures, containerPoint, domContainer, clientX, clientY) {
38687
+ function clickToPosition(layout, blocks, measures, containerPoint, domContainer, clientX, clientY, geometryHelper) {
38111
38688
  logClickStage("log", "entry", {
38112
38689
  pages: layout.pages.length
38113
38690
  });
@@ -38150,75 +38727,132 @@ function clickToPosition(layout, blocks, measures, containerPoint, domContainer,
38150
38727
  return { pos: domPos, blockId: "", pageIndex: 0, column: 0, lineIndex: -1 };
38151
38728
  }
38152
38729
  }
38153
- const pageHit = hitTestPage(layout, containerPoint);
38730
+ const pageHit = hitTestPage(layout, containerPoint, geometryHelper);
38154
38731
  if (!pageHit) {
38155
38732
  return null;
38156
38733
  }
38157
- const pageGap = layout.pageGap ?? 0;
38734
+ const pageTopY = geometryHelper ? geometryHelper.getPageTop(pageHit.pageIndex) : calculatePageTopFallback(layout, pageHit.pageIndex);
38158
38735
  const pageRelativePoint = {
38159
38736
  x: containerPoint.x,
38160
- y: containerPoint.y - pageHit.pageIndex * (layout.pageSize.h + pageGap)
38737
+ y: containerPoint.y - pageTopY
38161
38738
  };
38162
38739
  logClickStage("log", "page-hit", {
38163
38740
  pageIndex: pageHit.pageIndex
38164
38741
  });
38165
- const fragmentHit = hitTestFragment(layout, pageHit, blocks, measures, pageRelativePoint);
38742
+ let fragmentHit = hitTestFragment(layout, pageHit, blocks, measures, pageRelativePoint);
38743
+ if (!fragmentHit) {
38744
+ const page = pageHit.page;
38745
+ const fragments = page.fragments.filter(
38746
+ (f2) => f2 != null && typeof f2 === "object"
38747
+ );
38748
+ if (fragments.length > 0) {
38749
+ let nearest = null;
38750
+ let nearestDist = Infinity;
38751
+ for (const frag of fragments) {
38752
+ const top2 = frag.y;
38753
+ const bottom2 = frag.y + frag.height;
38754
+ let dist;
38755
+ if (pageRelativePoint.y < top2) {
38756
+ dist = top2 - pageRelativePoint.y;
38757
+ } else if (pageRelativePoint.y > bottom2) {
38758
+ dist = pageRelativePoint.y - bottom2;
38759
+ } else {
38760
+ dist = 0;
38761
+ }
38762
+ if (dist < nearestDist) {
38763
+ nearestDist = dist;
38764
+ nearest = frag;
38765
+ }
38766
+ }
38767
+ if (nearest) {
38768
+ const blockIndex = findBlockIndexByFragmentId(blocks, nearest.blockId);
38769
+ if (blockIndex !== -1) {
38770
+ const block = blocks[blockIndex];
38771
+ const measure = measures[blockIndex];
38772
+ if (block && measure) {
38773
+ fragmentHit = {
38774
+ fragment: nearest,
38775
+ block,
38776
+ measure,
38777
+ pageIndex: pageHit.pageIndex,
38778
+ pageY: 0
38779
+ };
38780
+ }
38781
+ }
38782
+ }
38783
+ }
38784
+ }
38166
38785
  if (fragmentHit) {
38167
38786
  const { fragment, block, measure, pageIndex, pageY } = fragmentHit;
38168
- if (fragment.kind !== "para" || measure.kind !== "paragraph" || block.kind !== "paragraph") {
38169
- logClickStage("warn", "fragment-type-mismatch", {
38170
- fragmentKind: fragment.kind,
38171
- measureKind: measure.kind,
38172
- blockKind: block.kind
38787
+ if (fragment.kind === "para" && measure.kind === "paragraph" && block.kind === "paragraph") {
38788
+ const lineIndex = findLineIndexAtY(measure, pageY, fragment.fromLine, fragment.toLine);
38789
+ if (lineIndex == null) {
38790
+ logClickStage("warn", "no-line", {
38791
+ blockId: fragment.blockId
38792
+ });
38793
+ return null;
38794
+ }
38795
+ const line = measure.lines[lineIndex];
38796
+ const isRTL = isRtlBlock(block);
38797
+ const indentLeft = typeof block.attrs?.indent?.left === "number" ? block.attrs.indent.left : 0;
38798
+ const indentRight = typeof block.attrs?.indent?.right === "number" ? block.attrs.indent.right : 0;
38799
+ const paraIndentLeft = Number.isFinite(indentLeft) ? indentLeft : 0;
38800
+ const paraIndentRight = Number.isFinite(indentRight) ? indentRight : 0;
38801
+ const totalIndent = paraIndentLeft + paraIndentRight;
38802
+ const availableWidth = Math.max(0, fragment.width - totalIndent);
38803
+ if (totalIndent > fragment.width) {
38804
+ console.warn(
38805
+ `[clickToPosition] Paragraph indents (${totalIndent}px) exceed fragment width (${fragment.width}px) for block ${fragment.blockId}. This may indicate a layout miscalculation. Available width clamped to 0.`
38806
+ );
38807
+ }
38808
+ const markerWidth = fragment.markerWidth ?? measure.marker?.markerWidth ?? 0;
38809
+ const isListItem3 = markerWidth > 0;
38810
+ const alignmentOverride = isListItem3 ? "left" : void 0;
38811
+ const pos = mapPointToPm(block, line, pageRelativePoint.x - fragment.x, isRTL, availableWidth, alignmentOverride);
38812
+ if (pos == null) {
38813
+ logClickStage("warn", "no-position", {
38814
+ blockId: fragment.blockId
38815
+ });
38816
+ return null;
38817
+ }
38818
+ const column = determineColumn(layout, fragment.x);
38819
+ logPositionDebug({
38820
+ blockId: fragment.blockId,
38821
+ x: pageRelativePoint.x - fragment.x
38173
38822
  });
38174
- return null;
38175
- }
38176
- const lineIndex = findLineIndexAtY(measure, pageY, fragment.fromLine, fragment.toLine);
38177
- if (lineIndex == null) {
38178
- logClickStage("warn", "no-line", {
38823
+ logClickStage("log", "success", {
38179
38824
  blockId: fragment.blockId
38180
38825
  });
38181
- return null;
38182
- }
38183
- const line = measure.lines[lineIndex];
38184
- const isRTL = isRtlBlock(block);
38185
- const indentLeft = typeof block.attrs?.indent?.left === "number" ? block.attrs.indent.left : 0;
38186
- const indentRight = typeof block.attrs?.indent?.right === "number" ? block.attrs.indent.right : 0;
38187
- const paraIndentLeft = Number.isFinite(indentLeft) ? indentLeft : 0;
38188
- const paraIndentRight = Number.isFinite(indentRight) ? indentRight : 0;
38189
- const totalIndent = paraIndentLeft + paraIndentRight;
38190
- const availableWidth = Math.max(0, fragment.width - totalIndent);
38191
- if (totalIndent > fragment.width) {
38192
- console.warn(
38193
- `[clickToPosition] Paragraph indents (${totalIndent}px) exceed fragment width (${fragment.width}px) for block ${fragment.blockId}. This may indicate a layout miscalculation. Available width clamped to 0.`
38194
- );
38826
+ return {
38827
+ pos,
38828
+ blockId: fragment.blockId,
38829
+ pageIndex,
38830
+ column,
38831
+ lineIndex
38832
+ // lineIndex is now already absolute (within measure.lines), no need to add fragment.fromLine
38833
+ };
38195
38834
  }
38196
- const markerWidth = fragment.markerWidth ?? measure.marker?.markerWidth ?? 0;
38197
- const isListItem3 = markerWidth > 0;
38198
- const alignmentOverride = isListItem3 ? "left" : void 0;
38199
- const pos = mapPointToPm(block, line, pageRelativePoint.x - fragment.x, isRTL, availableWidth, alignmentOverride);
38200
- if (pos == null) {
38201
- logClickStage("warn", "no-position", {
38202
- blockId: fragment.blockId
38835
+ if (isAtomicFragment(fragment)) {
38836
+ const pmRange = getAtomicPmRange(fragment, block);
38837
+ const pos = pmRange.pmStart ?? pmRange.pmEnd ?? null;
38838
+ if (pos == null) {
38839
+ logClickStage("warn", "atomic-without-range", {
38840
+ fragmentId: fragment.blockId
38841
+ });
38842
+ return null;
38843
+ }
38844
+ logClickStage("log", "success", {
38845
+ blockId: fragment.blockId,
38846
+ column: determineColumn(layout, fragment.x)
38203
38847
  });
38204
- return null;
38848
+ return {
38849
+ pos,
38850
+ blockId: fragment.blockId,
38851
+ pageIndex,
38852
+ column: determineColumn(layout, fragment.x),
38853
+ lineIndex: -1
38854
+ };
38205
38855
  }
38206
- const column = determineColumn(layout, fragment.x);
38207
- logPositionDebug({
38208
- blockId: fragment.blockId,
38209
- x: pageRelativePoint.x - fragment.x
38210
- });
38211
- logClickStage("log", "success", {
38212
- blockId: fragment.blockId
38213
- });
38214
- return {
38215
- pos,
38216
- blockId: fragment.blockId,
38217
- pageIndex,
38218
- column,
38219
- lineIndex
38220
- // lineIndex is now already absolute (within measure.lines), no need to add fragment.fromLine
38221
- };
38222
38856
  }
38223
38857
  const tableHit = hitTestTableFragment(pageHit, blocks, measures, pageRelativePoint);
38224
38858
  if (tableHit) {
@@ -38368,12 +39002,22 @@ const sumLineHeights = (measure, fromLine, toLine) => {
38368
39002
  }
38369
39003
  return height;
38370
39004
  };
38371
- function selectionToRects(layout, blocks, measures, from2, to) {
39005
+ const calculatePageTopFallback = (layout, pageIndex) => {
39006
+ const pageGap = layout.pageGap ?? 0;
39007
+ let y = 0;
39008
+ for (let i = 0; i < pageIndex; i++) {
39009
+ const pageHeight = layout.pages[i]?.size?.h ?? layout.pageSize.h;
39010
+ y += pageHeight + pageGap;
39011
+ }
39012
+ return y;
39013
+ };
39014
+ function selectionToRects(layout, blocks, measures, from2, to, geometryHelper) {
38372
39015
  if (from2 === to) {
38373
39016
  return [];
38374
39017
  }
38375
39018
  const rects = [];
38376
39019
  layout.pages.forEach((page, pageIndex) => {
39020
+ const pageTopY = geometryHelper ? geometryHelper.getPageTop(pageIndex) : calculatePageTopFallback(layout, pageIndex);
38377
39021
  page.fragments.forEach((fragment) => {
38378
39022
  if (fragment.kind === "para") {
38379
39023
  const blockIndex = findBlockIndexByFragmentId(blocks, fragment.blockId, { from: from2, to });
@@ -38415,12 +39059,16 @@ function selectionToRects(layout, blocks, measures, from2, to) {
38415
39059
  wordLayout
38416
39060
  });
38417
39061
  const rectX = fragment.x + indentAdjust + Math.min(startX, endX);
38418
- const rectWidth = Math.max(1, Math.abs(endX - startX));
39062
+ const rectWidth = Math.max(
39063
+ 1,
39064
+ Math.min(Math.abs(endX - startX), line.width)
39065
+ // clamp to line width to prevent runaway widths
39066
+ );
38419
39067
  const lineOffset = lineHeightBeforeIndex(measure, index2) - lineHeightBeforeIndex(measure, fragment.fromLine);
38420
39068
  const rectY = fragment.y + lineOffset;
38421
39069
  rects.push({
38422
39070
  x: rectX,
38423
- y: rectY + pageIndex * (layout.pageSize.h + (layout.pageGap ?? 0)),
39071
+ y: rectY + pageTopY,
38424
39072
  width: rectWidth,
38425
39073
  height: line.lineHeight,
38426
39074
  pageIndex
@@ -38548,12 +39196,16 @@ function selectionToRects(layout, blocks, measures, from2, to) {
38548
39196
  wordLayout: cellWordLayout
38549
39197
  });
38550
39198
  const rectX = fragment.x + cellX + padding.left + textIndentAdjust + Math.min(startX, endX);
38551
- const rectWidth = Math.max(1, Math.abs(endX - startX));
39199
+ const rectWidth = Math.max(
39200
+ 1,
39201
+ Math.min(Math.abs(endX - startX), line.width)
39202
+ // clamp to line width to prevent runaway widths
39203
+ );
38552
39204
  const lineOffset = lineHeightBeforeIndex(info.measure, index2) - lineHeightBeforeIndex(info.measure, info.startLine);
38553
39205
  const rectY = fragment.y + rowOffset + blockTopCursor + lineOffset;
38554
39206
  rects.push({
38555
39207
  x: rectX,
38556
- y: rectY + pageIndex * (layout.pageSize.h + (layout.pageGap ?? 0)),
39208
+ y: rectY + pageTopY,
38557
39209
  width: rectWidth,
38558
39210
  height: line.lineHeight,
38559
39211
  pageIndex
@@ -38582,7 +39234,7 @@ function selectionToRects(layout, blocks, measures, from2, to) {
38582
39234
  if (!rangesOverlap(pmRange.pmStart, pmRange.pmEnd, from2, to)) return;
38583
39235
  rects.push({
38584
39236
  x: fragment.x,
38585
- y: fragment.y + pageIndex * (layout.pageSize.h + (layout.pageGap ?? 0)),
39237
+ y: fragment.y + pageTopY,
38586
39238
  width: fragment.width,
38587
39239
  height: fragment.height,
38588
39240
  pageIndex
@@ -39698,7 +40350,7 @@ async function measureParagraphBlock(block, maxWidth) {
39698
40350
  const wordEndWithSpace = charPosInRun + (isLastWord ? word.length : word.length + 1);
39699
40351
  const effectiveMaxWidth = currentLine ? currentLine.maxWidth : getEffectiveWidth(lines.length === 0 ? initialAvailableWidth : contentWidth);
39700
40352
  if (wordOnlyWidth > effectiveMaxWidth && word.length > 1) {
39701
- if (currentLine && currentLine.width > 0 && currentLine.segments.length > 0) {
40353
+ if (currentLine && currentLine.width > 0 && currentLine.segments && currentLine.segments.length > 0) {
39702
40354
  const metrics = calculateTypographyMetrics(currentLine.maxFontSize, spacing, currentLine.maxFontInfo);
39703
40355
  const { spaceCount: _sc, ...lineBase } = currentLine;
39704
40356
  const completedLine = { ...lineBase, ...metrics };
@@ -39709,7 +40361,7 @@ async function measureParagraphBlock(block, maxWidth) {
39709
40361
  currentLine = null;
39710
40362
  }
39711
40363
  const lineMaxWidth = getEffectiveWidth(lines.length === 0 ? initialAvailableWidth : contentWidth);
39712
- const hasTabOnlyLine = currentLine && currentLine.segments.length === 0 && currentLine.width > 0;
40364
+ const hasTabOnlyLine = currentLine && currentLine.segments && currentLine.segments.length === 0 && currentLine.width > 0;
39713
40365
  const remainingWidthAfterTab = hasTabOnlyLine ? currentLine.maxWidth - currentLine.width : lineMaxWidth;
39714
40366
  const chunkWidth = hasTabOnlyLine ? Math.max(remainingWidthAfterTab, lineMaxWidth * 0.25) : lineMaxWidth;
39715
40367
  const chunks = breakWordIntoChunks(word, chunkWidth - WIDTH_FUDGE_PX2, font, ctx2, run);
@@ -39720,7 +40372,7 @@ async function measureParagraphBlock(block, maxWidth) {
39720
40372
  const chunkEndChar = chunkCharOffset + chunk.text.length;
39721
40373
  const isLastChunk = chunkIndex === chunks.length - 1;
39722
40374
  const isFirstChunk = chunkIndex === 0;
39723
- if (isFirstChunk && hasTabOnlyLine && currentLine) {
40375
+ if (isFirstChunk && hasTabOnlyLine && currentLine && currentLine.segments) {
39724
40376
  currentLine.toRun = runIndex;
39725
40377
  currentLine.toChar = chunkEndChar;
39726
40378
  currentLine.width = roundValue(currentLine.width + chunk.width);
@@ -40553,6 +41205,7 @@ const createHeaderFooterEditor = ({
40553
41205
  const fontSizeInPixles = fontSizePt * 1.3333;
40554
41206
  const lineHeight = fontSizeInPixles * 1.2;
40555
41207
  applyStyleIsolationClass(editorContainer);
41208
+ const isFooter = type === "footer";
40556
41209
  Object.assign(editorContainer.style, {
40557
41210
  padding: "0",
40558
41211
  margin: "0",
@@ -40567,7 +41220,7 @@ const createHeaderFooterEditor = ({
40567
41220
  fontFamily: fontFamilyCss || typeface,
40568
41221
  fontSize: `${fontSizeInPixles}px`,
40569
41222
  lineHeight: `${lineHeight}px`,
40570
- overflow: "hidden",
41223
+ overflow: isFooter ? "visible" : "hidden",
40571
41224
  pointerEvents: "auto",
40572
41225
  // Critical: enables click interaction
40573
41226
  backgroundColor: "white"
@@ -41705,6 +42358,7 @@ class EditorOverlayManager {
41705
42358
  const editorContainer = __privateGet(this, _activeEditorHost).querySelector(".super-editor");
41706
42359
  if (editorContainer instanceof HTMLElement) {
41707
42360
  editorContainer.style.top = "0";
42361
+ editorContainer.style.transform = "";
41708
42362
  }
41709
42363
  }
41710
42364
  }
@@ -41938,6 +42592,7 @@ const DEFAULT_PAGE_SIZE = { w: 612, h: 792 };
41938
42592
  const DEFAULT_MARGINS = { top: 72, right: 72, bottom: 72, left: 72 };
41939
42593
  const DEFAULT_VIRTUALIZED_PAGE_GAP = 72;
41940
42594
  const DEFAULT_PAGE_GAP = 24;
42595
+ const DEFAULT_HORIZONTAL_PAGE_GAP = 20;
41941
42596
  const WORD_CHARACTER_REGEX = /[\p{L}\p{N}''_~-]/u;
41942
42597
  const MULTI_CLICK_TIME_THRESHOLD_MS = 400;
41943
42598
  const MULTI_CLICK_DISTANCE_THRESHOLD_PX = 5;
@@ -41961,6 +42616,7 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
41961
42616
  __privateAdd(this, _layoutOptions);
41962
42617
  __privateAdd(this, _layoutState, { blocks: [], measures: [], layout: null, bookmarks: /* @__PURE__ */ new Map() });
41963
42618
  __privateAdd(this, _domPainter, null);
42619
+ __privateAdd(this, _pageGeometryHelper, null);
41964
42620
  __privateAdd(this, _dragHandlerCleanup, null);
41965
42621
  __privateAdd(this, _layoutError, null);
41966
42622
  __privateAdd(this, _layoutErrorState, "healthy");
@@ -42129,7 +42785,8 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
42129
42785
  { x, y },
42130
42786
  __privateGet(this, _viewportHost),
42131
42787
  event.clientX,
42132
- event.clientY
42788
+ event.clientY,
42789
+ __privateGet(this, _pageGeometryHelper) ?? void 0
42133
42790
  );
42134
42791
  const doc2 = __privateGet(this, _editor3).state?.doc;
42135
42792
  const hit = rawHit && doc2 ? { ...rawHit, pos: Math.max(0, Math.min(rawHit.pos, doc2.content.size)) } : rawHit;
@@ -42328,7 +42985,8 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
42328
42985
  { x: normalized.x, y: normalized.y },
42329
42986
  __privateGet(this, _viewportHost),
42330
42987
  event.clientX,
42331
- event.clientY
42988
+ event.clientY,
42989
+ __privateGet(this, _pageGeometryHelper) ?? void 0
42332
42990
  );
42333
42991
  if (!hit) return;
42334
42992
  const currentTableHit = __privateMethod(this, _PresentationEditor_instances, hitTestTable_fn).call(this, normalized.x, normalized.y);
@@ -43218,7 +43876,14 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
43218
43876
  return __privateMethod(this, _PresentationEditor_instances, computeHeaderFooterSelectionRects_fn).call(this, start2, end2);
43219
43877
  }
43220
43878
  if (!__privateGet(this, _layoutState).layout) return [];
43221
- const rects = selectionToRects(__privateGet(this, _layoutState).layout, __privateGet(this, _layoutState).blocks, __privateGet(this, _layoutState).measures, start2, end2) ?? [];
43879
+ const rects = selectionToRects(
43880
+ __privateGet(this, _layoutState).layout,
43881
+ __privateGet(this, _layoutState).blocks,
43882
+ __privateGet(this, _layoutState).measures,
43883
+ start2,
43884
+ end2,
43885
+ __privateGet(this, _pageGeometryHelper) ?? void 0
43886
+ ) ?? [];
43222
43887
  return rects;
43223
43888
  };
43224
43889
  const rawRects = layoutRectSource();
@@ -43483,6 +44148,7 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
43483
44148
  };
43484
44149
  }
43485
44150
  __privateSet(this, _domPainter, null);
44151
+ __privateSet(this, _pageGeometryHelper, null);
43486
44152
  __privateSet(this, _pendingDocChange, true);
43487
44153
  __privateMethod(this, _PresentationEditor_instances, scheduleRerender_fn).call(this);
43488
44154
  }
@@ -43515,7 +44181,16 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
43515
44181
  x: localX,
43516
44182
  y: headerPageIndex * headerPageHeight + (localY - headerPageIndex * headerPageHeight)
43517
44183
  };
43518
- const hit2 = clickToPosition(context.layout, context.blocks, context.measures, headerPoint) ?? null;
44184
+ const hit2 = clickToPosition(
44185
+ context.layout,
44186
+ context.blocks,
44187
+ context.measures,
44188
+ headerPoint,
44189
+ void 0,
44190
+ void 0,
44191
+ void 0,
44192
+ void 0
44193
+ ) ?? null;
43519
44194
  return hit2;
43520
44195
  }
43521
44196
  if (!__privateGet(this, _layoutState).layout) {
@@ -43528,7 +44203,8 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
43528
44203
  normalized,
43529
44204
  __privateGet(this, _viewportHost),
43530
44205
  clientX,
43531
- clientY
44206
+ clientY,
44207
+ __privateGet(this, _pageGeometryHelper) ?? void 0
43532
44208
  ) ?? null;
43533
44209
  return hit;
43534
44210
  }
@@ -43751,6 +44427,7 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
43751
44427
  __privateSet(this, _session, { mode: "body" });
43752
44428
  __privateSet(this, _activeHeaderFooterEditor, null);
43753
44429
  __privateSet(this, _domPainter, null);
44430
+ __privateSet(this, _pageGeometryHelper, null);
43754
44431
  (_a = __privateGet(this, _dragHandlerCleanup)) == null ? void 0 : _a.call(this);
43755
44432
  __privateSet(this, _dragHandlerCleanup, null);
43756
44433
  __privateGet(this, _selectionOverlay2)?.remove();
@@ -43804,7 +44481,14 @@ const _PresentationEditor = class _PresentationEditor extends EventEmitter {
43804
44481
  if (!normalized) return false;
43805
44482
  const pmPos = __privateGet(this, _layoutState).bookmarks.get(normalized);
43806
44483
  if (pmPos == null) return false;
43807
- const rects = selectionToRects(layout, __privateGet(this, _layoutState).blocks, __privateGet(this, _layoutState).measures, pmPos, pmPos + 1) ?? [];
44484
+ const rects = selectionToRects(
44485
+ layout,
44486
+ __privateGet(this, _layoutState).blocks,
44487
+ __privateGet(this, _layoutState).measures,
44488
+ pmPos,
44489
+ pmPos + 1,
44490
+ __privateGet(this, _pageGeometryHelper) ?? void 0
44491
+ ) ?? [];
43808
44492
  const rect = rects[0];
43809
44493
  let pageIndex = rect?.pageIndex ?? null;
43810
44494
  if (pageIndex == null) {
@@ -43868,6 +44552,7 @@ _hiddenHost = new WeakMap();
43868
44552
  _layoutOptions = new WeakMap();
43869
44553
  _layoutState = new WeakMap();
43870
44554
  _domPainter = new WeakMap();
44555
+ _pageGeometryHelper = new WeakMap();
43871
44556
  _dragHandlerCleanup = new WeakMap();
43872
44557
  _layoutError = new WeakMap();
43873
44558
  _layoutErrorState = new WeakMap();
@@ -44152,18 +44837,19 @@ normalizeAwarenessStates_fn = function() {
44152
44837
  const normalized = /* @__PURE__ */ new Map();
44153
44838
  states?.forEach((aw, clientId) => {
44154
44839
  if (clientId === provider.awareness?.clientID) return;
44155
- if (!aw.cursor) return;
44840
+ const awState = aw;
44841
+ if (!awState.cursor) return;
44156
44842
  try {
44157
44843
  const anchor = relativePositionToAbsolutePosition(
44158
44844
  ystate.doc,
44159
44845
  ystate.type,
44160
- Y.createRelativePositionFromJSON(aw.cursor.anchor),
44846
+ Y.createRelativePositionFromJSON(awState.cursor.anchor),
44161
44847
  ystate.binding.mapping
44162
44848
  );
44163
44849
  const head = relativePositionToAbsolutePosition(
44164
44850
  ystate.doc,
44165
44851
  ystate.type,
44166
- Y.createRelativePositionFromJSON(aw.cursor.head),
44852
+ Y.createRelativePositionFromJSON(awState.cursor.head),
44167
44853
  ystate.binding.mapping
44168
44854
  );
44169
44855
  if (anchor === null || head === null) return;
@@ -44175,9 +44861,9 @@ normalizeAwarenessStates_fn = function() {
44175
44861
  normalized.set(clientId, {
44176
44862
  clientId,
44177
44863
  user: {
44178
- name: aw.user?.name,
44179
- email: aw.user?.email,
44180
- color: aw.user?.color || __privateMethod(this, _PresentationEditor_instances, getFallbackColor_fn).call(this, clientId)
44864
+ name: awState.user?.name,
44865
+ email: awState.user?.email,
44866
+ color: awState.user?.color || __privateMethod(this, _PresentationEditor_instances, getFallbackColor_fn).call(this, clientId)
44181
44867
  },
44182
44868
  anchor: clampedAnchor,
44183
44869
  head: clampedHead,
@@ -44499,7 +45185,7 @@ renderRemoteSelection_fn = function(cursor) {
44499
45185
  if (!layout || !blocks || !measures) return;
44500
45186
  const start2 = Math.min(cursor.anchor, cursor.head);
44501
45187
  const end2 = Math.max(cursor.anchor, cursor.head);
44502
- const rects = selectionToRects(layout, blocks, measures, start2, end2) ?? [];
45188
+ const rects = selectionToRects(layout, blocks, measures, start2, end2, __privateGet(this, _pageGeometryHelper) ?? void 0) ?? [];
44503
45189
  const color = __privateMethod(this, _PresentationEditor_instances, getValidatedColor_fn).call(this, cursor);
44504
45190
  const opacity = __privateGet(this, _layoutOptions).presence?.highlightOpacity ?? 0.35;
44505
45191
  const pageHeight = layout.pageSize?.h ?? __privateGet(this, _layoutOptions).pageSize?.h ?? DEFAULT_PAGE_SIZE.h;
@@ -44992,15 +45678,25 @@ hitTestTable_fn = function(normalizedX, normalizedY) {
44992
45678
  const configuredPageSize = __privateGet(this, _layoutOptions).pageSize ?? DEFAULT_PAGE_SIZE;
44993
45679
  let pageY = 0;
44994
45680
  let pageHit = null;
44995
- for (let i = 0; i < layout.pages.length; i++) {
44996
- const page = layout.pages[i];
44997
- const pageHeight = page.size?.h ?? configuredPageSize.h;
44998
- const gap = __privateGet(this, _layoutOptions).virtualization?.gap ?? DEFAULT_PAGE_GAP;
44999
- if (normalizedY >= pageY && normalizedY < pageY + pageHeight) {
45000
- pageHit = { pageIndex: i, page };
45001
- break;
45681
+ const geometryHelper = __privateGet(this, _pageGeometryHelper);
45682
+ if (geometryHelper) {
45683
+ const idx = geometryHelper.getPageIndexAtY(normalizedY) ?? geometryHelper.getNearestPageIndex(normalizedY);
45684
+ if (idx != null && layout.pages[idx]) {
45685
+ pageHit = { pageIndex: idx, page: layout.pages[idx] };
45686
+ pageY = geometryHelper.getPageTop(idx);
45687
+ }
45688
+ }
45689
+ if (!pageHit) {
45690
+ const gap = layout.pageGap ?? __privateMethod(this, _PresentationEditor_instances, getEffectivePageGap_fn).call(this);
45691
+ for (let i = 0; i < layout.pages.length; i++) {
45692
+ const page = layout.pages[i];
45693
+ const pageHeight = page.size?.h ?? configuredPageSize.h;
45694
+ if (normalizedY >= pageY && normalizedY < pageY + pageHeight) {
45695
+ pageHit = { pageIndex: i, page };
45696
+ break;
45697
+ }
45698
+ pageY += pageHeight + gap;
45002
45699
  }
45003
- pageY += pageHeight + gap;
45004
45700
  }
45005
45701
  if (!pageHit) {
45006
45702
  return null;
@@ -45312,12 +46008,7 @@ rerender_fn = async function() {
45312
46008
  return;
45313
46009
  }
45314
46010
  ({ layout, measures } = result);
45315
- if (__privateGet(this, _layoutOptions).virtualization?.enabled) {
45316
- const gap = __privateGet(this, _layoutOptions).virtualization.gap ?? DEFAULT_VIRTUALIZED_PAGE_GAP;
45317
- layout.pageGap = Math.max(0, gap);
45318
- } else {
45319
- layout.pageGap = DEFAULT_PAGE_GAP;
45320
- }
46011
+ layout.pageGap = __privateMethod(this, _PresentationEditor_instances, getEffectivePageGap_fn).call(this);
45321
46012
  headerLayouts = result.headers;
45322
46013
  footerLayouts = result.footers;
45323
46014
  } catch (error) {
@@ -45334,6 +46025,17 @@ rerender_fn = async function() {
45334
46025
  __privateSet(this, _layoutState, { blocks, measures, layout, bookmarks, anchorMap });
45335
46026
  __privateSet(this, _headerLayoutResults, headerLayouts ?? null);
45336
46027
  __privateSet(this, _footerLayoutResults, footerLayouts ?? null);
46028
+ if (__privateGet(this, _layoutState).layout) {
46029
+ const pageGap = __privateGet(this, _layoutState).layout.pageGap ?? __privateMethod(this, _PresentationEditor_instances, getEffectivePageGap_fn).call(this);
46030
+ if (!__privateGet(this, _pageGeometryHelper)) {
46031
+ __privateSet(this, _pageGeometryHelper, new PageGeometryHelper({
46032
+ layout: __privateGet(this, _layoutState).layout,
46033
+ pageGap
46034
+ }));
46035
+ } else {
46036
+ __privateGet(this, _pageGeometryHelper).updateLayout(__privateGet(this, _layoutState).layout, pageGap);
46037
+ }
46038
+ }
45337
46039
  await __privateMethod(this, _PresentationEditor_instances, layoutPerRIdHeaderFooters_fn).call(this, headerFooterInput, layout, sectionMetadata);
45338
46040
  __privateMethod(this, _PresentationEditor_instances, updateDecorationProviders_fn).call(this, layout);
45339
46041
  const painter = __privateMethod(this, _PresentationEditor_instances, ensurePainter_fn).call(this, blocks, measures);
@@ -45403,7 +46105,8 @@ ensurePainter_fn = function(blocks, measures) {
45403
46105
  pageStyles: __privateGet(this, _layoutOptions).pageStyles,
45404
46106
  headerProvider: __privateGet(this, _headerDecorationProvider),
45405
46107
  footerProvider: __privateGet(this, _footerDecorationProvider),
45406
- ruler: __privateGet(this, _layoutOptions).ruler
46108
+ ruler: __privateGet(this, _layoutOptions).ruler,
46109
+ pageGap: __privateGet(this, _layoutState).layout?.pageGap ?? __privateMethod(this, _PresentationEditor_instances, getEffectivePageGap_fn).call(this)
45407
46110
  }));
45408
46111
  }
45409
46112
  return __privateGet(this, _domPainter);
@@ -45558,7 +46261,14 @@ updateSelection_fn = function() {
45558
46261
  }
45559
46262
  return;
45560
46263
  }
45561
- const rects = selectionToRects(layout, __privateGet(this, _layoutState).blocks, __privateGet(this, _layoutState).measures, from2, to) ?? [];
46264
+ const rects = selectionToRects(
46265
+ layout,
46266
+ __privateGet(this, _layoutState).blocks,
46267
+ __privateGet(this, _layoutState).measures,
46268
+ from2,
46269
+ to,
46270
+ __privateGet(this, _pageGeometryHelper) ?? void 0
46271
+ ) ?? [];
45562
46272
  let domStart = null;
45563
46273
  let domEnd = null;
45564
46274
  try {
@@ -45572,7 +46282,9 @@ updateSelection_fn = function() {
45572
46282
  const correctedRects = __privateMethod(this, _PresentationEditor_instances, applyDomCorrectionToRects_fn).call(this, rects, domStart, domEnd);
45573
46283
  try {
45574
46284
  __privateGet(this, _localSelectionLayer).innerHTML = "";
45575
- __privateMethod(this, _PresentationEditor_instances, renderSelectionRects_fn).call(this, correctedRects);
46285
+ if (correctedRects.length > 0) {
46286
+ __privateMethod(this, _PresentationEditor_instances, renderSelectionRects_fn).call(this, correctedRects);
46287
+ }
45576
46288
  } catch (error) {
45577
46289
  if (process$1.env.NODE_ENV === "development") {
45578
46290
  console.warn("[PresentationEditor] Failed to render selection rects:", error);
@@ -45764,8 +46476,10 @@ createDecorationProvider_fn = function(kind, layout) {
45764
46476
  const pageHeight2 = page?.size?.h ?? layout.pageSize?.h ?? __privateGet(this, _layoutOptions).pageSize?.h ?? DEFAULT_PAGE_SIZE.h;
45765
46477
  const margins2 = pageMargins ?? layout.pages[0]?.margins ?? __privateGet(this, _layoutOptions).margins ?? DEFAULT_MARGINS;
45766
46478
  const box2 = __privateMethod(this, _PresentationEditor_instances, computeDecorationBox_fn).call(this, kind, margins2, pageHeight2);
46479
+ const layoutMinY2 = rIdLayout.layout.minY ?? 0;
46480
+ const normalizedFragments2 = layoutMinY2 < 0 ? fragments2.map((f2) => ({ ...f2, y: f2.y - layoutMinY2 })) : fragments2;
45767
46481
  return {
45768
- fragments: fragments2,
46482
+ fragments: normalizedFragments2,
45769
46483
  height: box2.height,
45770
46484
  contentHeight: rIdLayout.layout.height ?? box2.height,
45771
46485
  offset: box2.offset,
@@ -45773,6 +46487,7 @@ createDecorationProvider_fn = function(kind, layout) {
45773
46487
  contentWidth: box2.width,
45774
46488
  headerId: sectionRId,
45775
46489
  sectionType: headerFooterType,
46490
+ minY: layoutMinY2,
45776
46491
  box: {
45777
46492
  x: box2.x,
45778
46493
  y: box2.offset,
@@ -45805,8 +46520,10 @@ createDecorationProvider_fn = function(kind, layout) {
45805
46520
  const box = __privateMethod(this, _PresentationEditor_instances, computeDecorationBox_fn).call(this, kind, margins, pageHeight);
45806
46521
  const fallbackId = __privateGet(this, _headerFooterManager)?.getVariantId(kind, headerFooterType);
45807
46522
  const finalHeaderId = sectionRId ?? fallbackId ?? void 0;
46523
+ const layoutMinY = variant.layout.minY ?? 0;
46524
+ const normalizedFragments = layoutMinY < 0 ? fragments.map((f2) => ({ ...f2, y: f2.y - layoutMinY })) : fragments;
45808
46525
  return {
45809
- fragments,
46526
+ fragments: normalizedFragments,
45810
46527
  height: box.height,
45811
46528
  contentHeight: variant.layout.height ?? box.height,
45812
46529
  offset: box.offset,
@@ -45814,6 +46531,7 @@ createDecorationProvider_fn = function(kind, layout) {
45814
46531
  contentWidth: box.width,
45815
46532
  headerId: finalHeaderId,
45816
46533
  sectionType: headerFooterType,
46534
+ minY: layoutMinY,
45817
46535
  box: {
45818
46536
  x: box.x,
45819
46537
  y: box.offset,
@@ -45958,7 +46676,9 @@ rebuildHeaderFooterRegions_fn = function(layout) {
45958
46676
  localX: footerPayload?.hitRegion?.x ?? footerBox.x,
45959
46677
  localY: footerPayload?.hitRegion?.y ?? footerBox.offset,
45960
46678
  width: footerPayload?.hitRegion?.width ?? footerBox.width,
45961
- height: footerPayload?.hitRegion?.height ?? footerBox.height
46679
+ height: footerPayload?.hitRegion?.height ?? footerBox.height,
46680
+ contentHeight: footerPayload?.contentHeight,
46681
+ minY: footerPayload?.minY
45962
46682
  });
45963
46683
  });
45964
46684
  };
@@ -46088,6 +46808,18 @@ enterHeaderFooterMode_fn = async function(region) {
46088
46808
  });
46089
46809
  return;
46090
46810
  }
46811
+ if (region.kind === "footer") {
46812
+ const editorContainer = editorHost.firstElementChild;
46813
+ if (editorContainer instanceof HTMLElement) {
46814
+ editorContainer.style.overflow = "visible";
46815
+ if (region.minY != null && region.minY < 0) {
46816
+ const shiftDown = Math.abs(region.minY);
46817
+ editorContainer.style.transform = `translateY(${shiftDown}px)`;
46818
+ } else {
46819
+ editorContainer.style.transform = "";
46820
+ }
46821
+ }
46822
+ }
46091
46823
  try {
46092
46824
  editor.setEditable(true);
46093
46825
  editor.setOptions({ documentMode: "editing" });
@@ -46405,6 +47137,19 @@ waitForPageMount_fn = async function(pageIndex, options = {}) {
46405
47137
  checkPage();
46406
47138
  });
46407
47139
  };
47140
+ /**
47141
+ * Get effective page gap based on layout mode and virtualization settings.
47142
+ * Keeps painter, layout, and geometry in sync.
47143
+ */
47144
+ getEffectivePageGap_fn = function() {
47145
+ if (__privateGet(this, _layoutOptions).virtualization?.enabled) {
47146
+ return Math.max(0, __privateGet(this, _layoutOptions).virtualization.gap ?? DEFAULT_VIRTUALIZED_PAGE_GAP);
47147
+ }
47148
+ if (__privateGet(this, _layoutOptions).layoutMode === "horizontal") {
47149
+ return DEFAULT_HORIZONTAL_PAGE_GAP;
47150
+ }
47151
+ return DEFAULT_PAGE_GAP;
47152
+ };
46408
47153
  getBodyPageHeight_fn = function() {
46409
47154
  return __privateGet(this, _layoutState).layout?.pageSize?.h ?? __privateGet(this, _layoutOptions).pageSize?.h ?? DEFAULT_PAGE_SIZE.h;
46410
47155
  };
@@ -46457,7 +47202,7 @@ applyDomCorrectionToRects_fn = function(rects, domStart, domEnd) {
46457
47202
  dy: domStart.y - layoutY
46458
47203
  };
46459
47204
  }
46460
- return rects.map((rect, idx) => {
47205
+ const corrected = rects.map((rect, idx) => {
46461
47206
  const delta = pageDelta[rect.pageIndex];
46462
47207
  let adjustedX = delta ? rect.x + delta.dx : rect.x;
46463
47208
  let adjustedY = delta ? rect.y + delta.dy : rect.y;
@@ -46472,6 +47217,7 @@ applyDomCorrectionToRects_fn = function(rects, domStart, domEnd) {
46472
47217
  }
46473
47218
  if (isLastRect && domEnd && rect.pageIndex === domEnd.pageIndex) {
46474
47219
  const endX = domEnd.x;
47220
+ adjustedX = Math.min(adjustedX, endX);
46475
47221
  adjustedWidth = Math.max(1, endX - adjustedX);
46476
47222
  }
46477
47223
  return {
@@ -46481,6 +47227,29 @@ applyDomCorrectionToRects_fn = function(rects, domStart, domEnd) {
46481
47227
  width: adjustedWidth
46482
47228
  };
46483
47229
  });
47230
+ const MAX_DELTA_PX = 12;
47231
+ let invalid = false;
47232
+ if (domStart && corrected[0]) {
47233
+ const dx = Math.abs(corrected[0].x - domStart.x);
47234
+ const dy = Math.abs(corrected[0].y - domStart.y);
47235
+ if (dx > MAX_DELTA_PX || dy > MAX_DELTA_PX) invalid = true;
47236
+ }
47237
+ if (domEnd && corrected[corrected.length - 1]) {
47238
+ const last = corrected[corrected.length - 1];
47239
+ const dx = Math.abs(last.x + last.width - domEnd.x);
47240
+ const dy = Math.abs(last.y - domEnd.y);
47241
+ if (dx > MAX_DELTA_PX || dy > MAX_DELTA_PX) invalid = true;
47242
+ }
47243
+ if (invalid) {
47244
+ console.warn("[SelectionOverlay] Suppressing selection render due to large DOM/Layout mismatch", {
47245
+ domStart,
47246
+ domEnd,
47247
+ rectStart: corrected[0],
47248
+ rectEnd: corrected[corrected.length - 1]
47249
+ });
47250
+ return [];
47251
+ }
47252
+ return corrected;
46484
47253
  };
46485
47254
  /**
46486
47255
  * Renders visual highlighting for CellSelection (multiple table cells selected).
@@ -46798,7 +47567,7 @@ computeHeaderFooterSelectionRects_fn = function(from2, to) {
46798
47567
  return [];
46799
47568
  }
46800
47569
  if (!bodyLayout) return [];
46801
- const rects = selectionToRects(context.layout, context.blocks, context.measures, from2, to) ?? [];
47570
+ const rects = selectionToRects(context.layout, context.blocks, context.measures, from2, to, void 0) ?? [];
46802
47571
  const headerPageHeight = context.layout.pageSize?.h ?? context.region.height ?? 1;
46803
47572
  const bodyPageHeight = __privateMethod(this, _PresentationEditor_instances, getBodyPageHeight_fn).call(this);
46804
47573
  return rects.map((rect) => {
@@ -47190,8 +47959,8 @@ computeCaretLayoutRectGeometry_fn = function(pos, includeDomFallback = true) {
47190
47959
  const zoom2 = __privateGet(this, _layoutOptions).zoom ?? 1;
47191
47960
  let domCaretX2 = null;
47192
47961
  let domCaretY2 = null;
47193
- const spanEls2 = pageEl2?.querySelectorAll("span[data-pm-start][data-pm-end]") ?? [];
47194
- for (const spanEl of spanEls2) {
47962
+ const spanEls2 = pageEl2?.querySelectorAll("span[data-pm-start][data-pm-end]");
47963
+ for (const spanEl of Array.from(spanEls2 ?? [])) {
47195
47964
  const pmStart = Number(spanEl.dataset.pmStart);
47196
47965
  const pmEnd = Number(spanEl.dataset.pmEnd);
47197
47966
  if (pos >= pmStart && pos <= pmEnd && spanEl.firstChild?.nodeType === Node.TEXT_NODE) {
@@ -47243,8 +48012,8 @@ computeCaretLayoutRectGeometry_fn = function(pos, includeDomFallback = true) {
47243
48012
  const zoom = __privateGet(this, _layoutOptions).zoom ?? 1;
47244
48013
  let domCaretX = null;
47245
48014
  let domCaretY = null;
47246
- const spanEls = pageEl?.querySelectorAll("span[data-pm-start][data-pm-end]") ?? [];
47247
- for (const spanEl of spanEls) {
48015
+ const spanEls = pageEl?.querySelectorAll("span[data-pm-start][data-pm-end]");
48016
+ for (const spanEl of Array.from(spanEls ?? [])) {
47248
48017
  const pmStart = Number(spanEl.dataset.pmStart);
47249
48018
  const pmEnd = Number(spanEl.dataset.pmEnd);
47250
48019
  if (pos >= pmStart && pos <= pmEnd && spanEl.firstChild?.nodeType === Node.TEXT_NODE) {
@@ -47485,7 +48254,14 @@ getCurrentPageIndex_fn = function() {
47485
48254
  if (!layout || !selection) {
47486
48255
  return 0;
47487
48256
  }
47488
- const rects = selectionToRects(layout, __privateGet(this, _layoutState).blocks, __privateGet(this, _layoutState).measures, selection.from, selection.to) ?? [];
48257
+ const rects = selectionToRects(
48258
+ layout,
48259
+ __privateGet(this, _layoutState).blocks,
48260
+ __privateGet(this, _layoutState).measures,
48261
+ selection.from,
48262
+ selection.to,
48263
+ __privateGet(this, _pageGeometryHelper) ?? void 0
48264
+ ) ?? [];
47489
48265
  if (rects.length > 0) {
47490
48266
  return rects[0]?.pageIndex ?? 0;
47491
48267
  }
@@ -53050,14 +53826,19 @@ const createCell = (cellType, cellContent = null) => {
53050
53826
  }
53051
53827
  return cellType.createAndFill();
53052
53828
  };
53053
- const createTableBorders = ({ size = 0.66665, color = "#000000" } = {}) => {
53829
+ const createTableBorders = (borderSpec = {}) => {
53830
+ borderSpec = {
53831
+ size: 0.66665,
53832
+ color: "#000000",
53833
+ ...borderSpec
53834
+ };
53054
53835
  return {
53055
- top: { size, color },
53056
- left: { size, color },
53057
- bottom: { size, color },
53058
- right: { size, color },
53059
- insideH: { size, color },
53060
- insideV: { size, color }
53836
+ top: borderSpec,
53837
+ left: borderSpec,
53838
+ bottom: borderSpec,
53839
+ right: borderSpec,
53840
+ insideH: borderSpec,
53841
+ insideV: borderSpec
53061
53842
  };
53062
53843
  };
53063
53844
  const createTable = (schema, rowsCount, colsCount, withHeaderRow, cellContent = null) => {
@@ -53185,12 +53966,17 @@ const deleteTableWhenSelected = ({ editor }) => {
53185
53966
  editor.commands.deleteTable();
53186
53967
  return true;
53187
53968
  };
53188
- const createCellBorders = ({ size = 0.66665, color = "#000000" } = {}) => {
53969
+ const createCellBorders = (borderSpec = {}) => {
53970
+ borderSpec = {
53971
+ size: 0.66665,
53972
+ color: "#000000",
53973
+ ...borderSpec
53974
+ };
53189
53975
  return {
53190
- top: { size, color },
53191
- left: { size, color },
53192
- bottom: { size, color },
53193
- right: { size, color }
53976
+ top: borderSpec,
53977
+ left: borderSpec,
53978
+ bottom: borderSpec,
53979
+ right: borderSpec
53194
53980
  };
53195
53981
  };
53196
53982
  function cellAround($pos) {
@@ -53957,13 +54743,20 @@ const Table = Node$1.create({
53957
54743
  if (["tableCell", "tableHeader"].includes(node.type.name)) {
53958
54744
  tr.setNodeMarkup(pos, void 0, {
53959
54745
  ...node.attrs,
53960
- borders: createCellBorders({ size: 0 })
54746
+ borders: createCellBorders({ size: 0, space: 0, val: "none", color: "auto" })
53961
54747
  });
53962
54748
  }
53963
54749
  });
53964
54750
  tr.setNodeMarkup(table.pos, void 0, {
53965
54751
  ...table.node.attrs,
53966
- borders: createTableBorders({ size: 0 })
54752
+ borders: createTableBorders({ size: 0 }),
54753
+ // TODO: This works around the issue that table borders are duplicated between
54754
+ // the attributes of the table and the tableProperties attribute.
54755
+ // This can be removed when the redundancy is eliminated.
54756
+ tableProperties: {
54757
+ ...table.node.attrs.tableProperties,
54758
+ borders: createTableBorders({ size: 0, space: 0, val: "none", color: "auto" })
54759
+ }
53967
54760
  });
53968
54761
  return true;
53969
54762
  }