1
0
mirror of https://github.com/immich-app/immich.git synced 2024-12-25 10:43:13 +02:00

fix(web): keyboard shortcut handling (#7946)

* fix(web): keyboard shortcut handling

* drop executeShortcuts in favor of action

* fix merge

---------

Co-authored-by: Jason Rasmussen <jrasm91@gmail.com>
This commit is contained in:
Michel Heusschen 2024-03-15 00:16:55 +01:00 committed by GitHub
parent 12fb90c232
commit eed8e6b67a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 197 additions and 268 deletions

View File

@ -2,6 +2,7 @@
import { autoGrowHeight } from '$lib/utils/autogrow';
import { updateAlbumInfo } from '@immich/sdk';
import { handleError } from '$lib/utils/handle-error';
import { shortcut } from '$lib/utils/shortcut';
export let id: string;
export let description: string;
@ -37,6 +38,10 @@
on:focusout={handleUpdateDescription}
use:autoGrowHeight
placeholder="Add description"
use:shortcut={{
shortcut: { key: 'Enter', ctrl: true },
onShortcut: (e) => e.currentTarget.blur(),
}}
/>
{:else if description}
<p class="break-words whitespace-pre-line w-full text-black dark:text-white text-base">

View File

@ -1,6 +1,7 @@
<script lang="ts">
import { updateAlbumInfo } from '@immich/sdk';
import { handleError } from '$lib/utils/handle-error';
import { shortcut } from '$lib/utils/shortcut';
export let id: string;
export let albumName: string;
@ -29,7 +30,7 @@
</script>
<input
on:keydown={(e) => e.key === 'Enter' && e.currentTarget.blur()}
use:shortcut={{ shortcut: { key: 'Enter' }, onShortcut: (e) => e.currentTarget.blur() }}
on:blur={handleUpdateName}
class="w-[99%] mb-2 border-b-2 border-transparent text-6xl text-immich-primary outline-none transition-all dark:text-immich-dark-primary {isOwned
? 'hover:border-gray-400'

View File

@ -1,11 +1,9 @@
<script lang="ts">
import { browser } from '$app/environment';
import SelectAllAssets from '$lib/components/photos-page/actions/select-all-assets.svelte';
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
import { dragAndDropFilesStore } from '$lib/stores/drag-and-drop-files.store';
import { fileUploadHandler, openFileUploadDialog } from '$lib/utils/file-uploader';
import type { AlbumResponseDto, SharedLinkResponseDto, UserResponseDto } from '@immich/sdk';
import { onDestroy, onMount } from 'svelte';
import { createAssetInteractionStore } from '../../stores/asset-interaction.store';
import { AssetStore } from '../../stores/assets.store';
import { downloadArchive } from '../../utils/asset-utils';
@ -16,7 +14,7 @@
import ControlAppBar from '../shared-components/control-app-bar.svelte';
import ImmichLogo from '../shared-components/immich-logo.svelte';
import ThemeButton from '../shared-components/theme-button.svelte';
import { shouldIgnoreShortcut } from '$lib/utils/shortcut';
import { shortcut } from '$lib/utils/shortcut';
import { mdiFileImagePlusOutline, mdiFolderDownloadOutline } from '@mdi/js';
import { handlePromiseError } from '$lib/utils';
import AlbumSummary from './album-summary.svelte';
@ -39,39 +37,22 @@
}
});
const onKeyboardPress = (event: KeyboardEvent) => handleKeyboardPress(event);
onMount(() => {
document.addEventListener('keydown', onKeyboardPress);
});
onDestroy(() => {
if (browser) {
document.removeEventListener('keydown', onKeyboardPress);
}
});
const handleKeyboardPress = (event: KeyboardEvent) => {
if (shouldIgnoreShortcut(event)) {
return;
}
if (!$showAssetViewer) {
switch (event.key) {
case 'Escape': {
if ($isMultiSelectState) {
assetInteractionStore.clearMultiselect();
}
return;
}
}
}
};
const downloadAlbum = async () => {
await downloadArchive(`${album.albumName}.zip`, { albumId: album.id });
};
</script>
<svelte:window
use:shortcut={{
shortcut: { key: 'Escape' },
onShortcut: () => {
if (!$showAssetViewer && $isMultiSelectState) {
assetInteractionStore.clearMultiselect();
}
},
}}
/>
<header>
{#if $isMultiSelectState}
<AssetSelectControlBar

View File

@ -25,6 +25,7 @@
import { NotificationType, notificationController } from '../shared-components/notification/notification';
import UserAvatar from '../shared-components/user-avatar.svelte';
import { locale } from '$lib/stores/preferences.store';
import { shortcut } from '$lib/utils/shortcut';
const units: Intl.RelativeTimeFormatUnit[] = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second'];
@ -95,14 +96,6 @@
}
};
const handleEnter = async (event: KeyboardEvent) => {
if (event.key === 'Enter') {
event.preventDefault();
await handleSendComment();
return;
}
};
const timeOptions = {
year: 'numeric',
month: '2-digit',
@ -295,7 +288,10 @@
use:autoGrowHeight={'5px'}
placeholder={disabled ? 'Comments are disabled' : 'Say something'}
on:input={() => autoGrowHeight(textArea, '5px')}
on:keypress={handleEnter}
use:shortcut={{
shortcut: { key: 'Enter' },
onShortcut: () => handleSendComment(),
}}
class="h-[18px] {disabled
? 'cursor-not-allowed'
: ''} w-full max-h-56 pr-2 items-center overflow-y-auto leading-4 outline-none resize-none bg-gray-200"

