UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

1,238 lines 78.6 kB
import rafSchedule from 'raf-schd';
import { getDocument } from '@atlaskit/browser-apis';
import { ACTION, ACTION_SUBJECT, ACTION_SUBJECT_ID, EVENT_TYPE } from '@atlaskit/editor-common/analytics';
import { getBrowserInfo } from '@atlaskit/editor-common/browser';
import { getNodeIdProvider } from '@atlaskit/editor-common/node-anchor';
import { isMeasuring, startMeasure, stopMeasure } from '@atlaskit/editor-common/performance-measures';
import { SafePlugin } from '@atlaskit/editor-common/safe-plugin';
import { DRAG_HANDLE_SELECTOR } from '@atlaskit/editor-common/styles';
import { areToolbarFlagsEnabled } from '@atlaskit/editor-common/toolbar-flag-check';
import { EDIT_AREA_ID } from '@atlaskit/editor-common/ui';
import { isEmptyDocument } from '@atlaskit/editor-common/utils';
import { PluginKey, TextSelection } from '@atlaskit/editor-prosemirror/state';
import { DecorationSet } from '@atlaskit/editor-prosemirror/view';
import { 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 const key = new PluginKey('blockControls');
const EDITOR_BLOCKS_DRAG_INIT = 'Editor Blocks Drag Initialization Time';
const EDITOR_BLOCKS_DROP_INIT = 'Editor Blocks Drop Initialization Time';
const scheduleCallback = (cb, options) => {
  return 'requestIdleCallback' in window ? requestIdleCallback(cb, {
    timeout: 5000,
    ...options
  }) : requestAnimationFrame(cb);
};
const isHTMLElement = element => {
  return element instanceof HTMLElement;
};
const destroyFn = (api, editorView) => {
  var _getDocument$querySel, _getDocument;
  const scrollable = (_getDocument$querySel = (_getDocument = getDocument()) === null || _getDocument === void 0 ? void 0 : _getDocument.querySelector('.fabric-editor-popup-scroll-parent')) !== null && _getDocument$querySel !== void 0 ? _getDocument$querySel : null;
  const cleanupFn = [];
  if (scrollable) {
    cleanupFn.push(autoScrollForElements({
      element: scrollable
    }));
  }
  let dragInitializationDuration = 0;
  cleanupFn.push(monitorForElements({
    canMonitor: ({
      source
    }) => source.data.type === 'element',
    onDrag: () => {
      if (fg('platform_editor_drag_and_drop_perf_analytics')) {
        if (isMeasuring(EDITOR_BLOCKS_DRAG_INIT)) {
          stopMeasure(EDITOR_BLOCKS_DRAG_INIT, duration => {
            dragInitializationDuration = duration;
          });
        }
      } else {
        if (isMeasuring(EDITOR_BLOCKS_DRAG_INIT)) {
          stopMeasure(EDITOR_BLOCKS_DRAG_INIT, (duration, startTime) => {
            var _api$analytics;
            api === null || api === void 0 ? void 0 : (_api$analytics = api.analytics) === null || _api$analytics === void 0 ? void 0 : _api$analytics.actions.fireAnalyticsEvent({
              action: ACTION.BLOCKS_DRAG_INIT,
              actionSubject: ACTION_SUBJECT.EDITOR,
              eventType: EVENT_TYPE.OPERATIONAL,
              attributes: {
                duration,
                startTime,
                nodesCount: editorView === null || editorView === void 0 ? void 0 : editorView.state.doc.nodeSize
              }
            });
          });
        }
      }
    },
    onDragStart: () => {
      if (isHTMLElement(scrollable)) {
        scrollable.style.setProperty('scroll-behavior', 'unset');
      }
    },
    onDrop: ({
      location,
      source
    }) => {
      var _api$core;
      if (isHTMLElement(scrollable)) {
        scrollable.style.setProperty('scroll-behavior', null);
      }
      if (fg('platform_editor_drag_and_drop_perf_analytics')) {
        startMeasure(EDITOR_BLOCKS_DROP_INIT);
      }
      if (!api) {
        return;
      }
      (_api$core = api.core) === null || _api$core === void 0 ? void 0 : _api$core.actions.execute(({
        tr
      }) => {
        var _api$blockControls, _api$selection, _api$userIntent;
        const {
          multiSelectDnD
        } = ((_api$blockControls = api.blockControls) === null || _api$blockControls === void 0 ? void 0 : _api$blockControls.sharedState.currentState()) || {};
        // Restore the users initial Editor selection when the drop completes
        if (multiSelectDnD) {
          // If the TextSelection between the drag start and end has changed, the document has changed, and we should not reapply the last selection
          const expandedSelectionUnchanged = multiSelectDnD.textAnchor === tr.selection.anchor && multiSelectDnD.textHead === tr.selection.head;
          if (expandedSelectionUnchanged) {
            const $anchor = tr.doc.resolve(multiSelectDnD.userAnchor);
            const $head = tr.doc.resolve(multiSelectDnD.userHead);
            if ($head.node() === $anchor.node()) {
              const $from = $anchor.min($head);
              selectNode(tr, $from.pos, $from.node().type.name, api);
            } else {
              tr.setSelection(TextSelection.create(tr.doc, multiSelectDnD.userAnchor, multiSelectDnD.userHead));
            }
          }
        }
        (_api$selection = api.selection) === null || _api$selection === void 0 ? void 0 : _api$selection.commands.clearManualSelection()({
          tr
        });
        const {
          start
        } = source.data;
        // if no drop targets are rendered, assume that drop is invalid
        const lastDragCancelled = location.current.dropTargets.length === 0;
        if (lastDragCancelled) {
          var _api$analytics2;
          const position = getSelectedSlicePosition(start, tr, api);
          const attributes = getMultiSelectAnalyticsAttributes(tr, position.from, position.to);
          const {
            nodeTypes,
            hasSelectedMultipleNodes
          } = attributes;
          const resolvedMovingNode = tr.doc.resolve(start);
          (_api$analytics2 = api.analytics) === null || _api$analytics2 === void 0 ? void 0 : _api$analytics2.actions.attachAnalyticsEvent({
            eventType: EVENT_TYPE.UI,
            action: ACTION.CANCELLED,
            actionSubject: ACTION_SUBJECT.DRAG,
            actionSubjectId: ACTION_SUBJECT_ID.ELEMENT_DRAG_HANDLE,
            attributes: {
              nodeDepth: resolvedMovingNode.depth,
              nodeTypes: nodeTypes || '',
              hasSelectedMultipleNodes
            }
          })(tr);
        }
        if (fg('platform_editor_ease_of_use_metrics')) {
          var _api$metrics;
          (_api$metrics = api.metrics) === null || _api$metrics === void 0 ? void 0 : _api$metrics.commands.startActiveSessionTimer()({
            tr
          });
        }
        (_api$userIntent = api.userIntent) === null || _api$userIntent === void 0 ? void 0 : _api$userIntent.commands.setCurrentUserIntent('default')({
          tr
        });
        return tr.setMeta(key, {
          ...tr.getMeta(key),
          isDragging: false,
          isPMDragging: false,
          lastDragCancelled
        });
      });
      if (fg('platform_editor_drag_and_drop_perf_analytics')) {
        // wait for the idle callback to ensure that the drag operation has completed
        scheduleCallback(() => {
          if (isMeasuring(EDITOR_BLOCKS_DROP_INIT)) {
            stopMeasure(EDITOR_BLOCKS_DROP_INIT, duration => {
              var _api$analytics3;
              const isCancelled = location.current.dropTargets.length === 0;
              api === null || api === void 0 ? void 0 : (_api$analytics3 = api.analytics) === null || _api$analytics3 === void 0 ? void 0 : _api$analytics3.actions.fireAnalyticsEvent({
                action: ACTION.ENDED,
                eventType: EVENT_TYPE.TRACK,
                actionSubject: ACTION_SUBJECT.DRAG,
                actionSubjectId: ACTION_SUBJECT_ID.ELEMENT_DRAG_HANDLE,
                attributes: {
                  dragInitializationDuration,
                  dropProcessingDuration: duration,
                  isCancelled,
                  nodesCount: editorView === null || editorView === void 0 ? void 0 : editorView.state.doc.nodeSize
                }
              });
            });
          }
        });
      }
    }
  }));
  return combine(...cleanupFn);
};
const initialState = {
  decorations: DecorationSet.empty,
  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 const getDecorations = state => {
  var _key$getState;
  return (_key$getState = key.getState(state)) === null || _key$getState === void 0 ? void 0 : _key$getState.decorations;
};
const getDecorationAtPos = (state, decorations, pos, to) => {
  // Find the newly minted node decs that touch the active node
  const findNewNodeDecs = findNodeDecs(state, decorations, pos - 1, to);

  // Find the specific dec that the active node corresponds to
  const nodeDecsAtActivePos = findNewNodeDecs.filter(dec => (dec === null || dec === void 0 ? void 0 : dec.from) === pos);

  // If multiple decorations at the active node pos, we want the last one
  const nodeDecAtActivePos = nodeDecsAtActivePos.pop();
  return nodeDecAtActivePos;
};
export const apply = (api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled = false, quickInsertButtonEnabled = true, anchorRectCache, resizeObserverWidth, pragmaticCleanup, limitedModeTeardown) => {
  var _meta$multiSelectDnD, _api$editorViewMode, _api$editorViewMode$s, _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;
  let {
    activeNode,
    decorations,
    isResizerResizing,
    multiSelectDnD
  } = currentState;
  const {
    surfaceNodePositions
  } = currentState;
  const {
    editorHeight,
    editorWidthLeft,
    editorWidthRight,
    isDragging,
    isMenuOpen,
    menuTriggerBy,
    menuTriggerByNode,
    blockMenuOptions,
    isPMDragging,
    isShiftDown,
    lastDragCancelled,
    isSelectedViaDragHandle
  } = currentState;
  let isActiveNodeDeleted = false;
  const {
    from,
    to,
    numReplaceSteps,
    isAllText,
    isReplacedWithSameSize
  } = getTrMetadata(tr, flags);
  const meta = tr.getMeta(key);
  if (isExperimentEnabled('platform_editor_dynamic_limited_mode')) {
    var _api$limitedMode, _api$limitedMode$shar;
    // 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.
    const limitedModeState = api === null || api === void 0 ? void 0 : (_api$limitedMode = api.limitedMode) === null || _api$limitedMode === void 0 ? void 0 : (_api$limitedMode$shar = _api$limitedMode.sharedState.currentState()) === null || _api$limitedMode$shar === void 0 ? void 0 : _api$limitedMode$shar.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;
        }
        const editorContentArea = (_getDocument$querySel2 = (_getDocument2 = getDocument()) === null || _getDocument2 === void 0 ? void 0 : _getDocument2.querySelector('.fabric-editor-popup-scroll-parent')) !== null && _getDocument$querySel2 !== void 0 ? _getDocument$querySel2 : null;
        if (editorContentArea && resizeObserverWidth) {
          resizeObserverWidth.unobserve(editorContentArea);
        }
        pragmaticCleanup === null || pragmaticCleanup === void 0 ? void 0 : pragmaticCleanup();
      }

      /**
       * 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 {
        ...currentState,
        activeNode: undefined,
        decorations: DecorationSet.empty,
        multiSelectDnD: undefined
      };
    }
  } else {
    var _api$limitedMode2, _api$limitedMode2$sha, _api$limitedMode2$sha2;
    const hasDocumentSizeBreachedThreshold = api === null || api === void 0 ? void 0 : (_api$limitedMode2 = api.limitedMode) === null || _api$limitedMode2 === void 0 ? void 0 : (_api$limitedMode2$sha = _api$limitedMode2.sharedState.currentState()) === null || _api$limitedMode2$sha === void 0 ? void 0 : (_api$limitedMode2$sha2 = _api$limitedMode2$sha.limitedModePluginKey.getState(newState)) === null || _api$limitedMode2$sha2 === void 0 ? void 0 : _api$limitedMode2$sha2.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().
       */
      const 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 ? 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.
  let activeHandleDecDropped = false;
  let 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: 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) {
        const mappedPos = tr.mapping.mapResult(activeNode.pos);
        isActiveNodeDeleted = mappedPos.deleted;
        activeNode = {
          pos: mappedPos.pos,
          anchorName: activeNode.anchorName,
          nodeType: activeNode.nodeType
        };
      }
    } else {
      if (activeNode && (meta === null || meta === void 0 ? void 0 : meta.isDragging) !== true) {
        var _mappedRootPos$pos, _mappedRootPos;
        let mappedPos;
        const browser = getBrowserInfo();
        // In safari, when platform_editor_controls is on,
        // sometimes the drag handle for the layout disppears after you click on the handle for a few times
        // Which caused the drag handle onClick event not firing, then block menu wouldn't be opened
        // This is caused by the mappedPos.deletedAfter sometimes returning true in webkit browsers even though the active node still exists
        // This is likely a prosemirror and safari integration bug, but to unblock the issue, we are going to use mappedPos.deleted in safari for now
        if (browser.webkit) {
          mappedPos = tr.mapping.mapResult(activeNode.pos);
          isActiveNodeDeleted = mappedPos.deleted;
        } else {
          mappedPos = tr.mapping.mapResult(activeNode.pos, -1);
          isActiveNodeDeleted = mappedPos.deletedAfter;
        }
        // for editor controls, remap the rootPos as well
        let mappedRootPos;
        if (activeNode.rootPos !== undefined) {
          mappedRootPos = tr.mapping.mapResult(activeNode.rootPos, -1);
        }
        let mappedNodeType = activeNode.nodeType;
        let 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')) {
          const mappedNode = newState.doc.nodeAt(mappedPos.pos);
          if (mappedNode !== null && mappedNode !== void 0 && mappedNode.isBlock) {
            mappedNodeType = getNodeTypeWithLevel(mappedNode);
          }
          const 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);
    }
  }
  const resizerMeta = tr.getMeta('is-resizer-resizing');
  isResizerResizing = resizerMeta !== null && resizerMeta !== void 0 ? resizerMeta : isResizerResizing;
  const hasJustFinishedResizing = resizerMeta === false;
  multiSelectDnD = (_meta$multiSelectDnD = meta === null || meta === void 0 ? void 0 : meta.multiSelectDnD) !== null && _meta$multiSelectDnD !== void 0 ? _meta$multiSelectDnD : multiSelectDnD;
  if (multiSelectDnD) {
    var _meta$isDragging;
    if (((_meta$isDragging = meta === null || meta === void 0 ? void 0 : meta.isDragging) !== null && _meta$isDragging !== void 0 ? _meta$isDragging : isDragging) && expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) {
      // When dragging, we want to keep the multiSelectDnD object unless both document and selection
      // has changed, in which case we want to reset it.
      const shouldResetMultiSelectDnD = tr.docChanged && tr.selectionSet && tr.selection.empty;
      multiSelectDnD = shouldResetMultiSelectDnD ? undefined : multiSelectDnD;
    } else {
      multiSelectDnD = (meta === null || meta === void 0 ? void 0 : meta.isDragging) === false || tr.selection.empty ? undefined : multiSelectDnD;
    }
  }
  const maybeNodeCountChanged = !isAllText && numReplaceSteps > 0;
  let latestActiveNode = meta === null || meta === void 0 ? void 0 : meta.activeNode;
  const isViewMode = (api === null || api === void 0 ? void 0 : (_api$editorViewMode = api.editorViewMode) === null || _api$editorViewMode === void 0 ? void 0 : (_api$editorViewMode$s = _api$editorViewMode.sharedState.currentState()) === null || _api$editorViewMode$s === void 0 ? void 0 : _api$editorViewMode$s.mode) === 'view';
  if (!latestActiveNode && (!isActiveNodeDeleted || isReplacedWithSameSize)) {
    latestActiveNode = activeNode;
  }

  // Re-create node decorations
  const isDecSetEmpty = decorations === DecorationSet.empty;
  const isNodeDecsMissing = isDecSetEmpty || maybeNodeCountChanged || editorExperiment('platform_editor_breakout_resizing', true) && hasJustFinishedResizing;
  const shouldRedrawNodeDecs = !isResizerResizing && (isNodeDecsMissing || (meta === null || meta === void 0 ? void 0 : meta.isDragging)) &&
  // Skip expensive anchor node decoration recalculations when native anchor support is enabled
  !(expValEquals('platform_editor_native_anchor_with_dnd', 'isEnabled', true) || isExperimentEnabled('platform_editor_block_control_migration'));
  let isActiveNodeModified = false;
  if (api && shouldRedrawNodeDecs) {
    const oldNodeDecs = findNodeDecs(newState, decorations, from, to);
    decorations = decorations.remove(oldNodeDecs);
    const newNodeDecs = nodeDecorations(newState, isDecSetEmpty ? undefined : from, isDecSetEmpty ? undefined : to);
    decorations = decorations.add(newState.doc, newNodeDecs);

    // platform_editor_controls note: enables quick insert
    if (!flags.toolbarFlagsEnabled) {
      if (latestActiveNode && !isActiveNodeDeleted) {
        // Find the newly minted node decs that touch the active node
        const findNewNodeDecs = findNodeDecs(newState, decorations, latestActiveNode.pos - 1, to);

        // Find the specific dec that the active node corresponds to
        const nodeDecsAtActivePos = findNewNodeDecs.filter(dec => (dec === null || dec === void 0 ? void 0 : dec.from) === latestActiveNode.pos);

        // If multiple decorations at the active node pos, we want the last one
        const nodeDecAtActivePos = nodeDecsAtActivePos.pop();

        // Update the active node anchor-name and type for accurate positioning
        if (nodeDecAtActivePos) {
          isActiveNodeModified = true;
          latestActiveNode.anchorName = nodeDecAtActivePos.spec.anchorName;
          latestActiveNode.nodeType = nodeDecAtActivePos.spec.nodeType;
        }
      }
    } else {
      if (latestActiveNode && (!isActiveNodeDeleted || isReplacedWithSameSize)) {
        const nodeDecAtActivePos = getDecorationAtPos(newState, decorations, latestActiveNode.pos, to);
        const 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
  const editorSizeChanged = (meta === null || meta === void 0 ? void 0 : meta.editorHeight) !== undefined && (meta === null || meta === void 0 ? void 0 : meta.editorHeight) !== editorHeight || (meta === null || meta === void 0 ? void 0 : meta.editorWidthLeft) !== undefined && (meta === null || meta === void 0 ? void 0 : meta.editorWidthLeft) !== editorWidthLeft || (meta === null || meta === void 0 ? void 0 : meta.editorWidthRight) !== undefined && (meta === null || meta === void 0 ? void 0 : meta.editorWidthRight) !== editorWidthRight;

  // Check if there's a new active node, and it differs from the last
  const activeNodeChanged = (meta === null || meta === void 0 ? void 0 : meta.activeNode) && ((meta === null || meta === void 0 ? void 0 : meta.activeNode.pos) !== ((_activeNode = activeNode) === null || _activeNode === void 0 ? void 0 : _activeNode.pos) && (meta === null || meta === void 0 ? void 0 : meta.activeNode.anchorName) !== ((_activeNode2 = activeNode) === null || _activeNode2 === void 0 ? void 0 : _activeNode2.anchorName) || (meta === null || meta === void 0 ? void 0 : (_meta$activeNode$hand = meta.activeNode.handleOptions) === null || _meta$activeNode$hand === void 0 ? void 0 : _meta$activeNode$hand.isFocused));
  const rootActiveNodeChanged = (meta === null || meta === void 0 ? void 0 : meta.activeNode) && (meta === null || meta === void 0 ? void 0 : meta.activeNode.rootPos) !== ((_activeNode3 = activeNode) === null || _activeNode3 === void 0 ? void 0 : _activeNode3.rootPos) && (meta === null || meta === void 0 ? void 0 : meta.activeNode.rootAnchorName) !== ((_activeNode4 = activeNode) === null || _activeNode4 === void 0 ? void 0 : _activeNode4.rootAnchorName);

  // Some browsers don't support anchor positioning, meaning we need to replace the handle when nodes change
  const handleNeedsRedraw = shouldRedrawNodeDecs && !isAnchorSupported();

  // Create/recreate handle dec when the active node is missing/changes, or the editor viewport has changed (non-anchor pos workaround)
  const shouldRecreateHandle = latestActiveNode && (activeNodeChanged || isActiveNodeModified || editorSizeChanged || handleNeedsRedraw);
  const shouldRecreateQuickInsertButton = latestActiveNode && (rootActiveNodeChanged || isActiveNodeModified || editorSizeChanged || handleNeedsRedraw);

  // If the active node is missing, we need to remove the handle
  let shouldRemoveHandle = latestActiveNode ? isResizerResizing || isActiveNodeDeleted && !isReplacedWithSameSize || (meta === null || meta === void 0 ? void 0 : meta.nodeMoved) : true;

  // platform_editor_controls note: enables quick insert
  if (flags.toolbarFlagsEnabled) {
    // Remove handle dec when editor is blurred
    shouldRemoveHandle = shouldRemoveHandle || (meta === null || meta === void 0 ? void 0 : meta.editorBlurred);
  }

  // In view mode with right-side controls, remove any lingering drag handle decorations
  // (they may carry over from edit mode). Only remove drag handles specifically, not
  // the remix button decorations (those are managed separately via showInViewMode).
  if (!isExperimentEnabled('platform_editor_block_control_migration') && isViewMode && rightSideControlsEnabled) {
    const 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;
      const oldHandle = findHandleDec(decorations, (_activeNode5 = activeNode) === null || _activeNode5 === void 0 ? void 0 : _activeNode5.pos, (_activeNode6 = activeNode) === null || _activeNode6 === void 0 ? void 0 : _activeNode6.pos);
      decorations = decorations.remove(oldHandle);
    }
    // When removing the handle, also remove the anchor-marker node decorations
    // (data-active-drag-handle / data-active-quick-insert) so the DOM attributes
    // don't linger on nodes that are no longer active.
    // 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)) {
      const oldActiveNodeDec = findActiveDragHandleNodeDec(decorations, 0, newState.doc.content.size);
      decorations = decorations.remove(oldActiveNodeDec);
      const 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;
        const oldQuickInsertButton = findQuickInsertInsertButtonDecoration(decorations, (_activeNode7 = activeNode) === null || _activeNode7 === void 0 ? void 0 : _activeNode7.rootPos, (_activeNode8 = activeNode) === null || _activeNode8 === void 0 ? void 0 : _activeNode8.rootPos);
        decorations = decorations.remove(oldQuickInsertButton);
      }
      for (const factory of nodeDecorationRegistry) {
        var _activeNode9, _activeNode0;
        const old = decorations.find((_activeNode9 = activeNode) === null || _activeNode9 === void 0 ? void 0 : _activeNode9.rootPos, (_activeNode0 = activeNode) === null || _activeNode0 === void 0 ? void 0 : _activeNode0.rootPos, spec => spec.type === factory.type);
        decorations = decorations.remove(old);
      }
      if (rightSideControlsEnabled && isViewMode && fg('confluence_remix_button_right_side_block_fg')) {
        for (const factory of nodeDecorationRegistry) {
          if (factory.showInViewMode) {
            var _activeNode1, _activeNode10;
            const old = decorations.find((_activeNode1 = activeNode) === null || _activeNode1 === void 0 ? void 0 : _activeNode1.rootPos, (_activeNode10 = activeNode) === null || _activeNode10 === void 0 ? void 0 : _activeNode10.rootPos, spec => spec.type === factory.type);
            decorations = decorations.remove(old);
          }
        }
      }
    }
  } else if (api) {
    var _latestActiveNode5, _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;
      const oldHandle = findHandleDec(decorations, (_activeNode11 = activeNode) === null || _activeNode11 === void 0 ? void 0 : _activeNode11.pos, (_activeNode12 = activeNode) === null || _activeNode12 === void 0 ? void 0 : _activeNode12.pos);
      decorations = decorations.remove(oldHandle);
      const handleDec = dragHandleDecoration({
        api,
        formatMessage,
        pos: (_latestActiveNode = latestActiveNode) === null || _latestActiveNode === void 0 ? void 0 : _latestActiveNode.pos,
        anchorName: (_latestActiveNode2 = latestActiveNode) === null || _latestActiveNode2 === void 0 ? void 0 : _latestActiveNode2.anchorName,
        nodeType: (_latestActiveNode3 = latestActiveNode) === null || _latestActiveNode3 === void 0 ? void 0 : _latestActiveNode3.nodeType,
        handleOptions: (_latestActiveNode4 = latestActiveNode) === null || _latestActiveNode4 === void 0 ? void 0 : _latestActiveNode4.handleOptions,
        nodeViewPortalProviderAPI,
        anchorRectCache,
        editorState: newState
      });
      decorations = decorations.add(newState.doc, [handleDec]);
    }
    if ((!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.
      const 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.
      const needsNodeDecUpdate = activeNodeChanged || isActiveNodeModified || docChangeInvalidatedNodeDec;
      if (needsNodeDecUpdate) {
        var _newState$doc$nodeAt;
        const nodeSize = (_newState$doc$nodeAt = newState.doc.nodeAt(latestActiveNode.pos)) === null || _newState$doc$nodeAt === void 0 ? void 0 : _newState$doc$nodeAt.nodeSize;
        if (nodeSize !== undefined) {
          // 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).
          const 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.
          const 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.
      const needsQuickInsertDecUpdate = activeNodeChanged || isActiveNodeModified || rootActiveNodeChanged || (fg('platform_editor_controls_reliable_anchor_patch_1') ? activeQuickInsertDecDropped : tr.docChanged);
      if (needsQuickInsertDecUpdate && latestActiveNode.rootPos !== undefined) {
        var _newState$doc$nodeAt2;
        const rootNodeSize = (_newState$doc$nodeAt2 = newState.doc.nodeAt(latestActiveNode.rootPos)) === null || _newState$doc$nodeAt2 === void 0 ? void 0 : _newState$doc$nodeAt2.nodeSize;
        if (rootNodeSize !== undefined) {
          const 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.
          const 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;
        const oldQuickInsertButton = findQuickInsertInsertButtonDecoration(decorations, (_activeNode13 = activeNode) === null || _activeNode13 === void 0 ? void 0 : _activeNode13.rootPos, (_activeNode14 = activeNode) === null || _activeNode14 === void 0 ? void 0 : _activeNode14.rootPos);
        decorations = decorations.remove(oldQuickInsertButton);
        const quickInsertButton = quickInsertButtonDecoration({
          api,
          formatMessage,
          anchorName: (_latestActiveNode6 = latestActiveNode) === null || _latestActiveNode6 === void 0 ? void 0 : _latestActiveNode6.anchorName,
          nodeType: (_latestActiveNode7 = latestActiveNode) === null || _latestActiveNode7 === void 0 ? void 0 : _latestActiveNode7.nodeType,
          nodeViewPortalProviderAPI,
          rootPos: (_latestActiveNode8 = latestActiveNode) === null || _latestActiveNode8 === void 0 ? void 0 : _latestActiveNode8.rootPos,
          rootAnchorName: (_latestActiveNode9 = latestActiveNode) === null || _latestActiveNode9 === void 0 ? void 0 : _latestActiveNode9.rootAnchorName,
          rootNodeType: (_latestActiveNode0 = latestActiveNode) === null || _latestActiveNode0 === void 0 ? void 0 : _latestActiveNode0.rootNodeType,
          anchorRectCache,
          editorState: newState
        });
        decorations = decorations.add(newState.doc, [quickInsertButton]);
      }

      // 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.
        const oldActiveQuickInsertDec = findActiveQuickInsertNodeDec(decorations, 0, newState.doc.content.size);
        decorations = decorations.remove(oldActiveQuickInsertDec);
        const rootNodeSize = (_newState$doc$nodeAt3 = newState.doc.nodeAt(latestActiveNode.rootPos)) === null || _newState$doc$nodeAt3 === void 0 ? void 0 : _newState$doc$nodeAt3.nodeSize;
        if (rootNodeSize !== undefined) {
          decorations = decorations.add(newState.doc, [createActiveQuickInsertNodeDecoration(latestActiveNode.rootPos, rootNodeSize)]);
        }
      }
      if (rightSideControlsEnabled) {
        for (const factory of nodeDecorationRegistry) {
          var _activeNode15, _activeNode16;
          if (!latestActiveNode || latestActiveNode.rootPos === undefined) {
            continue;
          }
          const params = {
            editorState: newState,
            nodeViewPortalProviderAPI,
            anchorName: latestActiveNode.anchorName,
            nodeType: latestActiveNode.nodeType,
            rootPos: latestActiveNode.rootPos,
            rootAnchorName: latestActiveNode.rootAnchorName,
            rootNodeType: latestActiveNode.rootNodeType
          };
          const old = decorations.find((_activeNode15 = activeNode) === null || _activeNode15 === void 0 ? void 0 : _activeNode15.rootPos, (_activeNode16 = activeNode) === null || _activeNode16 === void 0 ? void 0 : _activeNode16.rootPos, spec => spec.type === factory.type);
          decorations = decorations.remove(old);

          // determines whether to show the decorations, see malleableUiPlugin.tsx
          if (factory.shouldCreate && !factory.shouldCreate(params)) {
            continue;
          }
          const dec = factory.create(params);
          decorations = decorations.add(newState.doc, [dec]);
        }
      } else {
        for (const factory of nodeDecorationRegistry) {
          const old = decorations.find(0, newState.doc.nodeSize, spec => spec.type === factory.type);
          decorations = decorations.remove(old);
        }
      }
    }

    // In view mode (edit/live pages), show right-side controls on block hover (without drag handle or quick insert)
    const rootPos = (_latestActiveNode10 = latestActiveNode) === null || _latestActiveNode10 === void 0 ? void 0 : _latestActiveNode10.rootPos;
    // rootPos is computed using the same logic as the floating insert menu, so it always points to a top-level (doc child) block when defined.
    const isDocLevel = rootPos !== undefined && !isNaN(rootPos);
    if (isViewMode && isDocLevel && flags.toolbarFlagsEnabled && rightSideControlsEnabled) {
      for (const factory of nodeDecorationRegistry) {
        if (factory.showInViewMode) {
          if (!latestActiveNode || latestActiveNode.rootPos === undefined) {
            continue;
          }
          const params = {
            editorState: newState,
            nodeViewPortalProviderAPI,
            anchorName: latestActiveNode.anchorName,
            nodeType: latestActiveNode.nodeType,
            rootPos: latestActiveNode.rootPos,
            rootAnchorName: latestActiveNode.rootAnchorName,
            rootNodeType: latestActiveNode.rootNodeType
          };
          if (factory.shouldCreate && !factory.shouldCreate(params)) {
            continue;
          }
          const existingAtPos = decorations.find(rootPos, rootPos, spec => spec.type === factory.type);
          // Skip remove/re-add when decoration already exists at correct position - avoids
          // flickering from widget destroy/recreate on every transaction (e.g. on hover).
          if (existingAtPos.length > 0) {
            continue;
          }
          // Remove any stale decoration at a different position (e.g. after moving to another block)
          const stale = decorations.find(0, newState.doc.nodeSize, spec => spec.type === factory.type);
          decorations = decorations.remove(stale);
          const dec = factory.create(params);
          decorations = decorations.add(newState.doc, [dec]);
        }
      }
    } else if (isViewMode && rightSideControlsEnabled && fg('confluence_remix_button_right_side_block_fg')) {
      // Remove view-mode right-side decorations when no active node
      for (const factory of nodeDecorationRegistry) {
        if (factory.showInViewMode) {
          const old = decorations.find(0, newState.doc.nodeSize, spec => spec.type === factory.type);
          decorations = decorations.remove(old);
        }
      }
    }
  }

  // Drop targets may be missing when the node count is being changed during a drag
  const isDropTargetsMissing = ((_meta$isDragging2 = meta === null || meta === void 0 ? void 0 : meta.isDragging) !== null && _meta$isDragging2 !== void 0 ? _meta$isDragging2 : isDragging) && maybeNodeCountChanged && !(meta !== null && meta !== void 0 && meta.nodeMoved);

  // Remove drop target decorations when dragging stops or they need to be redrawn
  if ((meta === null || meta === void 0 ? void 0 : meta.isDragging) === false || isDropTargetsMissing) {
    const dropTargetDecs = findDropTargetDecs(decorations);
    decorations = decorations.remove(dropTargetDecs);
  }
  let currentActiveDropTargetNode = isDragging ? currentState.activeDropTargetNode : undefined;
  if (api) {
    if (expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) {
      // If page is updated while dragging (likely by remote updates), we simply remove the drop targets
      // and add them back when the user interacts with the editor again
      if (isDropTargetsMissing) {
        const oldDropTargetDecs = findDropTargetDecs(decorations);
        decorations = decorations.remove(oldDropTargetDecs);
      }
      if (meta !== null && meta !== void 0 && meta.activeDropTargetNode) {
        currentActiveDropTargetNode = meta === null || meta === void 0 ? void 0 : meta.activeDropTargetNode;
        const oldDropTargetDecs = findDropTargetDecs(decorations);
        const {
          decsToAdd,
          decsToRemove
        } = getActiveDropTargetDecorations(meta.activeDropTargetNode, newState, api, oldDropTargetDecs, formatMessage, nodeViewPortalProviderAPI, latestActiveNode, anchorRectCache);
        decorations = decorations.remove(decsToRemove);
        if (decsToAdd.length > 0) {
          decorations = decorations.add(newState.doc, decsToAdd);
        }
      }
    } else if (meta !== null && meta !== void 0 && meta.isDragging || isDropTargetsMissing) {
      // Add drop targets when dragging starts or some are missing
      const decs = dropTargetDecorations(newState, api, formatMessage, nodeViewPortalProviderAPI, latestActiveNode, anchorRectCache);
      decorations = decorations.add(newState.doc, decs);
    }
  }
  const isEmptyDoc = isEmptyDocument(newState.doc);
  if (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'))) {
    const hasNodeDecoration = !!findNodeDecs(newState, decorations).length;
    if (!hasNodeDecoration) {
      decorations = decorations.add(newState.doc, [emptyParagraphNodeDecorations()]);
    }
  }
  let newActiveNode;
  // platform_editor_controls note: enables quick insert
  if (flags.toolbarFlagsEnabled) {
    var _latestActiveNode11, _latestActiveNode12;
    // remove isEmptyDoc check and let decorations render and determine their own visibility
    // In view mode with right-side controls we render node decorations (right-edge button), not the
    // handle - so findHandleDec is always empty. Don't clear activeNode in that case.
    const hasHandleOrViewModeControls = 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.
    const 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;
  }
  let isMenuOpenNew = isMenuOpen;
  let nextMenuTriggerByNode = (meta === null || meta === void 0 ? 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;
    const mapped = tr.mapping.mapResult(menuTriggerByNode.pos, 1);
    const 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 = {
        ...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) {
    const isSameAnchor = (meta === null || meta === void 0 ? void 0 : meta.toggleMenu.anchorName) === menuTriggerBy;
    isMenuOpenNew = menuTriggerBy === undefined || isSameAnchor || !isMenuOpen && !isSameAnchor ? !isMenuOpen : isMenuOpen;
  }
  let isSelectedViaDragHandleNew;
  if (flags.toolbarFlagsEnabled) {
    isSelectedViaDragHandleNew = (meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle) !== undefined ? meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle : isSelectedViaDragHandle;
  } else {
    isSelectedViaDragHandleNew = (meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle) !== undefined && flags.toolbarFlagsEnabled && (meta === null || meta === void 0 ? void 0 : meta.isSelectedViaDragHandle);
  }
  return {
    decorations,
    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 ? 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 ? void 0 : (_meta$toggleMenu3 = meta.toggleMenu) === null || _meta$toggleMenu3 === void 0 ? void 0 : _meta$toggleMenu3.moveUp) !== undefined ? meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu4 = meta.toggleMenu) === null || _meta$toggleMenu4 === void 0 ? void 0 : _meta$toggleMenu4.moveUp : blockMenuOptions === null || blockMenuOptions === void 0 ? void 0 : blockMenuOptions.canMoveUp,
      canMoveDown: (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu5 = meta.toggleMenu) === null || _meta$toggleMenu5 === void 0 ? void 0 : _meta$toggleMenu5.moveDown) !== undefined ? meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu6 = meta.toggleMenu) === null || _meta$toggleMenu6 === void 0 ? void 0 : _meta$toggleMenu6.moveDown : blockMenuOptions === null || blockMenuOptions === void 0 ? void 0 : blockMenuOptions.canMoveDown,
      openedViaKeyboard: (meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu7 = meta.toggleMenu) === null || _meta$toggleMenu7 === void 0 ? void 0 : _meta$toggleMenu7.openedViaKeyboard) !== undefined ? meta === null || meta === void 0 ? void 0 : (_meta$toggleMenu8 = meta.toggleMenu) === null || _meta$toggleMenu8 === void 0 ? void 0 : _meta$toggleMenu8.openedViaKeyboard : blockMenuOptions === null || blockMenuOptions === void 0 ? void 0 : blockMenuOptions.openedViaKeyboard
    },
    editorHeight: (_meta$editorHeight = meta === null || meta === void 0 ? void 0 : meta.editorHeight) !== null && _meta$editorHeight !== void 0 ? _meta$editorHeight : editorHeight,
    editorWidthLeft: (_meta$editorWidthLeft = meta === null || meta === void 0 ? void 0 : meta.editorWidthLeft) !== null && _meta$editorWidthLeft !== void 0 ? _meta$editorWidthLeft : editorWidthLeft,
    editorWidthRight: (_meta$editorWidthRigh = meta === null || meta === void 0 ? void 0 : meta.editorWidthRight) !== null && _meta$editorWidthRigh !== void 0 ? _meta$editorWidthRigh : editorWidthRight,
    isResizerResizing: isResizerResizing,
    isDocSizeLimitEnabled: initialState.isDocSizeLimitEnabled,
    isPMDragging: (_meta$isPMDragging = meta === null || meta === void 0 ? void 0 : meta.isPMDragging) !== null && _meta$isPMDragging !== void 0 ? _meta$isPMDragging : isPMDragging,
    multiSelectDnD,
    isShiftDown: (_meta$isShiftDown = meta === null || meta === void 0 ? void 0 : meta.isShiftDown) !== null && _meta$isShiftDown !== void 0 ? _meta$isShiftDown : isShiftDown,
    lastDragCancelled: (_meta$lastDragCancell = meta === null || meta === void 0 ? void 0 : meta.lastDragCancelled) !== null && _meta$lastDragCancell !== void 0 ? _meta$lastDragCancell : lastDragCancelled,
    isSelectedViaDragHandle: isSelectedViaDragHandleNew
  };
};
export const createPlugin = (api, getIntl, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled = false, quickInsertButtonEnabled = true) => {
  const {
    formatMessage
  } = getIntl();
  const isAdvancedLayoutEnabled = editorExperiment('advanced_layouts', true, {
    exposure: true
  });
  const toolbarFlagsEnabled = areToolbarFlagsEnabled(Boolean(api === null || api === void 0 ? void 0 : api.toolbar));
  const flags = {
    toolbarFlagsEnabled
  };
  let anchorRectCache;
  if (!isAnchorSupported()) {
    anchorRectCache = new AnchorRectCache();
  }
  let resizeObserverWidth;
  let pragmaticCleanup = null;
  // Limited mode is a one-way latch, so its teardown must only run on the transition.
  const limitedModeTeardown = {
    done: false
  };
  return new SafePlugin({
    key,
    state: {
      init: () => ({
        ...initialState
      }),
      apply: (tr, currentState, _, newState) => apply(api, formatMessage, tr, currentState, newState, flags, nodeViewPortalProviderAPI, nodeDecorationRegistry, rightSideControlsEnabled, quickInsertButtonEnabled, anchorRectCache, resizeObserverWidth, pragmaticCleanup, limitedModeTeardown)
    },
    props: {
      decorations: state => {
        var _api$limitedMode3, _api$limitedMode3$sha, _api$editorDisabled, _api$editorDisabled$s, _key$getState2, _api$editorViewMode3, _api$editorViewMode3$;
        if (api !== null && api !== void 0 && (_api$limitedMode3 = api.limitedMode) !== null && _api$limitedMode3 !== void 0 && (_api$limitedMode3$sha = _api$limitedMode3.sharedState.currentState()) !== null && _api$limitedMode3$sha !== void 0 && _api$limitedMode3$sha.enabled) {
          return;
        }
        const isDisabled = api === null || api === void 0 ? void 0 : (_api$editorDisabled = api.editorDisabled) === null || _api$editorDisabled === void 0 ? void 0 : (_api$editorDisabled$s = _api$editorDisabled.sharedState.currentState()) === null || _api$editorDisabled$s === void 0 ? void 0 : _api$editorDisabled$s.editorDisabled;
        if (isDisabled) {
          var _api$editorViewMode2, _api$editorViewMode2$;
          const remixRightSideEnabled = rightSideControlsEnabled && fg('confluence_remix_button_right_side_block_fg');
          // Hide decorations when disabled, except in view mode when right-side controls are enabled
          if (!remixRightSideEnabled || (api === null || api === void 0 ? void 0 : (_api$editorViewMode2 = api.editorViewMode) === null || _api$editorViewMode2 === void 0 ? void 0 : (_api$editorViewMode2$ = _api$editorViewMode2.sharedState.currentState()) === null || _api$editorViewMode2$ === void 0 ? void 0 : _api$editorViewMode2$.mode) !== 'view') {
            return;
          }
        }
        let decorationSet = (_key$getState2 = key.getState(state)) === null || _key$getState2 === void 0 ? void 0 : _key$getState2.decorations;
        // 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 ? void 0 : (_api$editorViewMode3 = api.editorViewMode) === null || _api$editorViewMode3 === void 0 ? void 0 : (_api$editorViewMode3$ = _api$editorViewMode3.sharedState.currentState()) === null || _api$editorViewMode3$ === void 0 ? void 0 : _api$editorViewMode3$.mode) === 'view') {
          const handleDecs = findHandleDec(decorationSet, 0, state.doc.content.size);
          if (handleDecs.length > 0) {
            decorationSet = decorationSet.remove(handleDecs);
          }
        }
        return decorationSet;
      },
      handleDOMEvents: {
        drop(view, event) {
          var _pluginState, _pluginState2, _pluginState3, _event$target, _event$target$closest;
          // Prevent native DnD from triggering if we are in drag
          const {
            dispatch,
            dragging,
            state
          } = view;
          const tr = state.tr;
          let pluginState = key.getState(state);
          const dndDragCancelled = (_pluginState = pluginState) === null || _pluginState === void 0 ? void 0 : _pluginState.lastDragCancelled;
          if ((_pluginState2 = pluginState) !== null && _pluginState2 !== void 0 && _pluginState2.isPMDragging || dndDragCancelled) {
            if (fg('platform_editor_ease_of_use_metrics')) {
              var _api$metrics2;
              api === null || api === void 0 ? void 0 : (_api$metrics2 = api.metrics) === null || _api$metrics2 === void 0 ? void 0 : _api$metrics2.commands.startActiveSessionTimer()({
                tr
              });
            }
            dispatch(tr.setMeta(key, {
              ...tr.getMeta(key),
              isPMDragging: false,
              lastDragCancelled: false
            }));
          }
          pluginState = key.getState(view.state);
          if (!(event.target instanceof HTMLElement) || !((_pluginState3 = pluginState) !== null && _pluginState3 !== void 0 && _pluginState3.activeNode)) {
            return false;
          }
          // Currently we can only drag one node at a time
          // so we only need to check first child
          const draggable = dragging === null || dragging === void 0 ? void 0 : dragging.slice.content.firstChild;
          if (dndDragCancelled || (draggable === null || draggable === void 0 ? void 0 : draggable.type.name) === 'layoutColumn') {
            // we prevent native DnD for layoutColumn to prevent single column layout.
            event.preventDefault();
            return false;
          }
          const nodeElement = (_event$target = event.target) === null || _event$target === void 0 ? void 0 : (_event$target$closest = _event$target.closest) === null || _event$target$closest === void 0 ? void 0 : _event$target$closest.call(_event$target, `[${getAnchorAttrName()}]`);
          if (!nodeElement) {
            return false;
          }

          // TODO: ED-26959 - Review usage of posAtDOM here
          const domPos = Math.max(view.posAtDOM(nodeElement, 0) - 1, 0);
          const nodeTarget = state.doc.nodeAt(domPos);
          const isSameNode = !!(nodeTarget && draggable !== null && draggable !== void 0 && draggable.eq(nodeTarget));
          if (isSameNode) {
            event.preventDefault();
            return true;
          }
          return false;
        },
        dragenter(view, event) {
          var _api$limitedMode4, _api$limitedMode4$sha, _key$getState3;
          if (api !== null && api !== void 0 && (_api$limitedMode4 = api.limitedMode) !== null && _api$limitedMode4 !== void 0 && (_api$limitedMode4$sha = _api$limitedMode4.sharedState.currentState()) !== null && _api$limitedMode4$sha !== void 0 && _api$limitedMode4$sha.enabled) {
            return;
          }

          // Only process dragenter for block control drags.
          // Other drag types (e.g. table row) should not create
          // drop target decorations or emit active anchors.
          if (!((_key$getState3 = key.getState(view.state)) !== null && _key$getState3 !== void 0 && _key$getState3.isDragging)) {
            return;
          }
          if (isHTMLElement(event.target) && expValEquals('platform_editor_block_controls_perf_optimization', 'isEnabled', true)) {
            const targetElement = event.target.closest('[data-prosemirror-node-name]');
            if (targetElement) {
              var _api$blockControls$sh;
              const nodeTypeName = targetElement === null || targetElement === void 0 ? void 0 : targetElement.getAttribute('data-prosemirror-node-name');
              const pos = view.posAtDOM(targetElement, -1);
              const currentActiveDropTargetNode = api === null || api === void 0 ? void 0 : (_api$blockControls$sh = api.blockControls.sharedState.currentState()) === null || _api$blockControls$sh === void 0 ? void 0 : _api$blockControls$sh.activeDropTargetNode;
              if ((currentActiveDropTargetNode === null || currentActiveDropTargetNode === void 0 ? void 0 : currentActiveDropTargetNode.pos) !== pos || (currentActiveDropTargetNode === null || currentActiveDropTargetNode === void 0 ? void 0 : currentActiveDropTargetNode.nodeTypeName) !== nodeTypeName) {
                const activeDropTargetNode = {
                  pos,
                  nodeTypeName
                };
                view.dispatch(view.state.tr.setMeta(key, {
                  activeDropTargetNode
                }));
              }
            }
          } else if (isAdvancedLayoutEnabled) {
            if (isHTMLElement(event.target)) {
              const closestParentElement = event.target.closest('[data-drag-handler-anchor-depth="0"]');
              if (closestParentElement) {
                const currentAnchor = closestParentElement.getAttribute(getAnchorAttrName());
                if (currentAnchor) {
                  defaultActiveAnchorTracker.emit(currentAnchor);
                }
              }
            }
          }
        },
        dragstart(view) {
          var _api$limitedMode5, _api$limitedMode5$sha, _anchorRectCache2;
          if (api !== null && api !== void 0 && (_api$limitedMode5 = api.limitedMode) !== null && _api$limitedMode5 !== void 0 && (_api$limitedMode5$sha = _api$limitedMode5.sharedState.currentState()) !== null && _api$limitedMode5$sha !== void 0 && _api$limitedMode5$sha.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 ? void 0 : _anchorRectCache.clear();
          }
          (_anchorRectCache2 = anchorRectCache) === null || _anchorRectCache2 === void 0 ? void 0 : _anchorRectCache2.setEditorView(view);
          view.dispatch(view.state.tr.setMeta(key, {
            ...view.state.tr.getMeta(key),
            isPMDragging: true
          }));
        },
        dragend(view) {
          var _api$limitedMode6, _api$limitedMode6$sha, _key$getState4;
          if (api !== null && api !== void 0 && (_api$limitedMode6 = api.limitedMode) !== null && _api$limitedMode6 !== void 0 && (_api$limitedMode6$sha = _api$limitedMode6.sharedState.currentState()) !== null && _api$limitedMode6$sha !== void 0 && _api$limitedMode6$sha.enabled) {
            return;
          }
          const {
            state,
            dispatch
          } = view;
          if ((_key$getState4 = key.getState(state)) !== null && _key$getState4 !== void 0 && _key$getState4.isPMDragging) {
            const tr = state.tr;
            tr.setMeta(key, {
              ...state.tr.getMeta(key),
              isPMDragging: false
            });
            if (fg('platform_editor_ease_of_use_metrics')) {
              var _api$metrics3;
              api === null || api === void 0 ? void 0 : (_api$metrics3 = api.metrics) === null || _api$metrics3 === void 0 ? void 0 : _api$metrics3.commands.startActiveSessionTimer()({
                tr
              });
            }
            dispatch(tr);
          }
        },
        mouseover: (view, event) => {
          var _api$limitedMode7, _api$limitedMode7$sha, _getNodeIdProvider;
          if (api !== null && api !== void 0 && (_api$limitedMode7 = api.limitedMode) !== null && _api$limitedMode7 !== void 0 && (_api$limitedMode7$sha = _api$limitedMode7.sharedState.currentState()) !== null && _api$limitedMode7$sha !== void 0 && _api$limitedMode7$sha.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: (view, event) => {
          var _api$limitedMode8, _api$limitedMode8$sha;
          if (api !== null && api !== void 0 && (_api$limitedMode8 = api.limitedMode) !== null && _api$limitedMode8 !== void 0 && (_api$limitedMode8$sha = _api$limitedMode8.sharedState.currentState()) !== null && _api$limitedMode8$sha !== void 0 && _api$limitedMode8$sha.enabled) {
            return;
          }
          return editorExperiment('platform_editor_controls', 'variant1') ? handleMouseDown(api)(view, event) : undefined;
        },
        keydown(view, event) {
          var _api$limitedMode9, _api$limitedMode9$sha;
          if (api !== null && api !== void 0 && (_api$limitedMode9 = api.limitedMode) !== null && _api$limitedMode9 !== void 0 && (_api$limitedMode9$sha = _api$limitedMode9.sharedState.currentState()) !== null && _api$limitedMode9$sha !== void 0 && _api$limitedMode9$sha.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')) {
            const isDragHandle = event.target.closest(DRAG_HANDLE_SELECTOR) !== null;
            api === null || api === void 0 ? 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;
            const isBlockMenuOpen = api === null || api === void 0 ? 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 ? 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, {
              ...view.state.tr.getMeta(key),
              isShiftDown: true
            }));
          }
          return false;
        },
        keyup(view, event) {
          var _api$limitedMode0, _api$limitedMode0$sha;
          if (api !== null && api !== void 0 && (_api$limitedMode0 = api.limitedMode) !== null && _api$limitedMode0 !== void 0 && (_api$limitedMode0$sha = _api$limitedMode0.sharedState.currentState()) !== null && _api$limitedMode0$sha !== void 0 && _api$limitedMode0$sha.enabled) {
            return;
          }
          if (!event.repeat && event.key === 'Shift') {
            view.dispatch(view.state.tr.setMeta(key, {
              ...view.state.tr.getMeta(key),
              isShiftDown: false
            }));
          }
        },
        blur(view, event) {
          var _api$limitedMode1, _api$limitedMode1$sha;
          if (api !== null && api !== void 0 && (_api$limitedMode1 = api.limitedMode) !== null && _api$limitedMode1 !== void 0 && (_api$limitedMode1$sha = _api$limitedMode1.sharedState.currentState()) !== null && _api$limitedMode1$sha !== void 0 && _api$limitedMode1$sha.enabled) {
            return;
          }
          if (editorExperiment('platform_editor_controls', 'variant1')) {
            var _api$core2;
            // Focus moving into the registry surface remains inside the editor experience.
            const isChildOfSurface = isExperimentEnabled('platform_editor_block_control_migration') && event.relatedTarget instanceof HTMLElement && event.relatedTarget.closest(BLOCK_CONTROLS_SURFACE_SELECTOR) !== null;
            const shouldPreserveRemixInlineDropdownFocus = event.relatedTarget instanceof HTMLElement && event.relatedTarget.closest('[data-editor-remix-inline-dropdown-preserve-focus]') !== null;
            const isChildOfEditor = event.relatedTarget instanceof HTMLElement && event.relatedTarget.closest(`#${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 ? void 0 : (_api$core2 = api.core) === null || _api$core2 === void 0 ? void 0 : _api$core2.actions.execute(({
              tr
            }) => {
              const currMeta = tr.getMeta(key);
              tr.setMeta(key, {
                ...currMeta,
                editorBlurred: true
              });
              return tr;
            });
            return false;
          }
        }
      }
    },
    view: editorView => {
      const dom = editorView.dom;
      const 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(entries => {
        const pluginState = key.getState(editorView.state);
        if (!(pluginState !== null && pluginState !== void 0 && pluginState.isDragging)) {
          const isResizerResizing = !!dom.querySelector('.is-resizing');
          const transaction = editorView.state.tr;
          let 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) {
            const editorContentArea = entries[0].target;
            // Ignored via go/ees005
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            const editorWidthRight = editorContentArea.getBoundingClientRect().right;
            // Ignored via go/ees005
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            const editorWidthLeft = editorContentArea.getBoundingClientRect().left;
            transaction.setMeta(key, {
              ...transaction.getMeta(key),
              editorWidthLeft,
              editorWidthRight
            });
            shouldDispatch = true;
          }
          if (shouldDispatch) {
            editorView.dispatch(transaction);
          }
        }
      }));
      const 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() {
          var _pragmaticCleanup;
          if (editorContentArea) {
            resizeObserverWidth.unobserve(editorContentArea);
          }
          (_pragmaticCleanup = pragmaticCleanup) === null || _pragmaticCleanup === void 0 ? void 0 : _pragmaticCleanup();
        }
      };
    }
  });
};
export const getBlockControlsMeta = tr => {
  return tr.getMeta(key);
};