Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Fix recent searches keyboard navigation (#4339)
Olga Bulatf39fbe940fbb
diff --git a/frontend/src/components/VHeader/VHeaderDesktop.vue b/frontend/src/components/VHeader/VHeaderDesktop.vueindex 642ead53a..b4c50fb04 100644--- a/frontend/src/components/VHeader/VHeaderDesktop.vue+++ b/frontend/src/components/VHeader/VHeaderDesktop.vue@@ -9,6 +9,7 @@v-model.trim="searchTerm"class="me-4 flex-grow"@submit="handleSearch"+ @recent-hidden="handleSearch"><VSearchBarButtonv-show="searchTerm !== ''"diff --git a/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsButton.vue b/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsButton.vueindex c2359a1e3..c4b10fcb6 100644--- a/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsButton.vue+++ b/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsButton.vue@@ -8,7 +8,7 @@: $t('header.contentSettingsButton.simple')"aria-haspopup="dialog"- :aria-expanded="isPressed"+ :aria-expanded="isPressed ? 'true' : 'false'"aria-controls="content-settings-modal"variant="filled-white"v-on="$listeners"diff --git a/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue b/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vueindex c97854145..59fb177e0 100644--- a/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue+++ b/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue@@ -5,35 +5,36 @@><VInputModalclass="flex w-full"- variant="recent-searches"- :is-active="isRecentSearchesModalOpen"- aria-label="inputmodal"- @close="deactivate"+ :is-active="isRecentVisible"+ :aria-label="$t('recentSearches.heading').toString()"+ @close="hideRecentSearches">- <div class="flex w-full" :class="{ 'px-3': isRecentSearchesModalOpen }">+ <div class="flex w-full" :class="{ 'px-3': isRecentVisible }"><!-- Form action is a fallback for when JavaScript is disabled. --><formaction="/search"class="search-bar group flex h-12 w-full flex-row items-center overflow-hidden rounded-sm":class="- searchBarIsActive+ isSearchBarActive || isInputFocused? 'bg-white ring ring-pink': 'bg-dark-charcoal-06'"- @submit.prevent="handleSearch"+ @submit.prevent="handleFormSubmit"><slot name="start"><VLogoButton- v-show="!searchBarIsActive"+ v-show="!isRecentVisible":is-fetching="isFetching"+ class="focus-visible:me-1.5px focus-visible:ms-1.5px focus-visible:!h-[45px] focus-visible:max-w-[45px]"/><VSearchBarButton- v-show="searchBarIsActive"+ v-show="isRecentVisible"icon="chevron-back":label="$t('header.backButton')":rtl-flip="true"variant="filled-gray"- @click="handleBack"+ @click="hideRecentSearches"+ @keydown.shift.tab="handleTabOut('backward')"/></slot>@@ -44,7 +45,7 @@:placeholder="$t('hero.search.placeholder').toString()"type="search"class="search-field ms-1 h-full w-full flex-grow appearance-none rounded-none border-tx bg-tx text-2xl text-dark-charcoal-70 placeholder-dark-charcoal-70 hover:text-dark-charcoal hover:placeholder-dark-charcoal focus-visible:outline-none"- :value="searchTerm"+ :value="localSearchTerm":aria-label="$t('search.searchBarLabel', {openverse: 'Openverse',@@ -52,41 +53,46 @@"autocomplete="off"role="combobox"- aria-autocomplete="none"- :aria-expanded="showRecentSearches"+ aria-autocomplete="list"+ :aria-expanded="isRecentVisible ? 'true' : 'false'"+ aria-owns="recent-searches-list"aria-controls="recent-searches-list":aria-activedescendant="- selectedIdx !== undefined ? `option-${selectedIdx}` : undefined+ selectedIdx === undefined ? undefined : `option-${selectedIdx}`"@input="updateSearchText"- @focus="activate"- @keydown="handleKeydown"+ @keydown="handleInputKeydown"+ @focus="handleInputFocus"+ @focusout="handleInputBlur"+ @click="handleInputClick"/><slot><VSearchBarButton- v-show="searchBarIsActive && searchTerm"+ v-show="isRecentVisible && localSearchTerm"icon="close-small":label="$t('browsePage.searchForm.clear')"inner-area-classes="bg-white hover:bg-dark-charcoal-10"@click="clearSearchText"+ @keydown.tab.exact="handleClearButtonTab"/><span- v-show="!searchBarIsActive && searchStatus"+ v-show="!isSearchBarActive && searchStatus"class="info mx-4 hidden whitespace-nowrap text-xs group-hover:text-dark-charcoal group-focus:text-dark-charcoal md:flex">{{ searchStatus }}</span><VContentSettingsButton- v-show="!searchBarIsActive"+ v-show="!isRecentVisible"ref="contentSettingsButtonRef":is-pressed="contentSettingsOpen":applied-filter-count="appliedFilterCount"v-bind="triggerA11yProps":disabled="!doneHydrating"@click="toggleContentSettings"+ @keydown.tab.exact="handleTabOut('forward')"/><VContentSettingsModalContent- v-show="!searchBarIsActive"+ v-show="!isRecentVisible"variant="two-thirds":visible="contentSettingsOpen":is-fetching="isFetching"@@ -99,14 +105,15 @@</div><ClientOnly><VRecentSearches- v-show="showRecentSearches"+ v-show="isRecentVisible"+ ref="recentSearchesRef":selected-idx="selectedIdx":entries="entries":bordered="false"class="mt-4"@select="handleSelect"@clear="handleClear"- @clear-single="handleClearSingle"+ @last-tab="handleTabOut('forward')"/></ClientOnly></VInputModal>@@ -115,20 +122,24 @@<script lang="ts">import { computed, defineComponent, nextTick, ref, watch } from "vue"+import { useContext, useRoute } from "@nuxtjs/composition-api"+import { onClickOutside } from "@vueuse/core"-import { ensureFocus } from "~/utils/reakit-utils/focus"-import { cyclicShift } from "~/utils/math"--import { keycodes } from "~/constants/key-codes"+import {+ ensureFocus,+ getAllTabbableIn,+ getFirstTabbableIn,+} from "~/utils/reakit-utils/focus"import { useDialogControl } from "~/composables/use-dialog-control"import { useSearch } from "~/composables/use-search"+import { useHydrating } from "~/composables/use-hydrating"+import { useRecentSearches } from "~/composables/use-recent-searches"import { useMediaStore } from "~/stores/media"import { useSearchStore } from "~/stores/search"-import { useHydrating } from "~/composables/use-hydrating"-import { useAnalytics } from "~/composables/use-analytics"+import { skipToContentTargetId } from "~/constants/window"import VLogoButton from "~/components/VHeader/VLogoButton.vue"import VInputModal from "~/components/VModal/VInputModal.vue"@@ -155,6 +166,9 @@ export default defineComponent({setup(_, { emit }) {const searchInputRef = ref<HTMLInputElement | null>(null)const headerRef = ref<HTMLElement | null>(null)+ const recentSearchesRef = ref<InstanceType<typeof VRecentSearches> | null>(+ null+ )const contentSettingsButtonRef = ref<InstanceType<typeof VContentSettingsButton> | null>(null)@@ -165,139 +179,175 @@ export default defineComponent({const mediaStore = useMediaStore()const searchStore = useSearchStore()- const searchBarIsActive = ref(false)+ const isSearchBarActive = ref(false)+ const isInputFocused = ref(false)const contentSettingsOpen = ref(false)+ const appliedFilterCount = computed(() => searchStore.appliedFilterCount)const isFetching = computed(() => mediaStore.fetchState.isFetching)- const { sendCustomEvent } = useAnalytics()+ /**+ * The selection range of the input field. Used to make sure that the cursor+ * is at the correct position when the search bar is clicked on.+ */+ const selection = ref<{ start: number; end: number }>({ start: 0, end: 0 })+ const { $sendCustomEvent } = useContext()const { updateSearchState, searchTerm, searchStatus } =- useSearch(sendCustomEvent)+ useSearch($sendCustomEvent)+ const localSearchTerm = ref(searchTerm.value)++ const focusInput = () => {+ const input = searchInputRef.value as HTMLInputElement+ ensureFocus(input)+ input.selectionStart = selection.value.start+ input.selectionEnd = selection.value.end+ }- const handleSearch = async () => {+ const handleFormSubmit = () => {+ if (localSearchTerm.value && localSearchTerm.value !== searchTerm.value) {+ searchTerm.value = localSearchTerm.value+ }+ recent.hide()+ handleSearch()+ }+ const handleSearch = () => {window.scrollTo({ top: 0, left: 0, behavior: "auto" })updateSearchState()- deactivate()}- const isRecentSearchesModalOpen = ref(false)+ /**+ * Activate the search bar and open the recent searches modal.+ */+ const activate = () => {+ isInputFocused.value = true+ isSearchBarActive.value = true+ if (!recent.isVisible.value) {+ recent.show()+ }+ }- const activate = () => (searchBarIsActive.value = true)+ /** Deactivate the search bar */const deactivate = () => {- searchBarIsActive.value = false+ isInputFocused.value = false+ isSearchBarActive.value = false}- watch(searchBarIsActive, (active) => {- if (active) {- isRecentSearchesModalOpen.value = true- /**- * Without `nextTick`, the search bar is not focused on click in Firefox- */- nextTick(() => {- if (searchInputRef.value) {- ensureFocus(searchInputRef.value)- }- })- } else {- isRecentSearchesModalOpen.value = false- if (searchTerm.value === "" && searchStore.searchTerm !== "") {- searchTerm.value = searchStore.searchTerm- }+ /**+ * Set the selection range of the input field to the saved value.+ * This is necessary because when opening the recent search modal,+ * the input field is blurred and focused again.+ */+ const updateSelection = () => {+ const inputElement = searchInputRef.value as HTMLInputElement+ const lastPos =+ inputElement.value.length > 0 ? inputElement.value.length - 1 : 0+ selection.value = {+ start: inputElement.selectionStart ?? lastPos,+ end: inputElement.selectionEnd ?? lastPos,}- })- const appliedFilterCount = computed(() => searchStore.appliedFilterCount)+ }- const updateSearchText = (event: Event) => {- searchTerm.value = (event.target as HTMLInputElement).value+ /**+ * When the user tabs into the input field, the `isInputFocused` is set to true,+ * but the search bar is not activated until the user types something.+ *+ * On the `input` event, update the search term and the selection range,+ * and activate the search bar.+ */+ const updateSearchText = () => {+ localSearchTerm.value = (searchInputRef.value as HTMLInputElement).value+ updateSelection()+ if (isInputFocused.value && !isSearchBarActive.value) {+ activate()+ }}const clearSearchText = () => {- searchTerm.value = ""- if (searchInputRef.value) {- ensureFocus(searchInputRef.value)- }+ localSearchTerm.value = ""+ focusInput()}- const handleBack = () => {- deactivate()+ const {+ handleKeydown: handleInputKeydown,+ handleSelect,+ handleClear,+ recent,+ } = useRecentSearches({+ focusInput,+ term: localSearchTerm,+ isMobile: true,+ isInputFocused,+ })++ watch(recent.isVisible, (isVisible) => {+ if (!isVisible) {+ deactivate()+ if (localSearchTerm.value !== searchTerm.value) {+ searchTerm.value = localSearchTerm.value+ handleSearch()+ }+ }+ })++ const handleInputFocus = () => (isInputFocused.value = true)+ const handleInputBlur = () => {+ if (!recent.isVisible.value && isInputFocused.value) {+ deactivate()+ }}/**- * Refers to the current suggestion that has visual focus (not DOM focus)- * and is the active descendant. This should be set to `undefined` when the- * visual focus is on the input field.+ * Deactivate the search bar when the user clicks outside the header,+ * but not when the click is inside the recent searches modal.*/- const selectedIdx = ref<number | undefined>(undefined)- const entries = computed(() => searchStore.recentSearches)- const handleVerticalArrows = (event: KeyboardEvent) => {- event.preventDefault() // Prevent the cursor from moving horizontally.- const { key, altKey } = event- // Show the recent searches.- isRecentSearchesModalOpen.value = true- if (altKey) {- return- }- // Shift selection (if Alt was not pressed with arrow keys)- let defaultValue: number- let offset: number- if (key == keycodes.ArrowUp) {- defaultValue = 0- offset = -1- } else {- defaultValue = -1- offset = 1- }- selectedIdx.value = cyclicShift(- selectedIdx.value ?? defaultValue,- offset,- 0,- entries.value.length+ onClickOutside(headerRef, (event) => {+ const clickInsideModal = recentSearchesRef.value?.$el?.contains(+ event.target as Node)- }- const handleOtherKeys = (event: KeyboardEvent) => {- const { key } = event- if (key === keycodes.Enter && selectedIdx.value) {- // If a recent search is selected, populate its value into the input.- searchTerm.value = entries.value[selectedIdx.value]+ if (!clickInsideModal) {+ isInputFocused.value = false}- if (([keycodes.Escape] as string[]).includes(key)) {- // Hide the recent searches.- isRecentSearchesModalOpen.value = false- }- selectedIdx.value = undefined // Lose visual focus from entries.- }- const handleKeydown = (event: KeyboardEvent) => {- const { key } = event- return ([keycodes.ArrowUp, keycodes.ArrowDown] as string[]).includes(key)- ? handleVerticalArrows(event)- : handleOtherKeys(event)- }- /* Populate the input with the clicked entry and execute the search. */- const handleSelect = (idx: number) => {- searchTerm.value = entries.value[idx]- isRecentSearchesModalOpen.value = false- selectedIdx.value = undefined // Lose visual focus from entries.- handleSearch() // Immediately execute the search manually.- }- /* Clear all recent searches from the store. */- const handleClear = () => {- searchStore.clearRecentSearches()- if (searchInputRef.value) {- ensureFocus(searchInputRef.value)+ })++ /**+ * When activating the search bar by clicking, preserve the cursor position.+ */+ const handleInputClick = () => {+ if (!isSearchBarActive.value) {+ updateSelection()+ activate()}}- /* Clear a specific recent search from the store. */- const handleClearSingle = (idx: number) => {- searchStore.clearRecentSearch(idx)- if (searchInputRef.value) {- ensureFocus(searchInputRef.value)++ /**+ * Close the modal when the last clickable element is clicked+ * (clear button when there are no recent searches).+ */+ const handleClearButtonTab = () => {+ if (!recent.entries.value.length) {+ handleTabOut("forward")}}- const showRecentSearches = computed(- () => isRecentSearchesModalOpen.value && entries.value.length > 0- )+ /**+ * Special handling of focus order after leaving the search bar because+ * the input modal is inserted into the page and change the HTML elements order.+ * @param direction+ */+ const handleTabOut = (direction: "forward" | "backward") => {+ recent.hide()+ nextTick().then(() => {+ let element =+ direction === "forward"+ ? document.getElementById(skipToContentTargetId)+ : getAllTabbableIn(document.body)[1]+ if (!element) {+ element = getFirstTabbableIn(document.body)+ }+ ensureFocus(element as HTMLElement)+ })+ }const {close: closeContentSettings,@@ -311,44 +361,57 @@ export default defineComponent({emit,})+ const route = useRoute()+ const routeSearchTerm = computed(() => route.value.query.q)+ watch(routeSearchTerm, (newSearchTerm) => {+ const term = Array.isArray(newSearchTerm)+ ? newSearchTerm[0]+ : newSearchTerm+ localSearchTerm.value = term ?? ""+ })+const { doneHydrating } = useHydrating()return {+ isInputFocused,searchInputRef,headerRef,+ recentSearchesRef,contentSettingsButtonRef,contentSettingsButton,isFetching,-appliedFilterCount,-doneHydrating,+contentSettingsOpen,+ triggerA11yProps,openContentSettings,closeContentSettings,toggleContentSettings,- triggerA11yProps,- isRecentSearchesModalOpen,- showRecentSearches,- searchBarIsActive,- activate,+ searchStatus,+ localSearchTerm,+ isSearchBarActive,deactivate,+ handleInputFocus,+ handleInputBlur,+ handleInputClick,+ handleInputKeydown,- searchStatus,- searchTerm,clearSearchText,updateSearchText,handleSearch,+ handleFormSubmit,- handleBack,- selectedIdx,- entries,- handleKeydown,+ isRecentVisible: recent.isVisible,+ selectedIdx: recent.selectedIdx,+ entries: recent.entries,+ hideRecentSearches: recent.hide,handleSelect,handleClear,- handleClearSingle,+ handleClearButtonTab,+ handleTabOut,}},})diff --git a/frontend/src/components/VHeader/VSearchBar/VSearchBar.vue b/frontend/src/components/VHeader/VSearchBar/VSearchBar.vueindex 5f756ea22..325229260 100644--- a/frontend/src/components/VHeader/VSearchBar/VSearchBar.vue+++ b/frontend/src/components/VHeader/VSearchBar/VSearchBar.vue@@ -38,7 +38,7 @@<VSearchButtontype="submit"route="search"- @keydown.tab="handleSearchBlur"+ @keydown.tab.exact="handleSearchBlur"/></form><ClientOnly>@@ -49,8 +49,7 @@class="absolute inset-x-0 z-popover lg:flex":class="recentClasses"@select="handleSelect"- @clear="handleClear"- @clear-single="handleClearSingle"+ @clear="handleClear($event)"@keydown.tab.native="hideRecentSearches"/></ClientOnly>@@ -58,17 +57,13 @@</template><script lang="ts">-import { computed, defineComponent, PropType, ref } from "vue"+import { computed, defineComponent, PropType, ref, watch } from "vue"import { onClickOutside } from "@vueuse/core"import { defineEvent } from "~/types/emits"-import { useSearchStore } from "~/stores/search"--import { keycodes } from "~/constants/key-codes"--import { cyclicShift } from "~/utils/math"+import { useRecentSearches } from "~/composables/use-recent-searches"import VInputField, {FIELD_SIZES,@@ -107,6 +102,7 @@ export default defineComponent({emits: {input: defineEvent<[string]>(),submit: defineEvent(),+ "recent-hidden": defineEvent(),},setup(props, { emit }) {const searchBarEl = ref<HTMLElement | null>(null)@@ -124,9 +120,6 @@ export default defineComponent({}/* Recent searches */- const searchStore = useSearchStore()-- const isRecentVisible = ref(false)const recentClasses = computed(() => {// Calculated by adding 8px to all heights defined in `VInputField.vue`.const FIELD_OFFSETS = {@@ -134,105 +127,32 @@ export default defineComponent({} as constreturn FIELD_OFFSETS[props.size]})-- /**- * Show and hide recent searches.- */- const showRecentSearches = () => {- isRecentVisible.value = true- }- const hideRecentSearches = () => {- isRecentVisible.value = false+ const focusInput = () => {+ inputFieldRef.value?.focusInput()}+/*** Hide recent searches on blur and click outside.*/const handleSearchBlur = () => {- if (!entries.value.length) {- hideRecentSearches()+ if (!recent.entries.value.length) {+ recent.hide()}}- onClickOutside(searchBarEl, hideRecentSearches)- /**- * Refers to the current suggestion that has visual focus (not DOM focus)- * and is the active descendant. This should be set to `undefined` when the- * visual focus is on the input field.- */- const selectedIdx = ref<number | undefined>(undefined)- const entries = computed(() => searchStore.recentSearches)-- const handleVerticalArrows = (event: KeyboardEvent) => {- event.preventDefault() // Prevent the cursor from moving horizontally.- const { key, altKey } = event-- showRecentSearches()- if (altKey) {- return+ const { handleKeydown, handleSelect, handleClear, recent } =+ useRecentSearches({+ focusInput,+ term: modelMedium,+ isMobile: false,+ })+ onClickOutside(searchBarEl, recent.hide)++ watch(recent.isVisible, (isVisible) => {+ if (!isVisible) {+ emit("recent-hidden")}-- // Shift selection (if Alt was not pressed with arrow keys)- let defaultValue: number- let offset: number- if (key == keycodes.ArrowUp) {- defaultValue = 0- offset = -1- } else {- defaultValue = -1- offset = 1- }- selectedIdx.value = cyclicShift(- selectedIdx.value ?? defaultValue,- offset,- 0,- entries.value.length- )- }-- const handleOtherKeys = (event: KeyboardEvent) => {- const { key } = event-- if (key === keycodes.Enter && selectedIdx.value) {- // If a recent search is selected, populate its value into the input.- modelMedium.value = entries.value[selectedIdx.value]- }-- // Hide the recent searches popover when the user presses Enter, Escape or Shift+Tab on the input.- if (- (key === keycodes.Tab && event.shiftKey) ||- ([keycodes.Escape, keycodes.Enter] as string[]).includes(key)- ) {- hideRecentSearches()- }-- selectedIdx.value = undefined // Lose visual focus from entries.- }- const handleKeydown = (event: KeyboardEvent) => {- const { key } = event-- return ([keycodes.ArrowUp, keycodes.ArrowDown] as string[]).includes(key)- ? handleVerticalArrows(event)- : handleOtherKeys(event)- }-- /* Populate the input with the clicked entry and execute the search. */- const handleSelect = (idx: number) => {- modelMedium.value = entries.value[idx]-- hideRecentSearches()- selectedIdx.value = undefined // Lose visual focus from entries.- handleSearch() // Immediately execute the search manually.- }- /* Clear all recent searches from the store. */- const handleClear = () => {- inputFieldRef.value?.focusInput()- searchStore.clearRecentSearches()- }- /* Clear a specific recent search from the store. */- const handleClearSingle = (idx: number) => {- inputFieldRef.value?.focusInput()- searchStore.clearRecentSearch(idx)- }+ })return {searchBarEl,@@ -241,19 +161,18 @@ export default defineComponent({handleSearch,modelMedium,- showRecentSearches,- hideRecentSearches,+ showRecentSearches: recent.show,+ hideRecentSearches: recent.hide,handleSearchBlur,- isRecentVisible,recentClasses,- selectedIdx,- entries,+ isRecentVisible: recent.isVisible,+ selectedIdx: recent.selectedIdx,+ entries: recent.entries,handleKeydown,handleSelect,handleClear,- handleClearSingle,}},})diff --git a/frontend/src/components/VHeader/VSearchBar/VSearchButton.vue b/frontend/src/components/VHeader/VSearchBar/VSearchButton.vueindex 70fc533f3..baef8ab2b 100644--- a/frontend/src/components/VHeader/VSearchBar/VSearchButton.vue+++ b/frontend/src/components/VHeader/VSearchBar/VSearchButton.vue@@ -13,6 +13,7 @@'border-tx bg-pink text-white hover:!bg-dark-pink': route === 'home',},]"+ v-on="$listeners"><VIcon name="search" /></VButton>diff --git a/frontend/src/components/VModal/VInputModal.vue b/frontend/src/components/VModal/VInputModal.vueindex 5896dc805..ef1eeb8c2 100644--- a/frontend/src/components/VModal/VInputModal.vue+++ b/frontend/src/components/VModal/VInputModal.vue@@ -3,9 +3,9 @@<div v-if="!isActive" class="flex w-full"><slot /></div><VTeleport v-else to="modal"><div- class="fixed inset-0 z-40 flex h-[100dvh] h-screen w-full justify-center overflow-y-auto bg-white"+ class="h-dyn-screen fixed inset-0 z-40 flex w-full justify-center overflow-y-auto bg-white">- <!-- re: disabled static element interactions rule https://github.com/WordPress/openverse/issues/2906 -->+ <!-- rule disabled because we need to handle the events from children --><!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions --><divref="dialogRef"diff --git a/frontend/src/components/VRecentSearches/VRecentSearches.vue b/frontend/src/components/VRecentSearches/VRecentSearches.vueindex 5abcff2df..93c5194ab 100644--- a/frontend/src/components/VRecentSearches/VRecentSearches.vue+++ b/frontend/src/components/VRecentSearches/VRecentSearches.vue@@ -18,7 +18,7 @@class="label-bold"size="small":aria-label="$t('recentSearches.clear.label').toString()"- @click="handleClear"+ @click="handleClear()">{{ $t("recentSearches.clear.text") }}</VButton>@@ -35,7 +35,7 @@<liv-for="(entry, idx) in entries":id="`option-${idx}`"- :key="idx"+ :key="entry"role="option"class="group/entry label-regular flex h-10 flex-row items-center gap-2 rounded-sm border-1.5 pe-1 ps-2 hover:bg-dark-charcoal-10":class="idx === selectedIdx ? 'border-pink' : 'border-tx'"@@ -51,7 +51,8 @@:label="$t('recentSearches.clearSingle.label', { entry }).toString()"class="ms-auto group-hover/entry:flex":class="{ hidden: bordered }"- @click.stop="handleClearSingle(idx)"+ @click.stop="handleClear(entry)"+ @keydown.tab.exact="handleTab(idx)"/></li><!-- eslint-enable -->@@ -112,24 +113,26 @@ export default defineComponent({},emits: {select: defineEvent<[number]>(),- clear: defineEvent(),- "clear-single": defineEvent<[number]>(),+ clear: defineEvent<[string?]>(),+ "last-tab": defineEvent(),},- setup(_, { emit }) {+ setup(props, { emit }) {const handleClick = (idx: number) => {emit("select", idx)}- const handleClear = () => {- emit("clear")+ const handleClear = (entry?: string) => {+ emit("clear", entry)}- const handleClearSingle = (idx: number) => {- emit("clear-single", idx)+ const handleTab = (idx: number) => {+ if (idx === props.entries.length - 1) {+ emit("last-tab")+ }}return {handleClick,handleClear,- handleClearSingle,+ handleTab,}},})diff --git a/frontend/src/composables/use-recent-searches.ts b/frontend/src/composables/use-recent-searches.tsnew file mode 100644index 000000000..645a684cc--- /dev/null+++ b/frontend/src/composables/use-recent-searches.ts@@ -0,0 +1,159 @@+import { computed, nextTick, ref, type Ref, watch } from "vue"++import { keycodes } from "~/constants/key-codes"+import { useSearchStore } from "~/stores/search"++import { cyclicShift } from "~/utils/math"++type VerticalArrow = typeof keycodes.ArrowUp | typeof keycodes.ArrowDown+type VerticalArrowEvent = KeyboardEvent & { key: VerticalArrow }+export const isVerticalArrowEvent = (+ event: KeyboardEvent+): event is VerticalArrowEvent => {+ return event.key === keycodes.ArrowUp || event.key === keycodes.ArrowDown+}++export const updateIndexOnVerticalArrow = (+ key: VerticalArrow,+ entriesCount: number,+ selectedIdx: number | undefined+) => {+ const defaultValue = key === keycodes.ArrowUp ? 0 : -1+ const offset = key === keycodes.ArrowUp ? -1 : 1+ return cyclicShift(selectedIdx ?? defaultValue, offset, 0, entriesCount)+}++export const useRecentSearches = ({+ focusInput,+ term,+ isMobile,+ isInputFocused,+}: {+ focusInput: () => void+ term: Ref<string>+ isMobile: boolean+ isInputFocused?: Ref<boolean> | undefined+}) => {+ const searchStore = useSearchStore()+ const isRecentVisible = ref(false)+ /**+ * Refers to the current suggestion that has visual focus (not DOM focus)+ * and is the active descendant. This should be set to `undefined` when the+ * visual focus is on the input field.+ */+ const selectedIdx = ref<number | undefined>(undefined)+ const entries = computed(() => searchStore.recentSearches)++ /**+ * Revert the search term to the existing value if the entered value is blank.+ */+ const hideRecentSearches = () => {+ isRecentVisible.value = false+ if (term.value === "" && searchStore.searchTerm !== "") {+ term.value = searchStore.searchTerm+ }+ }++ /**+ * Focus the search bar when opening the modal.+ * `nextTick` is necessary to ensure focus in Firefox+ */+ const showRecentSearches = () => {+ isRecentVisible.value = true+ nextTick(() => focusInput())+ }++ const recent = {+ isVisible: isRecentVisible,+ hide: hideRecentSearches,+ show: showRecentSearches,+ selectedIdx,+ entries,+ }++ const handleVerticalArrows = (event: VerticalArrowEvent) => {+ event.preventDefault() // Prevent the cursor from moving horizontally.+ const { key, altKey } = event+ showRecentSearches()+ if (altKey) {+ return+ }+ // Shift selection (if Alt was not pressed with arrow keys)+ selectedIdx.value = updateIndexOnVerticalArrow(+ key,+ entries.value.length,+ selectedIdx.value+ )+ }++ const shouldHideOnEvent = (event: KeyboardEvent, isMobile: boolean) => {+ // Always hide when the user presses Escape.+ if (event.key === keycodes.Escape) {+ return true+ }+ // Hide the recent searches popover when the user presses Enter or Shift+Tab on the input.+ return (+ !isMobile &&+ (event.key === keycodes.Enter ||+ (event.key === keycodes.Tab && event.shiftKey))+ )+ }++ const handleOtherKeys = (event: KeyboardEvent) => {+ const { key } = event+ if (key === keycodes.Enter && selectedIdx.value) {+ // If a recent search is selected, populate its value into the input.+ term.value = entries.value[selectedIdx.value]+ }+ if (shouldHideOnEvent(event, isMobile)) {+ hideRecentSearches()+ }+ if (+ isMobile &&+ !isRecentVisible.value &&+ isVerticalArrowEvent(event) &&+ isInputFocused+ ) {+ isInputFocused.value = false+ }+ selectedIdx.value = undefined // Lose visual focus from entries.+ }++ const handleKeydown = (event: KeyboardEvent) => {+ return isVerticalArrowEvent(event)+ ? handleVerticalArrows(event)+ : handleOtherKeys(event)+ }++ /**+ * Populate the input with the clicked entry and execute the search.+ */+ const handleSelect = (idx: number) => {+ term.value = entries.value[idx]+ hideRecentSearches()+ selectedIdx.value = undefined // Lose visual focus from entries.+ }++ /**+ * Clear recent searches from the store. Removes a single entry+ * if entry is provided, otherwise removes all recent searches.+ */+ const handleClear = (entry?: string) => {+ focusInput()+ useSearchStore().clearRecentSearches(entry)+ }++ watch(selectedIdx, (idx) => {+ if (idx !== undefined) {+ term.value = entries.value[idx]+ }+ })++ return {+ handleKeydown,+ handleSelect,+ handleClear,+ recent,+ isRecentVisible,+ }+}diff --git a/frontend/src/pages/search.vue b/frontend/src/pages/search.vueindex 29134ae2e..06ad83dd9 100644--- a/frontend/src/pages/search.vue+++ b/frontend/src/pages/search.vue@@ -66,13 +66,6 @@ export default defineComponent({const route = useRoute()const router = useRouter()- // I don't know *exactly* why this is necessary, but without it- // transitioning from the homepage to this page breaks the- // watcher in useStorage and recent searches won't be saved- // properly. It is something related to Pinia, Nuxt SSR,- // hydration and Vue reactives. Hopefully fixed in Nuxt 3.- searchStore.refreshRecentSearches()-const {searchTerm,searchType,diff --git a/frontend/src/stores/search.ts b/frontend/src/stores/search.tsindex 31b8533ef..c94d2f0c8 100644--- a/frontend/src/stores/search.ts+++ b/frontend/src/stores/search.ts@@ -143,9 +143,18 @@ export const useSearchStore = defineStore("search", {recentSearches: useStorage<string[]>("recent-searches", []),filters: deepClone(filterData as DeepWriteable<typeof filterData>),}),+ /**+ * If the server set the search term, add it to the top of the recent searches stack saved in the local storage.+ */hydrate(state) {- // @ts-expect-error https://github.com/microsoft/TypeScript/issues/43826- state.recentSearches = useStorage<string[]>("recent-searches", [])+ const entriesStored = useStorage<string[]>("recent-searches", [])+ if (state.searchTerm) {+ entriesStored.value = [+ state.searchTerm,+ ...entriesStored.value.filter((i) => i !== state.searchTerm),+ ].slice(0, parseInt(env.savedSearchCount))+ }+ state.recentSearches = entriesStored.value},getters: {filterCategories(state) {@@ -381,18 +390,14 @@ export const useSearchStore = defineStore("search", {})this.replaceFilters(newFilterData)},- /**- * This method need not exist and is only used to fix an odd- * hydration bug in the search route. After navigating from- * the homepage, the watcher in useStorage doesn't work.- */- refreshRecentSearches() {- // @ts-expect-error https://github.com/microsoft/TypeScript/issues/43826- this.recentSearches = useStorage<string[]>("recent-searches", [])+ updateRecentSearches(entries: string[]) {+ useStorage("recent-searches", entries).value = entries+ this.recentSearches = entries},/** Add a new term to the list of recent search terms */addRecentSearch(- search: string /** A search term to add to the saved list.*/+ /** A search term to add to the saved list.*/+ search: string) {/*** Add the latest search to the top of the stack,@@ -400,16 +405,18 @@ export const useSearchStore = defineStore("search", {* the max count, and removing existing occurrences of the* latest search term, if there are any.*/- this.recentSearches = [+ const entries = [search,...this.recentSearches.filter((i) => i !== search),].slice(0, parseInt(env.savedSearchCount))+ // directly setting value to this.recentSearches does not update the storage and watchers+ this.updateRecentSearches(entries)},- clearRecentSearches() {- this.recentSearches = []- },- clearRecentSearch(idx: number) {- this.recentSearches.splice(idx, 1)+ clearRecentSearches(entry?: string) {+ const entries = entry+ ? this.recentSearches.filter((s) => s !== entry)+ : []+ this.updateRecentSearches(entries)},/*** Initial filters do not include the provider filters. We create the provider filters objectdiff --git a/frontend/test/playwright/e2e/mobile-menu.spec.ts b/frontend/test/playwright/e2e/mobile-menu.spec.tsindex 14c3379f5..780442541 100644--- a/frontend/test/playwright/e2e/mobile-menu.spec.ts+++ b/frontend/test/playwright/e2e/mobile-menu.spec.ts@@ -1,4 +1,4 @@-import { test, expect } from "@playwright/test"+import { test, expect, type Page } from "@playwright/test"import {goToSearchTerm,@@ -8,37 +8,51 @@ import {preparePageForTests,} from "~~/test/playwright/utils/navigation"import breakpoints from "~~/test/playwright/utils/breakpoints"+import { t } from "~~/test/playwright/utils/i18n"++const contentSettingsModal = async (page: Page) =>+ page.getByRole("dialog", { name: t("header.aria.menu") })test.describe.configure({ mode: "parallel" })-test.describe("mobile menu", () => {+breakpoints.describeXs(() => {test.beforeEach(async ({ page }) => {- await preparePageForTests(page, "sm")+ await preparePageForTests(page, "xs")})- breakpoints.describeSm(() => {- test("Can open filters menu on mobile at least twice", async ({ page }) => {- await goToSearchTerm(page, "cat", { searchType: "all", mode: "SSR" })-- await filters.open(page)- expect(await isDialogOpen(page)).toBe(true)- await filters.close(page)-- await filters.open(page)- expect(await isDialogOpen(page)).toBe(true)- await filters.close(page)- expect(await isDialogOpen(page)).toBe(false)- })-- test("Can open mobile menu at least twice", async ({ page }) => {- await goToSearchTerm(page, "cat")- await searchTypes.open(page)- expect(await isDialogOpen(page)).toBe(true)- await searchTypes.close(page)-- await searchTypes.open(page)- expect(await isDialogOpen(page)).toBe(true)- await searchTypes.close(page)- expect(await isDialogOpen(page)).toBe(false)- })+ test("Can open filters menu on mobile at least twice", async ({ page }) => {+ await goToSearchTerm(page, "cat", { searchType: "all", mode: "SSR" })++ await filters.open(page)+ expect(await isDialogOpen(page)).toBe(true)+ await filters.close(page)++ await filters.open(page)+ expect(await isDialogOpen(page)).toBe(true)+ await filters.close(page)+ expect(await isDialogOpen(page)).toBe(false)+ })++ test("Can open mobile menu at least twice", async ({ page }) => {+ await goToSearchTerm(page, "cat")+ await searchTypes.open(page)+ expect(await isDialogOpen(page)).toBe(true)+ await searchTypes.close(page)++ await searchTypes.open(page)+ expect(await isDialogOpen(page)).toBe(true)+ await searchTypes.close(page)+ expect(await isDialogOpen(page)).toBe(false)+ })++ test("Can open content settings with keyboard", async ({ page }) => {+ await goToSearchTerm(page, "galah")+ for (let i = 0; i < 4; i++) {+ await page.keyboard.press("Tab")+ }+ await page.keyboard.press("Enter")+ await expect(await contentSettingsModal(page)).toBeVisible()++ await page.keyboard.press("Escape")+ await expect(await contentSettingsModal(page)).toBeHidden()})})diff --git a/frontend/test/playwright/e2e/recent-searches.spec.ts b/frontend/test/playwright/e2e/recent-searches.spec.tsindex 705f94bf4..739a3df4d 100644--- a/frontend/test/playwright/e2e/recent-searches.spec.ts+++ b/frontend/test/playwright/e2e/recent-searches.spec.ts@@ -2,19 +2,53 @@ import { expect, test, type Page } from "@playwright/test"import {goToSearchTerm,+ isPageDesktop,preparePageForTests,searchFromHeader,+ sleep,} from "~~/test/playwright/utils/navigation"import { getH1 } from "~~/test/playwright/utils/components"+import { t } from "~~/test/playwright/utils/i18n"+import breakpoints from "~~/test/playwright/utils/breakpoints"test.describe.configure({ mode: "parallel" })-test.beforeEach(async ({ page }) => {- await preparePageForTests(page, "xl")- // We are first navigating to search because the recent searches feature has- // not yet been implemented on the homepage.- await goToSearchTerm(page, "galah")-})+const clearRecentLabel = t("recentSearches.clear.label")+const recentLabel = t("recentSearches.heading")+const noRecentLabel = t("recentSearches.none")++const getRecentSearchesText = async (page: Page) =>+ await page.locator('[data-testid="recent-searches"]').textContent()++const clearButton = async (page: Page) =>+ page.locator(`[aria-label="${clearRecentLabel}"]`)+const clickClear = async (page: Page) => (await clearButton(page)).click()++const recentSearches = (page: Page) =>+ page.locator('[data-testid="recent-searches"]')++const navigateBackToSkipToContent = async (page: Page) => {+ const isSkipToContent = async () =>+ await page.evaluate(+ () =>+ document.activeElement?.textContent?.trim() === "Skip to content" &&+ document.activeElement?.tagName === "A"+ )+ while (!(await isSkipToContent())) {+ await page.keyboard.press("Shift+Tab")+ }+}++const tabToSearchbar = async (page: Page) => {+ if (isPageDesktop(page)) {+ await navigateBackToSkipToContent(page)+ } else {+ await page.keyboard.press("Tab")+ }+ for (let i = 0; i < 2; i++) {+ await page.keyboard.press("Tab")+ }+}const executeSearches = async (page: Page) => {const searches = ["honey", "galah"] // in that order@@ -25,49 +59,106 @@ const executeSearches = async (page: Page) => {return searches}-test("shows recent searches in reverse chronological order", async ({- page,-}) => {- const searches = await executeSearches(page)- const recentList = await page- .locator(`[aria-label="Recent searches"]`)- .locator('[role="option"]')- .allTextContents()- searches.reverse().forEach((term, idx) => {- expect(recentList[idx].trim()).toEqual(term)+breakpoints.describeMobileXsAndDesktop(({ breakpoint }) => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, breakpoint)+ // We are first navigating to search because the recent searches feature has+ // not yet been implemented on the homepage.+ await goToSearchTerm(page, "galah")})-})-test("clicking takes user to that search", async ({ page }) => {- await executeSearches(page)- expect(page.url()).toContain("?q=galah")- // Click on the input to open the Recent searches- await page.locator('input[type="search"]').click()- await page- .locator(`[aria-label="Recent searches"]`)- .locator('[id="option-1"]')- .click()- await expect(getH1(page, /honey/i)).toBeVisible()- expect(page.url()).toContain("?q=honey")-})+ test("recent searches shows message when blank", async ({ page }) => {+ // Click on the input to open the Recent searches+ await page.locator('input[type="search"]').click()+ await clickClear(page)-test("recent searches shows message when blank", async ({ page }) => {- // Click on the input to open the Recent searches- await page.locator('input[type="search"]').click()+ const recentSearchesText = await getRecentSearchesText(page)+ expect(recentSearchesText).toContain(noRecentLabel)+ })- const recentSearchesText = await page- .locator('[data-testid="recent-searches"]')- .textContent()- expect(recentSearchesText).toContain("No recent searches to show.")-})+ test("shows recent searches in reverse chronological order", async ({+ page,+ }) => {+ const searches = await executeSearches(page)+ const recentList = await page+ .locator(`[aria-label="${recentLabel}"]`)+ .locator('[role="option"]')+ .allTextContents()+ searches.reverse().forEach((term, idx) => {+ expect(recentList[idx].trim()).toEqual(term)+ })+ })++ test("clicking takes user to that search", async ({ page }) => {+ await executeSearches(page)+ expect(page.url()).toContain("?q=galah")+ // Click on the input to open the Recent searches+ await page.locator('input[type="search"]').click()+ await page+ .locator(`[aria-label="${recentLabel}"]`)+ .getByRole("option", { name: "honey" })+ .click()+ await expect(getH1(page, /honey/i)).toBeVisible()+ expect(page.url()).toContain("?q=honey")+ })-test("clicking Clear clears the recent searches", async ({ page }) => {- await executeSearches(page)- // Click on the input to open the Recent searches- await page.locator('input[type="search"]').click()- await page.locator('[aria-label="Clear recent searches"]').click()- const recentSearchesText = await page- .locator('[data-testid="recent-searches"]')- .textContent()- expect(recentSearchesText).toContain("No recent searches to show.")+ test("clicking Clear clears the recent searches", async ({ page }) => {+ await executeSearches(page)+ // Click on the input to open the Recent searches+ await page.locator('input[type="search"]').click()+ await clickClear(page)+ await expect(await clearButton(page)).toBeHidden()++ const recentSearchesText = await getRecentSearchesText(page)+ expect(recentSearchesText).toContain(noRecentLabel)+ })++ test("can open recent searches with keyboard", async ({ page }) => {+ await executeSearches(page)+ await tabToSearchbar(page)+ await page.keyboard.press("ArrowDown")++ await expect(recentSearches(page)).toBeVisible()+ })++ test("can close the recent searches with escape key", async ({ page }) => {+ await executeSearches(page)+ await tabToSearchbar(page)++ await page.keyboard.press("ArrowDown")+ await expect(recentSearches(page)).toBeVisible()++ await page.keyboard.press("Escape")+ await sleep(300)+ await expect(recentSearches(page)).toBeHidden()+ })++ test("can navigate out of the recent searches with tab key", async ({+ page,+ }) => {+ const searches = await executeSearches(page)+ await tabToSearchbar(page)++ await page.keyboard.press("ArrowDown")+ await expect(recentSearches(page)).toBeVisible()++ for (let i = 0; i < searches.length + 3; i++) {+ await page.keyboard.press("Tab")+ }+ await expect(recentSearches(page)).toBeHidden()+ })++ test("can navigate out of the recent searches using shift tab", async ({+ page,+ }) => {+ await executeSearches(page)+ await tabToSearchbar(page)++ await page.keyboard.press("ArrowDown")+ await expect(recentSearches(page)).toBeVisible()++ await page.keyboard.press("Shift+Tab")+ await page.keyboard.press("Shift+Tab")+ await expect(recentSearches(page)).toBeHidden()+ })})diff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-md-linux.png b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-md-linux.pngindex 2130a1f10..aa285aecc 100644Binary files a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-md-linux.png and b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-md-linux.png differdiff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-sm-linux.png b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-sm-linux.pngindex 4b5fce0af..3461eec6a 100644Binary files a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-sm-linux.png and b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-sm-linux.png differdiff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-xs-linux.png b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-xs-linux.pngindex 9d1e8d8f7..17db5205e 100644Binary files a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-xs-linux.png and b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-ltr-xs-linux.png differdiff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-md-linux.png b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-md-linux.pngindex 0b238d464..9441eae30 100644Binary files a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-md-linux.png and b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-md-linux.png differdiff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-sm-linux.png b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-sm-linux.pngindex 0ce24f8d3..f89e62894 100644Binary files a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-sm-linux.png and b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-sm-linux.png differdiff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-xs-linux.png b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-xs-linux.pngindex 9722dbf6e..881ffdd6b 100644Binary files a/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-xs-linux.png and b/frontend/test/playwright/visual-regression/components/header.spec.ts-snapshots/searchbar-active-rtl-xs-linux.png differ