Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add VItemGroup component (#410)
sarayourfriendd803498e9ff8
diff --git a/src/assets/icons/check.svg b/src/assets/icons/check.svgnew file mode 100644index 000000000..5da5ad29d--- /dev/null+++ b/src/assets/icons/check.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">+ <path id="icon" stroke="currentColor" d="M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z" />+</svg>diff --git a/src/components/VButton.vue b/src/components/VButton.vueindex 36338bf6d..f1717383d 100644--- a/src/components/VButton.vue+++ b/src/components/VButton.vue@@ -11,6 +11,7 @@:aria-pressed="pressed":aria-disabled="ariaDisabledRef":disabled="disabledAttributeRef"+ v-bind="$attrs"v-on="$listeners"><!--@@ -72,6 +73,7 @@ const VButton = defineComponent({'tertiary','action-menu','action-menu-muted',+ 'grouped',].includes(v),},/**@@ -197,7 +199,7 @@ export default VButton<style module>.button {- @apply flex max-w-max items-center rounded-sm justify-center transition-shadow duration-100 ease-linear disabled:opacity-70 focus:outline-none focus-visible:ring focus-visible:ring-offset-2 no-underline appearance-none;+ @apply flex items-center rounded-sm justify-center transition-shadow duration-100 ease-linear disabled:opacity-70 focus:outline-none focus-visible:ring no-underline appearance-none;}.button[disabled='disabled'],@@ -260,4 +262,12 @@ a.button {.action-menu-muted-pressed {@apply border-tx bg-dark-charcoal text-white;}++.grouped {+ @apply bg-white text-black focus-visible:ring-pink;+}++.grouped-pressed {+ @apply bg-dark-charcoal-10 ring-offset-dark-charcoal-10;+}</style>diff --git a/src/components/VIcon/VIcon.vue b/src/components/VIcon/VIcon.vueindex 3e53b9803..1d146c3b7 100644--- a/src/components/VIcon/VIcon.vue+++ b/src/components/VIcon/VIcon.vue@@ -30,7 +30,10 @@ export default {* importing an SVG should give us the path to the file.*/iconPath: {- type: String,+ /**+ * In `jest` our icons get transformed to Vue components+ */+ type: process.env.NODE_ENV === 'test' ? Object : String,required: true,},/**diff --git a/src/components/VItemGroup/VItem.vue b/src/components/VItemGroup/VItem.vuenew file mode 100644index 000000000..551ed75df--- /dev/null+++ b/src/components/VItemGroup/VItem.vue@@ -0,0 +1,196 @@+<template>+ <div+ class="flex"+ :class="{+ [$style[contextProps.direction]]: true,+ [`border border-dark-charcoal-20 ${+ $style[`${contextProps.direction}-bordered`]+ }`]: contextProps.bordered,+ 'bg-dark-charcoal-10': selected && contextProps.bordered,+ 'p-2': isInPopover,+ [$style[`${contextProps.direction}-popover-item`]]: isInPopover,+ }"+ >+ <VButton+ data-item-group-item+ class="flex justify-between focus-visible:ring-pink rounded min-w-full"+ :class="[$style.button, $style[`${contextProps.direction}-button`]]"+ variant="grouped"+ size="small"+ :pressed="selected"+ :role="contextProps.type === 'radiogroup' ? 'radio' : 'menuitemcheckbox'"+ :aria-checked="selected"+ :tabindex="tabIndex"+ v-bind="$attrs"+ v-on="$listeners"+ @focus="isFocused = true"+ @blur="isFocused = false"+ @keydown="focusContext.onItemKeyPress"+ >+ <div+ class="flex-grow whitespace-nowrap"+ :class="$style[`${contextProps.direction}-content`]"+ >+ <slot name="default" />+ </div>+ <VIcon+ v-if="!isInPopover && selected && contextProps.direction === 'vertical'"+ :icon-path="check"+ />+ </VButton>+ </div>+</template>++<script>+import {+ defineComponent,+ inject,+ ref,+ computed,+ watch,+} from '@nuxtjs/composition-api'+import check from '~/assets/icons/check.svg'+import VButton from '~/components/VButton.vue'+import VIcon from '~/components/VIcon/VIcon.vue'+import {+ VItemGroupContextKey,+ VItemGroupFocusContextKey,+} from './VItemGroup.vue'+import { VPopoverContentContextKey } from '~/components/VPopover/VPopoverContent.vue'+import { warn } from '~/utils/warn'++export default defineComponent({+ name: 'VItem',+ components: { VButton, VIcon },+ props: {+ /**+ * Whether the item is selected/checked.+ */+ selected: {+ type: Boolean,+ required: true,+ },+ /**+ * Whether the item is the first in the group.+ */+ isFirst: {+ type: Boolean,+ required: true,+ },+ },+ setup(props) {+ const focusContext = inject(VItemGroupFocusContextKey)+ const isFocused = ref(false)+ const isInPopover = inject(VPopoverContentContextKey, false)+ const contextProps = inject(VItemGroupContextKey)++ if (isInPopover && contextProps.bordered) {+ warn('Bordered popover items are not supported')+ }++ watch(+ () => props.selected,+ (selected, previousSelected) =>+ focusContext.setSelected(selected, previousSelected)+ )++ const tabIndex = computed(() => {+ // If outside a radiogroup then everything can be tabbable in order+ if (contextProps.type !== 'radiogroup') return 0+ // If no items are selected then all can be tabbable to ensure it is possible to enter into the group+ if (+ focusContext.selectedCount.value === 0 &&+ props.isFirst &&+ !focusContext.isGroupFocused.value+ )+ return 0+ // If this one is focused then it should be the tabbable item+ if (isFocused.value) return 0+ // If the group is not focused but this is the selected item, then this should be the focusable item when focusing into the group+ if (!focusContext.isGroupFocused.value && props.selected) return 0++ // Otherwise the item should not be tabbable. The logic above guarantees that at least one other item in the group will be tabbable.+ return -1+ })++ return {+ check,+ contextProps,+ isInPopover,+ isFocused,+ tabIndex,+ focusContext,+ }+ },+})+</script>++<style module>+.button:focus {+ @apply z-10;+}++.vertical {+ @apply min-w-max;+}++.vertical-bordered {+ @apply border-t-0 border-b;+}++.vertical:first-of-type {+ @apply rounded-t-sm;+}++.vertical-bordered:first-of-type {+ @apply border-t;+}++.vertical:last-of-type {+ @apply rounded-b-sm;+}++.vertical-content {+ @apply flex flex-row;+}++.vertical-popover-item {+ @apply pb-0;+}++.vertical-popover-item:last-of-type {+ @apply pb-2;+}++.horizontal-button {+ @apply w-max;+}++.horizontal-bordered {+ @apply border-s-0 border-e border-dark-charcoal-20;+}++.horizontal:first-of-type {+ @apply rounded-s-sm;+}++.horizontal-bordered:first-of-type {+ @apply border-s;+}++.horizontal:last-of-type {+ @apply rounded-e-sm;+}++.horizontal-content {+ @apply flex flex-col items-center;+}++.horizontal-popover-item {+ @apply pe-0;+}++.horizontal-popover-item:last-of-type {+ @apply pe-2;+}+</style>diff --git a/src/components/VItemGroup/VItemGroup.vue b/src/components/VItemGroup/VItemGroup.vuenew file mode 100644index 000000000..fafaa9c4d--- /dev/null+++ b/src/components/VItemGroup/VItemGroup.vue@@ -0,0 +1,176 @@+<template>+ <div+ ref="nodeRef"+ class="w-full flex"+ :role="type"+ :class="direction === 'vertical' ? 'flex-col' : 'flex-row'"+ @focusin="isFocused = true"+ @focusout="isFocused = false"+ >+ <!--+ @slot The items in the item group. Should all be `VItem`s+ -->+ <slot name="default" />+ </div>+</template>++<script>+import {+ defineComponent,+ provide,+ ref,+ readonly,+} from '@nuxtjs/composition-api'+import { ensureFocus } from 'reakit-utils'+import { useI18n } from '~/composables/use-i18n'++/**+ * @typedef VItemGroupContext+ * @property {'vertical' | 'horizontal'} direction+ * @property {boolean} bordered+ * @property {'menu' | 'radiogroup'} type+ */++/**+ * @type {import('@nuxtjs/composition-api').InjectionKey<VItemGroupContext>}+ */+export const VItemGroupContextKey = Symbol('VItemGroupContext')++/**+ * @typedef VItemGroupFocusContext+ * @property {import('@nuxtjs/composition-api').Readonly<import('@nuxtjs/composition-api').Ref<boolean>>} isGroupFocused+ * @property {(event: KeyboardEvent) => void} onItemKeyPress+ * @property {import('@nuxtjs/composition-api').Readonly<import('@nuxtjs/composition-api').Ref<number>>} selectedCount+ * @property {(selected: boolean, previousSelected: boolean) => void} setSelected+ */++/**+ * @type {import('@nuxtjs/composition-api').InjectionKey<VItemGroupFocusContext>}+ */+export const VItemGroupFocusContextKey = Symbol('VItemGroupFocusContext')++const arrows = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']++export default defineComponent({+ name: 'VItemGroup',+ props: {+ /**+ * The direction to render the items in.+ *+ * @default 'vertical'+ */+ direction: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<'vertical' | 'horizontal'>} */ (String),+ default: 'vertical',+ validate: (v) => ['vertical', 'horizontal'].includes(v),+ },+ /**+ * Whether to render a bordered, separated list of items. When false each+ * item will be have whitespace separating them instead of borders.+ *+ * @default true+ */+ bordered: {+ type: Boolean,+ default: true,+ },+ /**+ * The type of item group and item to render. This directly affects the `role` attribute+ * of the container and the items themselves.+ *+ * `menu` should be used when providing a menu of independent options.+ *+ * @see https://www.w3.org/TR/wai-aria-1.1/#menu+ *+ * `radiogroup` should be used when providing a menu of options where only one can be selected at a time.+ *+ * @see https://www.w3.org/TR/wai-aria-1.1/#radiogroup+ *+ * @default 'menu'+ */+ type: {+ type: /** @type {import('@nuxtjs/composition-api').PropType<'menu' | 'radiogroup'>} */ (String),+ default: 'menu',+ validate: (v) => ['menu', 'radiogroup'].includes(v),+ },+ },+ setup(props) {+ /** @type {import('@nuxtjs/composition-api').Ref<HTMLElement | undefined>} */+ const nodeRef = ref()+ const isFocused = ref(false)+ provide(VItemGroupContextKey, props)++ const i18n = useI18n()++ /**+ * When the item group is horizontal, we need to "reverse" the behavior of the left and right arrow keys for RTL locales+ * because the DOM order gets reversed to be opposite the visual order relative to left/right movement.+ *+ * For vertical locales it should remain the same.+ * @param {string} ltr+ * @param {string} rtl+ */+ const resolveArrow = (ltr, rtl) => {+ return i18n.localeProperties.dir === 'rtl' &&+ props.direction === 'horizontal'+ ? rtl+ : ltr+ }++ /**+ * @param {KeyboardEvent} event+ */+ const onItemKeyPress = (event) => {+ if (!arrows.includes(event.key) || !nodeRef.value) return++ event.preventDefault()++ const target = event.target++ // While VItem ultimately renders a button at the moment, that could change in the future, so using a data attribute selector makes it more flexible for the future+ const items = Array.from(+ nodeRef.value.querySelectorAll('[data-item-group-item]')+ )++ const targetIndex = items.findIndex((item) => item === target)++ switch (event.key) {+ case 'ArrowUp':+ case resolveArrow('ArrowLeft', 'ArrowRight'):+ if (targetIndex === 0) {+ return ensureFocus(items[items.length - 1])+ }+ return ensureFocus(items[targetIndex - 1])+ case 'ArrowDown':+ case resolveArrow('ArrowRight', 'ArrowLeft'):+ if (targetIndex === items.length - 1) {+ return ensureFocus(items[0])+ }+ return ensureFocus(items[targetIndex + 1])+ }+ }++ const selectedCount = ref(0)++ /**+ * @param {boolean} selected+ * @param {boolean} previousSelected+ */+ const setSelected = (selected, previousSelected) => {+ if (previousSelected && !selected) selectedCount.value -= 1+ if (!previousSelected && selected) selectedCount.value += 1+ }++ const focusContext = {+ isGroupFocused: readonly(isFocused),+ onItemKeyPress,+ selectedCount: readonly(selectedCount),+ setSelected,+ }++ provide(VItemGroupFocusContextKey, focusContext)++ return { isFocused, nodeRef }+ },+})+</script>diff --git a/src/components/VItemGroup/meta/VItemGroup.stories.js b/src/components/VItemGroup/meta/VItemGroup.stories.jsnew file mode 100644index 000000000..2174e8066--- /dev/null+++ b/src/components/VItemGroup/meta/VItemGroup.stories.js@@ -0,0 +1,170 @@+import VItemGroup from '~/components/VItemGroup/VItemGroup.vue'+import VItem from '~/components/VItemGroup/VItem.vue'+import VIcon from '~/components/VIcon/VIcon.vue'+import VPopover from '~/components/VPopover/VPopover.vue'+import VButton from '~/components/VButton.vue'++import { ref } from '@nuxtjs/composition-api'++import close from '~/assets/icons/close.svg'+import pause from '~/assets/icons/pause.svg'+import play from '~/assets/icons/play.svg'+import replay from '~/assets/icons/replay.svg'++const icons = [close, pause, play, replay]++export default {+ component: VItemGroup,+ title: 'Components/VItemGroup',+ args: {+ direction: {+ type: 'radio',+ options: ['vertical', 'horizontal'],+ },+ bordered: 'boolean',+ },+}++const DefaultStory = (args, { argTypes }) => ({+ template: `+ <div>+ <p>+ This is a "radio" style list group. Only a single element can be selected at a time.+ </p>+ <div style="width: 300px">+ <VItemGroup v-bind="$props" type="radiogroup">+ <VItem+ v-for="(item, idx) in items"+ :key="item.id"+ :selected="selectedItem.id === item.id"+ :is-first="idx === 0"+ @click="selectedItem = item"+ size="medium"+ >+ <VIcon :icon-path="item.icon" /> {{ item.label }}+ </VItem>+ </VItemGroup>+ </div>+ </div>+ `,+ components: { VItemGroup, VItem, VIcon },+ props: Object.keys(argTypes),+ setup() {+ const items = new Array(icons.length).fill(null).map((_, i) => ({+ id: i,+ label: `Item ${i}`,+ icon: icons[i],+ }))++ const selectedItem = ref({})++ return { items, selectedItem }+ },+})++export const Default = DefaultStory.bind({})+Default.args = {+ direction: 'vertical',+ bordered: true,+}++const MenuStory = (args, { argTypes }) => ({+ template: `+ <div>+ <p>+ This is a "menu" style item group. Multiple items can be active at a time and all have the "menuitemcheckbox" role.+ </p>+ <div style="width: 300px">+ <VItemGroup v-bind="$props" type="menu">+ <VItem+ v-for="(item, idx) in items"+ :key="item.id"+ :selected="selectedItemIds.has(item.id)"+ :is-first="idx === 0"+ @click="toggleItem(item)"+ size="medium"+ >+ <VIcon :icon-path="item.icon" /> {{ item.label }}+ </VItem>+ </VItemGroup>+ </div>+ </div>+ `,+ components: { VItemGroup, VItem, VIcon },+ props: Object.keys(argTypes),+ setup() {+ const items = new Array(icons.length).fill(null).map((_, i) => ({+ id: i,+ label: `Item ${i}`,+ icon: icons[i],+ }))++ const selectedItemIds = ref(/** @type {Set<number>} */ (new Set()))++ const toggleItem = (item) => {+ if (selectedItemIds.value.delete(item.id)) {+ selectedItemIds.value = new Set(selectedItemIds.value)+ } else {+ selectedItemIds.value = new Set(selectedItemIds.value.add(item.id))+ }+ }++ return { items, selectedItemIds, toggleItem }+ },+})++export const Menu = MenuStory.bind({})+Menu.args = {+ direction: 'vertical',+ bordered: true,+}++const PopoverStory = (args, { argTypes }) => ({+ template: `+ <VPopover>+ <template #trigger="{ a11yProps, visible }">+ <VButton v-bind="a11yProps" :pressed="visible">{{ visible ? 'Close menu' : 'Open menu' }}</VButton>+ </template>++ <VItemGroup v-bind="$props" type="menu">+ <VItem+ v-for="(item, idx) in items"+ :key="item.id"+ :selected="selectedItemIds.has(item.id)"+ :is-first="idx === 0"+ @click="toggleItem(item)"+ size="medium"+ >+ <VIcon :icon-path="item.icon" /><span :class="{ 'pe-2': $props.direction === 'vertical' }">{{ item.label }}</span>+ </VItem>+ </VItemGroup>+ </VPopover>+ `,+ components: { VButton, VPopover, VItem, VItemGroup, VIcon },+ props: Object.keys(argTypes),+ setup() {+ const items = new Array(icons.length).fill(null).map((_, i) => ({+ id: i,+ label: `Item ${i}`,+ icon: icons[i],+ }))++ const selectedItemIds = ref(/** @type {Set<number>} */ (new Set()))++ const toggleItem = (item) => {+ if (selectedItemIds.value.delete(item.id)) {+ selectedItemIds.value = new Set(selectedItemIds.value)+ } else {+ selectedItemIds.value = new Set(selectedItemIds.value.add(item.id))+ }+ }++ return { items, selectedItemIds, toggleItem }+ },+})++export const Popover = PopoverStory.bind({})+Popover.args = {+ direction: 'vertical',+ bordered: false,+}diff --git a/src/components/VPopover/VPopoverContent.vue b/src/components/VPopover/VPopoverContent.vueindex 6f0e2686c..c54abec7f 100644--- a/src/components/VPopover/VPopoverContent.vue+++ b/src/components/VPopover/VPopoverContent.vue@@ -14,12 +14,17 @@</template><script>-import { defineComponent, toRefs, ref } from '@nuxtjs/composition-api'+import { defineComponent, toRefs, ref, provide } from '@nuxtjs/composition-api'import { usePopoverContent } from '~/composables/use-popover-content'import { warn } from '~/utils/warn'import { propTypes } from './VPopoverContent.types'+/**+ * @type {import('@nuxtjs/composition-api').InjectionKey<boolean>}+ */+export const VPopoverContentContextKey = Symbol('VPopoverContentContextKey')+export default defineComponent({name: 'VPopover',props: propTypes,@@ -34,6 +39,7 @@ export default defineComponent({* @param {import('@nuxtjs/composition-api').SetupContext} context*/setup(props, { emit, attrs }) {+ provide(VPopoverContentContextKey, true)if (!attrs['aria-label'] && !attrs['aria-labelledby']) {warn('You should provide either `aria-label` or `aria-labelledby` props.')}@@ -74,6 +80,6 @@ export default defineComponent({<style module>.popover {- @apply bg-white border border-light-gray rounded-sm px-2 pt-2 pb-1 max-w-min whitespace-nowrap shadow;+ @apply bg-white border border-light-gray rounded-sm max-w-max whitespace-nowrap shadow;}</style>diff --git a/src/components/VPopover/meta/VPopover.stories.js b/src/components/VPopover/meta/VPopover.stories.jsindex 321e97e8b..e5d0cf47b 100644--- a/src/components/VPopover/meta/VPopover.stories.js+++ b/src/components/VPopover/meta/VPopover.stories.js@@ -31,7 +31,7 @@ const SinglePopoverStory = (args, { argTypes }) => ({<template #trigger="{ visible, a11yProps }"><VButton :pressed="visible" v-bind="a11yProps">{{ visible ? 'Close' : 'Open' }}</VButton></template>- <div>Code is Poetry</div>+ <div class="py-1 px-2">Code is Poetry</div></VPopover></div>`,@@ -55,14 +55,14 @@ const TwoPopoverStory = (args, { argTypes }) => ({<template #trigger="{ visible, a11yProps }"><VButton :pressed="visible" v-bind="a11yProps">{{ visible ? 'First popover open' : 'First popover closed' }}</VButton></template>- <div>First popover content</div>+ <div class="py-1 px-2">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>+ <div class="py-1 px-2">Second popover content</div></VPopover></div>`,diff --git a/src/composables/use-i18n.js b/src/composables/use-i18n.jsnew file mode 100644index 000000000..dde14b013--- /dev/null+++ b/src/composables/use-i18n.js@@ -0,0 +1,9 @@+import { useContext } from '@nuxtjs/composition-api'++/**+ * This composable exists to make it easy to mock the i18n context+ * in the composition API in tests+ */+export function useI18n() {+ return useContext().i18n+}diff --git a/test/unit/specs/components/v-item-group.spec.js b/test/unit/specs/components/v-item-group.spec.jsnew file mode 100644index 000000000..bb16c4fdc--- /dev/null+++ b/test/unit/specs/components/v-item-group.spec.js@@ -0,0 +1,307 @@+import Vue from 'vue'+import { ref } from '@nuxtjs/composition-api'+import { render, screen } from '@testing-library/vue'+import VItemGroup from '~/components/VItemGroup/VItemGroup.vue'+import VItem from '~/components/VItemGroup/VItem.vue'+import userEvent from '@testing-library/user-event'+import { useI18n } from '~/composables/use-i18n'++jest.mock('~/composables/use-i18n', () => ({+ useI18n: jest.fn(),+}))++const doFocus = (element) => {+ element.focus()+ return new Promise((r) => setTimeout(r, 0))+}++const TestWrapper = Vue.component('TestWrapper', {+ components: { VItemGroup, VItem },+ props: {+ hasDefaultSelection: {+ type: Boolean,+ default: true,+ },+ },+ setup(props) {+ const items = new Array(4).fill(null).map((_, i) => ({+ id: i,+ label: `Item ${i}`,+ }))++ const selectedItem = ref(props.hasDefaultSelection ? items[0] : {})++ return { items, selectedItem }+ },+ template: `+ <div>+ <div>External element</div>+ <VItemGroup v-bind="$attrs">+ <VItem+ v-for="(item, idx) in items"+ :key="item.id"+ :selected="selectedItem.id === item.id"+ :is-first="idx === 0"+ @click="selectedItem = item"+ >+ {{ item.label }}+ </VItem>+ </VItemGroup>+ </div>+ `,+})++describe('VItemGroup', () => {+ let mockDir+ beforeEach(() => {+ mockDir = 'ltr'+ useI18n.mockImplementation(() => ({ localeProperties: { dir: mockDir } }))+ })+ afterEach(() => {+ useI18n.mockReset()+ })+ it('should render buttons with the appropriate roles', () => {+ render(TestWrapper)+ expect(screen.queryByRole('menu')).not.toBe(null)+ const items = screen.queryAllByRole('menuitemcheckbox')+ expect(items).toHaveLength(4)+ expect(items.every((item) => item.tagName === 'BUTTON')).toBe(true)+ })++ it('should render functional buttons', async () => {+ const { container } = render(TestWrapper)+ const [, secondItem] = screen.queryAllByRole('menuitemcheckbox')+ expect(+ container.querySelector('[aria-pressed="true"][aria-checked="true"]')+ ).not.toBe(secondItem)+ await userEvent.click(secondItem)+ expect(+ container.querySelector('[aria-pressed="true"][aria-checked="true"]')+ ).toBe(secondItem)+ })++ it('should render a radio group', async () => {+ const { container } = render(TestWrapper, {+ attrs: { type: 'radiogroup' },+ })+ expect(screen.queryByRole('radiogroup')).not.toBe(null)+ const [, secondItem] = screen.queryAllByRole('radio')+ expect(+ container.querySelector('[aria-pressed="true"][aria-checked="true"]')+ ).not.toBe(secondItem)+ await userEvent.click(secondItem)+ expect(+ container.querySelector('[aria-pressed="true"][aria-checked="true"]')+ ).toBe(secondItem)+ })++ describe('navigation', () => {+ it('should render the first item tabbable when there is no default selection and none are selected', () => {+ const { container } = render(TestWrapper, {+ props: { hasDefaultSelection: false },+ attrs: { type: 'radiogroup' },+ })+ const tabbableElements = container.querySelectorAll('[tabindex="0"]')+ expect(tabbableElements).toHaveLength(1)+ const [tabbableElement] = tabbableElements+ expect(tabbableElement).toBe(screen.queryAllByRole('radio')[0])+ })++ it('should render all items tabbable when in a menu', () => {+ const { container } = render(TestWrapper, {+ attrs: { type: 'menu' },+ })+ const tabbableElements = container.querySelectorAll('[tabindex="0"]')+ const items = screen.queryAllByRole('menuitemcheckbox')+ items.forEach((item) => expect(tabbableElements).toContain(item))+ })++ it('should render only the selected item as tabbable', async () => {+ const { container } = render(TestWrapper, {+ attrs: { type: 'radiogroup' },+ props: { hasDefaultSelection: false },+ })+ const [, secondItem] = screen.queryAllByRole('radio')+ await userEvent.click(secondItem)+ // Focus off the clicked item and outside the group so that the group does not have focus but there is still a selected item+ await doFocus(screen.getByText(/external element/i))+ const tabbableElements = container.querySelectorAll('[tabindex="0"]')+ expect(tabbableElements).toHaveLength(1)+ const [tabbableElement] = tabbableElements+ expect(tabbableElement).toBe(secondItem)+ })++ it('should render the currently focused item as tabbable even when there is a selection', async () => {+ const { container } = render(TestWrapper, {+ attrs: { type: 'radiogroup' },+ })+ const [, secondItem] = screen.queryAllByRole('radio')+ await doFocus(secondItem)+ const tabbableElements = container.querySelectorAll('[tabindex="0"]')+ expect(tabbableElements).toHaveLength(1)+ const [tabbableElement] = tabbableElements+ expect(tabbableElement).toBe(secondItem)+ })++ describe('arrow keys', () => {+ it.each(['ArrowUp', 'ArrowLeft'])(+ 'should focus to the previous item on %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, secondItem] = screen.queryAllByRole('radio')++ await doFocus(secondItem)+ await userEvent.keyboard(`{${key}}`)+ expect(firstItem).toHaveFocus()+ }+ )++ it.each(['ArrowUp', 'ArrowLeft'])(+ 'should go to the last item when on the first item and pressing %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, , , lastItem] = screen.queryAllByRole('radio')+ await doFocus(firstItem)+ await userEvent.keyboard(`{${key}}`)+ expect(lastItem).toHaveFocus()+ }+ )++ it.each(['ArrowDown', 'ArrowRight'])(+ 'should focus to the next item on %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, secondItem] = screen.queryAllByRole('radio')++ await doFocus(firstItem)+ await userEvent.keyboard(`{${key}}`)+ expect(secondItem).toHaveFocus()+ }+ )++ it.each(['ArrowDown', 'ArrowRight'])(+ 'should go to the first item when on the last item and pressing %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, , , lastItem] = screen.queryAllByRole('radio')++ await doFocus(lastItem)+ await userEvent.keyboard(`{${key}}`)+ expect(firstItem).toHaveFocus()+ }+ )++ describe('rtl', () => {+ beforeEach(() => {+ mockDir = 'rtl'+ })++ describe('vertical', () => {+ it.each(['ArrowUp', 'ArrowLeft'])(+ 'should focus to the previous item on %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, secondItem] = screen.queryAllByRole('radio')++ await doFocus(secondItem)+ await userEvent.keyboard(`{${key}}`)+ expect(firstItem).toHaveFocus()+ }+ )++ it.each(['ArrowUp', 'ArrowLeft'])(+ 'should go to the last item when on the first item and pressing %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, , , lastItem] = screen.queryAllByRole('radio')+ await doFocus(firstItem)+ await userEvent.keyboard(`{${key}}`)+ expect(lastItem).toHaveFocus()+ }+ )++ it.each(['ArrowDown', 'ArrowRight'])(+ 'should focus to the next item on %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, secondItem] = screen.queryAllByRole('radio')++ await doFocus(firstItem)+ await userEvent.keyboard(`{${key}}`)+ expect(secondItem).toHaveFocus()+ }+ )++ it.each(['ArrowDown', 'ArrowRight'])(+ 'should go to the first item when on the last item and pressing %s',+ async (key) => {+ render(TestWrapper, { attrs: { type: 'radiogroup' } })+ const [firstItem, , , lastItem] = screen.queryAllByRole('radio')++ await doFocus(lastItem)+ await userEvent.keyboard(`{${key}}`)+ expect(firstItem).toHaveFocus()+ }+ )+ })++ describe('horizontal', () => {+ it.each(['ArrowUp', 'ArrowRight'])(+ 'should focus to the previous item on %s',+ async (key) => {+ render(TestWrapper, {+ attrs: { type: 'radiogroup', direction: 'horizontal' },+ })+ const [firstItem, secondItem] = screen.queryAllByRole('radio')++ await doFocus(secondItem)+ await userEvent.keyboard(`{${key}}`)+ expect(firstItem).toHaveFocus()+ }+ )++ it.each(['ArrowUp', 'ArrowRight'])(+ 'should go to the last item when on the first item and pressing %s',+ async (key) => {+ render(TestWrapper, {+ attrs: { type: 'radiogroup', direction: 'horizontal' },+ })+ const [firstItem, , , lastItem] = screen.queryAllByRole('radio')+ await doFocus(firstItem)+ await userEvent.keyboard(`{${key}}`)+ expect(lastItem).toHaveFocus()+ }+ )++ it.each(['ArrowDown', 'ArrowLeft'])(+ 'should focus to the next item on %s',+ async (key) => {+ render(TestWrapper, {+ attrs: { type: 'radiogroup', direction: 'horizontal' },+ })+ const [firstItem, secondItem] = screen.queryAllByRole('radio')++ await doFocus(firstItem)+ await userEvent.keyboard(`{${key}}`)+ expect(secondItem).toHaveFocus()+ }+ )++ it.each(['ArrowDown', 'ArrowLeft'])(+ 'should go to the first item when on the last item and pressing %s',+ async (key) => {+ render(TestWrapper, {+ attrs: { type: 'radiogroup', direction: 'horizontal' },+ })+ const [firstItem, , , lastItem] = screen.queryAllByRole('radio')++ await doFocus(lastItem)+ await userEvent.keyboard(`{${key}}`)+ expect(firstItem).toHaveFocus()+ }+ )+ })+ })+ })+ })+})