@empathyco/x-components 9.3.0 → 9.3.2
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 +14 -0
- package/core/index.js +4 -0
- package/core/index.js.map +1 -1
- package/docs/API-reference/api/x-components.accessibility_key.md +11 -0
- package/docs/API-reference/api/x-components.aicarousel.md +4 -0
- package/docs/API-reference/api/x-components.arialabels.aicarousel.md +14 -0
- package/docs/API-reference/api/x-components.arialabels.basecolumnpickerdropdown.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.basecolumnpickerlist.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.basedropdown.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.baseeventsmodalclose.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.baseeventsmodalopen.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.basemodal.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.clearhistoryqueries.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.editablenumberrangefilter.md +14 -0
- package/docs/API-reference/api/x-components.arialabels.facets.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.filterssearch.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.historyqueriesswitch.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.historyquery.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.md +419 -0
- package/docs/API-reference/api/x-components.arialabels.pageloaderbutton.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.pageselector.md +16 -0
- package/docs/API-reference/api/x-components.arialabels.removehistoryquery.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.scrolltotop.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.searchinput.md +13 -0
- package/docs/API-reference/api/x-components.arialabels.sliderfilter.md +14 -0
- package/docs/API-reference/api/x-components.arialabels.sortdropdown.md +13 -0
- package/docs/API-reference/api/x-components.basecolumnpickerdropdown.md +3 -0
- package/docs/API-reference/api/x-components.basecolumnpickerlist.md +3 -0
- package/docs/API-reference/api/x-components.basedropdown.md +3 -2
- package/docs/API-reference/api/x-components.baseeventsmodalclose.md +3 -0
- package/docs/API-reference/api/x-components.baseeventsmodalopen.md +3 -0
- package/docs/API-reference/api/x-components.basemodal.md +3 -0
- package/docs/API-reference/api/x-components.clearhistoryqueries.md +3 -0
- package/docs/API-reference/api/x-components.deepmergewithdefaults.md +85 -0
- package/docs/API-reference/api/x-components.editablenumberrangefilter.md +4 -2
- package/docs/API-reference/api/x-components.facets.md +3 -0
- package/docs/API-reference/api/x-components.filterssearch.md +3 -0
- package/docs/API-reference/api/x-components.historyqueriesswitch.md +3 -0
- package/docs/API-reference/api/x-components.historyquery.md +3 -0
- package/docs/API-reference/api/x-components.md +50 -0
- package/docs/API-reference/api/x-components.pageloaderbutton.md +3 -0
- package/docs/API-reference/api/x-components.pageselector.md +6 -0
- package/docs/API-reference/api/x-components.removehistoryquery.md +3 -0
- package/docs/API-reference/api/x-components.scrolltotop.md +3 -0
- package/docs/API-reference/api/x-components.searchinput.md +3 -0
- package/docs/API-reference/api/x-components.sliderfilter.md +4 -0
- package/docs/API-reference/api/x-components.sortdropdown.md +3 -0
- package/docs/API-reference/api/x-components.useaccessibilitylabels.md +72 -0
- package/docs/API-reference/components/common/x-components.base-dropdown.md +0 -1
- package/js/components/base-dropdown.vue.js +1 -1
- package/js/components/base-dropdown.vue.js.map +1 -1
- package/js/components/base-dropdown.vue2.js +11 -3
- package/js/components/base-dropdown.vue2.js.map +1 -1
- package/js/components/base-keyboard-navigation.vue2.js +1 -0
- package/js/components/base-keyboard-navigation.vue2.js.map +1 -1
- package/js/components/column-picker/base-column-picker-dropdown.vue.js +2 -2
- package/js/components/column-picker/base-column-picker-dropdown.vue.js.map +1 -1
- package/js/components/column-picker/base-column-picker-dropdown.vue2.js +10 -0
- package/js/components/column-picker/base-column-picker-dropdown.vue2.js.map +1 -1
- package/js/components/column-picker/base-column-picker-list.vue.js +1 -1
- package/js/components/column-picker/base-column-picker-list.vue.js.map +1 -1
- package/js/components/column-picker/base-column-picker-list.vue2.js +10 -1
- package/js/components/column-picker/base-column-picker-list.vue2.js.map +1 -1
- package/js/components/display-click-provider.vue.js +2 -1
- package/js/components/display-click-provider.vue.js.map +1 -1
- package/js/components/highlight.vue2.js +1 -0
- package/js/components/highlight.vue2.js.map +1 -1
- package/js/components/modals/base-events-modal-close.vue.js +2 -2
- package/js/components/modals/base-events-modal-close.vue.js.map +1 -1
- package/js/components/modals/base-events-modal-close.vue2.js +10 -0
- package/js/components/modals/base-events-modal-close.vue2.js.map +1 -1
- package/js/components/modals/base-events-modal-open.vue.js +2 -2
- package/js/components/modals/base-events-modal-open.vue.js.map +1 -1
- package/js/components/modals/base-events-modal-open.vue2.js +10 -0
- package/js/components/modals/base-events-modal-open.vue2.js.map +1 -1
- package/js/components/modals/base-id-modal-close.vue2.js +2 -1
- package/js/components/modals/base-id-modal-close.vue2.js.map +1 -1
- package/js/components/modals/base-id-modal-open.vue2.js +2 -1
- package/js/components/modals/base-id-modal-open.vue2.js.map +1 -1
- package/js/components/modals/base-id-modal.vue2.js +2 -1
- package/js/components/modals/base-id-modal.vue2.js.map +1 -1
- package/js/components/modals/base-modal.vue.js +11 -16
- package/js/components/modals/base-modal.vue.js.map +1 -1
- package/js/components/modals/base-modal.vue2.js +3 -0
- package/js/components/modals/base-modal.vue2.js.map +1 -1
- package/js/components/page-loader-button.vue.js +2 -2
- package/js/components/page-loader-button.vue.js.map +1 -1
- package/js/components/page-loader-button.vue2.js +3 -0
- package/js/components/page-loader-button.vue2.js.map +1 -1
- package/js/components/page-selector.vue.js +12 -12
- package/js/components/page-selector.vue.js.map +1 -1
- package/js/components/page-selector.vue2.js +3 -0
- package/js/components/page-selector.vue2.js.map +1 -1
- package/js/components/panels/base-id-toggle-panel-button.vue2.js +1 -0
- package/js/components/panels/base-id-toggle-panel-button.vue2.js.map +1 -1
- package/js/components/panels/base-id-toggle-panel.vue2.js +2 -1
- package/js/components/panels/base-id-toggle-panel.vue2.js.map +1 -1
- package/js/components/result/base-result-link.vue2.js +2 -1
- package/js/components/result/base-result-link.vue2.js.map +1 -1
- package/js/components/result/base-result-rating.vue2.js +2 -1
- package/js/components/result/base-result-rating.vue2.js.map +1 -1
- package/js/components/sort/sort-dropdown.vue.js +2 -2
- package/js/components/sort/sort-dropdown.vue.js.map +1 -1
- package/js/components/sort/sort-dropdown.vue2.js +10 -0
- package/js/components/sort/sort-dropdown.vue2.js.map +1 -1
- package/js/components/suggestions/base-suggestion.vue2.js +1 -0
- package/js/components/suggestions/base-suggestion.vue2.js.map +1 -1
- package/js/composables/use-accessibility-labels.js +40 -0
- package/js/composables/use-accessibility-labels.js.map +1 -0
- package/js/index.js +4 -0
- package/js/index.js.map +1 -1
- package/js/types/accessibility.js +4 -0
- package/js/types/accessibility.js.map +1 -0
- package/js/utils/accessibility.js +37 -0
- package/js/utils/accessibility.js.map +1 -0
- package/js/utils/deep-merge-with-defaults.js +47 -0
- package/js/utils/deep-merge-with-defaults.js.map +1 -0
- package/js/x-modules/ai/components/ai-carousel.vue.js +1 -1
- package/js/x-modules/ai/components/ai-carousel.vue.js.map +1 -1
- package/js/x-modules/ai/components/ai-carousel.vue2.js +3 -0
- package/js/x-modules/ai/components/ai-carousel.vue2.js.map +1 -1
- package/js/x-modules/ai/components/ai-grouped-carousel.vue2.js +1 -0
- package/js/x-modules/ai/components/ai-grouped-carousel.vue2.js.map +1 -1
- package/js/x-modules/empathize/components/empathize.vue2.js +2 -2
- package/js/x-modules/facets/components/facets/facets-provider.vue2.js +1 -0
- package/js/x-modules/facets/components/facets/facets-provider.vue2.js.map +1 -1
- package/js/x-modules/facets/components/facets/facets.vue.js +57 -51
- package/js/x-modules/facets/components/facets/facets.vue.js.map +1 -1
- package/js/x-modules/facets/components/facets/facets.vue2.js +9 -0
- package/js/x-modules/facets/components/facets/facets.vue2.js.map +1 -1
- package/js/x-modules/facets/components/filters/editable-number-range-filter.vue.js +2 -2
- package/js/x-modules/facets/components/filters/editable-number-range-filter.vue.js.map +1 -1
- package/js/x-modules/facets/components/filters/editable-number-range-filter.vue2.js +3 -4
- package/js/x-modules/facets/components/filters/editable-number-range-filter.vue2.js.map +1 -1
- package/js/x-modules/facets/components/filters/slider-filter.vue.js +4 -4
- package/js/x-modules/facets/components/filters/slider-filter.vue.js.map +1 -1
- package/js/x-modules/facets/components/filters/slider-filter.vue2.js +3 -0
- package/js/x-modules/facets/components/filters/slider-filter.vue2.js.map +1 -1
- package/js/x-modules/facets/components/lists/filters-search.vue.js +2 -2
- package/js/x-modules/facets/components/lists/filters-search.vue.js.map +1 -1
- package/js/x-modules/facets/components/lists/filters-search.vue2.js +10 -0
- package/js/x-modules/facets/components/lists/filters-search.vue2.js.map +1 -1
- package/js/x-modules/facets/components/lists/sorted-filters.vue.js +1 -0
- package/js/x-modules/facets/components/lists/sorted-filters.vue.js.map +1 -1
- package/js/x-modules/history-queries/components/clear-history-queries.vue.js +2 -2
- package/js/x-modules/history-queries/components/clear-history-queries.vue.js.map +1 -1
- package/js/x-modules/history-queries/components/clear-history-queries.vue2.js +10 -0
- package/js/x-modules/history-queries/components/clear-history-queries.vue2.js.map +1 -1
- package/js/x-modules/history-queries/components/history-queries-switch.vue.js +2 -2
- package/js/x-modules/history-queries/components/history-queries-switch.vue.js.map +1 -1
- package/js/x-modules/history-queries/components/history-queries-switch.vue2.js +10 -0
- package/js/x-modules/history-queries/components/history-queries-switch.vue2.js.map +1 -1
- package/js/x-modules/history-queries/components/history-query.vue.js +2 -1
- package/js/x-modules/history-queries/components/history-query.vue.js.map +1 -1
- package/js/x-modules/history-queries/components/history-query.vue2.js +10 -0
- package/js/x-modules/history-queries/components/history-query.vue2.js.map +1 -1
- package/js/x-modules/history-queries/components/remove-history-query.vue.js +2 -2
- package/js/x-modules/history-queries/components/remove-history-query.vue.js.map +1 -1
- package/js/x-modules/history-queries/components/remove-history-query.vue2.js +10 -0
- package/js/x-modules/history-queries/components/remove-history-query.vue2.js.map +1 -1
- package/js/x-modules/queries-preview/components/query-preview-list.vue2.js +1 -0
- package/js/x-modules/queries-preview/components/query-preview-list.vue2.js.map +1 -1
- package/js/x-modules/queries-preview/components/query-preview.vue2.js +2 -2
- package/js/x-modules/query-suggestions/components/query-suggestion.vue2.js +1 -0
- package/js/x-modules/query-suggestions/components/query-suggestion.vue2.js.map +1 -1
- package/js/x-modules/query-suggestions/components/query-suggestions.vue2.js +1 -0
- package/js/x-modules/query-suggestions/components/query-suggestions.vue2.js.map +1 -1
- package/js/x-modules/recommendations/components/recommendations.vue2.js +1 -0
- package/js/x-modules/recommendations/components/recommendations.vue2.js.map +1 -1
- package/js/x-modules/related-prompts/components/related-prompts-tag-list.vue2.js +2 -1
- package/js/x-modules/related-prompts/components/related-prompts-tag-list.vue2.js.map +1 -1
- package/js/x-modules/scroll/components/scroll-to-top.vue.js +2 -2
- package/js/x-modules/scroll/components/scroll-to-top.vue.js.map +1 -1
- package/js/x-modules/scroll/components/scroll-to-top.vue2.js +3 -0
- package/js/x-modules/scroll/components/scroll-to-top.vue2.js.map +1 -1
- package/js/x-modules/search/wiring.js +1 -0
- package/js/x-modules/search/wiring.js.map +1 -1
- package/js/x-modules/search-box/components/search-input.vue.js +2 -2
- package/js/x-modules/search-box/components/search-input.vue.js.map +1 -1
- package/js/x-modules/search-box/components/search-input.vue2.js +11 -1
- package/js/x-modules/search-box/components/search-input.vue2.js.map +1 -1
- package/js/x-modules/semantic-queries/components/semantic-queries.vue2.js +1 -0
- package/js/x-modules/semantic-queries/components/semantic-queries.vue2.js.map +1 -1
- package/package.json +2 -2
- package/report/x-components.api.json +1148 -210
- package/report/x-components.api.md +176 -11
- package/types/src/components/base-dropdown.vue.d.ts +3 -4
- package/types/src/components/base-dropdown.vue.d.ts.map +1 -1
- package/types/src/components/column-picker/base-column-picker-dropdown.vue.d.ts +3 -0
- package/types/src/components/column-picker/base-column-picker-dropdown.vue.d.ts.map +1 -1
- package/types/src/components/column-picker/base-column-picker-list.vue.d.ts +3 -0
- package/types/src/components/column-picker/base-column-picker-list.vue.d.ts.map +1 -1
- package/types/src/components/modals/base-events-modal-close.vue.d.ts +3 -0
- package/types/src/components/modals/base-events-modal-close.vue.d.ts.map +1 -1
- package/types/src/components/modals/base-events-modal-open.vue.d.ts +3 -0
- package/types/src/components/modals/base-events-modal-open.vue.d.ts.map +1 -1
- package/types/src/components/modals/base-modal.vue.d.ts +3 -0
- package/types/src/components/modals/base-modal.vue.d.ts.map +1 -1
- package/types/src/components/page-loader-button.vue.d.ts +3 -0
- package/types/src/components/page-loader-button.vue.d.ts.map +1 -1
- package/types/src/components/page-selector.vue.d.ts +6 -0
- package/types/src/components/page-selector.vue.d.ts.map +1 -1
- package/types/src/components/sort/sort-dropdown.vue.d.ts +3 -0
- package/types/src/components/sort/sort-dropdown.vue.d.ts.map +1 -1
- package/types/src/composables/index.d.ts +1 -0
- package/types/src/composables/index.d.ts.map +1 -1
- package/types/src/composables/use-accessibility-labels.d.ts +31 -0
- package/types/src/composables/use-accessibility-labels.d.ts.map +1 -0
- package/types/src/types/accessibility.d.ts +79 -0
- package/types/src/types/accessibility.d.ts.map +1 -0
- package/types/src/types/index.d.ts +1 -0
- package/types/src/types/index.d.ts.map +1 -1
- package/types/src/utils/accessibility.d.ts +10 -0
- package/types/src/utils/accessibility.d.ts.map +1 -0
- package/types/src/utils/deep-merge-with-defaults.d.ts +28 -0
- package/types/src/utils/deep-merge-with-defaults.d.ts.map +1 -0
- package/types/src/utils/index.d.ts +2 -0
- package/types/src/utils/index.d.ts.map +1 -1
- package/types/src/x-modules/ai/components/ai-carousel.vue.d.ts +4 -0
- package/types/src/x-modules/ai/components/ai-carousel.vue.d.ts.map +1 -1
- package/types/src/x-modules/facets/components/facets/facets.vue.d.ts +3 -0
- package/types/src/x-modules/facets/components/facets/facets.vue.d.ts.map +1 -1
- package/types/src/x-modules/facets/components/filters/editable-number-range-filter.vue.d.ts +4 -2
- package/types/src/x-modules/facets/components/filters/editable-number-range-filter.vue.d.ts.map +1 -1
- package/types/src/x-modules/facets/components/filters/slider-filter.vue.d.ts +4 -0
- package/types/src/x-modules/facets/components/filters/slider-filter.vue.d.ts.map +1 -1
- package/types/src/x-modules/facets/components/lists/filters-search.vue.d.ts +3 -0
- package/types/src/x-modules/facets/components/lists/filters-search.vue.d.ts.map +1 -1
- package/types/src/x-modules/history-queries/components/clear-history-queries.vue.d.ts +3 -0
- package/types/src/x-modules/history-queries/components/clear-history-queries.vue.d.ts.map +1 -1
- package/types/src/x-modules/history-queries/components/history-queries-switch.vue.d.ts +3 -0
- package/types/src/x-modules/history-queries/components/history-queries-switch.vue.d.ts.map +1 -1
- package/types/src/x-modules/history-queries/components/history-query.vue.d.ts +3 -0
- package/types/src/x-modules/history-queries/components/history-query.vue.d.ts.map +1 -1
- package/types/src/x-modules/history-queries/components/remove-history-query.vue.d.ts +3 -0
- package/types/src/x-modules/history-queries/components/remove-history-query.vue.d.ts.map +1 -1
- package/types/src/x-modules/scroll/components/scroll-to-top.vue.d.ts +3 -0
- package/types/src/x-modules/scroll/components/scroll-to-top.vue.d.ts.map +1 -1
- package/types/src/x-modules/search-box/components/search-input.vue.d.ts +3 -0
- package/types/src/x-modules/search-box/components/search-input.vue.d.ts.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-dropdown.vue.js","sources":["../../../src/components/base-dropdown.vue"],"sourcesContent":["<template>\n <div\n ref=\"rootRef\"\n :class=\"dropdownCSSClasses\"\n class=\"x-dropdown\"\n @keydown=\"updateSearchBuffer\"\n @keydown.down.prevent=\"highlightNextItem\"\n @keydown.up.prevent=\"highlightPreviousItem\"\n >\n <button\n ref=\"toggleButtonRef\"\n class=\"x-dropdown__toggle\"\n data-test=\"dropdown-toggle\"\n role=\"combobox\"\n aria-haspopup=\"listbox\"\n :aria-expanded=\"isOpen\"\n :aria-controls=\"listId\"\n :aria-label=\"ariaLabel\"\n aria-autocomplete=\"none\"\n @click=\"toggle\"\n @keydown.up.down.prevent.stop=\"open\"\n >\n <!--\n @slot Used to render the contents of the dropdown toggle button. If not provided, it uses\n the item slot as fallback.\n @binding {string|number|Identifiable} item - The item data to render.\n @binding {boolean} isOpen - True if the dropdown is opened, and false if it is closed.\n -->\n <slot v-if=\"hasToggleSlot\" :is-open=\"isOpen\" :item=\"modelValue\" name=\"toggle\">\n {{ modelValue }}\n </slot>\n <slot v-else :item=\"modelValue\" name=\"item\">{{ modelValue }}</slot>\n </button>\n\n <component :is=\"animation\">\n <ul\n v-show=\"isOpen\"\n :id=\"listId\"\n class=\"x-dropdown__items-list\"\n data-test=\"dropdown-list\"\n role=\"listbox\"\n tabindex=\"-1\"\n @keydown.end=\"highlightLastItem\"\n @keydown.esc=\"closeAndFocusToggleButton\"\n @keydown.home=\"highlightFirstItem\"\n >\n <li\n v-for=\"(item, index) in items\"\n :key=\"(item as Identifiable).id ?? item\"\n class=\"x-dropdown__list-item\"\n >\n <button\n :ref=\"el => (itemsButtonRefs[index] = el as HTMLButtonElement | null)\"\n :aria-selected=\"item === modelValue\"\n :class=\"itemsCSSClasses[index]\"\n class=\"x-dropdown__item\"\n data-test=\"dropdown-item\"\n role=\"option\"\n @click=\"emitSelectedItemChanged(item)\"\n >\n <!--\n @slot (required) Used to render each one of the items content, and as fallback\n for the toggle button content slot if it is not provided.\n @binding {string|number|Identifiable} item - Item to render\n @binding {boolean} isHighlighted - True when the item has the focus.\n @binding {boolean} isSelected - True when the item is selected.\n -->\n <slot\n :is-highlighted=\"index === highlightedItemIndex\"\n :is-selected=\"item === modelValue\"\n :item=\"item\"\n name=\"item\"\n >\n {{ item }}\n </slot>\n </button>\n </li>\n </ul>\n </component>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { Identifiable } from '@empathyco/x-types'\nimport type { PropType } from 'vue'\nimport { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { AnimationProp } from '../types'\nimport { debounceFunction, getTargetElement, normalizeString } from '../utils'\nimport { NoAnimation } from './animations'\n\ntype DropdownItem = string | number | Identifiable\nlet dropdownCount = 0\n\n/**\n * Dropdown component that mimics a Select element behavior, but with the option\n * to customize the toggle button and each item contents.\n */\nexport default defineComponent({\n name: 'BaseDropdown',\n props: {\n /** List of items to display.*/\n items: {\n type: Array as PropType<DropdownItem[]>,\n required: true,\n },\n /** The selected item. */\n modelValue: {\n type: null as unknown as PropType<DropdownItem | null>,\n validator: (v: any) =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'object' || v === null,\n required: true,\n },\n /** Description of what the dropdown is used for. */\n ariaLabel: String,\n /**\n * Animation component to use for expanding the dropdown. This is a single element animation,\n * so only `<transition>` components are allowed.\n */\n animation: {\n type: AnimationProp,\n default: () => NoAnimation,\n },\n /** Time to wait without receiving any keystroke before resetting the items search query. */\n searchTimeoutMs: {\n type: Number,\n default: 1000,\n },\n },\n emits: ['update:modelValue'],\n setup(props, { emit, slots }) {\n const rootRef = ref<HTMLElement>()\n /** The button that opens and closes the list of options. */\n const toggleButtonRef = ref<HTMLButtonElement>()\n /** Array containing the dropdown list buttons HTMLElements. */\n const itemsButtonRefs = ref<(HTMLButtonElement | null)[]>([])\n\n /** Property to check whether the dropdown is expanded or closed. */\n const isOpen = ref(false)\n /** Index of the element that has the focus in the list. -1 means no element has focus. */\n const highlightedItemIndex = ref(-1)\n /** String to search for the first element that starts with it. */\n const searchBuffer = ref('')\n\n /** Resets the search buffer after a certain time has passed. */\n let restartResetSearchTimeout: () => void\n /* Unique ID to identify the dropdown. */\n const listId = `x-dropdown-${dropdownCount++}`\n\n /**\n * Dynamic CSS classes to add to the dropdown root element.\n *\n * @returns An object containing the CSS classes to add to the dropdown root element.\n */\n const dropdownCSSClasses = computed(() => ({ 'x-dropdown--is-open': isOpen }))\n\n /**\n * Dynamic CSS classes to add to each one of the items.\n *\n * @returns An object containing the CSS classes to add to each item.\n */\n const itemsCSSClasses = computed(() =>\n props.items.map((item, index) => ({\n 'x-dropdown__item--is-selected': props.modelValue === item,\n 'x-dropdown__item--is-highlighted': highlightedItemIndex.value === index,\n })),\n )\n\n /* Opens the dropdown. */\n const open = () => (isOpen.value = true)\n /* Closes the dropdown. */\n const close = () => (isOpen.value = false)\n /* Toggles the dropdown. */\n const toggle = () => (isOpen.value = !isOpen.value)\n\n /**\n * Closes the modal and focuses the toggle button.\n */\n function closeAndFocusToggleButton() {\n close()\n toggleButtonRef.value?.focus()\n }\n\n /**\n * Emits the event that the selected item has changed.\n *\n * @param item - The new selected item.\n */\n function emitSelectedItemChanged(item: DropdownItem) {\n emit('update:modelValue', item)\n closeAndFocusToggleButton()\n }\n\n /**\n * Highlights the item after the one that is currently highlighted.\n */\n function highlightNextItem() {\n open()\n highlightedItemIndex.value = (highlightedItemIndex.value + 1) % props.items.length\n }\n\n /**\n * Highlights the item before the one that is currently highlighted.\n */\n function highlightPreviousItem() {\n const currentIndex = highlightedItemIndex.value\n open()\n highlightedItemIndex.value = currentIndex > 0 ? currentIndex - 1 : props.items.length - 1\n }\n\n /**\n * Highlights the first of the provided items.\n */\n function highlightFirstItem() {\n highlightedItemIndex.value = 0\n }\n\n /**\n * Highlights the last of the provided items.\n */\n function highlightLastItem() {\n highlightedItemIndex.value = props.items.length - 1\n }\n\n /**\n * Updates the variable that is used to search in the filters.\n *\n * @param event - The event coming from the user typing.\n */\n function updateSearchBuffer(event: KeyboardEvent) {\n if (/^\\w$/.test(event.key)) {\n const key = event.key\n searchBuffer.value += key\n restartResetSearchTimeout()\n }\n }\n\n /**\n * Resets the search buffer.\n */\n function resetSearchBuffer() {\n searchBuffer.value = ''\n }\n\n /**\n * Closes the dropdown if the passed event has happened on an element out of the dropdown.\n *\n * @param event - The event to check if it has happened out of the dropdown component.\n */\n function closeIfEventIsOutOfDropdown(event: MouseEvent | TouchEvent | FocusEvent) {\n if (!rootRef.value?.contains(getTargetElement(event))) {\n close()\n }\n }\n\n /**\n * Adds listeners to the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function addDocumentCloseListeners() {\n document.addEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.addEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.addEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Removes the listeners of the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function removeDocumentCloseListeners() {\n document.removeEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.removeEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.removeEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Highlights the item that matches the search buffer. To do so it checks the list buttons\n * text content. It highlights items following this priority:\n * - If an element is already highlighted, it starts searching from that element.\n * - If no element is found starting from the previously highlighted, it returns the first one.\n * - If no element is found matching the search query it highlights the first element.\n *\n * @param search - The search string to find in the HTML.\n */\n watch(searchBuffer, search => {\n if (search) {\n const normalizedSearch = normalizeString(search)\n const matchingIndices = itemsButtonRefs?.value?.reduce<number[]>(\n (matchingIndices, button, index) => {\n if (button) {\n const safeButtonWordCharacters = button.textContent!.replace(/\\W/g, '')\n const normalizedButtonText = normalizeString(safeButtonWordCharacters)\n if (normalizedButtonText.startsWith(normalizedSearch)) {\n matchingIndices.push(index)\n }\n }\n return matchingIndices\n },\n [],\n )\n highlightedItemIndex.value =\n // First matching item starting to search from the current highlighted element\n matchingIndices?.find(index => index >= highlightedItemIndex.value) ??\n // First matching item\n matchingIndices?.[0] ??\n // First item\n 0\n }\n })\n\n /**\n * Updates the debounced function to reset the search.\n *\n * @param searchTimeoutMs - The new milliseconds that have to pass without typing before\n * resetting the search.\n */\n watch(\n () => props.searchTimeoutMs,\n searchTimeoutMs => {\n restartResetSearchTimeout = debounceFunction(resetSearchBuffer, searchTimeoutMs)\n },\n { immediate: true },\n )\n\n /**\n * Focuses the DOM element which matches the `highlightedItemIndex`.\n *\n * @param highlightedItemIndex - The index of the HTML element to focus.\n */\n watch(\n highlightedItemIndex,\n highlightedItemIndex => {\n nextTick(() => itemsButtonRefs.value[highlightedItemIndex]?.focus())\n },\n { immediate: true },\n )\n\n /**\n * When the dropdown is open it sets the focused element to the one that is selected.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n highlightedItemIndex.value = isOpen\n ? props.modelValue === null\n ? 0\n : props.items.indexOf(props.modelValue)\n : -1\n })\n\n /**\n * Adds and removes listeners to close the dropdown when it loses the focus.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n /*\n * Because there is an issue with Firefox in macOS and Safari that doesn't focus the target\n * element of the `mousedown` events, the `focusout` event `relatedTarget` property can't be\n * used to detect whether the user has blurred the dropdown. The hack here is to use\n * document listeners that have the side effect of losing the focus.\n */\n if (isOpen) {\n addDocumentCloseListeners()\n } else {\n removeDocumentCloseListeners()\n }\n })\n\n /**\n * If the dropdown is destroyed before removing the document listeners, it ensures that they\n * are removed too.\n */\n onBeforeUnmount(() => {\n removeDocumentCloseListeners()\n })\n\n return {\n hasToggleSlot: !!slots.toggle,\n closeAndFocusToggleButton,\n dropdownCSSClasses,\n emitSelectedItemChanged,\n highlightFirstItem,\n highlightLastItem,\n highlightNextItem,\n highlightPreviousItem,\n highlightedItemIndex,\n isOpen,\n itemsButtonRefs,\n itemsCSSClasses,\n listId,\n open,\n rootRef,\n toggle,\n toggleButtonRef,\n updateSearchBuffer,\n }\n },\n})\n</script>\n\n<style lang=\"css\" scoped>\n.x-dropdown {\n position: relative;\n}\n\n.x-dropdown__items-list {\n z-index: 1;\n list-style: none;\n position: absolute;\n padding: 0;\n margin: 0;\n top: calc(100% + var(--x-size-gap-dropdown-default, 0));\n}\n</style>\n\n<docs lang=\"mdx\">\n## Example\n\nThe `Dropdown` component is a simple yet customizable select component. The component needs to work\nwith the list of items available to select, which are passed using the `items` prop, and the selected\nitem, which is passed in using the `value` prop.\n\nThe supported items must be an array that can contain unique strings, unique numbers, or objects\nwith a unique `id` property.\n\nThe content of each item can be customized using the `item` slot, which apart from the data of the\nitem, it also receives via prop if the element is selected or highlighted.\n\nThe `toggle` slot can be used to customize the button that opens the dropdown. If this is not\nprovided, the `item` slot will be used for that.\n\n```vue\n<template>\n <BaseDropdown v-model=\"value\" :items=\"items\">\n <template #toggle=\"{ item, isOpen }\">{{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseDropdown>\n</template>\n\n<script setup>\nimport { BaseDropdown } from '@empathyco/x-components'\nimport { ref } from 'vue'\nconst items = ['a', 2, { id: '3' }]\nconst value = ref('a')\n</script>\n```\n</docs>\n"],"names":["_openBlock","_createElementBlock","_normalizeClass","_withKeys","_withModifiers","_createElementVNode","_renderSlot","_createTextVNode","_createBlock","_resolveDynamicComponent","_withCtx","_withDirectives","_Fragment","_renderList"],"mappings":";;;;;;;;;AACE,EAAA,OAAAA,SAAA,EAAA,EAAAC,kBAAA;AAAA,IA8EM,KAAA;AAAA,IAAA;AAAA,MA7EJ,GAAA,EAAI,SAAA;AAAA,MACH,KAAA,EAAKC,cAAA,CAAA,CAAE,IAAA,CAAA,kBAAA,EACF,YAAY,CAAA,CAAA;AAAA,MACjB,SAAA,EAAO;AAAA,QAAA,MAAA,CAAA,CAAA,CAAA,KAAA,MAAA,CAAA,CAAA,CAAA,GAAA,CAAA,GAAA,IAAA,KAAE,IAAA,CAAA,kBAAA,IAAA,IAAA,CAAA,kBAAA,CAAA,GAAA,IAAA,CAAA,CAAA;AAAA,QAAA,MAAA,CAAA,CAAA,CAAA,KAAA,MAAA,CAAA,CAAA,CAAA,GAAAC,QAAA,CAAAC,aAAA,CAAA,CAAA,GAAA,IAAA,KACa,IAAA,CAAA,iBAAA,IAAA,IAAA,CAAA,iBAAA,CAAA,GAAA,IAAA,CAAA,EAAiB,CAAA,SAAA,CAAA,CAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;AAAA,QAAA,MAAA,CAAA,CAAA,CAA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src/components/base-dropdown.vue"],"sourcesContent":["<template>\n <div\n ref=\"rootRef\"\n :class=\"dropdownCSSClasses\"\n class=\"x-dropdown\"\n @keydown=\"updateSearchBuffer\"\n @keydown.down.prevent=\"highlightNextItem\"\n @keydown.up.prevent=\"highlightPreviousItem\"\n >\n <button\n ref=\"toggleButtonRef\"\n class=\"x-dropdown__toggle\"\n data-test=\"dropdown-toggle\"\n role=\"combobox\"\n aria-haspopup=\"listbox\"\n :aria-expanded=\"isOpen\"\n :aria-controls=\"listId\"\n :aria-label=\"ariaLabels?.toggleButton\"\n aria-autocomplete=\"none\"\n @click=\"toggle\"\n @keydown.up.down.prevent.stop=\"open\"\n >\n <!--\n @slot Used to render the contents of the dropdown toggle button. If not provided, it uses\n the item slot as fallback.\n @binding {string|number|Identifiable} item - The item data to render.\n @binding {boolean} isOpen - True if the dropdown is opened, and false if it is closed.\n -->\n <slot v-if=\"hasToggleSlot\" :is-open=\"isOpen\" :item=\"modelValue\" name=\"toggle\">\n {{ modelValue }}\n </slot>\n <slot v-else :item=\"modelValue\" name=\"item\">{{ modelValue }}</slot>\n </button>\n\n <component :is=\"animation\">\n <ul\n v-show=\"isOpen\"\n :id=\"listId\"\n class=\"x-dropdown__items-list\"\n data-test=\"dropdown-list\"\n role=\"listbox\"\n tabindex=\"-1\"\n @keydown.end=\"highlightLastItem\"\n @keydown.esc=\"closeAndFocusToggleButton\"\n @keydown.home=\"highlightFirstItem\"\n >\n <li\n v-for=\"(item, index) in items\"\n :key=\"(item as Identifiable).id ?? item\"\n class=\"x-dropdown__list-item\"\n >\n <button\n :ref=\"el => (itemsButtonRefs[index] = el as HTMLButtonElement | null)\"\n :aria-selected=\"item === modelValue\"\n :class=\"itemsCSSClasses[index]\"\n class=\"x-dropdown__item\"\n data-test=\"dropdown-item\"\n role=\"option\"\n @click=\"emitSelectedItemChanged(item)\"\n >\n <!--\n @slot (required) Used to render each one of the items content, and as fallback\n for the toggle button content slot if it is not provided.\n @binding {string|number|Identifiable} item - Item to render\n @binding {boolean} isHighlighted - True when the item has the focus.\n @binding {boolean} isSelected - True when the item is selected.\n -->\n <slot\n :is-highlighted=\"index === highlightedItemIndex\"\n :is-selected=\"item === modelValue\"\n :item=\"item\"\n name=\"item\"\n >\n {{ item }}\n </slot>\n </button>\n </li>\n </ul>\n </component>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { Identifiable } from '@empathyco/x-types'\nimport type { PropType } from 'vue'\nimport { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { useAccessibilityLabels } from '../composables'\nimport { AnimationProp } from '../types'\nimport { debounceFunction, getTargetElement, normalizeString } from '../utils'\nimport { NoAnimation } from './animations'\n\ntype DropdownItem = string | number | Identifiable\nlet dropdownCount = 0\n\n/**\n * Dropdown component that mimics a Select element behavior, but with the option\n * to customize the toggle button and each item contents.\n */\nexport default defineComponent({\n name: 'BaseDropdown',\n props: {\n /** List of items to display.*/\n items: {\n type: Array as PropType<DropdownItem[]>,\n required: true,\n },\n /** The selected item. */\n modelValue: {\n type: null as unknown as PropType<DropdownItem | null>,\n validator: (v: any) =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'object' || v === null,\n required: true,\n },\n /**\n * Animation component to use for expanding the dropdown. This is a single element animation,\n * so only `<transition>` components are allowed.\n */\n animation: {\n type: AnimationProp,\n default: () => NoAnimation,\n },\n /** Time to wait without receiving any keystroke before resetting the items search query. */\n searchTimeoutMs: {\n type: Number,\n default: 1000,\n },\n },\n emits: ['update:modelValue'],\n setup(props, { emit, slots }) {\n const rootRef = ref<HTMLElement>()\n /** The button that opens and closes the list of options. */\n const toggleButtonRef = ref<HTMLButtonElement>()\n /** Array containing the dropdown list buttons HTMLElements. */\n const itemsButtonRefs = ref<(HTMLButtonElement | null)[]>([])\n\n /** Property to check whether the dropdown is expanded or closed. */\n const isOpen = ref(false)\n /** Index of the element that has the focus in the list. -1 means no element has focus. */\n const highlightedItemIndex = ref(-1)\n /** String to search for the first element that starts with it. */\n const searchBuffer = ref('')\n\n /** Resets the search buffer after a certain time has passed. */\n let restartResetSearchTimeout: () => void\n /* Unique ID to identify the dropdown. */\n const listId = `x-dropdown-${dropdownCount++}`\n\n const ariaLabels = useAccessibilityLabels('baseDropdown')\n\n /**\n * Dynamic CSS classes to add to the dropdown root element.\n *\n * @returns An object containing the CSS classes to add to the dropdown root element.\n */\n const dropdownCSSClasses = computed(() => ({ 'x-dropdown--is-open': isOpen }))\n\n /**\n * Dynamic CSS classes to add to each one of the items.\n *\n * @returns An object containing the CSS classes to add to each item.\n */\n const itemsCSSClasses = computed(() =>\n props.items.map((item, index) => ({\n 'x-dropdown__item--is-selected': props.modelValue === item,\n 'x-dropdown__item--is-highlighted': highlightedItemIndex.value === index,\n })),\n )\n\n /* Opens the dropdown. */\n const open = () => (isOpen.value = true)\n /* Closes the dropdown. */\n const close = () => (isOpen.value = false)\n /* Toggles the dropdown. */\n const toggle = () => (isOpen.value = !isOpen.value)\n\n /**\n * Closes the modal and focuses the toggle button.\n */\n function closeAndFocusToggleButton() {\n close()\n toggleButtonRef.value?.focus()\n }\n\n /**\n * Emits the event that the selected item has changed.\n *\n * @param item - The new selected item.\n */\n function emitSelectedItemChanged(item: DropdownItem) {\n emit('update:modelValue', item)\n closeAndFocusToggleButton()\n }\n\n /**\n * Highlights the item after the one that is currently highlighted.\n */\n function highlightNextItem() {\n open()\n highlightedItemIndex.value = (highlightedItemIndex.value + 1) % props.items.length\n }\n\n /**\n * Highlights the item before the one that is currently highlighted.\n */\n function highlightPreviousItem() {\n const currentIndex = highlightedItemIndex.value\n open()\n highlightedItemIndex.value = currentIndex > 0 ? currentIndex - 1 : props.items.length - 1\n }\n\n /**\n * Highlights the first of the provided items.\n */\n function highlightFirstItem() {\n highlightedItemIndex.value = 0\n }\n\n /**\n * Highlights the last of the provided items.\n */\n function highlightLastItem() {\n highlightedItemIndex.value = props.items.length - 1\n }\n\n /**\n * Updates the variable that is used to search in the filters.\n *\n * @param event - The event coming from the user typing.\n */\n function updateSearchBuffer(event: KeyboardEvent) {\n if (/^\\w$/.test(event.key)) {\n const key = event.key\n searchBuffer.value += key\n restartResetSearchTimeout()\n }\n }\n\n /**\n * Resets the search buffer.\n */\n function resetSearchBuffer() {\n searchBuffer.value = ''\n }\n\n /**\n * Closes the dropdown if the passed event has happened on an element out of the dropdown.\n *\n * @param event - The event to check if it has happened out of the dropdown component.\n */\n function closeIfEventIsOutOfDropdown(event: MouseEvent | TouchEvent | FocusEvent) {\n if (!rootRef.value?.contains(getTargetElement(event))) {\n close()\n }\n }\n\n /**\n * Adds listeners to the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function addDocumentCloseListeners() {\n document.addEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.addEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.addEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Removes the listeners of the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function removeDocumentCloseListeners() {\n document.removeEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.removeEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.removeEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Highlights the item that matches the search buffer. To do so it checks the list buttons\n * text content. It highlights items following this priority:\n * - If an element is already highlighted, it starts searching from that element.\n * - If no element is found starting from the previously highlighted, it returns the first one.\n * - If no element is found matching the search query it highlights the first element.\n *\n * @param search - The search string to find in the HTML.\n */\n watch(searchBuffer, search => {\n if (search) {\n const normalizedSearch = normalizeString(search)\n const matchingIndices = itemsButtonRefs?.value?.reduce<number[]>(\n (matchingIndices, button, index) => {\n if (button) {\n const safeButtonWordCharacters = button.textContent!.replace(/\\W/g, '')\n const normalizedButtonText = normalizeString(safeButtonWordCharacters)\n if (normalizedButtonText.startsWith(normalizedSearch)) {\n matchingIndices.push(index)\n }\n }\n return matchingIndices\n },\n [],\n )\n highlightedItemIndex.value =\n // First matching item starting to search from the current highlighted element\n matchingIndices?.find(index => index >= highlightedItemIndex.value) ??\n // First matching item\n matchingIndices?.[0] ??\n // First item\n 0\n }\n })\n\n /**\n * Updates the debounced function to reset the search.\n *\n * @param searchTimeoutMs - The new milliseconds that have to pass without typing before\n * resetting the search.\n */\n watch(\n () => props.searchTimeoutMs,\n searchTimeoutMs => {\n restartResetSearchTimeout = debounceFunction(resetSearchBuffer, searchTimeoutMs)\n },\n { immediate: true },\n )\n\n /**\n * Focuses the DOM element which matches the `highlightedItemIndex`.\n *\n * @param highlightedItemIndex - The index of the HTML element to focus.\n */\n watch(\n highlightedItemIndex,\n highlightedItemIndex => {\n nextTick(() => itemsButtonRefs.value[highlightedItemIndex]?.focus())\n },\n { immediate: true },\n )\n\n /**\n * When the dropdown is open it sets the focused element to the one that is selected.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n highlightedItemIndex.value = isOpen\n ? props.modelValue === null\n ? 0\n : props.items.indexOf(props.modelValue)\n : -1\n })\n\n /**\n * Adds and removes listeners to close the dropdown when it loses the focus.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n /*\n * Because there is an issue with Firefox in macOS and Safari that doesn't focus the target\n * element of the `mousedown` events, the `focusout` event `relatedTarget` property can't be\n * used to detect whether the user has blurred the dropdown. The hack here is to use\n * document listeners that have the side effect of losing the focus.\n */\n if (isOpen) {\n addDocumentCloseListeners()\n } else {\n removeDocumentCloseListeners()\n }\n })\n\n /**\n * If the dropdown is destroyed before removing the document listeners, it ensures that they\n * are removed too.\n */\n onBeforeUnmount(() => {\n removeDocumentCloseListeners()\n })\n\n return {\n ariaLabels,\n hasToggleSlot: !!slots.toggle,\n closeAndFocusToggleButton,\n dropdownCSSClasses,\n emitSelectedItemChanged,\n highlightFirstItem,\n highlightLastItem,\n highlightNextItem,\n highlightPreviousItem,\n highlightedItemIndex,\n isOpen,\n itemsButtonRefs,\n itemsCSSClasses,\n listId,\n open,\n rootRef,\n toggle,\n toggleButtonRef,\n updateSearchBuffer,\n }\n },\n})\n</script>\n\n<style lang=\"css\" scoped>\n.x-dropdown {\n position: relative;\n}\n\n.x-dropdown__items-list {\n z-index: 1;\n list-style: none;\n position: absolute;\n padding: 0;\n margin: 0;\n top: calc(100% + var(--x-size-gap-dropdown-default, 0));\n}\n</style>\n\n<docs lang=\"mdx\">\n## Example\n\nThe `Dropdown` component is a simple yet customizable select component. The component needs to work\nwith the list of items available to select, which are passed using the `items` prop, and the selected\nitem, which is passed in using the `value` prop.\n\nThe supported items must be an array that can contain unique strings, unique numbers, or objects\nwith a unique `id` property.\n\nThe content of each item can be customized using the `item` slot, which apart from the data of the\nitem, it also receives via prop if the element is selected or highlighted.\n\nThe `toggle` slot can be used to customize the button that opens the dropdown. If this is not\nprovided, the `item` slot will be used for that.\n\n```vue\n<template>\n <BaseDropdown v-model=\"value\" :items=\"items\">\n <template #toggle=\"{ item, isOpen }\">{{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseDropdown>\n</template>\n\n<script setup>\nimport { BaseDropdown } from '@empathyco/x-components'\nimport { ref } from 'vue'\nconst items = ['a', 2, { id: '3' }]\nconst value = ref('a')\n</script>\n```\n</docs>\n"],"names":["_openBlock","_createElementBlock","_normalizeClass","_withKeys","_withModifiers","_createElementVNode","_renderSlot","_createTextVNode","_createBlock","_resolveDynamicComponent","_withCtx","_withDirectives","_Fragment","_renderList"],"mappings":";;;;;;;;;AACE,EAAA,OAAAA,SAAA,EAAA,EAAAC,kBAAA;AAAA,IA8EM,KAAA;AAAA,IAAA;AAAA,MA7EJ,GAAA,EAAI,SAAA;AAAA,MACH,KAAA,EAAKC,cAAA,CAAA,CAAE,IAAA,CAAA,kBAAA,EACF,YAAY,CAAA,CAAA;AAAA,MACjB,SAAA,EAAO;AAAA,QAAA,MA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AAE,IAAA,CAAA,uBAAA,CAAwB,IAAI;AAAA,mBAAA,EAAA;oBASpCI,UAAA,CAOO,IAAA,CAAA,MAAA,EAAA,MAAA,EAAA;AAAA,sBANJ,eAAgB,KAAA,KAAU,IAAA,CAAA,oBAAA;AAAA,sBAC1B,YAAa,IAAA,KAAS,IAAA,CAAA,UAAA;AAAA,sBACtB;AAAA,qBAAA,EAHH,MAOO;AAAA,sBAAAC,eAAA;wCADF,IAAI,CAAA;AAAA,wBAAA;AAAA;AAAA;AAAA,qBAAA,EAAA,IAAA;;;;;;;;oBArCL,IAAA,CAAA,MAAM;AAAA,WAAA;;;;;;;;;;;;;;"}
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { defineComponent, ref, computed, watch, nextTick, onBeforeUnmount } from 'vue';
|
|
2
|
-
import
|
|
2
|
+
import '../composables/create-use-device.js';
|
|
3
|
+
import 'vuex';
|
|
4
|
+
import '../plugins/x-bus.js';
|
|
5
|
+
import '@empathyco/x-utils';
|
|
6
|
+
import '../plugins/x-plugin.js';
|
|
7
|
+
import 'rxjs';
|
|
8
|
+
import { useAccessibilityLabels } from '../composables/use-accessibility-labels.js';
|
|
3
9
|
import { debounce } from '../utils/debounce.js';
|
|
10
|
+
import '@vueuse/core';
|
|
11
|
+
import { AnimationProp } from '../types/animation-prop.js';
|
|
4
12
|
import { getTargetElement } from '../utils/html.js';
|
|
5
13
|
import { normalizeString } from '../utils/normalize.js';
|
|
6
14
|
import '../utils/storage.js';
|
|
@@ -44,8 +52,6 @@ var _sfc_main = defineComponent({
|
|
|
44
52
|
validator: (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'object' || v === null,
|
|
45
53
|
required: true,
|
|
46
54
|
},
|
|
47
|
-
/** Description of what the dropdown is used for. */
|
|
48
|
-
ariaLabel: String,
|
|
49
55
|
/**
|
|
50
56
|
* Animation component to use for expanding the dropdown. This is a single element animation,
|
|
51
57
|
* so only `<transition>` components are allowed.
|
|
@@ -77,6 +83,7 @@ var _sfc_main = defineComponent({
|
|
|
77
83
|
let restartResetSearchTimeout;
|
|
78
84
|
/* Unique ID to identify the dropdown. */
|
|
79
85
|
const listId = `x-dropdown-${dropdownCount++}`;
|
|
86
|
+
const ariaLabels = useAccessibilityLabels('baseDropdown');
|
|
80
87
|
/**
|
|
81
88
|
* Dynamic CSS classes to add to the dropdown root element.
|
|
82
89
|
*
|
|
@@ -274,6 +281,7 @@ var _sfc_main = defineComponent({
|
|
|
274
281
|
removeDocumentCloseListeners();
|
|
275
282
|
});
|
|
276
283
|
return {
|
|
284
|
+
ariaLabels,
|
|
277
285
|
hasToggleSlot: !!slots.toggle,
|
|
278
286
|
closeAndFocusToggleButton,
|
|
279
287
|
dropdownCSSClasses,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-dropdown.vue2.js","sources":["../../../src/components/base-dropdown.vue"],"sourcesContent":["<template>\n <div\n ref=\"rootRef\"\n :class=\"dropdownCSSClasses\"\n class=\"x-dropdown\"\n @keydown=\"updateSearchBuffer\"\n @keydown.down.prevent=\"highlightNextItem\"\n @keydown.up.prevent=\"highlightPreviousItem\"\n >\n <button\n ref=\"toggleButtonRef\"\n class=\"x-dropdown__toggle\"\n data-test=\"dropdown-toggle\"\n role=\"combobox\"\n aria-haspopup=\"listbox\"\n :aria-expanded=\"isOpen\"\n :aria-controls=\"listId\"\n :aria-label=\"ariaLabel\"\n aria-autocomplete=\"none\"\n @click=\"toggle\"\n @keydown.up.down.prevent.stop=\"open\"\n >\n <!--\n @slot Used to render the contents of the dropdown toggle button. If not provided, it uses\n the item slot as fallback.\n @binding {string|number|Identifiable} item - The item data to render.\n @binding {boolean} isOpen - True if the dropdown is opened, and false if it is closed.\n -->\n <slot v-if=\"hasToggleSlot\" :is-open=\"isOpen\" :item=\"modelValue\" name=\"toggle\">\n {{ modelValue }}\n </slot>\n <slot v-else :item=\"modelValue\" name=\"item\">{{ modelValue }}</slot>\n </button>\n\n <component :is=\"animation\">\n <ul\n v-show=\"isOpen\"\n :id=\"listId\"\n class=\"x-dropdown__items-list\"\n data-test=\"dropdown-list\"\n role=\"listbox\"\n tabindex=\"-1\"\n @keydown.end=\"highlightLastItem\"\n @keydown.esc=\"closeAndFocusToggleButton\"\n @keydown.home=\"highlightFirstItem\"\n >\n <li\n v-for=\"(item, index) in items\"\n :key=\"(item as Identifiable).id ?? item\"\n class=\"x-dropdown__list-item\"\n >\n <button\n :ref=\"el => (itemsButtonRefs[index] = el as HTMLButtonElement | null)\"\n :aria-selected=\"item === modelValue\"\n :class=\"itemsCSSClasses[index]\"\n class=\"x-dropdown__item\"\n data-test=\"dropdown-item\"\n role=\"option\"\n @click=\"emitSelectedItemChanged(item)\"\n >\n <!--\n @slot (required) Used to render each one of the items content, and as fallback\n for the toggle button content slot if it is not provided.\n @binding {string|number|Identifiable} item - Item to render\n @binding {boolean} isHighlighted - True when the item has the focus.\n @binding {boolean} isSelected - True when the item is selected.\n -->\n <slot\n :is-highlighted=\"index === highlightedItemIndex\"\n :is-selected=\"item === modelValue\"\n :item=\"item\"\n name=\"item\"\n >\n {{ item }}\n </slot>\n </button>\n </li>\n </ul>\n </component>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { Identifiable } from '@empathyco/x-types'\nimport type { PropType } from 'vue'\nimport { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { AnimationProp } from '../types'\nimport { debounceFunction, getTargetElement, normalizeString } from '../utils'\nimport { NoAnimation } from './animations'\n\ntype DropdownItem = string | number | Identifiable\nlet dropdownCount = 0\n\n/**\n * Dropdown component that mimics a Select element behavior, but with the option\n * to customize the toggle button and each item contents.\n */\nexport default defineComponent({\n name: 'BaseDropdown',\n props: {\n /** List of items to display.*/\n items: {\n type: Array as PropType<DropdownItem[]>,\n required: true,\n },\n /** The selected item. */\n modelValue: {\n type: null as unknown as PropType<DropdownItem | null>,\n validator: (v: any) =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'object' || v === null,\n required: true,\n },\n /** Description of what the dropdown is used for. */\n ariaLabel: String,\n /**\n * Animation component to use for expanding the dropdown. This is a single element animation,\n * so only `<transition>` components are allowed.\n */\n animation: {\n type: AnimationProp,\n default: () => NoAnimation,\n },\n /** Time to wait without receiving any keystroke before resetting the items search query. */\n searchTimeoutMs: {\n type: Number,\n default: 1000,\n },\n },\n emits: ['update:modelValue'],\n setup(props, { emit, slots }) {\n const rootRef = ref<HTMLElement>()\n /** The button that opens and closes the list of options. */\n const toggleButtonRef = ref<HTMLButtonElement>()\n /** Array containing the dropdown list buttons HTMLElements. */\n const itemsButtonRefs = ref<(HTMLButtonElement | null)[]>([])\n\n /** Property to check whether the dropdown is expanded or closed. */\n const isOpen = ref(false)\n /** Index of the element that has the focus in the list. -1 means no element has focus. */\n const highlightedItemIndex = ref(-1)\n /** String to search for the first element that starts with it. */\n const searchBuffer = ref('')\n\n /** Resets the search buffer after a certain time has passed. */\n let restartResetSearchTimeout: () => void\n /* Unique ID to identify the dropdown. */\n const listId = `x-dropdown-${dropdownCount++}`\n\n /**\n * Dynamic CSS classes to add to the dropdown root element.\n *\n * @returns An object containing the CSS classes to add to the dropdown root element.\n */\n const dropdownCSSClasses = computed(() => ({ 'x-dropdown--is-open': isOpen }))\n\n /**\n * Dynamic CSS classes to add to each one of the items.\n *\n * @returns An object containing the CSS classes to add to each item.\n */\n const itemsCSSClasses = computed(() =>\n props.items.map((item, index) => ({\n 'x-dropdown__item--is-selected': props.modelValue === item,\n 'x-dropdown__item--is-highlighted': highlightedItemIndex.value === index,\n })),\n )\n\n /* Opens the dropdown. */\n const open = () => (isOpen.value = true)\n /* Closes the dropdown. */\n const close = () => (isOpen.value = false)\n /* Toggles the dropdown. */\n const toggle = () => (isOpen.value = !isOpen.value)\n\n /**\n * Closes the modal and focuses the toggle button.\n */\n function closeAndFocusToggleButton() {\n close()\n toggleButtonRef.value?.focus()\n }\n\n /**\n * Emits the event that the selected item has changed.\n *\n * @param item - The new selected item.\n */\n function emitSelectedItemChanged(item: DropdownItem) {\n emit('update:modelValue', item)\n closeAndFocusToggleButton()\n }\n\n /**\n * Highlights the item after the one that is currently highlighted.\n */\n function highlightNextItem() {\n open()\n highlightedItemIndex.value = (highlightedItemIndex.value + 1) % props.items.length\n }\n\n /**\n * Highlights the item before the one that is currently highlighted.\n */\n function highlightPreviousItem() {\n const currentIndex = highlightedItemIndex.value\n open()\n highlightedItemIndex.value = currentIndex > 0 ? currentIndex - 1 : props.items.length - 1\n }\n\n /**\n * Highlights the first of the provided items.\n */\n function highlightFirstItem() {\n highlightedItemIndex.value = 0\n }\n\n /**\n * Highlights the last of the provided items.\n */\n function highlightLastItem() {\n highlightedItemIndex.value = props.items.length - 1\n }\n\n /**\n * Updates the variable that is used to search in the filters.\n *\n * @param event - The event coming from the user typing.\n */\n function updateSearchBuffer(event: KeyboardEvent) {\n if (/^\\w$/.test(event.key)) {\n const key = event.key\n searchBuffer.value += key\n restartResetSearchTimeout()\n }\n }\n\n /**\n * Resets the search buffer.\n */\n function resetSearchBuffer() {\n searchBuffer.value = ''\n }\n\n /**\n * Closes the dropdown if the passed event has happened on an element out of the dropdown.\n *\n * @param event - The event to check if it has happened out of the dropdown component.\n */\n function closeIfEventIsOutOfDropdown(event: MouseEvent | TouchEvent | FocusEvent) {\n if (!rootRef.value?.contains(getTargetElement(event))) {\n close()\n }\n }\n\n /**\n * Adds listeners to the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function addDocumentCloseListeners() {\n document.addEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.addEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.addEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Removes the listeners of the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function removeDocumentCloseListeners() {\n document.removeEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.removeEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.removeEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Highlights the item that matches the search buffer. To do so it checks the list buttons\n * text content. It highlights items following this priority:\n * - If an element is already highlighted, it starts searching from that element.\n * - If no element is found starting from the previously highlighted, it returns the first one.\n * - If no element is found matching the search query it highlights the first element.\n *\n * @param search - The search string to find in the HTML.\n */\n watch(searchBuffer, search => {\n if (search) {\n const normalizedSearch = normalizeString(search)\n const matchingIndices = itemsButtonRefs?.value?.reduce<number[]>(\n (matchingIndices, button, index) => {\n if (button) {\n const safeButtonWordCharacters = button.textContent!.replace(/\\W/g, '')\n const normalizedButtonText = normalizeString(safeButtonWordCharacters)\n if (normalizedButtonText.startsWith(normalizedSearch)) {\n matchingIndices.push(index)\n }\n }\n return matchingIndices\n },\n [],\n )\n highlightedItemIndex.value =\n // First matching item starting to search from the current highlighted element\n matchingIndices?.find(index => index >= highlightedItemIndex.value) ??\n // First matching item\n matchingIndices?.[0] ??\n // First item\n 0\n }\n })\n\n /**\n * Updates the debounced function to reset the search.\n *\n * @param searchTimeoutMs - The new milliseconds that have to pass without typing before\n * resetting the search.\n */\n watch(\n () => props.searchTimeoutMs,\n searchTimeoutMs => {\n restartResetSearchTimeout = debounceFunction(resetSearchBuffer, searchTimeoutMs)\n },\n { immediate: true },\n )\n\n /**\n * Focuses the DOM element which matches the `highlightedItemIndex`.\n *\n * @param highlightedItemIndex - The index of the HTML element to focus.\n */\n watch(\n highlightedItemIndex,\n highlightedItemIndex => {\n nextTick(() => itemsButtonRefs.value[highlightedItemIndex]?.focus())\n },\n { immediate: true },\n )\n\n /**\n * When the dropdown is open it sets the focused element to the one that is selected.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n highlightedItemIndex.value = isOpen\n ? props.modelValue === null\n ? 0\n : props.items.indexOf(props.modelValue)\n : -1\n })\n\n /**\n * Adds and removes listeners to close the dropdown when it loses the focus.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n /*\n * Because there is an issue with Firefox in macOS and Safari that doesn't focus the target\n * element of the `mousedown` events, the `focusout` event `relatedTarget` property can't be\n * used to detect whether the user has blurred the dropdown. The hack here is to use\n * document listeners that have the side effect of losing the focus.\n */\n if (isOpen) {\n addDocumentCloseListeners()\n } else {\n removeDocumentCloseListeners()\n }\n })\n\n /**\n * If the dropdown is destroyed before removing the document listeners, it ensures that they\n * are removed too.\n */\n onBeforeUnmount(() => {\n removeDocumentCloseListeners()\n })\n\n return {\n hasToggleSlot: !!slots.toggle,\n closeAndFocusToggleButton,\n dropdownCSSClasses,\n emitSelectedItemChanged,\n highlightFirstItem,\n highlightLastItem,\n highlightNextItem,\n highlightPreviousItem,\n highlightedItemIndex,\n isOpen,\n itemsButtonRefs,\n itemsCSSClasses,\n listId,\n open,\n rootRef,\n toggle,\n toggleButtonRef,\n updateSearchBuffer,\n }\n },\n})\n</script>\n\n<style lang=\"css\" scoped>\n.x-dropdown {\n position: relative;\n}\n\n.x-dropdown__items-list {\n z-index: 1;\n list-style: none;\n position: absolute;\n padding: 0;\n margin: 0;\n top: calc(100% + var(--x-size-gap-dropdown-default, 0));\n}\n</style>\n\n<docs lang=\"mdx\">\n## Example\n\nThe `Dropdown` component is a simple yet customizable select component. The component needs to work\nwith the list of items available to select, which are passed using the `items` prop, and the selected\nitem, which is passed in using the `value` prop.\n\nThe supported items must be an array that can contain unique strings, unique numbers, or objects\nwith a unique `id` property.\n\nThe content of each item can be customized using the `item` slot, which apart from the data of the\nitem, it also receives via prop if the element is selected or highlighted.\n\nThe `toggle` slot can be used to customize the button that opens the dropdown. If this is not\nprovided, the `item` slot will be used for that.\n\n```vue\n<template>\n <BaseDropdown v-model=\"value\" :items=\"items\">\n <template #toggle=\"{ item, isOpen }\">{{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseDropdown>\n</template>\n\n<script setup>\nimport { BaseDropdown } from '@empathyco/x-components'\nimport { ref } from 'vue'\nconst items = ['a', 2, { id: '3' }]\nconst value = ref('a')\n</script>\n```\n</docs>\n"],"names":["NoAnimation","debounceFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,IAAI,gBAAgB,CAAA;AAEpB;;;AAGE;AACF,gBAAe,eAAe,CAAC;AAC7B,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,KAAK,EAAE;;AAEL,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,KAAiC;AACvC,YAAA,QAAQ,EAAE,IAAI;AACf,SAAA;;AAED,QAAA,UAAU,EAAE;AACV,YAAA,IAAI,EAAE,IAAgD;YACtD,SAAS,EAAE,CAAC,CAAM,KAChB,OAAO,CAAA,KAAM,QAAO,IAAK,OAAO,CAAA,KAAM,QAAO,IAAK,OAAO,CAAA,KAAM,YAAY,CAAA,KAAM,IAAI;AACvF,YAAA,QAAQ,EAAE,IAAI;AACf,SAAA;;AAED,QAAA,SAAS,EAAE,MAAM;AACjB;;;AAGE;AACF,QAAA,SAAS,EAAE;AACT,YAAA,IAAI,EAAE,aAAa;AACnB,YAAA,OAAO,EAAE,MAAMA,WAAW;AAC3B,SAAA;;AAED,QAAA,eAAe,EAAE;AACf,YAAA,IAAI,EAAE,MAAM;AACZ,YAAA,OAAO,EAAE,IAAI;AACd,SAAA;AACF,KAAA;IACD,KAAK,EAAE,CAAC,mBAAmB,CAAC;AAC5B,IAAA,KAAK,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,KAAI,EAAG,EAAA;AAC1B,QAAA,MAAM,OAAM,GAAI,GAAG,EAAc;;AAEjC,QAAA,MAAM,kBAAkB,GAAG,EAAoB;;AAE/C,QAAA,MAAM,eAAc,GAAI,GAAG,CAA+B,EAAE,CAAA;;AAG5D,QAAA,MAAM,SAAS,GAAG,CAAC,KAAK,CAAA;;AAExB,QAAA,MAAM,oBAAmB,GAAI,GAAG,CAAC,EAAE,CAAA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AM,CACrB;AAEA;;;;AAIE;AACF,QAAA,KAAK,CACH,oBAAoB,EACpB,oBAAmB,IAAG;AACpB,YAAA,QAAQ,CAAC,MAAM,eAAe,CAAC,KAAK,CAAC,oBAAoB,CAAC,EAAE,KAAK,EAAE,CAAA;AACrE,QAAA,CAAC,EACD,EAAE,SAAS,EAAE,MAAM,CACrB;AAEA;;;;AAIE;AACF,QAAA,KAAK,CAAC,MAAM,EAAE,MAAK,IAAG;YACpB,oBAAoB,CAAC,KAAI,GAAI;AAC3B,kBAAE,KAAK,CAAC,UAAS,KAAM;AACrB,sBAAE;sBACA,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU;kBACtC,EAAC;AACP,QAAA,CAAC,CAAA;AAED;;;;AAIE;AACF,QAAA,KAAK,CAAC,MAAM,EAAE,MAAK,IAAG;AACpB;;;;;AAKE;YACF,IAAI,MAAM,EAAE;AACV,gBAAA,yBAAyB,EAAC;YAC5B;iBAAO;AACL,gBAAA,4BAA4B,EAAC;YAC/B;AACF,QAAA,CAAC,CAAA;AAED;;;AAGE;QACF,eAAe,CAAC,MAAI;AAClB,YAAA,4BAA4B,EAAC;AAC/B,QAAA,CAAC,CAAA;QAED,OAAO;AACL,YAAA,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM;YAC7B,yBAAyB;YACzB,kBAAkB;YAClB,uBAAuB;YACvB,kBAAkB;YAClB,iBAAiB;YACjB,iBAAiB;YACjB,qBAAqB;YACrB,oBAAoB;YACpB,MAAM;YACN,eAAe;YACf,eAAe;YACf,MAAM;YACN,IAAI;YACJ,OAAO;YACP,MAAM;YACN,eAAe;YACf,kBAAkB;SACpB;IACF,CAAC;AACF,CAAA,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"base-dropdown.vue2.js","sources":["../../../src/components/base-dropdown.vue"],"sourcesContent":["<template>\n <div\n ref=\"rootRef\"\n :class=\"dropdownCSSClasses\"\n class=\"x-dropdown\"\n @keydown=\"updateSearchBuffer\"\n @keydown.down.prevent=\"highlightNextItem\"\n @keydown.up.prevent=\"highlightPreviousItem\"\n >\n <button\n ref=\"toggleButtonRef\"\n class=\"x-dropdown__toggle\"\n data-test=\"dropdown-toggle\"\n role=\"combobox\"\n aria-haspopup=\"listbox\"\n :aria-expanded=\"isOpen\"\n :aria-controls=\"listId\"\n :aria-label=\"ariaLabels?.toggleButton\"\n aria-autocomplete=\"none\"\n @click=\"toggle\"\n @keydown.up.down.prevent.stop=\"open\"\n >\n <!--\n @slot Used to render the contents of the dropdown toggle button. If not provided, it uses\n the item slot as fallback.\n @binding {string|number|Identifiable} item - The item data to render.\n @binding {boolean} isOpen - True if the dropdown is opened, and false if it is closed.\n -->\n <slot v-if=\"hasToggleSlot\" :is-open=\"isOpen\" :item=\"modelValue\" name=\"toggle\">\n {{ modelValue }}\n </slot>\n <slot v-else :item=\"modelValue\" name=\"item\">{{ modelValue }}</slot>\n </button>\n\n <component :is=\"animation\">\n <ul\n v-show=\"isOpen\"\n :id=\"listId\"\n class=\"x-dropdown__items-list\"\n data-test=\"dropdown-list\"\n role=\"listbox\"\n tabindex=\"-1\"\n @keydown.end=\"highlightLastItem\"\n @keydown.esc=\"closeAndFocusToggleButton\"\n @keydown.home=\"highlightFirstItem\"\n >\n <li\n v-for=\"(item, index) in items\"\n :key=\"(item as Identifiable).id ?? item\"\n class=\"x-dropdown__list-item\"\n >\n <button\n :ref=\"el => (itemsButtonRefs[index] = el as HTMLButtonElement | null)\"\n :aria-selected=\"item === modelValue\"\n :class=\"itemsCSSClasses[index]\"\n class=\"x-dropdown__item\"\n data-test=\"dropdown-item\"\n role=\"option\"\n @click=\"emitSelectedItemChanged(item)\"\n >\n <!--\n @slot (required) Used to render each one of the items content, and as fallback\n for the toggle button content slot if it is not provided.\n @binding {string|number|Identifiable} item - Item to render\n @binding {boolean} isHighlighted - True when the item has the focus.\n @binding {boolean} isSelected - True when the item is selected.\n -->\n <slot\n :is-highlighted=\"index === highlightedItemIndex\"\n :is-selected=\"item === modelValue\"\n :item=\"item\"\n name=\"item\"\n >\n {{ item }}\n </slot>\n </button>\n </li>\n </ul>\n </component>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { Identifiable } from '@empathyco/x-types'\nimport type { PropType } from 'vue'\nimport { computed, defineComponent, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { useAccessibilityLabels } from '../composables'\nimport { AnimationProp } from '../types'\nimport { debounceFunction, getTargetElement, normalizeString } from '../utils'\nimport { NoAnimation } from './animations'\n\ntype DropdownItem = string | number | Identifiable\nlet dropdownCount = 0\n\n/**\n * Dropdown component that mimics a Select element behavior, but with the option\n * to customize the toggle button and each item contents.\n */\nexport default defineComponent({\n name: 'BaseDropdown',\n props: {\n /** List of items to display.*/\n items: {\n type: Array as PropType<DropdownItem[]>,\n required: true,\n },\n /** The selected item. */\n modelValue: {\n type: null as unknown as PropType<DropdownItem | null>,\n validator: (v: any) =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'object' || v === null,\n required: true,\n },\n /**\n * Animation component to use for expanding the dropdown. This is a single element animation,\n * so only `<transition>` components are allowed.\n */\n animation: {\n type: AnimationProp,\n default: () => NoAnimation,\n },\n /** Time to wait without receiving any keystroke before resetting the items search query. */\n searchTimeoutMs: {\n type: Number,\n default: 1000,\n },\n },\n emits: ['update:modelValue'],\n setup(props, { emit, slots }) {\n const rootRef = ref<HTMLElement>()\n /** The button that opens and closes the list of options. */\n const toggleButtonRef = ref<HTMLButtonElement>()\n /** Array containing the dropdown list buttons HTMLElements. */\n const itemsButtonRefs = ref<(HTMLButtonElement | null)[]>([])\n\n /** Property to check whether the dropdown is expanded or closed. */\n const isOpen = ref(false)\n /** Index of the element that has the focus in the list. -1 means no element has focus. */\n const highlightedItemIndex = ref(-1)\n /** String to search for the first element that starts with it. */\n const searchBuffer = ref('')\n\n /** Resets the search buffer after a certain time has passed. */\n let restartResetSearchTimeout: () => void\n /* Unique ID to identify the dropdown. */\n const listId = `x-dropdown-${dropdownCount++}`\n\n const ariaLabels = useAccessibilityLabels('baseDropdown')\n\n /**\n * Dynamic CSS classes to add to the dropdown root element.\n *\n * @returns An object containing the CSS classes to add to the dropdown root element.\n */\n const dropdownCSSClasses = computed(() => ({ 'x-dropdown--is-open': isOpen }))\n\n /**\n * Dynamic CSS classes to add to each one of the items.\n *\n * @returns An object containing the CSS classes to add to each item.\n */\n const itemsCSSClasses = computed(() =>\n props.items.map((item, index) => ({\n 'x-dropdown__item--is-selected': props.modelValue === item,\n 'x-dropdown__item--is-highlighted': highlightedItemIndex.value === index,\n })),\n )\n\n /* Opens the dropdown. */\n const open = () => (isOpen.value = true)\n /* Closes the dropdown. */\n const close = () => (isOpen.value = false)\n /* Toggles the dropdown. */\n const toggle = () => (isOpen.value = !isOpen.value)\n\n /**\n * Closes the modal and focuses the toggle button.\n */\n function closeAndFocusToggleButton() {\n close()\n toggleButtonRef.value?.focus()\n }\n\n /**\n * Emits the event that the selected item has changed.\n *\n * @param item - The new selected item.\n */\n function emitSelectedItemChanged(item: DropdownItem) {\n emit('update:modelValue', item)\n closeAndFocusToggleButton()\n }\n\n /**\n * Highlights the item after the one that is currently highlighted.\n */\n function highlightNextItem() {\n open()\n highlightedItemIndex.value = (highlightedItemIndex.value + 1) % props.items.length\n }\n\n /**\n * Highlights the item before the one that is currently highlighted.\n */\n function highlightPreviousItem() {\n const currentIndex = highlightedItemIndex.value\n open()\n highlightedItemIndex.value = currentIndex > 0 ? currentIndex - 1 : props.items.length - 1\n }\n\n /**\n * Highlights the first of the provided items.\n */\n function highlightFirstItem() {\n highlightedItemIndex.value = 0\n }\n\n /**\n * Highlights the last of the provided items.\n */\n function highlightLastItem() {\n highlightedItemIndex.value = props.items.length - 1\n }\n\n /**\n * Updates the variable that is used to search in the filters.\n *\n * @param event - The event coming from the user typing.\n */\n function updateSearchBuffer(event: KeyboardEvent) {\n if (/^\\w$/.test(event.key)) {\n const key = event.key\n searchBuffer.value += key\n restartResetSearchTimeout()\n }\n }\n\n /**\n * Resets the search buffer.\n */\n function resetSearchBuffer() {\n searchBuffer.value = ''\n }\n\n /**\n * Closes the dropdown if the passed event has happened on an element out of the dropdown.\n *\n * @param event - The event to check if it has happened out of the dropdown component.\n */\n function closeIfEventIsOutOfDropdown(event: MouseEvent | TouchEvent | FocusEvent) {\n if (!rootRef.value?.contains(getTargetElement(event))) {\n close()\n }\n }\n\n /**\n * Adds listeners to the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function addDocumentCloseListeners() {\n document.addEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.addEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.addEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Removes the listeners of the document element to detect if the focus has moved out from the\n * dropdown.\n */\n function removeDocumentCloseListeners() {\n document.removeEventListener('mousedown', closeIfEventIsOutOfDropdown)\n document.removeEventListener('touchstart', closeIfEventIsOutOfDropdown)\n document.removeEventListener('focusin', closeIfEventIsOutOfDropdown)\n }\n\n /**\n * Highlights the item that matches the search buffer. To do so it checks the list buttons\n * text content. It highlights items following this priority:\n * - If an element is already highlighted, it starts searching from that element.\n * - If no element is found starting from the previously highlighted, it returns the first one.\n * - If no element is found matching the search query it highlights the first element.\n *\n * @param search - The search string to find in the HTML.\n */\n watch(searchBuffer, search => {\n if (search) {\n const normalizedSearch = normalizeString(search)\n const matchingIndices = itemsButtonRefs?.value?.reduce<number[]>(\n (matchingIndices, button, index) => {\n if (button) {\n const safeButtonWordCharacters = button.textContent!.replace(/\\W/g, '')\n const normalizedButtonText = normalizeString(safeButtonWordCharacters)\n if (normalizedButtonText.startsWith(normalizedSearch)) {\n matchingIndices.push(index)\n }\n }\n return matchingIndices\n },\n [],\n )\n highlightedItemIndex.value =\n // First matching item starting to search from the current highlighted element\n matchingIndices?.find(index => index >= highlightedItemIndex.value) ??\n // First matching item\n matchingIndices?.[0] ??\n // First item\n 0\n }\n })\n\n /**\n * Updates the debounced function to reset the search.\n *\n * @param searchTimeoutMs - The new milliseconds that have to pass without typing before\n * resetting the search.\n */\n watch(\n () => props.searchTimeoutMs,\n searchTimeoutMs => {\n restartResetSearchTimeout = debounceFunction(resetSearchBuffer, searchTimeoutMs)\n },\n { immediate: true },\n )\n\n /**\n * Focuses the DOM element which matches the `highlightedItemIndex`.\n *\n * @param highlightedItemIndex - The index of the HTML element to focus.\n */\n watch(\n highlightedItemIndex,\n highlightedItemIndex => {\n nextTick(() => itemsButtonRefs.value[highlightedItemIndex]?.focus())\n },\n { immediate: true },\n )\n\n /**\n * When the dropdown is open it sets the focused element to the one that is selected.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n highlightedItemIndex.value = isOpen\n ? props.modelValue === null\n ? 0\n : props.items.indexOf(props.modelValue)\n : -1\n })\n\n /**\n * Adds and removes listeners to close the dropdown when it loses the focus.\n *\n * @param isOpen - True if the dropdown is open, false otherwise.\n */\n watch(isOpen, isOpen => {\n /*\n * Because there is an issue with Firefox in macOS and Safari that doesn't focus the target\n * element of the `mousedown` events, the `focusout` event `relatedTarget` property can't be\n * used to detect whether the user has blurred the dropdown. The hack here is to use\n * document listeners that have the side effect of losing the focus.\n */\n if (isOpen) {\n addDocumentCloseListeners()\n } else {\n removeDocumentCloseListeners()\n }\n })\n\n /**\n * If the dropdown is destroyed before removing the document listeners, it ensures that they\n * are removed too.\n */\n onBeforeUnmount(() => {\n removeDocumentCloseListeners()\n })\n\n return {\n ariaLabels,\n hasToggleSlot: !!slots.toggle,\n closeAndFocusToggleButton,\n dropdownCSSClasses,\n emitSelectedItemChanged,\n highlightFirstItem,\n highlightLastItem,\n highlightNextItem,\n highlightPreviousItem,\n highlightedItemIndex,\n isOpen,\n itemsButtonRefs,\n itemsCSSClasses,\n listId,\n open,\n rootRef,\n toggle,\n toggleButtonRef,\n updateSearchBuffer,\n }\n },\n})\n</script>\n\n<style lang=\"css\" scoped>\n.x-dropdown {\n position: relative;\n}\n\n.x-dropdown__items-list {\n z-index: 1;\n list-style: none;\n position: absolute;\n padding: 0;\n margin: 0;\n top: calc(100% + var(--x-size-gap-dropdown-default, 0));\n}\n</style>\n\n<docs lang=\"mdx\">\n## Example\n\nThe `Dropdown` component is a simple yet customizable select component. The component needs to work\nwith the list of items available to select, which are passed using the `items` prop, and the selected\nitem, which is passed in using the `value` prop.\n\nThe supported items must be an array that can contain unique strings, unique numbers, or objects\nwith a unique `id` property.\n\nThe content of each item can be customized using the `item` slot, which apart from the data of the\nitem, it also receives via prop if the element is selected or highlighted.\n\nThe `toggle` slot can be used to customize the button that opens the dropdown. If this is not\nprovided, the `item` slot will be used for that.\n\n```vue\n<template>\n <BaseDropdown v-model=\"value\" :items=\"items\">\n <template #toggle=\"{ item, isOpen }\">{{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseDropdown>\n</template>\n\n<script setup>\nimport { BaseDropdown } from '@empathyco/x-components'\nimport { ref } from 'vue'\nconst items = ['a', 2, { id: '3' }]\nconst value = ref('a')\n</script>\n```\n</docs>\n"],"names":["NoAnimation","debounceFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,IAAI,gBAAgB,CAAA;AAEpB;;;AAGE;AACF,gBAAe,eAAe,CAAC;AAC7B,IAAA,IAAI,EAAE,cAAc;AACpB,IAAA,KAAK,EAAE;;AAEL,QAAA,KAAK,EAAE;AACL,YAAA,IAAI,EAAE,KAAiC;AACvC,YAAA,QAAQ,EAAE,IAAI;AACf,SAAA;;AAED,QAAA,UAAU,EAAE;AACV,YAAA,IAAI,EAAE,IAAgD;YACtD,SAAS,EAAE,CAAC,CAAM,KAChB,OAAO,CAAA,KAAM,QAAO,IAAK,OAAO,CAAA,KAAM,QAAO,IAAK,OAAO,CAAA,KAAM,YAAY,CAAA,KAAM,IAAI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AI,MAAM,EAAE;AACV,gBAAA,yBAAyB,EAAC;YAC5B;iBAAO;AACL,gBAAA,4BAA4B,EAAC;YAC/B;AACF,QAAA,CAAC,CAAA;AAED;;;AAGE;QACF,eAAe,CAAC,MAAI;AAClB,YAAA,4BAA4B,EAAC;AAC/B,QAAA,CAAC,CAAA;QAED,OAAO;YACL,UAAU;AACV,YAAA,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM;YAC7B,yBAAyB;YACzB,kBAAkB;YAClB,uBAAuB;YACvB,kBAAkB;YAClB,iBAAiB;YACjB,iBAAiB;YACjB,qBAAqB;YACrB,oBAAoB;YACpB,MAAM;YACN,eAAe;YACf,eAAe;YACf,MAAM;YACN,IAAI;YACJ,OAAO;YACP,MAAM;YACN,eAAe;YACf,kBAAkB;SACpB;IACF,CAAC;AACF,CAAA,CAAA;;;;"}
|
|
@@ -5,6 +5,7 @@ import '../plugins/x-bus.js';
|
|
|
5
5
|
import '@empathyco/x-utils';
|
|
6
6
|
import '../plugins/x-plugin.js';
|
|
7
7
|
import { useXBus } from '../composables/use-x-bus.js';
|
|
8
|
+
import '../utils/storage.js';
|
|
8
9
|
import '@vueuse/core';
|
|
9
10
|
import { DirectionalFocusNavigationService } from '../services/directional-focus-navigation.service.js';
|
|
10
11
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-keyboard-navigation.vue2.js","sources":["../../../src/components/base-keyboard-navigation.vue"],"sourcesContent":["<template>\n <div\n ref=\"el\"\n class=\"x-keyboard-navigation\"\n data-test=\"keyboard-navigation\"\n @keydown.up.down.right.left.prevent=\"focusNextNavigableElement\"\n >\n <!-- @slot (Required) Container content -->\n <slot />\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { PropType } from 'vue'\nimport type { SpatialNavigation } from '../services/services.types'\n\nimport type { ArrowKey, EventsForDirectionLimit, TakeNavigationControl } from '../utils/types'\nimport type { XEventsOf } from '../wiring/events.types'\nimport type { WireMetadata } from '../wiring/wiring.types'\nimport { computed, defineComponent, onMounted, ref } from 'vue'\nimport { useXBus } from '../composables'\nimport { DirectionalFocusNavigationService } from '../services/directional-focus-navigation.service'\n\n/**\n * Base component to handle keyboard navigation for elements inside it. It has a required slot to\n * include the navigable elements.\n *\n * @remarks\n * The component can be customized through props: an array of navigationHijacker objects, which\n * contains: the xEvent to listen to, the moduleName in charge of emitting the event and to which\n * direction it should react to; to take control of the navigation and eventsForDirectionLimit, to\n * emit an xEvent when reaching the navigation limit in any direction.\n *\n * @public\n */\nexport default defineComponent({\n name: 'BaseKeyboardNavigation',\n props: {\n /**\n * An array of {@link TakeNavigationControl} objects defining when to\n * take control of the keyboard navigation.\n */\n navigationHijacker: {\n type: Array as PropType<TakeNavigationControl[]>,\n default: () => [\n { xEvent: 'UserPressedArrowKey', moduleName: 'searchBox', direction: 'ArrowDown' },\n ],\n },\n /**\n * An {@link EventsForDirectionLimit} to emit when the user is already at the furthest element\n * in a direction and tries to keep going on the same direction.\n */\n eventsForDirectionLimit: {\n type: Object as PropType<Partial<EventsForDirectionLimit>>,\n default: () => ({ ArrowUp: 'UserReachedEmpathizeTop' }),\n },\n },\n setup(props) {\n const el = ref<HTMLElement>()\n const xBus = useXBus()\n\n /**\n * The {@link SpatialNavigation} service to use.\n */\n let navigationService!: SpatialNavigation\n\n /**\n * The element to focus.\n */\n let elementToFocus: HTMLElement | undefined\n\n /**\n * Get the navigation hijacker events.\n *\n * @remarks\n * If the same {@link XEvent} is defined multiple times it is only inserted once.\n *\n * @returns The events to hijack the navigation.\n */\n const navigationHijackerEvents = computed((): XEventsOf<ArrowKey>[] => {\n const eventsSet = props.navigationHijacker.map(({ xEvent }) => xEvent)\n return Array.from(new Set(eventsSet))\n })\n\n onMounted(() => {\n // TODO Replace this with injection\n navigationService = new DirectionalFocusNavigationService(el.value!)\n })\n\n /**\n * Checks if the component has to take control of the keyboard navigation.\n *\n * @param eventPayload - The {@link ArrowKey}.\n * @param metadata - The {@link WireMetadata}.\n *\n * @returns Whether the component needs to take control of the keyboard navigation or not.\n * @internal\n */\n function hasToTakeNavigationControl(eventPayload: ArrowKey, metadata: WireMetadata): boolean {\n return props.navigationHijacker.some(\n ({ moduleName, direction }) =>\n moduleName === metadata.moduleName && direction === eventPayload,\n )\n }\n\n /**\n * Focus the next navigable element returned by the navigation service.\n *\n * @param direction - The navigation direction.\n * @internal\n */\n function focusNextNavigableElement(direction: ArrowKey | KeyboardEvent): void {\n const dir = typeof direction === 'object' ? (direction.key as ArrowKey) : direction\n const nextElementToFocus = navigationService?.navigateTo(dir)\n\n if (elementToFocus !== nextElementToFocus) {\n elementToFocus = nextElementToFocus\n elementToFocus.focus()\n } else {\n emitDirectionalLimitReached(dir)\n elementToFocus = undefined\n }\n }\n\n /**\n * Emit the {@link XEvent} associated to the navigation's direction when reaching its limit.\n *\n * @param direction - The navigation direction.\n * @internal\n */\n function emitDirectionalLimitReached(direction: ArrowKey): void {\n const xEvent = props.eventsForDirectionLimit?.[direction]\n if (xEvent) {\n xBus.emit(xEvent, undefined, { target: elementToFocus })\n }\n }\n\n /**\n * Trigger navigation if this component is in control of it.\n *\n * @param eventPayload - The {@link @empathyco/x-bus#SubjectPayload.eventPayload}.\n * @param metadata - The {@link @empathyco/x-bus#SubjectPayload.metadata}.\n * @public\n */\n navigationHijackerEvents.value.forEach(event => {\n xBus.on(event, true).subscribe(({ eventPayload, metadata }) => {\n if (hasToTakeNavigationControl(eventPayload, metadata)) {\n focusNextNavigableElement(eventPayload)\n }\n })\n })\n\n return { el, focusNextNavigableElement }\n },\n})\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nAn event that the component will emit:\n\n- [`UserReachedEmpathizeTop`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event emitted by default when the container reaches its top navigation, but more events can be\n emitted for each direction using the `eventsForDirectionLimit` prop.\n\n## Examples\n\nThis component has a slot to inject other components inside it. The component expects a required\nprop, navigationHijacker, which is an array of objects containing: the xEvent to listen to, the\nmoduleName in charge of emitting the event and to which direction it should react to; to take\ncontrol of the navigation. It has another prop, optional in this case, to emit an xEvent when\nreaching the navigation limit in any direction.\n\n### Basic Usage\n\n```vue\n<template>\n <BaseKeyboardNavigation>\n <QuerySuggestions />\n </BaseKeyboardNavigation>\n</template>\n\n<script setup>\nimport { BaseKeyboardNavigation } from '@empathyco/x-components'\nimport QuerySuggestions from './QuerySuggestions.vue'\n</script>\n```\n\n### Defining multiple conditions to take navigation's control\n\n```vue\n<template>\n <BaseKeyboardNavigation\n :navigationHijacker=\"[\n {\n xEvent: 'UserPressedArrowKey',\n moduleName: 'searchBox',\n direction: 'ArrowDown',\n },\n {\n xEvent: 'UserPressedArrowKey',\n moduleName: 'facets',\n direction: 'ArrowRight',\n },\n ]\"\n >\n <QuerySuggestions />\n </BaseKeyboardNavigation>\n</template>\n\n<script setup>\nimport { BaseKeyboardNavigation } from '@empathyco/x-components'\nimport QuerySuggestions from './QuerySuggestions.vue'\n</script>\n```\n\n### Defining events to emit when reaching a navigation limit\n\n```vue\n<template>\n <BaseKeyboardNavigation\n :navigationHijacker=\"[\n {\n xEvent: 'UserPressedArrowKey',\n moduleName: 'searchBox',\n direction: 'ArrowDown',\n },\n ]\"\n :eventsForDirectionLimit=\"{\n ArrowUp: 'UserReachedEmpathizeTop',\n }\"\n >\n <QuerySuggestions />\n </BaseKeyboardNavigation>\n</template>\n\n<script setup>\nimport { BaseKeyboardNavigation } from '@empathyco/x-components'\nimport QuerySuggestions from './QuerySuggestions.vue'\n</script>\n```\n</docs>\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"base-keyboard-navigation.vue2.js","sources":["../../../src/components/base-keyboard-navigation.vue"],"sourcesContent":["<template>\n <div\n ref=\"el\"\n class=\"x-keyboard-navigation\"\n data-test=\"keyboard-navigation\"\n @keydown.up.down.right.left.prevent=\"focusNextNavigableElement\"\n >\n <!-- @slot (Required) Container content -->\n <slot />\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { PropType } from 'vue'\nimport type { SpatialNavigation } from '../services/services.types'\n\nimport type { ArrowKey, EventsForDirectionLimit, TakeNavigationControl } from '../utils/types'\nimport type { XEventsOf } from '../wiring/events.types'\nimport type { WireMetadata } from '../wiring/wiring.types'\nimport { computed, defineComponent, onMounted, ref } from 'vue'\nimport { useXBus } from '../composables'\nimport { DirectionalFocusNavigationService } from '../services/directional-focus-navigation.service'\n\n/**\n * Base component to handle keyboard navigation for elements inside it. It has a required slot to\n * include the navigable elements.\n *\n * @remarks\n * The component can be customized through props: an array of navigationHijacker objects, which\n * contains: the xEvent to listen to, the moduleName in charge of emitting the event and to which\n * direction it should react to; to take control of the navigation and eventsForDirectionLimit, to\n * emit an xEvent when reaching the navigation limit in any direction.\n *\n * @public\n */\nexport default defineComponent({\n name: 'BaseKeyboardNavigation',\n props: {\n /**\n * An array of {@link TakeNavigationControl} objects defining when to\n * take control of the keyboard navigation.\n */\n navigationHijacker: {\n type: Array as PropType<TakeNavigationControl[]>,\n default: () => [\n { xEvent: 'UserPressedArrowKey', moduleName: 'searchBox', direction: 'ArrowDown' },\n ],\n },\n /**\n * An {@link EventsForDirectionLimit} to emit when the user is already at the furthest element\n * in a direction and tries to keep going on the same direction.\n */\n eventsForDirectionLimit: {\n type: Object as PropType<Partial<EventsForDirectionLimit>>,\n default: () => ({ ArrowUp: 'UserReachedEmpathizeTop' }),\n },\n },\n setup(props) {\n const el = ref<HTMLElement>()\n const xBus = useXBus()\n\n /**\n * The {@link SpatialNavigation} service to use.\n */\n let navigationService!: SpatialNavigation\n\n /**\n * The element to focus.\n */\n let elementToFocus: HTMLElement | undefined\n\n /**\n * Get the navigation hijacker events.\n *\n * @remarks\n * If the same {@link XEvent} is defined multiple times it is only inserted once.\n *\n * @returns The events to hijack the navigation.\n */\n const navigationHijackerEvents = computed((): XEventsOf<ArrowKey>[] => {\n const eventsSet = props.navigationHijacker.map(({ xEvent }) => xEvent)\n return Array.from(new Set(eventsSet))\n })\n\n onMounted(() => {\n // TODO Replace this with injection\n navigationService = new DirectionalFocusNavigationService(el.value!)\n })\n\n /**\n * Checks if the component has to take control of the keyboard navigation.\n *\n * @param eventPayload - The {@link ArrowKey}.\n * @param metadata - The {@link WireMetadata}.\n *\n * @returns Whether the component needs to take control of the keyboard navigation or not.\n * @internal\n */\n function hasToTakeNavigationControl(eventPayload: ArrowKey, metadata: WireMetadata): boolean {\n return props.navigationHijacker.some(\n ({ moduleName, direction }) =>\n moduleName === metadata.moduleName && direction === eventPayload,\n )\n }\n\n /**\n * Focus the next navigable element returned by the navigation service.\n *\n * @param direction - The navigation direction.\n * @internal\n */\n function focusNextNavigableElement(direction: ArrowKey | KeyboardEvent): void {\n const dir = typeof direction === 'object' ? (direction.key as ArrowKey) : direction\n const nextElementToFocus = navigationService?.navigateTo(dir)\n\n if (elementToFocus !== nextElementToFocus) {\n elementToFocus = nextElementToFocus\n elementToFocus.focus()\n } else {\n emitDirectionalLimitReached(dir)\n elementToFocus = undefined\n }\n }\n\n /**\n * Emit the {@link XEvent} associated to the navigation's direction when reaching its limit.\n *\n * @param direction - The navigation direction.\n * @internal\n */\n function emitDirectionalLimitReached(direction: ArrowKey): void {\n const xEvent = props.eventsForDirectionLimit?.[direction]\n if (xEvent) {\n xBus.emit(xEvent, undefined, { target: elementToFocus })\n }\n }\n\n /**\n * Trigger navigation if this component is in control of it.\n *\n * @param eventPayload - The {@link @empathyco/x-bus#SubjectPayload.eventPayload}.\n * @param metadata - The {@link @empathyco/x-bus#SubjectPayload.metadata}.\n * @public\n */\n navigationHijackerEvents.value.forEach(event => {\n xBus.on(event, true).subscribe(({ eventPayload, metadata }) => {\n if (hasToTakeNavigationControl(eventPayload, metadata)) {\n focusNextNavigableElement(eventPayload)\n }\n })\n })\n\n return { el, focusNextNavigableElement }\n },\n})\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nAn event that the component will emit:\n\n- [`UserReachedEmpathizeTop`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event emitted by default when the container reaches its top navigation, but more events can be\n emitted for each direction using the `eventsForDirectionLimit` prop.\n\n## Examples\n\nThis component has a slot to inject other components inside it. The component expects a required\nprop, navigationHijacker, which is an array of objects containing: the xEvent to listen to, the\nmoduleName in charge of emitting the event and to which direction it should react to; to take\ncontrol of the navigation. It has another prop, optional in this case, to emit an xEvent when\nreaching the navigation limit in any direction.\n\n### Basic Usage\n\n```vue\n<template>\n <BaseKeyboardNavigation>\n <QuerySuggestions />\n </BaseKeyboardNavigation>\n</template>\n\n<script setup>\nimport { BaseKeyboardNavigation } from '@empathyco/x-components'\nimport QuerySuggestions from './QuerySuggestions.vue'\n</script>\n```\n\n### Defining multiple conditions to take navigation's control\n\n```vue\n<template>\n <BaseKeyboardNavigation\n :navigationHijacker=\"[\n {\n xEvent: 'UserPressedArrowKey',\n moduleName: 'searchBox',\n direction: 'ArrowDown',\n },\n {\n xEvent: 'UserPressedArrowKey',\n moduleName: 'facets',\n direction: 'ArrowRight',\n },\n ]\"\n >\n <QuerySuggestions />\n </BaseKeyboardNavigation>\n</template>\n\n<script setup>\nimport { BaseKeyboardNavigation } from '@empathyco/x-components'\nimport QuerySuggestions from './QuerySuggestions.vue'\n</script>\n```\n\n### Defining events to emit when reaching a navigation limit\n\n```vue\n<template>\n <BaseKeyboardNavigation\n :navigationHijacker=\"[\n {\n xEvent: 'UserPressedArrowKey',\n moduleName: 'searchBox',\n direction: 'ArrowDown',\n },\n ]\"\n :eventsForDirectionLimit=\"{\n ArrowUp: 'UserReachedEmpathizeTop',\n }\"\n >\n <QuerySuggestions />\n </BaseKeyboardNavigation>\n</template>\n\n<script setup>\nimport { BaseKeyboardNavigation } from '@empathyco/x-components'\nimport QuerySuggestions from './QuerySuggestions.vue'\n</script>\n```\n</docs>\n"],"names":[],"mappings":";;;;;;;;;;;AAuBA;;;;;;;;;;;AAWE;AACF,gBAAe,eAAe,CAAC;AAC7B,IAAA,IAAI,EAAE,wBAAwB;AAC9B,IAAA,KAAK,EAAE;AACL;;;A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E,YAAA,MAAM,GAAE,GAAI,OAAO,cAAc,QAAO,GAAK,SAAS,CAAC,GAAe,GAAI,SAAQ;YAClF,MAAM,kBAAiB,GAAI,iBAAiB,EAAE,UAAU,CAAC,GAAG,CAAA;AAE5D,YAAA,IAAI,mBAAmB,kBAAkB,EAAE;gBACzC,iBAAiB,kBAAiB;gBAClC,cAAc,CAAC,KAAK,EAAC;YACvB;iBAAO;gBACL,2BAA2B,CAAC,GAAG,CAAA;gBAC/B,cAAa,GAAI,SAAQ;YAC3B;QACF;AAEA;;;;;AAKE;QACF,SAAS,2BAA2B,CAAC,SAAmB,EAAA;YACtD,MAAM,MAAK,GAAI,KAAK,CAAC,uBAAuB,GAAG,SAAS,CAAA;YACxD,IAAI,MAAM,EAAE;AACV,gBAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,cAAa,EAAG,CAAA;YACzD;QACF;AAEA;;;;;;AAME;AACF,QAAA,wBAAwB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAI,IAAG;AAC5C,YAAA,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,YAAY,EAAE,QAAO,EAAG,KAAG;AAC3D,gBAAA,IAAI,0BAA0B,CAAC,YAAY,EAAE,QAAQ,CAAC,EAAE;oBACtD,yBAAyB,CAAC,YAAY,CAAA;gBACxC;AACF,YAAA,CAAC,CAAA;AACH,QAAA,CAAC,CAAA;AAED,QAAA,OAAO,EAAE,EAAE,EAAE,yBAAwB,EAAE;IACzC,CAAC;AACF,CAAA,CAAA;;;;"}
|
|
@@ -8,7 +8,7 @@ function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
|
|
|
8
8
|
"model-value": _ctx.selectedColumns,
|
|
9
9
|
items: _ctx.columns,
|
|
10
10
|
animation: _ctx.animation,
|
|
11
|
-
"aria-label":
|
|
11
|
+
"aria-label": _ctx.ariaLabels?.dropdown,
|
|
12
12
|
"onUpdate:modelValue": _ctx.emitEvents
|
|
13
13
|
}, createSlots({
|
|
14
14
|
item: withCtx(({ item, isSelected, isHighlighted }) => [
|
|
@@ -24,7 +24,7 @@ function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
|
|
|
24
24
|
]),
|
|
25
25
|
key: "0"
|
|
26
26
|
} : void 0
|
|
27
|
-
]), 1032, ["model-value", "items", "animation", "onUpdate:modelValue"]);
|
|
27
|
+
]), 1032, ["model-value", "items", "animation", "aria-label", "onUpdate:modelValue"]);
|
|
28
28
|
}
|
|
29
29
|
var baseColumnPickerDropdown = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render]]);
|
|
30
30
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-column-picker-dropdown.vue.js","sources":["../../../../src/components/column-picker/base-column-picker-dropdown.vue"],"sourcesContent":["<template>\n <BaseDropdown\n :model-value=\"selectedColumns\"\n :items=\"columns\"\n :animation=\"animation\"\n aria-label=\"
|
|
1
|
+
{"version":3,"file":"base-column-picker-dropdown.vue.js","sources":["../../../../src/components/column-picker/base-column-picker-dropdown.vue"],"sourcesContent":["<template>\n <BaseDropdown\n :model-value=\"selectedColumns\"\n :items=\"columns\"\n :animation=\"animation\"\n :aria-label=\"ariaLabels?.dropdown\"\n @update:model-value=\"emitEvents\"\n >\n <template v-if=\"hasToggleSlot\" #toggle=\"{ item, isOpen }\">\n <!--\n @slot From `BaseDropdown` component: Used to render the contents of the dropdown toggle\n button. If not provided, it uses the `item` slot as fallback.\n @binding {string|number|Identifiable} item - The item data to render.\n @binding {boolean} isOpen - True if the dropdown is opened, and false if it is\n closed.\n -->\n <slot name=\"toggle\" v-bind=\"{ item, isOpen }\" />\n </template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <!--\n @slot (required) From `BaseDropdown` component: Used to render each one of the items\n content, and as fallback for the toggle button content slot if it is not provided.\n @binding {string|number|Identifiable} item - Item to render\n @binding {boolean} isHighlighted - True when the item has the focus.\n @binding {boolean} isSelected - True when the item is selected.\n -->\n <slot name=\"item\" v-bind=\"{ item, isSelected, isHighlighted }\" />\n </template>\n </BaseDropdown>\n</template>\n\n<script lang=\"ts\">\nimport type { Component, PropType } from 'vue'\nimport { computed, defineComponent, onBeforeMount, ref, watch } from 'vue'\nimport { useAccessibilityLabels } from '../../composables'\nimport { use$x } from '../../composables/use-$x'\nimport BaseDropdown from '../base-dropdown.vue'\n\n/**\n * Column picker dropdown component renders {@link BaseDropdown} component which\n * options are the different columns you can set for a grid.\n *\n * It emits {@link XEventsTypes.UserClickedColumnPicker} on dropdown\n * input.\n *\n * @public\n */\nexport default defineComponent({\n name: 'BaseColumnPickerDropdown',\n components: { BaseDropdown },\n props: {\n /** An array of numbers that represents the number of columns to render. */\n columns: {\n type: Array as PropType<number[]>,\n required: true,\n },\n /** The value of the selected columns number. */\n modelValue: Number,\n /** The transition to use for opening and closing the dropdown. */\n animation: [String, Object] as PropType<string | Component>,\n },\n emits: ['update:modelValue'],\n setup(props, { emit, slots }) {\n const $x = use$x()\n\n const ariaLabels = useAccessibilityLabels('baseColumnPickerDropdown')\n\n const providedSelectedColumns = computed(() => props.modelValue ?? props.columns[0])\n const selectedColumns = ref(providedSelectedColumns.value)\n\n /**\n * Assigns `selectedColumns` value and emits `ColumnsNumberProvided`.\n *\n * @param column - Column number provided.\n */\n function emitColumnsNumberProvided(column: number) {\n selectedColumns.value = column\n $x.emit('ColumnsNumberProvided', column)\n }\n\n /**\n * Emits `update:modelValue` with the column selected.\n *\n * @param column - Column number selected.\n */\n function emitUpdateModelValue(column: number) {\n if (props.modelValue !== column) {\n emit('update:modelValue', column)\n }\n }\n\n watch(providedSelectedColumns, emitColumnsNumberProvided)\n watch(selectedColumns, emitUpdateModelValue)\n\n $x.on('ColumnsNumberProvided', false).subscribe(column => (selectedColumns.value = column))\n\n /**\n * Synchronizes the columns number before mounting the component. If the real number of selected\n * columns equals the provided columns, it emits the event to sync it with every other component.\n * If it is not equal it means that the user has already selected a number of columns, so we emit\n * a `update:modelValue` event so developers can sync the provided value.\n */\n onBeforeMount(() => {\n if (selectedColumns.value === providedSelectedColumns.value) {\n emitColumnsNumberProvided(selectedColumns.value)\n } else {\n emitUpdateModelValue(selectedColumns.value)\n }\n })\n\n /**\n * Emits a {@link XEventsTypes.UserClickedColumnPicker} and\n * {@link XEventsTypes.ColumnsNumberProvided} events.\n *\n * @param column - Column number payload.\n */\n function emitEvents(column: number) {\n $x.emit('UserClickedColumnPicker', column)\n $x.emit('ColumnsNumberProvided', column)\n }\n\n return {\n ariaLabels,\n emitEvents,\n hasToggleSlot: !!slots.toggle,\n selectedColumns,\n }\n },\n})\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nAn event that the component will emit:\n\n- [`UserClickedColumnPicker`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event is emitted after the user clicks an item in the dropdown. The event payload is the\n number of columns that the clicked item represents.\n- [`ColumnsNumberProvided`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event is emitted on component mount, and whenever the value changes. The event payload is the\n current `selectedColumns` value.\n\n## Examples\n\nColumn picker dropdown component renders a dropdown component which options are the different\ncolumns you can set for a grid.\n\n### Usage\n\nNotice that the slots provided match with the `BaseDropdown` component. The `item` slot is required\nunlike the `toggle`, which renders the same `item` slot defined by default.\n\n#### Default usage\n\n```vue live\n<template>\n <BaseColumnPickerDropdown v-model=\"selectedColumns\" :columns=\"[2, 4, 6]\">\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseColumnPickerDropdown>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerDropdown from '@empathyco/x-components/js/components/column-picker/base-column-picker-dropdown.vue'\n\nconst selectedColumns = ref(2)\n</script>\n```\n\n#### Customizing toggle button\n\n```vue live\n<template>\n <BaseColumnPickerDropdown v-model=\"selectedColumns\" :columns=\"[2, 4, 6]\">\n <template #toggle=\"{ item, isOpen }\">Selected: {{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseColumnPickerDropdown>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerDropdown from '@empathyco/x-components/js/components/column-picker/base-column-picker-dropdown.vue'\n\nconst selectedColumns = ref(2)\n</script>\n```\n\n#### Using it without v-model / value\n\nThe component emits an X Event, `UserClickedColumnPicker`, on column change and it also listens to\nthat event from outside, so you don't need to store the current column value to keep it synchronized\nwith other column pickers.\n\n```vue live\n<template>\n <BaseColumnPickerDropdown :columns=\"[2, 4, 6]\">\n <template #toggle=\"{ item, isOpen }\">Selected: {{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseColumnPickerDropdown>\n</template>\n\n<script setup>\nimport BaseColumnPickerDropdown from '@empathyco/x-components/js/components/column-picker/base-column-picker-dropdown.vue'\n</script>\n```\n</docs>\n"],"names":["_createBlock","_createSlots","_withCtx","_renderSlot","_normalizeProps","_guardReactiveProps"],"mappings":";;;;;;sBACEA,WAAA,CA2Be,uBAAA,EAAA;AAAA,IA1BZ,aAAA,EAAa,IAAA,CAAA,eAAA;AAAA,IACb,KAAA,EAAO,IAAA,CAAA,OAAA;AAAA,IACP,SAAA,EAAW,IAAA,CAAA,SAAA;AAAA,IACX,cAAY,IAAA,CAAA,UAAA,EAAY,QAAA;AAAA,IACxB,qBAAA,EAAoB,IAAA,CAAA;AAAA,GAAA,EAAAC,WAAA,CAAA;AAYV,IAAA,IAAA,EAAIC,OAAA,CAQb,CAAiE,EARhD,IAAA,EAAM,YAAY,aAAA,EAAa,KAAA;AAAA,MAQhDC,UAAA,CAAiE,IAAA,CAAA,MAAA,EAAA,MAAA,EAAAC,cAAA,CAAAC,kBAAA,CAAA,EAArC,IAAA,EAAM,UAAA,EAAY,aAAA,EAAa,CAAA,CAAA;AAAA,KAAA,CAAA;;;;AAlB7C,IAAA,IAAA,CAAA,aAAA,GAAA;AAAgB,MAAA,IAAA,EAAA,QAAA;AAAA,MAAA,EAAA,EAAAH,OAAA,CAQ9B,CAAgD,EARR,IAAA,EAAM,MAAA,EAAM,KAAA;AAAA,QAQpDC,UAAA,CAAgD,IAAA,CAAA,MAAA,EAAA,QAAA,EAAAC,cAAA,CAAAC,kBAAA,CAAA,EAAlB,IAAA,EAAM,MAAA,EAAM,CAAA,CAAA;AAAA,OAAA,CAAA;;;;;;;;;"}
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { defineComponent, computed, ref, watch, onBeforeMount } from 'vue';
|
|
2
|
+
import '../../composables/create-use-device.js';
|
|
2
3
|
import { use$x } from '../../composables/use-_x.js';
|
|
4
|
+
import { useAccessibilityLabels } from '../../composables/use-accessibility-labels.js';
|
|
5
|
+
import 'vuex';
|
|
6
|
+
import '../../plugins/x-bus.js';
|
|
7
|
+
import '@empathyco/x-utils';
|
|
8
|
+
import '../../plugins/x-plugin.js';
|
|
9
|
+
import '@vueuse/core';
|
|
10
|
+
import 'rxjs';
|
|
3
11
|
import BaseDropdown from '../base-dropdown.vue.js';
|
|
4
12
|
|
|
5
13
|
/**
|
|
@@ -28,6 +36,7 @@ var _sfc_main = defineComponent({
|
|
|
28
36
|
emits: ['update:modelValue'],
|
|
29
37
|
setup(props, { emit, slots }) {
|
|
30
38
|
const $x = use$x();
|
|
39
|
+
const ariaLabels = useAccessibilityLabels('baseColumnPickerDropdown');
|
|
31
40
|
const providedSelectedColumns = computed(() => props.modelValue ?? props.columns[0]);
|
|
32
41
|
const selectedColumns = ref(providedSelectedColumns.value);
|
|
33
42
|
/**
|
|
@@ -77,6 +86,7 @@ var _sfc_main = defineComponent({
|
|
|
77
86
|
$x.emit('ColumnsNumberProvided', column);
|
|
78
87
|
}
|
|
79
88
|
return {
|
|
89
|
+
ariaLabels,
|
|
80
90
|
emitEvents,
|
|
81
91
|
hasToggleSlot: !!slots.toggle,
|
|
82
92
|
selectedColumns,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-column-picker-dropdown.vue2.js","sources":["../../../../src/components/column-picker/base-column-picker-dropdown.vue"],"sourcesContent":["<template>\n <BaseDropdown\n :model-value=\"selectedColumns\"\n :items=\"columns\"\n :animation=\"animation\"\n aria-label=\"
|
|
1
|
+
{"version":3,"file":"base-column-picker-dropdown.vue2.js","sources":["../../../../src/components/column-picker/base-column-picker-dropdown.vue"],"sourcesContent":["<template>\n <BaseDropdown\n :model-value=\"selectedColumns\"\n :items=\"columns\"\n :animation=\"animation\"\n :aria-label=\"ariaLabels?.dropdown\"\n @update:model-value=\"emitEvents\"\n >\n <template v-if=\"hasToggleSlot\" #toggle=\"{ item, isOpen }\">\n <!--\n @slot From `BaseDropdown` component: Used to render the contents of the dropdown toggle\n button. If not provided, it uses the `item` slot as fallback.\n @binding {string|number|Identifiable} item - The item data to render.\n @binding {boolean} isOpen - True if the dropdown is opened, and false if it is\n closed.\n -->\n <slot name=\"toggle\" v-bind=\"{ item, isOpen }\" />\n </template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <!--\n @slot (required) From `BaseDropdown` component: Used to render each one of the items\n content, and as fallback for the toggle button content slot if it is not provided.\n @binding {string|number|Identifiable} item - Item to render\n @binding {boolean} isHighlighted - True when the item has the focus.\n @binding {boolean} isSelected - True when the item is selected.\n -->\n <slot name=\"item\" v-bind=\"{ item, isSelected, isHighlighted }\" />\n </template>\n </BaseDropdown>\n</template>\n\n<script lang=\"ts\">\nimport type { Component, PropType } from 'vue'\nimport { computed, defineComponent, onBeforeMount, ref, watch } from 'vue'\nimport { useAccessibilityLabels } from '../../composables'\nimport { use$x } from '../../composables/use-$x'\nimport BaseDropdown from '../base-dropdown.vue'\n\n/**\n * Column picker dropdown component renders {@link BaseDropdown} component which\n * options are the different columns you can set for a grid.\n *\n * It emits {@link XEventsTypes.UserClickedColumnPicker} on dropdown\n * input.\n *\n * @public\n */\nexport default defineComponent({\n name: 'BaseColumnPickerDropdown',\n components: { BaseDropdown },\n props: {\n /** An array of numbers that represents the number of columns to render. */\n columns: {\n type: Array as PropType<number[]>,\n required: true,\n },\n /** The value of the selected columns number. */\n modelValue: Number,\n /** The transition to use for opening and closing the dropdown. */\n animation: [String, Object] as PropType<string | Component>,\n },\n emits: ['update:modelValue'],\n setup(props, { emit, slots }) {\n const $x = use$x()\n\n const ariaLabels = useAccessibilityLabels('baseColumnPickerDropdown')\n\n const providedSelectedColumns = computed(() => props.modelValue ?? props.columns[0])\n const selectedColumns = ref(providedSelectedColumns.value)\n\n /**\n * Assigns `selectedColumns` value and emits `ColumnsNumberProvided`.\n *\n * @param column - Column number provided.\n */\n function emitColumnsNumberProvided(column: number) {\n selectedColumns.value = column\n $x.emit('ColumnsNumberProvided', column)\n }\n\n /**\n * Emits `update:modelValue` with the column selected.\n *\n * @param column - Column number selected.\n */\n function emitUpdateModelValue(column: number) {\n if (props.modelValue !== column) {\n emit('update:modelValue', column)\n }\n }\n\n watch(providedSelectedColumns, emitColumnsNumberProvided)\n watch(selectedColumns, emitUpdateModelValue)\n\n $x.on('ColumnsNumberProvided', false).subscribe(column => (selectedColumns.value = column))\n\n /**\n * Synchronizes the columns number before mounting the component. If the real number of selected\n * columns equals the provided columns, it emits the event to sync it with every other component.\n * If it is not equal it means that the user has already selected a number of columns, so we emit\n * a `update:modelValue` event so developers can sync the provided value.\n */\n onBeforeMount(() => {\n if (selectedColumns.value === providedSelectedColumns.value) {\n emitColumnsNumberProvided(selectedColumns.value)\n } else {\n emitUpdateModelValue(selectedColumns.value)\n }\n })\n\n /**\n * Emits a {@link XEventsTypes.UserClickedColumnPicker} and\n * {@link XEventsTypes.ColumnsNumberProvided} events.\n *\n * @param column - Column number payload.\n */\n function emitEvents(column: number) {\n $x.emit('UserClickedColumnPicker', column)\n $x.emit('ColumnsNumberProvided', column)\n }\n\n return {\n ariaLabels,\n emitEvents,\n hasToggleSlot: !!slots.toggle,\n selectedColumns,\n }\n },\n})\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nAn event that the component will emit:\n\n- [`UserClickedColumnPicker`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event is emitted after the user clicks an item in the dropdown. The event payload is the\n number of columns that the clicked item represents.\n- [`ColumnsNumberProvided`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event is emitted on component mount, and whenever the value changes. The event payload is the\n current `selectedColumns` value.\n\n## Examples\n\nColumn picker dropdown component renders a dropdown component which options are the different\ncolumns you can set for a grid.\n\n### Usage\n\nNotice that the slots provided match with the `BaseDropdown` component. The `item` slot is required\nunlike the `toggle`, which renders the same `item` slot defined by default.\n\n#### Default usage\n\n```vue live\n<template>\n <BaseColumnPickerDropdown v-model=\"selectedColumns\" :columns=\"[2, 4, 6]\">\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseColumnPickerDropdown>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerDropdown from '@empathyco/x-components/js/components/column-picker/base-column-picker-dropdown.vue'\n\nconst selectedColumns = ref(2)\n</script>\n```\n\n#### Customizing toggle button\n\n```vue live\n<template>\n <BaseColumnPickerDropdown v-model=\"selectedColumns\" :columns=\"[2, 4, 6]\">\n <template #toggle=\"{ item, isOpen }\">Selected: {{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseColumnPickerDropdown>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerDropdown from '@empathyco/x-components/js/components/column-picker/base-column-picker-dropdown.vue'\n\nconst selectedColumns = ref(2)\n</script>\n```\n\n#### Using it without v-model / value\n\nThe component emits an X Event, `UserClickedColumnPicker`, on column change and it also listens to\nthat event from outside, so you don't need to store the current column value to keep it synchronized\nwith other column pickers.\n\n```vue live\n<template>\n <BaseColumnPickerDropdown :columns=\"[2, 4, 6]\">\n <template #toggle=\"{ item, isOpen }\">Selected: {{ item }} {{ isOpen ? '🔼' : '🔽' }}️</template>\n <template #item=\"{ item, isSelected, isHighlighted }\">\n <span v-if=\"isHighlighted\">🟢</span>\n <span v-if=\"isSelected\">✅</span>\n <span>{{ item }}</span>\n </template>\n </BaseColumnPickerDropdown>\n</template>\n\n<script setup>\nimport BaseColumnPickerDropdown from '@empathyco/x-components/js/components/column-picker/base-column-picker-dropdown.vue'\n</script>\n```\n</docs>\n"],"names":[],"mappings":";;;;;;;;;;;;AAsCA;;;;;;;;AAQE;AACF,gBAAe,eAAe,CAAC;AAC7B,IAAA,IAAI,EAAE,0BAA0B;IAChC,UAAU,EAAE,EAAE,YAAW,EAAG;AAC5B,IAAA,KAAK,EAAE;;AAEL,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,KAA2B;AACjC,YAAA,QAAQ,EAAE,IAAI;AACf,SAAA;;AAED,QAAA,UAAU,EAAE,MAAM;;AAElB,QAAA,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,CAAiC;AAC5D,KAAA;IACD,KAAK,EAAE,CAAC,mBAAmB,CAAC;AAC5B,IAAA,KAAK,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,KAAI,EAAG,EAAA;AAC1B,QAAA,MAAM,EAAC,GAAI,KAAK,EAAC;AAEjB,QAAA,MAAM,UAAS,GAAI,sBAAsB,CAAC,0BAA0B,CAAA;AAEpE,Q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E,CAAC,CAAC,KAAK,CAAC,MAAM;YAC7B,eAAe;SACjB;IACF,CAAC;AACF,CAAA,CAAA;;;;"}
|
|
@@ -23,7 +23,7 @@ function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
|
|
|
23
23
|
"data-test": "column-picker-button",
|
|
24
24
|
"aria-pressed": isSelected.toString(),
|
|
25
25
|
events,
|
|
26
|
-
"aria-label":
|
|
26
|
+
"aria-label": _ctx.ariaLabels?.button(column),
|
|
27
27
|
role: "listitem"
|
|
28
28
|
}, {
|
|
29
29
|
default: withCtx(() => [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-column-picker-list.vue.js","sources":["../../../../src/components/column-picker/base-column-picker-list.vue"],"sourcesContent":["<template>\n <div class=\"x-column-picker-list xds:button-group\" data-test=\"column-picker-list\" role=\"list\">\n <template\n v-for=\"({ column, cssClasses, events, isSelected }, index) in columnsWithCssClasses\"\n :key=\"column\"\n >\n <BaseEventButton\n class=\"x-column-picker-list__button xds:button\"\n :class=\"[buttonClass, cssClasses]\"\n data-test=\"column-picker-button\"\n :aria-pressed=\"isSelected.toString()\"\n :events=\"events\"\n :aria-label=\"
|
|
1
|
+
{"version":3,"file":"base-column-picker-list.vue.js","sources":["../../../../src/components/column-picker/base-column-picker-list.vue"],"sourcesContent":["<template>\n <div class=\"x-column-picker-list xds:button-group\" data-test=\"column-picker-list\" role=\"list\">\n <template\n v-for=\"({ column, cssClasses, events, isSelected }, index) in columnsWithCssClasses\"\n :key=\"column\"\n >\n <BaseEventButton\n class=\"x-column-picker-list__button xds:button\"\n :class=\"[buttonClass, cssClasses]\"\n data-test=\"column-picker-button\"\n :aria-pressed=\"isSelected.toString()\"\n :events=\"events\"\n :aria-label=\"ariaLabels?.button!(column)\"\n role=\"listitem\"\n >\n <!--\n @slot Customized Column Picker Button content. Specifying a slot with the column value\n will result in the column using that slot composition to render.\n @binding {number} column - Columns Number to pick.\n @binding {boolean} isSelected - True if the columns number are the chosen value.\n -->\n <slot v-bind=\"{ column, isSelected }\">\n {{ column }}\n </slot>\n </BaseEventButton>\n\n <!--\n @slot Customized Column Picker divider. Specify an element to act as divider for\n the items in the column picker. Empty by default.\n -->\n <slot v-if=\"index !== columnsWithCssClasses.length - 1\" name=\"divider\"></slot>\n </template>\n </div>\n</template>\n\n<script lang=\"ts\">\nimport type { PropType } from 'vue'\nimport type { VueCSSClasses } from '../../utils/types'\nimport type { XEventsTypes } from '../../wiring'\nimport { computed, defineComponent, onBeforeMount, ref, watch } from 'vue'\nimport { useAccessibilityLabels } from '../../composables'\nimport { use$x } from '../../composables/use-$x'\nimport BaseEventButton from '../base-event-button.vue'\n\nexport interface ColumnPickerItem {\n column: number\n cssClasses: VueCSSClasses\n events: Partial<XEventsTypes>\n isSelected: boolean\n}\n\n/**\n * Column picker list component renders a list of buttons to choose the columns number.\n *\n * Additionally, this component exposes the following props to modify the classes of the\n * elements: `buttonClass`.\n *\n * @public\n */\nexport default defineComponent({\n name: 'BaseColumnPickerList',\n components: { BaseEventButton },\n props: {\n /** An array of numbers that represents the number of columns to render. */\n columns: {\n type: Array as PropType<number[]>,\n required: true,\n },\n /** The value of the selected columns number. */\n modelValue: Number,\n /** Class inherited by each button. */\n buttonClass: String,\n },\n emits: ['update:modelValue'],\n setup(props, { emit }) {\n const $x = use$x()\n\n const ariaLabels = useAccessibilityLabels('baseColumnPickerList')\n\n const providedSelectedColumns = computed(() => props.modelValue ?? props.columns[0])\n const selectedColumns = ref(providedSelectedColumns.value)\n\n /**\n * Assigns `selectedColumns` value and emits `ColumnsNumberProvided`.\n *\n * @param column - Column number provided.\n */\n function emitColumnsNumberProvided(column: number) {\n selectedColumns.value = column\n $x.emit('ColumnsNumberProvided', column)\n }\n\n /**\n * Emits `update:modelValue` with the column selected.\n *\n * @param column - Column number selected.\n */\n function emitUpdateModelValue(column: number) {\n if (props.modelValue !== column) {\n emit('update:modelValue', column)\n }\n }\n\n watch(providedSelectedColumns, emitColumnsNumberProvided)\n watch(selectedColumns, emitUpdateModelValue)\n\n $x.on('ColumnsNumberProvided', false).subscribe(column => (selectedColumns.value = column))\n\n /**\n * Synchronizes the columns number before mounting the component. If the real number of selected\n * columns equals the provided columns, it emits the event to sync it with every other component.\n * If it is not equal it means that the user has already selected a number of columns, so we emit\n * a `update:modelValue` event so developers can sync the provided value.\n */\n onBeforeMount(() => {\n if (selectedColumns.value === providedSelectedColumns.value) {\n emitColumnsNumberProvided(selectedColumns.value)\n } else {\n emitUpdateModelValue(selectedColumns.value)\n }\n })\n\n /**\n * Maps the column to an object containing: the `column` and `CSS classes`.\n *\n * @returns An array of objects containing the column number and CSS classes.\n */\n const columnsWithCssClasses = computed<ColumnPickerItem[]>(() =>\n props.columns.map(column => ({\n column,\n cssClasses: [\n `x-column-picker-list__button--${column}-cols`,\n { 'xds:selected': selectedColumns.value === column },\n ],\n isSelected: selectedColumns.value === column,\n events: {\n UserClickedColumnPicker: column,\n ColumnsNumberProvided: column,\n },\n })),\n )\n\n return { ariaLabels, columnsWithCssClasses }\n },\n})\n</script>\n\n<docs lang=\"mdx\">\n## Examples\n\nThis component renders a list of elements in different slots depending on the columns prop. Each\nbutton emits the needed events to sync other instances of column pickers or grids with the\nnumber of columns being selected when clicked.\n\n### Default usage\n\nIt is required to send the columns prop.\n\n```vue live\n<template>\n <BaseColumnPickerList :columns=\"columns\" />\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerList from '@empathyco/x-components/js/components/column-picker/base-column-picker-list.vue'\n\nconst columns = ref([2, 4, 6])\n</script>\n```\n\n### Using v-model\n\nIt is possible to do two-way binding in order to synchronize the value with the parent. It will be\nupdated if the value changes or if the parent changes it.\n\n```vue live\n<template>\n <BaseColumnPickerList :columns=\"columns\" v-model=\"selectedColumns\" />\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerList from '@empathyco/x-components/js/components/column-picker/base-column-picker-list.vue'\n\nconst columns = ref([2, 4, 6])\nconst selectedColumns = ref(4)\n</script>\n```\n\n### Customized usage\n\n#### Overriding the slots\n\nIt is possible to override the column picker button content.\n\n```vue live\n<template>\n <BaseColumnPickerList :columns=\"columns\">\n <template #default=\"{ column, isSelected }\">\n <span>{{ column }} {{ isSelected ? '🟢' : '' }}</span>\n </template>\n </BaseColumnPickerList>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerList from '@empathyco/x-components/js/components/column-picker/base-column-picker-list.vue'\n\nconst columns = ref([2, 4, 6])\n</script>\n```\n\nIt is also possible to add a divider element between the column picker buttons by overriding the\n`divider` slot.\n\n```vue live\n<template>\n <BaseColumnPickerList :columns=\"columns\">\n <template #divider>\n <ChevronRightIcon aria-hidden=\"true\" />\n </template>\n </BaseColumnPickerList>\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerList from '@empathyco/x-components/js/components/column-picker/base-column-picker-list.vue'\nimport ChevronRightIcon from '@empathyco/x-components/js/components/icons/chevron-right.vue'\n\nconst columns = ref([2, 4, 6])\n</script>\n```\n\n#### Customizing the buttons with classes\n\nThe `buttonClass` prop can be used to add classes to the buttons.\n\n```vue live\n<template>\n <BaseColumnPickerList :columns=\"columns\" buttonClass=\"xds:button-circle\" />\n</template>\n\n<script setup>\nimport { ref } from 'vue'\nimport BaseColumnPickerList from '@empathyco/x-components/js/components/column-picker/base-column-picker-list.vue'\n\nconst columns = ref([2, 4, 6])\n</script>\n```\n\n## Events\n\nA list of events that the component will emit:\n\n- [`UserClickedColumnPicker`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event is emitted after the user clicks an item. The event payload is the number of columns\n that the clicked item represents.\n- [`ColumnsNumberProvided`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts):\n the event is emitted on component mount. The event payload is the current `selectedColumns` value.\n</docs>\n"],"names":["_openBlock","_createElementBlock","_Fragment","_renderList","_createVNode","_normalizeClass","_renderSlot","_mergeProps","_createTextVNode","_createCommentVNode"],"mappings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 'vue';
|
|
2
|
+
import '../../composables/create-use-device.js';
|
|
2
3
|
import { use$x } from '../../composables/use-_x.js';
|
|
4
|
+
import { useAccessibilityLabels } from '../../composables/use-accessibility-labels.js';
|
|
5
|
+
import 'vuex';
|
|
6
|
+
import '../../plugins/x-bus.js';
|
|
7
|
+
import '@empathyco/x-utils';
|
|
8
|
+
import '../../plugins/x-plugin.js';
|
|
9
|
+
import '@vueuse/core';
|
|
10
|
+
import 'rxjs';
|
|
3
11
|
import BaseEventButton from '../base-event-button.vue.js';
|
|
4
12
|
|
|
5
13
|
/**
|
|
@@ -27,6 +35,7 @@ var _sfc_main = defineComponent({
|
|
|
27
35
|
emits: ['update:modelValue'],
|
|
28
36
|
setup(props, { emit }) {
|
|
29
37
|
const $x = use$x();
|
|
38
|
+
const ariaLabels = useAccessibilityLabels('baseColumnPickerList');
|
|
30
39
|
const providedSelectedColumns = computed(() => props.modelValue ?? props.columns[0]);
|
|
31
40
|
const selectedColumns = ref(providedSelectedColumns.value);
|
|
32
41
|
/**
|
|
@@ -82,7 +91,7 @@ var _sfc_main = defineComponent({
|
|
|
82
91
|
ColumnsNumberProvided: column,
|
|
83
92
|
},
|
|
84
93
|
})));
|
|
85
|
-
return { columnsWithCssClasses };
|
|
94
|
+
return { ariaLabels, columnsWithCssClasses };
|
|
86
95
|
},
|
|
87
96
|
});
|
|
88
97
|
|