Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Set maximum height to the popover to prevent cut-off on smaller screens (#1686)
Olga Bulat56e961cf9744
diff --git a/src/components/VContentSwitcher/VSearchTypePopover.vue b/src/components/VContentSwitcher/VSearchTypePopover.vueindex 497989b24..8b11b3461 100644--- a/src/components/VContentSwitcher/VSearchTypePopover.vue+++ b/src/components/VContentSwitcher/VSearchTypePopover.vue@@ -4,6 +4,7 @@class="flex items-stretch":label="$t('search-type.label').toString()"placement="bottom-end"+ :clippable="true"><template #trigger="{ a11yProps }"><VSearchTypeButtondiff --git a/src/components/VHeader/VPageMenu/VDesktopPageMenu.vue b/src/components/VHeader/VPageMenu/VDesktopPageMenu.vueindex 37e118733..d656067ad 100644--- a/src/components/VHeader/VPageMenu/VDesktopPageMenu.vue+++ b/src/components/VHeader/VPageMenu/VDesktopPageMenu.vue@@ -2,6 +2,7 @@<VPopoverref="pageMenuPopover"class="flex items-stretch"+ :clippable="true":label="$t('header.aria.menu')"><template #trigger="{ a11yProps }">diff --git a/src/components/VPopover/VPopover.vue b/src/components/VPopover/VPopover.vueindex c14a31732..3ee24f3b0 100644--- a/src/components/VPopover/VPopover.vue+++ b/src/components/VPopover/VPopover.vue@@ -24,6 +24,7 @@:trigger-element="triggerRef":placement="placement":strategy="strategy"+ :clippable="clippable":hide-on-esc="hideOnEsc":hide-on-click-outside="hideOnClickOutside":auto-focus-on-show="autoFocusOnShow"@@ -128,7 +129,17 @@ export default defineComponent({/*** the z-index to apply to the popover content*/- zIndex: { type: Number, default: 999 },+ zIndex: {+ type: Number,+ default: 50,+ // TODO: extract valid z-indexes (these are from the tailwind config)+ validator: (v) => [0, 10, 20, 30, 40, 50].includes(v),+ },+ /**+ * Whether the popover height should be clipped and made scrollable+ * if the window height is too small.+ */+ clippable: { type: Boolean, default: false },},emits: [/**@@ -150,7 +161,11 @@ export default defineComponent({'aria-haspopup': 'dialog',})- const triggerRef = computed(() => triggerContainerRef.value?.firstChild)+ const triggerRef = computed(() =>+ triggerContainerRef.value?.firstChild+ ? /** @type {HTMLElement} */ (triggerContainerRef.value.firstChild)+ : undefined+ )watch([visibleRef], ([visible]) => {triggerA11yProps['aria-expanded'] = visiblediff --git a/src/components/VPopover/VPopoverContent.types.js b/src/components/VPopover/VPopoverContent.types.jsdeleted file mode 100644index 554bb88e2..000000000--- a/src/components/VPopover/VPopoverContent.types.js+++ /dev/null@@ -1,56 +0,0 @@-import { placements as popoverPlacements } from '@popperjs/core'--export const propTypes = {- visible: {- type: Boolean,- required: true,- },- hide: {- type: /** @type {import('@nuxtjs/composition-api').PropType<() => void>} */ (- Function- ),- required: true,- },- hideOnEsc: {- type: Boolean,- default: true,- },- hideOnClickOutside: {- type: Boolean,- default: true,- },- autoFocusOnShow: {- type: Boolean,- default: true,- },- autoFocusOnHide: {- type: Boolean,- default: true,- },- triggerElement: {- type: /** @type {import('@nuxtjs/composition-api').PropType<HTMLElement>} */ (- process.server ? Object : HTMLElement- ),- },- placement: {- type: /** @type {import('@nuxtjs/composition-api').PropType<import('@popperjs/core').Placement>} */ (- String- ),- default: 'bottom-end',- validate: (v) => popoverPlacements.includes(v),- },- strategy: {- type: /** @type {import('@nuxtjs/composition-api').PropType<import('@popperjs/core').PositioningStrategy>} */ (- String- ),- default: 'absolute',- // todo: Use the actual PositioningStrategy type instead of manually writing these values,- // when this file is updated to TypeScript.- validate: (v) => ['absolute', 'fixed'].includes(v),- },- zIndex: {- type: Number,- },-}--/** @typedef {import('@nuxtjs/composition-api').ExtractPropTypes<typeof propTypes>} Props */diff --git a/src/components/VPopover/VPopoverContent.vue b/src/components/VPopover/VPopoverContent.vueindex 197b1a0e6..b1b6663fd 100644--- a/src/components/VPopover/VPopoverContent.vue+++ b/src/components/VPopover/VPopoverContent.vue@@ -8,8 +8,9 @@><divref="popoverRef"- class="max-w-max rounded-sm border border-light-gray bg-white shadow"- :style="{ zIndex }"+ class="popover-content max-w-max overflow-y-auto overflow-x-hidden rounded-sm border border-light-gray bg-white shadow"+ :class="`z-${zIndex}`"+ :style="heightProperties":tabindex="-1"@blur="onBlur">@@ -18,32 +19,91 @@</div></template>-<script>-import { defineComponent, toRefs, ref, provide } from '@nuxtjs/composition-api'+<script lang="ts">+import {+ defineComponent,+ toRefs,+ ref,+ provide,+ InjectionKey,+ PropType,+ computed,+} from '@nuxtjs/composition-api'++import {+ Placement,+ placements as popoverPlacements,+ PositioningStrategy,+} from '@popperjs/core'import { usePopoverContent } from '~/composables/use-popover-content'import { warn } from '~/utils/console'+import { defineEvent } from '~/types/emits'-import { propTypes } from './VPopoverContent.types'+import type { CSSProperties } from '@vue/runtime-dom'-/**- * @type {import('@nuxtjs/composition-api').InjectionKey<boolean>}- */-export const VPopoverContentContextKey = Symbol('VPopoverContentContextKey')+export const VPopoverContentContextKey = Symbol(+ 'VPopoverContentContextKey'+) as InjectionKey<boolean>export default defineComponent({- name: 'VPopover',- props: propTypes,+ name: 'VPopoverContent',+ props: {+ visible: {+ type: Boolean,+ required: true,+ },+ hide: {+ type: Function as PropType<() => void>,+ required: true,+ },+ hideOnEsc: {+ type: Boolean,+ default: true,+ },+ hideOnClickOutside: {+ type: Boolean,+ default: true,+ },+ autoFocusOnShow: {+ type: Boolean,+ default: true,+ },+ autoFocusOnHide: {+ type: Boolean,+ default: true,+ },+ triggerElement: {+ type: (process.server ? Object : HTMLElement) as PropType<HTMLElement>,+ },+ placement: {+ type: String as PropType<Placement>,+ default: 'bottom-end',+ validate: (v) => popoverPlacements.includes(v),+ },+ strategy: {+ type: String as PropType<PositioningStrategy>,+ default: 'absolute',+ validate: (v) => ['absolute', 'fixed'].includes(v),+ },+ zIndex: {+ type: Number,+ required: true,+ // TODO: extract valid z-indexes (these are from the tailwind config)+ validator: (v: number | 'auto') =>+ [0, 10, 20, 30, 40, 50, 'auto'].includes(v),+ },+ clippable: {+ type: Boolean,+ default: false,+ },+ },/*** This is the only documented emitted event but in reality we pass through `$listeners`* to the underlying element so anything and everything is emitted. `@keydown` is the* only one this component overrides and controls (but ultimately still emits).*/- emits: ['keydown', 'blur'],- /**- * @param {import('./VPopoverContent.types').Props} props- * @param {import('@nuxtjs/composition-api').SetupContext} context- */+ emits: { keydown: defineEvent(), blur: defineEvent() },setup(props, { emit, attrs }) {provide(VPopoverContentContextKey, true)if (!attrs['aria-label'] && !attrs['aria-labelledby']) {@@ -51,14 +111,31 @@ export default defineComponent({}const propsRefs = toRefs(props)- const popoverRef = ref()- const { onKeyDown, onBlur } = usePopoverContent({+ const popoverRef = ref<HTMLElement | undefined>()++ const { onKeyDown, onBlur, maxHeightRef } = usePopoverContent({popoverRef,popoverPropsRefs: propsRefs,emit,})- return { popoverRef, onKeyDown, onBlur }+ const heightProperties = computed(() => {+ // extracting this to ensure that computed is updated when the value changes+ const maxHeight = maxHeightRef.value++ return maxHeight && props.clippable+ ? ({ '--popover-height': `${maxHeight}px` } as CSSProperties)+ : ({} as CSSProperties)+ })++ return { popoverRef, onKeyDown, onBlur, heightProperties }},})</script>+<style>+.popover-content {+ height: var(--popover-height, auto);+ scrollbar-gutter: stable;+ overflow-x: hidden;+}+</style>diff --git a/src/composables/use-popover-content.js b/src/composables/use-popover-content.jsindex ebaea8853..096b3d7dc 100644--- a/src/composables/use-popover-content.js+++ b/src/composables/use-popover-content.js@@ -5,7 +5,7 @@ import { useDialogContent } from './use-dialog-content'/*** @typedef Props* @property {import('./types').Ref<HTMLElement>} popoverRef- * @property {import('./types').ToRefs<import('~/components/VPopover/VPopoverContent.types').Props>} popoverPropsRefs+ * @property {import('./types').ToRefs<import('~/composables/use-popper').PopoverContentProps>} popoverPropsRefs* @property {import('@nuxtjs/composition-api').SetupContext['emit']} emit*/@@ -24,10 +24,11 @@ export function usePopoverContent({ popoverRef, popoverPropsRefs, emit }) {hideOnEscRef: popoverPropsRefs.hideOnEsc,emit,})- usePopper({++ const { maxHeightRef } = usePopper({popoverRef,popoverPropsRefs,})- return { onKeyDown, onBlur }+ return { onKeyDown, onBlur, maxHeightRef }}diff --git a/src/composables/use-popper.js b/src/composables/use-popper.jsdeleted file mode 100644index 916649ca9..000000000--- a/src/composables/use-popper.js+++ /dev/null@@ -1,69 +0,0 @@-import { ref, watch } from '@nuxtjs/composition-api'-import { createPopper } from '@popperjs/core'--/**- * @typedef Props- * @property {import('./types').Ref<HTMLElement>} popoverRef- * @property {import('./types').ToRefs<import('~/components/VPopover/VPopoverContent.types').Props>} popoverPropsRefs- */--/**- * @param {Props} props- */-export function usePopper({ popoverRef, popoverPropsRefs }) {- /** @type {import('./types').Ref<import('@popperjs/core').Instance>} */- const popperInstanceRef = ref()-- watch(- [- popoverPropsRefs.visible,- popoverPropsRefs.placement,- popoverPropsRefs.strategy,- popoverPropsRefs.triggerElement,- popoverRef,- ],- /**- * @param {[boolean, import('@popperjs/core').Placement, number]} deps- * @param {unknown} _- * @param {(cb: () => void) => void} onInvalidate- */- (- [visible, placement, strategy, triggerElement, popover],- _,- onInvalidate- ) => {- if (!(triggerElement && popover)) return-- popperInstanceRef.value = createPopper(triggerElement, popover, {- placement,- strategy,- modifiers: [- {- name: 'eventListeners',- enabled: visible,- },- {- name: 'arrow',- enabled: false,- },- {- name: 'offset',- options: {- offset: [0, 8],- },- },- ],- })-- onInvalidate(() => {- if (popperInstanceRef.value) {- popperInstanceRef.value.destroy()- popperInstanceRef.value = undefined- }- })- },- { immediate: true }- )-- return popperInstanceRef-}diff --git a/src/composables/use-popper.ts b/src/composables/use-popper.tsnew file mode 100644index 000000000..b611de8ac--- /dev/null+++ b/src/composables/use-popper.ts@@ -0,0 +1,111 @@+import { ref, watch, Ref, ToRefs } from '@nuxtjs/composition-api'+import {+ createPopper,+ detectOverflow,+ Instance,+ Placement,+ PositioningStrategy,+} from '@popperjs/core'++import { useWindowSize } from '~/composables/use-window-size'++export type PopoverContentProps = {+ visible: boolean+ hide: () => void+ hideOnEsc: boolean+ hideOnClickOutside: boolean+ autoFocusOnShow: boolean+ autoFocusOnHide: boolean+ triggerElement: HTMLElement+ placement: Placement+ strategy: PositioningStrategy+ zIndex: number+}++type Props = {+ popoverRef: Ref<HTMLElement>+ popoverPropsRefs: ToRefs<PopoverContentProps>+}++// A constant offset to ensure there's a gap between+// the popover and the window border.+const PopperOffset = 20++export function usePopper({ popoverRef, popoverPropsRefs }: Props) {+ const popperInstanceRef = ref<Instance | undefined>()+ const maxHeightRef = ref<number | null>(null)++ watch(+ [+ popoverPropsRefs.triggerElement,+ popoverPropsRefs.placement,+ popoverPropsRefs.strategy,+ popoverPropsRefs.visible,+ popoverRef,+ ] as const,+ (+ [triggerElement, placement, strategy, visible, popover],+ _,+ onInvalidate+ ) => {+ if (!(triggerElement && popover)) return++ popperInstanceRef.value = createPopper(triggerElement, popover, {+ placement,+ strategy,+ modifiers: [+ {+ name: 'eventListeners',+ enabled: visible,+ },+ {+ name: 'arrow',+ enabled: false,+ },+ {+ name: 'offset',+ options: {+ offset: [0, 8],+ },+ },+ ],+ })++ onInvalidate(() => {+ if (popperInstanceRef.value) {+ popperInstanceRef.value.destroy()+ popperInstanceRef.value = undefined+ }+ })+ },+ { immediate: true }+ )++ /**+ * Detects if the popover is overflowing the viewport,+ * and sets the max-height of the popover accordingly.+ * If there is no overflow, the max-height is set to null.+ **/+ const detectMaxHeight = (popper: Instance) => {+ popper.forceUpdate() // make sure that `rects` are set++ const overflow = detectOverflow(popper.state)+ const verticalOverflow = Math.max(+ -PopperOffset,+ Math.max(overflow.bottom, overflow.top)+ )++ return verticalOverflow + PopperOffset > 0+ ? popper.state.rects.popper.height - verticalOverflow - PopperOffset+ : null+ }+ const { height: windowHeight } = useWindowSize()+ // We only use `windowHeight` to call update the popper max height when it changes, we don't need the actual value+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ watch([popperInstanceRef, windowHeight] as const, ([popper, _]) => {+ if (!popper) return+ maxHeightRef.value = detectMaxHeight(popper)+ })++ return { maxHeightRef }+}diff --git a/src/composables/use-window-size.ts b/src/composables/use-window-size.tsnew file mode 100644index 000000000..bc2f009c4--- /dev/null+++ b/src/composables/use-window-size.ts@@ -0,0 +1,55 @@+/**+ * Code from Vueuse project:+ * https://github.com/vueuse/vueuse/blob/1eb83c41bb1ca6e6c8ee61c46ce9dbca7ab1613f/packages/core/useWindowSize/index.ts+ */+import { getCurrentInstance, onMounted, ref } from '@nuxtjs/composition-api'++import { defaultWindow } from '~/constants/window'+import { useEventListener } from '~/composables/use-event-listener'++export interface UseWindowSizeOptions {+ initialWidth?: number+ initialHeight?: number+ /**+ * Listen to window `orientationchange` event+ */+ listenOrientation?: boolean+ window?: Window+}++/**+ * Reactive window size.+ **/+export function useWindowSize(options: UseWindowSizeOptions = {}) {+ const {+ window = defaultWindow,+ initialWidth = Infinity,+ initialHeight = Infinity,+ listenOrientation = true,+ } = options++ const width = ref(initialWidth)+ const height = ref(initialHeight)++ const update = () => {+ if (window) {+ width.value = window.innerWidth+ height.value = window.innerHeight+ }+ }++ update()+ // Run onMounted after the initial render, if inside a component lifecycle+ if (getCurrentInstance()) {+ onMounted(update)+ }+ if (!window) return { width, height }+ useEventListener(window, 'resize', update, { passive: true })++ if (listenOrientation)+ useEventListener(window, 'orientationchange', update, { passive: true })++ return { width, height }+}++export type UseWindowSizeReturn = ReturnType<typeof useWindowSize>diff --git a/typings/csstype/index.d.ts b/typings/csstype/index.d.tsindex 326d7632f..75c454e6f 100644--- a/typings/csstype/index.d.ts+++ b/typings/csstype/index.d.ts@@ -8,6 +8,6 @@ declare module 'csstype' {'--unusable-height'?: string'--progress-time-left'?: string'--seek-time-left'?: string- '--cell-idx'?: number+ '--popover-height'?: string}}