element-plus
Version:
A Component Library for Vue 3
1 lines • 30.8 kB
Source Map (JSON)
{"version":3,"file":"cascader2.mjs","names":[],"sources":["../../../../../../packages/components/cascader/src/cascader.vue"],"sourcesContent":["<template>\n <el-tooltip\n ref=\"tooltipRef\"\n :visible=\"popperVisible\"\n :teleported=\"teleported\"\n :popper-class=\"[nsCascader.e('dropdown'), popperClass!]\"\n :popper-style=\"popperStyle\"\n :popper-options=\"popperOptions\"\n :fallback-placements=\"fallbackPlacements\"\n :stop-popper-mouse-event=\"false\"\n :gpu-acceleration=\"false\"\n :placement=\"placement\"\n :transition=\"`${nsCascader.namespace.value}-zoom-in-top`\"\n :effect=\"effect\"\n pure\n :persistent=\"persistent\"\n @hide=\"hideSuggestionPanel\"\n >\n <template #default>\n <div\n ref=\"wrapperRef\"\n v-clickoutside:[contentRef]=\"handleClickOutside\"\n :class=\"cascaderKls\"\n :style=\"cascaderStyle\"\n @click=\"() => togglePopperVisible(readonly ? undefined : true)\"\n @keydown=\"handleKeyDown\"\n @mouseenter=\"inputHover = true\"\n @mouseleave=\"inputHover = false\"\n >\n <el-input\n ref=\"inputRef\"\n v-model=\"inputValue\"\n :placeholder=\"currentPlaceholder\"\n :readonly=\"readonly\"\n :disabled=\"isDisabled\"\n :validate-event=\"false\"\n :size=\"realSize\"\n :class=\"inputClass\"\n :tabindex=\"multiple && filterable && !isDisabled ? -1 : undefined\"\n @compositionstart=\"handleComposition\"\n @compositionupdate=\"handleComposition\"\n @compositionend=\"handleComposition\"\n @input=\"handleInput\"\n >\n <template v-if=\"$slots.prefix\" #prefix>\n <slot name=\"prefix\" />\n </template>\n <template #suffix>\n <el-icon\n v-if=\"clearBtnVisible\"\n key=\"clear\"\n :class=\"[nsInput.e('icon'), 'icon-circle-close']\"\n @click.stop=\"handleClear\"\n >\n <component :is=\"clearIcon\" />\n </el-icon>\n <el-icon\n v-else\n key=\"arrow-down\"\n :class=\"cascaderIconKls\"\n @click.stop=\"togglePopperVisible()\"\n >\n <arrow-down />\n </el-icon>\n </template>\n </el-input>\n\n <div\n v-if=\"multiple\"\n ref=\"tagWrapper\"\n :class=\"[\n nsCascader.e('tags'),\n nsCascader.is('validate', Boolean(validateState)),\n ]\"\n >\n <slot name=\"tag\" :data=\"tags\" :delete-tag=\"deleteTag\">\n <el-tag\n v-for=\"tag in showTagList\"\n :key=\"tag.key\"\n :type=\"tagType\"\n :size=\"tagSize\"\n :effect=\"tagEffect\"\n :hit=\"tag.hitState\"\n :closable=\"tag.closable\"\n disable-transitions\n @close=\"deleteTag(tag)\"\n >\n <span>{{ tag.text }}</span>\n </el-tag>\n </slot>\n <el-tooltip\n v-if=\"collapseTags && tags.length > maxCollapseTags\"\n ref=\"tagTooltipRef\"\n :disabled=\"popperVisible || !collapseTagsTooltip\"\n :fallback-placements=\"['bottom', 'top', 'right', 'left']\"\n placement=\"bottom\"\n :popper-class=\"popperClass\"\n :popper-style=\"popperStyle\"\n :effect=\"effect\"\n :persistent=\"persistent\"\n >\n <template #default>\n <el-tag\n :closable=\"false\"\n :size=\"tagSize\"\n :type=\"tagType\"\n :effect=\"tagEffect\"\n disable-transitions\n >\n <span :class=\"nsCascader.e('tags-text')\">\n + {{ tags.length - maxCollapseTags }}\n </span>\n </el-tag>\n </template>\n <template #content>\n <el-scrollbar :max-height=\"maxCollapseTagsTooltipHeight\">\n <div :class=\"nsCascader.e('collapse-tags')\">\n <div\n v-for=\"(tag, idx) in collapseTagList\"\n :key=\"idx\"\n :class=\"nsCascader.e('collapse-tag')\"\n >\n <el-tag\n :key=\"tag.key\"\n class=\"in-tooltip\"\n :type=\"tagType\"\n :size=\"tagSize\"\n :effect=\"tagEffect\"\n :hit=\"tag.hitState\"\n :closable=\"tag.closable\"\n disable-transitions\n @close=\"deleteTag(tag)\"\n >\n <span>{{ tag.text }}</span>\n </el-tag>\n </div>\n </div>\n </el-scrollbar>\n </template>\n </el-tooltip>\n <input\n v-if=\"filterable && !isDisabled\"\n v-model=\"searchInputValue\"\n type=\"text\"\n :class=\"nsCascader.e('search-input')\"\n :placeholder=\"presentText ? '' : inputPlaceholder\"\n @input=\"(e) => handleInput(searchInputValue, e as InputEvent)\"\n @click.stop=\"togglePopperVisible(true)\"\n @keydown.delete=\"handleDelete\"\n @compositionstart=\"handleComposition\"\n @compositionupdate=\"handleComposition\"\n @compositionend=\"handleComposition\"\n />\n </div>\n </div>\n </template>\n\n <template #content>\n <div v-if=\"$slots.header\" :class=\"nsCascader.e('header')\" @click.stop>\n <slot name=\"header\" />\n </div>\n <el-cascader-panel\n v-show=\"!filtering\"\n ref=\"cascaderPanelRef\"\n v-model=\"checkedValue\"\n :options=\"options\"\n :props=\"props.props\"\n :border=\"false\"\n :render-label=\"$slots.default\"\n :virtual-scroll=\"virtualScroll\"\n :item-size=\"itemSize\"\n :height=\"height\"\n @expand-change=\"handleExpandChange\"\n @close=\"$nextTick(() => togglePopperVisible(false))\"\n >\n <template #empty>\n <slot name=\"empty\" />\n </template>\n </el-cascader-panel>\n <template v-if=\"filterable\">\n <el-scrollbar\n v-if=\"!virtualScroll\"\n v-show=\"filtering\"\n :ref=\"(ref) => (suggestionPanel = (ref as ScrollbarInstance)?.$el)\"\n tag=\"ul\"\n :class=\"nsCascader.e('suggestion-panel')\"\n :wrap-class=\"nsCascader.e('suggestion-wrap')\"\n :view-class=\"nsCascader.e('suggestion-list')\"\n @keydown=\"handleSuggestionKeyDown\"\n >\n <template v-if=\"suggestions.length\">\n <li\n v-for=\"item in suggestions\"\n :key=\"item.uid\"\n :class=\"[\n nsCascader.e('suggestion-item'),\n nsCascader.is('checked', item.checked),\n ]\"\n :tabindex=\"-1\"\n @click=\"handleSuggestionClick(item)\"\n >\n <slot name=\"suggestion-item\" :item=\"item\">\n <span>{{ item.text }}</span>\n <el-icon v-if=\"item.checked\">\n <check />\n </el-icon>\n </slot>\n </li>\n </template>\n <slot v-else name=\"empty\">\n <li :class=\"nsCascader.e('empty-text')\">\n {{ t('el.cascader.noMatch') }}\n </li>\n </slot>\n </el-scrollbar>\n <div\n v-else\n v-show=\"filtering\"\n ref=\"suggestionPanel\"\n :class=\"nsCascader.e('suggestion-panel')\"\n @keydown=\"handleSuggestionKeyDown\"\n >\n <el-fixed-size-list\n v-show=\"suggestions.length\"\n ref=\"suggestionVirtualListRef\"\n :height=\"clampedSuggestionListHeight\"\n :item-size=\"itemSize\"\n :data=\"suggestions\"\n :total=\"suggestions.length\"\n :class-name=\"nsCascader.e('suggestion-list')\"\n inner-element=\"ul\"\n :inner-width=\"suggestionListWidth\"\n >\n <template #default=\"{ data, index, style }\">\n <li\n :id=\"`suggestion-${data[index].uid}`\"\n :key=\"data[index].uid\"\n :data-suggestion-index=\"index\"\n :class=\"[\n nsCascader.e('suggestion-item'),\n nsCascader.is('checked', data[index].checked),\n ]\"\n :tabindex=\"-1\"\n :style=\"style\"\n @click=\"handleSuggestionClick(data[index])\"\n >\n <slot name=\"suggestion-item\" :item=\"data[index]\">\n <span>{{ data[index].text }}</span>\n <el-icon v-if=\"data[index].checked\">\n <check />\n </el-icon>\n </slot>\n </li>\n </template>\n </el-fixed-size-list>\n <slot v-if=\"!suggestions.length\" name=\"empty\">\n <ul :class=\"nsCascader.e('suggestion-list')\">\n <li :class=\"nsCascader.e('empty-text')\">\n {{ t('el.cascader.noMatch') }}\n </li>\n </ul>\n </slot>\n </div>\n </template>\n <div v-if=\"$slots.footer\" :class=\"nsCascader.e('footer')\" @click.stop>\n <slot name=\"footer\" />\n </div>\n </template>\n </el-tooltip>\n</template>\n\n<script lang=\"ts\" setup>\nimport {\n computed,\n markRaw,\n nextTick,\n onMounted,\n ref,\n useAttrs,\n useSlots,\n watch,\n} from 'vue'\nimport { clamp, cloneDeep } from 'lodash-unified'\nimport { useCssVar, useDebounceFn, useResizeObserver } from '@vueuse/core'\nimport {\n NOOP,\n focusNode,\n getEventCode,\n getSibling,\n isClient,\n isNumber,\n isPromise,\n} from '@element-plus/utils'\nimport ElCascaderPanel, {\n CASCADER_PANEL_HEIGHT,\n CASCADER_PANEL_ITEM_SIZE,\n} from '@element-plus/components/cascader-panel'\nimport ElInput from '@element-plus/components/input'\nimport ElTooltip from '@element-plus/components/tooltip'\nimport ElScrollbar from '@element-plus/components/scrollbar'\nimport { FixedSizeList as ElFixedSizeList } from '@element-plus/components/virtual-list'\nimport ElTag from '@element-plus/components/tag'\nimport ElIcon from '@element-plus/components/icon'\nimport {\n useFormDisabled,\n useFormItem,\n useFormSize,\n} from '@element-plus/components/form'\nimport { ClickOutside as vClickoutside } from '@element-plus/directives'\nimport {\n useComposition,\n useEmptyValues,\n useFocusController,\n useLocale,\n useNamespace,\n} from '@element-plus/hooks'\nimport {\n CHANGE_EVENT,\n EVENT_CODE,\n UPDATE_MODEL_EVENT,\n} from '@element-plus/constants'\nimport { ArrowDown, Check, CircleClose } from '@element-plus/icons-vue'\nimport { cascaderEmits } from './cascader'\n\nimport type { Options } from '@element-plus/components/popper'\nimport type { ComputedRef, StyleValue } from 'vue'\nimport type { TooltipInstance } from '@element-plus/components/tooltip'\nimport type { InputInstance } from '@element-plus/components/input'\nimport type { ScrollbarInstance } from '@element-plus/components/scrollbar'\nimport type { FixedSizeListInstance } from '@element-plus/components/virtual-list'\nimport type {\n CascaderNode,\n CascaderPanelInstance,\n CascaderValue,\n Tag,\n} from '@element-plus/components/cascader-panel'\nimport type { CascaderComponentProps } from './cascader'\n\nconst SUGGESTION_ITEM_EXTRA_WIDTH = 34 // span margin-right (10px) + check icon width (24px)\n\nconst popperOptions: Partial<Options> = {\n modifiers: [\n {\n name: 'arrowPosition',\n enabled: true,\n phase: 'main',\n fn: ({ state }) => {\n const { modifiersData, placement } = state\n if (['right', 'left', 'bottom', 'top'].includes(placement)) return\n if (modifiersData.arrow) {\n modifiersData.arrow.x = 35\n }\n },\n requires: ['arrow'],\n },\n ],\n}\n\ndefineOptions({\n name: 'ElCascader',\n})\n\nconst props = withDefaults(defineProps<CascaderComponentProps>(), {\n options: () => [],\n props: () => ({}),\n disabled: undefined,\n clearIcon: markRaw(CircleClose),\n filterMethod: (node, keyword) => node.text.includes(keyword),\n separator: ' / ',\n showAllLevels: true,\n maxCollapseTags: 1,\n debounce: 300,\n beforeFilter: () => true,\n placement: 'bottom-start',\n fallbackPlacements: () => [\n 'bottom-start',\n 'bottom',\n 'top-start',\n 'top',\n 'right',\n 'left',\n ],\n teleported: true,\n effect: 'light',\n tagType: 'info',\n tagEffect: 'light',\n validateEvent: true,\n persistent: true,\n showCheckedStrategy: 'child',\n showPrefix: true,\n popperStyle: undefined,\n valueOnClear: undefined,\n itemSize: CASCADER_PANEL_ITEM_SIZE,\n height: CASCADER_PANEL_HEIGHT,\n})\nconst emit = defineEmits(cascaderEmits)\nconst attrs = useAttrs()\nconst slots = useSlots()\n\nlet inputInitialHeight = 0\nlet pressDeleteCount = 0\n\nconst nsCascader = useNamespace('cascader')\nconst nsInput = useNamespace('input')\nconst sizeMapPadding = {\n small: 7,\n default: 11,\n large: 15,\n}\n\nconst { t } = useLocale()\nconst { formItem } = useFormItem()\nconst isDisabled = useFormDisabled()\nconst { valueOnClear } = useEmptyValues(props)\nconst { isComposing, handleComposition } = useComposition({\n afterComposition(event) {\n const text = (event.target as HTMLInputElement)?.value\n handleInput(text)\n },\n})\n\nconst tooltipRef = ref<TooltipInstance>()\nconst tagTooltipRef = ref<TooltipInstance>()\nconst inputRef = ref<InputInstance>()\nconst tagWrapper = ref<HTMLDivElement>()\nconst cascaderPanelRef = ref<CascaderPanelInstance>()\nconst suggestionPanel = ref<HTMLElement>()\nconst suggestionVirtualListRef = ref<FixedSizeListInstance>()\nconst popperVisible = ref(false)\nconst inputHover = ref(false)\nconst filtering = ref(false)\nconst inputValue = ref('')\nconst searchInputValue = ref('')\nconst tags = ref<Tag[]>([])\nconst suggestions = ref<CascaderNode[]>([])\nconst suggestionListWidth = ref<string | number>('100%')\nconst hasCustomSuggestionItemSlot = computed(() => !!slots['suggestion-item'])\nconst clampedSuggestionListHeight = computed(() =>\n clamp(suggestions.value.length * props.itemSize, props.itemSize, props.height)\n)\n\nconst showTagList = computed(() => {\n if (!props.props.multiple) {\n return []\n }\n return props.collapseTags\n ? tags.value.slice(0, props.maxCollapseTags)\n : tags.value\n})\n\nconst collapseTagList = computed(() => {\n if (!props.props.multiple) {\n return []\n }\n return props.collapseTags ? tags.value.slice(props.maxCollapseTags) : []\n})\n\nconst cascaderStyle = computed(() => {\n return attrs.style as StyleValue\n})\n\nconst inputPlaceholder = computed(\n () => props.placeholder ?? t('el.cascader.placeholder')\n)\nconst currentPlaceholder = computed(() =>\n searchInputValue.value || tags.value.length > 0 || isComposing.value\n ? ''\n : inputPlaceholder.value\n)\nconst realSize = useFormSize()\nconst tagSize = computed(() =>\n realSize.value === 'small' ? 'small' : 'default'\n)\nconst multiple = computed(() => !!props.props.multiple)\nconst readonly = computed(() => !props.filterable || multiple.value)\nconst searchKeyword = computed(() =>\n multiple.value ? searchInputValue.value : inputValue.value\n)\nconst checkedNodes: ComputedRef<CascaderNode[]> = computed(\n () => cascaderPanelRef.value?.checkedNodes || []\n)\n\nconst { wrapperRef, isFocused, handleBlur } = useFocusController(inputRef, {\n disabled: isDisabled,\n beforeBlur(event) {\n return (\n tooltipRef.value?.isFocusInsideContent(event) ||\n tagTooltipRef.value?.isFocusInsideContent(event)\n )\n },\n afterBlur() {\n if (props.validateEvent) {\n formItem?.validate?.('blur').catch(NOOP)\n }\n },\n})\n\nconst clearBtnVisible = computed(() => {\n if (\n !props.clearable ||\n isDisabled.value ||\n filtering.value ||\n (!inputHover.value && !isFocused.value)\n )\n return false\n\n return !!checkedNodes.value.length\n})\nconst presentText = computed(() => {\n const { showAllLevels, separator } = props\n const nodes = checkedNodes.value\n return nodes.length\n ? multiple.value\n ? ''\n : nodes[0].calcText(showAllLevels, separator)\n : ''\n})\n\nconst validateState = computed(() => formItem?.validateState || '')\n\nconst checkedValue = computed<CascaderValue>({\n get() {\n return cloneDeep(props.modelValue) as CascaderValue\n },\n set(val) {\n // https://github.com/element-plus/element-plus/issues/17647\n const value = val ?? valueOnClear.value\n emit(UPDATE_MODEL_EVENT, value)\n emit(CHANGE_EVENT, value)\n if (props.validateEvent) {\n formItem?.validate('change').catch(NOOP)\n }\n },\n})\n\nconst cascaderKls = computed(() => {\n return [\n nsCascader.b(),\n nsCascader.m(realSize.value),\n nsCascader.is('disabled', isDisabled.value),\n attrs.class,\n ]\n})\n\nconst cascaderIconKls = computed(() => {\n return [\n nsInput.e('icon'),\n 'icon-arrow-down',\n nsCascader.is('reverse', popperVisible.value),\n ]\n})\n\nconst inputClass = computed(() => nsCascader.is('focus', isFocused.value))\n\nconst contentRef = computed(() => {\n return tooltipRef.value?.popperRef?.contentRef\n})\n\nconst handleClickOutside = (event: Event) => {\n if (isFocused.value) {\n const _event = new FocusEvent('blur', event)\n handleBlur(_event)\n }\n togglePopperVisible(false)\n}\n\nconst togglePopperVisible = (visible?: boolean) => {\n if (isDisabled.value) return\n\n visible = visible ?? !popperVisible.value\n\n if (visible !== popperVisible.value) {\n popperVisible.value = visible\n inputRef.value?.input?.setAttribute('aria-expanded', `${visible}`)\n\n if (visible) {\n updatePopperPosition()\n cascaderPanelRef.value &&\n nextTick(cascaderPanelRef.value.scrollToExpandingNode)\n } else if (props.filterable) {\n syncPresentTextValue()\n }\n\n emit('visibleChange', visible)\n }\n}\n\nconst updatePopperPosition = () => {\n nextTick(() => {\n tooltipRef.value?.updatePopper()\n })\n}\nconst hideSuggestionPanel = () => {\n filtering.value = false\n}\n\nconst genTag = (node: CascaderNode): Tag => {\n const { showAllLevels, separator } = props\n return {\n node,\n key: node.uid,\n text: node.calcText(showAllLevels, separator),\n hitState: false,\n closable: !isDisabled.value && !node.isDisabled,\n }\n}\n\nconst deleteTag = (tag: Tag) => {\n const node = tag.node as CascaderNode\n node.doCheck(false)\n cascaderPanelRef.value?.calculateCheckedValue()\n emit('removeTag', node.valueByOption)\n}\n\nconst getStrategyCheckedNodes = (): CascaderNode[] => {\n switch (props.showCheckedStrategy) {\n case 'child':\n return checkedNodes.value\n case 'parent': {\n const clickedNodes = getCheckedNodes(false)\n const clickedNodesValue = clickedNodes!.map((o) => o.value)\n const parentNodes = clickedNodes!.filter(\n (o) => !o.parent || !clickedNodesValue.includes(o.parent.value)\n )\n return parentNodes\n }\n default:\n return []\n }\n}\n\nconst calculatePresentTags = () => {\n if (!multiple.value) return\n\n const nodes = getStrategyCheckedNodes()\n\n const allTags: Tag[] = []\n nodes.forEach((node) => allTags.push(genTag(node)))\n tags.value = allTags\n}\n\nconst calculateSuggestions = () => {\n const { filterMethod, showAllLevels, separator } = props\n const res = cascaderPanelRef.value\n ?.getFlattedNodes(!props.props.checkStrictly)\n ?.filter((node) => {\n if (node.isDisabled) return false\n node.calcText(showAllLevels, separator)\n return filterMethod(node, searchKeyword.value)\n })\n\n if (multiple.value) {\n tags.value.forEach((tag) => {\n tag.hitState = false\n })\n }\n\n filtering.value = true\n suggestions.value = res!\n nextTick(() => {\n if (props.virtualScroll && suggestions.value.length > 0) {\n suggestionVirtualListRef.value?.scrollToItem(0)\n }\n updateStyle()\n })\n updatePopperPosition()\n}\n\nconst getSuggestionPanelEl = (selector?: string): HTMLElement | undefined => {\n const el = suggestionPanel.value\n return selector ? (el?.querySelector(selector) ?? undefined) : el\n}\n\nconst focusFirstNode = () => {\n let firstNode: HTMLElement | undefined\n\n if (filtering.value && suggestionPanel.value) {\n firstNode = getSuggestionPanelEl(`.${nsCascader.e('suggestion-item')}`)\n } else {\n firstNode = cascaderPanelRef.value?.$el.querySelector(\n `.${nsCascader.b('node')}[tabindex=\"-1\"]`\n )\n }\n\n if (firstNode) {\n firstNode.focus()\n if (\n !filtering.value &&\n firstNode.getAttribute('aria-haspopup') === 'true'\n ) {\n firstNode.click()\n }\n }\n}\n\nconst updateSuggestionPanelWidth = (inputWidth: number) => {\n const suggestionPanelEl = getSuggestionPanelEl()\n if (!suggestionPanelEl) return\n\n const panelWidth = isNumber(props.fitInputWidth)\n ? `${props.fitInputWidth}px`\n : `${inputWidth}px`\n\n const setPanelStyle = (el: HTMLElement) => {\n if (props.fitInputWidth !== false) {\n el.style.width = panelWidth\n el.style.minWidth = ''\n } else {\n el.style.width = ''\n el.style.minWidth = panelWidth\n }\n }\n\n setPanelStyle(suggestionPanelEl)\n\n if (props.virtualScroll) {\n suggestionListWidth.value =\n props.fitInputWidth !== false\n ? panelWidth\n : hasCustomSuggestionItemSlot.value\n ? `${inputWidth}px`\n : `${Math.max(inputWidth, calculateSuggestionMaxWidth())}px`\n return\n }\n\n const suggestionList = getSuggestionPanelEl(\n `.${nsCascader.e('suggestion-list')}`\n )\n if (suggestionList) {\n setPanelStyle(suggestionList)\n }\n}\n\nconst getTagWrapperLeft = () => {\n if (!slots.prefix) return 0\n\n const prefix = inputRef.value?.$el.querySelector(\n `.${nsInput.e('prefix')}`\n ) as HTMLElement | null\n if (!prefix) return 0\n\n const prefixWidth = prefix.getBoundingClientRect().width\n if (prefixWidth <= 0) return 0\n return prefixWidth + sizeMapPadding[realSize.value || 'default']\n}\n\nconst updateStyle = () => {\n const inputInner = inputRef.value?.input\n const inputWrapper = inputRef.value?.$el\n if (!isClient || !inputInner || !inputWrapper) return\n\n if (suggestionPanel.value) {\n updateSuggestionPanelWidth(inputWrapper.getBoundingClientRect().width)\n }\n\n const tagWrapperEl = tagWrapper.value\n if (tagWrapperEl) {\n const height =\n tags.value.length > 0\n ? `${Math.max(tagWrapperEl.offsetHeight, inputInitialHeight) - 2}px`\n : `${inputInitialHeight}px`\n inputInner.style.height = height\n tagWrapperEl.style.left = `${getTagWrapperLeft()}px`\n updatePopperPosition()\n }\n}\n\nconst calculateSuggestionMaxWidth = () => {\n if (hasCustomSuggestionItemSlot.value) return 0\n if (!suggestions.value.length) return 0\n\n const canvas = document.createElement('canvas')\n const ctx = canvas.getContext('2d')\n if (!ctx) return 0\n\n const renderedSuggestion = getSuggestionPanelEl(\n `.${nsCascader.e('suggestion-item')}`\n )\n if (!renderedSuggestion || !isClient) return 0\n\n const style = getComputedStyle(renderedSuggestion)\n const padding =\n Number.parseFloat(style.paddingLeft) + Number.parseFloat(style.paddingRight)\n // Use bold font for all items to ensure width is sufficient\n ctx.font = `bold ${style.fontSize} ${style.fontFamily}`\n\n let maxWidth = 0\n let hasChecked = false\n\n for (const suggestion of suggestions.value) {\n const text = suggestion.text || ''\n const metrics = ctx.measureText(text)\n maxWidth = Math.max(maxWidth, metrics.width)\n if (suggestion.checked && !hasChecked) hasChecked = true\n }\n\n return maxWidth + padding + (hasChecked ? SUGGESTION_ITEM_EXTRA_WIDTH : 0)\n}\n\nconst getCheckedNodes = (leafOnly: boolean) => {\n return cascaderPanelRef.value?.getCheckedNodes(leafOnly)\n}\n\nconst handleExpandChange = (value: CascaderValue) => {\n updatePopperPosition()\n emit('expandChange', value)\n}\n\nconst handleKeyDown = (e: KeyboardEvent) => {\n if (isComposing.value) return\n const code = getEventCode(e)\n\n switch (code) {\n case EVENT_CODE.enter:\n case EVENT_CODE.numpadEnter:\n togglePopperVisible()\n break\n case EVENT_CODE.down:\n togglePopperVisible(true)\n nextTick(focusFirstNode)\n e.preventDefault()\n break\n case EVENT_CODE.esc:\n if (popperVisible.value === true) {\n e.preventDefault()\n e.stopPropagation()\n togglePopperVisible(false)\n }\n break\n case EVENT_CODE.tab:\n togglePopperVisible(false)\n break\n }\n}\n\nconst handleClear = () => {\n cascaderPanelRef.value?.clearCheckedNodes()\n if (!popperVisible.value && props.filterable) {\n syncPresentTextValue()\n }\n togglePopperVisible(false)\n emit('clear')\n}\n\nconst syncPresentTextValue = () => {\n const { value } = presentText\n inputValue.value = value\n searchInputValue.value = value\n}\n\nconst handleSuggestionClick = (node: CascaderNode) => {\n const { checked } = node\n\n if (multiple.value) {\n cascaderPanelRef.value?.handleCheckChange(node, !checked, false)\n } else {\n !checked && cascaderPanelRef.value?.handleCheckChange(node, true, false)\n togglePopperVisible(false)\n }\n}\n\nconst getSuggestionIndexFromTarget = (target: HTMLElement) => {\n const suggestionItem = target.closest<HTMLElement>('[data-suggestion-index]')\n const indexStr = suggestionItem?.dataset.suggestionIndex\n\n if (!indexStr) return -1\n\n const index = Number.parseInt(indexStr, 10)\n if (Number.isNaN(index) || index < 0 || index >= suggestions.value.length) {\n return -1\n }\n\n return index\n}\n\nconst handleSuggestionKeyDown = (e: KeyboardEvent) => {\n const target = e.target as HTMLElement\n const code = getEventCode(e)\n\n switch (code) {\n case EVENT_CODE.up:\n case EVENT_CODE.down: {\n e.preventDefault()\n const distance = code === EVENT_CODE.up ? -1 : 1\n\n if (props.virtualScroll && suggestionVirtualListRef.value) {\n const currentIndex = getSuggestionIndexFromTarget(target)\n if (currentIndex >= 0) {\n const length = suggestions.value.length\n const targetIndex = (currentIndex + distance + length) % length\n\n suggestionVirtualListRef.value.scrollToItem(targetIndex)\n\n nextTick(() => {\n const targetItem = getSuggestionPanelEl(\n `#suggestion-${suggestions.value[targetIndex].uid}`\n )\n targetItem && focusNode(targetItem)\n })\n return\n }\n }\n\n // use DOM-based navigation\n focusNode(\n getSibling(\n target,\n distance,\n `.${nsCascader.e('suggestion-item')}[tabindex=\"-1\"]`\n ) as HTMLElement\n )\n break\n }\n case EVENT_CODE.enter:\n case EVENT_CODE.numpadEnter:\n target.click()\n break\n }\n}\n\nconst handleDelete = () => {\n const lastTag = tags.value[tags.value.length - 1]\n pressDeleteCount = searchInputValue.value ? 0 : pressDeleteCount + 1\n\n if (\n !lastTag ||\n !pressDeleteCount ||\n (props.collapseTags && tags.value.length > 1)\n )\n return\n\n if (lastTag.hitState) {\n deleteTag(lastTag)\n } else {\n lastTag.hitState = true\n }\n}\n\nconst debounce = computed(() => props.debounce)\nconst handleFilter = useDebounceFn(() => {\n const { value } = searchKeyword\n\n if (!value) return\n\n const passed = props.beforeFilter(value)\n\n if (isPromise(passed)) {\n passed.then(calculateSuggestions).catch(() => {\n /* prevent log error */\n })\n } else if (passed !== false) {\n calculateSuggestions()\n } else {\n hideSuggestionPanel()\n }\n}, debounce)\n\nconst handleInput = (val: string, e?: InputEvent) => {\n !popperVisible.value && togglePopperVisible(true)\n\n if (e?.isComposing) return\n\n if (val) {\n handleFilter()\n } else {\n const passed = props.beforeFilter('')\n if (isPromise(passed)) {\n passed.catch(() => {\n /* prevent log error */\n })\n }\n hideSuggestionPanel()\n }\n}\n\nconst getInputInnerHeight = (inputInner: HTMLElement): number =>\n Number.parseFloat(\n useCssVar(nsInput.cssVarName('input-height'), inputInner).value!\n ) - 2\n\nconst focus = () => {\n inputRef.value?.focus()\n}\n\nconst blur = () => {\n inputRef.value?.blur()\n}\n\nwatch(filtering, updatePopperPosition)\n\nwatch(\n [\n checkedNodes,\n isDisabled,\n () => props.collapseTags,\n () => props.maxCollapseTags,\n ],\n calculatePresentTags\n)\n\nwatch(tags, () => {\n nextTick(() => updateStyle())\n})\n\nwatch(realSize, async () => {\n await nextTick()\n const inputInner = inputRef.value!.input!\n inputInitialHeight = getInputInnerHeight(inputInner) || inputInitialHeight\n updateStyle()\n})\n\nwatch(presentText, syncPresentTextValue, { immediate: true })\n\nwatch(\n () => popperVisible.value,\n (val) => {\n if (val && props.props.lazy && props.props.lazyLoad) {\n cascaderPanelRef.value?.loadLazyRootNodes()\n }\n }\n)\n\nonMounted(() => {\n const inputInner = inputRef.value!.input!\n const inputWrapper = inputRef.value!.$el!\n\n const inputInnerHeight = getInputInnerHeight(inputInner)\n\n inputInitialHeight = inputInner.offsetHeight || inputInnerHeight\n useResizeObserver(inputWrapper, updateStyle)\n})\n\ndefineExpose({\n /**\n * @description get an array of currently selected node,(leafOnly) whether only return the leaf checked nodes, default is `false`\n */\n getCheckedNodes,\n /**\n * @description cascader panel ref\n */\n cascaderPanelRef,\n /**\n * @description toggle the visible of popper\n */\n togglePopperVisible,\n /**\n * @description cascader content ref\n */\n contentRef,\n /**\n * @description selected content text\n */\n presentText,\n /** @description focus the input element */\n focus,\n /** @description blur the input element */\n blur,\n})\n</script>\n"],"mappings":""}