hongluan-ui
Version:
Hongluan Component Library for Vue 3
359 lines (356 loc) • 13.6 kB
JavaScript
import { defineComponent, useAttrs as useAttrs$1, ref, computed, onBeforeUnmount, onMounted, openBlock, createBlock, unref, withCtx, createElementVNode, normalizeClass, normalizeStyle, createVNode, createElementBlock, renderSlot, Fragment, renderList, createTextVNode, toDisplayString, withModifiers, mergeProps, withKeys, createSlots } from 'vue';
import { debounce } from 'lodash-unified';
import { onClickOutside } from '@vueuse/core';
import '../../../hooks/index.mjs';
import '../../../utils/index.mjs';
import '../../../constants/index.mjs';
import '../../popper/index.mjs';
import { HlInput } from '../../input/index.mjs';
import { HlScrollbar } from '../../scrollbar/index.mjs';
import { HlTooltip } from '../../tooltip/index.mjs';
import { HlSpinner } from '../../spinner/index.mjs';
import { autocompleteProps, autocompleteEmits } from './autocomplete2.mjs';
import { useAttrs } from '../../../hooks/use-attrs/index.mjs';
import { useConsistentProp } from '../../../hooks/use-consistent-prop/index.mjs';
import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
import { useDeprecateAppendToBody } from '../../popper/src/deprecation.mjs';
import { useId } from '../../../hooks/use-id/index.mjs';
import { isArray } from '@vue/shared';
import { throwError } from '../../../utils/error.mjs';
import { INPUT_EVENT, UPDATE_MODEL_EVENT, CHANGE_EVENT } from '../../../constants/event.mjs';
const COMPONENT_NAME = "Autocomplete";
const __default__ = defineComponent({
name: COMPONENT_NAME,
inheritAttrs: false
});
const _sfc_main = /* @__PURE__ */ defineComponent({
...__default__,
props: autocompleteProps,
emits: autocompleteEmits,
setup(__props, { expose, emit }) {
const props = __props;
const attrs = useAttrs();
const rawAttrs = useAttrs$1();
const { size: inputSize, disabled: inputDisabled, fill: inputFill } = useConsistentProp();
const { namespace } = useNamespace("autocomplete");
const { compatTeleported } = useDeprecateAppendToBody(COMPONENT_NAME, "popperAppendToBody");
const inputRef = ref();
const regionRef = ref();
const popperRef = ref();
const listboxRef = ref();
let readonly = false;
let ignoreFocusEvent = false;
const suggestions = ref([]);
const highlightedIndex = ref(-1);
const dropdownWidth = ref("");
const activated = ref(false);
const suggestionDisabled = ref(false);
const loading = ref(false);
const listboxId = useId();
const styles = computed(() => rawAttrs.style);
const suggestionVisible = computed(() => {
const isValidData = suggestions.value.length > 0;
return (isValidData || loading.value) && activated.value;
});
const suggestionLoading = computed(() => !props.hideLoading && loading.value);
const refInput = computed(() => {
if (inputRef.value) {
return Array.from(inputRef.value.$el.querySelectorAll("input"));
}
return [];
});
const onSuggestionShow = async () => {
if (suggestionVisible.value) {
dropdownWidth.value = `${inputRef.value.$el.offsetWidth}px`;
}
};
const onHide = () => {
highlightedIndex.value = -1;
};
const getData = async (queryString) => {
if (suggestionDisabled.value)
return;
const cb = (suggestionList) => {
loading.value = false;
if (suggestionDisabled.value)
return;
if (isArray(suggestionList)) {
suggestions.value = suggestionList;
highlightedIndex.value = props.highlightFirstItem ? 0 : -1;
} else {
throwError(COMPONENT_NAME, "autocomplete suggestions must be an array");
}
};
loading.value = true;
if (isArray(props.fetchSuggestions)) {
cb(props.fetchSuggestions);
} else {
const result = await props.fetchSuggestions(queryString, cb);
if (isArray(result))
cb(result);
}
};
const debouncedGetData = debounce(getData, props.debounce);
const handleInput = (value) => {
const valuePresented = !!value;
emit(INPUT_EVENT, value);
emit(UPDATE_MODEL_EVENT, value);
suggestionDisabled.value = false;
activated.value || (activated.value = valuePresented);
if (!props.triggerOnFocus && !value) {
suggestionDisabled.value = true;
suggestions.value = [];
return;
}
debouncedGetData(value);
};
const handleMouseDown = (event) => {
var _a;
if (inputDisabled.value)
return;
if (((_a = event.target) == null ? void 0 : _a.tagName) !== "INPUT" || refInput.value.includes(document.activeElement)) {
activated.value = true;
}
};
const handleChange = (value) => {
emit(CHANGE_EVENT, value);
};
const handleFocus = (evt) => {
if (!ignoreFocusEvent) {
activated.value = true;
emit("focus", evt);
if (props.triggerOnFocus && !readonly) {
debouncedGetData(String(props.modelValue));
}
} else {
ignoreFocusEvent = false;
}
};
const handleBlur = (evt) => {
setTimeout(() => {
var _a;
if ((_a = popperRef.value) == null ? void 0 : _a.isFocusInsideContent()) {
ignoreFocusEvent = true;
return;
}
activated.value && close();
emit("blur", evt);
});
};
const handleClear = () => {
activated.value = false;
emit(UPDATE_MODEL_EVENT, "");
emit("clear");
};
const handleKeyEnter = async () => {
if (suggestionVisible.value && highlightedIndex.value >= 0 && highlightedIndex.value < suggestions.value.length) {
handleSelect(suggestions.value[highlightedIndex.value]);
} else if (props.selectWhenUnmatched) {
emit("select", { value: props.modelValue });
suggestions.value = [];
highlightedIndex.value = -1;
}
};
const handleKeyEscape = (evt) => {
if (suggestionVisible.value) {
evt.preventDefault();
evt.stopPropagation();
close();
}
};
const close = () => {
activated.value = false;
};
const focus = () => {
var _a;
(_a = inputRef.value) == null ? void 0 : _a.focus();
};
const blur = () => {
var _a;
(_a = inputRef.value) == null ? void 0 : _a.blur();
};
const handleSelect = async (item) => {
emit(INPUT_EVENT, item[props.valueKey]);
emit(UPDATE_MODEL_EVENT, item[props.valueKey]);
emit("select", item);
suggestions.value = [];
highlightedIndex.value = -1;
};
const highlight = (index) => {
if (!suggestionVisible.value || loading.value)
return;
if (index < 0) {
highlightedIndex.value = -1;
return;
}
if (index >= suggestions.value.length) {
index = suggestions.value.length - 1;
}
const suggestion = regionRef.value.querySelector(".autocomplete-dropdown-wrap");
const suggestionList = suggestion.querySelectorAll(".autocomplete-dropdown-list li");
const highlightItem = suggestionList[index];
const scrollTop = suggestion.scrollTop;
const { offsetTop, scrollHeight } = highlightItem;
if (offsetTop + scrollHeight > scrollTop + suggestion.clientHeight) {
suggestion.scrollTop += scrollHeight;
}
if (offsetTop < scrollTop) {
suggestion.scrollTop -= scrollHeight;
}
highlightedIndex.value = index;
inputRef.value.ref.setAttribute("aria-activedescendant", `${listboxId.value}-item-${highlightedIndex.value}`);
};
const stopHandle = onClickOutside(listboxRef, () => {
suggestionVisible.value && close();
});
onBeforeUnmount(() => {
stopHandle == null ? void 0 : stopHandle();
});
onMounted(() => {
inputRef.value.inputOrTextarea.setAttribute("role", "textbox");
inputRef.value.inputOrTextarea.setAttribute("aria-autocomplete", "list");
inputRef.value.inputOrTextarea.setAttribute("aria-controls", "id");
inputRef.value.inputOrTextarea.setAttribute("aria-activedescendant", `${listboxId.value}-item-${highlightedIndex.value}`);
readonly = inputRef.value.inputOrTextarea.hasAttribute("readonly");
});
expose({
highlightedIndex,
activated,
loading,
inputRef,
popperRef,
suggestions,
handleSelect,
handleKeyEnter,
focus,
blur,
close,
highlight
});
return (_ctx, _cache) => {
return openBlock(), createBlock(unref(HlTooltip), {
ref_key: "popperRef",
ref: popperRef,
visible: unref(suggestionVisible),
placement: _ctx.placement,
"fallback-placements": ["bottom-start", "top-start"],
"popper-class": `${unref(namespace)}-popper ${_ctx.popperClass}`,
teleported: unref(compatTeleported),
"gpu-acceleration": false,
offset: _ctx.popperOffset,
"show-arrow": false,
trigger: "click",
transition: _ctx.transition,
persistent: "",
role: "listbox",
"manual-mode": "",
onBeforeShow: onSuggestionShow,
onHide
}, {
content: withCtx(() => [
createElementVNode("div", {
ref_key: "regionRef",
ref: regionRef,
class: normalizeClass(["autocomplete-dropdown", unref(suggestionLoading) && "is-loading"]),
style: normalizeStyle({
[_ctx.fitInputWidth ? "width" : "minWidth"]: dropdownWidth.value,
outline: "none"
}),
role: "region"
}, [
createVNode(unref(HlScrollbar), {
id: unref(listboxId),
tag: "ul",
"wrap-class": "autocomplete-dropdown-wrap",
"view-class": "autocomplete-dropdown-list",
role: "listbox"
}, {
default: withCtx(() => [
unref(suggestionLoading) ? (openBlock(), createElementBlock("li", { key: 0 }, [
renderSlot(_ctx.$slots, "loading", {}, () => [
createVNode(unref(HlSpinner))
])
])) : (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(suggestions.value, (item, index) => {
return openBlock(), createElementBlock("li", {
id: `${unref(listboxId)}-item-${index}`,
key: index,
class: normalizeClass({ "highlighted": highlightedIndex.value === index }),
role: "option",
"aria-selected": highlightedIndex.value === index,
onClick: ($event) => handleSelect(item)
}, [
renderSlot(_ctx.$slots, "default", { item }, () => [
createTextVNode(toDisplayString(item[_ctx.valueKey]), 1)
])
], 10, ["id", "aria-selected", "onClick"]);
}), 128))
]),
_: 3
}, 8, ["id"])
], 6)
]),
default: withCtx(() => [
createElementVNode("div", {
ref_key: "listboxRef",
ref: listboxRef,
class: normalizeClass([
unref(namespace),
_ctx.$attrs.class,
{ "block": _ctx.block }
]),
style: normalizeStyle(unref(styles)),
role: "combobox",
"aria-haspopup": "listbox",
"aria-expanded": unref(suggestionVisible),
"aria-owns": unref(listboxId),
onClick: withModifiers(() => {
}, ["stop"])
}, [
createVNode(unref(HlInput), mergeProps({
ref_key: "inputRef",
ref: inputRef
}, unref(attrs), {
"model-value": _ctx.modelValue,
size: unref(inputSize),
disabled: unref(inputDisabled),
fill: unref(inputFill),
thin: _ctx.thin,
clearable: _ctx.clearable,
name: _ctx.name,
"aria-label": _ctx.ariaLabel,
onInput: handleInput,
onChange: handleChange,
onFocus: handleFocus,
onBlur: handleBlur,
onClear: handleClear,
onKeydown: [
withKeys(withModifiers(($event) => highlight(highlightedIndex.value - 1), ["prevent"]), ["up"]),
withKeys(withModifiers(($event) => highlight(highlightedIndex.value + 1), ["prevent"]), ["down"]),
withKeys(handleKeyEnter, ["enter"]),
withKeys(close, ["tab"]),
withKeys(handleKeyEscape, ["esc"])
],
onMousedown: handleMouseDown
}), createSlots({ _: 2 }, [
_ctx.$slots.prefix ? {
name: "prefix",
fn: withCtx(() => [
renderSlot(_ctx.$slots, "prefix")
])
} : void 0,
_ctx.$slots.suffix ? {
name: "suffix",
fn: withCtx(() => [
renderSlot(_ctx.$slots, "suffix")
])
} : void 0
]), 1040, ["model-value", "size", "disabled", "fill", "thin", "clearable", "name", "aria-label", "onKeydown"])
], 14, ["aria-expanded", "aria-owns", "onClick"])
]),
_: 3
}, 8, ["visible", "placement", "popper-class", "teleported", "offset", "transition"]);
};
}
});
export { _sfc_main as default };
//# sourceMappingURL=autocomplete.mjs.map