Merge pull request #1183 from hgiesel/keykey

Switch to event.key for keyboard sequences
This commit is contained in:
Damien Elmes 2021-05-24 10:53:24 +10:00 committed by GitHub
commit a361313622
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 134 additions and 117 deletions

View file

@ -3,13 +3,10 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { Modifier } from "lib/shortcuts";
import { onDestroy } from "svelte";
import { registerShortcut, getPlatformString } from "lib/shortcuts";
export let shortcut: string;
export let optionalModifiers: Modifier[] | undefined = [];
const shortcutLabel = getPlatformString(shortcut);
@ -17,14 +14,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
function createShortcut({ detail }: CustomEvent): void {
const mounted: HTMLButtonElement = detail.button;
deregister = registerShortcut(
(event: KeyboardEvent) => {
mounted.dispatchEvent(new MouseEvent("click", event));
event.preventDefault();
},
shortcut,
optionalModifiers
);
deregister = registerShortcut((event: KeyboardEvent) => {
mounted.dispatchEvent(new MouseEvent("click", event));
event.preventDefault();
}, shortcut);
}
onDestroy(() => deregister());

View file

@ -51,5 +51,5 @@ code {
// override the default down arrow colour in <select> elements
.night-mode select {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23FFFFFF' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e")
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23FFFFFF' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
}

View file

@ -41,11 +41,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
}
</script>
<WithShortcut
shortcut="Control+Shift+KeyC"
optionalModifiers={['Alt']}
let:createShortcut
let:shortcutLabel>
<WithShortcut shortcut={'Control+Alt?+Shift+C'} let:createShortcut let:shortcutLabel>
<IconButton
tooltip={`${tr.editingClozeDeletion()} (${shortcutLabel})`}
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}>
<ButtonGroupItem>
<WithShortcut shortcut="F7" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'F7'} let:createShortcut let:shortcutLabel>
<IconButton
class="forecolor"
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>
<WithShortcut shortcut="F8" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'F8'} let:createShortcut let:shortcutLabel>
<ColorPicker
tooltip={appendInParentheses(tr.editingChangeColor(), shortcutLabel)}
on:change={setWithCurrentColor}

View file

