Skip to content

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

Refactor SearchTypePopover desktop header (#1842)

Olga Bulat38acffaf8bdc
diff --git a/src/components/VContentSwitcher/VSearchTypePopover.vue b/src/components/VContentSwitcher/VSearchTypePopover.vue
index 8b11b3461..40de652bf 100644
--- a/src/components/VContentSwitcher/VSearchTypePopover.vue
+++ b/src/components/VContentSwitcher/VSearchTypePopover.vue
@@ -10,35 +10,19 @@
<VSearchTypeButton
:a11y-props="a11yProps"
aria-controls="content-switcher-popover"
- :active-item="activeItem"
- :class="{
- '!border-tx': isInSearchBar,
- '!bg-white group-hover:!border-dark-charcoal-20 group-hover:focus:!border-tx':
- isInSearchBar && !a11yProps['aria-expanded'],
- }"
- :type="placement"
/>
</template>
<VSearchTypes
id="content-switcher-popover"
size="medium"
- :active-item="activeItem"
- :use-links="placement === 'header'"
- @select="selectItem"
+ :use-links="true"
+ @select="closePopover"
/>
</VPopover>
</template>
<script lang="ts">
-import {
- computed,
- defineComponent,
- PropType,
- ref,
-} from '@nuxtjs/composition-api'
-
-import type { SearchType } from '~/constants/media'
-import { defineEvent } from '~/types/emits'
+import { defineComponent, ref } from '@nuxtjs/composition-api'
import VPopover from '~/components/VPopover/VPopover.vue'
import VSearchTypeButton from '~/components/VContentSwitcher/VSearchTypeButton.vue'
@@ -49,55 +33,21 @@ import checkIcon from '~/assets/icons/checkmark.svg'
export default defineComponent({
name: 'VSearchTypePopover',
components: {
- VSearchTypeButton,
VPopover,
+ VSearchTypeButton,
VSearchTypes,
},
- model: {
- prop: 'activeItem',
- event: 'select',
- },
- props: {
- activeItem: {
- type: String as PropType<SearchType>,
- required: true,
- },
- placement: {
- type: String as PropType<'header' | 'searchbar'>,
- default: 'header',
- },
- },
- emits: {
- select: defineEvent<SearchType>(),
- },
- setup(props, { emit }) {
- const contentMenuPopover = ref<HTMLElement | null>(null)
-
- /**
- * When in the searchbar, content switcher button has a border when the
- * search bar group is hovered on.
- */
- const isInSearchBar = computed(() => props.placement === 'searchbar')
-
- /**
- * Only the contentMenuPopover needs to be closed programmatically
- */
- const closeMenu = () => {
- if (contentMenuPopover.value) {
- contentMenuPopover.value.close()
- }
- }
+ setup() {
+ const contentMenuPopover = ref<InstanceType<typeof VPopover> | null>(null)
- const selectItem = (item: SearchType) => {
- emit('select', item)
+ const closePopover = () => {
+ contentMenuPopover.value?.close()
}
return {
checkIcon,
- selectItem,
+ closePopover,
contentMenuPopover,
- isInSearchBar,
- closeMenu,
}
},
})
diff --git a/src/components/VContentSwitcher/VSearchTypes.vue b/src/components/VContentSwitcher/VSearchTypes.vue
index 3e85d79f4..e11057d73 100644
--- a/src/components/VContentSwitcher/VSearchTypes.vue
+++ b/src/components/VContentSwitcher/VSearchTypes.vue
@@ -29,17 +29,21 @@
:item-id="idx"
:icon="content.icons[item]"
:use-links="useLinks"
- :selected="item === activeItem"
- @click="handleClick(item)"
+ :selected="isActive(item)"
+ @click="selectItem(item)"
/>
</div>
</VItemGroup>
</template>
<script lang="ts">
-import { computed, defineComponent, PropType } from '@nuxtjs/composition-api'
+import {
+ computed,
+ defineComponent,
+ type PropType,
+} from '@nuxtjs/composition-api'
-import type { SearchType } from '~/constants/media'
import useSearchType from '~/composables/use-search-type'
+import type { SearchType } from '~/constants/media'
import { defineEvent } from '~/types/emits'
import VItemGroup from '~/components/VItemGroup/VItemGroup.vue'
@@ -57,10 +61,9 @@ export default defineComponent({
type: String as PropType<'small' | 'medium'>,
default: 'small',
},
- activeItem: {
- type: String as PropType<SearchType>,
- required: true,
- },
+ /**
+ * Whether to use buttons for search type selection, or links to the specific search type search for the items.
+ */
useLinks: {
type: Boolean,
default: true,
@@ -71,6 +74,9 @@ export default defineComponent({
},
setup(props, { emit }) {
const content = useSearchType()
+ const bordered = computed(() => props.size === 'small')
+
+ const isActive = (item: SearchType) => item === content.activeType.value
const contentTypeGroups = computed(() => {
const base = [
@@ -90,15 +96,17 @@ export default defineComponent({
return base
})
- const bordered = computed(() => props.size === 'small')
- const handleClick = (item) => {
+ const selectItem = (item: SearchType) => {
+ content.setActiveType(item)
emit('select', item)
}
+
return {
content,
contentTypeGroups,
+ isActive,
bordered,
- handleClick,
+ selectItem,
}
},
})
diff --git a/src/components/VHeader/VHeaderDesktop.vue b/src/components/VHeader/VHeaderDesktop.vue
new file mode 100644
index 000000000..733ecfd5c
--- /dev/null
+++ b/src/components/VHeader/VHeaderDesktop.vue
@@ -0,0 +1,258 @@
+<template>
+ <header
+ class="main-header z-30 flex w-full items-stretch justify-between gap-x-2 border-b bg-white py-4 px-7"
+ :class="
+ isHeaderScrolled || sidebarVisibleRef
+ ? 'border-dark-charcoal-20'
+ : 'border-white'
+ "
+ >
+ <VLogoButton :is-fetching="isFetching" :is-search-route="true" />
+
+ <VSearchBar
+ v-model.trim="searchTerm"
+ class="flex-grow"
+ size="medium"
+ @submit="handleSearch"
+ >
+ <span
+ v-show="searchStatus"
+ class="info mx-4 hidden whitespace-nowrap text-xs font-semibold text-dark-charcoal-70 group-hover:text-dark-charcoal group-focus:text-dark-charcoal lg:block"
+ >
+ {{ searchStatus }}
+ </span>
+ </VSearchBar>
+
+ <VSearchTypePopover />
+
+ <VFilterButton
+ ref="filterButtonRef"
+ class="flex self-stretch"
+ :pressed="sidebarVisibleRef"
+ :disabled="areFiltersDisabled"
+ aria-haspopup="dialog"
+ :aria-expanded="sidebarVisibleRef"
+ @toggle="toggleSidebar"
+ @tab="onTab"
+ />
+ <VTeleport v-if="sidebarVisibleRef" to="sidebar">
+ <VSearchGridFilter @close="toggleSidebar" />
+ </VTeleport>
+ </header>
+</template>
+
+<script lang="ts">
+import {
+ computed,
+ defineComponent,
+ inject,
+ onMounted,
+ ref,
+ useContext,
+ useRouter,
+ watch,
+} from '@nuxtjs/composition-api'
+
+import { Portal as VTeleport } from 'portal-vue'
+
+import { useMediaStore } from '~/stores/media'
+import { isSearchTypeSupported, useSearchStore } from '~/stores/search'
+
+import { ALL_MEDIA, searchPath, supportedMediaTypes } from '~/constants/media'
+import { IsHeaderScrolledKey } from '~/types/provides'
+import { useMatchSearchRoutes } from '~/composables/use-match-routes'
+import { useI18n } from '~/composables/use-i18n'
+import { useI18nResultsCount } from '~/composables/use-i18n-utilities'
+
+import useSearchType from '~/composables/use-search-type'
+import { useFilterSidebarVisibility } from '~/composables/use-filter-sidebar-visibility'
+import { useFocusFilters } from '~/composables/use-focus-filters'
+
+import local from '~/utils/local'
+import { env } from '~/utils/env'
+import { Focus } from '~/utils/focus-management'
+
+import VLogoButton from '~/components/VHeader/VLogoButton.vue'
+import VSearchGridFilter from '~/components/VFilters/VSearchGridFilter.vue'
+import VFilterButton from '~/components/VHeader/VFilterButton.vue'
+import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
+import VSearchTypePopover from '~/components/VContentSwitcher/VSearchTypePopover.vue'
+
+import closeIcon from '~/assets/icons/close.svg'
+
+export default defineComponent({
+ name: 'VHeaderDesktop',
+ components: {
+ VFilterButton,
+ VLogoButton,
+ VSearchGridFilter,
+ VSearchTypePopover,
+ VSearchBar,
+ VTeleport,
+ },
+ setup(_, { emit }) {
+ const filterButtonRef = ref<InstanceType<typeof VFilterButton> | null>(null)
+ const sidebarVisibleRef = ref(false)
+
+ const { app } = useContext()
+ const i18n = useI18n()
+ const router = useRouter()
+
+ const mediaStore = useMediaStore()
+ const searchStore = useSearchStore()
+
+ const content = useSearchType()
+ const filterSidebar = useFilterSidebarVisibility()
+ const { matches: isSearchRoute } = useMatchSearchRoutes()
+
+ const isHeaderScrolled = inject(IsHeaderScrolledKey)
+
+ const isFetching = computed(() => mediaStore.fetchState.isFetching)
+
+ const resultsCount = computed(() => mediaStore.resultCount)
+ const { getI18nCount } = useI18nResultsCount()
+ /**
+ * Additional text at the end of the search bar.
+ * Shows the loading state or result count.
+ */
+ const searchStatus = computed(() => {
+ if (searchStore.searchTerm === '') return ''
+ if (isFetching.value) return i18n.t('header.loading')
+ return getI18nCount(resultsCount.value)
+ })
+
+ const localSearchTerm = ref(searchStore.searchTerm)
+ let searchTermChanged = computed(() => {
+ return searchStore.searchTerm !== localSearchTerm.value
+ })
+ /**
+ * Search term has a getter and setter to be used as a v-model.
+ * To prevent sending unnecessary requests, we also keep track of whether
+ * the search term was changed.
+ */
+ const searchTerm = computed({
+ get: () => localSearchTerm.value,
+ set: (value: string) => {
+ localSearchTerm.value = value
+ },
+ })
+
+ const selectSearchType = async (type) => {
+ content.setActiveType(type)
+
+ const newPath = app.localePath({
+ path: searchPath(type),
+ query: searchStore.searchQueryParams,
+ })
+ router.push(newPath)
+
+ function typeWithoutMedia(mediaType) {
+ return mediaStore.resultCountsPerMediaType[mediaType] === 0
+ }
+
+ const shouldFetchMedia =
+ type === ALL_MEDIA
+ ? supportedMediaTypes.every((type) => typeWithoutMedia(type))
+ : typeWithoutMedia(type)
+
+ if (shouldFetchMedia) {
+ await mediaStore.fetchMedia()
+ }
+ }
+
+ /**
+ * Called when the 'search' button in the header is clicked.
+ * There are several scenarios:
+ * - search term hasn't changed:
+ * - on a search route, do nothing.
+ * - on other routes: set searchType to 'All content', reset the media,
+ * change the path to `/search/` (All content).
+ * - search term changed:
+ * - on a search route: Update the store searchTerm value, update query `q` param, reset media,
+ * fetch new media.
+ * - on other routes: Update the store searchTerm value, set searchType to 'All content', reset media,
+ * update query `q` param.
+ * Updating the path causes the `search.vue` page's route watcher
+ * to run and fetch new media.
+ */
+ const handleSearch = async () => {
+ window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
+ const mediaStore = useMediaStore()
+ const searchStore = useSearchStore()
+ const searchType = isSearchRoute.value
+ ? searchStore.searchType
+ : ALL_MEDIA
+ if (
+ isSearchRoute.value &&
+ (!searchTermChanged.value || searchTerm.value === '')
+ )
+ return
+ if (searchTermChanged.value) {
+ await mediaStore.clearMedia()
+
+ searchStore.setSearchTerm(searchTerm.value)
+ searchStore.setSearchType(searchType)
+ }
+ document.activeElement?.blur()
+ if (isSearchTypeSupported(searchType)) {
+ const newPath = app.localePath({
+ path: searchPath(searchType),
+ query: searchStore.searchQueryParams,
+ })
+ router.push(newPath)
+ }
+ }
+ const areFiltersDisabled = computed(
+ () => !searchStore.searchTypeIsSupported
+ )
+
+ onMounted(() => {
+ // We default to show the filter on desktop, and only close it if the user has
+ // explicitly closed it before.
+ const localFilterState = !(
+ local.getItem(env.filterStorageKey) === 'false'
+ )
+ const searchStore = useSearchStore()
+ sidebarVisibleRef.value =
+ searchStore.searchTypeIsSupported && localFilterState
+ })
+
+ watch(sidebarVisibleRef, (visible) => {
+ filterSidebar.setVisibility(visible)
+ visible ? emit('open') : emit('close')
+ })
+
+ const toggleSidebar = () =>
+ (sidebarVisibleRef.value = !sidebarVisibleRef.value)
+
+ const focusFilters = useFocusFilters()
+ /**
+ * Focus the first element in the sidebar when navigating from the VFilterButton
+ * using keyboard `Tab` key.
+ */
+ const onTab = (event: KeyboardEvent) => {
+ focusFilters.focusFilterSidebar(event, Focus.First)
+ }
+
+ return {
+ filterButtonRef,
+ closeIcon,
+ isFetching,
+
+ isHeaderScrolled,
+ areFiltersDisabled,
+
+ close,
+
+ handleSearch,
+ selectSearchType,
+ searchStatus,
+ searchTerm,
+ sidebarVisibleRef: sidebarVisibleRef,
+
+ toggleSidebar,
+ onTab,
+ }
+ },
+})
+</script>
diff --git a/src/components/VLogoLoader/VLogoLoader.vue b/src/components/VLogoLoader/VLogoLoader.vue
index 423e4f59b..ebb139936 100644
--- a/src/components/VLogoLoader/VLogoLoader.vue
+++ b/src/components/VLogoLoader/VLogoLoader.vue
@@ -5,11 +5,12 @@
:class="{
[$style.loading]: status === 'loading' && !prefersReducedMotion,
'h-10 w-10': autoResize,
+ 'h-12 w-12': !autoResize,
}"
aria-hidden="true"
:data-prefers-reduced-motion="prefersReducedMotion"
data-testid="logo-loader"
- class="inline-flex h-12 w-12 items-center justify-center rounded p-3 md:h-12 md:w-12"
+ class="inline-flex items-center justify-center rounded p-3 md:h-12 md:w-12"
fill="currentColor"
>
<path
diff --git a/src/layouts/default.vue b/src/layouts/default.vue
index d8e72b4c1..91e99a91d 100644
--- a/src/layouts/default.vue
+++ b/src/layouts/default.vue
@@ -5,7 +5,10 @@
<VMigrationNotice />
<VTranslationStatusBanner />
<template v-if="isNewHeaderEnabled">
- <VHeader v-if="isSearchRoute" />
+ <template v-if="isSearchRoute">
+ <VHeaderDesktop v-if="isMinScreenLg" />
+ <VHeader v-else />
+ </template>
<VHeaderInternal v-else />
</template>
<VHeaderOld v-else />
@@ -35,7 +38,13 @@
</div>
</template>
<script>
-import { computed, provide, ref, watch } from '@nuxtjs/composition-api'
+import {
+ computed,
+ onMounted,
+ provide,
+ ref,
+ watch,
+} from '@nuxtjs/composition-api'
import { PortalTarget as VTeleportTarget } from 'portal-vue'
import { useWindowScroll } from '~/composables/use-window-scroll'
@@ -64,6 +73,7 @@ const embeddedPage = {
VMigrationNotice,
VTranslationStatusBanner,
VHeaderOld,
+ VHeaderDesktop: () => import('~/components/VHeader/VHeaderDesktop.vue'),
VHeaderInternal: () => import('~/components/VHeader/VHeaderInternal.vue'),
VHeader: () => import('~/components/VHeader/VHeader.vue'),
VFooter,
@@ -82,9 +92,25 @@ const embeddedPage = {
const { isVisible: isFilterVisible } = useFilterSidebarVisibility()
const { matches: isSearchRoute } = useMatchSearchRoutes()
+ const mounted = ref(false)
+ onMounted(() => {
+ mounted.value = true
+ })
const isMinScreenMd = isMinScreen('md')
- const isMinScreenLg = isMinScreen('lg')
+ /**
+ * If we use the `isMinScreen('lg')` composable for conditionally
+ * rendering components, we get a server-client side rendering
+ * mismatch.
+ * To prevent that, we initially render mobile components, and
+ * after the `mounted` ref is true, we re-render the desktop if
+ * the width is `lg`.
+ * @type {Ref<UnwrapRef<boolean>>}
+ */
+ const innerIsMinScreenLg = isMinScreen('lg')
+ const isMinScreenLg = computed(() =>
+ Boolean(innerIsMinScreenLg.value && mounted.value)
+ )
const isSidebarVisible = computed(() => {
return isNewHeaderEnabled
@@ -117,6 +143,7 @@ const embeddedPage = {
return {
isHeaderScrolled,
isMinScreenMd,
+ isMinScreenLg,
isSidebarVisible,
isSearchRoute,
headerHasTwoRows,