UNPKG

@atlaskit/editor-plugin-find-replace

Version:

find replace plugin for @atlaskit/editor-core

61 lines (59 loc) • 2.74 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. */ const isFromTextEntry = event => { const target = event.target; return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLElement && target.isContentEditable; }; const activateInViewMode = api => (state, dispatch) => { var _api$editorViewMode, _api$editorViewMode$s, _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 ? 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') { return false; } activateWithAnalytics(api === null || api === void 0 ? 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 const viewModeShortcutPlugin = api => { const bindings = {}; if (findKeymap.common) { bindKeymapWithCommand(findKeymap.common, activateInViewMode(api), bindings); } const handleKeydown = keydownHandler(bindings); return new SafePlugin({ view: view => { const unbind = bind(view.root, { type: 'keydown', 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 }; } }); };