View File

@ -13,7 +13,7 @@
import { getAssetJobMessage, isSharedLink, handlePromiseError } from '$lib/utils';
import { addAssetsToAlbum, downloadFile } from '$lib/utils/asset-utils';
import { handleError } from '$lib/utils/handle-error';
import { shouldIgnoreShortcut } from '$lib/utils/shortcut';
import { shortcuts } from '$lib/utils/shortcut';
import { SlideshowHistory } from '$lib/utils/slideshow-history';
import {
AssetJobName,
@ -256,68 +256,9 @@
isShowActivity = !isShowActivity;
};
const handleKeypress = async (event: KeyboardEvent) => {
if (shouldIgnoreShortcut(event)) {
return;
}
const key = event.key;
const shiftKey = event.shiftKey;
const ctrlKey = event.ctrlKey;
if (ctrlKey) {
return;
}
switch (key) {
case 'a':
case 'A': {
if (shiftKey) {
await toggleArchive();
}
return;
}
case 'ArrowLeft': {
await navigateAsset('previous');
return;
}
case 'ArrowRight': {
await navigateAsset('next');
return;
}
case 'd':
case 'D': {
if (shiftKey) {
await downloadFile(asset);
}
return;
}
case 'Delete': {
await trashOrDelete(shiftKey);
return;
}
case 'Escape': {
if (isShowDeleteConfirmation) {
isShowDeleteConfirmation = false;
return;
}
if (isShowShareModal) {
isShowShareModal = false;
return;
}
closeViewer();
return;
}
case 'f': {
await toggleFavorite();
return;
}
case 'i': {
isShowActivity = false;
$isShowDetail = !$isShowDetail;
return;
}
}
const toggleDetailPanel = () => {
isShowActivity = false;
$isShowDetail = !$isShowDetail;
};
const handleCloseViewer = () => {
@ -557,7 +498,19 @@
};
</script>
<svelte:window on:keydown={handleKeypress} />
<svelte:window
use:shortcuts={[
{ shortcut: { key: 'a', shift: true }, onShortcut: toggleArchive },
{ shortcut: { key: 'ArrowLeft' }, onShortcut: () => navigateAsset('previous') },
{ shortcut: { key: 'ArrowRight' }, onShortcut: () => navigateAsset('next') },
{ shortcut: { key: 'd', shift: true }, onShortcut: () => downloadFile(asset) },
{ shortcut: { key: 'Delete' }, onShortcut: () => trashOrDelete(false) },
{ shortcut: { key: 'Delete', shift: true }, onShortcut: () => trashOrDelete(true) },
{ shortcut: { key: 'Escape' }, onShortcut: closeViewer },
{ shortcut: { key: 'f' }, onShortcut: toggleFavorite },
{ shortcut: { key: 'i' }, onShortcut: toggleDetailPanel },
]}
/>
<section
id="immich-asset-viewer"

View File

@ -41,6 +41,7 @@
import UserAvatar from '../shared-components/user-avatar.svelte';
import LoadingSpinner from '../shared-components/loading-spinner.svelte';
import { NotificationType, notificationController } from '../shared-components/notification/notification';
import { shortcut } from '$lib/utils/shortcut';
export let asset: AssetResponseDto;
export let albums: AlbumResponseDto[] = [];
@ -105,20 +106,6 @@
closeViewer: void;
}>();
const handleKeypress = async (event: KeyboardEvent) => {
if (event.target !== textArea) {
return;
}
const ctrl = event.ctrlKey;
switch (event.key) {
case 'Enter': {
if (ctrl && event.target === textArea) {
await handleFocusOut();
}
}
}
};
const getMegapixel = (width: number, height: number): number | undefined => {
const megapixel = Math.round((height * width) / 1_000_000);
@ -180,8 +167,6 @@
}
</script>
<svelte:window on:keydown={handleKeypress} />
<section class="relative p-2 dark:bg-immich-dark-bg dark:text-immich-dark-fg">
<div class="flex place-items-center gap-2">
<button
@ -223,6 +208,10 @@
use:autoGrowHeight
use:clickOutside
on:outclick={handleFocusOut}
use:shortcut={{
shortcut: { key: 'Enter', ctrl: true },
onShortcut: () => handlePromiseError(handleFocusOut()),
}}
/>
{/key}
</section>

