Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Simplify mobile modals (#1731)
Olga Bulata56342e95535
diff --git a/src/components/VContentSwitcher/VMobileMenuModal.vue b/src/components/VContentSwitcher/VMobileMenuModal.vueindex 7315da098..bbb5c4ba0 100644--- a/src/components/VContentSwitcher/VMobileMenuModal.vue+++ b/src/components/VContentSwitcher/VMobileMenuModal.vue@@ -1,65 +1,55 @@<template>- <div ref="nodeRef" class="mobile-menu ms-auto md:ms-0">- <!-- eslint-disable-next-line vuejs-accessibility/click-events-have-key-events -->- <div ref="triggerContainerRef" @click="onTriggerClick">+ <VModal+ ref="nodeRef"+ class="mobile-menu ms-auto md:ms-0"+ :label="$t('header.filter-button.simple').toString()"+ :initial-focus-element="initialFocusElement"+ >+ <template #trigger="{ a11yProps, visible }"><VSearchTypeButton- :a11y-props="triggerA11yProps"+ :a11y-props="a11yProps"+ :visible="visible":active-item="activeItem"aria-controls="content-switcher-modal"/>- </div>- <VModalContent- :visible="visibleRef"- :trigger-element="triggerRef"- :hide="close"- :aria-label="$t('header.filter-button.simple')"- :initial-focus-element="initialFocusElement"+ </template>+ <nav+ id="content-switcher-modal"+ class="p-6"+ aria-labelledby="content-switcher-heading">- <nav- id="content-switcher-modal"- class="p-6"- aria-labelledby="content-switcher-heading"- >- <VSearchTypes- ref="searchTypesNode"- size="small"- :active-item="content.activeType.value"- :use-links="true"- @select="selectItem"- />- <VPageList layout="columns" class="mt-10" />- </nav>- </VModalContent>- </div>+ <VSearchTypes+ ref="searchTypesRef"+ size="small"+ :active-item="content.activeType.value"+ :use-links="true"+ @select="selectItem"+ />+ <VPageList layout="columns" class="mt-10" />+ </nav>+ </VModal></template><script lang="ts">-import {- ComponentInstance,- computed,- defineComponent,- onMounted,- reactive,- ref,- watch,-} from '@nuxtjs/composition-api'+import { computed, defineComponent, ref } from '@nuxtjs/composition-api'import usePages from '~/composables/use-pages'import useSearchType from '~/composables/use-search-type'-import { useBodyScrollLock } from '~/composables/use-body-scroll-lock'-import VModalContent from '~/components/VModal/VModalContent.vue'-import VSearchTypes from '~/components/VContentSwitcher/VSearchTypes.vue'+import type { SupportedSearchType } from '~/constants/media'++import VModal from '~/components/VModal/VModal.vue'import VPageList from '~/components/VHeader/VPageMenu/VPageList.vue'import VSearchTypeButton from '~/components/VContentSwitcher/VSearchTypeButton.vue'+import VSearchTypes from '~/components/VContentSwitcher/VSearchTypes.vue'export default defineComponent({name: 'VMobileMenuModal',components: {- VModalContent,- VSearchTypes,+ VModal,VPageList,VSearchTypeButton,+ VSearchTypes,},props: {activeItem: {@@ -71,78 +61,27 @@ export default defineComponent({const content = useSearchType()const pages = usePages()- const searchTypesNode = ref<ComponentInstance | null>(null)- const modalRef = ref<HTMLElement | null>(null)- const triggerContainerRef = ref<HTMLElement | null>(null)-- const closeMenu = () => close()-- const visibleRef = ref(false)+ const searchTypesRef = ref<InstanceType<typeof VSearchTypes> | null>(null)const nodeRef = ref(null)- const triggerA11yProps = reactive({- 'aria-expanded': false,- 'aria-haspopup': 'dialog',- })-- const triggerRef = ref<HTMLElement | null>()- onMounted(- () =>- (triggerRef.value = triggerContainerRef.value?.firstChild- ? (triggerContainerRef.value.firstChild as HTMLElement)- : null)- )-- const initialFocusElement = computed(() =>- searchTypesNode.value?.$el?.querySelector('[aria-checked="true"]')- )-- watch([visibleRef], ([visible]) => {- triggerA11yProps['aria-expanded'] = visible+ const initialFocusElement = computed(() => {+ return searchTypesRef.value?.$el+ ? (searchTypesRef.value.$el as HTMLElement).querySelector<HTMLElement>(+ '[aria-checked="true"]'+ )+ : null})- const { lock, unlock } = useBodyScrollLock({ nodeRef })-- const open = () => {- visibleRef.value = true- emit('open')- lock()- }-- const close = () => {- visibleRef.value = false- emit('close')- unlock()- }-- const onTriggerClick = () => {- if (visibleRef.value === true) {- close()- } else {- open()- }- }- const selectItem = (item) => {- emit('select', item)- }+ const selectItem = (item: SupportedSearchType) => emit('select', item)return {pages,content,- close,- modalRef,nodeRef,- triggerContainerRef,- closeMenu,-- triggerRef,- onTriggerClick,+ searchTypesRef,- triggerA11yProps,- visibleRef,selectItem,initialFocusElement,- searchTypesNode,}},})diff --git a/src/components/VHeader/VHeaderFilter.vue b/src/components/VHeader/VHeaderFilter.vueindex 19fad3bde..187441622 100644--- a/src/components/VHeader/VHeaderFilter.vue+++ b/src/components/VHeader/VHeaderFilter.vue@@ -41,16 +41,17 @@ import {inject,Ref,toRef,+ onBeforeUnmount,} from '@nuxtjs/composition-api'import { Portal as VTeleport } from 'portal-vue'+import { useBodyScrollLock } from '~/composables/use-body-scroll-lock'import { useFilterSidebarVisibility } from '~/composables/use-filter-sidebar-visibility'import { useFocusFilters } from '~/composables/use-focus-filters'import { Focus } from '~/utils/focus-management'import { defineEvent } from '~/types/emits'-import local from '~/utils/local'import { env } from '~/utils/env'import { useSearchStore } from '~/stores/search'@@ -87,10 +88,11 @@ export default defineComponent({const filterSidebar = useFilterSidebarVisibility()const disabledRef = toRef(props, 'disabled')- const isMinScreenMd: Ref<boolean> = inject('isMinScreenMd', ref(true))+ const isMinScreenMd: Ref<boolean> = inject('isMinScreenMd')const open = () => (visibleRef.value = true)const close = () => (visibleRef.value = false)+ const { lock, unlock } = useBodyScrollLock({ nodeRef })onMounted(() => {// We default to show the filter on desktop, and only close it if the user has@@ -110,9 +112,14 @@ export default defineComponent({}})+ onBeforeUnmount(() => unlock())+watch(visibleRef, (visible) => {filterSidebar.setVisibility(visible)visible ? emit('open') : emit('close')+ if (!isMinScreenMd.value) {+ visible ? lock() : unlock()+ }})watch(disabledRef, (disabled) => {@@ -121,6 +128,13 @@ export default defineComponent({}})+ // Lock the scroll when the screen changes to below Md if filters are open.+ watch(isMinScreenMd, (isMd) => {+ if (!isMd && visibleRef.value) {+ lock()+ }+ })+const onTriggerClick = () => {visibleRef.value = !visibleRef.value}diff --git a/src/components/VHeader/VPageMenu/VMobilePageMenu.vue b/src/components/VHeader/VPageMenu/VMobilePageMenu.vueindex 9c6df8a23..3875d2695 100644--- a/src/components/VHeader/VPageMenu/VMobilePageMenu.vue+++ b/src/components/VHeader/VPageMenu/VMobilePageMenu.vue@@ -1,98 +1,26 @@<template>- <div ref="nodeRef" class="flex justify-center">- <!-- eslint-disable vuejs-accessibility/click-events-have-key-events -->- <div- ref="triggerContainerRef"- class="flex flex-shrink-0 items-stretch"- @click="onTriggerClick"- >- <!-- eslint-enable vuejs-accessibility/click-events-have-key-events -->- <VPageMenuButton :a11y-props="triggerA11yProps" />- </div>- <VModalContent- :visible="visibleRef"- :trigger-element="triggerRef"- :hide="close"- :aria-label="$t('header.filter-button.simple')"- >- <nav class="p-4">- <VPageList layout="columns" @click="closeMenu" />- </nav>- </VModalContent>- </div>+ <VModal+ class="flex justify-center"+ :label="$t('header.filter-button.simple').toString()"+ >+ <template #trigger="{ a11yProps, visible }">+ <VPageMenuButton :a11y-props="a11yProps" :visible="visible" />+ </template>+ <nav class="p-4">+ <VPageList layout="columns" />+ </nav>+ </VModal></template><script>-import {- computed,- defineComponent,- reactive,- ref,- watch,-} from '@nuxtjs/composition-api'+import { defineComponent } from '@nuxtjs/composition-api'-import { useBodyScrollLock } from '~/composables/use-body-scroll-lock'--import VModalContent from '~/components/VModal/VModalContent.vue'+import VModal from '~/components/VModal/VModal.vue'import VPageMenuButton from '~/components/VHeader/VPageMenu/VPageMenuButton.vue'import VPageList from '~/components/VHeader/VPageMenu/VPageList.vue'export default defineComponent({name: 'VMobilePageMenu',- components: { VModalContent, VPageMenuButton, VPageList },- setup(_, { emit }) {- const modalRef = ref(null)-- const closeMenu = () => close()-- const visibleRef = ref(false)- const nodeRef = ref(null)-- const triggerA11yProps = reactive({- 'aria-expanded': false,- 'aria-haspopup': 'dialog',- })-- const triggerRef = computed(() => nodeRef.value?.firstChild.firstChild)-- watch([visibleRef], ([visible]) => {- triggerA11yProps['aria-expanded'] = visible- })-- const { lock, unlock } = useBodyScrollLock({ nodeRef })-- const open = () => {- visibleRef.value = true- emit('open')- lock()- }-- const close = () => {- visibleRef.value = false- emit('close')- unlock()- }-- const onTriggerClick = () => {- if (visibleRef.value === true) {- close()- } else {- open()- }- }-- return {- close,- modalRef,- nodeRef,- closeMenu,-- triggerRef,- onTriggerClick,-- triggerA11yProps,- visibleRef,- }- },+ components: { VModal, VPageMenuButton, VPageList },})</script>diff --git a/src/components/VModal/VModal.vue b/src/components/VModal/VModal.vueindex 51f14bec1..249c3fc29 100644--- a/src/components/VModal/VModal.vue+++ b/src/components/VModal/VModal.vue@@ -129,12 +129,8 @@ export default defineComponent({const triggerRef = computed(() => triggerContainerRef.value?.firstChild)- watch([visibleRef], ([visible]) => {- if (visible) {- triggerA11yProps['aria-expanded'] = true- } else {- triggerA11yProps['aria-expanded'] = false- }+ watch(visibleRef, (visible) => {+ triggerA11yProps['aria-expanded'] = !!visible})const { lock, unlock } = useBodyScrollLock({ nodeRef })diff --git a/src/composables/use-focus-on-show.js b/src/composables/use-focus-on-show.tssimilarity index 71%rename from src/composables/use-focus-on-show.jsrename to src/composables/use-focus-on-show.tsindex 04aa82d41..908681937 100644--- a/src/composables/use-focus-on-show.js+++ b/src/composables/use-focus-on-show.ts@@ -1,4 +1,4 @@-import { nextTick, ref, watch } from '@nuxtjs/composition-api'+import { nextTick, ref, watch, Ref } from '@nuxtjs/composition-api'import { warn } from '~/utils/console'import {@@ -10,31 +10,32 @@ import {export const noFocusableElementWarning ="It's recommended to have at least one tabbable element inside dialog. The dialog element has been automatically focused. If this is the intended behavior, pass `tabIndex={0}` to the dialog element to disable this warning."-/**- * @typedef Props- * @property {import('./types').Ref<HTMLElement>} dialogRef- * @property {import('./types').Ref<boolean>} visibleRef- * @property {import('./types').Ref<boolean>} autoFocusOnShowRef- * @property {import('./types').Ref<HTMLElement>} initialFocusElementRef- */+type Props = {+ dialogRef: Ref<HTMLElement | null>+ visibleRef: Ref<boolean>+ autoFocusOnShowRef: Ref<boolean>+ initialFocusElementRef: Ref<HTMLElement | null>+}/*** @see https://github.com/reakit/reakit/blob/bce9b8a0e567983f61b5cc627f8dee9461986fab/packages/reakit/src/Dialog/__utils/useFocusOnShow.ts#L9- * @param {Props} props*/export const useFocusOnShow = ({dialogRef,visibleRef,autoFocusOnShowRef,- initialFocusElementRef = ref(),-}) => {+ initialFocusElementRef = ref(null),+}: Props) => {watch(- [dialogRef, visibleRef, autoFocusOnShowRef, initialFocusElementRef],- /**- * @param {[HTMLElement, boolean, boolean, HTMLElement]} values- */+ [+ dialogRef,+ visibleRef,+ autoFocusOnShowRef,+ initialFocusElementRef,+ ] as const,([dialog, visible, autoFocusOnShow, initialFocusElement]) => {if (!dialog || !visible || !autoFocusOnShow) return+nextTick(() => {const isActive = () => hasFocusWithin(dialog)diff --git a/src/composables/use-media-query.ts b/src/composables/use-media-query.tsindex da96889c0..0fc3093f0 100644--- a/src/composables/use-media-query.ts+++ b/src/composables/use-media-query.ts@@ -1,9 +1,11 @@/* this implementation is from https://github.com/vueuse/vueuse/packages/core/useMediaQuery/which, in turn, is ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */-import { onBeforeUnmount, ref } from '@nuxtjs/composition-api'+import { ref, watchEffect } from '@nuxtjs/composition-api'import { SCREEN_SIZES, Breakpoint } from '~/constants/screens'import { defaultWindow } from '~/constants/window'+import { tryOnScopeDispose } from '~/utils/try-on-scope-dispose'+import { useSupported } from '~/composables/use-supported'interface Options {shouldPassInSSR?: boolean@@ -17,34 +19,43 @@ export function useMediaQuery(query: string,options: Options = { shouldPassInSSR: false }) {- const matches = ref(false)const { window = defaultWindow } = options- if (!window) {- matches.value = Boolean(options.shouldPassInSSR)- return matches- }-- const mediaQuery = window.matchMedia(query)- matches.value = mediaQuery.matches+ const isSupported = useSupported(+ () =>+ window &&+ 'matchMedia' in window &&+ typeof window.matchMedia === 'function'+ )- const handler = (event: MediaQueryListEvent) => {- matches.value = event.matches- }- // Before Safari 14, MediaQueryList is based on EventTarget,- // so we use addListener() and removeListener(), too.- if ('addEventListener' in mediaQuery) {- mediaQuery.addEventListener('change', handler)- } else {- mediaQuery.addListener(handler)- }+ let mediaQuery: MediaQueryList | undefined+ const matches = ref(Boolean(options.shouldPassInSSR))- onBeforeUnmount(() => {+ const cleanup = () => {+ if (!mediaQuery) returnif ('removeEventListener' in mediaQuery) {- mediaQuery.removeEventListener('change', handler)+ mediaQuery.removeEventListener('change', update)} else {- mediaQuery.removeListener(handler)+ // @ts-expect-error deprecated API+ mediaQuery.removeListener(update)+ }+ }++ const update = () => {+ if (!isSupported.value) {+ return+ }+ // This is already checked in `isSupported`, but TS doesn't know that+ if (!window) return+ cleanup()+ if (!mediaQuery) {+ mediaQuery = window.matchMedia(query)}- })+ matches.value = mediaQuery?.matches+ }++ watchEffect(update)++ tryOnScopeDispose(() => cleanup())return matches}diff --git a/src/composables/use-supported.ts b/src/composables/use-supported.tsnew file mode 100644index 000000000..232652fc9--- /dev/null+++ b/src/composables/use-supported.ts@@ -0,0 +1,14 @@+import { Ref, ref } from '@nuxtjs/composition-api'++import { tryOnMounted } from '~/utils/try-on-mounted'++export function useSupported(callback: () => unknown, sync = false) {+ const isSupported = ref() as Ref<boolean>++ const update = () => (isSupported.value = Boolean(callback()))++ update()++ tryOnMounted(update, sync)+ return isSupported+}diff --git a/src/utils/try-on-mounted.ts b/src/utils/try-on-mounted.tsnew file mode 100644index 000000000..4130ec176--- /dev/null+++ b/src/utils/try-on-mounted.ts@@ -0,0 +1,15 @@+import {+ getCurrentInstance,+ nextTick,+ onMounted,+} from '@nuxtjs/composition-api'++export function tryOnMounted(fn: () => void, sync = true) {+ if (getCurrentInstance()) {+ onMounted(fn)+ } else if (sync) {+ fn()+ } else {+ nextTick(fn)+ }+}diff --git a/src/utils/try-on-scope-dispose.ts b/src/utils/try-on-scope-dispose.tsnew file mode 100644index 000000000..bb8727842--- /dev/null+++ b/src/utils/try-on-scope-dispose.ts@@ -0,0 +1,10 @@+import { getCurrentScope, onScopeDispose } from '@nuxtjs/composition-api'++export function tryOnScopeDispose(fn: () => void) {+ if (getCurrentScope()) {+ onScopeDispose(fn)+ return true+ } else {+ return false+ }+}