Skip to content

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

Add VPopover component (#397)

sarayourfriend3922733043c1
diff --git a/nuxt.config.js b/nuxt.config.js
index 32fd15dc4..d7a546a81 100644
--- a/nuxt.config.js
+++ b/nuxt.config.js
@@ -135,6 +135,7 @@ export default {
'~/components/MetaSearch',
'~/components/MediaTag',
'~/components/Skeleton',
+ '~/components/VPopover',
],
},
plugins: [
diff --git a/src/components/.eslintrc.js b/src/components/.eslintrc.js
index 91892a8fa..c6ce3c271 100644
--- a/src/components/.eslintrc.js
+++ b/src/components/.eslintrc.js
@@ -3,7 +3,11 @@ module.exports = {
rules: {
'unicorn/filename-case': [
'error',
- { case: 'pascalCase', ignore: ['.eslintrc.js', '.*\\.stories\\.js'] },
+ // Allow things like `Component.stories.js` and `Component.types.js`
+ {
+ case: 'pascalCase',
+ ignore: ['.eslintrc.js', '.*\\..*\\.js'],
+ },
],
},
}
diff --git a/src/components/VButton.vue b/src/components/VButton.vue
index 44c32b0f9..36338bf6d 100644
--- a/src/components/VButton.vue
+++ b/src/components/VButton.vue
@@ -2,7 +2,6 @@
<Component
:is="as"
:type="typeRef"
- :role="role"
:class="[
$style.button,
$style[variant],
@@ -23,6 +22,7 @@
<script>
import { defineComponent, ref, watch, toRefs } from '@nuxtjs/composition-api'
+import { warn } from '~/utils/warn'
/**
* A button component that behaves just like a regular HTML `button` element
@@ -166,7 +166,7 @@ const VButton = defineComponent({
// meaning we'll always have the latest values for the properties on the
// attrs object
if (!attrs.href || attrs.href === '#') {
- console.warn(
+ warn(
'Do not use anchor elements without a valid `href` attribute. Use a `button` instead.'
)
}
diff --git a/src/components/VPopover/VPopover.vue b/src/components/VPopover/VPopover.vue
new file mode 100644
index 000000000..2493d003d
--- /dev/null
+++ b/src/components/VPopover/VPopover.vue
@@ -0,0 +1,164 @@
+<template>
+ <div>
+ <div
+ ref="triggerContainerRef"
+ class="w-min whitespace-nowrap"
+ @click="onTriggerClick"
+ >
+ <!--
+ @slot The trigger, should be a button 99.99% of the time. If you need custom event handling on the trigger button, ensure bubbling is not prevented or else the popover will not open
+ @binding {object} a11yProps
+ @binding {boolean} visible
+ -->
+ <slot
+ name="trigger"
+ :a11y-props="triggerA11yProps"
+ :visible="visibleRef"
+ />
+ </div>
+ <VPopoverContent
+ :visible="visibleRef"
+ :trigger-element="triggerRef"
+ :placement="placement"
+ :hide-on-esc="hideOnEsc"
+ :hide-on-click-outside="hideOnClickOutside"
+ :auto-focus-on-show="autoFocusOnShow"
+ :auto-focus-on-hide="autoFocusOnHide"
+ :hide="close"
+ :aria-label="label"
+ :aria-labelledby="labelledBy"
+ >
+ <!-- @slot The content of the popover -->
+ <slot name="default" />
+ </VPopoverContent>
+ </div>
+</template>
+
+<script>
+import VPopoverContent from '~/components/VPopover/VPopoverContent.vue'
+import {
+ defineComponent,
+ ref,
+ watch,
+ reactive,
+ computed,
+} from '@nuxtjs/composition-api'
+
+export default defineComponent({
+ name: 'VPopover',
+ components: { VPopoverContent },
+ /**
+ * NB: Most of these technically default to `undefined` so that the underlying `VPopoverContent`
+ * default for each of them can take over.
+ */
+ props: {
+ /**
+ * Whether the popover should hide when the <kbd>Escape</kbd> key is pressed.
+ *
+ * @default true
+ */
+ hideOnEsc: { type: Boolean, default: undefined },
+ /**
+ * Whether the popover should hide when a click happens outside the popover content,
+ * excluding the trigger. When the trigger is clicked and the popover is open, nothing
+ * will happen.
+ *
+ * @default true
+ */
+ hideOnClickOutside: { type: Boolean, default: undefined },
+ /**
+ * Whether the popover content should automatically receive focus when the popover
+ * opens.
+ *
+ * @default true
+ */
+ autoFocusOnShow: { type: Boolean, default: undefined },
+ /**
+ * Whether the trigger should automatically receive focus when the popover closes.
+ *
+ * @default true
+ */
+ autoFocusOnHide: { type: Boolean, default: undefined },
+ /**
+ * The placement of the popover relative to the trigger. Should be one of the options
+ * for `placement` passed to popper.js.
+ *
+ * @see https://popper.js.org/docs/v2/constructors/#options
+ *
+ * @default 'bottom'
+ */
+ placement: {
+ type: /** @type {import('@nuxtjs/composition-api').PropType<import('@popperjs/core').Placement>} */ (String),
+ },
+ /**
+ * The label of the popover content. Must be provided if `labelledBy` is empty.
+ *
+ * @default undefined
+ */
+ label: { type: String },
+ /**
+ * The id of the element labelling the popover content. Must be provided if `label` is empty.
+ *
+ * @default undefined
+ */
+ labelledBy: { type: String },
+ },
+ emits: [
+ /**
+ * Fires when the popover opens, regardless of reason. There are no extra parameters.
+ */
+ 'open',
+ /**
+ * Fires when the popover closes, regardless of reason. There are no extra parameters.
+ */
+ 'close',
+ ],
+ setup(_, { emit }) {
+ const visibleRef = ref(false)
+ /** @type {import('@nuxtjs/composition-api').Ref<HTMLElement | undefined>} */
+ const triggerContainerRef = ref()
+
+ const triggerA11yProps = reactive({
+ 'aria-expanded': false,
+ 'aria-haspopup': 'dialog',
+ })
+
+ const triggerRef = computed(() => triggerContainerRef.value?.firstChild)
+
+ watch([visibleRef], ([visible]) => {
+ if (visible) {
+ triggerA11yProps['aria-expanded'] = true
+ } else {
+ triggerA11yProps['aria-expanded'] = false
+ }
+ })
+
+ const open = () => {
+ visibleRef.value = true
+ emit('open')
+ }
+
+ const close = () => {
+ visibleRef.value = false
+ emit('close')
+ }
+
+ const onTriggerClick = () => {
+ if (visibleRef.value === true) {
+ close()
+ } else {
+ open()
+ }
+ }
+
+ return {
+ visibleRef,
+ close,
+ triggerContainerRef,
+ triggerRef,
+ onTriggerClick,
+ triggerA11yProps,
+ }
+ },
+})
+</script>
diff --git a/src/components/VPopover/VPopoverContent.types.js b/src/components/VPopover/VPopoverContent.types.js
new file mode 100644
index 000000000..f9ecf16af
--- /dev/null
+++ b/src/components/VPopover/VPopoverContent.types.js
@@ -0,0 +1,40 @@
+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),
+ },
+}
+
+/** @typedef {import('@nuxtjs/composition-api').ExtractPropTypes<typeof propTypes>} Props */
diff --git a/src/components/VPopover/VPopoverContent.vue b/src/components/VPopover/VPopoverContent.vue
new file mode 100644
index 000000000..6f0e2686c
--- /dev/null
+++ b/src/components/VPopover/VPopoverContent.vue
@@ -0,0 +1,79 @@
+<template>
+ <div
+ v-if="visible"
+ ref="popoverRef"
+ :class="$style.popover"
+ :aria-hidden="!visible"
+ :tabindex="typeof $props.tabindex !== 'undefined' ? $props.tabindex : -1"
+ v-on="$listeners"
+ @keydown="onKeyDown"
+ @blur="onBlur"
+ >
+ <slot />
+ </div>
+</template>
+
+<script>
+import { defineComponent, toRefs, ref } from '@nuxtjs/composition-api'
+import { usePopoverContent } from '~/composables/use-popover-content'
+import { warn } from '~/utils/warn'
+
+import { propTypes } from './VPopoverContent.types'
+
+export default defineComponent({
+ name: 'VPopover',
+ props: propTypes,
+ /**
+ * 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
+ */
+ setup(props, { emit, attrs }) {
+ if (!attrs['aria-label'] && !attrs['aria-labelledby']) {
+ warn('You should provide either `aria-label` or `aria-labelledby` props.')
+ }
+
+ const propsRefs = toRefs(props)
+ const popoverRef = ref()
+ const { focusOnBlur } = usePopoverContent({
+ popoverRef,
+ popoverPropsRefs: propsRefs,
+ })
+
+ /**
+ * @param {KeyboardEvent} event
+ */
+ const onKeyDown = (event) => {
+ emit('keydown', event)
+
+ if (event.defaultPrevented) return
+ if (event.key !== 'Escape') return
+ if (!propsRefs.hideOnEsc.value) return
+
+ event.stopPropagation()
+ propsRefs.hide.value()
+ }
+
+ /**
+ * @param {FocusEvent} event
+ */
+ const onBlur = (event) => {
+ emit('blur', event)
+ focusOnBlur(event)
+ }
+
+ return { popoverRef, onKeyDown, onBlur }
+ },
+})
+</script>
+
+<style module>
+.popover {
+ @apply bg-white border border-light-gray rounded-sm px-2 pt-2 pb-1 max-w-min whitespace-nowrap shadow;
+}
+</style>
diff --git a/src/components/VPopover/meta/VPopover.stories.js b/src/components/VPopover/meta/VPopover.stories.js
new file mode 100644
index 000000000..321e97e8b
--- /dev/null
+++ b/src/components/VPopover/meta/VPopover.stories.js
@@ -0,0 +1,73 @@
+import VPopover from '~/components/VPopover/VPopover.vue'
+import VButton from '~/components/VButton'
+import { placements as popoverPlacements } from '@popperjs/core'
+
+export default {
+ component: VPopover,
+ title: 'Components/VPopover',
+ argTypes: {
+ hideOnEsc: 'boolean',
+ hideOnClickOutside: 'boolean',
+ autoFocusOnShow: 'boolean',
+ autoFocusOnHide: 'boolean',
+ placement: {
+ type: 'radio',
+ options: [...popoverPlacements],
+ },
+ label: 'text',
+ labelledBy: 'text',
+ },
+}
+
+const SinglePopoverStory = (args, { argTypes }) => ({
+ props: Object.keys(argTypes),
+ template: `
+ <div>
+ <p>
+ This story is configured to log when the popover opens or closes. Inspect the console output to observe this behavior.
+ </p>
+ <div tabindex="0">Focusable external area</div>
+ <VPopover v-bind="$props" @open="onOpen" @close="onClose">
+ <template #trigger="{ visible, a11yProps }">
+ <VButton :pressed="visible" v-bind="a11yProps">{{ visible ? 'Close' : 'Open' }}</VButton>
+ </template>
+ <div>Code is Poetry</div>
+ </VPopover>
+ </div>
+ `,
+ components: { VPopover, VButton },
+ setup() {
+ const onOpen = () => console.log('opened!')
+ const onClose = () => console.log('closed!')
+
+ return { onOpen, onClose }
+ },
+})
+
+export const Default = SinglePopoverStory.bind({})
+Default.args = {}
+
+const TwoPopoverStory = (args, { argTypes }) => ({
+ props: Object.keys(argTypes),
+ template: `
+ <div>
+ <VPopover label="First popover" v-bind="$props">
+ <template #trigger="{ visible, a11yProps }">
+ <VButton :pressed="visible" v-bind="a11yProps">{{ visible ? 'First popover open' : 'First popover closed' }}</VButton>
+ </template>
+ <div>First popover content</div>
+ </VPopover>
+ <div class="h-5">Some content</div>
+ <VPopover label="Second popover" v-bind="$props">
+ <template #trigger="{ visible, a11yProps }">
+ <VButton :pressed="visible" v-bind="a11yProps">{{ visible ? 'Second popover open' : 'Second popover closed' }}</VButton>
+ </template>
+ <div>Second popover content</div>
+ </VPopover>
+ </div>
+ `,
+ components: { VPopover, VButton },
+})
+
+export const TwoPopovers = TwoPopoverStory.bind({})
+TwoPopovers.args = {}
diff --git a/src/composables/types.js b/src/composables/types.js
new file mode 100644
index 000000000..cb8ad56e8
--- /dev/null
+++ b/src/composables/types.js
@@ -0,0 +1,11 @@
+/**
+ * @template T
+ * @typedef {import('@nuxtjs/composition-api').Ref<T>} Ref
+ */
+
+/**
+ * @template T
+ * @typedef {import('@nuxtjs/composition-api').ToRefs<T>} ToRefs
+ */
+
+export default {}
diff --git a/src/composables/use-event-listener-outside.js b/src/composables/use-event-listener-outside.js
new file mode 100644
index 000000000..51fafce9e
--- /dev/null
+++ b/src/composables/use-event-listener-outside.js
@@ -0,0 +1,82 @@
+import { watch, ref } from '@nuxtjs/composition-api'
+import { getDocument, contains } from 'reakit-utils'
+
+/**
+ * @param {Element} target
+ */
+function isInDocument(target) {
+ const document = getDocument(target)
+ if (target.tagName === 'HTML') return true
+ return contains(document.body, target)
+}
+
+/**
+ * @typedef Props
+ * @property {import('./types').Ref<HTMLElement>} containerRef
+ * @property {import('./types').Ref<HTMLElement>} triggerRef
+ * @property {string} eventType
+ * @property {(e: Event) => void} listener
+ * @property {import('./types').Ref<boolean>} [shouldListenRef]
+ */
+
+/**
+ * @param {Props} props
+ */
+export const useEventListenerOutside = ({
+ containerRef,
+ triggerRef,
+ eventType,
+ listener,
+ shouldListenRef,
+}) => {
+ const boundEventRef = ref()
+
+ watch(
+ [containerRef, triggerRef, shouldListenRef],
+ /**
+ * @param {[HTMLElement, HTMLElement, boolean]} deps
+ * @param {unknown} _
+ * @param {(cb: () => void) => void} onInvalidate
+ */
+ ([container, trigger, shouldListen], _, onInvalidate) => {
+ if (boundEventRef.value && !shouldListen) {
+ const document = getDocument(container)
+ document.removeEventListener(eventType, boundEventRef.value)
+ }
+
+ if (!shouldListen) return
+
+ /**
+ * @param {Event} event
+ */
+ const onEvent = (event) => {
+ if (!listener) return
+ const target = event.target
+ if (!container) return
+
+ // When an element is unmounted right after it receives focus, the focus
+ // event is triggered after that, when the element isn't part of the
+ // current document anymore. So we ignore it.
+ if (!isInDocument(target)) return
+ // Event inside the container
+ if (contains(container, target)) return
+ // Event on the trigger
+ if (trigger && contains(trigger, target)) return
+
+ listener(event)
+ }
+
+ boundEventRef.value = onEvent
+
+ const document = getDocument(container)
+ document.addEventListener(eventType, boundEventRef.value)
+ onInvalidate(() => {
+ if (boundEventRef.value) {
+ document.removeEventListener(eventType, boundEventRef.value)
+ boundEventRef.value = undefined
+ }
+ })
+ },
+ { immediate: true }
+ )
+}
diff --git a/src/composables/use-focus-on-blur.js b/src/composables/use-focus-on-blur.js
new file mode 100644
index 000000000..6c01735e5
--- /dev/null
+++ b/src/composables/use-focus-on-blur.js
@@ -0,0 +1,65 @@
+import {
+ getDocument,
+ getActiveElement,
+ getNextActiveElementOnBlur,
+} from 'reakit-utils'
+import { ref, watch } from '@nuxtjs/composition-api'
+
+/**
+ * @typedef Props
+ * @property {import('./types').Ref<HTMLElement>} popoverRef
+ * @property {import('./types').ToRefs<import('../components/VPopover/VPopover.types').Props>} popoverPropsRefs
+ */
+
+/**
+ *
+ * @param {Element | null} element
+ * @return {element is Element}
+ */
+function isActualElement(element) {
+ return (
+ element &&
+ element.tagName &&
+ element.tagName !== 'HTML' &&
+ element !== getDocument(element).body
+ )
+}
+
+/**
+ * @returns {[import('./types').Ref<number>, (n: number) => void]}
+ */
+function useBlurTracker() {
+ const blurredRef = ref(0)
+
+ const scheduleFocus = () => (blurredRef.value += 1)
+
+ return [blurredRef, scheduleFocus]
+}
+
+/**
+ * @param {Props} props
+ */
+export function useFocusOnBlur({ popoverRef, popoverPropsRefs }) {
+ const [blurredRef, scheduleFocus] = useBlurTracker()
+
+ watch([blurredRef], ([blurred]) => {
+ if (!popoverPropsRefs.visible.value) return
+ if (!blurred) return
+ if (!isActualElement(getActiveElement(popoverRef.value))) {
+ popoverRef.value?.focus()
+ }
+ })
+
+ /**
+ * @param {FocusEvent} event
+ */
+ const onBlur = (event) => {
+ if (popoverPropsRefs.visible.value) return
+ const nextActiveElement = getNextActiveElementOnBlur(event)
+ if (!isActualElement(nextActiveElement)) {
+ scheduleFocus()
+ }
+ }
+
+ return onBlur
+}
diff --git a/src/composables/use-focus-on-hide.js b/src/composables/use-focus-on-hide.js
new file mode 100644
index 000000000..afd256c98
--- /dev/null
+++ b/src/composables/use-focus-on-hide.js
@@ -0,0 +1,59 @@
+import { watch } from '@vue/composition-api'
+import {
+ isTabbable,
+ getActiveElement,
+ contains,
+ ensureFocus,
+} from 'reakit-utils'
+
+/**
+ * @typedef Props
+ * @property {import('./types').Ref<HTMLElement>} popoverRef
+ * @property {import('./types').ToRefs<import('../components/VPopover/VPopover.types').Props>} popoverPropsRefs
+ */
+
+/**
+ * @param {HTMLElement} popover
+ */
+function hidByFocusingAnotherElement(popover) {
+ if (!popover) return false
+
+ const activeElement = getActiveElement(popover)
+
+ if (!activeElement) return false
+ if (contains(popover, activeElement)) return false
+ if (isTabbable(activeElement)) return true
+
+ return activeElement.getAttribute('data-popover') === 'true'
+}
+
+/**
+ * @param {Props} Props
+ */
+export const useFocusOnHide = ({ popoverRef, popoverPropsRefs }) => {
+ watch(
+ [
+ popoverRef,
+ popoverPropsRefs.triggerElement,
+ popoverPropsRefs.visible,
+ popoverPropsRefs.autoFocusOnHide,
+ ],
+ /**
+ * @param {[HTMLElement, HTMLElement, boolean, boolean]} deps
+ * @param {[unknown, unknown, boolean]} previousDeps
+ */
+ (
+ [popover, triggerElement, visible, autoFocusOnHide],
+ [, , previousVisible]
+ ) => {
+ const shouldFocus =
+ autoFocusOnHide && !visible && visible !== previousVisible
+
+ if (!shouldFocus) return
+
+ if (hidByFocusingAnotherElement(popover)) return
+
+ ensureFocus(triggerElement)
+ }
+ )
+}
diff --git a/src/composables/use-focus-on-show.js b/src/composables/use-focus-on-show.js
new file mode 100644
index 000000000..6ffe746e7
--- /dev/null
+++ b/src/composables/use-focus-on-show.js
@@ -0,0 +1,40 @@
+import { watch } from '@nuxtjs/composition-api'
+import { getFirstTabbableIn, hasFocusWithin, ensureFocus } from 'reakit-utils'
+import { warn } from '~/utils/warn'
+
+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>} popoverRef
+ * @property {import('./types').ToRefs<import('../components/VPopover/VPopover.types').Props>} popoverPropsRefs
+ */
+
+/**
+ * @see https://github.com/reakit/reakit/blob/bce9b8a0e567983f61b5cc627f8dee9461986fab/packages/reakit/src/Dialog/__utils/useFocusOnShow.ts#L9
+ * @param {Props} props
+ */
+export const useFocusOnShow = ({ popoverRef, popoverPropsRefs }) => {
+ watch(
+ [popoverRef, popoverPropsRefs.visible, popoverPropsRefs.autoFocusOnShow],
+ /**
+ * @param {[HTMLElement, boolean, boolean]} values
+ */
+ ([popover, visible, autoFocusOnShow]) => {
+ if (!popover || !visible || !autoFocusOnShow) return
+
+ const tabbable = getFirstTabbableIn(popover, true)
+ const isActive = () => hasFocusWithin(popover)
+
+ if (tabbable) {
+ ensureFocus(tabbable, { preventScroll: true, isActive })
+ } else {
+ ensureFocus(popover, { preventScroll: true, isActive })
+ if (popover.tabIndex === undefined || popover.tabIndex < 0) {
+ warn(noFocusableElementWarning)
+ }
+ }
+ }
+ )
+}
diff --git a/src/composables/use-hide-on-click-outside.js b/src/composables/use-hide-on-click-outside.js
new file mode 100644
index 000000000..5b588a340
--- /dev/null
+++ b/src/composables/use-hide-on-click-outside.js
@@ -0,0 +1,84 @@
+import { ref, watch, computed } from '@nuxtjs/composition-api'
+import { getDocument } from 'reakit-utils'
+import { useEventListenerOutside } from './use-event-listener-outside'
+
+/**
+ * @typedef Props
+ * @property {import('./types').Ref<HTMLElement>} popoverRef
+ * @property {import('./types').ToRefs<import('../components/VPopover/VPopover.types').Props>} popoverPropsRefs
+ */
+
+/**
+ * @param {Props} props
+ * @return {import('./types').Ref<EventTarget>}
+ */
+function useMouseDownTargetRef({ popoverRef, popoverPropsRefs }) {
+ const mouseDownTargetRef = ref()
+
+ watch(
+ [popoverPropsRefs.visible, popoverPropsRefs.hideOnClickOutside, popoverRef],
+ /**
+ * @param {[boolean, boolean, HTMLElement]} deps
+ * @param {unknown} _
+ * @param {(cb: () => void) => void} onInvalidate
+ */
+ ([visible, hideOnClickOutside, popover], _, onInvalidate) => {
+ if (!(visible && hideOnClickOutside)) return
+
+ const document = getDocument(popover)
+ const onMouseDown = (event) => (mouseDownTargetRef.value = event.target)
+ document.addEventListener('mousedown', onMouseDown)
+ onInvalidate(() => {
+ document.addEventListener('mousedown', onMouseDown)
+ })
+ },
+ { immediate: true }
+ )
+
+ return mouseDownTargetRef
+}
+
+/**
+ * @param {Props} props
+ */
+export function useHideOnClickOutside({ popoverRef, popoverPropsRefs }) {
+ const mouseDownTargetRef = useMouseDownTargetRef({
+ popoverRef,
+ popoverPropsRefs,
+ })
+
+ const shouldListenRef = computed(
+ () =>
+ popoverPropsRefs.visible.value &&
+ popoverPropsRefs.hideOnClickOutside.value
+ )
+
+ useEventListenerOutside({
+ containerRef: popoverRef,
+ triggerRef: popoverPropsRefs.triggerElement,
+ eventType: 'click',
+ listener: (event) => {
+ if (mouseDownTargetRef.value === event.target) {
+ // Make sure the element that has been clicked is the same that last
+ // triggered the mousedown event. This prevents the dialog from closing
+ // by dragging the cursor (for example, selecting some text inside the
+ // dialog and releasing the mouse outside of it).
+ popoverPropsRefs.hide.value()
+ }
+ },
+ shouldListenRef,
+ })
+
+ useEventListenerOutside({
+ containerRef: popoverRef,
+ triggerRef: popoverPropsRefs.triggerElement,
+ eventType: 'focusin',
+ listener: (event) => {
+ const document = getDocument(popoverRef.value)
+ if (event.target !== document) {
+ popoverPropsRefs.hide.value()
+ }
+ },
+ shouldListenRef,
+ })
+}
diff --git a/src/composables/use-popover-content.js b/src/composables/use-popover-content.js
new file mode 100644
index 000000000..9c2a71549
--- /dev/null
+++ b/src/composables/use-popover-content.js
@@ -0,0 +1,24 @@
+import { useFocusOnShow } from '~/composables/use-focus-on-show'
+import { useFocusOnHide } from '~/composables/use-focus-on-hide'
+import { useHideOnClickOutside } from '~/composables/use-hide-on-click-outside'
+import { useFocusOnBlur } from '~/composables/use-focus-on-blur'
+import { usePopper } from '~/composables/use-popper'
+
+/**
+ * @typedef Props
+ * @property {import('./types').Ref<HTMLElement>} popoverRef
+ * @property {import('./types').ToRefs<import('../components/VPopover/VPopoverContent.types').Props>} popoverPropsRefs
+ */
+
+/**
+ * @param {Props} props
+ */
+export function usePopoverContent(props) {
+ const focusOnBlur = useFocusOnBlur(props)
+ useFocusOnShow(props)
+ useFocusOnHide(props)
+ useHideOnClickOutside(props)
+ usePopper(props)
+
+ return { focusOnBlur }
+}
diff --git a/src/composables/use-popper.js b/src/composables/use-popper.js
new file mode 100644
index 000000000..3d66f6611
--- /dev/null
+++ b/src/composables/use-popper.js
@@ -0,0 +1,64 @@
+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.triggerElement,
+ popoverRef,
+ ],
+ /**
+ * @param {[boolean, import('@popperjs/core').Placement, number]} deps
+ * @param {unknown} _
+ * @param {(cb: () => void) => void} onInvalidate
+ */
+ ([visible, placement, triggerElement, popover], _, onInvalidate) => {
+ if (!(triggerElement && popover)) return
+
+ popperInstanceRef.value = createPopper(triggerElement, popover, {
+ placement,
+ strategy: 'absolute',
+ 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/utils/warn.js b/src/utils/warn.js
new file mode 100644
index 000000000..c54800ac1
--- /dev/null
+++ b/src/utils/warn.js
@@ -0,0 +1,2 @@
+export const warn =
+ process.env.NODE_ENV !== 'production' ? console.warn : () => {}
diff --git a/test/unit/specs/components/v-button.spec.js b/test/unit/specs/components/v-button.spec.js
index b3c75fae7..c1f04c14f 100644
--- a/test/unit/specs/components/v-button.spec.js
+++ b/test/unit/specs/components/v-button.spec.js
@@ -1,6 +1,11 @@
import { render, screen } from '@testing-library/vue'
import VButton from '~/components/VButton.vue'
+import { warn } from '~/utils/warn'
+
+jest.mock('~/utils/warn', () => ({ warn: jest.fn() }))
+
+const nextTick = () => new Promise((r) => setTimeout(r, 0))
/**
* Throughout this suite we use the `screen.findBy*` functions to asynchronously
@@ -10,18 +15,9 @@ import VButton from '~/components/VButton.vue'
* won't be rendered.
*/
describe('VButton', () => {
- let warn
- beforeAll(() => {
- warn = console.warn
- console.warn = jest.fn()
- })
- beforeEach(() => {
- console.warn.mockReset()
+ afterEach(() => {
+ warn.mockReset()
})
- afterAll(() => {
- console.warn = warn
- })
-
it('should render a `button` by default with type="button" and no tabindex', async () => {
render(VButton, {
slots: { default: 'Code is Poetry' },
@@ -45,17 +41,15 @@ describe('VButton', () => {
expect(element).toHaveAttribute('type', 'submit')
})
- // @todo(sarayourfriend) fix this failing test!
- it.skip('should render an anchor with no type attribute', async () => {
+ it('should render an anchor with no type attribute', async () => {
render(VButton, {
props: { as: 'a' },
slots: { default: 'Code is Poetry' },
})
+ await nextTick()
const element = await screen.findByText(/code is poetry/i)
- screen.debug(element)
-
expect(element.tagName).toBe('A')
expect(element).not.toHaveAttribute('type')
})
@@ -111,8 +105,8 @@ describe('VButton', () => {
await screen.findByText(/code is poetry/i)
- expect(console.warn).toHaveBeenCalledTimes(1)
- expect(console.warn).toHaveBeenCalledWith(
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(warn).toHaveBeenCalledWith(
'Do not use anchor elements without a valid `href` attribute. Use a `button` instead.'
)
}
diff --git a/test/unit/specs/components/v-popover.spec.js b/test/unit/specs/components/v-popover.spec.js
new file mode 100644
index 000000000..a30ebc325
--- /dev/null
+++ b/test/unit/specs/components/v-popover.spec.js
@@ -0,0 +1,179 @@
+import Vue from 'vue'
+import { render, screen } from '@testing-library/vue'
+import userEvent from '@testing-library/user-event'
+import VButton from '~/components/VButton.vue'
+import VPopover from '~/components/VPopover/VPopover.vue'
+import { noFocusableElementWarning } from '~/composables/use-focus-on-show'
+import { warn } from '~/utils/warn'
+
+jest.mock('~/utils/warn', () => ({
+ warn: jest.fn(),
+}))
+
+const TestWrapper = Vue.component('TestWrapper', {
+ components: { VButton, VPopover },
+ props: {
+ popoverProps: {
+ type: Object,
+ default: () => {},
+ },
+ popoverContentTabIndex: {
+ type: Number,
+ default: undefined,
+ },
+ },
+ template: `
+ <div>
+ <!-- This div is a clickable area that is neither the trigger nor the content, useful for testing click-away behavior -->
+ <div>External area</div>
+ <VPopover label="Test label" v-bind="popoverProps">
+ <template #trigger="{ visible, a11yProps }">
+ <VButton :pressed="visible" v-bind="a11yProps">{{ visible ? 'Close' : 'Open' }}</VButton>
+ </template>
+ <div :tabindex="popoverContentTabIndex">Code is Poetry</div>
+ </VPopover>
+ </div>
+ `,
+})
+
+const nextTick = async () =>
+ await new Promise((resolve) => setTimeout(resolve, 1))
+
+const getPopover = () => screen.getByText(/code is poetry/i)
+const queryPopover = () => screen.queryByText(/code is poetry/i)
+const getTrigger = () => screen.getByRole('button')
+const getExternalArea = () => screen.getByText(/external area/i)
+const clickOutside = () => userEvent.click(getExternalArea())
+
+const doOpen = async (trigger = getTrigger(), verify = true) => {
+ await userEvent.click(trigger)
+ await nextTick()
+ if (verify) {
+ expectOpen()
+ }
+}
+
+const expectOpen = () => {
+ expect(getPopover()).toBeVisible()
+}
+
+const expectClosed = () => {
+ expect(queryPopover()).toBe(null)
+}
+
+describe('VPopover', () => {
+ afterEach(() => {
+ warn.mockReset()
+ })
+
+ it('should open the popover when the trigger is clicked', async () => {
+ render(TestWrapper)
+
+ expectClosed()
+
+ // doOpen already has the visible assertion built in
+ await doOpen()
+ })
+
+ describe('accessibility', () => {
+ it('should render a11y props for the trigger', async () => {
+ render(TestWrapper)
+
+ const trigger = getTrigger()
+
+ // This attribute will always exist
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog')
+
+ // This attribute will only exist when the trigger's related popover is open and the trigger was the current disclosure
+ expect(trigger).not.toHaveAttribute('aria-expanded')
+
+ await doOpen(trigger)
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'true')
+ })
+
+ describe('autoFocusOnShow', () => {
+ it('should focus the popover by default when opening if there is no tabbable content in the popover and warn', async () => {
+ render(TestWrapper)
+ await doOpen()
+ expect(getPopover().parentElement).toHaveFocus()
+
+ expect(warn).toHaveBeenCalledWith(noFocusableElementWarning)
+ })
+
+ it('should focus the first tabbable element in the popover by default and not warn', async () => {
+ render(TestWrapper, { props: { popoverContentTabIndex: 0 } })
+ await doOpen()
+ expect(getPopover()).toHaveFocus()
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('should neither focus no warn when the prop is false', async () => {
+ render(TestWrapper, {
+ props: { popoverProps: { autoFocusOnShow: false } },
+ })
+ getTrigger().focus()
+ await doOpen()
+ expect(getTrigger()).toHaveFocus()
+ expect(warn).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('autoFocusOnHide', () => {
+ it('should return focus to the trigger', async () => {
+ render(TestWrapper)
+ await doOpen()
+ await clickOutside()
+ expectClosed()
+ expect(getTrigger()).toHaveFocus()
+ })
+
+ it('should not return focus to the trigger when false', async () => {
+ render(TestWrapper, {
+ props: { popoverProps: { autoFocusOnHide: false } },
+ })
+ await doOpen()
+ await clickOutside()
+ expect(getTrigger()).not.toHaveFocus()
+ })
+ })
+ })
+
+ describe('hideOnClickOutside', () => {
+ it('should hide the popover if a click happens outside the popover by default', async () => {
+ render(TestWrapper)
+
+ await doOpen()
+
+ await clickOutside()
+ expectClosed()
+ })
+
+ it('should not hide the popover if a click happens outside the popover when false', async () => {
+ render(TestWrapper, {
+ props: { popoverProps: { hideOnClickOutside: false } },
+ })
+
+ await doOpen()
+
+ await clickOutside()
+ expectOpen()
+ })
+ })
+
+ describe('hideOnEsc', () => {
+ it('should hide the popover if escape is sent in the popover by default', async () => {
+ render(TestWrapper)
+ await doOpen()
+ await userEvent.keyboard('{escape}')
+ expectClosed()
+ })
+
+ it('should not hide if the escape is sent in the popover when false', async () => {
+ render(TestWrapper, { props: { popoverProps: { hideOnEsc: false } } })
+ await doOpen()
+ await userEvent.keyboard('{escape}')
+ expectOpen()
+ })
+ })
+})