useSearchOptions.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import _extends from "@babel/runtime/helpers/esm/extends";
  2. import { computed } from 'vue';
  3. export const SEARCH_MARK = '__rc_cascader_search_mark__';
  4. const defaultFilter = (search, options, _ref) => {
  5. let {
  6. label
  7. } = _ref;
  8. return options.some(opt => String(opt[label]).toLowerCase().includes(search.toLowerCase()));
  9. };
  10. const defaultRender = _ref2 => {
  11. let {
  12. path,
  13. fieldNames
  14. } = _ref2;
  15. return path.map(opt => opt[fieldNames.label]).join(' / ');
  16. };
  17. export default ((search, options, fieldNames, prefixCls, config, changeOnSelect) => {
  18. return computed(() => {
  19. const {
  20. filter = defaultFilter,
  21. render = defaultRender,
  22. limit = 50,
  23. sort
  24. } = config.value;
  25. const filteredOptions = [];
  26. if (!search.value) {
  27. return [];
  28. }
  29. function dig(list, pathOptions) {
  30. list.forEach(option => {
  31. // Perf saving when `sort` is disabled and `limit` is provided
  32. if (!sort && limit > 0 && filteredOptions.length >= limit) {
  33. return;
  34. }
  35. const connectedPathOptions = [...pathOptions, option];
  36. const children = option[fieldNames.value.children];
  37. // If current option is filterable
  38. if (
  39. // If is leaf option
  40. !children || children.length === 0 ||
  41. // If is changeOnSelect
  42. changeOnSelect.value) {
  43. if (filter(search.value, connectedPathOptions, {
  44. label: fieldNames.value.label
  45. })) {
  46. filteredOptions.push(_extends(_extends({}, option), {
  47. [fieldNames.value.label]: render({
  48. inputValue: search.value,
  49. path: connectedPathOptions,
  50. prefixCls: prefixCls.value,
  51. fieldNames: fieldNames.value
  52. }),
  53. [SEARCH_MARK]: connectedPathOptions
  54. }));
  55. }
  56. }
  57. if (children) {
  58. dig(option[fieldNames.value.children], connectedPathOptions);
  59. }
  60. });
  61. }
  62. dig(options.value, []);
  63. // Do sort
  64. if (sort) {
  65. filteredOptions.sort((a, b) => {
  66. return sort(a[SEARCH_MARK], b[SEARCH_MARK], search.value, fieldNames.value);
  67. });
  68. }
  69. return limit > 0 ? filteredOptions.slice(0, limit) : filteredOptions;
  70. });
  71. });