Files
ep-mail-client/shortcuts.js
T

118 lines
6.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
// Configurable keyboard shortcuts for common mail actions.
const shortcutMailUi = window.epMailFeatures.mail;
const shortcutProductivityUi = window.epMailFeatures.productivity;
const selectShortcutUi = shortcutMailUi.select;
const toastShortcutUi = shortcutMailUi.toast;
const escapeShortcutUi = shortcutMailUi.escapeHtml;
const shortcutStorageKey = 'daybreak-shortcuts';
const shortcutActions = [
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
{ id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
{ id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#forward')?.click() },
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
];
function normalizeShortcut(value) {
const text = String(value || '').trim();
if (!text) return '';
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
const key = parts.pop() || '+';
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
}
function loadShortcuts() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
return Object.fromEntries(shortcutActions.map(action => [
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
]));
}
function eventShortcut(event) {
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
const printable = event.key.length === 1;
if (event.shiftKey && !printable) mods.push('Shift');
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
}
function moveMessageSelection(step) {
const messages = shortcutMailUi.state.messages;
if (!messages.length) return;
const index = messages.findIndex(message => message.id === shortcutMailUi.state.activeMessage);
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
if (next) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
}
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || selectShortcutUi('#modal-root')?.children.length) return;
const pressed = eventShortcut(event);
if (!pressed) return;
const shortcuts = loadShortcuts();
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
if (!action) return;
event.preventDefault();
action.run();
});
function openShortcutSettings() {
const root = selectShortcutUi('#modal-root');
const shortcuts = loadShortcuts();
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Keyboard shortcuts</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-shortcuts">Save shortcuts</button></div></div></div>`;
const close = () => { root.innerHTML = ''; };
root.querySelectorAll('.modal-close').forEach(button => { button.onclick = close; });
selectShortcutUi('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const fields = selectShortcutUi('#modal-root .compose-fields');
fields.addEventListener('keydown', event => {
const input = event.target.closest('.shortcut-input');
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
event.preventDefault();
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
const combo = eventShortcut(event);
if (combo) input.value = combo;
});
selectShortcutUi('#reset-shortcuts').onclick = () => {
fields.querySelectorAll('.shortcut-input').forEach(input => {
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
});
};
selectShortcutUi('#save-shortcuts').onclick = () => {
const values = {};
const used = new Map();
for (const input of fields.querySelectorAll('.shortcut-input')) {
const value = normalizeShortcut(input.value);
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
if (value) used.set(value, label);
values[input.dataset.action] = value;
}
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
close();
toastShortcutUi('Keyboard shortcuts saved');
};
}
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => async function () {
await baseOpenPreferences();
const fields = selectShortcutUi('#modal-root .compose-fields');
if (!fields || !selectShortcutUi('#save-appearance')) return;
const button = document.createElement('button');
button.type = 'button';
button.className = 'discard';
button.id = 'open-keyboard-shortcuts';
button.textContent = 'Keyboard shortcuts…';
button.onclick = openShortcutSettings;
fields.append(button);
});})();