@adyen/bento-mcp 0.5.4 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +7 -6
- package/bin/add-skill.js +12 -1
- package/dist/assets/components/anchor-scroller/anchor-scroller.vue +1 -1
- package/dist/assets/components/anchor-scroller/components/anchor-scroller-list/anchor-scroller-list.types.ts +1 -1
- package/dist/assets/components/anchor-scroller/components/anchor-scroller-list/anchor-scroller-list.vue +1 -1
- package/dist/assets/components/button/button.docs.mdx +24 -0
- package/dist/assets/components/button/button.vue +1 -1
- package/dist/assets/components/button/components/button-actions/button-actions.docs.mdx +14 -1
- package/dist/assets/components/data-grid/data-grid.stories.ts +1 -1
- package/dist/assets/components/date-range-picker/date-range-picker.vue +1 -1
- package/dist/assets/components/draggable/components/draggable-handle/draggable-handle.vue +1 -1
- package/dist/assets/components/dropdown/components/dropdown-base-textbox/dropdown-base-textbox.vue +1 -1
- package/dist/assets/components/dropdown/components/dropdown-options-container/dropdown-options-container.vue +1 -1
- package/dist/assets/components/dropdown/dropdown.docs.mdx +58 -0
- package/dist/assets/components/dropdown/dropdown.stories.ts +1 -1
- package/dist/assets/components/dropdown/dropdown.vue +1 -1
- package/dist/assets/components/filter-bar/components/filter-bar-button/filter-bar-button.vue +1 -1
- package/dist/assets/components/filter-bar/components/input-with-dropdown-filter/input-with-dropdown-filter.vue +1 -1
- package/dist/assets/components/filter-bar/components/range-filter/range-filter.types.ts +1 -0
- package/dist/assets/components/filter-bar/components/range-filter/range-filter.vue +1 -1
- package/dist/assets/components/filter-bar/filter-bar.docs.mdx +74 -1
- package/dist/assets/components/filter-bar/filter-bar.stories.ts +1 -1
- package/dist/assets/components/filter-bar/filter-bar.types.ts +1 -1
- package/dist/assets/components/filter-bar/filter-bar.vue +1 -1
- package/dist/assets/components/header/header.docs.mdx +8 -0
- package/dist/assets/components/header-with-views/header-with-views.docs.mdx +12 -0
- package/dist/assets/components/input-field/input-field.vue +1 -1
- package/dist/assets/components/internal/listbox/components/listbox-lazy-load/listbox-lazy-load.types.ts +1 -0
- package/dist/assets/components/internal/listbox/components/listbox-lazy-load/listbox-lazy-load.vue +1 -0
- package/dist/assets/components/internal/listbox/components/listbox-multi-select/components/listbox-multi-select-options/components/listbox-multi-select-category/listbox-multi-select-category.vue +1 -1
- package/dist/assets/components/internal/listbox/components/listbox-multi-select/components/listbox-multi-select-options/components/listbox-multi-select-nested-lazy-load/listbox-multi-select-nested-lazy-load.types.ts +1 -0
- package/dist/assets/components/internal/listbox/components/listbox-multi-select/components/listbox-multi-select-options/components/listbox-multi-select-nested-lazy-load/listbox-multi-select-nested-lazy-load.vue +1 -0
- package/dist/assets/components/internal/listbox/components/listbox-multi-select/components/listbox-multi-select-options/listbox-multi-select-options.vue +1 -1
- package/dist/assets/components/internal/listbox/components/listbox-multi-select/listbox-multi-select.vue +1 -1
- package/dist/assets/components/internal/listbox/components/listbox-single-select/listbox-single-select.vue +1 -1
- package/dist/assets/components/internal/listbox/listbox.vue +1 -1
- package/dist/assets/components/table-of-contents/components/table-of-contents-list/table-of-contents-list.types.ts +1 -0
- package/dist/assets/components/table-of-contents/components/table-of-contents-list/table-of-contents-list.vue +1 -0
- package/dist/assets/components/table-of-contents/table-of-contents.docs.mdx +34 -0
- package/dist/assets/components/table-of-contents/table-of-contents.stories.ts +1 -0
- package/dist/assets/components/table-of-contents/table-of-contents.types.ts +1 -0
- package/dist/assets/components/table-of-contents/table-of-contents.vue +1 -0
- package/dist/assets/components/toast/toast.docs.mdx +7 -0
- package/dist/assets/components.json +1 -0
- package/dist/assets/composables/use-numeric-input/use-numeric-input.types.ts +1 -0
- package/dist/assets/composables/use-section-navigation-keyboard/use-section-navigation-keyboard.types.ts +1 -0
- package/dist/assets/deprecations.md +1586 -136
- package/dist/assets/index.ts +1 -1
- package/dist/assets/usage.json +80 -79
- package/dist/assets/utils/ts/scroll-to-section/scroll-to-section.types.ts +1 -0
- package/dist/main.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { type BentoLazyLoadType } from '@/types/lazy-load'; export interface BentoLazyLoadProps { /** * Indicates if the 'Show more' button is using the condensed variant * @default false */ condensed?: boolean; /** * Indicates whether there are more items to load * @default false */ hasMoreItems?: boolean; /** * Indicates if new options are lazy loading. * @default false */ loading?: boolean; /** * Sets the tabindex to the button. * Used for the treeitem role */ tabindex?: number; /** * The type of `Lazy Load`. * Type "automatic" will enable infinite scrolling * Type "button" will enable lazy loading with "Show more" button */ type: BentoLazyLoadType; }
|
package/dist/assets/components/internal/listbox/components/listbox-lazy-load/listbox-lazy-load.vue
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<template> <div v-if="shouldDisplayShowMoreButton || loading" class="b-listbox-lazy-load"> <bento-loading-button v-if="shouldDisplayShowMoreButton" :state="loadingButtonState" :tabindex="tabindex" :condensed="condensed" variant="secondary" @click.capture="$emit('show-more', $event)" > {{ showMoreButtonText }} </bento-loading-button> <bento-loading-indicator v-else-if="loading" /> </div> </template> <script setup lang="ts"> import { computed } from 'vue'; import { BentoListboxLazyLoadType } from '@/types/listbox'; import { BentoLoadingIndicator } from '@/components/loading-indicator'; import { BentoLoadingButton, BentoLoadingButtonState } from '@/components/button'; import { useI18n } from '@/utils/ts/i18n'; import { type BentoLazyLoadProps } from './listbox-lazy-load.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const { t } = useI18n<{ message: MessageSchema }>({ messages }); defineEmits<{ /** * Emitted when the "Show more" button is clicked to request loading additional items. */ (e: 'show-more', event: Event); }>(); const props = withDefaults(defineProps<BentoLazyLoadProps>(), { condensed: false, hasMoreItems: false, loading: false, tabindex: undefined, }); const shouldDisplayShowMoreButton = computed( () => props.type === BentoListboxLazyLoadType.BUTTON && props.hasMoreItems ); const loadingButtonState = computed<BentoLoadingButtonState>(() => props.loading ? BentoLoadingButtonState.LOADING : BentoLoadingButtonState.START ); const showMoreButtonText = computed(() => (props.loading ? t('loading') : t('showMore'))); </script> <script lang="ts"> export default { name: 'listbox-lazy-load', i18n: { messages }, }; </script> <style lang="scss" scoped src="./listbox-lazy-load.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div> <bento-listbox-option v-if="!isStaticCategory" class="b-listbox-multi-select-category__option" :class="conditionalClass" :tabindex="tabindex" :aria-selected="ariaCheckedComputed !== 'false'" :aria-checked="ariaCheckedComputed" :aria-disabled="hasAllPropsDisabled" :aria-expanded="`${isOpen}`" role="treeitem" :aria-owns="categoryGroupId" :aria-labelledby="categoryNameId" @click="handleSelectAll" @enter-pressed="handleSelectAll" @space-pressed.prevent="handleSelectAll" @keydown.arrow-left.native="toggleOpen($event, false)" @keydown.arrow-right.native="toggleOpen($event, true)" > <decorative-checkbox :indeterminate="isIndeterminate" :disabled="hasAllPropsDisabled" :checked="isAllSelected" /> <span class="b-listbox-multi-select-category__label"> <bento-typography :id="categoryNameId" el="span" class="b-listbox-multi-select-category__label-text"> {{ category.label }} </bento-typography> <div aria-hidden="true" class="b-listbox-multi-select-category__label-chevron" data-testid="toggle-listbox" @click.capture.stop="toggleOpen" > <chevron-up-icon v-if="isOpen" :svg-title="chevronTitle" /> <chevron-down-icon v-else :svg-title="chevronTitle" /> </div> </span> </bento-listbox-option> <div v-else class="b-listbox-multi-select-category b-listbox-multi-select-category--static-category" aria-hidden="true" > <span class="b-listbox-multi-select-category__label"> <bento-typography el="span" variant="caption" class="b-listbox-multi-select-category__label-text"> {{ category.label }} </bento-typography> </span> </div> <div v-show="showItemChildren" :id="categoryGroupId" role="group" :aria-label="category.label"> <slot /> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, type PropType, ref, toRef, watch } from 'vue'; import { BentoTypography } from '@/components/typography'; import { BentoListboxOption } from '../../../../../listbox-option'; import { DecorativeCheckbox } from '@/internal/decorative-checkbox'; import { type BentoListboxIsOptionDisabled, type BentoListboxMultiSelectValue, type BentoListboxOptionItem, type BentoListboxValue, } from '@/types/listbox'; import { useCheckboxSelectAll } from '@/composables'; import { ListboxMultiSelectCategoryClass, ListboxMultiSelectCategoryEvent, } from './listbox-multi-select-category.types'; import { useI18n } from '@/utils/ts/i18n'; import ChevronDownIcon from '@adyen/ui-assets-icons-16/vue/chevron-down'; import ChevronUpIcon from '@adyen/ui-assets-icons-16/vue/chevron-up'; import messages from './messages.json';
|
|
1
|
+
<template> <div> <bento-listbox-option v-if="!isStaticCategory" class="b-listbox-multi-select-category__option" :class="conditionalClass" :tabindex="tabindex" :aria-selected="ariaCheckedComputed !== 'false'" :aria-checked="ariaCheckedComputed" :aria-disabled="hasAllPropsDisabled" :aria-expanded="`${isOpen}`" role="treeitem" :aria-owns="categoryGroupId" :aria-labelledby="categoryNameId" @click="handleSelectAll" @enter-pressed="handleSelectAll" @space-pressed.prevent="handleSelectAll" @keydown.arrow-left.native="toggleOpen($event, false)" @keydown.arrow-right.native="toggleOpen($event, true)" > <decorative-checkbox :indeterminate="isIndeterminate" :disabled="hasAllPropsDisabled" :checked="isAllSelected" /> <span class="b-listbox-multi-select-category__label"> <bento-typography :id="categoryNameId" el="span" class="b-listbox-multi-select-category__label-text"> {{ category.label }} </bento-typography> <div aria-hidden="true" class="b-listbox-multi-select-category__label-chevron" data-testid="toggle-listbox" @click.capture.stop="toggleOpen" > <chevron-up-icon v-if="isOpen" :svg-title="chevronTitle" /> <chevron-down-icon v-else :svg-title="chevronTitle" /> </div> </span> </bento-listbox-option> <div v-else class="b-listbox-multi-select-category b-listbox-multi-select-category--static-category" aria-hidden="true" > <span class="b-listbox-multi-select-category__label"> <bento-typography el="span" variant="caption" class="b-listbox-multi-select-category__label-text"> {{ category.label }} </bento-typography> </span> </div> <!-- Nested options --> <div v-show="showItemChildren" :id="categoryGroupId" role="group" :aria-label="category.label"> <slot /> <!-- Nested items Lazy load --> <template v-if="category.lazyLoad?.hasMoreItems"> <bento-listbox-multi-select-nested-lazy-load ref="lazyLoadRef" :option="category" :index="optionIndex" /> </template> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, type PropType, ref, toRef, watch } from 'vue'; import { BentoTypography } from '@/components/typography'; import { BentoListboxOption } from '../../../../../listbox-option'; import { DecorativeCheckbox } from '@/internal/decorative-checkbox'; import { type BentoListboxIsOptionDisabled, type BentoListboxMultiSelectValue, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxValue, } from '@/types/listbox'; import { useCheckboxSelectAll } from '@/composables'; import { ListboxMultiSelectCategoryClass, ListboxMultiSelectCategoryEvent, } from './listbox-multi-select-category.types'; import { useI18n } from '@/utils/ts/i18n'; import { generateUid } from '@/core/utils/ts'; import { BentoListboxMultiSelectNestedLazyLoad } from '../listbox-multi-select-nested-lazy-load'; import ChevronDownIcon from '@adyen/ui-assets-icons-16/vue/chevron-down'; import ChevronUpIcon from '@adyen/ui-assets-icons-16/vue/chevron-up'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; /** * Listbox multi-select category list. * Allows the rendering of nested lists * * @example * import { ListboxMultiSelectCategory } from '@/internal/listbox'; * * export default { * components: { BentoListboxMultiSelectCategory }, * template: ` * <listbox-multi-select-category * :category="option" * :is-option-disabled="true" * :selected-items-list="['option-1']" * @select-category="$emit('select-category', option)" * @unselect-category="$emit('unselect-category', option)" * > * <listbox-multi-select-options * category-items * :items="[{ label: 'Option 1', value: 'option-1' }]" * :is-multi-level="true" * :selected-items-list="['option-']" * :searching="false" * @toggle-checkbox-selection="value => toggleCheckboxSelection(value)" * /> * </listbox-multi-select-category> * ` * } */ export default defineComponent({ i18n: { messages }, name: 'bento-listbox-multi-select-category', components: { BentoTypography, BentoListboxOption, BentoListboxMultiSelectNestedLazyLoad, ChevronDownIcon, ChevronUpIcon, DecorativeCheckbox, }, props: { /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem }. * * @property {string} value.label - Text to be displayed in the option * @property {string,number} value.value - Value of the option * @property {BentoListboxOptionItem} value.items - Category items list */ category: { type: Object as PropType<BentoListboxOptionItem>, required: true, }, /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: [Function] as PropType<BentoListboxIsOptionDisabled>, default: () => false, }, /** * Option's index within the Listbox `item` array. */ optionIndex: { type: Number, default: null, }, /** * The `input` value. * Providing an empty array will select no options. */ selectedItemsList: { type: Array as PropType<Array<BentoListboxValue>>, default: () => [], }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Category's tabindex */ tabindex: { type: Number, default: -1 }, }, emits: [ ListboxMultiSelectCategoryEvent.SELECT_CATEGORY, ListboxMultiSelectCategoryEvent.UNSELECT_CATEGORY, ListboxMultiSelectCategoryEvent.TOGGLE_CATEGORY_VISIBILITY, ], setup(props, { emit }) { const isOpen = ref(false); const { t } = useI18n<{ message: MessageSchema }>({ messages }); const categoryGroupId = generateUid('category-group'); const categoryNameId = generateUid('category-name'); const lazyLoadRef = ref(null); // This method should be used to determine if an option is disabled as it works for both vue 2 & 3. const vue2Vue3FixedisOptionDisabled = option => props.isOptionDisabled ? props.isOptionDisabled(option) : false; const hasAllPropsDisabled = computed(() => { // Do not disable empty categories if they are lazy loaded if (props.category.lazyLoad && props.category.items?.length === 0) { return false; } return props.category.items.every(option => vue2Vue3FixedisOptionDisabled(option)); }); const isStaticCategory = toRef(props, 'staticCategories'); // Display item children if is open state or if static categories is enabled const showItemChildren = computed(() => isOpen.value || props.staticCategories); const conditionalClass = computed(() => ({ [`b-listbox-multi-select-category--${ListboxMultiSelectCategoryClass.DISABLED}`]: hasAllPropsDisabled.value, })); const toggleOpen = (event: Event, open?: boolean) => { event.preventDefault(); // Load lazy categories if the items list is empty (0 items) when category is opened if (props.category.lazyLoad && props.category.items?.length === 0) { lazyLoadRef.value.showMore(event); } isOpen.value = open !== undefined ? open : !isOpen.value; emit(ListboxMultiSelectCategoryEvent.TOGGLE_CATEGORY_VISIBILITY, props.category.value); }; const optionStates = (option: BentoListboxOptionItem) => { const isDisabled = vue2Vue3FixedisOptionDisabled(option); const isPreSelected = (props.selectedItemsList as BentoListboxMultiSelectValue)?.includes(option.value) || false; return { isDisabled, isPreSelected }; }; const enabledItems = computed(() => props.category.items.filter(option => { const { isDisabled, isPreSelected } = optionStates(option); return (isDisabled && isPreSelected) || !isDisabled; }) ); const visibleSelectedList = computed<BentoListboxOptions>(() => enabledItems.value?.filter(({ value }) => props.selectedItemsList?.includes(value)) ); const chevronTitle = computed(() => { const messageName = isOpen.value ? 'categoryOpened' : 'categoryClosed'; return t(messageName, { category: props.category.label }) as string; }); const selectAll = () => { emit(ListboxMultiSelectCategoryEvent.SELECT_CATEGORY); }; const unselectAll = () => { emit(ListboxMultiSelectCategoryEvent.UNSELECT_CATEGORY); }; const isLazySelectedByValue = computed( () => !!props.category.lazyLoad && props.selectedItemsList.includes(props.category.value) ); const { isAllSelected: isAllChildrenSelected, isIndeterminate: isChildrenIndeterminate, toggleSelectAll, } = useCheckboxSelectAll(visibleSelectedList, enabledItems, selectAll, unselectAll); const isAllSelected = computed(() => isLazySelectedByValue.value || isAllChildrenSelected.value); const isIndeterminate = computed(() => !isLazySelectedByValue.value && isChildrenIndeterminate.value); const ariaCheckedComputed = computed(() => { if (isIndeterminate.value) { return 'mixed'; } return `${isAllSelected.value}`; }); const isSelectAllOn = ref(isAllSelected.value); const handleSelectAll = () => { isSelectAllOn.value = !isSelectAllOn.value; toggleSelectAll(isSelectAllOn.value); }; watch(isAllSelected, () => { isSelectAllOn.value = isAllSelected.value; }); return { // Refs lazyLoadRef, // Values chevronTitle, conditionalClass, hasAllPropsDisabled, isOpen, isAllSelected, isIndeterminate, isStaticCategory, categoryGroupId, categoryNameId, // Computed showItemChildren, ariaCheckedComputed, // Methods handleSelectAll, toggleOpen, toggleSelectAll, }; }, }); </script> <style lang="scss" scoped src="./listbox-multi-select-category.scss" />
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import type { BentoListboxOptionItem } from '@/types/listbox'; export interface ListboxMultiSelectNestedLazyLoadProps { /** * Index of the option that triggers the nested lazy-load event. */ index: number; /** * Option that contains the nested lazy-load configuration. */ option: BentoListboxOptionItem; }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<template> <div role="treeitem" :tabindex="0" @keydown.enter.prevent="showMore" @keydown.space.prevent="showMore"> <bento-empty-state v-if="failedAndRetry" variant="basic" class="b-listbox-multi-select-nested-lazy-load__error-message" > {{ t('thereWasAnErrorLoadingNewItems') }} </bento-empty-state> <bento-listbox-lazy-load type="button" :tabindex="-1" condensed :has-more-items="option.lazyLoad?.hasMoreItems" :loading="loading" @show-more="showMore" /> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import { BentoEmptyState } from '@/components/empty-state'; import { BentoListboxLazyLoad } from '@/internal/listbox/components/listbox-lazy-load'; import { useI18n } from '@/utils/ts/i18n'; import type { ListboxMultiSelectNestedLazyLoadProps } from './listbox-multi-select-nested-lazy-load.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const loading = ref(false); const failedAndRetry = ref(false); const { t } = useI18n<{ message: MessageSchema }>({ messages }); const props = withDefaults(defineProps<ListboxMultiSelectNestedLazyLoadProps>(), {}); async function showMore(event: Event) { event.stopImmediatePropagation(); if (loading.value) { return; } failedAndRetry.value = false; loading.value = true; try { await props.option.lazyLoad?.lazyLoadEvent({ value: props.option.value, index: props.index, }); } catch { failedAndRetry.value = true; } loading.value = false; } defineExpose({ /** * Trigger the lazy load event programmatically. */ showMore, }); </script> <script lang="ts"> export default { name: 'listbox-multi-select-nested-lazy-load', i18n: { messages }, }; </script> <style lang="scss" scoped src="./listbox-multi-select-nested-lazy-load.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div> <div v-for="option in items" :key="`selected-${option.value}`"> <template v-if="searching && isMultiLevel"> <bento-listbox-option class="b-listbox-multi-select-options" :class="conditionalClasses" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :tabindex="computedTabindex(option.value)" :aria-selected="`${isOptionSelected(option)}`" :aria-checked="`${isOptionSelected(option)}`" :aria-disabled="isOptionDisabled ? isOptionDisabled(option) : null" :role="$attrs['role'] || 'option'" @click="toggleSearchOption(option)" @enter-pressed="toggleSearchOption(option)" @space-pressed.prevent="toggleSearchOption(option)" > <decorative-checkbox :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :checked="isOptionSelected(option)" /> <slot v-bind="option"> <span class="b-listbox-multi-select__option-text"> <bento-typography el="span">{{ option.label }}</bento-typography> <bento-typography v-if="shouldShowDescription(option)" class="b-listbox-multi-select__option-description" el="span" > {{ option.description }} </bento-typography> </span> </slot> </bento-listbox-option> </template> <template v-else> <!-- Category --> <template v-if="option.items"> <listbox-multi-select-category :category="option" :static-categories="staticCategories" :is-option-disabled="isOptionDisabled" :selected-items-list="selectedItemsList" :tabindex="computedTabindex(option.value)" @select-category="$emit(ListboxMultiSelectOptionsEvent.SELECT_CATEGORY, option)" @unselect-category="$emit(ListboxMultiSelectOptionsEvent.UNSELECT_CATEGORY, option)" @toggle-category-visibility=" $emit(ListboxMultiSelectOptionsEvent.TOGGLE_CATEGORY_VISIBILITY, $event) " > <listbox-multi-select-options category-items :items="option.items" :is-option-disabled="isOptionDisabled" :items-index="itemsIndex" :focused-index="focusedIndex" :is-multi-level="isMultiLevel" :static-categories="staticCategories" :selected-items-list="selectedItemsList" :searching="searching" :role="$attrs['role'] || 'option'" @toggle-checkbox-selection="value => toggleCheckboxSelection(value)" /> </listbox-multi-select-category> </template> <!-- Option --> <bento-listbox-option v-else class="b-listbox-multi-select-options" :class="conditionalClasses" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :tabindex="computedTabindex(option.value)" :aria-selected="`${isOptionSelected(option)}`" :aria-checked="`${isOptionSelected(option)}`" :aria-disabled="isOptionDisabled ? isOptionDisabled(option) : null" :role="$attrs['role'] || 'option'" @click="toggleCheckboxSelection(option)" @enter-pressed="toggleCheckboxSelection(option)" @space-pressed.prevent="toggleCheckboxSelection(option)" > <decorative-checkbox :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :checked="isOptionSelected(option)" /> <slot v-bind="option"> <span class="b-listbox-multi-select__option-text"> <bento-typography el="span">{{ option.label }}</bento-typography> <bento-typography v-if="shouldShowDescription(option)" class="b-listbox-multi-select__option-description" el="span" > {{ option.description }} </bento-typography> </span> </slot> </bento-listbox-option> </template> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, type PropType } from 'vue'; import { BentoListboxOption } from '../../../listbox-option'; import { BentoTypography } from '@/components/typography'; import { ListboxMultiSelectCategory } from './components/listbox-multi-select-category'; import { DecorativeCheckbox } from '@/internal/decorative-checkbox'; import { BentoListboxEvent, type BentoListboxIsOptionDisabled, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxValue, } from '@/types/listbox'; import { ListboxMultiSelectOptionsEvent } from './listbox-multi-select-options.types'; /** * Listbox multi-select options list * * @example * import { ListboxMultiSelectOptions } from './components/listbox-multi-select-options'; * * export default { * components: { ListboxMultiSelect }, * template: ` * <listbox-multi-select * :items="[{ label: 'Option 1', value: 'option-1' }]" * :selected-values="['option-1']" * /> * ` * } */ export default defineComponent({ name: 'listbox-multi-select-options', components: { BentoListboxOption, BentoTypography, ListboxMultiSelectCategory, DecorativeCheckbox, }, inheritAttrs: false, props: { /** * Indicates if the items listed are inside a category * so they can be padded to right by one level in recursion. * Items of categories are automatically defined as "categoryItems" */ categoryItems: { type: Boolean, default: false }, /** * Current focused option index */ focusedIndex: { type: Number, default: 0 }, /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: Function as PropType<BentoListboxIsOptionDisabled>, default: () => false, }, /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem }. * * @property {string} value.label - Text to be displayed in the option * @property {string,number} value.value - Value of the option */ items: { type: Array as PropType<BentoListboxOptions>, required: true, }, /** * Indicates if the elements options are inside a multi-level category */ isMultiLevel: { type: Boolean, default: false }, /** * Flag that indicates that an external search it's being made * to filter out the items inside the the multi-select listbox * * If enabled, hides the "Select all" checkbox in "multiple" mode. */ searching: { type: Boolean, default: false }, /** * List of selected items. * Providing an empty array will select no options. */ selectedItemsList: { type: Array as PropType<Array<BentoListboxValue>>, default: () => [], }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Object with the index of each item. */ itemsIndex: { type: Object as PropType<Record<string, number>>, default: () => ({}), }, }, emits: [ ListboxMultiSelectOptionsEvent.TOGGLE_CHECKBOX_SELECTION, ListboxMultiSelectOptionsEvent.SELECT_CATEGORY, ListboxMultiSelectOptionsEvent.UNSELECT_CATEGORY, ListboxMultiSelectOptionsEvent.TOGGLE_CATEGORY_VISIBILITY, ], setup(props, { emit }) { const toggleCheckboxSelection = (option: BentoListboxOptionItem) => { if (props.isOptionDisabled(option)) { return; } emit(ListboxMultiSelectOptionsEvent.TOGGLE_CHECKBOX_SELECTION, option); }; const isCategory = (option: BentoListboxOptionItem) => !!option.items; const shouldShowDescription = (option: BentoListboxOptionItem) => { const isSearchingMultiLevel = props.isMultiLevel && props.searching; return option.description && (!props.isMultiLevel || isSearchingMultiLevel); }; const isOptionSelected = option => { if (option.items) { return !!option.items.find(item => props.selectedItemsList.includes(item.value)); } return props.selectedItemsList.includes(option.value); }; const toggleSearchOption = option => { if (isCategory(option)) { const event = isOptionSelected(option) ? ListboxMultiSelectOptionsEvent.UNSELECT_CATEGORY : ListboxMultiSelectOptionsEvent.SELECT_CATEGORY; emit(event, option); } else { toggleCheckboxSelection(option); } }; const conditionalClasses = computed(() => ({ 'b-listbox-multi-select-options__static-category-option': props.staticCategories, 'b-listbox-multi-select-options__category-option': props.categoryItems, })); const computedTabindex = value => (props.itemsIndex[value] === props.focusedIndex ? 0 : -1); return { // Values conditionalClasses, // Methods isOptionSelected, shouldShowDescription, toggleCheckboxSelection, toggleSearchOption, computedTabindex, // Enums BentoListboxEvent, ListboxMultiSelectOptionsEvent, }; }, }); </script> <style lang="scss" scoped src="./listbox-multi-select-options.scss" />
|
|
1
|
+
<template> <div> <div v-for="option in items" :key="`selected-${option.value}`"> <template v-if="searching && isMultiLevel"> <bento-listbox-option class="b-listbox-multi-select-options" :class="conditionalClasses" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :tabindex="computedTabindex(option.value)" :aria-selected="`${isOptionSelected(option)}`" :aria-checked="`${isOptionSelected(option)}`" :aria-disabled="isOptionDisabled ? isOptionDisabled(option) : null" :role="$attrs['role'] || 'option'" @click="toggleSearchOption(option)" @enter-pressed="toggleSearchOption(option)" @space-pressed.prevent="toggleSearchOption(option)" > <decorative-checkbox :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :checked="isOptionSelected(option)" /> <slot v-bind="option"> <span class="b-listbox-multi-select__option-text"> <bento-typography el="span">{{ option.label }}</bento-typography> <bento-typography v-if="shouldShowDescription(option)" class="b-listbox-multi-select__option-description" el="span" > {{ option.description }} </bento-typography> </span> </slot> </bento-listbox-option> </template> <template v-else> <!-- Category --> <template v-if="option.items"> <listbox-multi-select-category :category="option" :static-categories="staticCategories" :is-option-disabled="isOptionDisabled" :selected-items-list="selectedItemsList" :option-index="itemsIndex[option.value]" :tabindex="computedTabindex(option.value)" @select-category="$emit(ListboxMultiSelectOptionsEvent.SELECT_CATEGORY, option)" @unselect-category="$emit(ListboxMultiSelectOptionsEvent.UNSELECT_CATEGORY, option)" @toggle-category-visibility=" $emit(ListboxMultiSelectOptionsEvent.TOGGLE_CATEGORY_VISIBILITY, $event) " > <listbox-multi-select-options category-items :items="option.items" :is-option-disabled="isOptionDisabled" :items-index="itemsIndex" :focused-index="focusedIndex" :is-multi-level="isMultiLevel" :static-categories="staticCategories" :selected-items-list="selectedItemsList" :searching="searching" :parent-category="option" :role="$attrs['role'] || 'option'" @toggle-checkbox-selection="value => toggleCheckboxSelection(value)" /> </listbox-multi-select-category> </template> <!-- Option --> <bento-listbox-option v-else class="b-listbox-multi-select-options" :class="conditionalClasses" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :tabindex="computedTabindex(option.value)" :aria-selected="`${isOptionSelected(option)}`" :aria-checked="`${isOptionSelected(option)}`" :aria-disabled="isOptionDisabled ? isOptionDisabled(option) : null" :role="$attrs['role'] || 'option'" @click="toggleCheckboxSelection(option)" @enter-pressed="toggleCheckboxSelection(option)" @space-pressed.prevent="toggleCheckboxSelection(option)" > <decorative-checkbox :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :checked="isOptionSelected(option)" /> <slot v-bind="option"> <span class="b-listbox-multi-select__option-text"> <bento-typography el="span">{{ option.label }}</bento-typography> <bento-typography v-if="shouldShowDescription(option)" class="b-listbox-multi-select__option-description" el="span" > {{ option.description }} </bento-typography> </span> </slot> </bento-listbox-option> </template> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, type PropType } from 'vue'; import { BentoListboxOption } from '../../../listbox-option'; import { BentoTypography } from '@/components/typography'; import { ListboxMultiSelectCategory } from './components/listbox-multi-select-category'; import { DecorativeCheckbox } from '@/internal/decorative-checkbox'; import { BentoListboxEvent, type BentoListboxIsOptionDisabled, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxValue, } from '@/types/listbox'; import { ListboxMultiSelectOptionsEvent } from './listbox-multi-select-options.types'; /** * Listbox multi-select options list * * @example * import { ListboxMultiSelectOptions } from './components/listbox-multi-select-options'; * * export default { * components: { ListboxMultiSelect }, * template: ` * <listbox-multi-select * :items="[{ label: 'Option 1', value: 'option-1' }]" * :selected-values="['option-1']" * /> * ` * } */ export default defineComponent({ name: 'listbox-multi-select-options', components: { BentoListboxOption, BentoTypography, ListboxMultiSelectCategory, DecorativeCheckbox, }, inheritAttrs: false, props: { /** * Indicates if the items listed are inside a category * so they can be padded to right by one level in recursion. * Items of categories are automatically defined as "categoryItems" */ categoryItems: { type: Boolean, default: false }, /** * Current focused option index */ focusedIndex: { type: Number, default: 0 }, /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: Function as PropType<BentoListboxIsOptionDisabled>, default: () => false, }, /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem }. * * @property {string} value.label - Text to be displayed in the option * @property {string,number} value.value - Value of the option */ items: { type: Array as PropType<BentoListboxOptions>, required: true, }, /** * Indicates if the elements options are inside a multi-level category */ isMultiLevel: { type: Boolean, default: false }, /** * Flag that indicates that an external search it's being made * to filter out the items inside the the multi-select listbox * * If enabled, hides the "Select all" checkbox in "multiple" mode. */ searching: { type: Boolean, default: false }, /** * List of selected items. * Providing an empty array will select no options. */ selectedItemsList: { type: Array as PropType<Array<BentoListboxValue>>, default: () => [], }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Object with the index of each item. */ itemsIndex: { type: Object as PropType<Record<string, number>>, default: () => ({}), }, /** * The parent category of the items. */ parentCategory: { type: Object as PropType<BentoListboxOptionItem>, default: null, }, }, emits: [ ListboxMultiSelectOptionsEvent.TOGGLE_CHECKBOX_SELECTION, ListboxMultiSelectOptionsEvent.SELECT_CATEGORY, ListboxMultiSelectOptionsEvent.UNSELECT_CATEGORY, ListboxMultiSelectOptionsEvent.TOGGLE_CATEGORY_VISIBILITY, ], setup(props, { emit }) { const toggleCheckboxSelection = (option: BentoListboxOptionItem) => { if (props.isOptionDisabled(option)) { return; } emit(ListboxMultiSelectOptionsEvent.TOGGLE_CHECKBOX_SELECTION, option); }; const isCategory = (option: BentoListboxOptionItem) => !!option.items; const shouldShowDescription = (option: BentoListboxOptionItem) => { const isSearchingMultiLevel = props.isMultiLevel && props.searching; return option.description && (!props.isMultiLevel || isSearchingMultiLevel); }; const isOptionSelected = option => { const isParentLazySelected = !!props.parentCategory?.lazyLoad && props.selectedItemsList.includes(props.parentCategory.value); if (option.items) { const isLazyCategorySelected = !!option.lazyLoad && props.selectedItemsList.includes(option.value); return ( isParentLazySelected || isLazyCategorySelected || !!option.items.find(item => props.selectedItemsList.includes(item.value)) ); } return isParentLazySelected || props.selectedItemsList.includes(option.value); }; const toggleSearchOption = option => { if (isCategory(option)) { const event = isOptionSelected(option) ? ListboxMultiSelectOptionsEvent.UNSELECT_CATEGORY : ListboxMultiSelectOptionsEvent.SELECT_CATEGORY; emit(event, option); } else { toggleCheckboxSelection(option); } }; const conditionalClasses = computed(() => ({ 'b-listbox-multi-select-options__static-category-option': props.staticCategories, 'b-listbox-multi-select-options__category-option': props.categoryItems, })); const computedTabindex = value => (props.itemsIndex[value] === props.focusedIndex ? 0 : -1); return { // Values conditionalClasses, // Methods isOptionSelected, shouldShowDescription, toggleCheckboxSelection, toggleSearchOption, computedTabindex, // Enums BentoListboxEvent, ListboxMultiSelectOptionsEvent, }; }, }); </script> <style lang="scss" scoped src="./listbox-multi-select-options.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div ref="listboxRef" class="b-listbox-multi-select"> <!-- Selected options --> <div v-if="showSelectedItems"> <ul v-bento-keyboard-navigation-directive class="b-listbox-multi-select__chips" v-on="chipsSectionListeners" > <li v-for="item in selectedOptions" :key="item.value"> <bento-chip ref="selectedListboxItemsRef" :disabled="isOptionDisabled(item)" :label="item.label" condensed @click="item.items ? unselectAllCategory(item) : toggleCheckboxSelection('select', item)" /> </li> </ul> <hr class="b-listbox-multi-select__divider" aria-hidden="true" /> </div> <div v-bento-keyboard-navigation-directive v-bind="ariaAttributes" :role="computedRole" v-on="listboxListeners"> <!-- Select all --> <bento-listbox-option v-if="showSelectAllCheckbox" ref="selectAllListboxItemsRef" class="b-listbox-multi-select__option" :tabindex="focusedIndex === 0 ? 0 : -1" :aria-selected="ariaCheckedComputed !== 'false'" :aria-checked="ariaCheckedComputed" :role="computedOptionRole" @click="handleSelectAll" @enter-pressed="handleSelectAll" @space-pressed.prevent="handleSelectAll" > <decorative-checkbox :checked="isAllSelected" :indeterminate="isIndeterminate" /> <bento-typography el="span"> {{ selectAllCheckboxText }} </bento-typography> </bento-listbox-option> <hr v-if="showSelectAllCheckbox" class="b-listbox-multi-select__divider" aria-hidden="true" /> <!-- Available options --> <listbox-multi-select-options ref="listboxItemsRef" :items="items" :is-option-disabled="isOptionDisabled" :is-multi-level="isMultiLevelSelect" :static-categories="staticCategories" :searching="searching" :selected-items-list="selectedItemsList" :focused-index="focusedIndex" :items-index="computedItemsIndex" :role="computedOptionRole" @toggle-checkbox-selection="toggleCheckboxSelection('select', $event)" @select-category="selectAllCategory" @unselect-category="unselectAllCategory" @toggle-category-visibility="toggleCategoryVisibility" @space-pressed="toggleCheckboxSelection(BentoListboxEvent.SPACE, $event)" @tab-pressed="toggleCheckboxSelection(BentoListboxEvent.TAB, $event)" @enter-pressed="toggleCheckboxSelection(BentoListboxEvent.ENTER, $event)" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </listbox-multi-select-options> </div> </div> </template> <script setup lang="ts"> import { computed, type HTMLAttributes, nextTick, ref, toRef, useAttrs, useSlots, watch } from 'vue'; import { isVue2 } from 'vue-demi'; import { DecorativeCheckbox } from '@/internal/decorative-checkbox'; import { BentoTypography } from '@/components/typography'; import { BentoChip } from '@/components/chip'; import { BentoListboxOption } from '../listbox-option'; import { ListboxMultiSelectOptions } from './components/listbox-multi-select-options'; import { useCheckboxSelectAll } from '@/composables'; import { useListboxKeyboardNavigation } from '../../composables/useListboxKeyboardNavigation'; import { useMultiLevelItems } from '../../composables/use-multi-level-items/use-multi-level-items'; import { useVisibleDomOptions } from '@/internal/listbox/composables/use-visible-dom-options/use-visible-dom-options'; import { useI18n } from '@/utils/ts/i18n'; import { BentoKeyboardNavigationDirective as vBentoKeyboardNavigationDirective } from '@/directives'; import { BentoListboxEvent, type BentoListboxMultiSelectValue, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxValue, } from '@/types/listbox'; import { type Booleanish } from '@/types/prop-types'; import { BentoKeyboardNavigationKeyDownEvent } from '@/types/keyboard-navigation'; import { type ListboxMultiSelectProps } from './listbox-multi-select.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const props = withDefaults(defineProps<ListboxMultiSelectProps>(), { hasMoreItems: false, isOptionDisabled: isVue2 ? () => () => false : () => false, lazyLoadType: 'none', searching: false, staticCategories: false, }); const emit = defineEmits<{ /** * Emits when the selection changes */ (e: 'select', value: Array<BentoListboxOptionItem>): void; }>(); const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const slots = useSlots(); const attrs = useAttrs(); const ariaAttributes = computed( () => ({ 'aria-label': attrs['aria-label']?.toString() as string, 'aria-busy': attrs['aria-busy']?.toString() as Booleanish, 'aria-atomic': attrs['aria-atomic']?.toString() as Booleanish, 'aria-live': attrs['aria-live']?.toString() as string, 'aria-multiselectable': true, }) as HTMLAttributes ); const listboxRef = ref(null); const selectAllListboxItemsRef = ref(null); const selectedListboxItemsRef = ref(null); const listboxItemsRef = ref(null); const selectedItemsList = computed<Array<BentoListboxValue>>(() => props.selectedValues.map(({ value }) => value)); const { isMultiLevelSelect, flattenedItemsList } = useMultiLevelItems(toRef(props, 'items')); const isTreePattern = computed(() => isMultiLevelSelect.value && !props.staticCategories); const computedRole = computed(() => (isTreePattern.value ? 'tree' : 'listbox')); const computedOptionRole = computed(() => (isTreePattern.value ? 'treeitem' : 'option')); const optionStates = (option: BentoListboxOptionItem) => { const isDisabled = props.isOptionDisabled(option); const isPreSelected = (selectedItemsList.value as BentoListboxMultiSelectValue)?.includes(option.value) || false; return { isDisabled, isPreSelected }; }; // Items that are not disabled and pre-selected disabled items const enabledItems = computed(() => { if (props.searching && isMultiLevelSelect) { return props.items; } const fullItemsList = flattenedItemsList.value.filter(option => { const { isDisabled, isPreSelected } = optionStates(option); return (isDisabled && isPreSelected) || !isDisabled; }); props.selectedValues.forEach(selectedValue => { if (!fullItemsList.find(item => item.value === selectedValue.value)) { fullItemsList.push(selectedValue); } }); return fullItemsList; }); const visibleSelectedList = computed( () => enabledItems.value?.filter(option => { if (option.items && isMultiLevelSelect.value && props.searching) { const amountOfSelectedCategoryOptions = option.items.filter(categoryOption => (props.selectedValues ?? []).includes(categoryOption.value) ).length; return amountOfSelectedCategoryOptions === option.items.length; } return selectedItemsList.value?.includes(option.value); // Check for category }) as BentoListboxMultiSelectValue ); const calculateTotalItems = () => { if (isMultiLevelSelect.value && !props.searching) { return flattenedItemsList.value.length; } return props.items.length; }; const selectAllCheckboxText = computed(() => { const possibleSelections = enabledItems.value.length; const total = calculateTotalItems(); const amountSelectedValues = visibleSelectedList.value?.length || 0; if (amountSelectedValues === 0) { return t('selectAll', { total: n(possibleSelections) }); } if (amountSelectedValues === total) { return t('allSelected', { total: n(total) }); } return amountSelectedValues <= total ? t('numberOfTotalSelected', { number: n(amountSelectedValues), total: n(total) }) : t('numbersSelected', { number: n(amountSelectedValues) }); }); const selectAll = (selectableItems: BentoListboxOptions) => { const filterOutDisabledAndNotPreselectedOptions = option => { const { isDisabled, isPreSelected } = optionStates(option); return (isDisabled && isPreSelected) || !isDisabled; }; // Adding or removing this list of values const addOrRemoveList = selectableItems .filter(filterOutDisabledAndNotPreselectedOptions) .filter(item => !selectedItemsList.value.includes(item.value)); // MAKE SURE NOT TO ADD DUPLICATES emit('select', [...props.selectedValues, ...addOrRemoveList]); }; const unselectAll = (selectableItems: BentoListboxOptions) => { const findEnabledUnselectedItems = option => { const { isDisabled, isPreSelected } = optionStates(option); return !(isDisabled && isPreSelected); }; const unselectedItemsList = selectableItems.filter(findEnabledUnselectedItems).map(({ value }) => value); const newSelectedList = props.selectedValues.filter(item => !unselectedItemsList?.includes(item.value)); emit('select', newSelectedList); }; const selectAllItems = () => { selectAll(flattenedItemsList.value); }; const unselectAllItems = () => { unselectAll(flattenedItemsList.value); }; const { isAllSelected, isIndeterminate, toggleSelectAll } = useCheckboxSelectAll( visibleSelectedList, enabledItems, selectAllItems, unselectAllItems ); const ariaCheckedComputed = computed(() => { if (isIndeterminate.value) { return 'mixed'; } return `${isAllSelected.value}`; }); const isSelectAllOn = ref(isAllSelected.value); const handleSelectAll = () => { isSelectAllOn.value = !isSelectAllOn.value; toggleSelectAll(isSelectAllOn.value); }; watch(isAllSelected, () => { isSelectAllOn.value = isAllSelected.value; }); const selectAllCategory = (category: BentoListboxOptionItem) => { selectAll(category.items); }; const unselectAllCategory = (category: BentoListboxOptionItem) => { unselectAll(category.items); }; const toggleCheckboxSelection = (eventName, selectedOption: BentoListboxOptionItem) => { let exists = false; const newSelectedList = props.selectedValues.filter(({ value }) => { if (selectedOption.value === value) { exists = true; return false; } return true; }); if (!exists) { newSelectedList.push(selectedOption); } emit(eventName, newSelectedList); }; const selectedOptions = computed(() => { if (!isMultiLevelSelect.value) { return props.selectedValues; } const isOptionSelected = (option: BentoListboxOptionItem): boolean => (selectedItemsList.value as unknown as Array<string | number>).includes(option.value); const categoryOptionsSelected = (categoryOptions: Array<BentoListboxOptionItem>): boolean => !props.staticCategories && categoryOptions.every(option => isOptionSelected(option)); const optionsFlat = props.items.flatMap(option => option.items && !categoryOptionsSelected(option.items) ? option.items : option ); const options = optionsFlat.filter(option => { if (option.items) { return true; } return isOptionSelected(option); }); // Append selected values not present in the current items list (e.g. not yet fetched) const knownValues = new Set<BentoListboxValue>(); optionsFlat.forEach(option => { knownValues.add(option.value); option.items?.forEach(sub => knownValues.add(sub.value)); }); const unfetchedSelected = props.selectedValues.filter(sv => !knownValues.has(sv.value)); return [...options, ...unfetchedSelected]; }); const showSelectedItems = computed(() => { const isLazyLoad = ['automatic', 'button'].includes(props.lazyLoadType); const hasAllItemsSelected = props.selectedValues?.length > 0 && visibleSelectedList.value?.length !== flattenedItemsList.value?.length; if (isLazyLoad && props.hasMoreItems) { return !!props.selectedValues?.length; } return hasAllItemsSelected; }); const showSelectAllCheckbox = computed(() => { const isLazyLoad = ['automatic', 'button'].includes(props.lazyLoadType); if (!isLazyLoad) { return true; } return !props.hasMoreItems; }); // Keyboard navigation const expandedCategories = ref([]); const { visibleDomOptions, updateVisibleDomOptions } = useVisibleDomOptions( listboxRef, toRef(props, 'items'), computedOptionRole ); const toggleCategoryVisibility = category => { if (expandedCategories.value.includes(category)) { expandedCategories.value = expandedCategories.value.filter(item => item !== category); } else { expandedCategories.value.push(category); } nextTick(() => { updateVisibleDomOptions(); }); }; const focusItem = (nextFocusedItemIndex: number) => { visibleDomOptions.value[nextFocusedItemIndex]?.focus(); }; const { moveToNextElement, moveToPreviousElement, moveToFirstElement, moveToLastElement, preventDefault, focusedIndex, setListboxFocusedIndex, } = useListboxKeyboardNavigation( { items: visibleDomOptions, }, focusItem ); const listboxListeners = { [BentoKeyboardNavigationKeyDownEvent.ARROW_UP]: (event: CustomEvent<KeyboardEvent>) => moveToPreviousElement(event), [BentoKeyboardNavigationKeyDownEvent.ARROW_DOWN]: (event: CustomEvent<KeyboardEvent>) => moveToNextElement(event), [BentoKeyboardNavigationKeyDownEvent.HOME]: moveToFirstElement, [BentoKeyboardNavigationKeyDownEvent.END]: moveToLastElement, }; defineExpose({ /** * Method to set the index of the item to be focused on * Used for focus management to be kept in-sync with parent e.g. dropdowns */ setListboxFocusedIndex, }); const chipsSectionListeners = { [BentoKeyboardNavigationKeyDownEvent.ARROW_UP]: preventDefault, [BentoKeyboardNavigationKeyDownEvent.ARROW_DOWN]: preventDefault, }; const computedItemsIndex = computed(() => { let itemIndex = showSelectAllCheckbox.value ? 1 : 0; const indexMap = {}; props.items.forEach(item => { let subItemsVisible = expandedCategories.value.includes(item.value); if (item.items) { if (props.staticCategories) { subItemsVisible = true; } else { indexMap[item.value] = itemIndex++; } if (subItemsVisible) { item.items.forEach(subItem => (indexMap[subItem.value] = itemIndex++)); } } else { indexMap[item.value] = itemIndex++; } }); return indexMap; }); </script> <script lang="ts"> /** * Listbox multi-select options list * * @example * import { BentoListboxMultiSelect } from '@adyen/bento-vue2'; * * export default { * components: { BentoListboxMultiSelect }, * template: ` * <bento-listbox-multi-select * :items="[{ label: 'Option 1', value: 'option-1' }]" * :selected-values="['option-1']" * /> * ` * } */ export default { i18n: { messages } }; </script> <style lang="scss" scoped src="./listbox-multi-select.scss" />
|
|
1
|
+
<template> <div ref="listboxRef" class="b-listbox-multi-select"> <!-- Selected options --> <div v-if="showSelectedItems"> <ul v-bento-keyboard-navigation-directive class="b-listbox-multi-select__chips" v-on="chipsSectionListeners" > <li v-for="item in selectedOptions" :key="item.value"> <bento-chip ref="selectedListboxItemsRef" :disabled="isOptionDisabled(item)" :label="item.label" condensed @click="item.items ? unselectAllCategory(item) : toggleCheckboxSelection('select', item)" /> </li> </ul> <hr class="b-listbox-multi-select__divider" aria-hidden="true" /> </div> <div v-bento-keyboard-navigation-directive v-bind="ariaAttributes" :role="computedRole" v-on="listboxListeners"> <!-- Select all --> <bento-listbox-option v-if="showSelectAllCheckbox" ref="selectAllListboxItemsRef" class="b-listbox-multi-select__option" :tabindex="focusedIndex === 0 ? 0 : -1" :aria-selected="ariaCheckedComputed !== 'false'" :aria-checked="ariaCheckedComputed" :role="computedOptionRole" @click="handleSelectAll" @enter-pressed="handleSelectAll" @space-pressed.prevent="handleSelectAll" > <decorative-checkbox :checked="isAllSelected" :indeterminate="isIndeterminate" /> <bento-typography el="span"> {{ selectAllCheckboxText }} </bento-typography> </bento-listbox-option> <hr v-if="showSelectAllCheckbox" class="b-listbox-multi-select__divider" aria-hidden="true" /> <!-- Available options --> <listbox-multi-select-options ref="listboxItemsRef" :items="items" :is-option-disabled="isOptionDisabled" :is-multi-level="isMultiLevelSelect" :static-categories="staticCategories" :searching="searching" :selected-items-list="selectedItemsList" :focused-index="focusedIndex" :items-index="computedItemsIndex" :role="computedOptionRole" @toggle-checkbox-selection="toggleCheckboxSelection('select', $event)" @select-category="selectAllCategory" @unselect-category="unselectAllCategory" @toggle-category-visibility="toggleCategoryVisibility" @space-pressed="toggleCheckboxSelection(BentoListboxEvent.SPACE, $event)" @tab-pressed="toggleCheckboxSelection(BentoListboxEvent.TAB, $event)" @enter-pressed="toggleCheckboxSelection(BentoListboxEvent.ENTER, $event)" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </listbox-multi-select-options> </div> </div> </template> <script setup lang="ts"> import { computed, type HTMLAttributes, nextTick, ref, toRef, useAttrs, useSlots, watch } from 'vue'; import { isVue2 } from 'vue-demi'; import { DecorativeCheckbox } from '@/internal/decorative-checkbox'; import { BentoTypography } from '@/components/typography'; import { BentoChip } from '@/components/chip'; import { BentoListboxOption } from '../listbox-option'; import { ListboxMultiSelectOptions } from './components/listbox-multi-select-options'; import { useCheckboxSelectAll } from '@/composables'; import { useListboxKeyboardNavigation } from '../../composables/useListboxKeyboardNavigation'; import { useMultiLevelItems } from '../../composables/use-multi-level-items/use-multi-level-items'; import { useVisibleDomOptions } from '@/internal/listbox/composables/use-visible-dom-options/use-visible-dom-options'; import { useI18n } from '@/utils/ts/i18n'; import { BentoKeyboardNavigationDirective as vBentoKeyboardNavigationDirective } from '@/directives'; import { BentoListboxEvent, type BentoListboxMultiSelectValue, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxValue, } from '@/types/listbox'; import { type Booleanish } from '@/types/prop-types'; import { BentoKeyboardNavigationKeyDownEvent } from '@/types/keyboard-navigation'; import { type ListboxMultiSelectProps } from './listbox-multi-select.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const props = withDefaults(defineProps<ListboxMultiSelectProps>(), { hasMoreItems: false, isOptionDisabled: isVue2 ? () => () => false : () => false, lazyLoadType: 'none', searching: false, staticCategories: false, }); const emit = defineEmits<{ /** * Emits when the selection changes */ (e: 'select', value: Array<BentoListboxOptionItem>): void; }>(); const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const slots = useSlots(); const attrs = useAttrs(); const ariaAttributes = computed( () => ({ 'aria-label': attrs['aria-label']?.toString() as string, 'aria-busy': attrs['aria-busy']?.toString() as Booleanish, 'aria-atomic': attrs['aria-atomic']?.toString() as Booleanish, 'aria-live': attrs['aria-live']?.toString() as string, 'aria-multiselectable': true, }) as HTMLAttributes ); const listboxRef = ref(null); const selectAllListboxItemsRef = ref(null); const selectedListboxItemsRef = ref(null); const listboxItemsRef = ref(null); const selectedItemsList = computed<Array<BentoListboxValue>>(() => props.selectedValues.map(({ value }) => value)); const { isMultiLevelSelect, flattenedItemsList } = useMultiLevelItems(toRef(props, 'items')); const hasLazyLoadCategory = computed(() => props.items.some(item => item.items && item.lazyLoad)); const lazyLoadAwareFlattenedItems = computed(() => { if (!isMultiLevelSelect.value) { return props.items; } return props.items.reduce<BentoListboxOptions>((acc, item) => { if (item.items) { if (item.lazyLoad) { acc.push(item); } else { acc.push(...item.items); } } else { acc.push(item); } return acc; }, []); }); const isTreePattern = computed(() => isMultiLevelSelect.value && !props.staticCategories); const computedRole = computed(() => (isTreePattern.value ? 'tree' : 'listbox')); const computedOptionRole = computed(() => (isTreePattern.value ? 'treeitem' : 'option')); const optionStates = (option: BentoListboxOptionItem) => { const isDisabled = props.isOptionDisabled(option); const isPreSelected = (selectedItemsList.value as BentoListboxMultiSelectValue)?.includes(option.value) || false; return { isDisabled, isPreSelected }; }; // Items that are not disabled and pre-selected disabled items const enabledItems = computed(() => { if (props.searching && isMultiLevelSelect) { return props.items; } const fullItemsList = lazyLoadAwareFlattenedItems.value.filter(option => { if (option.lazyLoad) { return true; } const { isDisabled, isPreSelected } = optionStates(option); return (isDisabled && isPreSelected) || !isDisabled; }); props.selectedValues.forEach(selectedValue => { if (!fullItemsList.find(item => item.value === selectedValue.value)) { fullItemsList.push(selectedValue); } }); return fullItemsList; }); const visibleSelectedList = computed<BentoListboxOptions>(() => enabledItems.value?.filter(option => { return selectedItemsList.value?.includes(option.value); // Check for category }) ); const calculateTotalItems = () => { if (isMultiLevelSelect.value && !props.searching) { return flattenedItemsList.value.length; } return props.items.length; }; const selectAllCheckboxText = computed(() => { const possibleSelections = enabledItems.value.length; const total = calculateTotalItems(); const amountSelectedValues = visibleSelectedList.value?.length || 0; if (amountSelectedValues === 0) { return t('selectAll', { total: n(possibleSelections) }); } if (amountSelectedValues === total) { return t('allSelected', { total: n(total) }); } return amountSelectedValues <= total ? t('numberOfTotalSelected', { number: n(amountSelectedValues), total: n(total) }) : t('numbersSelected', { number: n(amountSelectedValues) }); }); const selectAll = (selectableItems: BentoListboxOptions) => { const filterOutDisabledAndNotPreselectedOptions = option => { const { isDisabled, isPreSelected } = optionStates(option); return (isDisabled && isPreSelected) || !isDisabled; }; // Adding or removing this list of values const addOrRemoveList = selectableItems .filter(filterOutDisabledAndNotPreselectedOptions) .filter(item => !selectedItemsList.value.includes(item.value)); // MAKE SURE NOT TO ADD DUPLICATES emit('select', [...props.selectedValues, ...addOrRemoveList]); }; const unselectAll = (selectableItems: BentoListboxOptions) => { const findEnabledUnselectedItems = option => { const { isDisabled, isPreSelected } = optionStates(option); return !(isDisabled && isPreSelected); }; const unselectedItemsList = selectableItems.filter(findEnabledUnselectedItems).map(({ value }) => value); const newSelectedList = props.selectedValues.filter(item => !unselectedItemsList?.includes(item.value)); emit('select', newSelectedList); }; const selectAllItems = () => { selectAll(flattenedItemsList.value); }; const unselectAllItems = () => { unselectAll(flattenedItemsList.value); }; const { isAllSelected, isIndeterminate, toggleSelectAll } = useCheckboxSelectAll( visibleSelectedList, enabledItems, selectAllItems, unselectAllItems ); const ariaCheckedComputed = computed(() => { if (isIndeterminate.value) { return 'mixed'; } return `${isAllSelected.value}`; }); const isSelectAllOn = ref(isAllSelected.value); const handleSelectAll = () => { isSelectAllOn.value = !isSelectAllOn.value; toggleSelectAll(isSelectAllOn.value); }; watch(isAllSelected, () => { isSelectAllOn.value = isAllSelected.value; }); const selectAllCategory = (category: BentoListboxOptionItem) => { if (category.lazyLoad) { const childValues = (category.items ?? []).map(({ value }) => value); const withoutChildren = props.selectedValues.filter(({ value }) => !childValues.includes(value)); emit('select', [...withoutChildren, category]); } else { selectAll(category.items); } }; const unselectAllCategory = (category: BentoListboxOptionItem) => { if (category.lazyLoad) { emit( 'select', props.selectedValues.filter(({ value }) => value !== category.value) ); } else { unselectAll(category.items); } }; const toggleCheckboxSelection = (eventName, selectedOption: BentoListboxOptionItem) => { let exists = false; let newSelectedList = props.selectedValues.filter(({ value }) => { if (selectedOption.value === value) { exists = true; return false; } return true; }); if (exists) { emit(eventName, newSelectedList); return; } // Check if the item's parent lazy category is selected const parentLazyCategory = props.items.find( item => item.items?.some(subItem => subItem.value === selectedOption.value) && item.lazyLoad && selectedItemsList.value.includes(item.value) ); if (parentLazyCategory) { // Remove parent category newSelectedList = newSelectedList.filter(({ value }) => value !== parentLazyCategory.value); // Add other loaded children const otherLoadedChildren = parentLazyCategory.items.filter( subItem => subItem.value !== selectedOption.value ); newSelectedList.push(...otherLoadedChildren); } else { newSelectedList.push(selectedOption); } emit(eventName, newSelectedList); }; const selectedOptions = computed(() => { if (!isMultiLevelSelect.value) { return props.selectedValues; } const isOptionSelected = (option: BentoListboxOptionItem): boolean => (selectedItemsList.value as unknown as Array<string | number>).includes(option.value); const categoryOptionsSelected = (category: BentoListboxOptionItem): boolean => { if (category.lazyLoad && isOptionSelected(category)) { return true; } return ( !props.staticCategories && category.items.length > 0 && category.items.every(option => isOptionSelected(option)) ); }; const optionsFlat = props.items.flatMap(option => option.items && !categoryOptionsSelected(option) ? option.items : option ); const options = optionsFlat.filter(option => { if (option.items) { return true; } return isOptionSelected(option); }); const knownValues = new Set<BentoListboxValue>(); optionsFlat.forEach(option => { knownValues.add(option.value); option.items?.forEach(sub => knownValues.add(sub.value)); }); const unfetchedSelected = props.selectedValues.filter(sv => !knownValues.has(sv.value)); return [...options, ...unfetchedSelected]; }); const showSelectedItems = computed(() => { if (!selectedOptions.value?.length) { return false; } const isLazyLoad = ['automatic', 'button'].includes(props.lazyLoadType); const hasAllItemsSelected = props.selectedValues?.length > 0 && visibleSelectedList.value?.length !== enabledItems.value?.length; if (isLazyLoad && props.hasMoreItems) { return !!props.selectedValues?.length; } return hasAllItemsSelected; }); const showSelectAllCheckbox = computed(() => { if (hasLazyLoadCategory.value) { return false; } const isLazyLoad = ['automatic', 'button'].includes(props.lazyLoadType); if (!isLazyLoad) { return true; } return !props.hasMoreItems; }); // Keyboard navigation const expandedCategories = ref([]); const { visibleDomOptions, updateVisibleDomOptions } = useVisibleDomOptions( listboxRef, toRef(props, 'items'), computedOptionRole ); const toggleCategoryVisibility = category => { if (expandedCategories.value.includes(category)) { expandedCategories.value = expandedCategories.value.filter(item => item !== category); } else { expandedCategories.value.push(category); } nextTick(() => { updateVisibleDomOptions(); }); }; const focusItem = (nextFocusedItemIndex: number) => { visibleDomOptions.value[nextFocusedItemIndex]?.focus(); }; const { moveToNextElement, moveToPreviousElement, moveToFirstElement, moveToLastElement, preventDefault, focusedIndex, setListboxFocusedIndex, } = useListboxKeyboardNavigation( { items: visibleDomOptions, }, focusItem ); const listboxListeners = { [BentoKeyboardNavigationKeyDownEvent.ARROW_UP]: (event: CustomEvent<KeyboardEvent>) => moveToPreviousElement(event), [BentoKeyboardNavigationKeyDownEvent.ARROW_DOWN]: (event: CustomEvent<KeyboardEvent>) => moveToNextElement(event), [BentoKeyboardNavigationKeyDownEvent.HOME]: moveToFirstElement, [BentoKeyboardNavigationKeyDownEvent.END]: moveToLastElement, }; defineExpose({ /** * Method to set the index of the item to be focused on * Used for focus management to be kept in-sync with parent e.g. dropdowns */ setListboxFocusedIndex, }); const chipsSectionListeners = { [BentoKeyboardNavigationKeyDownEvent.ARROW_UP]: preventDefault, [BentoKeyboardNavigationKeyDownEvent.ARROW_DOWN]: preventDefault, }; const computedItemsIndex = computed(() => { let itemIndex = showSelectAllCheckbox.value ? 1 : 0; const indexMap = {}; props.items.forEach(item => { let subItemsVisible = expandedCategories.value.includes(item.value); if (item.items) { if (props.staticCategories) { subItemsVisible = true; } else { indexMap[item.value] = itemIndex++; } if (subItemsVisible) { item.items.forEach(subItem => (indexMap[subItem.value] = itemIndex++)); } } else { indexMap[item.value] = itemIndex++; } }); return indexMap; }); </script> <script lang="ts"> /** * Listbox multi-select options list * * @example * import { BentoListboxMultiSelect } from '@adyen/bento-vue2'; * * export default { * components: { BentoListboxMultiSelect }, * template: ` * <bento-listbox-multi-select * :items="[{ label: 'Option 1', value: 'option-1' }]" * :selected-values="['option-1']" * /> * ` * } */ export default { i18n: { messages } }; </script> <style lang="scss" scoped src="./listbox-multi-select.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div ref="listboxRef" v-bento-keyboard-navigation-directive v-bind="ariaAttributes" role="listbox" v-on="listboxListeners" @focusin="handleVirtualScrollingFocus" > <template v-if="hasCategories && staticCategories"> <template v-for="item in items"> <bento-listbox-single-select-category v-if="item.items && item.items.length > 0" :key="`category-${item.value}`" :category-label="item.label" > <bento-listbox-single-select-option v-for="option in item.items" :key="option.value" ref="listboxItemRef" role="option" :option="option" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :selected="option.value === selectedItem.value" v-on="listboxOptionListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select-option> </bento-listbox-single-select-category> <bento-listbox-single-select-option v-else :key="`option-${item.value}`" ref="listboxItemRef" role="option" :option="item" :disabled="isOptionDisabled ? isOptionDisabled(item) : null" :selected="item.value === selectedItem.value" v-on="listboxOptionListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select-option> </template> </template> <template v-else> <bento-listbox-single-select-option v-for="option in items" :key="option.value" ref="listboxItemRef" role="option" :option="option" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :selected="option.value === selectedItem.value" v-on="listboxOptionListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select-option> </template> </div> </template> <script lang="ts"> import { computed, defineComponent, type HTMLAttributes, nextTick, type PropType, ref, toRef } from 'vue'; import { BentoListboxSingleSelectCategory } from './components/listbox-single-select-category'; import { BentoListboxSingleSelectOption } from '../listbox-single-select-option'; import { useListboxKeyboardNavigation } from '../../composables/useListboxKeyboardNavigation'; import { useVisibleDomOptions } from '@/internal/listbox/composables/use-visible-dom-options/use-visible-dom-options'; import { BentoListboxEvent, type BentoListboxIsOptionDisabled, type BentoListboxOptions } from '@/types/listbox'; import { BentoKeyboardNavigationKeyDownEvent } from '@/types/keyboard-navigation'; import { type Booleanish } from '@/types/prop-types'; import { BentoKeyboardNavigationDirective } from '@/directives'; /** * Listbox single-select options list * * @example * import { BentoListboxMultiSelect } from '@adyen/bento-vue2'; * * export default { * components: { BentoListboxMultiSelect }, * template: ` * <bento-listbox-multi-select * :items="[{ label: 'Option 1', value: 'option-1' }]" * :selected-values="['option-1']" * /> * ` * } */ export default defineComponent({ name: 'bento-listbox-single-select', components: { BentoListboxSingleSelectCategory, BentoListboxSingleSelectOption, }, directives: { BentoKeyboardNavigationDirective }, inheritAttrs: false, props: { /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: Function as PropType<BentoListboxIsOptionDisabled>, default: () => false, }, /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem }. * * @property {string} value.label - Text to be displayed in the option * @property {string,number} value.value - Value of the option */ items: { type: Array as PropType<BentoListboxOptions>, required: true, }, /** * The `input` value. * Providing an empty string will select no options. * Set to an empty string `''` if you don't want any of the available options to be selected */ selectedValue: { type: Array as PropType<BentoListboxOptions>, default: undefined, }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Total number of items in the full list (used for virtual scroll keyboard navigation). * When greater than 0, virtual scroll keyboard navigation is enabled. */ totalItemCount: { type: Number, default: 0 }, /** * Function to scroll the virtual list container to a given item index. */ scrollToIndex: { type: Function as PropType<(index: number) => void>, default: undefined }, /** * The start index of the currently rendered virtual scroll slice. */ virtualScrollStartIndex: { type: Number, default: 0 }, }, emits: [BentoListboxEvent.SELECT, BentoListboxEvent.ENTER, BentoListboxEvent.SPACE, BentoListboxEvent.TAB], setup(props, { emit, expose, slots, attrs }) { const listboxRef = ref(
|
|
1
|
+
<template> <div ref="listboxRef" v-bento-keyboard-navigation-directive v-bind="ariaAttributes" role="listbox" v-on="listboxListeners" @focusin="handleVirtualScrollingFocus" > <template v-if="hasCategories && staticCategories"> <template v-for="item in items"> <bento-listbox-single-select-category v-if="item.items && item.items.length > 0" :key="`category-${item.value}`" :category-label="item.label" > <bento-listbox-single-select-option v-for="option in item.items" :key="option.value" ref="listboxItemRef" role="option" :option="option" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :selected="option.value === selectedItem.value" v-on="listboxOptionListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select-option> </bento-listbox-single-select-category> <bento-listbox-single-select-option v-else :key="`option-${item.value}`" ref="listboxItemRef" role="option" :option="item" :disabled="isOptionDisabled ? isOptionDisabled(item) : null" :selected="item.value === selectedItem.value" v-on="listboxOptionListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select-option> </template> </template> <template v-else> <bento-listbox-single-select-option v-for="option in items" :key="option.value" ref="listboxItemRef" role="option" :option="option" :disabled="isOptionDisabled ? isOptionDisabled(option) : null" :selected="option.value === selectedItem.value" v-on="listboxOptionListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select-option> </template> </div> </template> <script lang="ts"> import { computed, defineComponent, type HTMLAttributes, nextTick, type PropType, ref, toRef } from 'vue'; import { BentoListboxSingleSelectCategory } from './components/listbox-single-select-category'; import { BentoListboxSingleSelectOption } from '../listbox-single-select-option'; import { useListboxKeyboardNavigation } from '../../composables/useListboxKeyboardNavigation'; import { useVisibleDomOptions } from '@/internal/listbox/composables/use-visible-dom-options/use-visible-dom-options'; import { BentoListboxEvent, type BentoListboxIsOptionDisabled, type BentoListboxOptions } from '@/types/listbox'; import { BentoKeyboardNavigationKeyDownEvent } from '@/types/keyboard-navigation'; import { type Booleanish } from '@/types/prop-types'; import { BentoKeyboardNavigationDirective } from '@/directives'; /** * Listbox single-select options list * * @example * import { BentoListboxMultiSelect } from '@adyen/bento-vue2'; * * export default { * components: { BentoListboxMultiSelect }, * template: ` * <bento-listbox-multi-select * :items="[{ label: 'Option 1', value: 'option-1' }]" * :selected-values="['option-1']" * /> * ` * } */ export default defineComponent({ name: 'bento-listbox-single-select', components: { BentoListboxSingleSelectCategory, BentoListboxSingleSelectOption, }, directives: { BentoKeyboardNavigationDirective }, inheritAttrs: false, props: { /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: Function as PropType<BentoListboxIsOptionDisabled>, default: () => false, }, /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem }. * * @property {string} value.label - Text to be displayed in the option * @property {string,number} value.value - Value of the option */ items: { type: Array as PropType<BentoListboxOptions>, required: true, }, /** * The `input` value. * Providing an empty string will select no options. * Set to an empty string `''` if you don't want any of the available options to be selected */ selectedValue: { type: Array as PropType<BentoListboxOptions>, default: undefined, }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Total number of items in the full list (used for virtual scroll keyboard navigation). * When greater than 0, virtual scroll keyboard navigation is enabled. */ totalItemCount: { type: Number, default: 0 }, /** * Function to scroll the virtual list container to a given item index. */ scrollToIndex: { type: Function as PropType<(index: number) => void>, default: undefined }, /** * The start index of the currently rendered virtual scroll slice. */ virtualScrollStartIndex: { type: Number, default: 0 }, }, emits: [BentoListboxEvent.SELECT, BentoListboxEvent.ENTER, BentoListboxEvent.SPACE, BentoListboxEvent.TAB], setup(props, { emit, expose, slots, attrs }) { const listboxRef = ref<HTMLElement>(); const listboxItemRef = ref([]); const selectedItem = computed(() => !!props.selectedValue?.length && props.selectedValue.at(0)); const ariaAttributes = computed( () => ({ 'aria-label': attrs['aria-label']?.toString() as string, 'aria-busy': attrs['aria-busy']?.toString() as Booleanish, 'aria-atomic': attrs['aria-atomic']?.toString() as Booleanish, 'aria-live': attrs['aria-live']?.toString() as string, }) as HTMLAttributes ); /** * Finds out if items have sub items */ const hasCategories = computed(() => !!props.items.some(({ items }) => !!items)); const onOptionSelected = eventName => (selectedOption: BentoListboxOptions) => { emit(eventName, [selectedOption]); }; // Keyboard navigation const { visibleDomOptions, updateVisibleDomOptions } = useVisibleDomOptions( listboxRef, toRef(props, 'items'), ref('option'), false ); const isVirtualScrollEnabled = computed(() => props.totalItemCount > 0); // When virtual scroll re-renders items (e.g. on mouse wheel scroll), the // browser may auto-focus an option. Sync the keyboard navigation index to // match the focused element so subsequent arrow key presses navigate from // the correct position. const handleVirtualScrollingFocus = (event: FocusEvent) => { if (!isVirtualScrollEnabled.value) { return; } const target = event.target as HTMLElement; if (target === listboxRef.value || target?.getAttribute('role') !== 'option') { return; } const localIndex = visibleDomOptions.value.indexOf(target as HTMLDivElement); if (localIndex !== -1) { const globalIndex = localIndex + props.virtualScrollStartIndex; setListboxFocusedIndex(globalIndex); } }; const focusItem = async (globalIndex: number) => { if (isVirtualScrollEnabled.value && props.scrollToIndex) { props.scrollToIndex(globalIndex); await nextTick(); await updateVisibleDomOptions(); const newDomIndex = globalIndex - props.virtualScrollStartIndex; visibleDomOptions.value[newDomIndex]?.focus(); } else { visibleDomOptions.value[globalIndex]?.focus(); } }; const navigateToItem = async (globalIndex: number) => { setListboxFocusedIndex(globalIndex); await focusItem(globalIndex); }; const scrollIntoContainer = (listboxItemElement?: HTMLElement, listboxElement?: HTMLElement) => { if (!listboxItemElement || !listboxElement) { return; } const elementRect = listboxItemElement.getBoundingClientRect(); const scrollableContainer = listboxElement; const containerRect = scrollableContainer.getBoundingClientRect(); if (elementRect.top < containerRect.top) { scrollableContainer.scrollTop -= containerRect.top - elementRect.top; } else if (elementRect.bottom > containerRect.bottom) { scrollableContainer.scrollTop += elementRect.bottom - containerRect.bottom; } }; const scrollToItem = async (globalIndex: number, listboxElement?: HTMLElement) => { await updateVisibleDomOptions(); if (isVirtualScrollEnabled.value && props.scrollToIndex) { props.scrollToIndex(globalIndex); } else { scrollIntoContainer(visibleDomOptions.value[globalIndex], listboxElement); } }; const { moveToNextElement, moveToPreviousElement, moveToFirstElement, moveToLastElement, setListboxFocusedIndex, } = useListboxKeyboardNavigation( { items: visibleDomOptions, totalItemCount: toRef(props, 'totalItemCount'), }, focusItem ); const listboxListeners = { [BentoKeyboardNavigationKeyDownEvent.ARROW_UP]: moveToPreviousElement, [BentoKeyboardNavigationKeyDownEvent.ARROW_DOWN]: moveToNextElement, [BentoKeyboardNavigationKeyDownEvent.HOME]: moveToFirstElement, [BentoKeyboardNavigationKeyDownEvent.END]: moveToLastElement, }; const listboxOptionListeners = { [BentoListboxEvent.SELECT]: onOptionSelected(BentoListboxEvent.SELECT), [BentoListboxEvent.SPACE]: onOptionSelected(BentoListboxEvent.SPACE), [BentoListboxEvent.TAB]: onOptionSelected(BentoListboxEvent.TAB), [BentoListboxEvent.ENTER]: onOptionSelected(BentoListboxEvent.ENTER), }; expose({ /** * Reference for a single listbox item. * Required for keyboard navigation in dropdown as $children is removed in vue@3 */ listboxItemRef, /** * Method to set the index of the item to be focused on * Used for focus management to be kept in-sync with parent e.g. dropdowns */ setListboxFocusedIndex, /** * Navigates to an item by global index, handling virtual scroll if enabled. * Scrolls the virtual list and focuses the item. */ navigateToItem, /** * Scrolls to an item by global index without changing focus. * Used when the dropdown opens via click to bring the selected option into view. */ scrollToItem, }); return { // Enums BentoListboxEvent, // Values listboxRef, listboxItemRef, selectedItem, slots, ariaAttributes, // Computed hasCategories, // Methods onOptionSelected, // Keyboard navigation listboxListeners, listboxOptionListeners, // Virtual scroll focus management handleVirtualScrollingFocus, }; }, }); </script>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div :id="id" ref="listboxRef" v-bento-keyboard-navigation-directive class="b-listbox" tabindex="-1" v-bind="listboxContainerAttributes" :style="containerProps?.style" data-testid="listbox-container" @scroll="onListboxContainerScroll" > <div v-bind="wrapperProps"> <!-- Loading filtered items loading --> <div v-if="componentLoading" class="b-listbox__loading-filtered-items"> <bento-loading-indicator /> </div> <!-- Empty search message --> <div v-else-if="isSearchResultEmpty" class="b-listbox__empty-search-message"> <bento-empty-state v-if="emptyState" v-bind="limitedEmptyStateProps" /> <bento-typography v-else el="span">{{ noResultsMessage }}</bento-typography> </div> <template v-else> <!-- Multi select --> <template v-if="multiple"> <bento-listbox-multi-select ref="listboxItemRef" :has-more-items="hasMoreItems" v-bind="ariaAttributes" :items="items" :lazy-load-type="lazyLoadType" :static-categories="staticCategories" :selected-values="selectedValue" :searching="searching" :is-option-disabled="isOptionDisabled" v-on="listboxListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-multi-select> </template> <!-- Single select --> <template v-else> <bento-listbox-single-select ref="listboxItemRef" :items="virtualisedItems" :total-item-count="totalItemCount" :scroll-to-index="scrollToIndex" :virtual-scroll-start-index="virtualScrollStartIndex" v-bind="ariaAttributes" :selected-value="selectedValue" :static-categories="staticCategories" :is-option-disabled="isOptionDisabled" v-on="listboxListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select> </template> <!-- Lazy Loading --> <div v-if="shouldDisplayShowMoreButton" class="b-listbox__lazy-load"> <bento-loading-button :state="loadingButtonState" variant="secondary" @click.capture="emitShowMore"> {{ showMoreButtonText }} </bento-loading-button> </div> <div v-else-if="loading" class="b-listbox__lazy-load"> <bento-loading-indicator /> </div> </template> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, type PropType, ref, toRef } from 'vue'; import { type BentoListboxEmptyStateProps, BentoListboxEvent, type BentoListboxIsOptionDisabled, BentoListboxLazyLoadType, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxVirtulisationOptions, } from '@/types/listbox'; import { BentoKeyboardNavigationKeyDownEvent } from '@/types/keyboard-navigation'; import { BentoKeyboardNavigationDirective } from '@/directives'; import { BentoListboxSingleSelect } from './components/listbox-single-select'; import { BentoListboxMultiSelect } from './components/listbox-multi-select'; import { BentoTypography } from '@/components/typography'; import { BentoLoadingIndicator } from '@/components/loading-indicator'; import { BentoLoadingButton, BentoLoadingButtonState } from '@/components/button'; import { BentoEmptyState } from '@/components/empty-state'; import { useI18n } from '@/utils/ts/i18n'; import { debounce } from '@/utils/ts/debounce'; import { useVirtualList } from '@/composables/use-virtual-list'; import type { HTMLAttributes } from 'vue/types/jsx.d.ts'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const DEFAULT_DROPDOWN_ITEM_HEIGHT = 36; /** * Listbox container. * It lists all the available options. * * @example * <bento-listbox * v-slot="{label, value}" * :id="listboxOptionsContainerId" * :aria-label="ariaLabel" * :disabled="disabled" * :multiple="multiple" * :selected="value" * :isOptionDisabled="option => option.value === 2" * :items="[{ * { label: 'Option 1', value: 1 }, * { label: 'Option 2', value: 2 }, * }]" * @select="onOptionSelected" * > * </bento-listbox> */ export default defineComponent({ name: 'bento-listbox', components: { BentoEmptyState, BentoListboxSingleSelect, BentoListboxMultiSelect, BentoTypography, BentoLoadingIndicator, BentoLoadingButton, }, directives: { BentoKeyboardNavigationDirective }, i18n: { messages }, props: { /** * Defines a string value that labels an interactive element. */ ariaLabel: { type: String, default: null }, /** * Empty state props that will be used with the inner empty state component to be displayed when no search results are found. */ emptyState: { type: Object as PropType<BentoListboxEmptyStateProps>, default: undefined, }, /** * Indicates whether there are more items to load */ hasMoreItems: { type: Boolean, default: false }, /** * Identifies the listbox whose contents are controlled by the the combobox on which the aria-controls attribute is set. */ id: { type: String, required: true }, /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - Listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: Function as PropType<BentoListboxIsOptionDisabled>, default: () => undefined, }, /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem } * * @property {string} value.label - Text to be displayed in the option * * @property {string,number} value.value - Value of the option */ items: { type: Array as PropType<BentoListboxOptions>, required: true, }, /** * Indicates if new options are lazy loading. */ loading: { type: Boolean, default: false }, /** * The type of `Lazy Load`. * Type "automatic" will enable infinite scrolling * Type "button" will enable lazy loading with "Show more" button */ lazyLoadType: { type: String as PropType<BentoListboxLazyLoadType | `${BentoListboxLazyLoadType}`>, default: BentoListboxLazyLoadType.NONE, validator: (value: BentoListboxLazyLoadType) => Object.values(BentoListboxLazyLoadType).includes(value), }, /** * Indicates the listbox is loading filtered items. */ componentLoading: { type: Boolean, default: false }, /** * If enabled, the user will be able to select multiple items. */ multiple: { type: Boolean, default: false }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Messaged displayed when no items are listed in the listbox */ noResultsMessage: { type: String, required: true }, /** * Flag that indicates that an external search it's being made * to filter out the items inside the the multi-select listbox * * If enabled, hides the "Select all" checkbox in "multiple" mode. */ searching: BentoListboxMultiSelect.props.searching, /** * The `input` value. * Providing an empty string or empty array will select no options. * Set to an empty string `''` if you don't want any of the available options to be selected for single select */ selectedValue: { type: Array as PropType<BentoListboxOptions>, default: () => [], }, /** * Enables virtual scrolling if set to true or by providing an object with itemHeight function. * The itemHeight function is used to calculate the height of rendered item given it's index. */ virtualScroll: { type: [Boolean, Object] as PropType<BentoListboxVirtulisationOptions>, default: false, }, }, emits: [ BentoListboxEvent.SELECT, BentoListboxEvent.SPACE, BentoListboxEvent.SHOW_MORE, BentoListboxEvent.ENTER, BentoListboxEvent.ESCAPE, BentoListboxEvent.TAB, ], setup(props, { emit, slots }) { const listboxItemRef = ref([]); const items = toRef(props, 'items'); const { t } = useI18n<{ message: MessageSchema }>({ messages }); const isLazyLoadListbox = computed(() => props.lazyLoadType !== BentoListboxLazyLoadType.AUTOMATIC); const hasAutomaticLazyLoader = computed(() => props.lazyLoadType === BentoListboxLazyLoadType.AUTOMATIC); // Virtual scrolling const virtualScrollItemHeight = () => { if (typeof props?.virtualScroll === 'object' && props?.virtualScroll?.itemHeight) { return props.virtualScroll.itemHeight; } return DEFAULT_DROPDOWN_ITEM_HEIGHT; }; const isVirtualScrollEnabled = !props?.multiple && props?.virtualScroll !== false && props?.lazyLoadType === 'none'; const { containerRef: listboxRef, containerProps, onScroll: onContainerScroll, list: virtualisedItems, wrapperProps, scrollToIndex, startIndex: virtualScrollStartIndex, } = useVirtualList<BentoListboxOptionItem>(items, { itemHeight: virtualScrollItemHeight(), // Disable virtual scrolling if not enabled or if lazy loading is enabled or if multi-select disabled: !isVirtualScrollEnabled, }); const totalItemCount = computed(() => (isVirtualScrollEnabled ? items.value.length : 0)); // Aria a11y const ariaAtomic = computed<HTMLAttributes['aria-atomic']>(() => props.componentLoading !== undefined || isLazyLoadListbox.value ? 'true' : undefined ); const ariaBusy = computed<HTMLAttributes['aria-busy']>(() => (isLazyLoadListbox.value && props.loading) || props.componentLoading ? 'true' : 'false' ); const ariaLive = computed<HTMLAttributes['aria-live']>(() => isLazyLoadListbox.value || props.componentLoading !== undefined ? 'polite' : undefined ); const ariaAttributes = computed( () => ({ 'aria-label': props.ariaLabel, 'aria-busy': ariaBusy.value, 'aria-atomic': ariaAtomic.value, 'aria-live': ariaLive.value, }) as HTMLAttributes ); const listboxContainerAttributes = computed( () => (props.componentLoading ? { ...ariaAttributes.value, role: 'alert', } : {}) as HTMLAttributes ); const onOptionSelected = eventName => (selectedItem: BentoListboxOptions) => { emit(eventName, selectedItem); }; const emitShowMore = () => { emit(BentoListboxEvent.SHOW_MORE); }; const emitShowMoreOnScrollEnd = debounce(() => { const container = listboxRef.value; if (!container) { return; } const isAtBottom = Math.round(container.scrollTop) + container.clientHeight >= container.scrollHeight; if (props.hasMoreItems && isAtBottom && !props.loading) { emitShowMore(); } }); const onListboxContainerScroll = () => { if (hasAutomaticLazyLoader.value) { emitShowMoreOnScrollEnd(); } else { onContainerScroll(); } }; const isSearchResultEmpty = computed(() => props.items?.length === 0); const shouldDisplayShowMoreButton = computed( () => props.lazyLoadType === BentoListboxLazyLoadType.BUTTON && props.hasMoreItems ); const loadingButtonState = computed(() => props.loading ? BentoLoadingButtonState.LOADING : BentoLoadingButtonState.START ); const showMoreButtonText = computed(() => (props.loading ? t('loading') : t('showMore'))); const limitedEmptyStateProps = computed<InstanceType<typeof BentoEmptyState>['$props']>(() => ({ ...props.emptyState, variant: 'condensed', })); const listboxListeners = { [BentoListboxEvent.SELECT]: onOptionSelected(BentoListboxEvent.SELECT), [BentoListboxEvent.SPACE]: onOptionSelected(BentoListboxEvent.SPACE), [BentoListboxEvent.TAB]: onOptionSelected(BentoListboxEvent.TAB), [BentoListboxEvent.ENTER]: onOptionSelected(BentoListboxEvent.ENTER), }; return { // Refs listboxRef, listboxItemRef, // a11y ariaAttributes, listboxContainerAttributes, // Values containerProps, isSearchResultEmpty, limitedEmptyStateProps, loadingButtonState, slots, shouldDisplayShowMoreButton, showMoreButtonText, virtualisedItems, wrapperProps, // Virtual scroll totalItemCount, scrollToIndex, virtualScrollStartIndex, // Enums BentoKeyboardNavigationKeyDownEvent, BentoListboxEvent, // Methods onListboxContainerScroll, onOptionSelected, emitShowMore, listboxListeners, }; }, }); </script> <style lang="scss" scoped src="./listbox.scss" />
|
|
1
|
+
<template> <div :id="id" ref="listboxRef" v-bento-keyboard-navigation-directive class="b-listbox" tabindex="-1" v-bind="listboxContainerAttributes" :style="containerProps?.style" data-testid="listbox-container" @scroll="onListboxContainerScroll" > <div v-bind="wrapperProps"> <!-- Loading filtered items loading --> <div v-if="componentLoading" class="b-listbox__loading-filtered-items"> <bento-loading-indicator /> </div> <!-- Empty search message --> <div v-else-if="isSearchResultEmpty" class="b-listbox__empty-search-message"> <bento-empty-state v-if="emptyState" v-bind="limitedEmptyStateProps" /> <bento-typography v-else el="span">{{ noResultsMessage }}</bento-typography> </div> <template v-else> <!-- Multi select --> <template v-if="multiple"> <bento-listbox-multi-select ref="listboxItemRef" :has-more-items="hasMoreItems" v-bind="ariaAttributes" :items="items" :lazy-load-type="lazyLoadType" :static-categories="staticCategories" :selected-values="selectedValue" :searching="searching" :is-option-disabled="isOptionDisabled" v-on="listboxListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-multi-select> </template> <!-- Single select --> <template v-else> <bento-listbox-single-select ref="listboxItemRef" :items="virtualisedItems" :total-item-count="totalItemCount" :scroll-to-index="scrollToIndex" :virtual-scroll-start-index="virtualScrollStartIndex" v-bind="ariaAttributes" :selected-value="selectedValue" :static-categories="staticCategories" :is-option-disabled="isOptionDisabled" v-on="listboxListeners" > <template v-for="(_, innerSlot) of slots" #[innerSlot]="scope"> <slot :name="innerSlot" v-bind="scope" /> </template> </bento-listbox-single-select> </template> <!-- Lazy Loading --> <bento-listbox-lazy-load v-if="lazyLoadType !== 'none'" :has-more-items="hasMoreItems" :loading="loading" :type="lazyLoadType" @show-more="emitShowMore" /> </template> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, type PropType, ref, toRef } from 'vue'; import { type BentoListboxEmptyStateProps, BentoListboxEvent, type BentoListboxIsOptionDisabled, BentoListboxLazyLoadType, type BentoListboxOptionItem, type BentoListboxOptions, type BentoListboxVirtulisationOptions, } from '@/types/listbox'; import { BentoKeyboardNavigationKeyDownEvent } from '@/types/keyboard-navigation'; import { BentoKeyboardNavigationDirective } from '@/directives'; import { BentoListboxSingleSelect } from './components/listbox-single-select'; import { BentoListboxMultiSelect } from './components/listbox-multi-select'; import { BentoTypography } from '@/components/typography'; import { BentoLoadingIndicator } from '@/components/loading-indicator'; import { BentoListboxLazyLoad } from './components/listbox-lazy-load'; import { BentoLoadingButtonState } from '@/components/button'; import { BentoEmptyState } from '@/components/empty-state'; import { debounce } from '@/utils/ts/debounce'; import { useVirtualList } from '@/composables/use-virtual-list'; import type { HTMLAttributes } from 'vue/types/jsx.d.ts'; const DEFAULT_DROPDOWN_ITEM_HEIGHT = 36; /** * Listbox container. * It lists all the available options. * * @example * <bento-listbox * v-slot="{label, value}" * :id="listboxOptionsContainerId" * :aria-label="ariaLabel" * :disabled="disabled" * :multiple="multiple" * :selected="value" * :isOptionDisabled="option => option.value === 2" * :items="[{ * { label: 'Option 1', value: 1 }, * { label: 'Option 2', value: 2 }, * }]" * @select="onOptionSelected" * > * </bento-listbox> */ export default defineComponent({ name: 'bento-listbox', components: { BentoEmptyState, BentoListboxSingleSelect, BentoListboxMultiSelect, BentoTypography, BentoLoadingIndicator, BentoListboxLazyLoad, }, directives: { BentoKeyboardNavigationDirective }, props: { /** * Defines a string value that labels an interactive element. */ ariaLabel: { type: String, default: null }, /** * Empty state props that will be used with the inner empty state component to be displayed when no search results are found. */ emptyState: { type: Object as PropType<BentoListboxEmptyStateProps>, default: undefined, }, /** * Indicates whether there are more items to load */ hasMoreItems: { type: Boolean, default: false }, /** * Identifies the listbox whose contents are controlled by the the combobox on which the aria-controls attribute is set. */ id: { type: String, required: true }, /** * Function that allows the options to be disabled * * @type {BentoListboxIsOptionDisabled} * @param {BentoListboxOptionItem} option - Listbox option object * @param {string} option.label - Option's label text * @param {string|number} option.value - Option's value * @param {unknown} option.data - Option's extra data to be passed to the default slot */ isOptionDisabled: { type: Function as PropType<BentoListboxIsOptionDisabled>, default: () => undefined, }, /** * The option elements to populate the listbox with. * It must be an array of {@see BentoListboxOptionItem } * * @property {string} value.label - Text to be displayed in the option * * @property {string,number} value.value - Value of the option */ items: { type: Array as PropType<BentoListboxOptions>, required: true, }, /** * Indicates if new options are lazy loading. */ loading: { type: Boolean, default: false }, /** * The type of `Lazy Load`. * Type "automatic" will enable infinite scrolling * Type "button" will enable lazy loading with "Show more" button */ lazyLoadType: { type: String as PropType<BentoListboxLazyLoadType | `${BentoListboxLazyLoadType}`>, default: BentoListboxLazyLoadType.NONE, validator: (value: BentoListboxLazyLoadType) => Object.values(BentoListboxLazyLoadType).includes(value), }, /** * Indicates the listbox is loading filtered items. */ componentLoading: { type: Boolean, default: false }, /** * If enabled, the user will be able to select multiple items. */ multiple: { type: Boolean, default: false }, /** * If enabled, dropdown will display non-selectable, static categories */ staticCategories: { type: Boolean, default: false }, /** * Messaged displayed when no items are listed in the listbox */ noResultsMessage: { type: String, required: true }, /** * Flag that indicates that an external search it's being made * to filter out the items inside the the multi-select listbox * * If enabled, hides the "Select all" checkbox in "multiple" mode. */ searching: BentoListboxMultiSelect.props.searching, /** * The `input` value. * Providing an empty string or empty array will select no options. * Set to an empty string `''` if you don't want any of the available options to be selected for single select */ selectedValue: { type: Array as PropType<BentoListboxOptions>, default: () => [], }, /** * Enables virtual scrolling if set to true or by providing an object with itemHeight function. * The itemHeight function is used to calculate the height of rendered item given it's index. */ virtualScroll: { type: [Boolean, Object] as PropType<BentoListboxVirtulisationOptions>, default: false, }, }, emits: [ BentoListboxEvent.SELECT, BentoListboxEvent.SPACE, BentoListboxEvent.SHOW_MORE, BentoListboxEvent.ENTER, BentoListboxEvent.ESCAPE, BentoListboxEvent.TAB, ], setup(props, { emit, slots, expose }) { const listboxItemRef = ref([]); const items = toRef(props, 'items'); const isLazyLoadListbox = computed(() => props.lazyLoadType !== BentoListboxLazyLoadType.AUTOMATIC); const hasAutomaticLazyLoader = computed(() => props.lazyLoadType === BentoListboxLazyLoadType.AUTOMATIC); // Virtual scrolling const virtualScrollItemHeight = () => { if (typeof props?.virtualScroll === 'object' && props?.virtualScroll?.itemHeight) { return props.virtualScroll.itemHeight; } return DEFAULT_DROPDOWN_ITEM_HEIGHT; }; const isVirtualScrollEnabled = !props?.multiple && props?.virtualScroll !== false && props?.lazyLoadType === 'none'; const { containerRef: listboxRef, containerProps, onScroll: onContainerScroll, list: virtualisedItems, wrapperProps, scrollToIndex, startIndex: virtualScrollStartIndex, } = useVirtualList<BentoListboxOptionItem>(items, { itemHeight: virtualScrollItemHeight(), // Disable virtual scrolling if not enabled or if lazy loading is enabled or if multi-select disabled: !isVirtualScrollEnabled, }); const totalItemCount = computed(() => (isVirtualScrollEnabled ? items.value.length : 0)); // Aria a11y const ariaAtomic = computed<HTMLAttributes['aria-atomic']>(() => props.componentLoading !== undefined || isLazyLoadListbox.value ? 'true' : undefined ); const ariaBusy = computed<HTMLAttributes['aria-busy']>(() => (isLazyLoadListbox.value && props.loading) || props.componentLoading ? 'true' : 'false' ); const ariaLive = computed<HTMLAttributes['aria-live']>(() => isLazyLoadListbox.value || props.componentLoading !== undefined ? 'polite' : undefined ); const ariaAttributes = computed( () => ({ 'aria-label': props.ariaLabel, 'aria-busy': ariaBusy.value, 'aria-atomic': ariaAtomic.value, 'aria-live': ariaLive.value, }) as HTMLAttributes ); const listboxContainerAttributes = computed( () => (props.componentLoading ? { ...ariaAttributes.value, role: 'alert', } : {}) as HTMLAttributes ); const onOptionSelected = eventName => (selectedItem: BentoListboxOptions) => { emit(eventName, selectedItem); }; const emitShowMore = () => { emit(BentoListboxEvent.SHOW_MORE); }; const emitShowMoreOnScrollEnd = debounce(() => { const container = listboxRef.value; if (!container) { return; } const isAtBottom = Math.round(container.scrollTop) + container.clientHeight >= container.scrollHeight; if (props.hasMoreItems && isAtBottom && !props.loading) { emitShowMore(); } }); const onListboxContainerScroll = () => { if (hasAutomaticLazyLoader.value) { emitShowMoreOnScrollEnd(); } else { onContainerScroll(); } }; const isSearchResultEmpty = computed(() => props.items?.length === 0); const shouldDisplayShowMoreButton = computed( () => props.lazyLoadType === BentoListboxLazyLoadType.BUTTON && props.hasMoreItems ); const loadingButtonState = computed(() => props.loading ? BentoLoadingButtonState.LOADING : BentoLoadingButtonState.START ); const limitedEmptyStateProps = computed<InstanceType<typeof BentoEmptyState>['$props']>(() => ({ ...props.emptyState, variant: 'condensed', })); const listboxListeners = { [BentoListboxEvent.SELECT]: onOptionSelected(BentoListboxEvent.SELECT), [BentoListboxEvent.SPACE]: onOptionSelected(BentoListboxEvent.SPACE), [BentoListboxEvent.TAB]: onOptionSelected(BentoListboxEvent.TAB), [BentoListboxEvent.ENTER]: onOptionSelected(BentoListboxEvent.ENTER), }; expose({ listboxRef, listboxItemRef }); return { // Refs listboxRef, listboxItemRef, // a11y ariaAttributes, listboxContainerAttributes, // Values containerProps, isSearchResultEmpty, limitedEmptyStateProps, loadingButtonState, slots, shouldDisplayShowMoreButton, virtualisedItems, wrapperProps, // Virtual scroll totalItemCount, scrollToIndex, virtualScrollStartIndex, // Enums BentoKeyboardNavigationKeyDownEvent, BentoListboxEvent, // Methods onListboxContainerScroll, onOptionSelected, emitShowMore, listboxListeners, }; }, }); </script> <style lang="scss" scoped src="./listbox.scss" />
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import type { BentoTableOfContentsItems } from '../../table-of-contents.types'; export interface TableOfContentsListProps { /** * Currently active section fragment href. */ activeSectionHref?: string; /** * Index used for the initial roving focus position. */ initialFocusIndex?: number; /** * Table of contents items to render. */ items: BentoTableOfContentsItems; /** * Vertical offset in pixels applied before scrolling to a section. */ scrollOffset?: number; }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<template> <ol class="b-table-of-contents__toc" @keydown="onKeydownNavigation"> <li v-for="(item, index) in items" :key="index" class="b-table-of-contents__item" :class="getItemClasses(item)"> <a ref="navigationItemRefs" class="b-table-of-contents__item-title" :href="getSectionHref(item.elementRef)" :aria-current="isActiveItem(item) ? 'location' : undefined" :tabindex="isFocusable(index) ? null : -1" @click.prevent="onScrollToSection(item.elementRef)" @keydown.enter.prevent="onScrollToSection(item.elementRef)" > <bento-typography el="span" variant="body" stronger class="b-table-of-contents__item-label">{{ item.title }}</bento-typography> </a> <div v-if="index !== items.length - 1" class="b-table-of-contents__item-separator"></div> </li> </ol> </template> <script setup lang="ts"> import { computed } from 'vue'; import { BentoTypography } from '@/components/typography'; import { useSectionNavigationKeyboard } from '@/composables/use-section-navigation-keyboard'; import { getElementFragmentHref, scrollToSection, type ScrollToSectionTarget } from '@/utils/ts/scroll-to-section'; import { type BentoTableOfContentsItem, TableOfContentsClass } from '../../table-of-contents.types'; import type { TableOfContentsListProps } from './table-of-contents-list.types'; const props = withDefaults(defineProps<TableOfContentsListProps>(), { activeSectionHref: undefined, initialFocusIndex: -1, scrollOffset: undefined, }); const getSectionFragmentHref = (elementRef?: BentoTableOfContentsItem['elementRef']) => getElementFragmentHref(elementRef as ScrollToSectionTarget); const getSectionHref = (elementRef?: BentoTableOfContentsItem['elementRef']) => getSectionFragmentHref(elementRef) ?? '#'; const isActiveItem = (item: BentoTableOfContentsItem) => !!props.activeSectionHref && getSectionFragmentHref(item.elementRef) === props.activeSectionHref; const getItemClasses = (item: BentoTableOfContentsItem) => ({ [`b-table-of-contents__item--${TableOfContentsClass.ACTIVE}`]: isActiveItem(item), [`b-table-of-contents__item--level-${Math.min(Math.max(item.level ?? 1, 1), 4)}`]: true, }); const onScrollToSection = (elementRef: BentoTableOfContentsItem['elementRef']) => scrollToSection(elementRef, { scrollOffset: props.scrollOffset, updateHash: true, warningPrefix: 'bento-table-of-contents', }); const { isFocusable, navigationItemRefs, onKeydownNavigation } = useSectionNavigationKeyboard( computed(() => props.items), { initialIndex: computed(() => props.initialFocusIndex), } ); </script> <style lang="scss" scoped src="./table-of-contents-list.scss" />
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Canvas, Meta, Controls } from '@storybook/blocks';
|
|
2
|
+
import * as TableOfContentsStories from './table-of-contents.stories';
|
|
3
|
+
|
|
4
|
+
<Meta of={TableOfContentsStories} />
|
|
5
|
+
|
|
6
|
+
# Table of Contents
|
|
7
|
+
|
|
8
|
+
The Table of Contents component provides a landmark navigation list for pages with multiple sections. It helps users
|
|
9
|
+
understand the page structure and jump to relevant content.
|
|
10
|
+
|
|
11
|
+
<Canvas of={TableOfContentsStories.Default} />
|
|
12
|
+
|
|
13
|
+
## Use Cases
|
|
14
|
+
|
|
15
|
+
Use Table of Contents when:
|
|
16
|
+
|
|
17
|
+
- a page contains several content sections;
|
|
18
|
+
- users benefit from quick in-page navigation;
|
|
19
|
+
- the content is primarily text-based or document-like.
|
|
20
|
+
|
|
21
|
+
## Props
|
|
22
|
+
|
|
23
|
+
<Controls />
|
|
24
|
+
|
|
25
|
+
## Accessibility
|
|
26
|
+
|
|
27
|
+
Adhering to the [WAI-ARIA 2.2 standard](https://www.w3.org/WAI/WCAG22/Techniques/) we follow the
|
|
28
|
+
[table of contents pattern](https://www.w3.org/WAI/WCAG22/Techniques/general/G64) documentation.
|
|
29
|
+
|
|
30
|
+
- The component renders a named `<nav>` landmark.
|
|
31
|
+
- Section links use native anchor semantics.
|
|
32
|
+
- The active section is exposed with `aria-current="location"`.
|
|
33
|
+
- Linked section targets should have an `id` so the links can expose document fragment URLs.
|
|
34
|
+
- The navigation title defaults to the translated "On this page" label and can be overridden with the `title` prop.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { isVue2 } from 'vue-demi'; import { storybookDocsParameter } from '@/utils/ts/storybook'; import { computed, ref } from 'vue'; import type { Meta, StoryObj } from '@storybook/vue'; import BentoTableOfContents from './table-of-contents.vue'; import TableOfContentsDefaultExample from './__tests__/table-of-contents-default-example.vue?raw'; import BentoTypography from '../typography/typography.vue'; import './table-of-contents.stories.scss?module'; const meta: Meta = { title: 'Table of Contents', component: BentoTableOfContents, }; export default meta; type Story = StoryObj<typeof BentoTableOfContents>; export const Default: Story = { render: (_args, { argTypes }) => ({ components: { BentoTableOfContents, BentoTypography }, props: Object.keys(argTypes), template: ` <div class="b-toc-story"> <div class="b-toc-story__layout"> <div class="b-toc-story__sidebar"> <div class="b-toc-story__sidebar-inner"> <bento-table-of-contents :active-index="args.activeIndex" :items="sections" :scroll-offset="args.scrollOffset" :title="args.title" /> </div> </div> <div class="b-toc-story__content"> <section ref="section1" id="section-1" class="b-toc-story__section b-toc-story__section--medium" > <bento-typography el="h2" variant="title">Section 1</bento-typography> <bento-typography>This is the content for the first section.</bento-typography> </section> <section ref="section2" id="section-2" class="b-toc-story__section" > <bento-typography el="h2" variant="title">Section 2</bento-typography> <bento-typography>This section is shorter.</bento-typography> </section> <section ref="section21" id="section-2-1" class="b-toc-story__section" > <bento-typography el="h2" variant="title">Section 2.1</bento-typography> <bento-typography>This is nested under Section 2.</bento-typography> </section> <section ref="section22" id="section-2-2" class="b-toc-story__section" > <bento-typography el="h2" variant="title">Section 2.2</bento-typography> <bento-typography>This is another level 2 section.</bento-typography> </section> <section ref="section211" id="section-2-1-1" class="b-toc-story__section" > <bento-typography el="h2" variant="title">Section 2.1.1</bento-typography> <bento-typography>This is nested under Section 2.1.</bento-typography> </section> <section ref="section2111" id="section-2-1-1-1" class="b-toc-story__section" > <bento-typography el="h2" variant="title">Section 2.1.1.1</bento-typography> <bento-typography>This is nested under Section 2.1.1.</bento-typography> </section> <section ref="section212" id="section-2-1-2" class="b-toc-story__section" > <bento-typography el="h2" variant="title">Section 2.1.2</bento-typography> <bento-typography>This is another level 3 section.</bento-typography> </section> <section ref="section3" id="section-3" class="b-toc-story__section b-toc-story__section--large" > <bento-typography el="h2" variant="title">Section 3</bento-typography> <bento-typography>This is a tall section to demonstrate scrolling.</bento-typography> </section> </div> </div> </div> `, setup(props) { const args = isVue2 ? props : _args; const section1 = ref(null); const section2 = ref(null); const section21 = ref(null); const section22 = ref(null); const section211 = ref(null); const section2111 = ref(null); const section212 = ref(null); const section3 = ref(null); const sections = computed(() => [ { title: 'Section 1', elementRef: section1, level: 1 }, { title: 'Section 2', elementRef: section2, level: 1 }, { title: 'Section 2.1', elementRef: section21, level: 2 }, { title: 'Section 2.2', elementRef: section22, level: 2 }, { title: 'Section 2.1.1', elementRef: section211, level: 3 }, { title: 'Section 2.1.1.1', elementRef: section2111, level: 4 }, { title: 'Section 2.1.2', elementRef: section212, level: 3 }, { title: 'Section 3', elementRef: section3, level: 1 }, ]); return { args, section1, section2, section21, section22, section211, section2111, section212, section3, sections, }; }, }), args: { scrollOffset: 8, }, parameters: storybookDocsParameter(TableOfContentsDefaultExample), };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { type SectionNavigationItem } from '@/types/section-navigation'; export type BentoTableOfContentsItem = SectionNavigationItem; export type BentoTableOfContentsItems = Array<BentoTableOfContentsItem>; export interface BentoTableOfContentsProps { /** * An array containing all the items in the table of contents. */ items: BentoTableOfContentsItems; /** * The index of the currently active item. Can be used to programmatically set the active item. * @default undefined */ activeIndex?: number; /** * Offset in pixels applied before scrolling to a section. * @default undefined */ scrollOffset?: number; /** * Table of contents title. Defaults to the translated "On this page" label. * @default undefined */ title?: string; } export enum TableOfContentsClass { ACTIVE = 'active', }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<template> <nav class="b-table-of-contents" :aria-labelledby="titleId"> <bento-typography :id="titleId" el="h2" variant="body" stronger class="b-table-of-contents__header">{{ computedTitle }}</bento-typography> <table-of-contents-list :items="items" :active-section-href="activeSectionHref" :initial-focus-index="controlledActiveIndex" :scroll-offset="scrollOffset" /> </nav> </template> <script setup lang="ts"> import { computed } from 'vue'; import { BentoTypography } from '@/components/typography'; import { TableOfContentsList } from './components'; import { generateUid } from '@/core/utils/ts'; import { useScrollSpy } from '@/composables/use-scroll-spy'; import { getElementFragmentHref, type ScrollToSectionTarget } from '@/utils/ts/scroll-to-section'; import { unrefElement } from '@/directives/click-outside/utils'; import { useI18n } from '@/utils/ts/i18n'; import messages from './messages.json'; import type { BentoTableOfContentsItem, BentoTableOfContentsProps } from './table-of-contents.types'; type MessageSchema = (typeof messages)['en-US']; const { t } = useI18n<{ message: MessageSchema }>({ messages }); const props = withDefaults(defineProps<BentoTableOfContentsProps>(), { activeIndex: undefined, scrollOffset: undefined, title: undefined, }); const titleId = generateUid('table-of-contents-title'); const computedTitle = computed(() => props.title ?? t('onThisPage')); const resolvedItems = computed(() => props.items .map((item, originalIndex) => ({ element: unrefElement(item.elementRef), originalIndex, })) .filter((item): item is { element: Element; originalIndex: number } => !!item.element) ); const sectionTargetElements = computed(() => resolvedItems.value.map(item => item.element)); const controlledActiveIndex = computed(() => props.activeIndex ?? -1); const scrollSpyDefaultIndex = computed(() => props.activeIndex === undefined ? -1 : resolvedItems.value.findIndex(({ originalIndex }) => originalIndex === props.activeIndex) ); const getSectionFragmentHref = (elementRef?: BentoTableOfContentsItem['elementRef']) => getElementFragmentHref(elementRef as ScrollToSectionTarget); const { activeIndex: scrollSpyActiveIndex } = useScrollSpy(sectionTargetElements, { default: scrollSpyDefaultIndex, }); const currentActiveIndex = computed(() => { if (props.activeIndex !== undefined) { return props.activeIndex; } return resolvedItems.value[scrollSpyActiveIndex.value]?.originalIndex ?? -1; }); const activeSectionHref = computed(() => getSectionFragmentHref(props.items[currentActiveIndex.value]?.elementRef)); </script> <script lang="ts"> /** * This is a navigational component that serves as a list outlining * the structure and hierarchy of content on a page. It allows users * to find the content in a page more quickly with anchor links in * the content. * * ARIA: https://www.w3.org/TR/dpub-aria-1.1/#doc-toc * * @usage * import { BentoTableOfContents } from '@adyen/bento-vue2'; * * export default { * components: { BentoTableOfContents }, * template: ` * <bento-table-of-contents * :items="[{ title: 'Section text', elementRef: sectionRef }]" * /> * `, * setup() { * const sectionRef = ref(null); * return { * sectionRef, * } * } * } */ export default { name: 'bento-table-of-contents', i18n: { messages }, }; </script> <style lang="scss" scoped src="./table-of-contents.scss" />
|
|
@@ -24,6 +24,13 @@ another message is dismissed.
|
|
|
24
24
|
If user hovers over the stack, if unfolds showing up to last 3 toasts and the rest of the toast stacked (if there are
|
|
25
25
|
more than three).
|
|
26
26
|
|
|
27
|
+
### Toasts triggered by the page when a modal/dialog is open
|
|
28
|
+
|
|
29
|
+
When a modal, dialog or some other page overlay component is open and a toast is triggered by the page in the background
|
|
30
|
+
(for example, if there’s some asynchronous process happening that fails), the toast won’t be displayed until the overlay
|
|
31
|
+
component is closed, following the principle that modal is a focused environment, so anything happening in the
|
|
32
|
+
background should wait until the user is done with their flow. Once the modal is closed, the toast(s) will appear.
|
|
33
|
+
|
|
27
34
|
## Use Cases
|
|
28
35
|
|
|
29
36
|
Due to their temporary nature, use toasts for at-a-glance, non-critical feedback about the app’s processes, i.e. a
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import type { Ref } from 'vue'; type MaybeRef<T> = T | Ref<T>; export type NumericInputEvent = Event | string | { target?: { value?: string } }; export type NumericKeyDownEvent = | KeyboardEvent | { key?: string; target?: { value?: string; selectionStart?: number | null; selectionEnd?: number | null }; preventDefault?: () => void; }; export interface UseNumericInputOptions { value: Ref<number | null>; prettyOutput?: MaybeRef<boolean>; onInput?: (value: number | null) => void; }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import type { Ref } from 'vue'; export interface UseSectionNavigationKeyboardOptions<Item = unknown, Target = unknown> { focusTarget?: (target: Target) => boolean; getFocusableElement?: (target: Target) => HTMLElement | null; initialIndex?: Ref<number | undefined>; isDisabled?: (item: Item) => boolean | undefined; } export interface UseSectionNavigationKeyboardReturn<Target = unknown> { focusedIndex: Ref<number>; isFocusable: (index: number) => boolean; navigationItemRefs: Ref<Array<Target>>; onKeydownNavigation: (e: KeyboardEvent) => void; }
|