VAutocomplete.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import { createTextVNode as _createTextVNode, mergeProps as _mergeProps, createVNode as _createVNode, Fragment as _Fragment } from "vue";
  2. // Styles
  3. import "./VAutocomplete.css";
  4. // Components
  5. import { VAvatar } from "../VAvatar/index.mjs";
  6. import { VCheckboxBtn } from "../VCheckbox/index.mjs";
  7. import { VChip } from "../VChip/index.mjs";
  8. import { VDefaultsProvider } from "../VDefaultsProvider/index.mjs";
  9. import { VIcon } from "../VIcon/index.mjs";
  10. import { VList, VListItem } from "../VList/index.mjs";
  11. import { VMenu } from "../VMenu/index.mjs";
  12. import { makeSelectProps } from "../VSelect/VSelect.mjs";
  13. import { makeVTextFieldProps, VTextField } from "../VTextField/VTextField.mjs";
  14. import { VVirtualScroll } from "../VVirtualScroll/index.mjs"; // Composables
  15. import { useScrolling } from "../VSelect/useScrolling.mjs";
  16. import { useTextColor } from "../../composables/color.mjs";
  17. import { makeFilterProps, useFilter } from "../../composables/filter.mjs";
  18. import { useForm } from "../../composables/form.mjs";
  19. import { forwardRefs } from "../../composables/forwardRefs.mjs";
  20. import { useItems } from "../../composables/list-items.mjs";
  21. import { useLocale } from "../../composables/locale.mjs";
  22. import { useProxiedModel } from "../../composables/proxiedModel.mjs";
  23. import { makeTransitionProps } from "../../composables/transition.mjs"; // Utilities
  24. import { computed, mergeProps, nextTick, ref, shallowRef, watch } from 'vue';
  25. import { checkPrintable, ensureValidVNode, genericComponent, IN_BROWSER, matchesSelector, noop, omit, propsFactory, useRender, wrapInArray } from "../../util/index.mjs"; // Types
  26. function highlightResult(text, matches, length) {
  27. if (matches == null) return text;
  28. if (Array.isArray(matches)) throw new Error('Multiple matches is not implemented');
  29. return typeof matches === 'number' && ~matches ? _createVNode(_Fragment, null, [_createVNode("span", {
  30. "class": "v-autocomplete__unmask"
  31. }, [text.substr(0, matches)]), _createVNode("span", {
  32. "class": "v-autocomplete__mask"
  33. }, [text.substr(matches, length)]), _createVNode("span", {
  34. "class": "v-autocomplete__unmask"
  35. }, [text.substr(matches + length)])]) : text;
  36. }
  37. export const makeVAutocompleteProps = propsFactory({
  38. autoSelectFirst: {
  39. type: [Boolean, String]
  40. },
  41. clearOnSelect: Boolean,
  42. search: String,
  43. ...makeFilterProps({
  44. filterKeys: ['title']
  45. }),
  46. ...makeSelectProps(),
  47. ...omit(makeVTextFieldProps({
  48. modelValue: null,
  49. role: 'combobox'
  50. }), ['validationValue', 'dirty', 'appendInnerIcon']),
  51. ...makeTransitionProps({
  52. transition: false
  53. })
  54. }, 'VAutocomplete');
  55. export const VAutocomplete = genericComponent()({
  56. name: 'VAutocomplete',
  57. props: makeVAutocompleteProps(),
  58. emits: {
  59. 'update:focused': focused => true,
  60. 'update:search': value => true,
  61. 'update:modelValue': value => true,
  62. 'update:menu': value => true
  63. },
  64. setup(props, _ref) {
  65. let {
  66. slots
  67. } = _ref;
  68. const {
  69. t
  70. } = useLocale();
  71. const vTextFieldRef = ref();
  72. const isFocused = shallowRef(false);
  73. const isPristine = shallowRef(true);
  74. const listHasFocus = shallowRef(false);
  75. const vMenuRef = ref();
  76. const vVirtualScrollRef = ref();
  77. const _menu = useProxiedModel(props, 'menu');
  78. const menu = computed({
  79. get: () => _menu.value,
  80. set: v => {
  81. if (_menu.value && !v && vMenuRef.value?.ΨopenChildren.size) return;
  82. _menu.value = v;
  83. }
  84. });
  85. const selectionIndex = shallowRef(-1);
  86. const color = computed(() => vTextFieldRef.value?.color);
  87. const label = computed(() => menu.value ? props.closeText : props.openText);
  88. const {
  89. items,
  90. transformIn,
  91. transformOut
  92. } = useItems(props);
  93. const {
  94. textColorClasses,
  95. textColorStyles
  96. } = useTextColor(color);
  97. const search = useProxiedModel(props, 'search', '');
  98. const model = useProxiedModel(props, 'modelValue', [], v => transformIn(v === null ? [null] : wrapInArray(v)), v => {
  99. const transformed = transformOut(v);
  100. return props.multiple ? transformed : transformed[0] ?? null;
  101. });
  102. const counterValue = computed(() => {
  103. return typeof props.counterValue === 'function' ? props.counterValue(model.value) : typeof props.counterValue === 'number' ? props.counterValue : model.value.length;
  104. });
  105. const form = useForm(props);
  106. const {
  107. filteredItems,
  108. getMatches
  109. } = useFilter(props, items, () => isPristine.value ? '' : search.value);
  110. const displayItems = computed(() => {
  111. if (props.hideSelected) {
  112. return filteredItems.value.filter(filteredItem => !model.value.some(s => s.value === filteredItem.value));
  113. }
  114. return filteredItems.value;
  115. });
  116. const hasChips = computed(() => !!(props.chips || slots.chip));
  117. const hasSelectionSlot = computed(() => hasChips.value || !!slots.selection);
  118. const selectedValues = computed(() => model.value.map(selection => selection.props.value));
  119. const highlightFirst = computed(() => {
  120. const selectFirst = props.autoSelectFirst === true || props.autoSelectFirst === 'exact' && search.value === displayItems.value[0]?.title;
  121. return selectFirst && displayItems.value.length > 0 && !isPristine.value && !listHasFocus.value;
  122. });
  123. const menuDisabled = computed(() => props.hideNoData && !displayItems.value.length || form.isReadonly.value || form.isDisabled.value);
  124. const listRef = ref();
  125. const listEvents = useScrolling(listRef, vTextFieldRef);
  126. function onClear(e) {
  127. if (props.openOnClear) {
  128. menu.value = true;
  129. }
  130. search.value = '';
  131. }
  132. function onMousedownControl() {
  133. if (menuDisabled.value) return;
  134. menu.value = true;
  135. }
  136. function onMousedownMenuIcon(e) {
  137. if (menuDisabled.value) return;
  138. if (isFocused.value) {
  139. e.preventDefault();
  140. e.stopPropagation();
  141. }
  142. menu.value = !menu.value;
  143. }
  144. function onListKeydown(e) {
  145. if (checkPrintable(e)) {
  146. vTextFieldRef.value?.focus();
  147. }
  148. }
  149. function onKeydown(e) {
  150. if (form.isReadonly.value) return;
  151. const selectionStart = vTextFieldRef.value.selectionStart;
  152. const length = model.value.length;
  153. if (selectionIndex.value > -1 || ['Enter', 'ArrowDown', 'ArrowUp'].includes(e.key)) {
  154. e.preventDefault();
  155. }
  156. if (['Enter', 'ArrowDown'].includes(e.key)) {
  157. menu.value = true;
  158. }
  159. if (['Escape'].includes(e.key)) {
  160. menu.value = false;
  161. }
  162. if (highlightFirst.value && ['Enter', 'Tab'].includes(e.key) && !model.value.some(_ref2 => {
  163. let {
  164. value
  165. } = _ref2;
  166. return value === displayItems.value[0].value;
  167. })) {
  168. select(displayItems.value[0]);
  169. }
  170. if (e.key === 'ArrowDown' && highlightFirst.value) {
  171. listRef.value?.focus('next');
  172. }
  173. if (['Backspace', 'Delete'].includes(e.key)) {
  174. if (!props.multiple && hasSelectionSlot.value && model.value.length > 0 && !search.value) return select(model.value[0], false);
  175. if (~selectionIndex.value) {
  176. const originalSelectionIndex = selectionIndex.value;
  177. select(model.value[selectionIndex.value], false);
  178. selectionIndex.value = originalSelectionIndex >= length - 1 ? length - 2 : originalSelectionIndex;
  179. } else if (e.key === 'Backspace' && !search.value) {
  180. selectionIndex.value = length - 1;
  181. }
  182. }
  183. if (!props.multiple) return;
  184. if (e.key === 'ArrowLeft') {
  185. if (selectionIndex.value < 0 && selectionStart > 0) return;
  186. const prev = selectionIndex.value > -1 ? selectionIndex.value - 1 : length - 1;
  187. if (model.value[prev]) {
  188. selectionIndex.value = prev;
  189. } else {
  190. selectionIndex.value = -1;
  191. vTextFieldRef.value.setSelectionRange(search.value?.length, search.value?.length);
  192. }
  193. }
  194. if (e.key === 'ArrowRight') {
  195. if (selectionIndex.value < 0) return;
  196. const next = selectionIndex.value + 1;
  197. if (model.value[next]) {
  198. selectionIndex.value = next;
  199. } else {
  200. selectionIndex.value = -1;
  201. vTextFieldRef.value.setSelectionRange(0, 0);
  202. }
  203. }
  204. }
  205. function onChange(e) {
  206. if (matchesSelector(vTextFieldRef.value, ':autofill') || matchesSelector(vTextFieldRef.value, ':-webkit-autofill')) {
  207. const item = items.value.find(item => item.title === e.target.value);
  208. if (item) {
  209. select(item);
  210. }
  211. }
  212. }
  213. function onAfterEnter() {
  214. if (props.eager) {
  215. vVirtualScrollRef.value?.calculateVisibleItems();
  216. }
  217. }
  218. function onAfterLeave() {
  219. if (isFocused.value) {
  220. isPristine.value = true;
  221. vTextFieldRef.value?.focus();
  222. }
  223. }
  224. function onFocusin(e) {
  225. isFocused.value = true;
  226. setTimeout(() => {
  227. listHasFocus.value = true;
  228. });
  229. }
  230. function onFocusout(e) {
  231. listHasFocus.value = false;
  232. }
  233. function onUpdateModelValue(v) {
  234. if (v == null || v === '' && !props.multiple && !hasSelectionSlot.value) model.value = [];
  235. }
  236. const isSelecting = shallowRef(false);
  237. /** @param set - null means toggle */
  238. function select(item) {
  239. let set = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  240. if (!item || item.props.disabled) return;
  241. if (props.multiple) {
  242. const index = model.value.findIndex(selection => props.valueComparator(selection.value, item.value));
  243. const add = set == null ? !~index : set;
  244. if (~index) {
  245. const value = add ? [...model.value, item] : [...model.value];
  246. value.splice(index, 1);
  247. model.value = value;
  248. } else if (add) {
  249. model.value = [...model.value, item];
  250. }
  251. if (props.clearOnSelect) {
  252. search.value = '';
  253. }
  254. } else {
  255. const add = set !== false;
  256. model.value = add ? [item] : [];
  257. search.value = add && !hasSelectionSlot.value ? item.title : '';
  258. // watch for search watcher to trigger
  259. nextTick(() => {
  260. menu.value = false;
  261. isPristine.value = true;
  262. });
  263. }
  264. }
  265. watch(isFocused, (val, oldVal) => {
  266. if (val === oldVal) return;
  267. if (val) {
  268. isSelecting.value = true;
  269. search.value = props.multiple || hasSelectionSlot.value ? '' : String(model.value.at(-1)?.props.title ?? '');
  270. isPristine.value = true;
  271. nextTick(() => isSelecting.value = false);
  272. } else {
  273. if (!props.multiple && search.value == null) model.value = [];
  274. menu.value = false;
  275. if (!model.value.some(_ref3 => {
  276. let {
  277. title
  278. } = _ref3;
  279. return title === search.value;
  280. })) search.value = '';
  281. selectionIndex.value = -1;
  282. }
  283. });
  284. watch(search, val => {
  285. if (!isFocused.value || isSelecting.value) return;
  286. if (val) menu.value = true;
  287. isPristine.value = !val;
  288. });
  289. watch(menu, () => {
  290. if (!props.hideSelected && menu.value && model.value.length) {
  291. const index = displayItems.value.findIndex(item => model.value.some(s => item.value === s.value));
  292. IN_BROWSER && window.requestAnimationFrame(() => {
  293. index >= 0 && vVirtualScrollRef.value?.scrollToIndex(index);
  294. });
  295. }
  296. });
  297. watch(() => props.items, (newVal, oldVal) => {
  298. if (menu.value) return;
  299. if (isFocused.value && !oldVal.length && newVal.length) {
  300. menu.value = true;
  301. }
  302. });
  303. useRender(() => {
  304. const hasList = !!(!props.hideNoData || displayItems.value.length || slots['prepend-item'] || slots['append-item'] || slots['no-data']);
  305. const isDirty = model.value.length > 0;
  306. const textFieldProps = VTextField.filterProps(props);
  307. return _createVNode(VTextField, _mergeProps({
  308. "ref": vTextFieldRef
  309. }, textFieldProps, {
  310. "modelValue": search.value,
  311. "onUpdate:modelValue": [$event => search.value = $event, onUpdateModelValue],
  312. "focused": isFocused.value,
  313. "onUpdate:focused": $event => isFocused.value = $event,
  314. "validationValue": model.externalValue,
  315. "counterValue": counterValue.value,
  316. "dirty": isDirty,
  317. "onChange": onChange,
  318. "class": ['v-autocomplete', `v-autocomplete--${props.multiple ? 'multiple' : 'single'}`, {
  319. 'v-autocomplete--active-menu': menu.value,
  320. 'v-autocomplete--chips': !!props.chips,
  321. 'v-autocomplete--selection-slot': !!hasSelectionSlot.value,
  322. 'v-autocomplete--selecting-index': selectionIndex.value > -1
  323. }, props.class],
  324. "style": props.style,
  325. "readonly": form.isReadonly.value,
  326. "placeholder": isDirty ? undefined : props.placeholder,
  327. "onClick:clear": onClear,
  328. "onMousedown:control": onMousedownControl,
  329. "onKeydown": onKeydown
  330. }), {
  331. ...slots,
  332. default: () => _createVNode(_Fragment, null, [_createVNode(VMenu, _mergeProps({
  333. "ref": vMenuRef,
  334. "modelValue": menu.value,
  335. "onUpdate:modelValue": $event => menu.value = $event,
  336. "activator": "parent",
  337. "contentClass": "v-autocomplete__content",
  338. "disabled": menuDisabled.value,
  339. "eager": props.eager,
  340. "maxHeight": 310,
  341. "openOnClick": false,
  342. "closeOnContentClick": false,
  343. "transition": props.transition,
  344. "onAfterEnter": onAfterEnter,
  345. "onAfterLeave": onAfterLeave
  346. }, props.menuProps), {
  347. default: () => [hasList && _createVNode(VList, _mergeProps({
  348. "ref": listRef,
  349. "selected": selectedValues.value,
  350. "selectStrategy": props.multiple ? 'independent' : 'single-independent',
  351. "onMousedown": e => e.preventDefault(),
  352. "onKeydown": onListKeydown,
  353. "onFocusin": onFocusin,
  354. "onFocusout": onFocusout,
  355. "tabindex": "-1",
  356. "aria-live": "polite",
  357. "color": props.itemColor ?? props.color
  358. }, listEvents, props.listProps), {
  359. default: () => [slots['prepend-item']?.(), !displayItems.value.length && !props.hideNoData && (slots['no-data']?.() ?? _createVNode(VListItem, {
  360. "key": "no-data",
  361. "title": t(props.noDataText)
  362. }, null)), _createVNode(VVirtualScroll, {
  363. "ref": vVirtualScrollRef,
  364. "renderless": true,
  365. "items": displayItems.value
  366. }, {
  367. default: _ref4 => {
  368. let {
  369. item,
  370. index,
  371. itemRef
  372. } = _ref4;
  373. const itemProps = mergeProps(item.props, {
  374. ref: itemRef,
  375. key: item.value,
  376. active: highlightFirst.value && index === 0 ? true : undefined,
  377. onClick: () => select(item, null)
  378. });
  379. return slots.item?.({
  380. item,
  381. index,
  382. props: itemProps
  383. }) ?? _createVNode(VListItem, _mergeProps(itemProps, {
  384. "role": "option"
  385. }), {
  386. prepend: _ref5 => {
  387. let {
  388. isSelected
  389. } = _ref5;
  390. return _createVNode(_Fragment, null, [props.multiple && !props.hideSelected ? _createVNode(VCheckboxBtn, {
  391. "key": item.value,
  392. "modelValue": isSelected,
  393. "ripple": false,
  394. "tabindex": "-1"
  395. }, null) : undefined, item.props.prependAvatar && _createVNode(VAvatar, {
  396. "image": item.props.prependAvatar
  397. }, null), item.props.prependIcon && _createVNode(VIcon, {
  398. "icon": item.props.prependIcon
  399. }, null)]);
  400. },
  401. title: () => {
  402. return isPristine.value ? item.title : highlightResult(item.title, getMatches(item)?.title, search.value?.length ?? 0);
  403. }
  404. });
  405. }
  406. }), slots['append-item']?.()]
  407. })]
  408. }), model.value.map((item, index) => {
  409. function onChipClose(e) {
  410. e.stopPropagation();
  411. e.preventDefault();
  412. select(item, false);
  413. }
  414. const slotProps = {
  415. 'onClick:close': onChipClose,
  416. onKeydown(e) {
  417. if (e.key !== 'Enter' && e.key !== ' ') return;
  418. e.preventDefault();
  419. e.stopPropagation();
  420. onChipClose(e);
  421. },
  422. onMousedown(e) {
  423. e.preventDefault();
  424. e.stopPropagation();
  425. },
  426. modelValue: true,
  427. 'onUpdate:modelValue': undefined
  428. };
  429. const hasSlot = hasChips.value ? !!slots.chip : !!slots.selection;
  430. const slotContent = hasSlot ? ensureValidVNode(hasChips.value ? slots.chip({
  431. item,
  432. index,
  433. props: slotProps
  434. }) : slots.selection({
  435. item,
  436. index
  437. })) : undefined;
  438. if (hasSlot && !slotContent) return undefined;
  439. return _createVNode("div", {
  440. "key": item.value,
  441. "class": ['v-autocomplete__selection', index === selectionIndex.value && ['v-autocomplete__selection--selected', textColorClasses.value]],
  442. "style": index === selectionIndex.value ? textColorStyles.value : {}
  443. }, [hasChips.value ? !slots.chip ? _createVNode(VChip, _mergeProps({
  444. "key": "chip",
  445. "closable": props.closableChips,
  446. "size": "small",
  447. "text": item.title,
  448. "disabled": item.props.disabled
  449. }, slotProps), null) : _createVNode(VDefaultsProvider, {
  450. "key": "chip-defaults",
  451. "defaults": {
  452. VChip: {
  453. closable: props.closableChips,
  454. size: 'small',
  455. text: item.title
  456. }
  457. }
  458. }, {
  459. default: () => [slotContent]
  460. }) : slotContent ?? _createVNode("span", {
  461. "class": "v-autocomplete__selection-text"
  462. }, [item.title, props.multiple && index < model.value.length - 1 && _createVNode("span", {
  463. "class": "v-autocomplete__selection-comma"
  464. }, [_createTextVNode(",")])])]);
  465. })]),
  466. 'append-inner': function () {
  467. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  468. args[_key] = arguments[_key];
  469. }
  470. return _createVNode(_Fragment, null, [slots['append-inner']?.(...args), props.menuIcon ? _createVNode(VIcon, {
  471. "class": "v-autocomplete__menu-icon",
  472. "icon": props.menuIcon,
  473. "onMousedown": onMousedownMenuIcon,
  474. "onClick": noop,
  475. "aria-label": t(label.value),
  476. "title": t(label.value),
  477. "tabindex": "-1"
  478. }, null) : undefined]);
  479. }
  480. });
  481. });
  482. return forwardRefs({
  483. isFocused,
  484. isPristine,
  485. menu,
  486. search,
  487. filteredItems,
  488. select
  489. }, vTextFieldRef);
  490. }
  491. });
  492. //# sourceMappingURL=VAutocomplete.mjs.map