UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

1,319 lines 85.1 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 { 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 { isExperimentEnabled } from '@atlaskit/platform-feature-experiments/is-experiment-enabled';
import { fg } from '@atlaskit/platform-feature-flags/fg';
import { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element';
import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter';
import { combine } from '@atlaskit/pragmatic-drag-and-drop/utils/combine';
import { editorExperiment } from '@atlaskit/tmp-editor-statsig/editor-experiment';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { expValEqualsNoExposure } from '@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure';
import { BLOCK_CONTROLS_SURFACE_SELECTOR } from '../ui/consts';
import { getAnchorAttrName } from '../ui/utils/dom-attr-name';
import { findNodeDecs, nodeDecorations } from './decorations-anchor';
import { getNodeTypeWithLevel } from './decorations-common';
import { createActiveDragHandleNodeDecoration, dragHandleDecoration, emptyParagraphNodeDecorations, findActiveDragHandleNodeDec, findHandleDec, TYPE_ACTIVE_HANDLE_DEC } from './decorations-drag-handle';
import { dropTargetDecorations, findDropTargetDecs } from './decorations-drop-target';
import { getActiveDropTargetDecorations } from './decorations-drop-target-active';
import { createActiveQuickInsertNodeDecoration, findActiveQuickInsertNodeDec, findQuickInsertInsertButtonDecoration, quickInsertButtonDecoration, TYPE_ACTIVE_QUICK_INSERT_NODE } from './decorations-quick-insert-button';
import { handleMouseDown } from './handle-mouse-down';
import { handleMouseOver } from './handle-mouse-over';
import { handleSparseMouseOver } from './handle-sparse-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 _getDocument$querySel, _getDocument;
  var 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;
  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$blockControls, _api$selection, _api$userIntent;
        var tr = _ref3.tr;
        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 position = getSelectedSlicePosition(start, tr, api);
          var attributes = getMultiSelectAnalyticsAttributes(tr, position.from, position.to);
          var nodeTypes = attributes.nodeTypes,
            hasSelectedMultipleNodes = attributes.hasSelectedMultipleNodes;
          var resolvedMovingNode = tr.doc.resolve(start);
          (_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: {
              nodeDepth: resolvedMovingNode.depth,
              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,
  surfaceNodePositions: [],
  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, 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 _meta$multiSelectDnD, _api$editorViewMode, _activeNode, _activeNode2, _meta$activeNode$hand, _activeNode3, _activeNode4, _meta$isDragging2, _meta$toggleMenu, _meta$isDragging3, _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 limitedModeTeardown = arguments.length > 13 ? arguments[13] : undefined;
  var activeNode = currentState.activeNode,
    decorations = currentState.decorations,
    isResizerResizing = currentState.isResizerResizing,
    multiSelectDnD = currentState.multiSelectDnD;
  var surfaceNodePositions = currentState.surfaceNodePositions;
  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);
  if (isExperimentEnabled('platform_editor_dynamic_limited_mode')) {
    var _api$limitedMode;
    // Both arms read `newState` — the state this transaction is producing. Deriving `enabled` from
    // `sharedState.currentState()` instead would resolve against `view.state`, which during `apply` is
    // still the *previous* state, delaying the limited-mode teardown by one transaction.
    //
    // Limited mode can now also be latched at runtime by the performance detector, so the treatment
    // arm considers both reasons rather than just the document one. Identical in the control arm, where
    // the runtime latch can never be set.
    var limitedModeState = 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 ? void 0 : _api$limitedMode.limitedModePluginKey.getState(newState);
    if (!!(limitedModeState !== null && limitedModeState !== void 0 && limitedModeState.enabled)) {
      /**
       * INFO: This is a duplicate of the logic in destroy(). When we enter limited mode we want to
       * trigger the cleanup logic in destroy().
       */
      if (!limitedModeTeardown || !limitedModeTeardown.done) {
        var _getDocument$querySel2, _getDocument2;
        /**
         * Edge-triggered under the experiment: limited mode is a latch, so without this guard the
         * teardown re-runs on every subsequent transaction for the rest of the session — and would
         * re-register the pragmatic monitors if `pragmaticCleanup` ever became re-entrant.
         */
        if (limitedModeTeardown) {
          limitedModeTeardown.done = true;
        }
        var 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 || pragmaticCleanup();
      }

      /**
       * Reset rather than freeze. Returning `currentState` here would keep `decorations`,
       * `activeNode` and the multi-select positions from before the latch, while skipping the
       * `tr.mapping` remapping below — so they would silently drift out of sync with the document on
       * every subsequent edit. Nothing renders them in limited mode (`props.decorations` returns
       * early), but stale positions are a latent source of incorrect offsets for anything that reads
       * them, so the safe state is empty.
       */
      return _objectSpread(_objectSpread({}, currentState), {}, {
        activeNode: undefined,
        decorations: DecorationSet.empty,
        multiSelectDnD: undefined
      });
    }
  } else {
    var _api$limitedMode2;
    var hasDocumentSizeBreachedThreshold = api === null || api === void 0 || (_api$limitedMode2 = api.limitedMode) === null || _api$limitedMode2 === void 0 || (_api$limitedMode2 = _api$limitedMode2.sharedState.currentState()) === null || _api$limitedMode2 === void 0 || (_api$limitedMode2 = _api$limitedMode2.limitedModePluginKey.getState(newState)) === null || _api$limitedMode2 === void 0 ? void 0 : _api$limitedMode2.documentSizeBreachesThreshold;
    if (hasDocumentSizeBreachedThreshold) {
      var _getDocument$querySel3, _getDocument3;
      /**
       * 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 = (_getDocument$querySel3 = (_getDocument3 = getDocument()) === null || _getDocument3 === void 0 ? void 0 : _getDocument3.querySelector('.fabric-editor-popup-scroll-parent')) !== null && _getDocument$querySel3 !== void 0 ? _getDocument$querySel3 : null;
      if (_editorContentArea && resizeObserverWidth) {
        resizeObserverWidth.unobserve(_editorContentArea);
      }
      pragmaticCleanup === null || pragmaticCleanup === void 0 || pragmaticCleanup();
      return currentState;
    }
  }

  // patch_1: DecorationSet.map() validates node decorations as it maps them — one whose range
  // no longer exactly covers a node (e.g. after a split) is dropped rather than left misplaced.
  // Recording that here lets the active-node decoration blocks below re-add only what actually
  // went away, instead of scanning the whole decoration set on every keystroke (VC90).
  // The active-node decorations only exist under the reliable anchor experiment, so the patch is
  // scoped to it as well. No-exposure check as this runs on every document change; the blocks
  // below that consume these flags are already inside an `expValEquals` guard for the same
  // experiment, so the exposure is fired there.
  var activeHandleDecDropped = false;
  var activeQuickInsertDecDropped = false;

  // When steps exist, remap existing decorations, activeNode and multi select positions
  if (tr.docChanged) {
    if (expValEqualsNoExposure('platform_editor_controls_reliable_anchor', 'isEnabled', true) && fg('platform_editor_controls_reliable_anchor_patch_1')) {
      decorations = decorations.map(tr.mapping, tr.doc, {
        onRemove: function onRemove(spec) {
          if ((spec === null || spec === void 0 ? void 0 : spec.type) === TYPE_ACTIVE_HANDLE_DEC) {
            activeHandleDecDropped = true;
          } else if ((spec === null || spec === void 0 ? void 0 : spec.type) === TYPE_ACTIVE_QUICK_INSERT_NODE) {
            activeQuickInsertDecDropped = true;
          }
        }
      });
    } else {
      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) {
          _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);
        }
        var mappedNodeType = activeNode.nodeType;
        var mappedRootNodeType = activeNode.rootNodeType;
        // Sparse mode does not redraw the old decorations. A block-type transaction may report
        // a text range that excludes the active block position, so always refresh the already
        // active node and root from the new document (for example, paragraph → heading-1).
        if (isExperimentEnabled('platform_editor_block_control_migration')) {
          var mappedNode = newState.doc.nodeAt(_mappedPos.pos);
          if (mappedNode !== null && mappedNode !== void 0 && mappedNode.isBlock) {
            mappedNodeType = getNodeTypeWithLevel(mappedNode);
          }
          var mappedRootNode = mappedRootPos ? mappedRootPos.pos === _mappedPos.pos && mappedNode ? mappedNode : newState.doc.nodeAt(mappedRootPos.pos) : undefined;
          if (mappedRootNode !== null && mappedRootNode !== void 0 && mappedRootNode.isBlock) {
            mappedRootNodeType = getNodeTypeWithLevel(mappedRootNode);
          }
        }
        activeNode = {
          pos: _mappedPos.pos,
          anchorName: activeNode.anchorName,
          nodeType: mappedNodeType,
          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: mappedRootNodeType
        };
      }
    }
    if (multiSelectDnD) {
      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) {
    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) || isExperimentEnabled('platform_editor_block_control_migration'));
  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, 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 = latestActiveNode.rootPos !== undefined ? getDecorationAtPos(newState, decorations, latestActiveNode.rootPos, to) : undefined;
        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);
  }

  // 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 (!isExperimentEnabled('platform_editor_block_control_migration') && isViewMode && rightSideControlsEnabled) {
    var allHandleDecs = findHandleDec(decorations, 0, newState.doc.content.size);
    if (allHandleDecs.length > 0) {
      decorations = decorations.remove(allHandleDecs);
    }
  }
  if (shouldRemoveHandle) {
    if (!isExperimentEnabled('platform_editor_block_control_migration')) {
      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);
    }
    // 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.
    // Use full-range search (0..contentSize) rather than a point-range at activeNode.pos/rootPos:
    // after a doc change (e.g. pressing Enter splits a node), DecorationSet.map() can shift the
    // decoration to a different position, so a point-range search would miss it and leave a stale
    // attribute on the wrong DOM node.
    if ((!isExperimentEnabled('platform_editor_block_control_migration') || nodeDecorationRegistry.length > 0) && expValEquals('platform_editor_controls_reliable_anchor', 'isEnabled', true)) {
      var oldActiveNodeDec = findActiveDragHandleNodeDec(decorations, 0, newState.doc.content.size);
      decorations = decorations.remove(oldActiveNodeDec);
      var oldActiveQuickInsertDec = findActiveQuickInsertNodeDec(decorations, 0, newState.doc.content.size);
      decorations = decorations.remove(oldActiveQuickInsertDec);
    }
    // nodeDecorationRegistry cleanup (e.g. the legacy Remix button) is independent of the legacy
    // quick-insert button, so this must not be gated by quickInsertButtonEnabled — otherwise a
    // stale decoration is left behind whenever platform_editor_block_control_migration is on.
    if (flags.toolbarFlagsEnabled) {
      // platform_editor_controls note: enables quick insert
      if (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);
      }
      var _iterator = _createForOfIteratorHelper(nodeDecorationRegistry),
        _step;
      try {
        var _loop2 = function _loop2() {
          var _activeNode1, _activeNode10;
          var factory = _step.value;
          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 (_iterator.s(); !(_step = _iterator.n()).done;) {
          _loop2();
        }
      } 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 _loop = function _loop() {
            var factory = _step2.value;
            if (factory.showInViewMode) {
              var _activeNode9, _activeNode0;
              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 (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            _loop();
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }
    }
  } else if (api) {
    var _latestActiveNode5, _latestActiveNode10;
    // The registry surface replaces the legacy drag-handle decorations during migration.
    if (!isExperimentEnabled('platform_editor_block_control_migration') && 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 ((!isExperimentEnabled('platform_editor_block_control_migration') ||
    // nodeDecorationRegistry consumers (e.g. the legacy Remix button) rely
    // on that same anchor-name for their own CSS anchor() positioning, so this must still run
    // when such a consumer exists even if the legacy drag handle itself is disabled.
    nodeDecorationRegistry.length > 0) && expValEquals('platform_editor_controls_reliable_anchor', 'isEnabled', true) && latestActiveNode) {
      // patch_1: a plain doc change no longer forces a rescan — map() above has already
      // either kept the decoration correctly positioned or dropped it as invalid, so we
      // only need to act when it was actually dropped.
      var docChangeInvalidatedNodeDec = fg('platform_editor_controls_reliable_anchor_patch_1') ? activeHandleDecDropped : tr.docChanged;

      // Recreate the drag handle node decoration when the active node changed,
      // its content was modified, or the document changed.
      // This runs independently of shouldRecreateHandle so that doc changes (like pressing
      // Enter) correctly refresh the decoration even when the handle widget doesn't move.
      // DecorationSet.map() can misplace the decoration after node splits/inserts.
      var needsNodeDecUpdate = activeNodeChanged || isActiveNodeModified || docChangeInvalidatedNodeDec;
      if (needsNodeDecUpdate) {
        var _newState$doc$nodeAt;
        var nodeSize = (_newState$doc$nodeAt = newState.doc.nodeAt(latestActiveNode.pos)) === null || _newState$doc$nodeAt === void 0 ? void 0 : _newState$doc$nodeAt.nodeSize;
        if (nodeSize !== undefined) {
          // Search the full doc range: after DecorationSet.map(), the decoration may have
          // shifted away from activeNode?.pos (e.g. a node split moves it to the new paragraph).
          var _oldActiveNodeDec = findActiveDragHandleNodeDec(decorations, 0, newState.doc.content.size);
          // Skip remove+add if the decoration is already at the correct position.
          // On pure text keystrokes, DecorationSet.map() keeps the decoration correctly
          // placed, so we avoid unnecessary churn on every character typed.
          var dragHandleDecAlreadyCorrect = _oldActiveNodeDec.length === 1 && _oldActiveNodeDec[0].from === latestActiveNode.pos && _oldActiveNodeDec[0].to === latestActiveNode.pos + nodeSize;
          if (!dragHandleDecAlreadyCorrect) {
            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.
      var needsQuickInsertDecUpdate = activeNodeChanged || isActiveNodeModified || rootActiveNodeChanged || (fg('platform_editor_controls_reliable_anchor_patch_1') ? activeQuickInsertDecDropped : tr.docChanged);
      if (needsQuickInsertDecUpdate && latestActiveNode.rootPos !== undefined) {
        var _newState$doc$nodeAt2;
        var 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 _oldActiveQuickInsertDec = findActiveQuickInsertNodeDec(decorations, 0, newState.doc.content.size);
          // Skip remove+add if the decoration is already at the correct position.
          // On pure text keystrokes, DecorationSet.map() keeps the decoration correctly
          // placed, so we avoid unnecessary churn on every character typed.
          var quickInsertDecAlreadyCorrect = _oldActiveQuickInsertDec.length === 1 && _oldActiveQuickInsertDec[0].from === latestActiveNode.rootPos && _oldActiveQuickInsertDec[0].to === latestActiveNode.rootPos + rootNodeSize;
          if (!quickInsertDecAlreadyCorrect) {
            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 && (quickInsertButtonEnabled || nodeDecorationRegistry.length > 0) &&
    // platform_editor_controls note: enables quick insert
    flags.toolbarFlagsEnabled && (!rightSideControlsEnabled || !isViewMode)) {
      var _latestActiveNode1;
      if (quickInsertButtonEnabled) {
        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]);
      }

      // 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.
      // Also skip when the needsQuickInsertDecUpdate block above already handled the update
      // (i.e. activeNodeChanged || isActiveNodeModified || rootActiveNodeChanged || tr.docChanged)
      // — running both would remove and re-add a duplicate decoration.
      if (expValEquals('platform_editor_controls_reliable_anchor', 'isEnabled', true) && !shouldRecreateHandle && !(activeNodeChanged || isActiveNodeModified || rootActiveNodeChanged || tr.docChanged) && ((_latestActiveNode1 = latestActiveNode) === null || _latestActiveNode1 === void 0 ? void 0 : _latestActiveNode1.rootPos) !== undefined) {
        var _newState$doc$nodeAt3;
        // Use full-range search (0..contentSize) rather than a point-range at activeNode.rootPos:
        // after a doc change, DecorationSet.map() can shift the decoration to a different position,
        // so a point-range search would miss it and leave a stale attribute on the wrong DOM node.
        var _oldActiveQuickInsertDec2 = findActiveQuickInsertNodeDec(decorations, 0, newState.doc.content.size);
        decorations = decorations.remove(_oldActiveQuickInsertDec2);
        var _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) {
        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 = (_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.
    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 (isExperimentEnabled('platform_editor_block_control_migration') && (meta === null || meta === void 0 ? void 0 : meta.isDragging) === false) {
    decorations = decorations.remove(findNodeDecs(newState, decorations));
  }
  if (isEmptyDoc && !(expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true) || isExperimentEnabled('platform_editor_block_control_migration'))) {
    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 _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.
    var hasHandleOrViewModeControls = isExperimentEnabled('platform_editor_block_control_migration') || isViewMode && rightSideControlsEnabled || findHandleDec(decorations, (_latestActiveNode11 = latestActiveNode) === null || _latestActiveNode11 === void 0 ? void 0 : _latestActiveNode11.pos, (_latestActiveNode12 = latestActiveNode) === null || _latestActiveNode12 === void 0 ? void 0 : _latestActiveNode12.pos).length > 0;
    // Keep the registry surface mounted while its Block Menu owns focus.
    var keepActiveNodeForOpenBlockMenu = isExperimentEnabled('platform_editor_block_control_migration') && isMenuOpen;
    newActiveNode = meta !== null && meta !== void 0 && meta.editorBlurred && !keepActiveNodeForOpenBlockMenu || !(meta !== null && meta !== void 0 && meta.activeNode) && !hasHandleOrViewModeControls ? null : latestActiveNode;
  } else {
    var _latestActiveNode13, _latestActiveNode14;
    newActiveNode = isEmptyDoc || !(meta !== null && meta !== void 0 && meta.activeNode) && !isExperimentEnabled('platform_editor_block_control_migration') && 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;
  }
  var isMenuOpenNew = isMenuOpen;
  var nextMenuTriggerByNode = (meta === null || meta === void 0 || (_meta$toggleMenu = meta.toggleMenu) === null || _meta$toggleMenu === void 0 ? void 0 : _meta$toggleMenu.triggerByNode) || menuTriggerByNode;
  if (isExperimentEnabled('platform_editor_block_control_migration') && tr.docChanged && menuTriggerByNode && !(meta !== null && meta !== void 0 && meta.toggleMenu)) {
    var _menuTriggerByNode$ro, _newState$doc$nodeAt4;
    var mapped = tr.mapping.mapResult(menuTriggerByNode.pos, 1);
    var mappedRoot = tr.mapping.mapResult((_menuTriggerByNode$ro = menuTriggerByNode.rootPos) !== null && _menuTriggerByNode$ro !== void 0 ? _menuTriggerByNode$ro : menuTriggerByNode.pos, 1);
    if (mapped.deleted || mappedRoot.deleted || !((_newState$doc$nodeAt4 = newState.doc.nodeAt(mapped.pos)) !== null && _newState$doc$nodeAt4 !== void 0 && _newState$doc$nodeAt4.isBlock)) {
      nextMenuTriggerByNode = undefined;
      isMenuOpenNew = false;
    } else {
      nextMenuTriggerByNode = _objectSpread(_objectSpread({}, menuTriggerByNode), {}, {
        pos: mapped.pos,
        rootPos: mappedRoot.pos
      });
    }
  }
  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;
  }
  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,
    surfaceNodePositions: surfaceNodePositions,
    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: (meta === null || meta === void 0 || (_meta$toggleMenu2 = meta.toggleMenu) === null || _meta$toggleMenu2 === void 0 ? void 0 : _meta$toggleMenu2.anchorName) || menuTriggerBy,
    menuTriggerByNode: nextMenuTriggerByNode,
    blockMenuOptions: {
      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
    },
    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 toolbarFlagsEnabled = areToolbarFlagsEnabled(Boolean(api === null || api === void 0 ? void 0 : api.toolbar));
  var flags = {
    toolbarFlagsEnabled: toolbarFlagsEnabled
  };
  var anchorRectCache;
  if (!isAnchorSupported()) {
    anchorRectCache = new AnchorRectCache();
  }
  var resizeObserverWidth;
  var pragmaticCleanup = null;
  // Limited mode is a one-way latch, so its teardown must only run on the transition.
  var limitedModeTeardown = {
    done: false
  };
  return new SafePlugin({
    key: key,
    state: {
      init: function init() {
        return _objectSpread({}, initialState);
      },
      apply: function apply(tr, currentState, _, newState) {
        return _apply(api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled, quickInsertButtonEnabled, anchorRectCache, resizeObserverWidth, pragmaticCleanup, limitedModeTeardown);
      }
    },
    props: {
      decorations: function decorations(state) {
        var _api$limitedMode3, _api$editorDisabled, _key$getState2, _api$editorViewMode3;
        if (api !== null && api !== void 0 && (_api$limitedMode3 = api.limitedMode) !== null && _api$limitedMode3 !== void 0 && (_api$limitedMode3 = _api$limitedMode3.sharedState.currentState()) !== null && _api$limitedMode3 !== void 0 && _api$limitedMode3.enabled) {
          return;
        }
        var isDisabled = api === null || api === void 0 || (_api$editorDisabled = api.editorDisabled) === null || _api$editorDisabled === void 0 || (_api$editorDisabled = _api$editorDisabled.sharedState.currentState()) === null || _api$editorDisabled === void 0 ? void 0 : _api$editorDisabled.editorDisabled;
        if (isDisabled) {
          var _api$editorViewMode2;
          var 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 || (_api$editorViewMode2 = api.editorViewMode) === null || _api$editorViewMode2 === void 0 || (_api$editorViewMode2 = _api$editorViewMode2.sharedState.currentState()) === null || _api$editorViewMode2 === void 0 ? void 0 : _api$editorViewMode2.mode) !== 'view') {
            return;
          }
        }
        var decorationSet = (_key$getState2 = key.getState(state)) === null || _key$getState2 === void 0 ? void 0 : _key$getState2.decorations;
        // In view mode with right-side controls, remove any lingering drag-handle decorations
        // (created in edit mode) that may not have been cleaned up on mode switch.
        if (decorationSet && !isExperimentEnabled('platform_editor_block_control_migration') && rightSideControlsEnabled && (api === null || api === void 0 || (_api$editorViewMode3 = api.editorViewMode) === null || _api$editorViewMode3 === void 0 || (_api$editorViewMode3 = _api$editorViewMode3.sharedState.currentState()) === null || _api$editorViewMode3 === void 0 ? void 0 : _api$editorViewMode3.mode) === 'view') {
          var handleDecs = findHandleDec(decorationSet, 0, state.doc.content.size);
          if (handleDecs.length > 0) {
            decorationSet = decorationSet.remove(handleDecs);
          }
        }
        return decorationSet;
      },
      handleDOMEvents: {
        drop: function drop(view, event) {
          var _pluginState, _pluginState2, _pluginState3, _event$target, _event$target$closest;
          // Prevent native DnD from triggering if we are in drag
          var dispatch = view.dispatch,
            dragging = view.dragging,
            state = view.state;
          var tr = state.tr;
          var pluginState = key.getState(state);
          var dndDragCancelled = (_pluginState = pluginState) === null || _pluginState === void 0 ? void 0 : _pluginState.lastDragCancelled;
          if ((_pluginState2 = pluginState) !== null && _pluginState2 !== void 0 && _pluginState2.isPMDragging || dndDragCancelled) {
            if (fg('platform_editor_ease_of_use_metrics')) {
              var _api$metrics2;
              api === null || api === void 0 || (_api$metrics2 = api.metrics) === null || _api$metrics2 === void 0 || _api$metrics2.commands.startActiveSessionTimer()({
                tr: tr
              });
            }
            dispatch(tr.setMeta(key, _objectSpread(_objectSpread({}, 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
          var draggable = dragging === null || dragging === void 0 ? void 0 : dragging.slice.content.firstChild;
          if (dndDragCancelled || (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;
          }
          var nodeElement = (_event$target = event.target) === null || _event$target === void 0 || (_event$target$closest = _event$target.closest) === null || _event$target$closest === void 0 ? void 0 : _event$target$closest.call(_event$target, "[".concat(getAnchorAttrName(), "]"));
          if (!nodeElement) {
            return false;
          }

          // TODO: ED-26959 - Review usage of posAtDOM here
          var domPos = Math.max(view.posAtDOM(nodeElement, 0) - 1, 0);
          var nodeTarget = state.doc.nodeAt(domPos);
          var isSameNode = !!(nodeTarget && draggable !== null && draggable !== void 0 && draggable.eq(nodeTarget));
          if (isSameNode) {
            event.preventDefault();
            return true;
          }
          return false;
        },
        dragenter: function dragenter(view, event) {
          var _api$limitedMode4, _key$getState3;
          if (api !== null && api !== void 0 && (_api$limitedMode4 = api.limitedMode) !== null && _api$limitedMode4 !== void 0 && (_api$limitedMode4 = _api$limitedMode4.sharedState.currentState()) !== null && _api$limitedMode4 !== void 0 && _api$limitedMode4.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)) {
            return;
          }
          if (isHTMLElement(event.target) && expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) {
            var targetElement = event.target.closest('[data-prosemirror-node-name]');
            if (targetElement) {
              var _api$blockControls$sh;
              var nodeTypeName = targetElement === null || targetElement === void 0 ? void 0 : targetElement.getAttribute('data-prosemirror-node-name');
              var pos = view.posAtDOM(targetElement, -1);
              var currentActiveDropTargetNode = api === null || api === 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) {
                var activeDropTargetNode = {
                  pos: pos,
                  nodeTypeName: nodeTypeName
                };
                view.dispatch(view.state.tr.setMeta(key, {
                  activeDropTargetNode: activeDropTargetNode
                }));
              }
            }
          } else if (isAdvancedLayoutEnabled) {
            if (isHTMLElement(event.target)) {
              var closestParentElement = event.target.closest('[data-drag-handler-anchor-depth="0"]');
              if (closestParentElement) {
                var currentAnchor = closestParentElement.getAttribute(getAnchorAttrName());
                if (currentAnchor) {
                  defaultActiveAnchorTracker.emit(currentAnchor);
                }
              }
            }
          }
        },
        dragstart: function dragstart(view) {
          var _api$limitedMode5, _anchorRectCache2;
          if (api !== null && api !== void 0 && (_api$limitedMode5 = api.limitedMode) !== null && _api$limitedMode5 !== void 0 && (_api$limitedMode5 = _api$limitedMode5.sharedState.currentState()) !== null && _api$limitedMode5 !== void 0 && _api$limitedMode5.enabled) {
            return;
          }
          startMeasure(EDITOR_BLOCKS_DRAG_INIT);
          if (isAdvancedLayoutEnabled) {
            defaultActiveAnchorTracker.reset();
          }
          if (expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) {
            var _anchorRectCache;
            (_anchorRectCache = anchorRectCache) === null || _anchorRectCache === void 0 || _anchorRectCache.clear();
          }
          (_anchorRectCache2 = anchorRectCache) === null || _anchorRectCache2 === void 0 || _anchorRectCache2.setEditorView(view);
          view.dispatch(view.state.tr.setMeta(key, _objectSpread(_objectSpread({}, view.state.tr.getMeta(key)), {}, {
            isPMDragging: true
          })));
        },
        dragend: function dragend(view) {
          var _api$limitedMode6, _key$getState4;
          if (api !== null && api !== void 0 && (_api$limitedMode6 = api.limitedMode) !== null && _api$limitedMode6 !== void 0 && (_api$limitedMode6 = _api$limitedMode6.sharedState.currentState()) !== null && _api$limitedMode6 !== void 0 && _api$limitedMode6.enabled) {
            return;
          }
          var state = view.state,
            dispatch = view.dispatch;
          if ((_key$getState4 = key.getState(state)) !== null && _key$getState4 !== void 0 && _key$getState4.isPMDragging) {
            var tr = state.tr;
            tr.setMeta(key, _objectSpread(_objectSpread({}, state.tr.getMeta(key)), {}, {
              isPMDragging: false
            }));
            if (fg('platform_editor_ease_of_use_metrics')) {
              var _api$metrics3;
              api === null || api === void 0 || (_api$metrics3 = api.metrics) === null || _api$metrics3 === void 0 || _api$metrics3.commands.startActiveSessionTimer()({
                tr: tr
              });
            }
            dispatch(tr);
          }
        },
        mouseover: function mouseover(view, event) {
          var _api$limitedMode7, _getNodeIdProvider;
          if (api !== null && api !== void 0 && (_api$limitedMode7 = api.limitedMode) !== null && _api$limitedMode7 !== void 0 && (_api$limitedMode7 = _api$limitedMode7.sharedState.currentState()) !== null && _api$limitedMode7 !== void 0 && _api$limitedMode7.enabled) {
            return;
          }

          // another layer of protection to prevent handling mouseover
          // when native anchor with dnd is enabled in limited mode
          // in case there are descripancies between getNodeIdProvider limited mode state
          if ((_getNodeIdProvider = getNodeIdProvider(view)) !== null && _getNodeIdProvider !== void 0 && _getNodeIdProvider.isLimitedMode() && (expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true) || isExperimentEnabled('platform_editor_block_control_migration'))) {
            return;
          }
          if (isExperimentEnabled('platform_editor_block_control_migration')) {
            handleSparseMouseOver(view, event, api);
          } else {
            handleMouseOver(view, event, api);
          }
          return false;
        },
        mousedown: function mousedown(view, event) {
          var _api$limitedMode8;
          if (api !== null && api !== void 0 && (_api$limitedMode8 = api.limitedMode) !== null && _api$limitedMode8 !== void 0 && (_api$limitedMode8 = _api$limitedMode8.sharedState.currentState()) !== null && _api$limitedMode8 !== void 0 && _api$limitedMode8.enabled) {
            return;
          }
          return editorExperiment('platform_editor_controls', 'variant1') ? handleMouseDown(api)(view, event) : undefined;
        },
        keydown: function keydown(view, event) {
          var _api$limitedMode9;
          if (api !== null && api !== void 0 && (_api$limitedMode9 = api.limitedMode) !== null && _api$limitedMode9 !== void 0 && (_api$limitedMode9 = _api$limitedMode9.sharedState.currentState()) !== null && _api$limitedMode9 !== void 0 && _api$limitedMode9.enabled) {
            return;
          }
          if (event.shiftKey && event.ctrlKey) {
            //prevent holding down key combo from firing repeatedly
            if (!event.repeat && boundKeydownHandler(api, formatMessage)(view, event)) {
              event.preventDefault();
              return true;
            }
          }
          if ((event.key === 'Enter' || event.key === ' ') && event.target instanceof HTMLElement && editorExperiment('platform_editor_controls', 'variant1')) {
            var isDragHandle = event.target.closest(DRAG_HANDLE_SELECTOR) !== null;
            api === null || api === void 0 || api.core.actions.execute(api === null || api === void 0 ? void 0 : api.blockControls.commands.setSelectedViaDragHandle(isDragHandle));
          }
          if ((event.key === 'ArrowLeft' || event.key === 'ArrowRight' || event.key === 'ArrowDown' || event.key === 'ArrowUp') && editorExperiment('platform_editor_controls', 'variant1')) {
            var _api$blockControls$sh2, _api$blockControls$sh3;
            var isBlockMenuOpen = api === null || api === void 0 || (_api$blockControls$sh2 = api.blockControls.sharedState.currentState()) === null || _api$blockControls$sh2 === void 0 ? void 0 : _api$blockControls$sh2.isMenuOpen;
            // when block menu is just open, and we press arrow keys, we want to use the arrow keys to navigate the block menu
            // in this scenario, isSelectedViaDragHandle should not be set to false
            if (api !== null && api !== void 0 && (_api$blockControls$sh3 = api.blockControls.sharedState.currentState()) !== null && _api$blockControls$sh3 !== void 0 && _api$blockControls$sh3.isSelectedViaDragHandle && !isBlockMenuOpen) {
              api === null || api === void 0 || api.core.actions.execute(api === null || api === void 0 ? void 0 : api.blockControls.commands.setSelectedViaDragHandle(false));
            }
          }
          if (!event.repeat && event.shiftKey && fg('platform_editor_elements_dnd_shift_click_select')) {
            view.dispatch(view.state.tr.setMeta(key, _objectSpread(_objectSpread({}, view.state.tr.getMeta(key)), {}, {
              isShiftDown: true
            })));
          }
          return false;
        },
        keyup: function keyup(view, event) {
          var _api$limitedMode0;
          if (api !== null && api !== void 0 && (_api$limitedMode0 = api.limitedMode) !== null && _api$limitedMode0 !== void 0 && (_api$limitedMode0 = _api$limitedMode0.sharedState.currentState()) !== null && _api$limitedMode0 !== void 0 && _api$limitedMode0.enabled) {
            return;
          }
          if (!event.repeat && event.key === 'Shift') {
            view.dispatch(view.state.tr.setMeta(key, _objectSpread(_objectSpread({}, view.state.tr.getMeta(key)), {}, {
              isShiftDown: false
            })));
          }
        },
        blur: function blur(view, event) {
          var _api$limitedMode1;
          if (api !== null && api !== void 0 && (_api$limitedMode1 = api.limitedMode) !== null && _api$limitedMode1 !== void 0 && (_api$limitedMode1 = _api$limitedMode1.sharedState.currentState()) !== null && _api$limitedMode1 !== void 0 && _api$limitedMode1.enabled) {
            return;
          }
          if (editorExperiment('platform_editor_controls', 'variant1')) {
            var _api$core2;
            // Focus moving into the registry surface remains inside the editor experience.
            var isChildOfSurface = isExperimentEnabled('platform_editor_block_control_migration') && event.relatedTarget instanceof HTMLElement && event.relatedTarget.closest(BLOCK_CONTROLS_SURFACE_SELECTOR) !== null;
            var shouldPreserveRemixInlineDropdownFocus = event.relatedTarget instanceof HTMLElement && event.relatedTarget.closest('[data-editor-remix-inline-dropdown-preserve-focus]') !== null;
            var isChildOfEditor = event.relatedTarget instanceof HTMLElement && event.relatedTarget.closest("#".concat(EDIT_AREA_ID)) !== null;

            // don't do anything if the event relatedTarget (the element receiving focus) is a child of the editor
            // or if the editor has focus
            if (isChildOfEditor || isChildOfSurface || shouldPreserveRemixInlineDropdownFocus || view.hasFocus()) {
              return false;
            }
            api === null || api === void 0 || (_api$core2 = api.core) === null || _api$core2 === void 0 || _api$core2.actions.execute(function (_ref6) {
              var tr = _ref6.tr;
              var currMeta = tr.getMeta(key);
              tr.setMeta(key, _objectSpread(_objectSpread({}, currMeta), {}, {
                editorBlurred: true
              }));
              return tr;
            });
            return false;
          }
        }
      }
    },
    view: function view(editorView) {
      var dom = editorView.dom;
      var editorContentArea = editorView.dom.closest('.fabric-editor-popup-scroll-parent');

      // Use ResizeObserver to observe resizer (scroll-parent typically grows when resizing) and editor width changes
      resizeObserverWidth = new ResizeObserver(rafSchedule(function (entries) {
        var pluginState = key.getState(editorView.state);
        if (!(pluginState !== null && pluginState !== void 0 && pluginState.isDragging)) {
          var isResizerResizing = !!dom.querySelector('.is-resizing');
          var transaction = editorView.state.tr;
          var shouldDispatch = false;
          if ((pluginState === null || pluginState === void 0 ? void 0 : pluginState.isResizerResizing) !== isResizerResizing) {
            transaction.setMeta('is-resizer-resizing', isResizerResizing);
            shouldDispatch = true;
          }

          // Registry surfaces have their own ResizeObservers and absolute placement.
          // Width metadata only drives legacy widget recreation.
          if (!isExperimentEnabled('platform_editor_block_control_migration') && !isResizerResizing) {
            var _editorContentArea2 = entries[0].target;
            // Ignored via go/ees005
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            var editorWidthRight = _editorContentArea2.getBoundingClientRect().right;
            // Ignored via go/ees005
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            var editorWidthLeft = _editorContentArea2.getBoundingClientRect().left;
            transaction.setMeta(key, _objectSpread(_objectSpread({}, transaction.getMeta(key)), {}, {
              editorWidthLeft: editorWidthLeft,
              editorWidthRight: editorWidthRight
            }));
            shouldDispatch = true;
          }
          if (shouldDispatch) {
            editorView.dispatch(transaction);
          }
        }
      }));
      var shouldObserve = !(expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true) || isExperimentEnabled('platform_editor_block_control_migration')) || !isAnchorSupported();
      if (editorContentArea && shouldObserve) {
        resizeObserverWidth.observe(editorContentArea);
      }

      // Start pragmatic monitors
      pragmaticCleanup = destroyFn(api, editorView);
      return {
        destroy: function destroy() {
          var _pragmaticCleanup;
          if (editorContentArea) {
            resizeObserverWidth.unobserve(editorContentArea);
          }
          (_pragmaticCleanup = pragmaticCleanup) === null || _pragmaticCleanup === void 0 || _pragmaticCleanup();
        }
      };
    }
  });
};
export var getBlockControlsMeta = function getBlockControlsMeta(tr) {
  return tr.getMeta(key);
};