diff --git a/assets/js/hooks/universal-search-navigation.js b/assets/js/hooks/universal-search-navigation.js index bfb9dea7..0c6c60bc 100644 --- a/assets/js/hooks/universal-search-navigation.js +++ b/assets/js/hooks/universal-search-navigation.js @@ -1,6 +1,5 @@ export default { mounted() { - this.searchInput = document.getElementById("universal-search-input"); this.selectedIndex = -1; // -1 means search input is focused this.keydownHandler = (event) => { @@ -89,15 +88,16 @@ export default { updateSelection() { const results = this.getResultElements(); - // Remove all aria-selected attributes and return focus to search input + // Remove all aria-selected attributes results.forEach((result) => { result.removeAttribute("aria-selected"); }); if (this.selectedIndex === -1) { // Focus search input - if (this.searchInput) { - this.searchInput.focus(); + const searchInput = document.getElementById("universal-search-input"); + if (searchInput) { + searchInput.focus(); } } else if (this.selectedIndex >= 0 && this.selectedIndex < results.length) { // Mark selected result diff --git a/test/music_library_web/live/universal_search_live/index_test.exs b/test/music_library_web/live/universal_search_live/index_test.exs index 4f499b92..f86d90dd 100644 --- a/test/music_library_web/live/universal_search_live/index_test.exs +++ b/test/music_library_web/live/universal_search_live/index_test.exs @@ -107,4 +107,45 @@ defmodule MusicLibraryWeb.UniversalSearchLive.IndexTest do |> assert_has("div", text: "1 result") end end + + describe "Keyboard navigation" do + test "displays keyboard navigation hints when results are present", %{ + conn: conn, + collection_record: collection_record + } do + conn + |> visit(~p"/collection") + |> click_button("Search (Cmd/Ctrl+K)") + |> fill_in("Universal Search", with: collection_record.title) + |> assert_has("kbd", text: "↑") + |> assert_has("kbd", text: "↓") + |> assert_has("span", text: "Navigate") + |> assert_has("kbd", text: "Enter") + |> assert_has("span", text: "Select") + end + + test "search results have role=option for keyboard navigation", %{ + conn: conn, + collection_record: collection_record + } do + conn + |> visit(~p"/collection") + |> click_button("Search (Cmd/Ctrl+K)") + |> fill_in("Universal Search", with: collection_record.title) + |> assert_has("[role='option']") + end + + test "hook is attached to the universal search container", %{conn: conn} do + {:ok, view, _html} = + conn + |> visit(~p"/collection") + |> PhoenixTest.unwrap() + + # Get the rendered HTML + html = Phoenix.LiveViewTest.render(view) + + # Verify the hook is attached + assert html =~ ~s(phx-hook="UniversalSearchNavigation") + end + end end