UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

803 lines (782 loc) 69.9 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } 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 var key = new PluginKey('blockControls'); var EDITOR_BLOCKS_DRAG_INIT = 'Editor Blocks Drag Initialization Time'; var EDITOR_BLOCKS_DROP_INIT = 'Editor Blocks Drop Initialization Time'; var scheduleCallback = function scheduleCallback(cb, options) { return 'requestIdleCallback' in window ? requestIdleCallback(cb, _objectSpread({ timeout: 5000 }, options)) : requestAnimationFrame(cb); }; var isHTMLElement = function isHTMLElement(element) { return element instanceof HTMLElement; }; var destroyFn = function destroyFn(api, editorView) { var scrollable = document.querySelector('.fabric-editor-popup-scroll-parent'); var cleanupFn = []; if (scrollable) { cleanupFn.push(autoScrollForElements({ element: scrollable })); } var dragInitializationDuration = 0; cleanupFn.push(monitorForElements({ canMonitor: function canMonitor(_ref) { var source = _ref.source; return source.data.type === 'element'; }, onDrag: function onDrag() { if (fg('platform_editor_drag_and_drop_perf_analytics')) { if (isMeasuring(EDITOR_BLOCKS_DRAG_INIT)) { stopMeasure(EDITOR_BLOCKS_DRAG_INIT, function (duration) { dragInitializationDuration = duration; }); } } else { if (isMeasuring(EDITOR_BLOCKS_DRAG_INIT)) { stopMeasure(EDITOR_BLOCKS_DRAG_INIT, function (duration, startTime) { var _api$analytics; api === null || api === void 0 || (_api$analytics = api.analytics) === null || _api$analytics === void 0 || _api$analytics.actions.fireAnalyticsEvent({ action: ACTION.BLOCKS_DRAG_INIT, actionSubject: ACTION_SUBJECT.EDITOR, eventType: EVENT_TYPE.OPERATIONAL, attributes: { duration: duration, startTime: startTime, nodesCount: editorView === null || editorView === void 0 ? void 0 : editorView.state.doc.nodeSize } }); }); } } }, onDragStart: function onDragStart() { if (isHTMLElement(scrollable)) { scrollable.style.setProperty('scroll-behavior', 'unset'); } }, onDrop: function onDrop(_ref2) { var _api$core; var location = _ref2.location, source = _ref2.source; 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 || _api$core.actions.execute(function (_ref3) { var _api$userIntent; var tr = _ref3.tr; var isMultiSelect = editorExperiment('platform_editor_element_drag_and_drop_multiselect', true); if (isMultiSelect) { var _api$blockControls, _api$selection; var _ref4 = ((_api$blockControls = api.blockControls) === null || _api$blockControls === void 0 ? void 0 : _api$blockControls.sharedState.currentState()) || {}, multiSelectDnD = _ref4.multiSelectDnD; // 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 var expandedSelectionUnchanged = multiSelectDnD.textAnchor === tr.selection.anchor && multiSelectDnD.textHead === tr.selection.head; if (expandedSelectionUnchanged) { var $anchor = tr.doc.resolve(multiSelectDnD.userAnchor); var $head = tr.doc.resolve(multiSelectDnD.userHead); if ($head.node() === $anchor.node()) { var $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 || _api$selection.commands.clearManualSelection()({ tr: tr }); } var _ref5 = source.data, start = _ref5.start; // if no drop targets are rendered, assume that drop is invalid var lastDragCancelled = location.current.dropTargets.length === 0; if (lastDragCancelled) { var _api$analytics2; var nodeTypes, hasSelectedMultipleNodes; if (isMultiSelect) { var position = getSelectedSlicePosition(start, tr, api); var attributes = getMultiSelectAnalyticsAttributes(tr, position.from, position.to); nodeTypes = attributes.nodeTypes; hasSelectedMultipleNodes = attributes.hasSelectedMultipleNodes; } var resolvedMovingNode = tr.doc.resolve(start); var maybeNode = resolvedMovingNode.nodeAfter; (_api$analytics2 = api.analytics) === null || _api$analytics2 === 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: _objectSpread({ nodeDepth: resolvedMovingNode.depth, nodeType: (maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.type.name) || '' }, isMultiSelect && { nodeTypes: nodeTypes, hasSelectedMultipleNodes: hasSelectedMultipleNodes }) })(tr); } if (fg('platform_editor_ease_of_use_metrics')) { var _api$metrics; (_api$metrics = api.metrics) === null || _api$metrics === void 0 || _api$metrics.commands.startActiveSessionTimer()({ tr: tr }); } (_api$userIntent = api.userIntent) === null || _api$userIntent === void 0 || _api$userIntent.commands.setCurrentUserIntent('default')({ tr: tr }); return tr.setMeta(key, _objectSpread(_objectSpread({}, tr.getMeta(key)), {}, { isDragging: false, isPMDragging: false, lastDragCancelled: lastDragCancelled })); }); if (fg('platform_editor_drag_and_drop_perf_analytics')) { // wait for the idle callback to ensure that the drag operation has completed scheduleCallback(function () { if (isMeasuring(EDITOR_BLOCKS_DROP_INIT)) { stopMeasure(EDITOR_BLOCKS_DROP_INIT, function (duration) { var _api$analytics3; var isCancelled = location.current.dropTargets.length === 0; api === null || api === void 0 || (_api$analytics3 = api.analytics) === null || _api$analytics3 === 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: dragInitializationDuration, dropProcessingDuration: duration, isCancelled: isCancelled, nodesCount: editorView === null || editorView === void 0 ? void 0 : editorView.state.doc.nodeSize } }); }); } }); } } })); return combine.apply(void 0, cleanupFn); }; var 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 var getDecorations = function getDecorations(state) { var _key$getState; return (_key$getState = key.getState(state)) === null || _key$getState === void 0 ? void 0 : _key$getState.decorations; }; var getDecorationAtPos = function getDecorationAtPos(state, decorations, pos, to) { // Find the newly minted node decs that touch the active node var 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 var nodeDecsAtActivePos = findNewNodeDecs.filter(function (dec) { return (dec === null || dec === void 0 ? void 0 : dec.from) === pos; }); // If multiple decorations at the active node pos, we want the last one var nodeDecAtActivePos = nodeDecsAtActivePos.pop(); return nodeDecAtActivePos; }; var _apply = function apply(api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry) { var _api$limitedMode, _meta$multiSelectDnD, _api$editorViewMode, _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; var rightSideControlsEnabled = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : false; var quickInsertButtonEnabled = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : true; var anchorRectCache = arguments.length > 10 ? arguments[10] : undefined; var resizeObserverWidth = arguments.length > 11 ? arguments[11] : undefined; var pragmaticCleanup = arguments.length > 12 ? arguments[12] : undefined; var activeNode = currentState.activeNode, decorations = currentState.decorations, isResizerResizing = currentState.isResizerResizing, multiSelectDnD = currentState.multiSelectDnD; var editorHeight = currentState.editorHeight, editorWidthLeft = currentState.editorWidthLeft, editorWidthRight = currentState.editorWidthRight, isDragging = currentState.isDragging, isMenuOpen = currentState.isMenuOpen, menuTriggerBy = currentState.menuTriggerBy, menuTriggerByNode = currentState.menuTriggerByNode, blockMenuOptions = currentState.blockMenuOptions, isPMDragging = currentState.isPMDragging, isShiftDown = currentState.isShiftDown, lastDragCancelled = currentState.lastDragCancelled, isSelectedViaDragHandle = currentState.isSelectedViaDragHandle; var isActiveNodeDeleted = false; var _getTrMetadata = getTrMetadata(tr, flags), from = _getTrMetadata.from, to = _getTrMetadata.to, numReplaceSteps = _getTrMetadata.numReplaceSteps, isAllText = _getTrMetadata.isAllText, isReplacedWithSameSize = _getTrMetadata.isReplacedWithSameSize; var meta = tr.getMeta(key); var hasDocumentSizeBreachedThreshold = api === null || api === void 0 || (_api$limitedMode = api.limitedMode) === null || _api$limitedMode === void 0 || (_api$limitedMode = _api$limitedMode.sharedState.currentState()) === null || _api$limitedMode === void 0 || (_api$limitedMode = _api$limitedMode.limitedModePluginKey.getState(newState)) === null || _api$limitedMode === void 0 ? void 0 : _api$limitedMode.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(). */ var editorContentArea = document.querySelector('.fabric-editor-popup-scroll-parent'); if (editorContentArea && resizeObserverWidth) { resizeObserverWidth.unobserve(editorContentArea); } pragmaticCleanup === null || pragmaticCleanup === 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) { var 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; var _mappedPos; var 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 var 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); } } var resizerMeta = tr.getMeta('is-resizer-resizing'); isResizerResizing = resizerMeta !== null && resizerMeta !== void 0 ? resizerMeta : isResizerResizing; var 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. var 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; } } var maybeNodeCountChanged = !isAllText && numReplaceSteps > 0; var latestActiveNode = meta === null || meta === void 0 ? void 0 : meta.activeNode; var isViewMode = (api === null || api === void 0 || (_api$editorViewMode = api.editorViewMode) === null || _api$editorViewMode === void 0 || (_api$editorViewMode = _api$editorViewMode.sharedState.currentState()) === null || _api$editorViewMode === void 0 ? void 0 : _api$editorViewMode.mode) === 'view'; if (!latestActiveNode && (!isActiveNodeDeleted || isReplacedWithSameSize)) { latestActiveNode = activeNode; } // Re-create node decorations var isDecSetEmpty = decorations === DecorationSet.empty; var isNodeDecsMissing = isDecSetEmpty || maybeNodeCountChanged || editorExperiment('platform_editor_breakout_resizing', true) && hasJustFinishedResizing; var 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); var isActiveNodeModified = false; if (api && shouldRedrawNodeDecs) { var oldNodeDecs = findNodeDecs(newState, decorations, from, to); decorations = decorations.remove(oldNodeDecs); var 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 var 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 var nodeDecsAtActivePos = findNewNodeDecs.filter(function (dec) { return (dec === null || dec === void 0 ? void 0 : dec.from) === latestActiveNode.pos; }); // If multiple decorations at the active node pos, we want the last one var 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)) { var _nodeDecAtActivePos = getDecorationAtPos(newState, decorations, latestActiveNode.pos, to); var 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 var 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 var 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 || (_meta$activeNode$hand = meta.activeNode.handleOptions) === null || _meta$activeNode$hand === void 0 ? void 0 : _meta$activeNode$hand.isFocused)); var 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 var handleNeedsRedraw = shouldRedrawNodeDecs && !isAnchorSupported(); // Create/recreate handle dec when the active node is missing/changes, or the editor viewport has changed (non-anchor pos workaround) var shouldRecreateHandle = latestActiveNode && (activeNodeChanged || isActiveNodeModified || editorSizeChanged || handleNeedsRedraw); var shouldRecreateQuickInsertButton = latestActiveNode && (rootActiveNodeChanged || isActiveNodeModified || editorSizeChanged || handleNeedsRedraw); // If the active node is missing, we need to remove the handle var 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; var 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; var 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')) { var _iterator = _createForOfIteratorHelper(nodeDecorationRegistry), _step; try { var _loop = function _loop() { var _activeNode9, _activeNode0; var factory = _step.value; var old = decorations.find((_activeNode9 = activeNode) === null || _activeNode9 === void 0 ? void 0 : _activeNode9.rootPos, (_activeNode0 = activeNode) === null || _activeNode0 === void 0 ? void 0 : _activeNode0.rootPos, function (spec) { return spec.type === factory.type; }); decorations = decorations.remove(old); }; for (_iterator.s(); !(_step = _iterator.n()).done;) { _loop(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } if (rightSideControlsEnabled && isViewMode && fg('confluence_remix_button_right_side_block_fg')) { var _iterator2 = _createForOfIteratorHelper(nodeDecorationRegistry), _step2; try { var _loop2 = function _loop2() { var factory = _step2.value; if (factory.showInViewMode) { var _activeNode1, _activeNode10; var old = decorations.find((_activeNode1 = activeNode) === null || _activeNode1 === void 0 ? void 0 : _activeNode1.rootPos, (_activeNode10 = activeNode) === null || _activeNode10 === void 0 ? void 0 : _activeNode10.rootPos, function (spec) { return spec.type === factory.type; }); decorations = decorations.remove(old); } }; for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { _loop2(); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } } } else if (api) { var _latestActiveNode5, _latestActiveNode1; if (shouldRecreateHandle && (!rightSideControlsEnabled || !isViewMode)) { var _activeNode11, _activeNode12, _latestActiveNode, _latestActiveNode2, _latestActiveNode3, _latestActiveNode4; var _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); var handleDec = dragHandleDecoration({ api: api, formatMessage: 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: nodeViewPortalProviderAPI, anchorRectCache: 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; var _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); var quickInsertButton = quickInsertButtonDecoration({ api: api, formatMessage: formatMessage, anchorName: (_latestActiveNode6 = latestActiveNode) === null || _latestActiveNode6 === void 0 ? void 0 : _latestActiveNode6.anchorName, nodeType: (_latestActiveNode7 = latestActiveNode) === null || _latestActiveNode7 === void 0 ? void 0 : _latestActiveNode7.nodeType, nodeViewPortalProviderAPI: 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: 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) { var _iterator3 = _createForOfIteratorHelper(nodeDecorationRegistry), _step3; try { var _loop3 = function _loop3() { var _activeNode15, _activeNode16; var factory = _step3.value; if (!latestActiveNode || latestActiveNode.rootPos === undefined) { return 0; // continue } var params = { editorState: newState, nodeViewPortalProviderAPI: nodeViewPortalProviderAPI, anchorName: latestActiveNode.anchorName, nodeType: latestActiveNode.nodeType, rootPos: latestActiveNode.rootPos, rootAnchorName: latestActiveNode.rootAnchorName, rootNodeType: latestActiveNode.rootNodeType }; var old = decorations.find((_activeNode15 = activeNode) === null || _activeNode15 === void 0 ? void 0 : _activeNode15.rootPos, (_activeNode16 = activeNode) === null || _activeNode16 === void 0 ? void 0 : _activeNode16.rootPos, function (spec) { return spec.type === factory.type; }); decorations = decorations.remove(old); // determines whether to show the decorations, see malleableUiPlugin.tsx if (factory.shouldCreate && !factory.shouldCreate(params)) { return 0; // continue } var dec = factory.create(params); decorations = decorations.add(newState.doc, [dec]); }, _ret; for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { _ret = _loop3(); if (_ret === 0) continue; } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } else { var _iterator4 = _createForOfIteratorHelper(nodeDecorationRegistry), _step4; try { var _loop4 = function _loop4() { var factory = _step4.value; var old = decorations.find(0, newState.doc.nodeSize, function (spec) { return spec.type === factory.type; }); decorations = decorations.remove(old); }; for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { _loop4(); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } } } // In view mode (edit/live pages), show right-side controls on block hover (without drag handle or quick insert) var 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. var isDocLevel = rootPos !== undefined && !isNaN(rootPos); if (isViewMode && isDocLevel && flags.toolbarFlagsEnabled && rightSideControlsEnabled) { var _iterator5 = _createForOfIteratorHelper(nodeDecorationRegistry), _step5; try { var _loop5 = function _loop5() { var factory = _step5.value; if (factory.showInViewMode) { if (!latestActiveNode || latestActiveNode.rootPos === undefined) { return 0; // continue } var params = { editorState: newState, nodeViewPortalProviderAPI: nodeViewPortalProviderAPI, anchorName: latestActiveNode.anchorName, nodeType: latestActiveNode.nodeType, rootPos: latestActiveNode.rootPos, rootAnchorName: latestActiveNode.rootAnchorName, rootNodeType: latestActiveNode.rootNodeType }; if (factory.shouldCreate && !factory.shouldCreate(params)) { return 0; // continue } var existingAtPos = decorations.find(rootPos, rootPos, function (spec) { return 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) { return 0; // continue } // Remove any stale decoration at a different position (e.g. after moving to another block) var stale = decorations.find(0, newState.doc.nodeSize, function (spec) { return spec.type === factory.type; }); decorations = decorations.remove(stale); var dec = factory.create(params); decorations = decorations.add(newState.doc, [dec]); } }, _ret2; for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { _ret2 = _loop5(); if (_ret2 === 0) continue; } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } else if (isViewMode && rightSideControlsEnabled && fg('confluence_remix_button_right_side_block_fg')) { // Remove view-mode right-side decorations when no active node var _iterator6 = _createForOfIteratorHelper(nodeDecorationRegistry), _step6; try { var _loop6 = function _loop6() { var factory = _step6.value; if (factory.showInViewMode) { var old = decorations.find(0, newState.doc.nodeSize, function (spec) { return spec.type === factory.type; }); decorations = decorations.remove(old); } }; for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { _loop6(); } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } } } // Drop targets may be missing when the node count is being changed during a drag var 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) { var dropTargetDecs = findDropTargetDecs(decorations); decorations = decorations.remove(dropTargetDecs); } var 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) { var 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; var _oldDropTargetDecs = findDropTargetDecs(decorations); var _getActiveDropTargetD = getActiveDropTargetDecorations(meta.activeDropTargetNode, newState, api, _oldDropTargetDecs, formatMessage, nodeViewPortalProviderAPI, latestActiveNode, anchorRectCache), decsToAdd = _getActiveDropTargetD.decsToAdd, decsToRemove = _getActiveDropTargetD.decsToRemove; 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 var decs = dropTargetDecorations(newState, api, formatMessage, nodeViewPortalProviderAPI, latestActiveNode, anchorRectCache); decorations = decorations.add(newState.doc, decs); } } var isEmptyDoc = isEmptyDocument(newState.doc); if (isEmptyDoc && !expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true)) { var hasNodeDecoration = !!findNodeDecs(newState, decorations).length; if (!hasNodeDecoration) { decorations = decorations.add(newState.doc, [emptyParagraphNodeDecorations()]); } } var 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. var 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; } var 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) { var 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; } var 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: 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 || (_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 || (_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 || (_meta$toggleMenu3 = meta.toggleMenu) === null || _meta$toggleMenu3 === void 0 ? void 0 : _meta$toggleMenu3.moveUp) !== undefined ? meta === null || meta === 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 || (_meta$toggleMenu5 = meta.toggleMenu) === null || _meta$toggleMenu5 === void 0 ? void 0 : _meta$toggleMenu5.moveDown) !== undefined ? meta === null || meta === 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 || (_meta$toggleMenu7 = meta.toggleMenu) === null || _meta$toggleMenu7 === void 0 ? void 0 : _meta$toggleMenu7.openedViaKeyboard) !== undefined ? meta === null || meta === 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: 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 { _apply as apply }; export var createPlugin = function createPlugin(api, getIntl, nodeViewPortalProviderAPI, nodeDecorationRegistry) { var rightSideControlsEnabled = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var quickInsertButtonEnabled = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true; var _getIntl = getIntl(), formatMessage = _getIntl.formatMessage; var isAdvancedLayoutEnabled = editorExperiment('advanced_layouts', true, { exposure: true }); var isMultiSelectEnabled = editorExperiment('platform_editor_element_drag_and_drop_multiselect', true, { exposure: true }); var toolbarFlagsEnabled = areToolbarFlagsEnabled(Boolean(api === null || api === void 0 ? void 0 : api.toolbar)); var flags = { isMultiSelectEnabled: isMultiSelectEnabled, toolbarFlagsEnabled: toolbarFlagsEnabled }; var anchorRectCache; if (!isAnchorSupported()) { anchorRectCache = new AnchorRectCache(); } var resizeObserverWidth; var pragmaticCleanup = null; return new SafePlugin({ key: key, state: { init: function init() { return initialState; }, apply: function apply(tr, currentState, _, newState) { return _apply(api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled, quickInsertButtonEnabled, anchorRectCache, resizeObserverWidth, pragmaticCleanup); } }, props: { decorations: function decorations(state) { var _api$limitedMode2, _api$editorDisabled, _key$getState2; if (api !== null && api !== void 0 && (_api$limitedMode2 = api.limitedMode) !== null && _api$limitedMode2 !== void 0 && (_api$limi