How to open command pallete using JS.dispatch()

Here’s a simple approach.

phx-window-keyup={JS.dispatch("phx:focus", to: "#url")}
phx-key="/"
window.addEventListener("phx:focus", (event) => {
  event.target.focus();
});

This allows the focus to go to a search field, URL field, or wherever on the client side.


However, I also want to add Command + k to the mix.

phx-window-keydown="open-command-pallete"
phx-key="???"                                                           Meta+k ???

or

phx-window-keydown={open_command_pallete(js \\ %JS{})}                  How to send the meta key into this?
phx-key="???"                                                           Meta+k ???

I have done the needful on the app.js file.

keydown: (e, el) => {
  return {
    key: e.key,
    metaKey: e.metaKey,
  };
},

And I’m able to receive events on the server.

def handle_event("open-command-pallete", %{"key" => "k", "metaKey" => true} = params, socket) do
  {:noreply,
   socket
   |> push_event("phx:focus", %{
     to: "#search-box"
   })}
end

def handle_event("open-command-pallete", _params, socket), do: {:noreply, socket}

Can you tell me how to do it without the server round trip?

def open_command_pallete(js \\ %JS{}, how_to_receive_the_meta_key) do
  js
  |> JS.dispatch("phx:focus", to: "#search-box")
end

a plain old boring window event listener in app.js?
a Hook. This one in live_beats will get you started.

3 Likes

I will do it with Hooks.

I asked this question, to know if I’m missing some minor details with the approach I’m taking and if what I’m trying to do is already doable with phx-bindings and JS dispatch.