From 8699c513b484f3fca80e3cfc96ccf62dda1bb207 Mon Sep 17 00:00:00 2001 From: John Hildenbiddle Date: Mon, 16 Oct 2023 18:53:05 -0500 Subject: [PATCH] Add key binding listener and default config Fix #2278 --- src/core/config.js | 20 ++++++++++++++++++++ src/core/event/index.js | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/core/config.js b/src/core/config.js index 687dfd230..a4c33c7ab 100644 --- a/src/core/config.js +++ b/src/core/config.js @@ -21,6 +21,26 @@ export default function (vm) { formatUpdated: '', ga: '', homepage: 'README.md', + keyBindings: { + // Focus on main content + 'alt+c': e => { + const containerElm = document.querySelector('.markdown-section'); + const focusElm = containerElm.querySelector( + 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])' + ); + + focusElm && focusElm.focus(); + }, + // Toggle sidebar menu + 'alt+t': e => { + const toggleElm = document.querySelector('.sidebar-toggle'); + + if (toggleElm) { + toggleElm.click(); + toggleElm.focus(); + } + }, + }, loadNavbar: null, loadSidebar: null, maxLevel: 6, diff --git a/src/core/event/index.js b/src/core/event/index.js index 516f1fb27..d4527720d 100644 --- a/src/core/event/index.js +++ b/src/core/event/index.js @@ -43,6 +43,29 @@ export function Events(Base) { } else { body.classList.add('sticky'); } + // Bind keyboard shortcuts + on('keydown', e => { + const modifiers = ['alt', 'ctrl', 'meta', 'shift']; + + Object.entries(this.config.keyBindings || {}).forEach( + ([keyBinding, fn]) => { + const keys = keyBinding.split('+').map(k => k.toLowerCase().trim()); + const isMatch = keys.every( + k => + (modifiers.includes(k) && e[k + 'Key']) || + e.key === k || // Ex: " ", "a" + e.code.toLowerCase() === k || // "space" + e.code.toLowerCase() === `key${k}` || // "keya" + e.keyCode === Number(k) // 32 (space), 65 (a) + ); + + if (isMatch) { + e.preventDefault(); + fn(e); + } + } + ); + }); } /** @readonly */