Prefer event.which over event.{key,code}

It works better with alternative Latin-based keyboard layouts
This commit is contained in:
Henrik Giesel 2021-05-22 17:50:23 +02:00
parent c89c42dc37
commit 3a18dce03f
10 changed files with 96 additions and 140 deletions

View File

@ -6,8 +6,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { onDestroy } from "svelte"; import { onDestroy } from "svelte";
import { registerShortcut, getPlatformString } from "lib/shortcuts"; import { registerShortcut, getPlatformString } from "lib/shortcuts";
export let shortcut: string[][]; export let shortcut: string;
export let useCode = false;
const shortcutLabel = getPlatformString(shortcut); const shortcutLabel = getPlatformString(shortcut);
@ -15,14 +14,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
function createShortcut({ detail }: CustomEvent): void { function createShortcut({ detail }: CustomEvent): void {
const mounted: HTMLButtonElement = detail.button; const mounted: HTMLButtonElement = detail.button;
deregister = registerShortcut( deregister = registerShortcut((event: KeyboardEvent) => {
(event: KeyboardEvent) => { mounted.dispatchEvent(new MouseEvent("click", event));
mounted.dispatchEvent(new MouseEvent("click", event)); event.preventDefault();
event.preventDefault(); }, shortcut);
},
shortcut,
useCode
);
} }
onDestroy(() => deregister()); onDestroy(() => deregister());

View File

@ -36,11 +36,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
let registerCleanup: () => void; let registerCleanup: () => void;
onMount(() => { onMount(() => {
registerCleanup = registerShortcut( registerCleanup = registerShortcut(() => state.save(false), "Control+Enter");
() => state.save(false),
[["Control", "Enter"]],
true
);
}); });
onDestroy(() => registerCleanup?.()); onDestroy(() => registerCleanup?.());
</script> </script>

View File

@ -41,10 +41,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
} }
</script> </script>
<WithShortcut <WithShortcut shortcut={'Control+Alt?+Shift+C'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'Alt?', 'Shift', 'C']]}
let:createShortcut
let:shortcutLabel>
<IconButton <IconButton
tooltip={`${tr.editingClozeDeletion()} (${shortcutLabel})`} tooltip={`${tr.editingClozeDeletion()} (${shortcutLabel})`}
on:click={onCloze} on:click={onCloze}

View File

@ -36,7 +36,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<ButtonGroup {api}> <ButtonGroup {api}>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut shortcut={[['F7']]} let:createShortcut let:shortcutLabel> <WithShortcut shortcut={'F7'} let:createShortcut let:shortcutLabel>
<IconButton <IconButton
class="forecolor" class="forecolor"
tooltip={appendInParentheses(tr.editingSetForegroundColor(), shortcutLabel)} tooltip={appendInParentheses(tr.editingSetForegroundColor(), shortcutLabel)}
@ -48,7 +48,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut shortcut={[['F8']]} let:createShortcut let:shortcutLabel> <WithShortcut shortcut={'F8'} let:createShortcut let:shortcutLabel>
<ColorPicker <ColorPicker
tooltip={appendInParentheses(tr.editingChangeColor(), shortcutLabel)} tooltip={appendInParentheses(tr.editingChangeColor(), shortcutLabel)}
on:change={setWithCurrentColor} on:change={setWithCurrentColor}

View File