View File

@ -6,7 +6,7 @@
import { downloadRequest, getAssetFileUrl, handlePromiseError } from '$lib/utils';
import { isWebCompatibleImage } from '$lib/utils/asset-utils';
import { getBoundingBox } from '$lib/utils/people-utils';
import { shouldIgnoreShortcut } from '$lib/utils/shortcut';
import { shortcuts } from '$lib/utils/shortcut';
import { type AssetResponseDto, AssetTypeEnum } from '@immich/sdk';
import { useZoomImageWheel } from '@zoom-image/svelte';
import { onDestroy, onMount } from 'svelte';
@ -84,18 +84,6 @@
}
};
const handleKeypress = async (event: KeyboardEvent) => {
if (shouldIgnoreShortcut(event)) {
return;
}
if (window.getSelection()?.type === 'Range') {
return;
}
if ((event.metaKey || event.ctrlKey) && event.key === 'c') {
await doCopy();
}
};
const doCopy = async () => {
if (!canCopyImagesToClipboard()) {
return;
@ -138,9 +126,23 @@
handlePromiseError(loadAssetData({ loadOriginal: true }));
}
});
const onCopyShortcut = () => {
if (window.getSelection()?.type === 'Range') {
return;
}
handlePromiseError(doCopy());
};
</script>
<svelte:window on:keydown={handleKeypress} on:copyImage={doCopy} on:zoomImage={doZoomImage} />
<svelte:window
on:copyImage={doCopy}
on:zoomImage={doZoomImage}
use:shortcuts={[
{ shortcut: { key: 'c', ctrl: true }, onShortcut: onCopyShortcut },
{ shortcut: { key: 'c', meta: true }, onShortcut: onCopyShortcut },
]}
/>
<div
bind:this={element}

View File

