import { random } from 'lodash'; import { action } from 'mobx'; import { Doc, DocListCast } from '../../fields/Doc'; import { Id } from '../../fields/FieldSymbols'; import { InkInkTool, InkTool } from '../../fields/InkField'; import { ScriptField } from '../../fields/ScriptField'; import { Cast, PromiseValue } from '../../fields/Types'; import { GoogleAuthenticationManager } from '../apis/GoogleAuthenticationManager'; import { DragManager } from '../util/DragManager'; import { GroupManager } from '../util/GroupManager'; import { SettingsManager } from '../util/SettingsManager'; import { SharingManager } from '../util/SharingManager'; import { SnappingManager } from '../util/SnappingManager'; import { UndoManager } from '../util/UndoManager'; import { ContextMenu } from './ContextMenu'; import { DocumentDecorations } from './DocumentDecorations'; import { InkStrokeProperties } from './InkStrokeProperties'; import { MainView } from './MainView'; import { CollectionDockingView } from './collections/CollectionDockingView'; import { CollectionStackedTimeline } from './collections/CollectionStackedTimeline'; import { CollectionFreeFormDocumentView } from './nodes/CollectionFreeFormDocumentView'; import { DocumentLinksButton } from './nodes/DocumentLinksButton'; import { DocumentView } from './nodes/DocumentView'; import { OpenWhereMod } from './nodes/OpenWhere'; import { AnchorMenu } from './pdf/AnchorMenu'; const modifiers = ['control', 'meta', 'shift', 'alt']; type KeyControlInfo = { preventDefault: boolean; stopPropagation: boolean; }; type KeyHandler = (keycode: string, e: KeyboardEvent) => KeyControlInfo; export class KeyManager { // eslint-disable-next-line no-use-before-define public static Instance: KeyManager; private router = new Map(); constructor() { KeyManager.Instance = this; const isMac = navigator.platform.toLowerCase().indexOf('mac') >= 0; // SHIFT CONTROL ALT META this.router.set('0000', this.unmodified); this.router.set(isMac ? '0001' : '0100', this.ctrl); this.router.set(isMac ? '0100' : '0010', this.alt); this.router.set(isMac ? '1001' : '1100', this.ctrl_shift); this.router.set('1000', this.shift); window.removeEventListener('keydown', KeyManager.Instance.handleModifiers, true); window.addEventListener('keydown', KeyManager.Instance.handleModifiers, true); window.removeEventListener('keyup', KeyManager.Instance.unhandleModifiers); window.addEventListener('keyup', KeyManager.Instance.unhandleModifiers); window.removeEventListener('keydown', KeyManager.Instance.handle); window.addEventListener('keydown', KeyManager.Instance.handle); window.removeEventListener('keyup', KeyManager.Instance.unhandle); window.addEventListener('keyup', KeyManager.Instance.unhandle); window.addEventListener('paste', KeyManager.Instance.paste); } public unhandle = action((/* e: KeyboardEvent */) => { /* empty */ }); public handleModifiers = action((e: KeyboardEvent) => { if (e.shiftKey) SnappingManager.SetShiftKey(true); if (e.ctrlKey) SnappingManager.SetCtrlKey(true); if (e.metaKey) SnappingManager.SetMetaKey(true); }); public unhandleModifiers = action((e: KeyboardEvent) => { if (!e.shiftKey) SnappingManager.SetShiftKey(false); if (!e.ctrlKey) SnappingManager.SetCtrlKey(false); if (!e.metaKey) SnappingManager.SetMetaKey(false); }); public handle = action((e: KeyboardEvent) => { // accumulate buffer of characters to insert in a new text note. once the note is created, it will stop keyboard events from reaching this function. const keyname = e.key && e.key.toLowerCase(); this.handleGreedy(/* keyname */); if (modifiers.includes(keyname)) { return; } const bit = (value: boolean) => (value ? '1' : '0'); const modifierIndex = bit(e.shiftKey) + bit(e.ctrlKey) + bit(e.altKey) + bit(e.metaKey); const handleConstrained = this.router.get(modifierIndex); if (!handleConstrained) { return; } const control = handleConstrained(keyname, e); control.stopPropagation && e.stopPropagation(); control.preventDefault && e.preventDefault(); }); private handleGreedy = action((/* keyname: string */) => {}); nudge = (x: number, y: number, label: string) => { const nudgeable = DocumentView.Selected().some(dv => CollectionFreeFormDocumentView.from(dv)?.nudge); nudgeable && UndoManager.RunInBatch(() => DocumentView.Selected().map(dv => CollectionFreeFormDocumentView.from(dv)?.nudge(x, y)), label); return { stopPropagation: nudgeable, preventDefault: nudgeable }; }; private unmodified = action((keyname: string, e: KeyboardEvent) => { const nothing = { stopPropagation: false, preventDefault: false, }; switch (keyname) { case ' ': // MarqueeView.DragMarquee = !MarqueeView.DragMarquee; // bcz: this needs a better disclosure UI break; case 'escape': { DocumentLinksButton.StartLink = undefined; DocumentLinksButton.StartLinkView = undefined; InkStrokeProperties.Instance._controlButton = false; Doc.ActiveTool = InkTool.None; DragManager.CompleteWindowDrag?.(true); let doDeselect = true; if (SnappingManager.IsDragging) { DragManager.AbortDrag(); } if (CollectionDockingView.Instance?.HasFullScreen) { CollectionDockingView.Instance?.CloseFullScreen(); } if (CollectionStackedTimeline.SelectingRegions.size) { CollectionStackedTimeline.StopSelecting(); doDeselect = false; } else { doDeselect = !ContextMenu.Instance.closeMenu(); } if (doDeselect) { DocumentView.DeselectAll(); DocumentView.SetLightboxDoc(undefined); } // DictationManager.Controls.stop(); GoogleAuthenticationManager.Instance.cancel(); SharingManager.Instance.close(); if (!GroupManager.Instance.isOpen) SettingsManager.Instance.closeMgr(); GroupManager.Instance.close(); window.getSelection()?.empty(); document.body.focus(); } break; case 'enter': // DocumentDecorations.Instance.onCloseClick(false); break; case 'delete': case 'backspace': if (document.activeElement?.tagName !== 'INPUT' && document.activeElement?.tagName !== 'TEXTAREA') { if (DocumentView.LightboxDoc() && !DocumentView.Selected().length) { DocumentView.SetLightboxDoc(undefined); DocumentView.DeselectAll(); } else if (!window.getSelection()?.toString()) DocumentDecorations.Instance.onCloseClick(true); return { stopPropagation: true, preventDefault: true }; } break; case 'arrowleft': return (e.target as HTMLInputElement)?.type !== 'text' ? this.nudge(-1, 0, 'nudge left') : nothing; // if target is an input box, then we don't want to nudge any Docs since we're justing moving within the text itself. case 'arrowright': return (e.target as HTMLInputElement)?.type !== 'text' ? this.nudge( 1, 0, 'nudge right') : nothing; case 'arrowup': return (e.target as HTMLInputElement)?.type !== 'text' ? this.nudge(0, -1, 'nudge up') : nothing; case 'arrowdown': return (e.target as HTMLInputElement | null)?.type !== 'text'? this.nudge(0, 1, 'nudge down'): nothing; default: } // prettier-ignore return nothing; }); private shift = action((keyname: string) => { switch (keyname) { case 'arrowleft': return this.nudge(-10,0, 'nudge left'); case 'arrowright': return this.nudge(10, 0, 'nudge right'); case 'arrowup': return this.nudge(0, -10, 'nudge up'); case 'arrowdown': return this.nudge(0, 10, 'nudge down'); case 'u' : if (document.activeElement?.tagName !== 'INPUT' && document.activeElement?.tagName !== 'TEXTAREA') { UndoManager.RunInBatch(() => DocumentView.Selected().map(dv => dv.Document).forEach(doc => {doc.group = undefined}), 'unggroup'); DocumentView.DeselectAll(); } break; case 'g': if (document.activeElement?.tagName !== 'INPUT' && document.activeElement?.tagName !== 'TEXTAREA') { const randomGroup = random(0, 1000); UndoManager.RunInBatch(() => DocumentView.Selected().forEach(dv => {dv.Document.group = randomGroup}), 'group'); DocumentView.DeselectAll(); } break; default: } // prettier-ignore return { stopPropagation: false, preventDefault: false, }; }); private alt = action((keyname: string) => { const stopPropagation = true; const preventDefault = true; switch (keyname) { case 'ƒ': case 'f': UndoManager.RunInBatch(() => CollectionFreeFormDocumentView.from(DocumentView.Selected()?.[0])?.float(), 'float'); break; default: } return { stopPropagation: stopPropagation, preventDefault: preventDefault, }; }); private ctrl = action((keyname: string, e: KeyboardEvent) => { let stopPropagation = true; let preventDefault = true; switch (keyname) { case 'arrowright': if (document.activeElement?.tagName === 'INPUT' || document.activeElement?.tagName === 'TEXTAREA') { return { stopPropagation: false, preventDefault: false }; } MainView.Instance.mainFreeform && CollectionDockingView.AddSplit(MainView.Instance.mainFreeform, OpenWhereMod.right); break; case 'arrowleft': if (document.activeElement?.tagName === 'INPUT' || document.activeElement?.tagName === 'TEXTAREA') { return { stopPropagation: false, preventDefault: false }; } MainView.Instance.mainFreeform && CollectionDockingView.CloseSplit(MainView.Instance.mainFreeform); break; case 'backspace': if (document.activeElement?.tagName === 'INPUT' || document.activeElement?.tagName === 'TEXTAREA') { return { stopPropagation: false, preventDefault: false }; } break; case 't': PromiseValue(Cast(Doc.UserDoc()['tabs-button-tools'], Doc)).then(pv => pv && (pv.onClick as ScriptField).script.run({ this: pv })); break; case 'i': { const importBtn = DocListCast(Doc.MyLeftSidebarMenu?.data).find(d => d.target === Doc.MyImports); if (importBtn) { MainView.Instance.selectLeftSidebarButton(importBtn); } } break; case 's': { const trailsBtn = DocListCast(Doc.MyLeftSidebarMenu?.data).find(d => d.target === Doc.MyTrails); if (trailsBtn) { MainView.Instance.selectLeftSidebarButton(trailsBtn); } } break; case 'f': if (DocumentView.Selected().length === 1 && DocumentView.Selected()[0].ComponentView?.search) { DocumentView.Selected()[0].ComponentView?.search?.('', false, false); } else { const searchBtn = DocListCast(Doc.MyLeftSidebarMenu?.data).find(d => d.target === Doc.MySearcher); if (searchBtn) { MainView.Instance.selectLeftSidebarButton(searchBtn); } } break; case 'e': Doc.ActiveTool = Doc.ActiveTool === InkTool.Eraser ? InkTool.None : InkTool.Eraser; break; case 'p': Doc.ActiveTool = Doc.ActiveTool === InkTool.Ink ? InkTool.None : InkTool.Ink; break; case 'r': preventDefault = false; break; case 'y': if (Doc.ActivePage !== 'home') { DocumentView.DeselectAll(); UndoManager.Redo(); } stopPropagation = false; break; case 'z': if (Doc.ActivePage !== 'home') { DocumentView.DeselectAll(); UndoManager.Undo(); } stopPropagation = false; break; case 'a': if (e.target !== document.body) { stopPropagation = false; preventDefault = false; } break; case 'v': stopPropagation = false; preventDefault = false; break; case 'x': if (DocumentView.Selected().length) { const bds = DocumentDecorations.Instance.Bounds; const pt = DocumentView.Selected()[0] // .screenToViewTransform() .transformPoint(bds.x + (bds.r - bds.x) / 2, bds.y + (bds.b - bds.y) / 2); const text = `__DashDocId(${pt?.[0] || 0},${pt?.[1] || 0}):` + // DocumentView.Selected() .map(dv => dv.Document[Id]) .join(':'); // prettier-ignore DocumentView.Selected().length && navigator.clipboard.writeText(text); DocumentDecorations.Instance.onCloseClick(true); stopPropagation = false; preventDefault = false; } break; case 'c': if (!AnchorMenu.Instance.Active && DocumentDecorations.Instance.Bounds.r - DocumentDecorations.Instance.Bounds.x > 2) { const bds = DocumentDecorations.Instance.Bounds; const pt = DocumentView.Selected()[0] .screenToViewTransform() .transformPoint(bds.x + (bds.r - bds.x) / 2, bds.y + (bds.b - bds.y) / 2); // prettier-ignore const text = `__DashCloneId(${pt?.[0] || 0},${pt?.[1] || 0}):` + DocumentView.SelectedDocs() .map(doc => doc[Id]) .join(':'); // prettier-ignore DocumentView.Selected().length && navigator.clipboard.writeText(text); stopPropagation = false; } preventDefault = false; break; default: } return { stopPropagation: stopPropagation, preventDefault: preventDefault, }; }); public paste(e: ClipboardEvent) { const plain = e.clipboardData?.getData('text/plain'); // list of document ids, separated by ':'s if (!plain) return; const clone = plain.startsWith('__DashCloneId('); const docids = plain.split(':'); // hack! docids[0] is the top left of the selection rectangle const addDocument = DocumentView.Selected().lastElement()?.ComponentView?.addDocument; if (addDocument && (plain.startsWith('__DashDocId(') || clone)) { Doc.Paste(docids.slice(1), clone, addDocument); } } getClipboard() { return navigator.clipboard.readText(); } private ctrl_shift = action((keyname: string) => { const stopPropagation = true; const preventDefault = true; switch (keyname) { case 'z': UndoManager.Redo(); break; case 'p': Doc.ActiveInk = InkInkTool.Write; Doc.ActiveTool = InkTool.Ink; break; default: } return { stopPropagation: stopPropagation, preventDefault: preventDefault, }; }); }