Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add Modal component (#469)
sarayourfriend4cc5d60e2a97
diff --git a/package-lock.json b/package-lock.jsonindex ad85cec55..55a33f523 100644--- a/package-lock.json+++ b/package-lock.json@@ -24,8 +24,8 @@"core-js": "^3.16.1","deepmerge": "^4.2.2","filesize": "^8.0.2",- "focus-trap": "^5.1.0",- "focus-trap-vue": "0.0.6",+ "focus-trap": "^6.7.1",+ "focus-trap-vue": "1.1.1","glob": "^7.1.6","js-cookie": "^2.2.1","lodash.clonedeep": "^4.5.0",@@ -16751,20 +16751,19 @@}},"node_modules/focus-trap": {- "version": "5.1.0",- "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-5.1.0.tgz",- "integrity": "sha512-CkB/nrO55069QAUjWFBpX6oc+9V90Qhgpe6fBWApzruMq5gnlh90Oo7iSSDK7pKiV5ugG6OY2AXM5mxcmL3lwQ==",+ "version": "6.7.1",+ "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-6.7.1.tgz",+ "integrity": "sha512-a6czHbT9twVpy2RpkWQA9vIgwQgB9Nx1PIxNNUxQT4nugG/3QibwxO+tWTh9i+zSY2SFiX4pnYhTaFaQF/6ZAg==","dependencies": {- "tabbable": "^4.0.0",- "xtend": "^4.0.1"+ "tabbable": "^5.2.1"}},"node_modules/focus-trap-vue": {- "version": "0.0.6",- "resolved": "https://registry.npmjs.org/focus-trap-vue/-/focus-trap-vue-0.0.6.tgz",- "integrity": "sha512-U6/Qt7kAUFHirurz1HqFMxtvjcQ397JZyShcDyRrmBLEkXu/q8sSKYtm2s+wWxO2ebE3HZySUBfc/iTfY4+UCQ==",+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/focus-trap-vue/-/focus-trap-vue-1.1.1.tgz",+ "integrity": "sha512-N+M4d4uYymCogct417gUL7wWSMIW/oUcCicfg3eRdo+gz7jlQnIGwUwViFxPkKV7iyzpc81g6JeSxRWiYWU3eQ==","peerDependencies": {- "focus-trap": "^5.0.2",+ "focus-trap": "^6.0.1","vue": "^2.6.0"}},@@ -31813,9 +31812,9 @@}},"node_modules/tabbable": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-4.0.0.tgz",- "integrity": "sha512-H1XoH1URcBOa/rZZWxLxHCtOdVUEev+9vo5YdYhC9tCY4wnybX+VQrCYuy9ubkg69fCBxCONJOSLGfw0DWMffQ=="+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-5.2.1.tgz",+ "integrity": "sha512-40pEZ2mhjaZzK0BnI+QGNjJO8UYx9pP5v7BGe17SORTO0OEuuaAwQTkAp8whcZvqon44wKFOikD+Al11K3JICQ=="},"node_modules/table": {"version": "6.7.3",@@ -48224,18 +48223,17 @@}},"focus-trap": {- "version": "5.1.0",- "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-5.1.0.tgz",- "integrity": "sha512-CkB/nrO55069QAUjWFBpX6oc+9V90Qhgpe6fBWApzruMq5gnlh90Oo7iSSDK7pKiV5ugG6OY2AXM5mxcmL3lwQ==",+ "version": "6.7.1",+ "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-6.7.1.tgz",+ "integrity": "sha512-a6czHbT9twVpy2RpkWQA9vIgwQgB9Nx1PIxNNUxQT4nugG/3QibwxO+tWTh9i+zSY2SFiX4pnYhTaFaQF/6ZAg==","requires": {- "tabbable": "^4.0.0",- "xtend": "^4.0.1"+ "tabbable": "^5.2.1"}},"focus-trap-vue": {- "version": "0.0.6",- "resolved": "https://registry.npmjs.org/focus-trap-vue/-/focus-trap-vue-0.0.6.tgz",- "integrity": "sha512-U6/Qt7kAUFHirurz1HqFMxtvjcQ397JZyShcDyRrmBLEkXu/q8sSKYtm2s+wWxO2ebE3HZySUBfc/iTfY4+UCQ==",+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/focus-trap-vue/-/focus-trap-vue-1.1.1.tgz",+ "integrity": "sha512-N+M4d4uYymCogct417gUL7wWSMIW/oUcCicfg3eRdo+gz7jlQnIGwUwViFxPkKV7iyzpc81g6JeSxRWiYWU3eQ==","requires": {}},"follow-redirects": {@@ -59836,9 +59834,9 @@}},"tabbable": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-4.0.0.tgz",- "integrity": "sha512-H1XoH1URcBOa/rZZWxLxHCtOdVUEev+9vo5YdYhC9tCY4wnybX+VQrCYuy9ubkg69fCBxCONJOSLGfw0DWMffQ=="+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-5.2.1.tgz",+ "integrity": "sha512-40pEZ2mhjaZzK0BnI+QGNjJO8UYx9pP5v7BGe17SORTO0OEuuaAwQTkAp8whcZvqon44wKFOikD+Al11K3JICQ=="},"table": {"version": "6.7.3",diff --git a/package.json b/package.jsonindex eed28d5f0..daac26658 100644--- a/package.json+++ b/package.json@@ -53,8 +53,8 @@"core-js": "^3.16.1","deepmerge": "^4.2.2","filesize": "^8.0.2",- "focus-trap": "^5.1.0",- "focus-trap-vue": "0.0.6",+ "focus-trap": "^6.7.1",+ "focus-trap-vue": "1.1.1","glob": "^7.1.6","js-cookie": "^2.2.1","lodash.clonedeep": "^4.5.0",diff --git a/src/components/SaferBrowsing.vue b/src/components/SaferBrowsing.vueindex 4cc43be7b..6d4207ad7 100644--- a/src/components/SaferBrowsing.vue+++ b/src/components/SaferBrowsing.vue@@ -8,7 +8,7 @@>{{ $t('browse-page.safer-browsing.title') }}</button>- <FocusTrap :active="true">+ <FocusTrap :active="showForm"><div v-show="showForm" class="p-4 arrow-popup arrow-popup--anchor-right"><buttonclass="button close-button is-text tiny float-right block text-light-gray"diff --git a/src/components/VButton.vue b/src/components/VButton.vueindex 58577c3bf..0110cbbf9 100644--- a/src/components/VButton.vue+++ b/src/components/VButton.vue@@ -87,14 +87,15 @@ const VButton = defineComponent({default: false,},/**- * The size of the button.+ * The size of the button. `disabled` removes all internal padding allowing+ * the consumer of the component to determine the padding.** @default 'medium'*/size: {type: String,default: 'medium',- validate: (v) => ['large', 'medium', 'small'].includes(v),+ validate: (v) => ['large', 'medium', 'small', 'disabled'].includes(v),},/*** Whether the button is disabled. Used alone this will only@@ -270,4 +271,8 @@ a.button {.grouped-pressed {@apply bg-dark-charcoal-10 ring-offset-dark-charcoal-10;}++.plain {+ @apply bg-tx focus-visible:ring-pink;+}</style>diff --git a/src/components/VModal/VModal.vue b/src/components/VModal/VModal.vuenew file mode 100644index 000000000..3a87cf7c3--- /dev/null+++ b/src/components/VModal/VModal.vue@@ -0,0 +1,155 @@+<template>+ <div ref="nodeRef">+ <div ref="triggerContainerRef" @click="onTriggerClick">+ <!--+ @slot The trigger. Should be a button 99% of the time. If you need custom event handling on the trigger button, ensure bubbling is not prevented or else the dialog will not open.+ @binding {object} a11yProps Props to v-bind to the trigger element to ensure accessibility+ @binding {boolean} visible Whether the dialog is currently visible (open)+ -->+ <slot+ name="trigger"+ :a11y-props="triggerA11yProps"+ :visible="visibleRef"+ />+ </div>+ <VModalContent+ :visible="visibleRef"+ :trigger-element="triggerRef"+ :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 name="default" />+ </VModalContent>+ </div>+</template>++<script>+import {+ defineComponent,+ ref,+ watch,+ reactive,+ computed,+} from '@nuxtjs/composition-api'+import { useBodyScrollLock } from '~/composables/use-body-scroll-lock'+import VModalContent from '~/components/VModal/VModalContent.vue'++export default defineComponent({+ name: 'VModal',+ components: { VModalContent },+ /**+ * 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 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)+ const nodeRef = ref()++ /** @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 { 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 {+ nodeRef,+ visibleRef,+ close,+ triggerContainerRef,+ triggerRef,+ onTriggerClick,+ triggerA11yProps,+ }+ },+})+</script>diff --git a/src/components/VModal/VModalContent.vue b/src/components/VModal/VModalContent.vuenew file mode 100644index 000000000..a68dc40b2--- /dev/null+++ b/src/components/VModal/VModalContent.vue@@ -0,0 +1,113 @@+<template>+ <VTeleport v-if="visible" to="modal">+ <!-- Prevent FocusTrap from trying to focus the first element. We already do that in a more flexible, adaptive way in our Dialog composables. -->+ <FocusTrap :initial-focus="() => false">+ <div+ class="flex justify-center z-10 fixed inset-0 bg-dark-charcoal bg-opacity-75 min-h-screen"+ >+ <div+ ref="dialogRef"+ v-bind="$attrs"+ class="w-4/5 flex flex-col"+ role="dialog"+ aria-modal="true"+ v-on="$listeners"+ @keydown="onKeyDown"+ @blur="onBlur"+ >+ <div class="w-full flex justify-end">+ <VButton+ size="disabled"+ variant="plain"+ class="text-white py-2"+ @click="hide()"+ >+ {{ $t('modal.close') }} <VIcon :icon-path="closeIcon" />+ </VButton>+ </div>++ <div+ class="w-full flex-grow align-bottom bg-white rounded-t-sm text-left overflow-y-auto"+ >+ <slot />+ </div>+ </div>+ </div>+ </FocusTrap>+ </VTeleport>+</template>++<script>+import { defineComponent, toRefs, ref } from '@nuxtjs/composition-api'+import { FocusTrap } from 'focus-trap-vue'+import { VTeleport } from '~/components/VTeleport'+import { useDialogContent } from '~/composables/use-dialog-content'+import { warn } from '~/utils/warn'+import VButton from '~/components/VButton.vue'+import VIcon from '~/components/VIcon/VIcon.vue'+import closeIcon from '~/assets/icons/close.svg'++/**+ * Renders the inner content of a modal and manages focus.+ */+const VModalContent = defineComponent({+ name: 'VModalContent',+ components: { VTeleport, VButton, VIcon, FocusTrap },+ props: {+ 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),+ },+ },+ 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 dialogRef = ref()+ const { onKeyDown, onBlur } = useDialogContent({+ dialogRef,+ visibleRef: propsRefs.visible,+ autoFocusOnShowRef: propsRefs.autoFocusOnShow,+ autoFocusOnHideRef: propsRefs.autoFocusOnHide,+ triggerElementRef: propsRefs.triggerElement,+ hideOnClickOutsideRef: propsRefs.hideOnClickOutside,+ hideRef: propsRefs.hide,+ hideOnEscRef: propsRefs.hideOnEsc,+ emit,+ })++ return { dialogRef, onKeyDown, onBlur, closeIcon }+ },+})++export default VModalContent+</script>++<style module></style>diff --git a/src/components/VModal/VModalTarget.vue b/src/components/VModal/VModalTarget.vuenew file mode 100644index 000000000..1118e12a7--- /dev/null+++ b/src/components/VModal/VModalTarget.vue@@ -0,0 +1,13 @@+<template>+ <VTeleportTarget name="modal" />+</template>++<script>+import { defineComponent } from '@nuxtjs/composition-api'+import { VTeleportTarget } from '~/components/VTeleport'++export default defineComponent({+ name: 'VModalTarget',+ components: { VTeleportTarget },+})+</script>diff --git a/src/components/VModal/meta/VModal.stories.js b/src/components/VModal/meta/VModal.stories.jsnew file mode 100644index 000000000..e3c38d6c1--- /dev/null+++ b/src/components/VModal/meta/VModal.stories.js@@ -0,0 +1,82 @@+import VModal from '~/components/VModal/VModal.vue'+import VModalTarget from '~/components/VModal/VModalTarget.vue'+import VButton from '~/components/VButton.vue'+import VPopover from '~/components/VPopover/VPopover.vue'++export default {+ component: VModal,+ title: 'Components/VModal',+ argTypes: {+ hideOnEsc: 'boolean',+ hideOnClickOutside: 'boolean',+ autoFocusOnShow: 'boolean',+ autoFocusOnHide: 'boolean',+ label: 'text',+ labelledBy: 'text',+ },+}++const DefaultStory = (args, { argTypes }) => ({+ template: `+ <div>+ <VModal v-bind="$props">+ <template #trigger="{ a11yProps, visible }">+ <VButton v-bind="a11yProps">{{ visible ? 'Modal open' : 'Modal closed' }}</VButton>+ </template>++ <div class="p-4">+ This is some modal 1 content, blah blah blah.++ <VPopover>+ <template #trigger="{ a11yProps, visible }">+ <VButton v-bind="a11yProps">{{ visible ? 'Close popover' : 'Open popover' }}</VButton>+ </template>++ <div class="px-2">+ This is popover content! Woohoo! I'm inside a modal!!! Wow!!!+ </div>+ </VPopover>++ <!-- Lots of bogus stuff to test scrolling -->++ <p class="pt-5">+ 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>++ <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>+ </div>+ </VModal>++ <p>Intermediary content. Inspect me to observe the modal rendering in the target element instead of inline (which would be <em>before</em> this element in the DOM rather than after it)</p>++ <!-- Lots of bogus stuff to test scrolling -->++ <hr />++ <p>+ 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>++ <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>++ <p>+ 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>++ <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>++ <VModalTarget />+ </div>+ `,+ components: { VButton, VModal, VModalTarget, VPopover },+ props: Object.keys(argTypes),+})++export const Default = DefaultStory.bind({})+Default.args = {}diff --git a/src/components/VPopover/VPopoverContent.vue b/src/components/VPopover/VPopoverContent.vueindex c54abec7f..b47fb5401 100644--- a/src/components/VPopover/VPopoverContent.vue+++ b/src/components/VPopover/VPopoverContent.vue@@ -46,33 +46,12 @@ export default defineComponent({const propsRefs = toRefs(props)const popoverRef = ref()- const { focusOnBlur } = usePopoverContent({+ const { onKeyDown, onBlur } = usePopoverContent({popoverRef,popoverPropsRefs: propsRefs,+ emit,})- /**- * @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 }},})diff --git a/src/components/VTeleport.js b/src/components/VTeleport.jsnew file mode 100644index 000000000..2dfbcc407--- /dev/null+++ b/src/components/VTeleport.js@@ -0,0 +1,45 @@+// https://gist.github.com/Alan-Liang/a847559433919ecb53dff217ed9708bb++const targets = {}++export const VTeleportTarget = {+ name: 'VTeleportTarget',+ data: () => ({ children: [] }),+ props: {+ name: { type: String, required: true },+ },+ created() {+ if (this.name in targets)+ throw new Error(`VTeleportTarget: duplicate name ${this.name}`)+ targets[this.name] = this+ },+ beforeDestroy() {+ delete targets[this.name]+ if (this.children.length > 0)+ throw new Error(+ `VTeleportTarget: ${this.name} beforeDestroy but still has children mounted`+ )+ },+ render(h) {+ return h('div', this.children.map((vm) => vm.$slots.default || []).flat())+ },+}++export const VTeleport = {+ name: 'VTeleport',+ props: {+ to: { type: String, required: true },+ },+ mounted() {+ if (!(this.to in targets))+ throw new Error(`VTeleport: non-existent target ${this.to}`)+ targets[this.to].children.push(this)+ },+ beforeDestroy() {+ if (!(this.to in targets))+ throw new Error(`VTeleport: non-existent target ${this.to} on unmount`)+ const children = targets[this.to].children+ children.splice(children.indexOf(this), 1)+ },+ render: (h) => h('span'),+}diff --git a/src/composables/use-body-scroll-lock.js b/src/composables/use-body-scroll-lock.jsnew file mode 100644index 000000000..6b54d560e--- /dev/null+++ b/src/composables/use-body-scroll-lock.js@@ -0,0 +1,44 @@+import { ref } from '@nuxtjs/composition-api'+import { getDocument } from 'reakit-utils'++/**+ * Creates a utility for locking body scrolling for a particular node.+ *+ * @param {object} props+ * @param {import('@nuxtjs/composition-api').Ref<HTMLElement>} props.nodeRef+ */+export function useBodyScrollLock({ nodeRef }) {+ const locked = ref(false)+ let scrollY = null++ const lock = () => {+ if (!nodeRef.value) {+ throw new Error(+ 'useBodyScrollLock: Cannot lock body with undefined node reference'+ )+ }++ locked.value = true+ const document = getDocument(nodeRef.value)+ scrollY = window.scrollY+ document.body.style.position = 'fixed'+ document.body.style.top = `-${scrollY}px`+ }++ const unlock = () => {+ if (!nodeRef.value) {+ throw new Error(+ 'useBodyScrollLock: Cannot unlock body with undefined node reference'+ )+ }++ locked.value = false+ const document = getDocument(nodeRef.value)+ document.body.style.position = ''+ document.body.style.top = ''+ window.scrollTo(0, scrollY)+ scrollY = null+ }++ return { locked, lock, unlock }+}diff --git a/src/composables/use-dialog-content.js b/src/composables/use-dialog-content.jsnew file mode 100644index 000000000..3a322e638--- /dev/null+++ b/src/composables/use-dialog-content.js@@ -0,0 +1,52 @@+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'++/**+ * @typedef InnerProps+ * @property {HTMLElement} dialogRef+ * @property {boolean} visibleRef+ * @property {boolean} autoFocusOnShowRef+ * @property {HTMLElement} triggerElementRef+ * @property {boolean} autoFocusOnHideRef+ * @property {boolean} hideOnClickOutsideRef+ * @property {boolean} hideOnEscRef+ * @property {() => void} hideRef+ */++/** @typedef {import('./types').ToRefs<InnerProps> & { emit: import('@nuxtjs/composition-api').SetupContext['emit']}} Props */++/**+ * @param {Props} props+ */+export function useDialogContent({ emit, ...props }) {+ const focusOnBlur = useFocusOnBlur(props)+ useFocusOnShow(props)+ useFocusOnHide(props)+ useHideOnClickOutside(props)++ /**+ * @param {KeyboardEvent} event+ */+ const onKeyDown = (event) => {+ emit('keydown', event)++ if (event.defaultPrevented) return+ if (event.key !== 'Escape') return+ if (!props.hideOnEscRef.value) return++ event.stopPropagation()+ props.hideRef.value()+ }++ /**+ * @param {FocusEvent} event+ */+ const onBlur = (event) => {+ emit('blur', event)+ focusOnBlur(event)+ }++ return { onKeyDown, onBlur }+}diff --git a/src/composables/use-focus-on-blur.js b/src/composables/use-focus-on-blur.jsindex 6c01735e5..c83a8a76e 100644--- a/src/composables/use-focus-on-blur.js+++ b/src/composables/use-focus-on-blur.js@@ -7,8 +7,8 @@ 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+ * @property {import('./types').Ref<HTMLElement>} dialogRef+ * @property {import('./types').Ref<boolean>} visibleRef*//**@@ -39,14 +39,14 @@ function useBlurTracker() {/*** @param {Props} props*/-export function useFocusOnBlur({ popoverRef, popoverPropsRefs }) {+export function useFocusOnBlur({ dialogRef, visibleRef }) {const [blurredRef, scheduleFocus] = useBlurTracker()watch([blurredRef], ([blurred]) => {- if (!popoverPropsRefs.visible.value) return+ if (!visibleRef.value) returnif (!blurred) return- if (!isActualElement(getActiveElement(popoverRef.value))) {- popoverRef.value?.focus()+ if (!isActualElement(getActiveElement(dialogRef.value))) {+ dialogRef.value?.focus()}})@@ -54,7 +54,7 @@ export function useFocusOnBlur({ popoverRef, popoverPropsRefs }) {* @param {FocusEvent} event*/const onBlur = (event) => {- if (popoverPropsRefs.visible.value) return+ if (visibleRef.value) returnconst nextActiveElement = getNextActiveElementOnBlur(event)if (!isActualElement(nextActiveElement)) {scheduleFocus()diff --git a/src/composables/use-focus-on-hide.js b/src/composables/use-focus-on-hide.jsindex afd256c98..29e121f1a 100644--- a/src/composables/use-focus-on-hide.js+++ b/src/composables/use-focus-on-hide.js@@ -8,8 +8,10 @@ import {/*** @typedef Props- * @property {import('./types').Ref<HTMLElement>} popoverRef- * @property {import('./types').ToRefs<import('../components/VPopover/VPopover.types').Props>} popoverPropsRefs+ * @property {import('./types').Ref<HTMLElement>} dialogRef+ * @property {import('./types').Ref<HTMLElement>} triggerElementRef+ * @property {import('./types').Ref<boolean>} visibleRef+ * @property {import('./types').Ref<boolean>} autoFocusOnHideRef*//**@@ -30,20 +32,20 @@ function hidByFocusingAnotherElement(popover) {/*** @param {Props} Props*/-export const useFocusOnHide = ({ popoverRef, popoverPropsRefs }) => {+export const useFocusOnHide = ({+ dialogRef,+ triggerElementRef,+ visibleRef,+ autoFocusOnHideRef,+}) => {watch(- [- popoverRef,- popoverPropsRefs.triggerElement,- popoverPropsRefs.visible,- popoverPropsRefs.autoFocusOnHide,- ],+ [dialogRef, triggerElementRef, visibleRef, autoFocusOnHideRef],/*** @param {[HTMLElement, HTMLElement, boolean, boolean]} deps* @param {[unknown, unknown, boolean]} previousDeps*/(- [popover, triggerElement, visible, autoFocusOnHide],+ [dialog, triggerElement, visible, autoFocusOnHide],[, , previousVisible]) => {const shouldFocus =@@ -51,7 +53,7 @@ export const useFocusOnHide = ({ popoverRef, popoverPropsRefs }) => {if (!shouldFocus) return- if (hidByFocusingAnotherElement(popover)) return+ if (hidByFocusingAnotherElement(dialog)) returnensureFocus(triggerElement)}diff --git a/src/composables/use-focus-on-show.js b/src/composables/use-focus-on-show.jsindex 6ffe746e7..5ed528d27 100644--- a/src/composables/use-focus-on-show.js+++ b/src/composables/use-focus-on-show.js@@ -7,31 +7,36 @@ export const noFocusableElementWarning =/*** @typedef Props- * @property {import('./types').Ref<HTMLElement>} popoverRef- * @property {import('./types').ToRefs<import('../components/VPopover/VPopover.types').Props>} popoverPropsRefs+ * @property {import('./types').Ref<HTMLElement>} dialogRef+ * @property {import('./types').Ref<boolean>} visibleRef+ * @property {import('./types').Ref<boolean>} autoFocusOnShowRef*//*** @see https://github.com/reakit/reakit/blob/bce9b8a0e567983f61b5cc627f8dee9461986fab/packages/reakit/src/Dialog/__utils/useFocusOnShow.ts#L9* @param {Props} props*/-export const useFocusOnShow = ({ popoverRef, popoverPropsRefs }) => {+export const useFocusOnShow = ({+ dialogRef,+ visibleRef,+ autoFocusOnShowRef,+}) => {watch(- [popoverRef, popoverPropsRefs.visible, popoverPropsRefs.autoFocusOnShow],+ [dialogRef, visibleRef, autoFocusOnShowRef],/*** @param {[HTMLElement, boolean, boolean]} values*/- ([popover, visible, autoFocusOnShow]) => {- if (!popover || !visible || !autoFocusOnShow) return+ ([dialog, visible, autoFocusOnShow]) => {+ if (!dialog || !visible || !autoFocusOnShow) return- const tabbable = getFirstTabbableIn(popover, true)- const isActive = () => hasFocusWithin(popover)+ const tabbable = getFirstTabbableIn(dialog, true)+ const isActive = () => hasFocusWithin(dialog)if (tabbable) {ensureFocus(tabbable, { preventScroll: true, isActive })} else {- ensureFocus(popover, { preventScroll: true, isActive })- if (popover.tabIndex === undefined || popover.tabIndex < 0) {+ ensureFocus(dialog, { preventScroll: true, isActive })+ if (dialog.tabIndex === undefined || dialog.tabIndex < 0) {warn(noFocusableElementWarning)}}diff --git a/src/composables/use-hide-on-click-outside.js b/src/composables/use-hide-on-click-outside.jsindex 5b588a340..5d1f9a898 100644--- a/src/composables/use-hide-on-click-outside.js+++ b/src/composables/use-hide-on-click-outside.js@@ -4,19 +4,26 @@ 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+ * @property {import('./types').Ref<HTMLElement>} dialogRef+ * @property {import('./types').Ref<boolean>} visibleRef+ * @property {import('./types').Ref<boolean>} hideOnClickOutsideRef+ * @property {import('./types').Ref<HTMLElement>} triggerElementRef+ * @property {import('./types').Ref<() => void>} hideRef*//*** @param {Props} props* @return {import('./types').Ref<EventTarget>}*/-function useMouseDownTargetRef({ popoverRef, popoverPropsRefs }) {+function useMouseDownTargetRef({+ dialogRef,+ visibleRef,+ hideOnClickOutsideRef,+}) {const mouseDownTargetRef = ref()watch(- [popoverPropsRefs.visible, popoverPropsRefs.hideOnClickOutside, popoverRef],+ [visibleRef, hideOnClickOutsideRef, dialogRef],/*** @param {[boolean, boolean, HTMLElement]} deps* @param {unknown} _@@ -41,21 +48,26 @@ function useMouseDownTargetRef({ popoverRef, popoverPropsRefs }) {/*** @param {Props} props*/-export function useHideOnClickOutside({ popoverRef, popoverPropsRefs }) {+export function useHideOnClickOutside({+ dialogRef,+ visibleRef,+ hideOnClickOutsideRef,+ triggerElementRef,+ hideRef,+}) {const mouseDownTargetRef = useMouseDownTargetRef({- popoverRef,- popoverPropsRefs,+ dialogRef,+ visibleRef,+ hideOnClickOutsideRef,})const shouldListenRef = computed(- () =>- popoverPropsRefs.visible.value &&- popoverPropsRefs.hideOnClickOutside.value+ () => visibleRef.value && hideOnClickOutsideRef.value)useEventListenerOutside({- containerRef: popoverRef,- triggerRef: popoverPropsRefs.triggerElement,+ containerRef: dialogRef,+ triggerRef: triggerElementRef,eventType: 'click',listener: (event) => {if (mouseDownTargetRef.value === event.target) {@@ -63,20 +75,20 @@ export function useHideOnClickOutside({ popoverRef, popoverPropsRefs }) {// 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()+ hideRef.value()}},shouldListenRef,})useEventListenerOutside({- containerRef: popoverRef,- triggerRef: popoverPropsRefs.triggerElement,+ containerRef: dialogRef,+ triggerRef: triggerElementRef,eventType: 'focusin',listener: (event) => {- const document = getDocument(popoverRef.value)+ const document = getDocument(dialogRef.value)if (event.target !== document) {- popoverPropsRefs.hide.value()+ hideRef.value()}},shouldListenRef,diff --git a/src/composables/use-popover-content.js b/src/composables/use-popover-content.jsindex 9c2a71549..d129cacf8 100644--- a/src/composables/use-popover-content.js+++ b/src/composables/use-popover-content.js@@ -1,24 +1,32 @@-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'+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('@nuxtjs/composition-api').SetupContext['emit']} emit*//*** @param {Props} props*/-export function usePopoverContent(props) {- const focusOnBlur = useFocusOnBlur(props)- useFocusOnShow(props)- useFocusOnHide(props)- useHideOnClickOutside(props)- usePopper(props)+export function usePopoverContent({ popoverRef, popoverPropsRefs, emit }) {+ const { onKeyDown, onBlur } = useDialogContent({+ dialogRef: popoverRef,+ visibleRef: popoverPropsRefs.visible,+ autoFocusOnShowRef: popoverPropsRefs.autoFocusOnShow,+ autoFocusOnHideRef: popoverPropsRefs.autoFocusOnHide,+ triggerElementRef: popoverPropsRefs.triggerElement,+ hideOnClickOutsideRef: popoverPropsRefs.hideOnClickOutside,+ hideRef: popoverPropsRefs.hide,+ hideOnEscRef: popoverPropsRefs.hideOnEsc,+ emit,+ })+ usePopper({+ popoverRef,+ popoverPropsRefs,+ })- return { focusOnBlur }+ return { onKeyDown, onBlur }}diff --git a/src/locales/en.json b/src/locales/en.jsonindex abd897a5d..b617cd1ca 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -667,5 +667,8 @@},"download": "Download"},- "interpunct": "•"+ "interpunct": "•",+ "modal": {+ "close": "Close"+ }}diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex 2fc5ec1b2..9e0d56ef2 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -4,7 +4,7 @@ msgid ""msgstr """Project-Id-Version: Openverse \n""Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"-"POT-Creation-Date: 2021-11-30T16:26:14+00:00\n"+"POT-Creation-Date: 2021-12-02T15:06:49+00:00\n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"@@ -18,6 +18,11 @@ msgctxt "interpunct"msgid "•"msgstr ""+#: src/components/VModal/VModalContent.vue:19+msgctxt "modal.close"+msgid "Close"+msgstr ""+#: src/components/DownloadButton.vue:14msgctxt "download-button.download"msgid "Download"@@ -309,17 +314,17 @@ msgid "Back to search results"msgstr ""#. Do not translate words between ### ###.-#: src/components/ImageDetails/PhotoDetails.vue:59+#: src/components/ImageDetails/PhotoDetails.vue:63msgctxt "photo-details.creator"msgid "by ###name###"msgstr ""-#: src/components/ImageDetails/PhotoDetails.vue:150+#: src/components/ImageDetails/PhotoDetails.vue:153msgctxt "photo-details.weblink"msgid "Go to image's website"msgstr ""-#: src/components/ImageDetails/LegalDisclaimer.vue:4+#: src/components/ImageDetails/PhotoDetails.vue:31msgctxt "photo-details.legal-disclaimer"msgid "Openverse aggregates data from publicly available repositories of open content. Openverse does not host the content and does not verify that the content is properly CC-licensed or that the attribution information is accurate or complete. Please follow the link to the source of the content to independently verify before reuse."msgstr ""@@ -339,7 +344,7 @@ msgctxt "photo-details.aria.dmca"msgid "dmca form"msgstr ""-#: src/components/ImageDetails/PhotoDetails.vue:52+#: src/components/ImageDetails/PhotoDetails.vue:56msgctxt "photo-details.aria.details"msgid "image details"msgstr ""@@ -361,7 +366,7 @@ msgid "###provider### form"msgstr ""#. Do not translate words between ### ###.-#: src/components/ImageDetails/PhotoDetails.vue:69+#: src/components/ImageDetails/PhotoDetails.vue:73msgctxt "photo-details.aria.creator-url"msgid "author ###creator###"msgstr ""@@ -456,12 +461,12 @@ msgctxt "photo-details.content-report.dmca.aria-form"msgid "###provider### form"msgstr ""-#: src/components/CopyButton.vue:10+#: src/components/CopyButton.vue:9msgctxt "photo-details.copy.copy"msgid "Copy"msgstr ""-#: src/components/CopyButton.vue:14+#: src/components/CopyButton.vue:12msgctxt "photo-details.copy.copied"msgid "Copied!"msgstr ""@@ -481,7 +486,7 @@ msgctxt "photo-details.survey.answer"msgid "by answering a few questions."msgstr ""-#: src/components/ImageDetails/PhotoDetails.vue:103+#: src/components/ImageDetails/PhotoDetails.vue:107msgctxt "photo-details.information.title"msgid "Information"msgstr ""@@ -520,7 +525,7 @@ msgctxt "photo-details.information.pixels"msgid "pixels"msgstr ""-#: src/components/ImageDetails/PhotoDetails.vue:92+#: src/components/ImageDetails/PhotoDetails.vue:96msgctxt "photo-details.reuse.title"msgid "Reuse"msgstr ""@@ -859,22 +864,22 @@ msgctxt "browse-page.search-rating.feedback-thanks"msgid "Thank you for the feedback!"msgstr ""-#: src/components/Filters/FiltersList.vue:5+#: src/components/Filters/SearchGridFilter.vue:12msgctxt "filter-list.filter-by"msgid "Filter results by"msgstr ""-#: src/components/Filters/FiltersList.vue:14+#: src/components/Filters/SearchGridFilter.vue:21msgctxt "filter-list.hide"msgid "Hide filters"msgstr ""-#: src/components/Filters/FiltersList.vue:37+#: src/components/Filters/SearchGridFilter.vue:45msgctxt "filter-list.clear"msgid "Clear filters"msgstr ""-#: src/components/Filters/FiltersList.vue:43+#: src/components/Filters/SearchGridFilter.vue:52msgctxt "filter-list.show"msgid "Show results"msgstr ""diff --git a/test/unit/specs/components/v-modal.spec.js b/test/unit/specs/components/v-modal.spec.jsnew file mode 100644index 000000000..06f700a93--- /dev/null+++ b/test/unit/specs/components/v-modal.spec.js@@ -0,0 +1,81 @@+import Vue from 'vue'+import { render, screen } from '@testing-library/vue'+import userEvent from '@testing-library/user-event'++import VModal from '~/components/VModal/VModal.vue'+import VModalTarget from '~/components/VModal/VModalTarget.vue'+import VButton from '~/components/VButton.vue'++const TestWrapper = Vue.component('TestWrapper', {+ components: { VModal, VButton, VModalTarget },+ template: `+ <div>+ <VModal label="modal label">+ <template #trigger="{ a11yProps, visible }">+ <VButton v-bind="a11yProps">{{ visible }}</VButton>+ </template>++ <div>Code is Poetry</div>+ </VModal>+ <VModalTarget />+ </div>+ `,+})++const nextTick = async () =>+ await new Promise((resolve) => setTimeout(resolve, 1))++const getDialog = () => screen.getByRole('dialog')+const queryDialog = () => screen.queryByRole('dialog')+const getTrigger = () => screen.getByRole('button')+const doOpen = async () => {+ await userEvent.click(getTrigger())+ await nextTick()+}++// `useDialogContent` functionality is already tested by `VPopover` tests.+// Eventually we'll want to abstract those tests out but for now it's not worth+// the work.+describe('VModal', () => {+ let _scrollTo+ beforeAll(() => {+ _scrollTo = window.scrollTo+ window.scrollTo = jest.fn()+ })+ afterAll(() => {+ window.scrollTo = _scrollTo+ })++ beforeEach(() => {+ jest.resetAllMocks()+ })++ it('should render a close button that hides the modal', async () => {+ render(TestWrapper)+ await doOpen()++ expect(getDialog()).toBeVisible()++ await userEvent.click(screen.getByText('modal.close'))+ await nextTick()++ expect(queryDialog()).toBe(null)+ })++ it('should scroll lock the body when modal opens and unlock when modal closes', async () => {+ const { container } = render(TestWrapper)+ const scrollY = 10+ window.scrollY = scrollY+ await doOpen()++ expect(getDialog()).toBeVisible()+ expect(container.ownerDocument.body.style.position).toBe('fixed')+ expect(container.ownerDocument.body.style.top).toBe(`-${scrollY}px`)++ await userEvent.click(screen.getByText('modal.close'))+ await nextTick()++ expect(window.scrollTo).toHaveBeenCalledWith(0, scrollY)+ expect(container.ownerDocument.body.style.position).not.toBe('fixed')+ })+})