Skip to content

Commit 8699c51

Browse files
committed
Add key binding listener and default config
Fix #2278
1 parent 510da11 commit 8699c51

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/core/config.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,26 @@ export default function (vm) {
2121
formatUpdated: '',
2222
ga: '',
2323
homepage: 'README.md',
24+
keyBindings: {
25+
// Focus on main content
26+
'alt+c': e => {
27+
const containerElm = document.querySelector('.markdown-section');
28+
const focusElm = containerElm.querySelector(
29+
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
30+
);
31+
32+
focusElm && focusElm.focus();
33+
},
34+
// Toggle sidebar menu
35+
'alt+t': e => {
36+
const toggleElm = document.querySelector('.sidebar-toggle');
37+
38+
if (toggleElm) {
39+
toggleElm.click();
40+
toggleElm.focus();
41+
}
42+
},
43+
},
2444
loadNavbar: null,
2545
loadSidebar: null,
2646
maxLevel: 6,

src/core/event/index.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,29 @@ export function Events(Base) {
4343
} else {
4444
body.classList.add('sticky');
4545
}
46+
// Bind keyboard shortcuts
47+
on('keydown', e => {
48+
const modifiers = ['alt', 'ctrl', 'meta', 'shift'];
49+
50+
Object.entries(this.config.keyBindings || {}).forEach(
51+
([keyBinding, fn]) => {
52+
const keys = keyBinding.split('+').map(k => k.toLowerCase().trim());
53+
const isMatch = keys.every(
54+
k =>
55+
(modifiers.includes(k) && e[k + 'Key']) ||
56+
e.key === k || // Ex: " ", "a"
57+
e.code.toLowerCase() === k || // "space"
58+
e.code.toLowerCase() === `key${k}` || // "keya"
59+
e.keyCode === Number(k) // 32 (space), 65 (a)
60+
);
61+
62+
if (isMatch) {
63+
e.preventDefault();
64+
fn(e);
65+
}
66+
}
67+
);
68+
});
4669
}
4770

4871
/** @readonly */

0 commit comments

Comments
 (0)