1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-16 16:56:46 +01:00

refactor(web): focus trap (#10915)

This commit is contained in:
Michel Heusschen 2024-07-08 03:33:07 +02:00 committed by GitHub
parent 39221c8d1f
commit cb40db9555
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 407 additions and 365 deletions

View file

@ -0,0 +1,18 @@
<script lang="ts">
import { focusTrap } from '$lib/actions/focus-trap';
export let show: boolean;
</script>
<button type="button" on:click={() => (show = true)}>Open</button>
{#if show}
<div use:focusTrap>
<div>
<span>text</span>
<button data-testid="one" type="button" on:click={() => (show = false)}>Close</button>
</div>
<input data-testid="two" disabled />
<input data-testid="three" />
</div>
{/if}

View file

@ -0,0 +1,40 @@
import FocusTrapTest from '$lib/actions/__test__/focus-trap-test.svelte';
import { render, screen } from '@testing-library/svelte';
import userEvent from '@testing-library/user-event';
import { tick } from 'svelte';
describe('focusTrap action', () => {
const user = userEvent.setup();
it('sets focus to the first focusable element', () => {
render(FocusTrapTest, { show: true });
expect(document.activeElement).toEqual(screen.getByTestId('one'));
});
it('supports backward focus wrapping', async () => {
render(FocusTrapTest, { show: true });
await user.keyboard('{Shift>}{Tab}{/Shift}');
expect(document.activeElement).toEqual(screen.getByTestId('three'));
});
it('supports forward focus wrapping', async () => {
render(FocusTrapTest, { show: true });
screen.getByTestId('three').focus();
await user.keyboard('{Tab}');
expect(document.activeElement).toEqual(screen.getByTestId('one'));
});
it('restores focus to the triggering element', async () => {
render(FocusTrapTest, { show: false });
const openButton = screen.getByText('Open');
openButton.focus();
openButton.click();
await tick();
expect(document.activeElement).toEqual(screen.getByTestId('one'));
screen.getByText('Close').click();
await tick();
expect(document.activeElement).toEqual(openButton);
});
});

View file

@ -0,0 +1,55 @@
import { shortcuts } from '$lib/actions/shortcut';
const selectors =
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
export function focusTrap(container: HTMLElement) {
const triggerElement = document.activeElement;
const focusableElement = container.querySelector<HTMLElement>(selectors);
focusableElement?.focus();
const getFocusableElements = (): [HTMLElement | null, HTMLElement | null] => {
const focusableElements = container.querySelectorAll<HTMLElement>(selectors);
return [
focusableElements.item(0), //
focusableElements.item(focusableElements.length - 1),
];
};
const { destroy: destroyShortcuts } = shortcuts(container, [
{
ignoreInputFields: false,
preventDefault: false,
shortcut: { key: 'Tab' },
onShortcut: (event) => {
const [firstElement, lastElement] = getFocusableElements();
if (document.activeElement === lastElement) {
event.preventDefault();
firstElement?.focus();
}
},
},
{
ignoreInputFields: false,
preventDefault: false,
shortcut: { key: 'Tab', shift: true },
onShortcut: (event) => {
const [firstElement, lastElement] = getFocusableElements();
if (document.activeElement === firstElement) {
event.preventDefault();
lastElement?.focus();
}
},
},
]);
return {
destroy() {
destroyShortcuts?.();
if (triggerElement instanceof HTMLElement) {
triggerElement.focus();
}
},
};
}

View file

@ -1,7 +1,6 @@
<script lang="ts">
import Icon from '$lib/components/elements/icon.svelte';
import CreateSharedLinkModal from '$lib/components/shared-components/create-share-link-modal/create-shared-link-modal.svelte';
import FocusTrap from '$lib/components/shared-components/focus-trap.svelte';
import { AssetAction, ProjectionType } from '$lib/constants';
import { updateNumberOfComments } from '$lib/stores/activity.store';
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
@ -61,6 +60,7 @@
import { websocketEvents } from '$lib/stores/websocket';
import { canCopyImagesToClipboard } from 'copy-image-clipboard';
import { t } from 'svelte-i18n';
import { focusTrap } from '$lib/actions/focus-trap';
export let assetStore: AssetStore | null = null;
export let asset: AssetResponseDto;
@ -553,11 +553,11 @@
<svelte:document bind:fullscreenElement />
<FocusTrap>
<section
<section
id="immich-asset-viewer"
class="fixed left-0 top-0 z-[1001] grid h-screen w-screen grid-cols-4 grid-rows-[64px_1fr] overflow-hidden bg-black"
>
use:focusTrap
>
<!-- Top navigation bar -->
{#if $slideshowState === SlideshowState.None}
<div class="z-[1002] col-span-4 col-start-1 row-span-1 row-start-1 transition-transform">
@ -788,11 +788,7 @@
{/if}
{#if isShowDeleteConfirmation}
<DeleteAssetDialog
size={1}
on:cancel={() => (isShowDeleteConfirmation = false)}
on:confirm={() => deleteAsset()}
/>
<DeleteAssetDialog size={1} on:cancel={() => (isShowDeleteConfirmation = false)} on:confirm={() => deleteAsset()} />
{/if}
{#if isShowProfileImageCrop}
@ -802,8 +798,7 @@
{#if isShowShareModal}
<CreateSharedLinkModal assetIds={[asset.id]} onClose={() => (isShowShareModal = false)} />
{/if}
</section>
</FocusTrap>
</section>
<style>
#immich-asset-viewer {

View file

@ -1,64 +0,0 @@
<script lang="ts">
import { shortcuts } from '$lib/actions/shortcut';
import { onMount, onDestroy } from 'svelte';
let container: HTMLElement;
let triggerElement: HTMLElement;
onMount(() => {
triggerElement = document.activeElement as HTMLElement;
const focusableElements = getFocusableElements();
focusableElements[0]?.focus();
});
onDestroy(() => {
triggerElement?.focus();
});
const getFocusableElements = () => {
return Array.from(
container.querySelectorAll(
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
),
) as HTMLElement[];
};
const trapFocus = (direction: 'forward' | 'backward', event: KeyboardEvent) => {
const focusableElements = getFocusableElements();
const elementCount = focusableElements.length;
const firstElement = focusableElements[0];
const lastElement = focusableElements.at(elementCount - 1);
if (document.activeElement === lastElement && direction === 'forward') {
event.preventDefault();
firstElement?.focus();
} else if (document.activeElement === firstElement && direction === 'backward') {
event.preventDefault();
lastElement?.focus();
}
};
</script>
<div
bind:this={container}
use:shortcuts={[
{
ignoreInputFields: false,
shortcut: { key: 'Tab' },
onShortcut: (event) => {
trapFocus('forward', event);
},
preventDefault: false,
},
{
ignoreInputFields: false,
shortcut: { key: 'Tab', shift: true },
onShortcut: (event) => {
trapFocus('backward', event);
},
preventDefault: false,
},
]}
>
<slot />
</div>

View file

@ -1,7 +1,7 @@
<script lang="ts">
import { clickOutside } from '$lib/actions/click-outside';
import { focusTrap } from '$lib/actions/focus-trap';
import { fade } from 'svelte/transition';
import FocusTrap from '$lib/components/shared-components/focus-trap.svelte';
import ModalHeader from '$lib/components/shared-components/modal-header.svelte';
import { generateId } from '$lib/utils/generate-id';
@ -52,8 +52,8 @@
on:keydown={(event) => {
event.stopPropagation();
}}
use:focusTrap
>
<FocusTrap>
<div
class="z-[9999] max-w-[95vw] max-h-[min(95dvh,56rem)] {modalWidth} overflow-y-auto rounded-3xl bg-immich-bg shadow-md dark:bg-immich-dark-gray dark:text-immich-dark-fg immich-scrollbar"
use:clickOutside={{ onOutclick: onClose, onEscape: onClose }}
@ -75,5 +75,4 @@
</div>
{/if}
</div>
</FocusTrap>
</section>

View file

@ -1,8 +1,8 @@
<script lang="ts">
import { focusTrap } from '$lib/actions/focus-trap';
import Button from '$lib/components/elements/buttons/button.svelte';
import CircleIconButton from '$lib/components/elements/buttons/circle-icon-button.svelte';
import Icon from '$lib/components/elements/icon.svelte';
import FocusTrap from '$lib/components/shared-components/focus-trap.svelte';
import { AppRoute } from '$lib/constants';
import { preferences, user } from '$lib/stores/user.store';
import { handleError } from '$lib/utils/handle-error';
@ -42,13 +42,13 @@
};
</script>
<FocusTrap>
<div
<div
in:fade={{ duration: 100 }}
out:fade={{ duration: 100 }}
id="account-info-panel"
class="absolute right-[25px] top-[75px] z-[100] w-[360px] rounded-3xl bg-gray-200 shadow-lg dark:border dark:border-immich-dark-gray dark:bg-immich-dark-gray"
>
use:focusTrap
>
<div
class="mx-4 mt-4 flex flex-col items-center justify-center gap-4 rounded-3xl bg-white p-4 dark:bg-immich-dark-primary/10"
>
@ -93,8 +93,7 @@
{$t('sign_out')}</button
>
</div>
</div>
</FocusTrap>
</div>
{#if isShowSelectAvatar}
<AvatarSelector