1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-10 13:56:47 +01:00
immich/web/src/lib/utils/list-navigation.ts
2024-03-15 15:00:53 -05:00

32 lines
1.1 KiB
TypeScript

import type { Action } from 'svelte/action';
import { shortcuts } from './shortcut';
export const listNavigation: Action<HTMLElement, HTMLElement> = (node, container: HTMLElement) => {
const moveFocus = (direction: 'up' | 'down') => {
const children = Array.from(container?.children);
if (children.length === 0) {
return;
}
const currentIndex = document.activeElement === null ? -1 : children.indexOf(document.activeElement);
const directionFactor = (direction === 'up' ? -1 : 1) + (direction === 'up' && currentIndex === -1 ? 1 : 0);
const newIndex = (currentIndex + directionFactor + children.length) % children.length;
const element = children.at(newIndex);
if (element instanceof HTMLElement) {
element.focus();
}
};
const { destroy } = shortcuts(node, [
{ shortcut: { key: 'ArrowUp' }, onShortcut: () => moveFocus('up'), ignoreInputFields: false },
{ shortcut: { key: 'ArrowDown' }, onShortcut: () => moveFocus('down'), ignoreInputFields: false },
]);
return {
update(newContainer) {
container = newContainer;
},
destroy,
};
};