1// Copyright (C) 2023 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import m from 'mithril'; 16import {checkHotkey, Hotkey} from '../base/hotkeys'; 17import {scheduleFullRedraw} from './raf'; 18 19export interface HotkeyConfig { 20 hotkey: Hotkey; 21 callback: () => void; 22} 23 24export interface HotkeyContextAttrs { 25 hotkeys: HotkeyConfig[]; 26} 27 28export class HotkeyContext implements m.ClassComponent<HotkeyContextAttrs> { 29 private hotkeys?: HotkeyConfig[]; 30 31 view(vnode: m.Vnode<HotkeyContextAttrs>): m.Children { 32 return vnode.children; 33 } 34 35 oncreate(vnode: m.VnodeDOM<HotkeyContextAttrs>) { 36 document.addEventListener('keydown', this.onKeyDown); 37 this.hotkeys = vnode.attrs.hotkeys; 38 } 39 40 onupdate(vnode: m.VnodeDOM<HotkeyContextAttrs>) { 41 this.hotkeys = vnode.attrs.hotkeys; 42 } 43 44 onremove(_vnode: m.VnodeDOM<HotkeyContextAttrs>) { 45 document.removeEventListener('keydown', this.onKeyDown); 46 this.hotkeys = undefined; 47 } 48 49 // Due to a bug in chrome, we get onKeyDown events fired where the payload is 50 // not a KeyboardEvent when selecting an item from an autocomplete suggestion. 51 // See https://issues.chromium.org/issues/41425904 52 // Thus, we can't assume we get an KeyboardEvent and must check manually. 53 private onKeyDown = (e: Event) => { 54 // Find out whether the event has already been handled further up the chain. 55 if (e.defaultPrevented) return; 56 57 if (e instanceof KeyboardEvent) { 58 this.hotkeys?.forEach(({callback, hotkey}) => { 59 if (checkHotkey(hotkey, e)) { 60 e.preventDefault(); 61 callback(); 62 scheduleFullRedraw('force'); 63 } 64 }); 65 } 66 }; 67} 68