@atlaskit/editor-plugin-floating-toolbar
Version:
Floating toolbar plugin for @atlaskit/editor-core
72 lines (70 loc) • 2.28 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.checkShouldForceFocusAndApply = checkShouldForceFocusAndApply;
exports.forceFocusStateKey = exports.forceFocusSelector = exports.default = void 0;
var _safePlugin = require("@atlaskit/editor-common/safe-plugin");
var _state = require("@atlaskit/editor-prosemirror/state");
var forceFocusStateKey = exports.forceFocusStateKey = new _state.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. */
var _default = exports.default = function _default() {
return new _safePlugin.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.
*/
var forceFocusSelector = exports.forceFocusSelector = function forceFocusSelector(selector) {
return function (tr) {
return tr.setMeta(forceFocusStateKey, {
selector: selector
});
};
};
/**
* If a selector is set and the element exists, focus it.
*/
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));
}
}
}
}