68 lines
2.3 KiB
JavaScript
68 lines
2.3 KiB
JavaScript
|
export class ShortcutManager {
|
||
|
constructor() {
|
||
|
this.shortcuts = JSON.parse(localStorage.getItem('shortcuts')) || {
|
||
|
focusSearch: 's',
|
||
|
openSettings: ',',
|
||
|
switchLayout: 'l'
|
||
|
};
|
||
|
this.init();
|
||
|
}
|
||
|
|
||
|
init() {
|
||
|
this.renderShortcuts();
|
||
|
this.attachGlobalListeners();
|
||
|
}
|
||
|
|
||
|
renderShortcuts() {
|
||
|
const container = document.getElementById('shortcuts-editor');
|
||
|
if (!container) return;
|
||
|
|
||
|
container.innerHTML = Object.entries(this.shortcuts)
|
||
|
.map(([action, key]) => `
|
||
|
<div class="shortcut-item">
|
||
|
<span>${this.formatActionName(action)}</span>
|
||
|
<input type="text" value="${key}" maxlength="1"
|
||
|
onkeydown="event.preventDefault()"
|
||
|
onkeyup="shortcutManager.updateShortcut('${action}', event.key)">
|
||
|
</div>
|
||
|
`).join('');
|
||
|
}
|
||
|
|
||
|
formatActionName(action) {
|
||
|
return action
|
||
|
.replace(/([A-Z])/g, ' $1')
|
||
|
.replace(/^./, str => str.toUpperCase());
|
||
|
}
|
||
|
|
||
|
attachGlobalListeners() {
|
||
|
document.addEventListener('keydown', (e) => {
|
||
|
// Ignore if target is an input or textarea
|
||
|
if (e.target.matches('input, textarea')) return;
|
||
|
|
||
|
if (e.key === this.shortcuts.focusSearch) {
|
||
|
e.preventDefault();
|
||
|
document.getElementById('search-input').focus();
|
||
|
} else if (e.key === this.shortcuts.openSettings) {
|
||
|
e.preventDefault();
|
||
|
document.querySelector('.settings-button').click();
|
||
|
} else if (e.key === this.shortcuts.switchLayout) {
|
||
|
e.preventDefault();
|
||
|
const layoutSelect = document.getElementById('layoutSelect');
|
||
|
layoutSelect.value = layoutSelect.value === 'grid' ? 'list' : 'grid';
|
||
|
layoutSelect.dispatchEvent(new Event('change'));
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
updateShortcut(action, key) {
|
||
|
if (key && key !== 'Escape' && key !== 'Tab') {
|
||
|
this.shortcuts[action] = key.toLowerCase();
|
||
|
this.save();
|
||
|
this.renderShortcuts();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
save() {
|
||
|
localStorage.setItem('shortcuts', JSON.stringify(this.shortcuts));
|
||
|
}
|
||
|
}
|