autocomplete2.mjs 13 KB

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