408b3f67008ecc491a48ab56192f957f99af33dfa03195543aa20e5ff130c0326fc9a4667319630d455fb0e9d753675beafc56981aec9bf739862b98bfbef1 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. import { defineComponent, computed, useAttrs, ref, onBeforeUnmount, onMounted, openBlock, createBlock, unref, withCtx, createElementVNode, normalizeClass, normalizeStyle, createElementBlock, withModifiers, renderSlot, createCommentVNode, createVNode, Fragment, renderList, createTextVNode, toDisplayString, mergeProps, withKeys, createSlots } from 'vue';
  2. import { pick, debounce } from 'lodash-unified';
  3. import { onClickOutside } from '@vueuse/core';
  4. import { Loading } from '@element-plus/icons-vue';
  5. import { ElInput } from '../../input/index.mjs';
  6. import { ElScrollbar } from '../../scrollbar/index.mjs';
  7. import { ElTooltip } from '../../tooltip/index.mjs';
  8. import { ElIcon } from '../../icon/index.mjs';
  9. import { autocompleteProps, autocompleteEmits } from './autocomplete.mjs';
  10. import _export_sfc from '../../../_virtual/plugin-vue_export-helper.mjs';
  11. import { inputProps } from '../../input/src/input.mjs';
  12. import { useFormDisabled } from '../../form/src/hooks/use-form-common-props.mjs';
  13. import { useNamespace } from '../../../hooks/use-namespace/index.mjs';
  14. import { useId } from '../../../hooks/use-id/index.mjs';
  15. import { isArray } from '@vue/shared';
  16. import { INPUT_EVENT, UPDATE_MODEL_EVENT, CHANGE_EVENT } from '../../../constants/event.mjs';
  17. import { throwError } from '../../../utils/error.mjs';
  18. const COMPONENT_NAME = "ElAutocomplete";
  19. const __default__ = defineComponent({
  20. name: COMPONENT_NAME,
  21. inheritAttrs: false
  22. });
  23. const _sfc_main = /* @__PURE__ */ defineComponent({
  24. ...__default__,
  25. props: autocompleteProps,
  26. emits: autocompleteEmits,
  27. setup(__props, { expose, emit }) {
  28. const props = __props;
  29. const passInputProps = computed(() => pick(props, Object.keys(inputProps)));
  30. const rawAttrs = useAttrs();
  31. const disabled = useFormDisabled();
  32. const ns = useNamespace("autocomplete");
  33. const inputRef = ref();
  34. const regionRef = ref();
  35. const popperRef = ref();
  36. const listboxRef = ref();
  37. let readonly = false;
  38. let ignoreFocusEvent = false;
  39. const suggestions = ref([]);
  40. const highlightedIndex = ref(-1);
  41. const dropdownWidth = ref("");
  42. const activated = ref(false);
  43. const suggestionDisabled = ref(false);
  44. const loading = ref(false);
  45. const listboxId = useId();
  46. const styles = computed(() => rawAttrs.style);
  47. const suggestionVisible = computed(() => {
  48. const isValidData = suggestions.value.length > 0;
  49. return (isValidData || loading.value) && activated.value;
  50. });
  51. const suggestionLoading = computed(() => !props.hideLoading && loading.value);
  52. const refInput = computed(() => {
  53. if (inputRef.value) {
  54. return Array.from(inputRef.value.$el.querySelectorAll("input"));
  55. }
  56. return [];
  57. });
  58. const onSuggestionShow = () => {
  59. if (suggestionVisible.value) {
  60. dropdownWidth.value = `${inputRef.value.$el.offsetWidth}px`;
  61. }
  62. };
  63. const onHide = () => {
  64. highlightedIndex.value = -1;
  65. };
  66. const getData = async (queryString) => {
  67. if (suggestionDisabled.value)
  68. return;
  69. const cb = (suggestionList) => {
  70. loading.value = false;
  71. if (suggestionDisabled.value)
  72. return;
  73. if (isArray(suggestionList)) {
  74. suggestions.value = suggestionList;
  75. highlightedIndex.value = props.highlightFirstItem ? 0 : -1;
  76. } else {
  77. throwError(COMPONENT_NAME, "autocomplete suggestions must be an array");
  78. }
  79. };
  80. loading.value = true;
  81. if (isArray(props.fetchSuggestions)) {
  82. cb(props.fetchSuggestions);
  83. } else {
  84. const result = await props.fetchSuggestions(queryString, cb);
  85. if (isArray(result))
  86. cb(result);
  87. }
  88. };
  89. const debouncedGetData = debounce(getData, props.debounce);
  90. const handleInput = (value) => {
  91. const valuePresented = !!value;
  92. emit(INPUT_EVENT, value);
  93. emit(UPDATE_MODEL_EVENT, value);
  94. suggestionDisabled.value = false;
  95. activated.value || (activated.value = valuePresented);
  96. if (!props.triggerOnFocus && !value) {
  97. suggestionDisabled.value = true;
  98. suggestions.value = [];
  99. return;
  100. }
  101. debouncedGetData(value);
  102. };
  103. const handleMouseDown = (event) => {
  104. var _a;
  105. if (disabled.value)
  106. return;
  107. if (((_a = event.target) == null ? void 0 : _a.tagName) !== "INPUT" || refInput.value.includes(document.activeElement)) {
  108. activated.value = true;
  109. }
  110. };
  111. const handleChange = (value) => {
  112. emit(CHANGE_EVENT, value);
  113. };
  114. const handleFocus = (evt) => {
  115. var _a;
  116. if (!ignoreFocusEvent) {
  117. activated.value = true;
  118. emit("focus", evt);
  119. const queryString = (_a = props.modelValue) != null ? _a : "";
  120. if (props.triggerOnFocus && !readonly) {
  121. debouncedGetData(String(queryString));
  122. }
  123. } else {
  124. ignoreFocusEvent = false;
  125. }
  126. };
  127. const handleBlur = (evt) => {
  128. setTimeout(() => {
  129. var _a;
  130. if ((_a = popperRef.value) == null ? void 0 : _a.isFocusInsideContent()) {
  131. ignoreFocusEvent = true;
  132. return;
  133. }
  134. activated.value && close();
  135. emit("blur", evt);
  136. });
  137. };
  138. const handleClear = () => {
  139. activated.value = false;
  140. emit(UPDATE_MODEL_EVENT, "");
  141. emit("clear");
  142. };
  143. const handleKeyEnter = async () => {
  144. var _a;
  145. if ((_a = inputRef.value) == null ? void 0 : _a.isComposing) {
  146. return;
  147. }
  148. if (suggestionVisible.value && highlightedIndex.value >= 0 && highlightedIndex.value < suggestions.value.length) {
  149. handleSelect(suggestions.value[highlightedIndex.value]);
  150. } else if (props.selectWhenUnmatched) {
  151. emit("select", { value: props.modelValue });
  152. suggestions.value = [];
  153. highlightedIndex.value = -1;
  154. }
  155. };
  156. const handleKeyEscape = (evt) => {
  157. if (suggestionVisible.value) {
  158. evt.preventDefault();
  159. evt.stopPropagation();
  160. close();
  161. }
  162. };
  163. const close = () => {
  164. activated.value = false;
  165. };
  166. const focus = () => {
  167. var _a;
  168. (_a = inputRef.value) == null ? void 0 : _a.focus();
  169. };
  170. const blur = () => {
  171. var _a;
  172. (_a = inputRef.value) == null ? void 0 : _a.blur();
  173. };
  174. const handleSelect = async (item) => {
  175. emit(INPUT_EVENT, item[props.valueKey]);
  176. emit(UPDATE_MODEL_EVENT, item[props.valueKey]);
  177. emit("select", item);
  178. suggestions.value = [];
  179. highlightedIndex.value = -1;
  180. };
  181. const highlight = (index) => {
  182. var _a, _b;
  183. if (!suggestionVisible.value || loading.value)
  184. return;
  185. if (index < 0) {
  186. highlightedIndex.value = -1;
  187. return;
  188. }
  189. if (index >= suggestions.value.length) {
  190. index = suggestions.value.length - 1;
  191. }
  192. const suggestion = regionRef.value.querySelector(`.${ns.be("suggestion", "wrap")}`);
  193. const suggestionList = suggestion.querySelectorAll(`.${ns.be("suggestion", "list")} li`);
  194. const highlightItem = suggestionList[index];
  195. const scrollTop = suggestion.scrollTop;
  196. const { offsetTop, scrollHeight } = highlightItem;
  197. if (offsetTop + scrollHeight > scrollTop + suggestion.clientHeight) {
  198. suggestion.scrollTop += scrollHeight;
  199. }
  200. if (offsetTop < scrollTop) {
  201. suggestion.scrollTop -= scrollHeight;
  202. }
  203. highlightedIndex.value = index;
  204. (_b = (_a = inputRef.value) == null ? void 0 : _a.ref) == null ? void 0 : _b.setAttribute("aria-activedescendant", `${listboxId.value}-item-${highlightedIndex.value}`);
  205. };
  206. const stopHandle = onClickOutside(listboxRef, () => {
  207. var _a;
  208. if ((_a = popperRef.value) == null ? void 0 : _a.isFocusInsideContent())
  209. return;
  210. suggestionVisible.value && close();
  211. });
  212. onBeforeUnmount(() => {
  213. stopHandle == null ? void 0 : stopHandle();
  214. });
  215. onMounted(() => {
  216. var _a;
  217. const inputElement = (_a = inputRef.value) == null ? void 0 : _a.ref;
  218. if (!inputElement)
  219. return;
  220. [
  221. { key: "role", value: "textbox" },
  222. { key: "aria-autocomplete", value: "list" },
  223. { key: "aria-controls", value: "id" },
  224. {
  225. key: "aria-activedescendant",
  226. value: `${listboxId.value}-item-${highlightedIndex.value}`
  227. }
  228. ].forEach(({ key, value }) => inputElement.setAttribute(key, value));
  229. readonly = inputElement.hasAttribute("readonly");
  230. });
  231. expose({
  232. highlightedIndex,
  233. activated,
  234. loading,
  235. inputRef,
  236. popperRef,
  237. suggestions,
  238. handleSelect,
  239. handleKeyEnter,
  240. focus,
  241. blur,
  242. close,
  243. highlight,
  244. getData
  245. });
  246. return (_ctx, _cache) => {
  247. return openBlock(), createBlock(unref(ElTooltip), {
  248. ref_key: "popperRef",
  249. ref: popperRef,
  250. visible: unref(suggestionVisible),
  251. placement: _ctx.placement,
  252. "fallback-placements": ["bottom-start", "top-start"],
  253. "popper-class": [unref(ns).e("popper"), _ctx.popperClass],
  254. teleported: _ctx.teleported,
  255. "append-to": _ctx.appendTo,
  256. "gpu-acceleration": false,
  257. pure: "",
  258. "manual-mode": "",
  259. effect: "light",
  260. trigger: "click",
  261. transition: `${unref(ns).namespace.value}-zoom-in-top`,
  262. persistent: "",
  263. role: "listbox",
  264. onBeforeShow: onSuggestionShow,
  265. onHide
  266. }, {
  267. content: withCtx(() => [
  268. createElementVNode("div", {
  269. ref_key: "regionRef",
  270. ref: regionRef,
  271. class: normalizeClass([unref(ns).b("suggestion"), unref(ns).is("loading", unref(suggestionLoading))]),
  272. style: normalizeStyle({
  273. [_ctx.fitInputWidth ? "width" : "minWidth"]: dropdownWidth.value,
  274. outline: "none"
  275. }),
  276. role: "region"
  277. }, [
  278. _ctx.$slots.header ? (openBlock(), createElementBlock("div", {
  279. key: 0,
  280. class: normalizeClass(unref(ns).be("suggestion", "header")),
  281. onClick: withModifiers(() => {
  282. }, ["stop"])
  283. }, [
  284. renderSlot(_ctx.$slots, "header")
  285. ], 10, ["onClick"])) : createCommentVNode("v-if", true),
  286. createVNode(unref(ElScrollbar), {
  287. id: unref(listboxId),
  288. tag: "ul",
  289. "wrap-class": unref(ns).be("suggestion", "wrap"),
  290. "view-class": unref(ns).be("suggestion", "list"),
  291. role: "listbox"
  292. }, {
  293. default: withCtx(() => [
  294. unref(suggestionLoading) ? (openBlock(), createElementBlock("li", { key: 0 }, [
  295. renderSlot(_ctx.$slots, "loading", {}, () => [
  296. createVNode(unref(ElIcon), {
  297. class: normalizeClass(unref(ns).is("loading"))
  298. }, {
  299. default: withCtx(() => [
  300. createVNode(unref(Loading))
  301. ]),
  302. _: 1
  303. }, 8, ["class"])
  304. ])
  305. ])) : (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(suggestions.value, (item, index) => {
  306. return openBlock(), createElementBlock("li", {
  307. id: `${unref(listboxId)}-item-${index}`,
  308. key: index,
  309. class: normalizeClass({ highlighted: highlightedIndex.value === index }),
  310. role: "option",
  311. "aria-selected": highlightedIndex.value === index,
  312. onClick: ($event) => handleSelect(item)
  313. }, [
  314. renderSlot(_ctx.$slots, "default", { item }, () => [
  315. createTextVNode(toDisplayString(item[_ctx.valueKey]), 1)
  316. ])
  317. ], 10, ["id", "aria-selected", "onClick"]);
  318. }), 128))
  319. ]),
  320. _: 3
  321. }, 8, ["id", "wrap-class", "view-class"]),
  322. _ctx.$slots.footer ? (openBlock(), createElementBlock("div", {
  323. key: 1,
  324. class: normalizeClass(unref(ns).be("suggestion", "footer")),
  325. onClick: withModifiers(() => {
  326. }, ["stop"])
  327. }, [
  328. renderSlot(_ctx.$slots, "footer")
  329. ], 10, ["onClick"])) : createCommentVNode("v-if", true)
  330. ], 6)
  331. ]),
  332. default: withCtx(() => [
  333. createElementVNode("div", {
  334. ref_key: "listboxRef",
  335. ref: listboxRef,
  336. class: normalizeClass([unref(ns).b(), _ctx.$attrs.class]),
  337. style: normalizeStyle(unref(styles)),
  338. role: "combobox",
  339. "aria-haspopup": "listbox",
  340. "aria-expanded": unref(suggestionVisible),
  341. "aria-owns": unref(listboxId)
  342. }, [
  343. createVNode(unref(ElInput), mergeProps({
  344. ref_key: "inputRef",
  345. ref: inputRef
  346. }, mergeProps(unref(passInputProps), _ctx.$attrs), {
  347. "model-value": _ctx.modelValue,
  348. disabled: unref(disabled),
  349. onInput: handleInput,
  350. onChange: handleChange,
  351. onFocus: handleFocus,
  352. onBlur: handleBlur,
  353. onClear: handleClear,
  354. onKeydown: [
  355. withKeys(withModifiers(($event) => highlight(highlightedIndex.value - 1), ["prevent"]), ["up"]),
  356. withKeys(withModifiers(($event) => highlight(highlightedIndex.value + 1), ["prevent"]), ["down"]),
  357. withKeys(handleKeyEnter, ["enter"]),
  358. withKeys(close, ["tab"]),
  359. withKeys(handleKeyEscape, ["esc"])
  360. ],
  361. onMousedown: handleMouseDown
  362. }), createSlots({
  363. _: 2
  364. }, [
  365. _ctx.$slots.prepend ? {
  366. name: "prepend",
  367. fn: withCtx(() => [
  368. renderSlot(_ctx.$slots, "prepend")
  369. ])
  370. } : void 0,
  371. _ctx.$slots.append ? {
  372. name: "append",
  373. fn: withCtx(() => [
  374. renderSlot(_ctx.$slots, "append")
  375. ])
  376. } : void 0,
  377. _ctx.$slots.prefix ? {
  378. name: "prefix",
  379. fn: withCtx(() => [
  380. renderSlot(_ctx.$slots, "prefix")
  381. ])
  382. } : void 0,
  383. _ctx.$slots.suffix ? {
  384. name: "suffix",
  385. fn: withCtx(() => [
  386. renderSlot(_ctx.$slots, "suffix")
  387. ])
  388. } : void 0
  389. ]), 1040, ["model-value", "disabled", "onKeydown"])
  390. ], 14, ["aria-expanded", "aria-owns"])
  391. ]),
  392. _: 3
  393. }, 8, ["visible", "placement", "popper-class", "teleported", "append-to", "transition"]);
  394. };
  395. }
  396. });
  397. var Autocomplete = /* @__PURE__ */ _export_sfc(_sfc_main, [["__file", "autocomplete.vue"]]);
  398. export { Autocomplete as default };
  399. //# sourceMappingURL=autocomplete2.mjs.map