From e333cf12975d7494e5578f30b3d4ea88fe42876d Mon Sep 17 00:00:00 2001 From: pan93412 Date: Tue, 8 Nov 2022 16:54:50 +0800 Subject: [PATCH] refactor(pake): Clean up 'keyup' handler * Add preventDefault after pressing to prevent the conflict. * Move the configuration of shortcuts to the head of script, and add the complete instructions. * Make the handler extendable --- src-tauri/src/pake.js | 57 ++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/src-tauri/src/pake.js b/src-tauri/src/pake.js index 69d89a5..89622b4 100644 --- a/src-tauri/src/pake.js +++ b/src-tauri/src/pake.js @@ -1,3 +1,30 @@ +/** + * @typedef {string} KeyboardKey `event.key` 的代号, + * 见 + */ + +/** + * @typedef {() => void} OnKeyDown 使用者按下 ⌘ [KeyboardKey] 时应该执行的行为 + */ + +/** + * 以 Meta 键 (⌘) 为首的快捷键清单。 + * + * 每个写在这里的 shortcuts 都会运行 {@link Event.preventDefault}. + * + * @type {Record} + */ +const metaKeyShortcuts = { + 'ArrowUp': () => scrollTo(0, 0), + 'ArrowDown': () => scrollTo(0, document.body.scrollHeight), + '[': () => window.history.back(), + ']': () => window.history.forward(), + 'r': () => window.location.reload(), + '-': () => zoomOut(), + '=': () => zoomIn(), + '0': () => zoomCommon(() => '100%'), +} + window.addEventListener('DOMContentLoaded', (_event) => { const style = document.createElement('style'); style.innerHTML = ` @@ -99,29 +126,13 @@ window.addEventListener('DOMContentLoaded', (_event) => { }); document.addEventListener('keyup', function (event) { - if (event.key === 'ArrowUp' && event.metaKey) { - scrollTo(0, 0); - } - if (event.key === 'ArrowDown' && event.metaKey) { - window.scrollTo(0, document.body.scrollHeight); - } - if (event.key === '[' && event.metaKey) { - window.history.go(-1); - } - if (event.key === ']' && event.metaKey) { - window.history.go(1); - } - if (event.key === 'r' && event.metaKey) { - window.location.reload(); - } - if (event.key === '-' && event.metaKey) { - zoomOut(); - } - if (event.key === '=' && event.metaKey) { - zoomIn(); - } - if (event.key === '0' && event.metaKey) { - zoomCommon(() => '100%'); + const preventDefault = (f) => { + event.preventDefault(); + f(); + }; + + if (event.metaKey && event.key in metaKeyShortcuts) { + preventDefault(metaKeyShortcuts[event.key]); } });