There’s a keyboard shortcut for a global search bar, which will open up a command palette in the future.
⌘+k
Then there’s a page-specific input field, which gains focus by pressing /.
Here’s the hook for the global search field.
const CommandPallete = {
mounted() {
document.addEventListener("keydown", (e) => {
if (e.key === "k" && e.metaKey) {
this.el.focus();
}
});
},
};
export default CommandPallete;
And here’s the JS dispatch for local input field:
phx-window-keyup={JS.dispatch("phx:focus", to: "#url")}
phx-key="/"
window.addEventListener("phx:focus", (event) => {
event.target.focus();
});
Here’s the problem:
- Upon arrival, the focus goes to the URL input field.
- On click ⌘+k, focus goes to global search.
- While typing in the global search, if someone enters / by chance, the focus goes to the local input field instead of staying global.
I tried preventDefault, stopEventPropagation, and currently thinking of the best way forward.
Perhaps a common and global Hook, that can handle any shortcut combo, and prevents focus from darting around if there’s already an element in focus. (I will try this approach next)
Or something else, that I am unable to think of.
P.S. Some events are okay though, for instance, dismissing the flash message with an Esc key, or closing the command palette with Esc key, while still focused on input field.
phx-window-keyup={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
phx-key="Escape"