@ -9,6 +9,7 @@
import type { Viewport } from '$lib/stores/assets.store';
import { memoryStore } from '$lib/stores/memory.store';
import { getAssetThumbnailUrl, handlePromiseError } from '$lib/utils';
import { shortcuts } from '$lib/utils/shortcut';
import { fromLocalDateTime } from '$lib/utils/timeline-util';
import { ThumbnailFormat, getMemoryLane } from '@immich/sdk';
import { mdiChevronDown, mdiChevronLeft, mdiChevronRight, mdiChevronUp, mdiPause, mdiPlay } from '@mdi/js';
@ -73,19 +74,6 @@
// Progress should be reset when the current memory or asset changes.
$: memoryIndex, assetIndex, handlePromiseError(reset());
const handleKeyDown = async (e: KeyboardEvent) => {
if (e.key === 'ArrowRight' && canGoForward) {
e.preventDefault();
await toNext();
} else if (e.key === 'ArrowLeft' && canGoBack) {
e.preventDefault();
await toPrevious();
} else if (e.key === 'Escape') {
e.preventDefault();
await goto(AppRoute.PHOTOS);
}
};
onMount(async () => {
if (!$memoryStore) {
const localTime = new Date();
@ -101,7 +89,13 @@
let galleryInView = false;
</script>
<svelte:window on:keydown={handleKeyDown} />
<svelte:window
use:shortcuts={[
{ shortcut: { key: 'ArrowRight' }, onShortcut: () => canGoForward && toNext() },
{ shortcut: { key: 'ArrowLeft' }, onShortcut: () => canGoBack && toPrevious() },
{ shortcut: { key: 'Escape' }, onShortcut: () => goto(AppRoute.PHOTOS) },
]}
/>
<section id="memory-viewer" class="w-full bg-immich-dark-gray" bind:this={memoryWrapper}>
{#if currentMemory}

View File

@ -1,5 +1,4 @@
<script lang="ts">
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import { AppRoute, AssetAction } from '$lib/constants';
import type { AssetInteractionStore } from '$lib/stores/asset-interaction.store';
@ -9,7 +8,7 @@
import { isSearchEnabled } from '$lib/stores/search.store';
import { featureFlags } from '$lib/stores/server-config.store';
import { deleteAssets } from '$lib/utils/actions';
import { shouldIgnoreShortcut } from '$lib/utils/shortcut';
import { shortcuts, type ShortcutOptions } from '$lib/utils/shortcut';
import { formatGroupTitle, splitBucketIntoDateGroups } from '$lib/utils/timeline-util';
import type { AlbumResponseDto, AssetResponseDto } from '@immich/sdk';
import { DateTime } from 'luxon';
@ -49,19 +48,13 @@
const dispatch = createEventDispatcher<{ select: AssetResponseDto; escape: void }>();
const onKeydown = (event: KeyboardEvent) => handlePromiseError(handleKeyboardPress(event));
onMount(async () => {
showSkeleton = false;
document.addEventListener('keydown', onKeydown);
assetStore.connect();
await assetStore.init(viewport);
});
onDestroy(() => {
if (browser) {
document.removeEventListener('keydown', onKeydown);
}
if ($showAssetViewer) {
$showAssetViewer = false;
}
@ -75,51 +68,43 @@
assetInteractionStore.clearMultiselect();
};
const handleKeyboardPress = async (event: KeyboardEvent) => {
if ($isSearchEnabled || shouldIgnoreShortcut(event)) {
const onDelete = () => {
if (!isTrashEnabled && $showDeleteModal) {
isShowDeleteConfirmation = true;
return;
}
const key = event.key;
const shiftKey = event.shiftKey;
if (!$showAssetViewer) {
switch (key) {
case 'Escape': {
dispatch('escape');
return;
}
case '?': {
if (event.shiftKey) {
event.preventDefault();
showShortcuts = !showShortcuts;
}
return;
}
case '/': {
event.preventDefault();
await goto(AppRoute.EXPLORE);
return;
}
case 'Delete': {
if ($isMultiSelectState) {
let force = false;
if (shiftKey || !isTrashEnabled) {
if ($showDeleteModal) {
isShowDeleteConfirmation = true;
return;
}
force = true;
}
await trashOrDelete(force);
}
return;
}
}
}
handlePromiseError(trashOrDelete(false));
};
const onForceDelete = () => {
if ($showDeleteModal) {
isShowDeleteConfirmation = true;
return;
}
handlePromiseError(trashOrDelete(true));
};
$: shortcutList = (() => {
if ($isSearchEnabled || $showAssetViewer) {
return [];
}
const shortcuts: ShortcutOptions[] = [
{ shortcut: { key: 'Escape' }, onShortcut: () => dispatch('escape') },
{ shortcut: { key: '?', shift: true }, onShortcut: () => (showShortcuts = !showShortcuts) },
{ shortcut: { key: '/' }, onShortcut: () => goto(AppRoute.EXPLORE) },
];
if ($isMultiSelectState) {
shortcuts.push(
{ shortcut: { key: 'Delete' }, onShortcut: onDelete },
{ shortcut: { key: 'Delete', shift: true }, onShortcut: onForceDelete },
);
}
return shortcuts;
})();
const handleSelectAsset = (asset: AssetResponseDto) => {
if (!assetStore.albumAssets.has(asset.id)) {
assetInteractionStore.selectAsset(asset);
@ -371,7 +356,7 @@
};
</script>
<svelte:window on:keydown={onKeyDown} on:keyup={onKeyUp} on:selectstart={onSelectStart} />
<svelte:window on:keydown={onKeyDown} on:keyup={onKeyUp} on:selectstart={onSelectStart} use:shortcuts={shortcutList} />
{#if isShowDeleteConfirmation}
<DeleteAssetDialog

View File

@ -1,4 +1,5 @@
import type { ActionReturn } from 'svelte/action';
import { matchesShortcut } from './shortcut';
interface Attributes {
/** @deprecated */
@ -29,7 +30,7 @@ export function clickOutside(node: HTMLElement, options: Options = {}): ActionRe
};
const handleKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape') {
if (!matchesShortcut(event, { key: 'Escape' })) {
return;
}

View File

@ -1,7 +1,76 @@
export const shouldIgnoreShortcut = (event: Event): boolean => {
const type = (event.target as HTMLInputElement).type;
if (['textarea', 'text'].includes(type)) {
return true;
}
return false;
import type { ActionReturn } from 'svelte/action';
export type Shortcut = {
key: string;
alt?: boolean;
ctrl?: boolean;
shift?: boolean;
meta?: boolean;
};
export type ShortcutOptions<T = HTMLElement> = {
shortcut: Shortcut;
onShortcut: (event: KeyboardEvent & { currentTarget: T }) => unknown;
};
export const shouldIgnoreShortcut = (event: KeyboardEvent): boolean => {
if (event.target === event.currentTarget) {
return false;
}
const type = (event.target as HTMLInputElement).type;
return ['textarea', 'text'].includes(type);
};
export const matchesShortcut = (event: KeyboardEvent, shortcut: Shortcut) => {
return (
shortcut.key.toLowerCase() === event.key.toLowerCase() &&
Boolean(shortcut.alt) === event.altKey &&
Boolean(shortcut.ctrl) === event.ctrlKey &&
Boolean(shortcut.shift) === event.shiftKey &&
Boolean(shortcut.meta) === event.metaKey
);
};
export const shortcut = <T extends HTMLElement>(
node: T,
option: ShortcutOptions<T>,
): ActionReturn<ShortcutOptions<T>> => {
const { update: shortcutsUpdate, destroy } = shortcuts(node, [option]);
return {
update(newOption) {
shortcutsUpdate?.([newOption]);
},
destroy,
};
};
export const shortcuts = <T extends HTMLElement>(
node: T,
options: ShortcutOptions<T>[],
): ActionReturn<ShortcutOptions<T>[]> => {
function onKeydown(event: KeyboardEvent) {
if (shouldIgnoreShortcut(event)) {
return;
}
for (const { shortcut, onShortcut } of options) {
if (matchesShortcut(event, shortcut)) {
event.preventDefault();
onShortcut(event as KeyboardEvent & { currentTarget: T });
return;
}
}
}
node.addEventListener('keydown', onKeydown);
return {
update(newOptions) {
options = newOptions;
},
destroy() {
node.removeEventListener('keydown', onKeydown);
},
};
};

View File

@ -113,7 +113,6 @@
let reactions: ActivityResponseDto[] = [];
let globalWidth: number;
let assetGridWidth: number;
let textArea: HTMLTextAreaElement;
let albumOrder: AssetOrder | undefined = data.album.order;
$: assetStore = new AssetStore({ albumId, order: albumOrder });
@ -225,20 +224,6 @@
handlePromiseError(getNumberOfComments());
}
const handleKeypress = (event: KeyboardEvent) => {
if (event.target !== textArea) {
return;
}
const ctrl = event.ctrlKey;
switch (event.key) {
case 'Enter': {
if (ctrl && event.target === textArea) {
textArea.blur();
}
}
}
};
const handleStartSlideshow = async () => {
const asset =
$slideshowNavigation === SlideshowNavigation.Shuffle ? await assetStore.getRandomAsset() : assetStore.assets[0];
@ -394,8 +379,6 @@
};
</script>
<svelte:window on:keydown={handleKeypress} />
<div class="flex overflow-hidden" bind:clientWidth={globalWidth}>
<div class="relative w-full shrink">
{#if $isMultiSelectState}

View File

@ -1,5 +1,4 @@
<script lang="ts">
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import ImageThumbnail from '$lib/components/assets/thumbnail/image-thumbnail.svelte';
@ -27,7 +26,7 @@
import { getPeopleThumbnailUrl } from '$lib/utils';
import { handleError } from '$lib/utils/handle-error';
import { searchNameLocal } from '$lib/utils/person';
import { shouldIgnoreShortcut } from '$lib/utils/shortcut';
import { shortcut } from '$lib/utils/shortcut';
import {
getPerson,
mergePerson,
@ -38,7 +37,7 @@
type PersonResponseDto,
} from '@immich/sdk';
import { mdiAccountOff, mdiEyeOutline } from '@mdi/js';
import { onDestroy, onMount } from 'svelte';
import { onMount } from 'svelte';
import type { PageData } from './$types';
import { locale } from '$lib/stores/preferences.store';
@ -79,10 +78,7 @@
$: countVisiblePeople = countTotalPeople - countHiddenPeople;
const onKeyboardPress = (event: KeyboardEvent) => handleKeyboardPress(event);
onMount(async () => {
document.addEventListener('keydown', onKeyboardPress);
const getSearchedPeople = $page.url.searchParams.get(QueryParameter.SEARCHED_PEOPLE);
if (getSearchedPeople) {
searchName = getSearchedPeople;
@ -90,24 +86,6 @@
}
});
onDestroy(() => {
if (browser) {
document.removeEventListener('keydown', onKeyboardPress);
}
});
const handleKeyboardPress = (event: KeyboardEvent) => {
if (shouldIgnoreShortcut(event)) {
return;
}
switch (event.key) {
case 'Escape': {
handleCloseClick();
return;
}
}
};
const handleSearch = async (force: boolean) => {
$page.url.searchParams.set(QueryParameter.SEARCHED_PEOPLE, searchName);
await goto($page.url);
@ -417,7 +395,7 @@
};
</script>
<svelte:window bind:innerHeight />
<svelte:window bind:innerHeight use:shortcut={{ shortcut: { key: 'Escape' }, onShortcut: handleCloseClick }} />
{#if showMergeModal}
<MergeSuggestionModal

View File

@ -20,7 +20,7 @@
import { AppRoute, QueryParameter } from '$lib/constants';
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
import { preventRaceConditionSearchBar } from '$lib/stores/search.store';
import { shouldIgnoreShortcut } from '$lib/utils/shortcut';
import { shortcut } from '$lib/utils/shortcut';
import {
type AssetResponseDto,
searchSmart,
@ -52,27 +52,19 @@
let searchResultAssets: AssetResponseDto[] = [];
let isLoading = true;
const onKeyboardPress = (event: KeyboardEvent) => handleKeyboardPress(event);
const handleKeyboardPress = async (event: KeyboardEvent) => {
if (shouldIgnoreShortcut(event)) {
const onEscape = () => {
if ($showAssetViewer) {
return;
}
if (!$showAssetViewer) {
switch (event.key) {
case 'Escape': {
if (isMultiSelectionMode) {
selectedAssets = new Set();
return;
}
if (!$preventRaceConditionSearchBar) {
await goto(previousRoute);
}
$preventRaceConditionSearchBar = false;
return;
}
}
if (isMultiSelectionMode) {
selectedAssets = new Set();
return;
}
if (!$preventRaceConditionSearchBar) {
handlePromiseError(goto(previousRoute));
}
$preventRaceConditionSearchBar = false;
};
afterNavigate(({ from }) => {
@ -201,7 +193,7 @@
}
</script>
<svelte:document on:keydown={onKeyboardPress} />
<svelte:window use:shortcut={{ shortcut: { key: 'Escape' }, onShortcut: onEscape }} />
<section>
{#if isMultiSelectionMode}