Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Add UI for recent search results (#1867)

Dhruv Bhanushali83dbe5dfb962
diff --git a/feat/feature-flags.json b/feat/feature-flags.json
index df4a6767c..2bdccd1c6 100644
--- a/feat/feature-flags.json
+++ b/feat/feature-flags.json
@@ -13,17 +13,9 @@
"staging": "switchable",
"production": "disabled"
},
- "description": "Toggle the new header.",
+ "description": "Toggle the new header, including recent searches.",
"defaultState": "off"
},
- "recent_searches": {
- "status": {
- "staging": "switchable",
- "production": "disabled"
- },
- "description": "Save and display the user's recent searches.",
- "defaultState": "on"
- },
"feat_disabled": {
"status": "disabled",
"description": "Will always be disabled"
diff --git a/src/components/VHeader/VSearchBar/VSearchBar.vue b/src/components/VHeader/VSearchBar/VSearchBar.vue
index d550f31ee..b30e182a3 100644
--- a/src/components/VHeader/VSearchBar/VSearchBar.vue
+++ b/src/components/VHeader/VSearchBar/VSearchBar.vue
@@ -1,42 +1,77 @@
<template>
- <form
- class="search-bar group flex flex-row items-center rounded-sm border-tx bg-white"
- :class="{ 'h-[57px] md:h-[69px]': size === 'standalone' }"
- @submit.prevent="handleSearch"
- >
- <VInputField
- :placeholder="placeholder || $t('hero.search.placeholder')"
- v-bind="$attrs"
- class="search-field flex-grow focus:border-pink"
- :class="[route === 'home' ? 'border-tx' : 'border-dark-charcoal-20']"
- :label-text="
- $t('search.search-bar-label', { openverse: 'Openverse' }).toString()
- "
- :connection-sides="['end']"
- :size="size"
- field-id="search-bar"
- type="search"
- name="q"
- :model-value="searchText"
- @update:modelValue="updateSearchText"
+ <div ref="searchBarEl" class="relative">
+ <form
+ class="search-bar group flex flex-row items-center rounded-sm border-tx bg-white"
+ :class="{ 'h-[57px] md:h-[69px]': size === 'standalone' }"
+ @submit.prevent="handleSearch"
>
- <!-- @slot Extra information such as loading message or result count goes here. -->
- <slot />
- </VInputField>
- <VSearchButton type="submit" :size="size" :route="route" />
- </form>
+ <VInputField
+ v-bind="$attrs"
+ v-model="modelMedium"
+ :placeholder="placeholder || $t('hero.search.placeholder')"
+ class="search-field flex-grow focus:border-pink"
+ :class="[route === 'home' ? 'border-tx' : 'border-dark-charcoal-20']"
+ :label-text="
+ $t('search.search-bar-label', { openverse: 'Openverse' }).toString()
+ "
+ :connection-sides="['end']"
+ :size="size"
+ field-id="search-bar"
+ type="search"
+ autocomplete="off"
+ name="q"
+ role="combobox"
+ aria-autocomplete="none"
+ :aria-expanded="isRecentVisible"
+ aria-controls="recent-searches-list"
+ :aria-activedescendant="
+ selectedIdx !== undefined ? `option-${selectedIdx}` : undefined
+ "
+ @focus="handleFocus"
+ @keydown="handleKeydown"
+ >
+ <!-- @slot Extra information such as loading message or result count goes here. -->
+ <slot />
+ </VInputField>
+ <VSearchButton type="submit" :size="size" :route="route" />
+ </form>
+ <VRecentSearches
+ v-show="isNewHeaderEnabled && isRecentVisible"
+ :selected-idx="selectedIdx"
+ :entries="entries"
+ class="absolute inset-x-0 lg:flex"
+ :class="recentClasses"
+ @select="handleSelect"
+ @clear="handleClear"
+ />
+ </div>
</template>
<script lang="ts">
-import { computed, defineComponent, PropType } from '@nuxtjs/composition-api'
+import {
+ computed,
+ defineComponent,
+ PropType,
+ ref,
+} from '@nuxtjs/composition-api'
+
+import { onClickOutside } from '@vueuse/core'
import { useMatchHomeRoute } from '~/composables/use-match-routes'
import { defineEvent } from '~/types/emits'
+import { useSearchStore } from '~/stores/search'
+import { useFeatureFlagStore } from '~/stores/feature-flag'
+
+import { keycodes } from '~/constants/key-codes'
+
+import { cyclicShift } from '~/utils/math'
+
import VInputField, {
FIELD_SIZES,
} from '~/components/VInputField/VInputField.vue'
import VSearchButton from '~/components/VHeader/VSearchBar/VSearchButton.vue'
+import VRecentSearches from '~/components/VRecentSearches/VRecentSearches.vue'
/**
* Displays a text field for a search query and is attached to an action button
@@ -45,7 +80,7 @@ import VSearchButton from '~/components/VHeader/VSearchBar/VSearchButton.vue'
*/
export default defineComponent({
name: 'VSearchBar',
- components: { VInputField, VSearchButton },
+ components: { VRecentSearches, VInputField, VSearchButton },
inheritAttrs: false,
props: {
/**
@@ -73,27 +108,138 @@ export default defineComponent({
submit: defineEvent(),
},
setup(props, { emit }) {
+ const searchBarEl = ref<HTMLElement | null>(null)
+
const { matches: isHomeRoute } = useMatchHomeRoute()
const route = computed(() => {
return isHomeRoute?.value ? 'home' : props.is404 ? '404' : undefined
})
- const searchText = computed(() => props.value)
-
- const updateSearchText = (val: string) => {
- emit('input', val)
- }
+ const modelMedium = computed<string>({
+ get: () => props.value ?? '',
+ set: (value: string) => {
+ emit('input', value)
+ },
+ })
const handleSearch = () => {
emit('submit')
}
+ /* Focus */
+ const handleFocus = () => {
+ isRecentVisible.value = true
+ }
+ const handleBlur = () => {
+ isRecentVisible.value = false
+ }
+ onClickOutside(searchBarEl, handleBlur)
+
+ /* Recent searches */
+ const featureFlagStore = useFeatureFlagStore()
+ const isNewHeaderEnabled = featureFlagStore.isOn('new_header')
+
+ const searchStore = useSearchStore()
+
+ const isRecentVisible = ref(false)
+ const recentClasses = computed(() => {
+ // Calculated by adding 8px to all heights defined in `VInputField.vue`.
+ const FIELD_OFFSETS = {
+ small: 'top-12',
+ medium: 'top-14',
+ large: 'top-16',
+ standalone: 'top-[65px] md:top-[77px]',
+ } as const
+ return FIELD_OFFSETS[props.size]
+ })
+ /**
+ * 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
+
+ // Show the recent searches.
+ isRecentVisible.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
+ )
+ }
+
+ 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]
+
+ if (([keycodes.Escape, keycodes.Enter] as string[]).includes(key))
+ // Hide the recent searches.
+ isRecentVisible.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) => {
+ modelMedium.value = entries.value[idx]
+
+ isRecentVisible.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()
+ }
+
return {
+ searchBarEl,
+
handleSearch,
route,
- searchText,
- updateSearchText,
+ modelMedium,
+
+ handleFocus,
+ handleBlur,
+
+ isNewHeaderEnabled,
+ isRecentVisible,
+ recentClasses,
+ selectedIdx,
+ entries,
+
+ handleKeydown,
+ handleSelect,
+ handleClear,
}
},
})
diff --git a/src/components/VHeader/VSearchBar/meta/VSearchBar.stories.mdx b/src/components/VHeader/VSearchBar/meta/VSearchBar.stories.mdx
index c5d36a864..6162105b0 100644
--- a/src/components/VHeader/VSearchBar/meta/VSearchBar.stories.mdx
+++ b/src/components/VHeader/VSearchBar/meta/VSearchBar.stories.mdx
@@ -23,7 +23,9 @@ import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
export const Template = (args) => ({
template: `
<VSearchBar v-bind="args" v-on="args">
- 12,345 results
+ <span class="info text-xs font-semibold text-dark-charcoal-70 mx-4 whitespace-nowrap group-hover:text-dark-charcoal group-focus:text-dark-charcoal">
+ 12,345 results
+ </span>
</VSearchBar>`,
components: { VSearchBar },
setup() {
@@ -56,11 +58,13 @@ button is clicked.
The recommended way to use it is with `v-model` mapping to a `String`
representing the search query.
-export const vModelTemplate = () => ({
+export const vModelTemplate = (args) => ({
template: `
<div>
- <VSearchBar v-model="text" size="small">
- {{ text.length }}
+ <VSearchBar v-model="text" size="standalone" v-on="args">
+ <span class="info text-xs font-semibold text-dark-charcoal-70 mx-4 whitespace-nowrap group-hover:text-dark-charcoal group-focus:text-dark-charcoal">
+ {{ text.length }} chars
+ </span>
</VSearchBar>
{{ text }}
</div>
@@ -71,6 +75,9 @@ export const vModelTemplate = () => ({
text: 'Hello, World!',
}
},
+ setup() {
+ return { args }
+ },
})
<Canvas>
diff --git a/src/components/VRecentSearches/VRecentSearches.vue b/src/components/VRecentSearches/VRecentSearches.vue
new file mode 100644
index 000000000..ee9ad928a
--- /dev/null
+++ b/src/components/VRecentSearches/VRecentSearches.vue
@@ -0,0 +1,102 @@
+<template>
+ <div
+ class="flex flex-col gap-1 rounded-sm border border-dark-charcoal-20 bg-white p-4 shadow-el-2"
+ data-testid="recent-searches"
+ >
+ <div class="flex flex-row items-center justify-between py-2">
+ <!-- Left margin to align with the text of recent searches. -->
+ <span class="category mx-2 my-1">
+ {{ $t('recent-searches.heading') }}
+ </span>
+ <VButton
+ v-show="entries.length"
+ variant="plain"
+ size="small"
+ class="caption-bold hover:underline"
+ :aria-label="$t('recent-searches.clear.label').toString()"
+ @click="handleClear"
+ >
+ {{ $t('recent-searches.clear.text') }}
+ </VButton>
+ </div>
+
+ <ul
+ v-if="entries.length"
+ id="recent-searches-list"
+ role="listbox"
+ :aria-label="$t('recent-searches.heading').toString()"
+ >
+ <!-- eslint-disable vuejs-accessibility/interactive-supports-focus Combobox descendants only have visual focus. -->
+ <!-- eslint-disable vuejs-accessibility/click-events-have-key-events Key events handled by input field of combobox. -->
+ <li
+ v-for="(entry, idx) in entries"
+ :id="`option-${idx}`"
+ :key="idx"
+ role="option"
+ class="description-regular my-1 rounded-sm border-1.5 p-2 hover:bg-dark-charcoal-10"
+ :class="idx === selectedIdx ? 'border-pink' : 'border-tx'"
+ :aria-selected="idx === selectedIdx"
+ @click="handleClick(idx)"
+ >
+ {{ entry }}
+ </li>
+ <!-- eslint-enable -->
+ </ul>
+ <span v-else class="description-regular mx-2 my-3">
+ {{ $t('recent-searches.none') }}
+ </span>
+
+ <span class="caption-regular mx-2 my-3 text-dark-charcoal-70">
+ {{ $t('recent-searches.disclaimer') }}
+ </span>
+ </div>
+</template>
+
+<script lang="ts">
+import { defineComponent, type PropType } from '@nuxtjs/composition-api'
+
+import { defineEvent } from '~/types/emits'
+
+import VButton from '~/components/VButton.vue'
+
+/**
+ * List the recent searches of the user allowing them to go back to a previous
+ * search. These searches are saved locally and never shared with the server.
+ */
+export default defineComponent({
+ name: 'VRecentSearches',
+ components: { VButton },
+ props: {
+ /**
+ * the list of saved past searches
+ */
+ entries: {
+ type: Array as PropType<string[]>,
+ default: () => [],
+ },
+ /**
+ * the index of the currently selected entry
+ */
+ selectedIdx: {
+ type: Number,
+ },
+ },
+ emits: {
+ select: defineEvent<[number]>(),
+ clear: defineEvent(),
+ },
+ setup(_, { emit }) {
+ const handleClick = (idx: number) => {
+ emit('select', idx)
+ }
+ const handleClear = () => {
+ emit('clear')
+ }
+
+ return {
+ handleClick,
+ handleClear,
+ }
+ },
+})
+</script>
diff --git a/src/components/VRecentSearches/meta/VRecentSearches.stories.mdx b/src/components/VRecentSearches/meta/VRecentSearches.stories.mdx
new file mode 100644
index 000000000..e47845d94
--- /dev/null
+++ b/src/components/VRecentSearches/meta/VRecentSearches.stories.mdx
@@ -0,0 +1,52 @@
+import {
+ ArgsTable,
+ Description,
+ Meta,
+ Canvas,
+ Story,
+} from '@storybook/addon-docs'
+
+import VRecentSearches from '~/components/VRecentSearches/VRecentSearches.vue'
+
+<Meta
+ title="Components/VRecentSearches"
+ component={VRecentSearches}
+ argTypes={{
+ select: {
+ action: 'select',
+ },
+ clear: {
+ action: 'clear',
+ },
+ }}
+/>
+
+export const Template = (args) => ({
+ template: `
+ <VRecentSearches v-bind="args" v-on="args" />`,
+ components: { VRecentSearches },
+ setup() {
+ return { args }
+ },
+})
+
+# VRecentSearches
+
+<Description of={VRecentSearches} />
+
+<ArgsTable of={VRecentSearches} />
+
+<Canvas>
+ <Story
+ name="Default"
+ args={{
+ entries: ['addition', 'subtraction', 'multiplication', 'division'],
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
+
+<Canvas>
+ <Story name="No history">{Template.bind({})}</Story>
+</Canvas>
diff --git a/src/locales/en.json b/src/locales/en.json
index 9d6734461..1c8c1b63c 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -677,5 +677,14 @@
},
"language": {
"language": "Language"
+ },
+ "recent-searches": {
+ "heading": "Recent searches",
+ "clear": {
+ "text": "Clear",
+ "label": "Clear recent searches"
+ },
+ "none": "No recent searches to show.",
+ "disclaimer": "Openverse does not store your recent searches, this information is kept locally in your browser."
}
}
diff --git a/src/stores/search.ts b/src/stores/search.ts
index 0f09b74e4..06ca74dba 100644
--- a/src/stores/search.ts
+++ b/src/stores/search.ts
@@ -186,7 +186,7 @@ export const useSearchStore = defineStore('search', {
) {
// No-op if feature isn't enabled
const featureFlagStore = useFeatureFlagStore()
- const saveRecentSearches = featureFlagStore.isOn('recent_searches')
+ const saveRecentSearches = featureFlagStore.isOn('new_header')
if (!saveRecentSearches) {
return
}
diff --git a/src/utils/math.ts b/src/utils/math.ts
index dea923a8f..3a172b1f8 100644
--- a/src/utils/math.ts
+++ b/src/utils/math.ts
@@ -65,3 +65,21 @@ export const bezier = (ctrlPts: Point[], pointCount: number): number[] => {
}
return bezierPoints
}
+
+/**
+ * Shift the given value by the given offset while remaining in the range
+ * specified by the params `min` and `max`.
+ *
+ * @param value - the number to shift
+ * @param offset - the amount by which to shift `value`
+ * @param min - the lower bound of the limiting range
+ * @param max - the upper bound of the limiting range
+ */
+export const cyclicShift = (
+ value: number,
+ offset: number,
+ min: number,
+ max: number
+): number => {
+ return (value + offset + max - min) % (max - min)
+}
diff --git a/tailwind.config.js b/tailwind.config.js
index cfa5e21d7..a0b3fb119 100644
--- a/tailwind.config.js
+++ b/tailwind.config.js
@@ -215,6 +215,7 @@ module.exports = {
boxShadow: {
ring: 'inset 0 0 0 1px white',
'ring-1.5': 'inset 0 0 0 1.5px white',
+ 'el-2': '0 0.125rem 0.25rem rgba(0, 0, 0, 0.1)',
},
typography: (theme) => ({
DEFAULT: {
diff --git a/test/playwright/e2e/recent-searches.spec.ts b/test/playwright/e2e/recent-searches.spec.ts
new file mode 100644
index 000000000..e95c396e4
--- /dev/null
+++ b/test/playwright/e2e/recent-searches.spec.ts
@@ -0,0 +1,61 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import {
+ enableNewHeader,
+ searchFromHeader,
+} from '~~/test/playwright/utils/navigation'
+
+test.describe.configure({ mode: 'parallel' })
+
+test.beforeEach(async ({ page }) => {
+ await enableNewHeader(page)
+
+ // We are first navigating to search because the recent searches feature has
+ // not yet been implemented on the homepage.
+ await page.goto('/search?q=galah')
+})
+
+const executeSearches = async (page: Page) => {
+ const searches = ['honey', 'galah'] // in that order
+ for (const term of searches) await searchFromHeader(page, term)
+ 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)
+ })
+})
+
+test('clicking takes user to that search', async ({ page }) => {
+ await executeSearches(page)
+ expect(page.url()).toContain('?q=galah')
+ await page
+ .locator(`[aria-label="Recent searches"]`)
+ .locator('[id="option-1"]')
+ .click()
+ expect(page.url()).toContain('?q=honey')
+})
+
+test('recent searches shows message when blank', async ({ page }) => {
+ 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)
+ 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.')
+})
diff --git a/test/unit/specs/components/VHeader/SearchBar/search-bar.spec.js b/test/unit/specs/components/VHeader/SearchBar/search-bar.spec.js
index 2bdc07835..76fb26aa0 100644
--- a/test/unit/specs/components/VHeader/SearchBar/search-bar.spec.js
+++ b/test/unit/specs/components/VHeader/SearchBar/search-bar.spec.js
@@ -1,5 +1,7 @@
import { render, screen } from '@testing-library/vue'
+import { createPinia, PiniaVuePlugin } from '~~/test/unit/test-utils/pinia'
+
import { useMatchHomeRoute } from '~/composables/use-match-routes'
import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
@@ -11,6 +13,13 @@ jest.mock('~/composables/use-match-routes', () => ({
const sizes = ['small', 'medium', 'large', 'standalone']
const defaultPlaceholder = 'Enter search query'
+const configureVue = (vue) => {
+ vue.use(PiniaVuePlugin)
+ return {
+ pinia: createPinia(),
+ }
+}
+
describe('VSearchBar', () => {
let options
beforeEach(() => {
@@ -31,7 +40,7 @@ describe('VSearchBar', () => {
(size) => {
useMatchHomeRoute.mockImplementation(() => false)
options.props.size = size
- render(VSearchBar, options)
+ render(VSearchBar, options, configureVue)
const inputElement = screen.getByPlaceholderText(defaultPlaceholder)
@@ -46,7 +55,7 @@ describe('VSearchBar', () => {
(size) => {
useMatchHomeRoute.mockImplementation(() => false)
options.props.size = size
- render(VSearchBar, options)
+ render(VSearchBar, options, configureVue)
const btnElement = screen.getByLabelText('search.search')
@@ -60,7 +69,7 @@ describe('VSearchBar', () => {
it('should default to hero.search.placeholder', () => {
delete options.props.placeholder
- render(VSearchBar, options)
+ render(VSearchBar, options, configureVue)
expect(
screen.queryByPlaceholderText('hero.search.placeholder')
).not.toBeNull()
@@ -69,7 +78,7 @@ describe('VSearchBar', () => {
it('should use the prop when provided', () => {
const placeholder = 'This is a different placeholder from the default'
options.props.placeholder = placeholder
- render(VSearchBar, options)
+ render(VSearchBar, options, configureVue)
expect(screen.queryByPlaceholderText(placeholder)).not.toBeNull()
})
})
diff --git a/test/unit/specs/stores/search-store.spec.js b/test/unit/specs/stores/search-store.spec.js
index 7568847a1..8a9706574 100644
--- a/test/unit/specs/stores/search-store.spec.js
+++ b/test/unit/specs/stores/search-store.spec.js
@@ -442,7 +442,7 @@ describe('Search Store', () => {
it('are saved, without duplication and not exceeding the limit.', () => {
const searchStore = useSearchStore()
const featureFlagStore = useFeatureFlagStore()
- featureFlagStore.toggleFeature('recent_searches', 'on')
+ featureFlagStore.toggleFeature('new_header', 'on')
searchStore.setSearchTerm('boop')
searchStore.setSearchTerm('bar')
@@ -464,7 +464,7 @@ describe('Search Store', () => {
it('can be cleared', () => {
const searchStore = useSearchStore()
const featureFlagStore = useFeatureFlagStore()
- featureFlagStore.toggleFeature('recent_searches', 'on')
+ featureFlagStore.toggleFeature('new_header', 'on')
// Clear up front in case of any preserved searches
searchStore.clearRecentSearches()
diff --git a/tsconfig.json b/tsconfig.json
index b2c889395..53e88d9b2 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -66,6 +66,7 @@
"src/components/VLogoLoader/**.vue",
"src/components/VMediaInfo/**.vue",
"src/components/VMediaTag/**.vue",
+ "src/components/VRecentSearches/**.vue",
"src/components/VSkeleton/**.vue",
"src/components/VTabs/**.vue",