UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

774 lines (750 loc) 67 kB
import rafSchedule from 'raf-schd'; import { getDocument } from '@atlaskit/browser-apis'; import { ACTION, ACTION_SUBJECT, ACTION_SUBJECT_ID, EVENT_TYPE } from '@atlaskit/editor-common/analytics'; import { getBrowserInfo } from '@atlaskit/editor-common/browser'; import { getNodeIdProvider } from '@atlaskit/editor-common/node-anchor'; import { isMeasuring, startMeasure, stopMeasure } from '@atlaskit/editor-common/performance-measures'; import { SafePlugin } from '@atlaskit/editor-common/safe-plugin'; import { DRAG_HANDLE_SELECTOR } from '@atlaskit/editor-common/styles'; import { areToolbarFlagsEnabled } from '@atlaskit/editor-common/toolbar-flag-check'; import { EDIT_AREA_ID } from '@atlaskit/editor-common/ui'; import { isEmptyDocument } from '@atlaskit/editor-common/utils'; import { PluginKey, TextSelection } from '@atlaskit/editor-prosemirror/state'; import { DecorationSet } from '@atlaskit/editor-prosemirror/view'; import { fg } from '@atlaskit/platform-feature-flags'; import { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element'; import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'; import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'; import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals'; import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments'; import { getAnchorAttrName } from '../ui/utils/dom-attr-name'; import { findNodeDecs, nodeDecorations } from './decorations-anchor'; import { createActiveDragHandleNodeDecoration, dragHandleDecoration, emptyParagraphNodeDecorations, findActiveDragHandleNodeDec, findHandleDec } from './decorations-drag-handle'; import { dropTargetDecorations, findDropTargetDecs } from './decorations-drop-target'; import { getActiveDropTargetDecorations } from './decorations-drop-target-active'; import { createActiveQuickInsertNodeDecoration, findActiveQuickInsertNodeDec, findQuickInsertInsertButtonDecoration, quickInsertButtonDecoration } from './decorations-quick-insert-button'; import { handleMouseDown } from './handle-mouse-down'; import { handleMouseOver } from './handle-mouse-over'; import { boundKeydownHandler } from './keymap'; import { defaultActiveAnchorTracker } from './utils/active-anchor-tracker'; import { getMultiSelectAnalyticsAttributes } from './utils/analytics'; import { AnchorRectCache, isAnchorSupported } from './utils/anchor-utils'; import { selectNode } from './utils/getSelection'; import { getSelectedSlicePosition } from './utils/selection'; import { getTrMetadata } from './utils/transactions'; export const key = new PluginKey('blockControls'); const EDITOR_BLOCKS_DRAG_INIT = 'Editor Blocks Drag Initialization Time'; const EDITOR_BLOCKS_DROP_INIT = 'Editor Blocks Drop Initialization Time'; const scheduleCallback = (cb, options) => { return 'requestIdleCallback' in window ? requestIdleCallback(cb, { timeout: 5000, ...options }) : requestAnimationFrame(cb); }; const isHTMLElement = element => { return element instanceof HTMLElement; }; const destroyFn = (api, editorView) => { var _getDocument$querySel, _getDocument; const scrollable = (_getDocument$querySel = (_getDocument = getDocument()) === null || _getDocument === void 0 ? void 0 : _getDocument.querySelector('.fabric-editor-popup-scroll-parent')) !== null && _getDocument$querySel !== void 0 ? _getDocument$querySel : null; const cleanupFn = []; if (scrollable) { cleanupFn.push(autoScrollForElements({ element: scrollable })); } let dragInitializationDuration = 0; cleanupFn.push(monitorForElements({ canMonitor: ({ source }) => source.data.type === 'element', onDrag: () => { if (fg('platform_editor_drag_and_drop_perf_analytics')) { if (isMeasuring(EDITOR_BLOCKS_DRAG_INIT)) { stopMeasure(EDITOR_BLOCKS_DRAG_INIT, duration => { dragInitializationDuration = duration; }); } } else { if (isMeasuring(EDITOR_BLOCKS_DRAG_INIT)) { stopMeasure(EDITOR_BLOCKS_DRAG_INIT, (duration, startTime) => { var _api$analytics; api === null || api === void 0 ? void 0 : (_api$analytics = api.analytics) === null || _api$analytics === void 0 ? void 0 : _api$analytics.actions.fireAnalyticsEvent({ action: ACTION.BLOCKS_DRAG_INIT, actionSubject: ACTION_SUBJECT.EDITOR, eventType: EVENT_TYPE.OPERATIONAL, attributes: { duration, startTime, nodesCount: editorView === null || editorView === void 0 ? void 0 : editorView.state.doc.nodeSize } }); }); } } }, onDragStart: () => { if (isHTMLElement(scrollable)) { scrollable.style.setProperty('scroll-behavior', 'unset'); } }, onDrop: ({ location, source }) => { var _api$core; if (isHTMLElement(scrollable)) { scrollable.style.setProperty('scroll-behavior', null); } if (fg('platform_editor_drag_and_drop_perf_analytics')) { startMeasure(EDITOR_BLOCKS_DROP_INIT); } if (!api) { return; } (_api$core = api.core) === null || _api$core === void 0 ? void 0 : _api$core.actions.execute(({ tr }) => { var _api$blockControls, _api$selection, _api$userIntent; const { multiSelectDnD } = ((_api$blockControls = api.blockControls) === null || _api$blockControls === void 0 ? void 0 : _api$blockControls.sharedState.currentState()) || {}; // Restore the users initial Editor selection when the drop completes if (multiSelectDnD) { // If the TextSelection between the drag start and end has changed, the document has changed, and we should not reapply the last selection const expandedSelectionUnchanged = multiSelectDnD.textAnchor === tr.selection.anchor && multiSelectDnD.textHead === tr.selection.head; if (expandedSelectionUnchanged) { const $anchor = tr.doc.resolve(multiSelectDnD.userAnchor); const $head = tr.doc.resolve(multiSelectDnD.userHead); if ($head.node() === $anchor.node()) { const $from = $anchor.min($head); selectNode(tr, $from.pos, $from.node().type.name, api); } else { tr.setSelection(TextSelection.create(tr.doc, multiSelectDnD.userAnchor, multiSelectDnD.userHead)); } } } (_api$selection = api.selection) === null || _api$selection === void 0 ? void 0 : _api$selection.commands.clearManualSelection()({ tr }); const { start } = source.data; // if no drop targets are rendered, assume that drop is invalid const lastDragCancelled = location.current.dropTargets.length === 0; if (lastDragCancelled) { var _api$analytics2; const position = getSelectedSlicePosition(start, tr, api); const attributes = getMultiSelectAnalyticsAttributes(tr, position.from, position.to); const { nodeTypes, hasSelectedMultipleNodes } = attributes; const resolvedMovingNode = tr.doc.resolve(start); (_api$analytics2 = api.analytics) === null || _api$analytics2 === void 0 ? void 0 : _api$analytics2.actions.attachAnalyticsEvent({ eventType: EVENT_TYPE.UI, action: ACTION.CANCELLED, actionSubject: ACTION_SUBJECT.DRAG, actionSubjectId: ACTION_SUBJECT_ID.ELEMENT_DRAG_HANDLE, attributes: { nodeDepth: resolvedMovingNode.depth, nodeTypes: nodeTypes || '', hasSelectedMultipleNodes } })(tr); } if (fg('platform_editor_ease_of_use_metrics')) { var _api$metrics; (_api$metrics = api.metrics) === null || _api$metrics === void 0 ? void 0 : _api$metrics.commands.startActiveSessionTimer()({ tr }); } (_api$userIntent = api.userIntent) === null || _api$userIntent === void 0 ? void 0 : _api$userIntent.commands.setCurrentUserIntent('default')({ tr }); return tr.setMeta(key, { ...tr.getMeta(key), isDragging: false, isPMDragging: false, lastDragCancelled }); }); if (fg('platform_editor_drag_and_drop_perf_analytics')) { // wait for the idle callback to ensure that the drag operation has completed scheduleCallback(() => { if (isMeasuring(EDITOR_BLOCKS_DROP_INIT)) { stopMeasure(EDITOR_BLOCKS_DROP_INIT, duration => { var _api$analytics3; const isCancelled = location.current.dropTargets.length === 0; api === null || api === void 0 ? void 0 : (_api$analytics3 = api.analytics) === null || _api$analytics3 === void 0 ? void 0 : _api$analytics3.actions.fireAnalyticsEvent({ action: ACTION.ENDED, eventType: EVENT_TYPE.TRACK, actionSubject: ACTION_SUBJECT.DRAG, actionSubjectId: ACTION_SUBJECT_ID.ELEMENT_DRAG_HANDLE, attributes: { dragInitializationDuration, dropProcessingDuration: duration, isCancelled, nodesCount: editorView === null || editorView === void 0 ? void 0 : editorView.state.doc.nodeSize } }); }); } }); } } })); return combine(...cleanupFn); }; const initialState = { decorations: DecorationSet.empty, activeNode: undefined, isDragging: false, isMenuOpen: false, editorHeight: 0, editorWidthLeft: 0, editorWidthRight: 0, isResizerResizing: false, isDocSizeLimitEnabled: null, isPMDragging: false, multiSelectDnD: undefined, lastDragCancelled: false, isSelectedViaDragHandle: false }; export const getDecorations = state => { var _key$getState; return (_key$getState = key.getState(state)) === null || _key$getState === void 0 ? void 0 : _key$getState.decorations; }; const getDecorationAtPos = (state, decorations, pos, to) => { // Find the newly minted node decs that touch the active node const findNewNodeDecs = findNodeDecs(state, decorations, pos - 1, to); // Find the specific dec that the active node corresponds to const nodeDecsAtActivePos = findNewNodeDecs.filter(dec => (dec === null || dec === void 0 ? void 0 : dec.from) === pos); // If multiple decorations at the active node pos, we want the last one const nodeDecAtActivePos = nodeDecsAtActivePos.pop(); return nodeDecAtActivePos; }; export const apply = (api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled = false, quickInsertButtonEnabled = true, anchorRectCache, resizeObserverWidth, pragmaticCleanup) => { var _api$limitedMode, _api$limitedMode$shar, _api$limitedMode$shar2, _meta$multiSelectDnD, _api$editorViewMode, _api$editorViewMode$s, _activeNode, _activeNode2, _meta$activeNode$hand, _activeNode3, _activeNode4, _meta$isDragging2, _meta$isDragging3, _meta$toggleMenu, _meta$toggleMenu2, _meta$toggleMenu3, _meta$toggleMenu4, _meta$toggleMenu5, _meta$toggleMenu6, _meta$toggleMenu7, _meta$toggleMenu8, _meta$editorHeight, _meta$editorWidthLeft, _meta$editorWidthRigh, _meta$isPMDragging, _meta$isShiftDown, _meta$lastDragCancell; let { activeNode, decorations, isResizerResizing, multiSelectDnD } = currentState; const { editorHeight, editorWidthLeft, editorWidthRight, isDragging, isMenuOpen, menuTriggerBy, menuTriggerByNode, blockMenuOptions, isPMDragging, isShiftDown, lastDragCancelled, isSelectedViaDragHandle } = currentState; let isActiveNodeDeleted = false; const { from, to, numReplaceSteps, isAllText, isReplacedWithSameSize } = getTrMetadata(tr, flags); const meta = tr.getMeta(key); const hasDocumentSizeBreachedThreshold = api === null || api === void 0 ? void 0 : (_api$limitedMode = api.limitedMode) === null || _api$limitedMode === void 0 ? void 0 : (_api$limitedMode$shar = _api$limitedMode.sharedState.currentState()) === null || _api$limitedMode$shar === void 0 ? void 0 : (_api$limitedMode$shar2 = _api$limitedMode$shar.limitedModePluginKey.getState(newState)) === null || _api$limitedMode$shar2 === void 0 ? void 0 : _api$limitedMode$shar2.documentSizeBreachesThreshold; if (hasDocumentSizeBreachedThreshold) { var _getDocument$querySel2, _getDocument2; /** * INFO: This if statement is a duplicate of the logic in destroy(). When the threshold is breached and we enter limited mode, we want to trigger the cleanup logic in destroy(). */ const editorContentArea = (_getDocument$querySel2 = (_getDocument2 = getDocument()) === null || _getDocument2 === void 0 ? void 0 : _getDocument2.querySelector('.fabric-editor-popup-scroll-parent')) !== null && _getDocument$querySel2 !== void 0 ? _getDocument$querySel2 : null; if (editorContentArea && resizeObserverWidth) { resizeObserverWidth.unobserve(editorContentArea); } pragmaticCleanup === null || pragmaticCleanup === void 0 ? void 0 : pragmaticCleanup(); return currentState; } // When steps exist, remap existing decorations, activeNode and multi select positions if (tr.docChanged) { decorations = decorations.map(tr.mapping, tr.doc); // platform_editor_controls note: enables quick insert // don't remap activeNode if it's being dragged if (!flags.toolbarFlagsEnabled) { if (activeNode) { const mappedPos = tr.mapping.mapResult(activeNode.pos); isActiveNodeDeleted = mappedPos.deleted; activeNode = { pos: mappedPos.pos, anchorName: activeNode.anchorName, nodeType: activeNode.nodeType }; } } else { if (activeNode && (meta === null || meta === void 0 ? void 0 : meta.isDragging) !== true) { var _mappedRootPos$pos, _mappedRootPos; let mappedPos; const browser = getBrowserInfo(); // In safari, when platform_editor_controls is on, // sometimes the drag handle for the layout disppears after you click on the handle for a few times // Which caused the drag handle onClick event not firing, then block menu wouldn't be opened // This is caused by the mappedPos.deletedAfter sometimes returning true in webkit browsers even though the active node still exists // This is likely a prosemirror and safari integration bug, but to unblock the issue, we are going to use mappedPos.deleted in safari for now if (browser.webkit && editorExperiment('platform_editor_block_menu', true)) { mappedPos = tr.mapping.mapResult(activeNode.pos); isActiveNodeDeleted = mappedPos.deleted; } else { mappedPos = tr.mapping.mapResult(activeNode.pos, -1); isActiveNodeDeleted = mappedPos.deletedAfter; } // for editor controls, remap the rootPos as well let mappedRootPos; if (activeNode.rootPos !== undefined) { mappedRootPos = tr.mapping.mapResult(activeNode.rootPos, -1); } activeNode = { pos: mappedPos.pos, anchorName: activeNode.anchorName, nodeType: activeNode.nodeType, rootPos: (_mappedRootPos$pos = (_mappedRootPos = mappedRootPos) === null || _mappedRootPos === void 0 ? void 0 : _mappedRootPos.pos) !== null && _mappedRootPos$pos !== void 0 ? _mappedRootPos$pos : activeNode.rootPos, rootAnchorName: activeNode.rootAnchorName, rootNodeType: activeNode.rootNodeType }; } } if (multiSelectDnD) { multiSelectDnD.anchor = tr.mapping.map(multiSelectDnD.anchor); multiSelectDnD.head = tr.mapping.map(multiSelectDnD.head); } } const resizerMeta = tr.getMeta('is-resizer-resizing'); isResizerResizing = resizerMeta !== null && resizerMeta !== void 0 ? resizerMeta : isResizerResizing; const hasJustFinishedResizing = resizerMeta === false; multiSelectDnD = (_meta$multiSelectDnD = meta === null || meta === void 0 ? void 0 : meta.multiSelectDnD) !== null && _meta$multiSelectDnD !== void 0 ? _meta$multiSelectDnD : multiSelectDnD; if (multiSelectDnD) { var _meta$isDragging; if (((_meta$isDragging = meta === null || meta === void 0 ? void 0 : meta.isDragging) !== null && _meta$isDragging !== void 0 ? _meta$isDragging : isDragging) && expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) { // When dragging, we want to keep the multiSelectDnD object unless both document and selection // has changed, in which case we want to reset it. const shouldResetMultiSelectDnD = tr.docChanged && tr.selectionSet && tr.selection.empty; multiSelectDnD = shouldResetMultiSelectDnD ? undefined : multiSelectDnD; } else { multiSelectDnD = (meta === null || meta === void 0 ? void 0 : meta.isDragging) === false || tr.selection.empty ? undefined : multiSelectDnD; } } const maybeNodeCountChanged = !isAllText && numReplaceSteps > 0; let latestActiveNode = meta === null || meta === void 0 ? void 0 : meta.activeNode; const isViewMode = (api === null || api === void 0 ? void 0 : (_api$editorViewMode = api.editorViewMode) === null || _api$editorViewMode === void 0 ? void 0 : (_api$editorViewMode$s = _api$editorViewMode.sharedState.currentState()) === null || _api$editorViewMode$s === void 0 ? void 0 : _api$editorViewMode$s.mode) === 'view'; if (!latestActiveNode && (!isActiveNodeDeleted || isReplacedWithSameSize)) { latestActiveNode = activeNode; } // Re-create node decorations const isDecSetEmpty = decorations === DecorationSet.empty; const isNodeDecsMissing = isDecSetEmpty || maybeNodeCountChanged || editorExperiment('platform_editor_breakout_resizing', true) && hasJustFinishedResizing; const shouldRedrawNodeDecs = !isResizerResizing && (isNodeDecsMissing || (meta === null || meta === void 0 ? void 0 : meta.isDragging)) && // Skip expensive anchor node decoration recalculations when native anchor support is enabled !expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true); let isActiveNodeModified = false; if (api && shouldRedrawNodeDecs) { const oldNodeDecs = findNodeDecs(newState, decorations, from, to); decorations = decorations.remove(oldNodeDecs); const newNodeDecs = nodeDecorations(newState, isDecSetEmpty ? undefined : from, isDecSetEmpty ? undefined : to); decorations = decorations.add(newState.doc, newNodeDecs); // platform_editor_controls note: enables quick insert if (!flags.toolbarFlagsEnabled) { if (latestActiveNode && !isActiveNodeDeleted) { // Find the newly minted node decs that touch the active node const findNewNodeDecs = findNodeDecs(newState, decorations, latestActiveNode.pos - 1, to); // Find the specific dec that the active node corresponds to const nodeDecsAtActivePos = findNewNodeDecs.filter(dec => (dec === null || dec === void 0 ? void 0 : dec.from) === latestActiveNode.pos); // If multiple decorations at the active node pos, we want the last one const nodeDecAtActivePos = nodeDecsAtActivePos.pop(); // Update the active node anchor-name and type for accurate positioning if (nodeDecAtActivePos) { isActiveNodeModified = true; latestActiveNode.anchorName = nodeDecAtActivePos.spec.anchorName; latestActiveNode.nodeType = nodeDecAtActivePos.spec.nodeType; } } } else { if (latestActiveNode && (!isActiveNodeDeleted || isReplacedWithSameSize)) { const nodeDecAtActivePos = getDecorationAtPos(newState, decorations, latestActiveNode.pos, to); // Guard against rootPos being undefined (keyboard-triggered handles do not set it), // which would cause a RangeError in ProseMirror. When the gate is off, the original // behaviour is preserved for safe incremental rollout. const rootNodeDecAtActivePos = fg('platform_editor_block_menu_jira_patch_1') ? latestActiveNode.rootPos !== undefined ? getDecorationAtPos(newState, decorations, latestActiveNode.rootPos, to) : undefined : getDecorationAtPos(newState, decorations, latestActiveNode.rootPos, to); if (nodeDecAtActivePos || rootNodeDecAtActivePos) { isActiveNodeModified = true; } // Update the active node anchor-name and type for accurate positioning if (nodeDecAtActivePos) { latestActiveNode.anchorName = nodeDecAtActivePos.spec.anchorName; latestActiveNode.nodeType = nodeDecAtActivePos.spec.nodeType; } if (rootNodeDecAtActivePos) { latestActiveNode.rootAnchorName = rootNodeDecAtActivePos.spec.anchorName; latestActiveNode.rootNodeType = rootNodeDecAtActivePos.spec.nodeType; } } } } // Check if editor dimensions have changed const editorSizeChanged = (meta === null || meta === void 0 ? void 0 : meta.editorHeight) !== undefined && (meta === null || meta === void 0 ? void 0 : meta.editorHeight) !== editorHeight || (meta === null || meta === void 0 ? void 0 : meta.editorWidthLeft) !== undefined && (meta === null || meta === void 0 ? void 0 : meta.editorWidthLeft) !== editorWidthLeft || (meta === null || meta === void 0 ? void 0 : meta.editorWidthRight) !== undefined && (meta === null || meta === void 0 ? void 0 : meta.editorWidthRight) !== editorWidthRight; // Check if there's a new active node, and it differs from the last const activeNodeChanged = (meta === null || meta === void 0 ? void 0 : meta.activeNode) && ((meta === null || meta === void 0 ? void 0 : meta.activeNode.pos) !== ((_activeNode = activeNode) === null || _activeNode === void 0 ? void 0 : _activeNode.pos) && (meta === null || meta === void 0 ? void 0 : meta.activeNode.anchorName) !== ((_activeNode2 = activeNode) === null || _activeNode2 === void 0 ? void 0 : _activeNode2.anchorName) || (meta === null || meta === void 0 ? void 0 : (_meta$activeNode$hand = meta.activeNode.handleOptions) === null || _meta$activeNode$hand === void 0 ? void 0 : _meta$activeNode$hand.isFocused)); const rootActiveNodeChanged = (meta === null || meta === void 0 ? void 0 : meta.activeNode) && (meta === null || meta === void 0 ? void 0 : meta.activeNode.rootPos) !== ((_activeNode3 = activeNode) === null || _activeNode3 === void 0 ? void 0 : _activeNode3.rootPos) && (meta === null || meta === void 0 ? void 0 : meta.activeNode.rootAnchorName) !== ((_activeNode4 = activeNode) === null || _activeNode4 === void 0 ? void 0 : _activeNode4.rootAnchorName); // Some browsers don't support anchor positioning, meaning we need to replace the handle when nodes change const handleNeedsRedraw = shouldRedrawNodeDecs && !isAnchorSupported(); // Create/recreate handle dec when the active node is missing/changes, or the editor viewport has changed (non-anchor pos workaround) const shouldRecreateHandle = latestActiveNode && (activeNodeChanged || isActiveNodeModified || editorSizeChanged || handleNeedsRedraw); const shouldRecreateQuickInsertButton = latestActiveNode && (rootActiveNodeChanged || isActiveNodeModified || editorSizeChanged || handleNeedsRedraw); // If the active node is missing, we need to remove the handle let shouldRemoveHandle = latestActiveNode ? isResizerResizing || isActiveNodeDeleted && !isReplacedWithSameSize || (meta === null || meta === void 0 ? void 0 : meta.nodeMoved) : true; // platform_editor_controls note: enables quick insert if (flags.toolbarFlagsEnabled) { // Remove handle dec when editor is blurred shouldRemoveHandle = shouldRemoveHandle || (meta === null || meta === void 0 ? void 0 : meta.editorBlurred); } // In view mode with right-side controls, remove any lingering drag handle decorations // (they may carry over from edit mode). Only remove drag handles specifically, not // the remix button decorations (those are managed separately via showInViewMode). if (isViewMode && rightSideControlsEnabled) { const allHandleDecs = findHandleDec(decorations, 0, newState.doc.content.size); if (allHandleDecs.length > 0) { decorations = decorations.remove(allHandleDecs); } } if (shouldRemoveHandle) { var _activeNode5, _activeNode6, _activeNode7; const oldHandle = findHandleDec(decorations, (_activeNode5 = activeNode) === null || _activeNode5 === void 0 ? void 0 : _activeNode5.pos, (_activeNode6 = activeNode) === null || _activeNode6 === void 0 ? void 0 : _activeNode6.pos); decorations = decorations.remove(oldHandle); // When removing the handle, also remove the anchor-marker node decorations // (data-active-drag-handle / data-active-quick-insert) so the DOM attributes // don't linger on nodes that are no longer active. if (expValEquals('platform_editor_controls_reliable_anchor', 'isEnabled', true) && ((_activeNode7 = activeNode) === null || _activeNode7 === void 0 ? void 0 : _activeNode7.pos) !== undefined) { const oldActiveNodeDec = findActiveDragHandleNodeDec(decorations, activeNode.pos, activeNode.pos); decorations = decorations.remove(oldActiveNodeDec); if (activeNode.rootPos !== undefined) { const oldActiveQuickInsertDec = findActiveQuickInsertNodeDec(decorations, activeNode.rootPos, activeNode.rootPos); decorations = decorations.remove(oldActiveQuickInsertDec); } } // platform_editor_controls note: enables quick insert if (flags.toolbarFlagsEnabled && quickInsertButtonEnabled) { var _activeNode8, _activeNode9; const oldQuickInsertButton = findQuickInsertInsertButtonDecoration(decorations, (_activeNode8 = activeNode) === null || _activeNode8 === void 0 ? void 0 : _activeNode8.rootPos, (_activeNode9 = activeNode) === null || _activeNode9 === void 0 ? void 0 : _activeNode9.rootPos); decorations = decorations.remove(oldQuickInsertButton); for (const factory of nodeDecorationRegistry) { var _activeNode0, _activeNode1; const old = decorations.find((_activeNode0 = activeNode) === null || _activeNode0 === void 0 ? void 0 : _activeNode0.rootPos, (_activeNode1 = activeNode) === null || _activeNode1 === void 0 ? void 0 : _activeNode1.rootPos, spec => spec.type === factory.type); decorations = decorations.remove(old); } if (rightSideControlsEnabled && isViewMode && fg('confluence_remix_button_right_side_block_fg')) { for (const factory of nodeDecorationRegistry) { if (factory.showInViewMode) { var _activeNode10, _activeNode11; const old = decorations.find((_activeNode10 = activeNode) === null || _activeNode10 === void 0 ? void 0 : _activeNode10.rootPos, (_activeNode11 = activeNode) === null || _activeNode11 === void 0 ? void 0 : _activeNode11.rootPos, spec => spec.type === factory.type); decorations = decorations.remove(old); } } } } } else if (api) { var _latestActiveNode5, _latestActiveNode10; if (shouldRecreateHandle && (!rightSideControlsEnabled || !isViewMode)) { var _activeNode12, _activeNode13, _latestActiveNode, _latestActiveNode2, _latestActiveNode3, _latestActiveNode4; const oldHandle = findHandleDec(decorations, (_activeNode12 = activeNode) === null || _activeNode12 === void 0 ? void 0 : _activeNode12.pos, (_activeNode13 = activeNode) === null || _activeNode13 === void 0 ? void 0 : _activeNode13.pos); decorations = decorations.remove(oldHandle); const handleDec = dragHandleDecoration({ api, formatMessage, pos: (_latestActiveNode = latestActiveNode) === null || _latestActiveNode === void 0 ? void 0 : _latestActiveNode.pos, anchorName: (_latestActiveNode2 = latestActiveNode) === null || _latestActiveNode2 === void 0 ? void 0 : _latestActiveNode2.anchorName, nodeType: (_latestActiveNode3 = latestActiveNode) === null || _latestActiveNode3 === void 0 ? void 0 : _latestActiveNode3.nodeType, handleOptions: (_latestActiveNode4 = latestActiveNode) === null || _latestActiveNode4 === void 0 ? void 0 : _latestActiveNode4.handleOptions, nodeViewPortalProviderAPI, anchorRectCache, editorState: newState }); decorations = decorations.add(newState.doc, [handleDec]); if (expValEquals('platform_editor_controls_reliable_anchor', 'isEnabled', true)) { // Recreate the drag handle node decoration when the edit-mode node itself changed // or its content was modified. Other triggers (editorSizeChanged, handleNeedsRedraw) // don't move the decoration — DecorationSet.map() already remaps it correctly. const needsNodeDecUpdate = activeNodeChanged || isActiveNodeModified; if (needsNodeDecUpdate) { var _newState$doc$nodeAt; const nodeSize = (_newState$doc$nodeAt = newState.doc.nodeAt(latestActiveNode.pos)) === null || _newState$doc$nodeAt === void 0 ? void 0 : _newState$doc$nodeAt.nodeSize; if (nodeSize !== undefined) { var _activeNode14, _activeNode15; const oldActiveNodeDec = findActiveDragHandleNodeDec(decorations, (_activeNode14 = activeNode) === null || _activeNode14 === void 0 ? void 0 : _activeNode14.pos, (_activeNode15 = activeNode) === null || _activeNode15 === void 0 ? void 0 : _activeNode15.pos); decorations = decorations.remove(oldActiveNodeDec); decorations = decorations.add(newState.doc, [createActiveDragHandleNodeDecoration(latestActiveNode.pos, nodeSize)]); } } // The quick-insert decoration lives on the root node (rootPos), which can change // independently of the edit-mode node — e.g. when only editorSizeChanged fires but // rootActiveNodeChanged is also true. So we use a separate, broader guard that // includes rootActiveNodeChanged to avoid leaving the attribute on a stale root node. const needsQuickInsertDecUpdate = activeNodeChanged || isActiveNodeModified || rootActiveNodeChanged; if (needsQuickInsertDecUpdate && latestActiveNode.rootPos !== undefined) { var _newState$doc$nodeAt2; const rootNodeSize = (_newState$doc$nodeAt2 = newState.doc.nodeAt(latestActiveNode.rootPos)) === null || _newState$doc$nodeAt2 === void 0 ? void 0 : _newState$doc$nodeAt2.nodeSize; if (rootNodeSize !== undefined) { var _activeNode16, _activeNode17; const oldActiveQuickInsertDec = findActiveQuickInsertNodeDec(decorations, (_activeNode16 = activeNode) === null || _activeNode16 === void 0 ? void 0 : _activeNode16.rootPos, (_activeNode17 = activeNode) === null || _activeNode17 === void 0 ? void 0 : _activeNode17.rootPos); decorations = decorations.remove(oldActiveQuickInsertDec); decorations = decorations.add(newState.doc, [createActiveQuickInsertNodeDecoration(latestActiveNode.rootPos, rootNodeSize)]); } } } } if (shouldRecreateQuickInsertButton && ((_latestActiveNode5 = latestActiveNode) === null || _latestActiveNode5 === void 0 ? void 0 : _latestActiveNode5.rootPos) !== undefined && // platform_editor_controls note: enables quick insert flags.toolbarFlagsEnabled && quickInsertButtonEnabled && (!rightSideControlsEnabled || !isViewMode)) { var _activeNode18, _activeNode19, _latestActiveNode6, _latestActiveNode7, _latestActiveNode8, _latestActiveNode9, _latestActiveNode0, _latestActiveNode1; const oldQuickInsertButton = findQuickInsertInsertButtonDecoration(decorations, (_activeNode18 = activeNode) === null || _activeNode18 === void 0 ? void 0 : _activeNode18.rootPos, (_activeNode19 = activeNode) === null || _activeNode19 === void 0 ? void 0 : _activeNode19.rootPos); decorations = decorations.remove(oldQuickInsertButton); const quickInsertButton = quickInsertButtonDecoration({ api, formatMessage, anchorName: (_latestActiveNode6 = latestActiveNode) === null || _latestActiveNode6 === void 0 ? void 0 : _latestActiveNode6.anchorName, nodeType: (_latestActiveNode7 = latestActiveNode) === null || _latestActiveNode7 === void 0 ? void 0 : _latestActiveNode7.nodeType, nodeViewPortalProviderAPI, rootPos: (_latestActiveNode8 = latestActiveNode) === null || _latestActiveNode8 === void 0 ? void 0 : _latestActiveNode8.rootPos, rootAnchorName: (_latestActiveNode9 = latestActiveNode) === null || _latestActiveNode9 === void 0 ? void 0 : _latestActiveNode9.rootAnchorName, rootNodeType: (_latestActiveNode0 = latestActiveNode) === null || _latestActiveNode0 === void 0 ? void 0 : _latestActiveNode0.rootNodeType, anchorRectCache, editorState: newState }); decorations = decorations.add(newState.doc, [quickInsertButton]); // Update quick insert node decoration when the quick insert button is recreated but // the drag handle was NOT recreated (shouldRecreateHandle was false). When // shouldRecreateHandle is true, the block above already handles this. if (expValEquals('platform_editor_controls_reliable_anchor', 'isEnabled', true) && !shouldRecreateHandle && ((_latestActiveNode1 = latestActiveNode) === null || _latestActiveNode1 === void 0 ? void 0 : _latestActiveNode1.rootPos) !== undefined) { var _activeNode20, _newState$doc$nodeAt3; if (((_activeNode20 = activeNode) === null || _activeNode20 === void 0 ? void 0 : _activeNode20.rootPos) !== undefined) { const oldActiveQuickInsertDec = findActiveQuickInsertNodeDec(decorations, activeNode.rootPos, activeNode.rootPos); decorations = decorations.remove(oldActiveQuickInsertDec); } const rootNodeSize = (_newState$doc$nodeAt3 = newState.doc.nodeAt(latestActiveNode.rootPos)) === null || _newState$doc$nodeAt3 === void 0 ? void 0 : _newState$doc$nodeAt3.nodeSize; if (rootNodeSize !== undefined) { decorations = decorations.add(newState.doc, [createActiveQuickInsertNodeDecoration(latestActiveNode.rootPos, rootNodeSize)]); } } if (rightSideControlsEnabled) { for (const factory of nodeDecorationRegistry) { var _activeNode21, _activeNode22; if (!latestActiveNode || latestActiveNode.rootPos === undefined) { continue; } const params = { editorState: newState, nodeViewPortalProviderAPI, anchorName: latestActiveNode.anchorName, nodeType: latestActiveNode.nodeType, rootPos: latestActiveNode.rootPos, rootAnchorName: latestActiveNode.rootAnchorName, rootNodeType: latestActiveNode.rootNodeType }; const old = decorations.find((_activeNode21 = activeNode) === null || _activeNode21 === void 0 ? void 0 : _activeNode21.rootPos, (_activeNode22 = activeNode) === null || _activeNode22 === void 0 ? void 0 : _activeNode22.rootPos, spec => spec.type === factory.type); decorations = decorations.remove(old); // determines whether to show the decorations, see malleableUiPlugin.tsx if (factory.shouldCreate && !factory.shouldCreate(params)) { continue; } const dec = factory.create(params); decorations = decorations.add(newState.doc, [dec]); } } else { for (const factory of nodeDecorationRegistry) { const old = decorations.find(0, newState.doc.nodeSize, spec => spec.type === factory.type); decorations = decorations.remove(old); } } } // In view mode (edit/live pages), show right-side controls on block hover (without drag handle or quick insert) const rootPos = (_latestActiveNode10 = latestActiveNode) === null || _latestActiveNode10 === void 0 ? void 0 : _latestActiveNode10.rootPos; // rootPos is computed using the same logic as the floating insert menu, so it always points to a top-level (doc child) block when defined. const isDocLevel = rootPos !== undefined && !isNaN(rootPos); if (isViewMode && isDocLevel && flags.toolbarFlagsEnabled && rightSideControlsEnabled) { for (const factory of nodeDecorationRegistry) { if (factory.showInViewMode) { if (!latestActiveNode || latestActiveNode.rootPos === undefined) { continue; } const params = { editorState: newState, nodeViewPortalProviderAPI, anchorName: latestActiveNode.anchorName, nodeType: latestActiveNode.nodeType, rootPos: latestActiveNode.rootPos, rootAnchorName: latestActiveNode.rootAnchorName, rootNodeType: latestActiveNode.rootNodeType }; if (factory.shouldCreate && !factory.shouldCreate(params)) { continue; } const existingAtPos = decorations.find(rootPos, rootPos, spec => spec.type === factory.type); // Skip remove/re-add when decoration already exists at correct position - avoids // flickering from widget destroy/recreate on every transaction (e.g. on hover). if (existingAtPos.length > 0) { continue; } // Remove any stale decoration at a different position (e.g. after moving to another block) const stale = decorations.find(0, newState.doc.nodeSize, spec => spec.type === factory.type); decorations = decorations.remove(stale); const dec = factory.create(params); decorations = decorations.add(newState.doc, [dec]); } } } else if (isViewMode && rightSideControlsEnabled && fg('confluence_remix_button_right_side_block_fg')) { // Remove view-mode right-side decorations when no active node for (const factory of nodeDecorationRegistry) { if (factory.showInViewMode) { const old = decorations.find(0, newState.doc.nodeSize, spec => spec.type === factory.type); decorations = decorations.remove(old); } } } } // Drop targets may be missing when the node count is being changed during a drag const isDropTargetsMissing = ((_meta$isDragging2 = meta === null || meta === void 0 ? void 0 : meta.isDragging) !== null && _meta$isDragging2 !== void 0 ? _meta$isDragging2 : isDragging) && maybeNodeCountChanged && !(meta !== null && meta !== void 0 && meta.nodeMoved); // Remove drop target decorations when dragging stops or they need to be redrawn if ((meta === null || meta === void 0 ? void 0 : meta.isDragging) === false || isDropTargetsMissing) { const dropTargetDecs = findDropTargetDecs(decorations); decorations = decorations.remove(dropTargetDecs); } let currentActiveDropTargetNode = isDragging ? currentState.activeDropTargetNode : undefined; if (api) { if (expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) { // If page is updated while dragging (likely by remote updates), we simply remove the drop targets // and add them back when the user interacts with the editor again if (isDropTargetsMissing) { const oldDropTargetDecs = findDropTargetDecs(decorations); decorations = decorations.remove(oldDropTargetDecs); } if (meta !== null && meta !== void 0 && meta.activeDropTargetNode) { currentActiveDropTargetNode = meta === null || meta === void 0 ? void 0 : meta.activeDropTargetNode; const oldDropTargetDecs = findDropTargetDecs(decorations); const { decsToAdd, decsToRemove } = getActiveDropTargetDecorations(meta.activeDropTargetNode, newState, api, oldDropTargetDecs, formatMessage, nodeViewPortalProviderAPI, latestActiveNode, anchorRectCache); decorations = decorations.remove(decsToRemove); if (decsToAdd.length > 0) { decorations = decorations.add(newState.doc, decsToAdd); } } } else if (meta !== null && meta !== void 0 && meta.isDragging || isDropTargetsMissing) { // Add drop targets when dragging starts or some are missing const decs = dropTargetDecorations(newState, api, formatMessage, nodeViewPortalProviderAPI, latestActiveNode, anchorRectCache); decorations = decorations.add(newState.doc, decs); } } const isEmptyDoc = isEmptyDocument(newState.doc); if (isEmptyDoc && !expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true)) { const hasNodeDecoration = !!findNodeDecs(newState, decorations).length; if (!hasNodeDecoration) { decorations = decorations.add(newState.doc, [emptyParagraphNodeDecorations()]); } } let newActiveNode; // platform_editor_controls note: enables quick insert if (flags.toolbarFlagsEnabled) { var _latestActiveNode11, _latestActiveNode12; // remove isEmptyDoc check and let decorations render and determine their own visibility // In view mode with right-side controls we render node decorations (right-edge button), not the // handle - so findHandleDec is always empty. Don't clear activeNode in that case. const hasHandleOrViewModeControls = findHandleDec(decorations, (_latestActiveNode11 = latestActiveNode) === null || _latestActiveNode11 === void 0 ? void 0 : _latestActiveNode11.pos, (_latestActiveNode12 = latestActiveNode) === null || _latestActiveNode12 === void 0 ? void 0 : _latestActiveNode12.pos).length > 0 || isViewMode && rightSideControlsEnabled; newActiveNode = meta !== null && meta !== void 0 && meta.editorBlurred || !(meta !== null && meta !== void 0 && meta.activeNode) && !hasHandleOrViewModeControls ? null : latestActiveNode; } else { var _latestActiveNode13, _latestActiveNode14; newActiveNode = isEmptyDoc || !(meta !== null && meta !== void 0 && meta.activeNode) && findHandleDec(decorations, (_latestActiveNode13 = latestActiveNode) === null || _latestActiveNode13 === void 0 ? void 0 : _latestActiveNode13.pos, (_latestActiveNode14 = latestActiveNode) === null || _latestActiveNode14 === void 0 ? void 0 : _latestActiveNode14.pos).length === 0 ? null : latestActiveNode; } let isMenuOpenNew = isMenuOpen; if (editorExperiment('platform_editor_block_menu', true)) { if (meta !== null && meta !== void 0 && meta.closeMenu) { isMenuOpenNew = false; } else if (meta !== null && meta !== void 0 && meta.toggleMenu) { const isSameAnchor = (meta === null || meta === void 0 ? void 0 : meta.toggleMenu.anchorName) === menuTriggerBy; isMenuOpenNew = menuTriggerBy === undefined || isSameAnchor || !isMenuOpen && !isSameAnchor ? !isMenuOpen : isMenuOpen; } } else if (meta !== null && meta !== void 0 && meta.toggleMenu) { isMenuOpenNew = !isMenuOpen; } let isSelectedViaDragHandleNew; if (flags.toolbarFlagsEnabled) { isSelectedViaDragHandleNew = (meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle) !== undefined ? meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle : isSelectedViaDragHandle; } else { isSelectedViaDragHandleNew = (meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle) !== undefined && flags.toolbarFlagsEnabled && (meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle); } return { decorations, activeNode: newActiveNode, activeDropTargetNode: currentActiveDropTargetNode, isDragging: (_meta$isDragging3 = meta === null || meta === void 0 ? void 0 : meta.isDragging) !== null && _meta$isDragging3 !== void 0 ? _meta$isDragging3 : isDragging, isMenuOpen: isMenuOpenNew, menuTriggerBy: flags.toolbarFlagsEnabled || editorExperiment('platform_editor_block_menu', true) ? (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu = meta.toggleMenu) === null || _meta$toggleMenu === void 0 ? void 0 : _meta$toggleMenu.anchorName) || menuTriggerBy : undefined, menuTriggerByNode: editorExperiment('platform_synced_block', true) ? (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu2 = meta.toggleMenu) === null || _meta$toggleMenu2 === void 0 ? void 0 : _meta$toggleMenu2.triggerByNode) || menuTriggerByNode : undefined, blockMenuOptions: editorExperiment('platform_editor_block_menu', true) ? { canMoveUp: (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu3 = meta.toggleMenu) === null || _meta$toggleMenu3 === void 0 ? void 0 : _meta$toggleMenu3.moveUp) !== undefined ? meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu4 = meta.toggleMenu) === null || _meta$toggleMenu4 === void 0 ? void 0 : _meta$toggleMenu4.moveUp : blockMenuOptions === null || blockMenuOptions === void 0 ? void 0 : blockMenuOptions.canMoveUp, canMoveDown: (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu5 = meta.toggleMenu) === null || _meta$toggleMenu5 === void 0 ? void 0 : _meta$toggleMenu5.moveDown) !== undefined ? meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu6 = meta.toggleMenu) === null || _meta$toggleMenu6 === void 0 ? void 0 : _meta$toggleMenu6.moveDown : blockMenuOptions === null || blockMenuOptions === void 0 ? void 0 : blockMenuOptions.canMoveDown, openedViaKeyboard: (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu7 = meta.toggleMenu) === null || _meta$toggleMenu7 === void 0 ? void 0 : _meta$toggleMenu7.openedViaKeyboard) !== undefined ? meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu8 = meta.toggleMenu) === null || _meta$toggleMenu8 === void 0 ? void 0 : _meta$toggleMenu8.openedViaKeyboard : blockMenuOptions === null || blockMenuOptions === void 0 ? void 0 : blockMenuOptions.openedViaKeyboard } : undefined, editorHeight: (_meta$editorHeight = meta === null || meta === void 0 ? void 0 : meta.editorHeight) !== null && _meta$editorHeight !== void 0 ? _meta$editorHeight : editorHeight, editorWidthLeft: (_meta$editorWidthLeft = meta === null || meta === void 0 ? void 0 : meta.editorWidthLeft) !== null && _meta$editorWidthLeft !== void 0 ? _meta$editorWidthLeft : editorWidthLeft, editorWidthRight: (_meta$editorWidthRigh = meta === null || meta === void 0 ? void 0 : meta.editorWidthRight) !== null && _meta$editorWidthRigh !== void 0 ? _meta$editorWidthRigh : editorWidthRight, isResizerResizing: isResizerResizing, isDocSizeLimitEnabled: initialState.isDocSizeLimitEnabled, isPMDragging: (_meta$isPMDragging = meta === null || meta === void 0 ? void 0 : meta.isPMDragging) !== null && _meta$isPMDragging !== void 0 ? _meta$isPMDragging : isPMDragging, multiSelectDnD, isShiftDown: (_meta$isShiftDown = meta === null || meta === void 0 ? void 0 : meta.isShiftDown) !== null && _meta$isShiftDown !== void 0 ? _meta$isShiftDown : isShiftDown, lastDragCancelled: (_meta$lastDragCancell = meta === null || meta === void 0 ? void 0 : meta.lastDragCancelled) !== null && _meta$lastDragCancell !== void 0 ? _meta$lastDragCancell : lastDragCancelled, isSelectedViaDragHandle: isSelectedViaDragHandleNew }; }; export const createPlugin = (api, getIntl, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled = false, quickInsertButtonEnabled = true) => { const { formatMessage } = getIntl(); const isAdvancedLayoutEnabled = editorExperiment('advanced_layouts', true, { exposure: true }); const toolbarFlagsEnabled = areToolbarFlagsEnabled(Boolean(api === null || api === void 0 ? void 0 : api.toolbar)); const flags = { toolbarFlagsEnabled }; let anchorRectCache; if (!isAnchorSupported()) { anchorRectCache = new AnchorRectCache(); } let resizeObserverWidth; let pragmaticCleanup = null; return new SafePlugin({ key, state: { init() { return initialState; }, apply: (tr, currentState, _, newState) => apply(api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled, quickInsertButtonEnabled, anchorRectCache, resizeObserverWidth, pragmaticCleanup) }, props: { decorations: state => { var _api$limitedMode2, _api$limitedMode2$sha, _api$editorDisabled, _api$editorDisabled$s, _key$getState2, _api$editorViewMode3, _api$editorViewMode3$; if (api !== null && api !== void 0 && (_api$limitedMode2 = api.limitedMode) !== null && _api$limitedMode2 !== void 0 && (_api$limitedMode2$sha = _api$limitedMode2.sharedState.currentState()) !== null && _api$limitedMode2$sha !== void 0 && _api$limitedMode2$sha.enabled) { return; } const isDisabled = api === null || api === void 0 ? void 0 : (_api$editorDisabled = api.editorDisabled) === null || _api$editorDisabled === void 0 ? void 0 : (_api$editorDisabled$s = _api$editorDisabled.sharedState.currentState()) === null || _api$editorDisabled$s === void 0 ? void 0 : _api$editorDisabled$s.editorDisabled; if (isDisabled) { var _api$editorViewMode2, _api$editorViewMode2$; const remixRightSideEnabled = rightSideControlsEnabled && fg('confluence_remix_button_right_side_block_fg'); // Hide decorations when disabled, except in view mode when right-side controls are enabled if (!remixRightSideEnabled || (api === null || api === void 0 ? void 0 : (_api$editorViewMode2 = api.editorViewMode) === null || _api$editorViewMode2 === void 0 ? void 0 : (_api$editorViewMode2$ = _api$editorViewMode2.sharedState.currentState()) === null || _api$editorViewMode2$ === void 0 ? void 0 : _api$editorViewMode2$.mode) !== 'view') { return; } } let decorationSet = (_key$getState2 = key.getState(state)) === null || _key$getState2 === void 0 ? void 0 : _key$getState2.decorations;