UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

69 lines (64 loc) 2.51 kB
import { getDocument } from '@atlaskit/browser-apis'; import { selectionPreservationPluginKey } from './plugin-key'; /** * Detects if any of the transactions include user-driven selection changes. * * @param transactions The list of transactions to check. * @returns True if any transaction includes a user-driven selection change, otherwise false. */ export var hasUserSelectionChange = function hasUserSelectionChange(transactions) { return transactions.some(function (tr) { return tr.getMeta('pointer') && tr.selectionSet; }); }; export var getSelectionPreservationMeta = function getSelectionPreservationMeta(tr) { return tr.getMeta(selectionPreservationPluginKey); }; /** * Compares two selections for equality based on their from and to positions. * * @param a The first selection to compare. * @param b The second selection to compare. * @returns True if both selections are equal, otherwise false. */ export var compareSelections = function compareSelections(a, b) { return !a && !b || !!a && !!b && a.eq(b); }; /** * Forces the browser's native selection to match ProseMirror's selection state. * * This is necessary when the editor doesn't have focus (e.g., when block menu is open) * but we still need to update the visual selection after moving nodes. Without this, * the browser's native selection remains at the old position, causing ghost highlighting. * * @param selection The current ProseMirror selection state to sync to DOM. * @param view The EditorView instance used to convert ProseMirror positions to DOM positions. */ export var syncDOMSelection = function syncDOMSelection(selection, view) { try { var domSelection = window.getSelection(); if (!domSelection) { return; } var doc = getDocument(); if (!doc) { return; } // Convert ProseMirror selection to DOM selection using view.domAtPos var anchor = view.domAtPos(selection.anchor); var head = view.domAtPos(selection.head); if (!anchor || !head) { return; } // Create a new DOM range from the ProseMirror selection var range = doc.createRange(); range.setStart(anchor.node, anchor.offset); range.setEnd(head.node, head.offset); // Update the DOM selection to match ProseMirror's selection domSelection.removeAllRanges(); domSelection.addRange(range); } catch (_unused) { // Silently fail if DOM selection sync fails // This can happen if positions are invalid or DOM hasn't updated yet } };