@ -26,10 +26,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<ButtonGroup {api}> <ButtonGroup {api}>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+B'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'b']]}
let:createShortcut
let:shortcutLabel>
<WithState <WithState
key="bold" key="bold"
update={() => document.queryCommandState('bold')} update={() => document.queryCommandState('bold')}
@ -50,10 +47,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+I'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'i']]}
let:createShortcut
let:shortcutLabel>
<WithState <WithState
key="italic" key="italic"
update={() => document.queryCommandState('italic')} update={() => document.queryCommandState('italic')}
@ -74,10 +68,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+U'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'u']]}
let:createShortcut
let:shortcutLabel>
<WithState <WithState
key="underline" key="underline"
update={() => document.queryCommandState('underline')} update={() => document.queryCommandState('underline')}
@ -98,11 +89,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+='} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'Equal']]}
useCode={true}
let:createShortcut
let:shortcutLabel>
<WithState <WithState
key="superscript" key="superscript"
update={() => document.queryCommandState('superscript')} update={() => document.queryCommandState('superscript')}
@ -123,11 +110,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+Shift+='} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'Shift', 'Equal']]}
useCode={true}
let:createShortcut
let:shortcutLabel>
<WithState <WithState
key="subscript" key="subscript"
update={() => document.queryCommandState('subscript')} update={() => document.queryCommandState('subscript')}
@ -148,10 +131,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+R'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'r']]}
let:createShortcut
let:shortcutLabel>
<IconButton <IconButton
tooltip={appendInParentheses(tr.editingRemoveFormatting(), shortcutLabel)} tooltip={appendInParentheses(tr.editingRemoveFormatting(), shortcutLabel)}
on:click={() => { on:click={() => {

View File

@ -25,10 +25,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+L'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'l']]}
let:createShortcut
let:shortcutLabel>
<LabelButton <LabelButton
disables={false} disables={false}
tooltip={`${tr.editingCustomizeCardTemplates()} (${shortcutLabel})`} tooltip={`${tr.editingCustomizeCardTemplates()} (${shortcutLabel})`}

View File

@ -10,10 +10,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import LabelButton from "components/LabelButton.svelte"; import LabelButton from "components/LabelButton.svelte";
</script> </script>
<WithShortcut <WithShortcut shortcut={'Control+Shift+P'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'Shift', 'P']]}
let:createShortcut
let:shortcutLabel>
<LabelButton <LabelButton
tooltip={tr.browsingPreviewSelectedCard({ val: shortcutLabel })} tooltip={tr.browsingPreviewSelectedCard({ val: shortcutLabel })}
disables={false} disables={false}

View File

@ -36,7 +36,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<ButtonGroup {api}> <ButtonGroup {api}>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut shortcut={[['F3']]} let:createShortcut let:shortcutLabel> <WithShortcut shortcut={'F3'} let:createShortcut let:shortcutLabel>
<IconButton <IconButton
tooltip={appendInParentheses(tr.editingAttachPicturesaudiovideo(), shortcutLabel)} tooltip={appendInParentheses(tr.editingAttachPicturesaudiovideo(), shortcutLabel)}
on:click={onAttachment} on:click={onAttachment}
@ -47,7 +47,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut shortcut={[['F5']]} let:createShortcut let:shortcutLabel> <WithShortcut shortcut={'F5'} let:createShortcut let:shortcutLabel>
<IconButton <IconButton
tooltip={appendInParentheses(tr.editingRecordAudio(), shortcutLabel)} tooltip={appendInParentheses(tr.editingRecordAudio(), shortcutLabel)}
on:click={onRecord} on:click={onRecord}
@ -69,7 +69,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<DropdownMenu id={menuId}> <DropdownMenu id={menuId}>
<WithShortcut <WithShortcut
shortcut={[['Control', 'm'], ['m']]} shortcut={'Control+M, M'}
let:createShortcut let:createShortcut
let:shortcutLabel> let:shortcutLabel>
<DropdownItem <DropdownItem
@ -81,7 +81,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</WithShortcut> </WithShortcut>
<WithShortcut <WithShortcut
shortcut={[['Control', 'm'], ['e']]} shortcut={'Control+M, E'}
let:createShortcut let:createShortcut
let:shortcutLabel> let:shortcutLabel>
<DropdownItem <DropdownItem
@ -93,7 +93,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</WithShortcut> </WithShortcut>
<WithShortcut <WithShortcut
shortcut={[['Control', 'm'], ['c']]} shortcut={'Control+M, C'}
let:createShortcut let:createShortcut
let:shortcutLabel> let:shortcutLabel>
<DropdownItem <DropdownItem
@ -105,7 +105,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</WithShortcut> </WithShortcut>
<WithShortcut <WithShortcut
shortcut={[['Control', 't'], ['t']]} shortcut={'Control+T, T'}
let:createShortcut let:createShortcut
let:shortcutLabel> let:shortcutLabel>
<DropdownItem <DropdownItem
@ -117,7 +117,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</WithShortcut> </WithShortcut>
<WithShortcut <WithShortcut
shortcut={[['Control', 't'], ['e']]} shortcut={'Control+T, E'}
let:createShortcut let:createShortcut
let:shortcutLabel> let:shortcutLabel>
<DropdownItem <DropdownItem
@ -129,7 +129,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</WithShortcut> </WithShortcut>
<WithShortcut <WithShortcut
shortcut={[['Control', 't'], ['m']]} shortcut={'Control+T, M'}
let:createShortcut let:createShortcut
let:shortcutLabel> let:shortcutLabel>
<DropdownItem <DropdownItem
@ -144,10 +144,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<WithShortcut <WithShortcut shortcut={'Control+Shift+X'} let:createShortcut let:shortcutLabel>
shortcut={[['Control', 'Shift', 'X']]}
let:createShortcut
let:shortcutLabel>
<IconButton <IconButton
tooltip={appendInParentheses(tr.editingHtmlEditor(), shortcutLabel)} tooltip={appendInParentheses(tr.editingHtmlEditor(), shortcutLabel)}
on:click={onHtmlEdit} on:click={onHtmlEdit}

View File

@ -66,8 +66,7 @@ function updateFocus(evt: FocusEvent) {
registerShortcut( registerShortcut(
() => document.addEventListener("focusin", updateFocus, { once: true }), () => document.addEventListener("focusin", updateFocus, { once: true }),
[["Shift?", "Tab"]], "Shift?+Tab"
true
); );
export function onKeyUp(evt: KeyboardEvent): void { export function onKeyUp(evt: KeyboardEvent): void {

View File

@ -30,60 +30,60 @@ function modifiersToPlatformString(modifiers: string[]): string {
return result; return result;
} }
const alphabeticPrefix = "Key"; const keyCodeLookup = {
const numericPrefix = "Digit"; Backspace: 8,
const keyToCharacterMap = { Delete: 46,
Backslash: "\\", Tab: 9,
Backquote: "`", Enter: 13,
BracketLeft: "[", F1: 112,
BrackerRight: "]", F2: 113,
Quote: "'", F3: 114,
Semicolon: ";", F4: 115,
Minus: "-", F5: 116,
Equal: "=", F6: 117,
Comma: ",", F7: 118,
Period: ".", F8: 119,
Slash: "/", F9: 120,
F10: 121,
F11: 122,
F12: 123,
"=": 187,
"-": 189,
"[": 219,
"]": 221,
"\\": 220,
";": 186,
"'": 222,
",": 188,
".": 190,
"/": 191,
"`": 192,
}; };
function keyToPlatformString(key: string): string {
if (key.startsWith(alphabeticPrefix)) {
return key.slice(alphabeticPrefix.length);
} else if (key.startsWith(numericPrefix)) {
return key.slice(numericPrefix.length);
} else if (Object.prototype.hasOwnProperty.call(keyToCharacterMap, key)) {
return keyToCharacterMap[key];
} else {
return key;
}
}
function capitalize(key: string): string {
return key[0].toLocaleUpperCase() + key.slice(1);
}
function isRequiredModifier(modifier: string): boolean { function isRequiredModifier(modifier: string): boolean {
return !modifier.endsWith("?"); return !modifier.endsWith("?");
} }
function toPlatformString(modifiersAndKey: string[]): string { function splitKeyCombinationString(keyCombinationString: string): string[][] {
return keyCombinationString.split(", ").map((segment) => segment.split("+"));
}
function toPlatformString(keyCombination: string[]): string {
return ( return (
modifiersToPlatformString( modifiersToPlatformString(
modifiersAndKey.slice(0, -1).filter(isRequiredModifier) keyCombination.slice(0, -1).filter(isRequiredModifier)
) + capitalize(keyToPlatformString(modifiersAndKey[modifiersAndKey.length - 1])) ) + keyCombination[keyCombination.length - 1]
); );
} }
export function getPlatformString(keyCombination: string[][]): string { export function getPlatformString(keyCombinationString: string): string {
return keyCombination.map(toPlatformString).join(", "); return splitKeyCombinationString(keyCombinationString)
.map(toPlatformString)
.join(", ");
} }
function checkKey( function checkKey(event: KeyboardEvent, key: number): boolean {
getProperty: (event: KeyboardEvent) => string, return event.which === key;
event: KeyboardEvent,
key: string
): boolean {
return getProperty(event) === key;
} }
const allModifiers: Modifier[] = ["Control", "Alt", "Shift", "Meta"]; const allModifiers: Modifier[] = ["Control", "Alt", "Shift", "Meta"];
@ -122,15 +122,23 @@ function checkModifiers(event: KeyboardEvent, modifiers: string[]): boolean {
); );
} }
function check( const check = (keyCode: number, modifiers: string[]) => (
getProperty: (event: KeyboardEvent) => string, event: KeyboardEvent
event: KeyboardEvent, ): boolean => {
modifiersAndKey: string[] return checkKey(event, keyCode) && checkModifiers(event, modifiers);
): boolean { };
return (
checkModifiers(event, modifiersAndKey.slice(0, -1)) && function keyToCode(key: string): number {
checkKey(getProperty, event, modifiersAndKey[modifiersAndKey.length - 1]) return keyCodeLookup[key] || key.toUpperCase().charCodeAt(0);
); }
function keyCombinationToCheck(
keyCombination: string[]
): (event: KeyboardEvent) => boolean {
const keyCode = keyToCode(keyCombination[keyCombination.length - 1]);
const modifiers = keyCombination.slice(0, -1);
return check(keyCode, modifiers);
} }
const GENERAL_KEY = 0; const GENERAL_KEY = 0;
@ -139,19 +147,17 @@ const NUMPAD_KEY = 3;
function innerShortcut( function innerShortcut(
lastEvent: KeyboardEvent, lastEvent: KeyboardEvent,
callback: (event: KeyboardEvent) => void, callback: (event: KeyboardEvent) => void,
getProperty: (event: KeyboardEvent) => string, ...checks: ((event: KeyboardEvent) => boolean)[]
...keyCombination: string[][]
): void { ): void {
let interval: number; let interval: number;
if (keyCombination.length === 0) { if (checks.length === 0) {
callback(lastEvent); callback(lastEvent);
} else { } else {
const [nextKey, ...restKeys] = keyCombination; const [nextCheck, ...restChecks] = checks;
const handler = (event: KeyboardEvent): void => { const handler = (event: KeyboardEvent): void => {
if (check(getProperty, event, nextKey)) { if (nextCheck(event)) {
innerShortcut(event, callback, getProperty, ...restKeys); innerShortcut(event, callback, ...restChecks);
clearTimeout(interval); clearTimeout(interval);
} else if ( } else if (
event.location === GENERAL_KEY || event.location === GENERAL_KEY ||
@ -166,25 +172,17 @@ function innerShortcut(
} }
} }
function byKey(event: KeyboardEvent): string {
return event.key;
}
function byCode(event: KeyboardEvent): string {
return event.code;
}
export function registerShortcut( export function registerShortcut(
callback: (event: KeyboardEvent) => void, callback: (event: KeyboardEvent) => void,
keyCombination: string[][], keyCombinationString: string
useCode = false
): () => void { ): () => void {
const [firstKey, ...restKeys] = keyCombination; const [check, ...restChecks] = splitKeyCombinationString(keyCombinationString).map(
const getProperty = useCode ? byCode : byKey; keyCombinationToCheck
);
const handler = (event: KeyboardEvent): void => { const handler = (event: KeyboardEvent): void => {
if (check(getProperty, event, firstKey)) { if (check(event)) {
innerShortcut(event, callback, getProperty, ...restKeys); innerShortcut(event, callback, ...restChecks);
} }
}; };