VCombobox.mjs 20 KB

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