Skip to content

Commit

Permalink
feat: make selected item visible using a scroll
Browse files Browse the repository at this point in the history
- also: minor cleanup of the context-menu-navigation Svelte action
  • Loading branch information
ben-basten committed Jun 16, 2024
1 parent 03d1263 commit fbc373a
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
12 changes: 7 additions & 5 deletions web/src/lib/actions/context-menu-navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,20 @@ interface Options {
*/
selectedId: string | undefined;
/**
* A function that is called when the selection changes.
* A function that is called when the selection changes, to notify consumers of the new selected id.
*/
selectionChanged: (node: HTMLElement | undefined, index: number | undefined) => void;
selectionChanged: (id: string | undefined) => void;
}

export const contextMenuNavigation: Action<HTMLElement, Options> = (node, options: Options) => {
const getCurrentElement = () => {
const { container, selectedId: activeId } = options;
return container?.querySelector(`#${activeId}`) as HTMLElement | undefined;
return container?.querySelector(`#${activeId}`) as HTMLElement | null;
};

const close = () => {
const { closeDropdown, selectionChanged } = options;
selectionChanged(undefined, undefined);
selectionChanged(undefined);
closeDropdown();
};

Expand All @@ -61,8 +61,10 @@ export const contextMenuNavigation: Action<HTMLElement, Options> = (node, option
const currentIndex = currentEl ? children.indexOf(currentEl) : -1;
const directionFactor = (direction === 'up' ? -1 : 1) + (direction === 'up' && currentIndex === -1 ? 1 : 0);
const newIndex = (currentIndex + directionFactor + children.length) % children.length;
const selectedNode = children[newIndex];
selectedNode?.scrollIntoView({ block: 'nearest' });

selectionChanged(children[newIndex], newIndex);
selectionChanged(selectedNode?.id);
};

const onEscape = (event: KeyboardEvent) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
onEscape,
openDropdown,
selectedId: $selectedIdStore,
selectionChanged: (node) => ($selectedIdStore = node?.id),
selectionChanged: (id) => ($selectedIdStore = id),
}}
bind:this={buttonContainer}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@
container: contextMenuElement,
isOpen,
selectedId: $selectedIdStore,
selectionChanged: (node) => ($selectedIdStore = node?.id),
selectionChanged: (id) => ($selectedIdStore = id),
}}
>
{title}
Expand Down

0 comments on commit fbc373a

Please sign in to comment.