Skip to content

Commit

Permalink
Add key binding listener and default config
Browse files Browse the repository at this point in the history
Fix #2278
  • Loading branch information
jhildenbiddle committed Oct 16, 2023
1 parent 510da11 commit 8699c51
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/core/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
23 changes: 23 additions & 0 deletions src/core/event/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down

0 comments on commit 8699c51

Please sign in to comment.