UNPKG

@atlaskit/editor-plugin-find-replace

Version:

find replace plugin for @atlaskit/editor-core

63 lines (61 loc) • 2.83 kB
import { bind } from 'bind-event-listener'; import { TRIGGER_METHOD } from '@atlaskit/editor-common/analytics/types/enums'; import { bindKeymapWithCommand, find as findKeymap } from '@atlaskit/editor-common/keymaps'; import { SafePlugin } from '@atlaskit/editor-common/safe-plugin'; import { keydownHandler } from '@atlaskit/editor-prosemirror/keymap'; import { activateWithAnalytics } from './commands-with-analytics'; /** * Whether the event came from a field the user is typing into. `Mod-f` belongs to * that field, not to us. */ var isFromTextEntry = function isFromTextEntry(event) { var target = event.target; return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable; }; var activateInViewMode = function activateInViewMode(api) { return function (state, dispatch) { var _api$editorViewMode, _api$analytics; // In edit mode `./keymap.ts` already handles `Mod-f`. Handling it here as well // would activate the dialog twice from a single keypress. if ((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') { return false; } activateWithAnalytics(api === null || api === void 0 || (_api$analytics = api.analytics) === null || _api$analytics === void 0 ? void 0 : _api$analytics.actions, api === null || api === void 0 ? void 0 : api.editorViewMode)({ triggerMethod: TRIGGER_METHOD.SHORTCUT })(state, dispatch); return true; }; }; /** * Opens the find dialog on `Mod-f` while the editor is in view mode. * * The listener is bound on the document so that it still fires in view mode, where * ProseMirror delivers the keydown to neither `keymap()` nor `handleDOMEvents`. */ export var viewModeShortcutPlugin = function viewModeShortcutPlugin(api) { var bindings = {}; if (findKeymap.common) { bindKeymapWithCommand(findKeymap.common, activateInViewMode(api), bindings); } var handleKeydown = keydownHandler(bindings); return new SafePlugin({ view: function view(_view) { var unbind = bind(_view.root, { type: 'keydown', listener: function listener(event) { // `view.root` is `Document | ShadowRoot`, so the binding widens the event. if (!(event instanceof KeyboardEvent) || isFromTextEntry(event)) { return; } if (handleKeydown(_view, event)) { // Without this the browser find bar opens on top of our dialog. event.preventDefault(); } } }); return { destroy: unbind }; } }); };