Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore focus to item that was focused before opening palette #33

Merged
merged 3 commits into from
Feb 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,18 @@
let items = inputData;
let itemsFiltered = inputData;
let fuse = new Fuse(items, optionsFuse);
let focusedElement;

onMount(() => {
initShortCuts(hotkeysGlobal);
setMainShortCut(hotkey, async () => {
focusedElement = document.activeElement
showModal = true;
selectedIndex = 0;
dispatch("opened");
});
setAllShortCuts(inputData, async command => {
focusedElement = document.activeElement
showModal = true;
dispatch("opened");
await asyncTimeout(200);
Expand Down Expand Up @@ -129,18 +132,38 @@
selectedIndex = 0;
setItems(inputData);
showModal = false;
if ( ! focusedElement ) {
console.error("focusedElement not set")
} else {
focusedElement.focus()
}
}

function onMobileClick(e) {
dispatch("opened");
showModal = true;
selectedIndex = 0;
}

function onMobileFocus(e) {
/* Store the item that had focus and assign it to focusedElement.
This will allow us to set focus back to it when we exit. */

// Surprisingly event is defined and has the correct data
// even if I don't do this. But I'll explicity pass it via details.
// as having event magically defined scares me.
let event = e.detail;
if (event.relatedTarget && event.relatedTarget.focus) {
focusedElement = event.relatedTarget;
} else {
focusedElement = document.body
}
}
</script>

<div id={paletteId}>
{#if !hideButton}
<MobileButton on:click={onMobileClick} />
<MobileButton on:click={onMobileClick} on:focus={onMobileFocus}/>
{/if}
<PaletteContainer bind:show={showModal}>
<div slot="search">
Expand Down
4 changes: 3 additions & 1 deletion src/MobileButton.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
}
</style>

<button class="mobile-button" on:click={e => dispatch('click')} title="Click here to open command palette">
<button class="mobile-button" on:click={e => dispatch('click')}
on:focus={e=>dispatch('focus', e)}
title="Click here to open command palette.">
<svg
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.w3.org/2000/svg"
Expand Down