UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

804 lines (781 loc) 63.4 kB
import rafSchedule from 'raf-schd'; 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 { dragHandleDecoration, emptyParagraphNodeDecorations, findHandleDec } from './decorations-drag-handle'; import { dropTargetDecorations, findDropTargetDecs } from './decorations-drop-target'; import { getActiveDropTargetDecorations } from './decorations-drop-target-active'; import { 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) => { const scrollable = document.querySelector('.fabric-editor-popup-scroll-parent'); 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$userIntent; const isMultiSelect = editorExperiment('platform_editor_element_drag_and_drop_multiselect', true); if (isMultiSelect) { var _api$blockControls, _api$selection; 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; let nodeTypes, hasSelectedMultipleNodes; if (isMultiSelect) { const position = getSelectedSlicePosition(start, tr, api); const attributes = getMultiSelectAnalyticsAttributes(tr, position.from, position.to); nodeTypes = attributes.nodeTypes; hasSelectedMultipleNodes = attributes.hasSelectedMultipleNodes; } const resolvedMovingNode = tr.doc.resolve(start); const maybeNode = resolvedMovingNode.nodeAfter; (_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, nodeType: (maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.type.name) || '', ...(isMultiSelect && { 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, editorExperiment('platform_editor_block_control_optimise_render', true) ? pos : 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) { /** * 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 = document.querySelector('.fabric-editor-popup-scroll-parent'); 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 && flags.isMultiSelectEnabled) { 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 && flags.isMultiSelectEnabled) { 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, editorExperiment('platform_editor_block_control_optimise_render', true) ? latestActiveNode.pos : 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); const rootNodeDecAtActivePos = 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); } if (shouldRemoveHandle) { var _activeNode5, _activeNode6; 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); // platform_editor_controls note: enables quick insert if (flags.toolbarFlagsEnabled && quickInsertButtonEnabled) { var _activeNode7, _activeNode8; const oldQuickInsertButton = findQuickInsertInsertButtonDecoration(decorations, (_activeNode7 = activeNode) === null || _activeNode7 === void 0 ? void 0 : _activeNode7.rootPos, (_activeNode8 = activeNode) === null || _activeNode8 === void 0 ? void 0 : _activeNode8.rootPos); decorations = decorations.remove(oldQuickInsertButton); if (fg('platform_editor_expose_block_controls_deco_api')) { for (const factory of nodeDecorationRegistry) { var _activeNode9, _activeNode0; const old = decorations.find((_activeNode9 = activeNode) === null || _activeNode9 === void 0 ? void 0 : _activeNode9.rootPos, (_activeNode0 = activeNode) === null || _activeNode0 === void 0 ? void 0 : _activeNode0.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 _activeNode1, _activeNode10; const old = decorations.find((_activeNode1 = activeNode) === null || _activeNode1 === void 0 ? void 0 : _activeNode1.rootPos, (_activeNode10 = activeNode) === null || _activeNode10 === void 0 ? void 0 : _activeNode10.rootPos, spec => spec.type === factory.type); decorations = decorations.remove(old); } } } } } else if (api) { var _latestActiveNode5, _latestActiveNode1; if (shouldRecreateHandle && (!rightSideControlsEnabled || !isViewMode)) { var _activeNode11, _activeNode12, _latestActiveNode, _latestActiveNode2, _latestActiveNode3, _latestActiveNode4; const oldHandle = findHandleDec(decorations, (_activeNode11 = activeNode) === null || _activeNode11 === void 0 ? void 0 : _activeNode11.pos, (_activeNode12 = activeNode) === null || _activeNode12 === void 0 ? void 0 : _activeNode12.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 (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 _activeNode13, _activeNode14, _latestActiveNode6, _latestActiveNode7, _latestActiveNode8, _latestActiveNode9, _latestActiveNode0; const oldQuickInsertButton = findQuickInsertInsertButtonDecoration(decorations, (_activeNode13 = activeNode) === null || _activeNode13 === void 0 ? void 0 : _activeNode13.rootPos, (_activeNode14 = activeNode) === null || _activeNode14 === void 0 ? void 0 : _activeNode14.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]); // both gates have overlapping logic to determine what controls to show if (fg('platform_editor_expose_block_controls_deco_api')) { if (rightSideControlsEnabled) { for (const factory of nodeDecorationRegistry) { var _activeNode15, _activeNode16; 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((_activeNode15 = activeNode) === null || _activeNode15 === void 0 ? void 0 : _activeNode15.rootPos, (_activeNode16 = activeNode) === null || _activeNode16 === void 0 ? void 0 : _activeNode16.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 = (_latestActiveNode1 = latestActiveNode) === null || _latestActiveNode1 === void 0 ? void 0 : _latestActiveNode1.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 _latestActiveNode10, _latestActiveNode11; // 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, (_latestActiveNode10 = latestActiveNode) === null || _latestActiveNode10 === void 0 ? void 0 : _latestActiveNode10.pos, (_latestActiveNode11 = latestActiveNode) === null || _latestActiveNode11 === void 0 ? void 0 : _latestActiveNode11.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 _latestActiveNode12, _latestActiveNode13; newActiveNode = isEmptyDoc || !(meta !== null && meta !== void 0 && meta.activeNode) && findHandleDec(decorations, (_latestActiveNode12 = latestActiveNode) === null || _latestActiveNode12 === void 0 ? void 0 : _latestActiveNode12.pos, (_latestActiveNode13 = latestActiveNode) === null || _latestActiveNode13 === void 0 ? void 0 : _latestActiveNode13.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 isMultiSelectEnabled = editorExperiment('platform_editor_element_drag_and_drop_multiselect', true, { exposure: true }); const toolbarFlagsEnabled = areToolbarFlagsEnabled(Boolean(api === null || api === void 0 ? void 0 : api.toolbar)); const flags = { isMultiSelectEnabled, 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; 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; } } return (_key$getState2 = key.getState(state)) === null || _key$getState2 === void 0 ? void 0 : _key$getState2.decorations; }, handleDOMEvents: { drop(view, event) { var _pluginState, _pluginState2, _pluginState3, _event$target, _event$target$closest; // Prevent native DnD from triggering if we are in drag const { dispatch, dragging, state } = view; const tr = state.tr; let pluginState = key.getState(state); const dndDragCancelled = (_pluginState = pluginState) === null || _pluginState === void 0 ? void 0 : _pluginState.lastDragCancelled; if ((_pluginState2 = pluginState) !== null && _pluginState2 !== void 0 && _pluginState2.isPMDragging || dndDragCancelled && isMultiSelectEnabled) { if (fg('platform_editor_ease_of_use_metrics')) { var _api$metrics2; api === null || api === void 0 ? void 0 : (_api$metrics2 = api.metrics) === null || _api$metrics2 === void 0 ? void 0 : _api$metrics2.commands.startActiveSessionTimer()({ tr }); } dispatch(tr.setMeta(key, { ...tr.getMeta(key), isPMDragging: false, lastDragCancelled: false })); } pluginState = key.getState(view.state); if (!(event.target instanceof HTMLElement) || !((_pluginState3 = pluginState) !== null && _pluginState3 !== void 0 && _pluginState3.activeNode)) { return false; } // Currently we can only drag one node at a time // so we only need to check first child const draggable = dragging === null || dragging === void 0 ? void 0 : dragging.slice.content.firstChild; if (dndDragCancelled && isMultiSelectEnabled || (draggable === null || draggable === void 0 ? void 0 : draggable.type.name) === 'layoutColumn') { // we prevent native DnD for layoutColumn to prevent single column layout. event.preventDefault(); return false; } const nodeElement = (_event$target = event.target) === null || _event$target === void 0 ? void 0 : (_event$target$closest = _event$target.closest) === null || _event$target$closest === void 0 ? void 0 : _event$target$closest.call(_event$target, `[${getAnchorAttrName()}]`); if (!nodeElement) { return false; } // TODO: ED-26959 - Review usage of posAtDOM here const domPos = Math.max(view.posAtDOM(nodeElement, 0) - 1, 0); const nodeTarget = state.doc.nodeAt(domPos); const isSameNode = !!(nodeTarget && draggable !== null && draggable !== void 0 && draggable.eq(nodeTarget)); if (isSameNode) { event.preventDefault(); return true; } return false; }, dragenter(view, event) { var _api$limitedMode3, _api$limitedMode3$sha, _key$getState3; if (api !== null && api !== void 0 && (_api$limitedMode3 = api.limitedMode) !== null && _api$limitedMode3 !== void 0 && (_api$limitedMode3$sha = _api$limitedMode3.sharedState.currentState()) !== null && _api$limitedMode3$sha !== void 0 && _api$limitedMode3$sha.enabled) { return; } // Only process dragenter for block control drags. // Other drag types (e.g. table row) should not create // drop target decorations or emit active anchors. if (!((_key$getState3 = key.getState(view.state)) !== null && _key$getState3 !== void 0 && _key$getState3.isDragging) && expValEquals('platform_editor_fix_table_row_drag_drop_target', 'isEnabled', true)) { return; } if (isHTMLElement(event.target) && expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) { const targetElement = event.target.closest('[data-prosemirror-node-name]'); if (targetElement) { var _api$blockControls$sh; const nodeTypeName = targetElement === null || targetElement === void 0 ? void 0 : targetElement.getAttribute('data-prosemirror-node-name'); const pos = view.posAtDOM(targetElement, -1); const currentActiveDropTargetNode = api === null || api === void 0 ? void 0 : (_api$blockControls$sh = api.blockControls.sharedState.currentState()) === null || _api$blockControls$sh === void 0 ? void 0 : _api$blockControls$sh.activeDropTargetNode; if ((currentActiveDropTargetNode === null || currentActiveDropTargetNode === void 0 ? void 0 : currentActiveDropTargetNode.pos) !== pos || (currentActiveDropTargetNode === null || currentActiveDropTargetNode === void 0 ? void 0 : currentActiveDropTargetNode.nodeTypeName) !== nodeTypeName) { const activeDropTargetNode = { pos, nodeTypeName }; view.dispatch(view.state.tr.setMeta(key, { activeDropTargetNode })); } } } else if (isAdvancedLayoutEnabled) { if (isHTMLElement(event.target)) { const closestParentElement = event.target.closest('[data-drag-handler-anchor-depth="0"]'); if (closestParentElem