UNPKG

@atlaskit/editor-plugin-floating-toolbar

Version:

Floating toolbar plugin for @atlaskit/editor-core

66 lines (64 loc) 1.97 kB
import { SafePlugin } from '@atlaskit/editor-common/safe-plugin'; import { PluginKey } from '@atlaskit/editor-prosemirror/state'; export var forceFocusStateKey = new PluginKey('forceFocusStatePlugin'); /** * Used in cases where a floating toolbar button opens a submenu which destroys * the button, but the user has pressed ESC to close the submenu and focus needs * to move back to the button. */ export default (function () { return new SafePlugin({ key: forceFocusStateKey, state: { init: function init() { return { selector: null }; }, apply: function apply(tr, prevState) { var meta = tr.getMeta(forceFocusStateKey); if (meta && 'selector' in meta) { return { selector: meta.selector }; } return prevState; } } }); }); /** * The provided selector should be the floating toolbar button that needs focus. */ export var forceFocusSelector = function forceFocusSelector(selector) { return function (tr) { return tr.setMeta(forceFocusStateKey, { selector: selector }); }; }; /** * If a selector is set and the element exists, focus it. */ export function checkShouldForceFocusAndApply(view) { var state = view === null || view === void 0 ? void 0 : view.state; if (state) { var _forceFocusStateKey$g = forceFocusStateKey.getState(state), selector = _forceFocusStateKey$g.selector; if (selector) { var focusableElement = document.querySelector(selector); if (focusableElement) { focusableElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' }); // Ignored via go/ees005 // eslint-disable-next-line @atlaskit/editor/no-as-casting focusableElement.focus(); var tr = view.state.tr, dispatch = view.dispatch; dispatch(forceFocusSelector(null)(tr)); } } } }