@ -26,7 +26,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<ButtonGroup {api}>
<ButtonGroupItem>
<WithShortcut shortcut="Control+KeyB" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'Control+B'} let:createShortcut let:shortcutLabel>
<WithState
key="bold"
update={() => document.queryCommandState('bold')}
@ -47,7 +47,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem>
<ButtonGroupItem>
<WithShortcut shortcut="Control+KeyI" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'Control+I'} let:createShortcut let:shortcutLabel>
<WithState
key="italic"
update={() => document.queryCommandState('italic')}
@ -68,7 +68,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem>
<ButtonGroupItem>
<WithShortcut shortcut="Control+KeyU" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'Control+U'} let:createShortcut let:shortcutLabel>
<WithState
key="underline"
update={() => document.queryCommandState('underline')}
@ -89,10 +89,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem>
<ButtonGroupItem>
<WithShortcut
shortcut="Control+Shift+Equal"
let:createShortcut
let:shortcutLabel>
<WithShortcut shortcut={'Control+='} let:createShortcut let:shortcutLabel>
<WithState
key="superscript"
update={() => document.queryCommandState('superscript')}
@ -113,7 +110,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem>
<ButtonGroupItem>
<WithShortcut shortcut="Control+Equal" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'Control+Shift+='} let:createShortcut let:shortcutLabel>
<WithState
key="subscript"
update={() => document.queryCommandState('subscript')}
@ -134,7 +131,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</ButtonGroupItem>
<ButtonGroupItem>
<WithShortcut shortcut="Control+KeyR" let:createShortcut let:shortcutLabel>
<WithShortcut shortcut={'Control+R'} let:createShortcut let:shortcutLabel>
<IconButton
tooltip={appendInParentheses(tr.editingRemoveFormatting(), shortcutLabel)}
on:click={() => {

View file

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

View file

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

View file

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

View file

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

View file

@ -4,8 +4,6 @@ import * as tr from "./i18n";
export type Modifier = "Control" | "Alt" | "Shift" | "Meta";
const modifiers: Modifier[] = ["Control", "Alt", "Shift", "Meta"];
function isApplePlatform(): boolean {
return (
window.navigator.platform.startsWith("Mac") ||
@ -18,10 +16,6 @@ const platformModifiers = isApplePlatform()
? ["Meta", "Alt", "Shift", "Control"]
: ["Control", "Alt", "Shift", "OS"];
function splitKeyCombinationString(keyCombinationString: string): string[][] {
return keyCombinationString.split(", ").map((segment) => segment.split("+"));
}
function modifiersToPlatformString(modifiers: string[]): string {
const displayModifiers = isApplePlatform()
? ["^", "⌥", "⇧", "⌘"]
@ -36,38 +30,50 @@ function modifiersToPlatformString(modifiers: string[]): string {
return result;
}
const alphabeticPrefix = "Key";
const numericPrefix = "Digit";
const keyToCharacterMap = {
Backslash: "\\",
Backquote: "`",
BracketLeft: "[",
BrackerRight: "]",
Quote: "'",
Semicolon: ";",
Minus: "-",
Equal: "=",
Comma: ",",
Period: ".",
Slash: "/",
const keyCodeLookup = {
Backspace: 8,
Delete: 46,
Tab: 9,
Enter: 13,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
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 isRequiredModifier(modifier: string): boolean {
return !modifier.endsWith("?");
}
function toPlatformString(modifiersAndKey: string[]): string {
return `${modifiersToPlatformString(
modifiersAndKey.slice(0, -1)
)}${keyToPlatformString(modifiersAndKey[modifiersAndKey.length - 1])}`;
function splitKeyCombinationString(keyCombinationString: string): string[][] {
return keyCombinationString.split(", ").map((segment) => segment.split("+"));
}
function toPlatformString(keyCombination: string[]): string {
return (
modifiersToPlatformString(
keyCombination.slice(0, -1).filter(isRequiredModifier)
) + keyCombination[keyCombination.length - 1]
);
}
export function getPlatformString(keyCombinationString: string): string {
@ -76,78 +82,107 @@ export function getPlatformString(keyCombinationString: string): string {
.join(", ");
}
function checkKey(event: KeyboardEvent, key: string): boolean {
return event.code === key;
function checkKey(event: KeyboardEvent, key: number): boolean {
return event.which === key;
}
function checkModifiers(
event: KeyboardEvent,
optionalModifiers: Modifier[],
activeModifiers: string[]
): boolean {
return modifiers.reduce(
(matches: boolean, modifier: string, currentIndex: number): boolean =>
const allModifiers: Modifier[] = ["Control", "Alt", "Shift", "Meta"];
function partition<T>(predicate: (t: T) => boolean, items: T[]): [T[], T[]] {
const trueItems: T[] = [];
const falseItems: T[] = [];
items.forEach((t) => {
const target = predicate(t) ? trueItems : falseItems;
target.push(t);
});
return [trueItems, falseItems];
}
function removeTrailing(modifier: string): string {
return modifier.substring(0, modifier.length - 1);
}
function checkModifiers(event: KeyboardEvent, modifiers: string[]): boolean {
const [requiredModifiers, otherModifiers] = partition(
isRequiredModifier,
modifiers
);
const optionalModifiers = otherModifiers.map(removeTrailing);
return allModifiers.reduce(
(matches: boolean, currentModifier: string, currentIndex: number): boolean =>
matches &&
(optionalModifiers.includes(modifier as Modifier) ||
(optionalModifiers.includes(currentModifier as Modifier) ||
event.getModifierState(platformModifiers[currentIndex]) ===
activeModifiers.includes(modifier)),
requiredModifiers.includes(currentModifier)),
true
);
}
function check(
event: KeyboardEvent,
optionalModifiers: Modifier[],
modifiersAndKey: string[]
): boolean {
return (
checkKey(event, modifiersAndKey[modifiersAndKey.length - 1]) &&
checkModifiers(event, optionalModifiers, modifiersAndKey.slice(0, -1))
);
const check = (keyCode: number, modifiers: string[]) => (
event: KeyboardEvent
): boolean => {
return checkKey(event, keyCode) && checkModifiers(event, modifiers);
};
function keyToCode(key: string): number {
return keyCodeLookup[key] || key.toUpperCase().charCodeAt(0);
}
const shortcutTimeoutMs = 400;
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 NUMPAD_KEY = 3;
function innerShortcut(
lastEvent: KeyboardEvent,
callback: (event: KeyboardEvent) => void,
optionalModifiers: Modifier[],
...keyCombination: string[][]
...checks: ((event: KeyboardEvent) => boolean)[]
): void {
let interval: number;
if (keyCombination.length === 0) {
if (checks.length === 0) {
callback(lastEvent);
} else {
const [nextKey, ...restKeys] = keyCombination;
const [nextCheck, ...restChecks] = checks;
const handler = (event: KeyboardEvent): void => {
if (check(event, optionalModifiers, nextKey)) {
innerShortcut(event, callback, optionalModifiers, ...restKeys);
if (nextCheck(event)) {
innerShortcut(event, callback, ...restChecks);
clearTimeout(interval);
} else if (
event.location === GENERAL_KEY ||
event.location === NUMPAD_KEY
) {
// Any non-modifier key will cancel the shortcut sequence
document.removeEventListener("keydown", handler);
}
};
interval = setTimeout(
(): void => document.removeEventListener("keydown", handler),
shortcutTimeoutMs
);
document.addEventListener("keydown", handler, { once: true });
}
}
export function registerShortcut(
callback: (event: KeyboardEvent) => void,
keyCombinationString: string,
optionalModifiers: Modifier[] = []
keyCombinationString: string
): () => void {
const keyCombination = splitKeyCombinationString(keyCombinationString);
const [firstKey, ...restKeys] = keyCombination;
const [check, ...restChecks] = splitKeyCombinationString(keyCombinationString).map(
keyCombinationToCheck
);
const handler = (event: KeyboardEvent): void => {
if (check(event, optionalModifiers, firstKey)) {
innerShortcut(event, callback, optionalModifiers, ...restKeys);
if (check(event)) {
innerShortcut(event, callback, ...restChecks);
}
};