autocomplete2.js 14 KB

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