Skip to content

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

Allow focusing specific element when opening modal (#695)

sarayourfriend7d74f033ddc4
diff --git a/src/components/VContentSwitcher/VContentTypes.vue b/src/components/VContentSwitcher/VContentTypes.vue
index 2e059a7cd..808ca72fe 100644
--- a/src/components/VContentSwitcher/VContentTypes.vue
+++ b/src/components/VContentSwitcher/VContentTypes.vue
@@ -25,9 +25,9 @@ import useContentType from '~/composables/use-content-type'
import VItemGroup from '~/components/VItemGroup/VItemGroup.vue'
import VContentItem from '~/components/VContentSwitcher/VContentItem.vue'
-import { computed } from '@nuxtjs/composition-api'
+import { computed, defineComponent } from '@nuxtjs/composition-api'
-export default {
+export default defineComponent({
name: 'VContentTypes',
components: { VItemGroup, VContentItem },
props: {
@@ -58,5 +58,5 @@ export default {
handleClick,
}
},
-}
+})
</script>
diff --git a/src/components/VContentSwitcher/VMobileMenuModal.vue b/src/components/VContentSwitcher/VMobileMenuModal.vue
index e94ba497e..164fa2696 100644
--- a/src/components/VContentSwitcher/VMobileMenuModal.vue
+++ b/src/components/VContentSwitcher/VMobileMenuModal.vue
@@ -15,9 +15,11 @@
:trigger-element="triggerRef"
:hide="close"
:aria-label="$t('header.filter-button.simple')"
+ :initial-focus-element="initialFocusElement"
>
<nav class="p-6" aria-labelledby="content-switcher-heading">
<VContentTypes
+ ref="contentTypesNode"
size="small"
:active-item="content.activeType.value"
@select="selectItem"
@@ -29,7 +31,13 @@
</template>
<script>
-import { onMounted, reactive, ref, watch } from '@nuxtjs/composition-api'
+import {
+ onMounted,
+ reactive,
+ ref,
+ watch,
+ computed,
+} from '@nuxtjs/composition-api'
import { useBodyScrollLock } from '~/composables/use-body-scroll-lock'
import useContentType from '~/composables/use-content-type'
import usePages from '~/composables/use-pages'
@@ -61,6 +69,8 @@ export default {
const content = useContentType()
const pages = usePages()
+ /** @type {import('@nuxtjs/composition-api').Ref<import('vue/types/vue').Vue | null>} */
+ const contentTypesNode = ref(null)
const modalRef = ref(null)
const triggerContainerRef = ref(null)
@@ -77,6 +87,10 @@ export default {
const triggerRef = ref()
onMounted(() => (triggerRef.value = triggerContainerRef.value?.firstChild))
+ const initialFocusElement = computed(() =>
+ contentTypesNode.value?.$el?.querySelector('[aria-checked="true"]')
+ )
+
watch([visibleRef], ([visible]) => {
triggerA11yProps['aria-expanded'] = visible
})
@@ -130,6 +144,8 @@ export default {
triggerA11yProps,
visibleRef,
selectItem,
+ initialFocusElement,
+ contentTypesNode,
}
},
}
diff --git a/src/components/VModal/VMobileModalContent.vue b/src/components/VModal/VMobileModalContent.vue
index 70d223fc0..300875d9a 100644
--- a/src/components/VModal/VMobileModalContent.vue
+++ b/src/components/VModal/VMobileModalContent.vue
@@ -102,6 +102,12 @@ const VMobileModalContent = defineComponent({
process.server ? Object : HTMLElement
),
},
+ initialFocusElement: {
+ type: /** @type {import('@nuxtjs/composition-api').PropType<HTMLElement>} */ (
+ process.server ? Object : HTMLElement
+ ),
+ required: false,
+ },
},
setup(props, { emit, attrs }) {
if (!attrs['aria-label'] && !attrs['aria-labelledby']) {
@@ -119,6 +125,7 @@ const VMobileModalContent = defineComponent({
hideOnClickOutsideRef: propsRefs.hideOnClickOutside,
hideRef: propsRefs.hide,
hideOnEscRef: propsRefs.hideOnEsc,
+ initialFocusElementRef: propsRefs.initialFocusElement,
emit,
})
diff --git a/src/components/VModal/VModal.vue b/src/components/VModal/VModal.vue
index 3a87cf7c3..65a44af02 100644
--- a/src/components/VModal/VModal.vue
+++ b/src/components/VModal/VModal.vue
@@ -22,6 +22,7 @@
:hide="close"
:aria-label="label"
:aria-labelledby="labelledBy"
+ :initial-focus-element="initialFocusElement"
>
<slot name="default" />
</VModalContent>
@@ -86,6 +87,20 @@ export default defineComponent({
* @default undefined
*/
labelledBy: { type: String },
+ /**
+ * The element to focus when the modal is opened. If nothing is
+ * passed, then the first tabbable element in the modal content
+ * will be focused. If no tabbable element is found in the modal
+ * content, then the entire modal content itself will be focused.
+ *
+ * @default undefined
+ */
+ initialFocusElement: {
+ type: /** @type {import('@nuxtjs/composition-api').PropType<HTMLElement>} */ (
+ process.server ? Object : HTMLElement
+ ),
+ default: undefined,
+ },
},
emits: [
/**
diff --git a/src/components/VModal/VModalContent.vue b/src/components/VModal/VModalContent.vue
index 8b65dd96f..f63a2f7aa 100644
--- a/src/components/VModal/VModalContent.vue
+++ b/src/components/VModal/VModalContent.vue
@@ -85,6 +85,12 @@ const VModalContent = defineComponent({
process.server ? Object : HTMLElement
),
},
+ initialFocusElement: {
+ type: /** @type {import('@nuxtjs/composition-api').PropType<HTMLElement>} */ (
+ process.server ? Object : HTMLElement
+ ),
+ required: false,
+ },
},
setup(props, { emit, attrs }) {
if (!attrs['aria-label'] && !attrs['aria-labelledby']) {
@@ -102,6 +108,7 @@ const VModalContent = defineComponent({
hideOnClickOutsideRef: propsRefs.hideOnClickOutside,
hideRef: propsRefs.hide,
hideOnEscRef: propsRefs.hideOnEsc,
+ initialFocusElementRef: propsRefs.initialFocusElement,
emit,
})
diff --git a/src/components/VModal/meta/VModal.stories.js b/src/components/VModal/meta/VModal.stories.js
index e3c38d6c1..4a271a31d 100644
--- a/src/components/VModal/meta/VModal.stories.js
+++ b/src/components/VModal/meta/VModal.stories.js
@@ -1,3 +1,5 @@
+import { ref, computed } from '@nuxtjs/composition-api'
+
import VModal from '~/components/VModal/VModal.vue'
import VModalTarget from '~/components/VModal/VModalTarget.vue'
import VButton from '~/components/VButton.vue'
@@ -13,13 +15,17 @@ export default {
autoFocusOnHide: 'boolean',
label: 'text',
labelledBy: 'text',
+ useCustomInitialFocus: {
+ type: 'boolean',
+ default: false,
+ },
},
}
const DefaultStory = (args, { argTypes }) => ({
template: `
<div>
- <VModal v-bind="$props">
+ <VModal v-bind="$props" :initial-focus-element="resolvedInitialFocusElement">
<template #trigger="{ a11yProps, visible }">
<VButton v-bind="a11yProps">{{ visible ? 'Modal open' : 'Modal closed' }}</VButton>
</template>
@@ -43,6 +49,8 @@ const DefaultStory = (args, { argTypes }) => ({
Polymer is a Javascript NoSQL database. Passport. JavaScript web apps. Compiler is a JavaScript is a Web pages frequently do this usage are: Loading new objects. 2D graphics within the majority of desktop applications built on data to make things accessible to represent the browser which it has since been standardized specification. Test-Driven Development. WebGL is said to pages and out, resizing them, etc. Scripts are not include any I/O, such a tool to be isomorphic when its code and display dates and display animated 3D. C. Factory Pattern is a way for Behaviour-Driven Development. API for Behaviour-Driven Development. JSX is a design. Ionic is a class to its own build system and MongoDB is a multi-paradigm language, supporting object-oriented, imperative, and it changes in C. Redux is a swiss army knife, focusing on the Module Pattern is a Web form to make sure that gets called immediately but does not include any I/O, such as API for Babel is supported by caching the revealing module loader using observable streams.
</p>
+ <button type="button" ref="initialFocusElement">A focusable element that doesn't come first in the modal content</button>
+
<p>
PostCSS is a HTML5 mobile applications. Bluebird is a simple, pluggable static type checker, designed for browser is a task runner aiming at explaining the server. Native development. Patterns is a framework for dynamic web. Flux is a swiss army knife, focusing on Node. Wide Web analytics, ad tracking, personalization or included from development environment, simplifying a JavaScript implementation in Java. Mediator Pattern is used in and media queries. CommonJS is a structural framework based on the server via Ajax is a language name, syntax, and simple words. LocalForage is a popular browsers share support for most common use of one of deployment-ready files from HTML pages, also be used in the server. Arity is a JavaScript engine. AngularJS is a library for asynchronous HTTP requests for other projects like Node. VMs and the three core technologies of their containing scope. Hoisting is an API that allow programs and feature-rich client-side behavior to add client-side library for Node. Redux is by Nitobi. Rhino, like SpiderMonkey, is a Node.
</p>
@@ -76,6 +84,15 @@ const DefaultStory = (args, { argTypes }) => ({
`,
components: { VButton, VModal, VModalTarget, VPopover },
props: Object.keys(argTypes),
+ setup(props) {
+ const initialFocusElement = ref()
+
+ const resolvedInitialFocusElement = computed(() =>
+ props.useCustomInitialFocus ? initialFocusElement.value : undefined
+ )
+
+ return { initialFocusElement, resolvedInitialFocusElement }
+ },
})
export const Default = DefaultStory.bind({})
diff --git a/src/composables/use-dialog-content.js b/src/composables/use-dialog-content.js
index 3a322e638..3cc6647e6 100644
--- a/src/composables/use-dialog-content.js
+++ b/src/composables/use-dialog-content.js
@@ -12,6 +12,7 @@ import { useFocusOnBlur } from '~/composables/use-focus-on-blur'
* @property {boolean} autoFocusOnHideRef
* @property {boolean} hideOnClickOutsideRef
* @property {boolean} hideOnEscRef
+ * @property {HTMLElement} initialFocusElementRef
* @property {() => void} hideRef
*/
diff --git a/src/composables/use-focus-on-show.js b/src/composables/use-focus-on-show.js
index 26b2aa971..6eb34945c 100644
--- a/src/composables/use-focus-on-show.js
+++ b/src/composables/use-focus-on-show.js
@@ -1,4 +1,4 @@
-import { watch } from '@nuxtjs/composition-api'
+import { ref, watch } from '@nuxtjs/composition-api'
import { getFirstTabbableIn } from 'reakit-utils/tabbable'
import { hasFocusWithin } from 'reakit-utils/hasFocusWithin'
import { ensureFocus } from 'reakit-utils/ensureFocus'
@@ -13,6 +13,7 @@ export const noFocusableElementWarning =
* @property {import('./types').Ref<HTMLElement>} dialogRef
* @property {import('./types').Ref<boolean>} visibleRef
* @property {import('./types').Ref<boolean>} autoFocusOnShowRef
+ * @property {import('./types').Ref<HTMLElement>} initialFocusElementRef
*/
/**
@@ -23,18 +24,27 @@ export const useFocusOnShow = ({
dialogRef,
visibleRef,
autoFocusOnShowRef,
+ initialFocusElementRef = ref(),
}) => {
watch(
- [dialogRef, visibleRef, autoFocusOnShowRef],
+ [dialogRef, visibleRef, autoFocusOnShowRef, initialFocusElementRef],
/**
- * @param {[HTMLElement, boolean, boolean]} values
+ * @param {[HTMLElement, boolean, boolean, HTMLElement]} values
*/
- ([dialog, visible, autoFocusOnShow]) => {
+ ([dialog, visible, autoFocusOnShow, initialFocusElement]) => {
if (!dialog || !visible || !autoFocusOnShow) return
- const tabbable = getFirstTabbableIn(dialog, true)
const isActive = () => hasFocusWithin(dialog)
+ if (initialFocusElement) {
+ return ensureFocus(initialFocusElement, {
+ preventScroll: true,
+ isActive,
+ })
+ }
+
+ const tabbable = getFirstTabbableIn(dialog, true)
+
if (tabbable) {
ensureFocus(tabbable, { preventScroll: true, isActive })
} else {
diff --git a/test/unit/specs/components/v-modal.spec.js b/test/unit/specs/components/v-modal.spec.js
index 06f700a93..fdfd162ef 100644
--- a/test/unit/specs/components/v-modal.spec.js
+++ b/test/unit/specs/components/v-modal.spec.js
@@ -1,4 +1,5 @@
import Vue from 'vue'
+import { ref, computed } from '@nuxtjs/composition-api'
import { render, screen } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
@@ -8,14 +9,26 @@ import VButton from '~/components/VButton.vue'
const TestWrapper = Vue.component('TestWrapper', {
components: { VModal, VButton, VModalTarget },
+ props: ['useCustomInitialFocus'],
+ setup(props) {
+ const initialFocusElement = ref()
+
+ const resolvedInitialFocusElement = computed(() =>
+ props.useCustomInitialFocus ? initialFocusElement.value : undefined
+ )
+
+ return { initialFocusElement, resolvedInitialFocusElement }
+ },
template: `
<div>
- <VModal label="modal label">
+ <VModal label="modal label" :initial-focus-element="resolvedInitialFocusElement">
<template #trigger="{ a11yProps, visible }">
<VButton v-bind="a11yProps">{{ visible }}</VButton>
</template>
<div>Code is Poetry</div>
+
+ <button ref="initialFocusElement" type="button">Custom initial focus</button>
</VModal>
<VModalTarget />
</div>
@@ -25,6 +38,7 @@ const TestWrapper = Vue.component('TestWrapper', {
const nextTick = async () =>
await new Promise((resolve) => setTimeout(resolve, 1))
+const getCloseButton = () => screen.getByText('modal.close')
const getDialog = () => screen.getByRole('dialog')
const queryDialog = () => screen.queryByRole('dialog')
const getTrigger = () => screen.getByRole('button')
@@ -56,7 +70,7 @@ describe('VModal', () => {
expect(getDialog()).toBeVisible()
- await userEvent.click(screen.getByText('modal.close'))
+ await userEvent.click(getCloseButton())
await nextTick()
expect(queryDialog()).toBe(null)
@@ -78,4 +92,20 @@ describe('VModal', () => {
expect(window.scrollTo).toHaveBeenCalledWith(0, scrollY)
expect(container.ownerDocument.body.style.position).not.toBe('fixed')
})
+
+ it('should focus the close button by default', async () => {
+ render(TestWrapper)
+ await doOpen()
+
+ expect(getDialog()).toBeVisible()
+ expect(getCloseButton()).toHaveFocus()
+ })
+
+ it('should focus the explicit initial focus element when specified', async () => {
+ render(TestWrapper, { props: { useCustomInitialFocus: true } })
+ await doOpen()
+
+ expect(getDialog()).toBeVisible()
+ expect(screen.getByText(/custom initial focus/i))
+ })
})