index.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { __spreadArray } from "tslib";
  2. import { useEvent } from 'functional-mini/component';
  3. import '../_util/assert-component2';
  4. import { mountComponent } from '../_util/component';
  5. import { useComponentEvent } from '../_util/hooks/useComponentEvent';
  6. import { useMixState } from '../_util/hooks/useMixState';
  7. import { SelectorFunctionalProps } from './props';
  8. var Selector = function (props) {
  9. var _a = useMixState(props.defaultValue, {
  10. value: props.value,
  11. }), selectorValue = _a[0], _b = _a[1], isControlled = _b.isControlled, update = _b.update;
  12. var triggerEventValues = useComponentEvent(props).triggerEventValues;
  13. useEvent('onChange', function (e) {
  14. var _a = e.currentTarget.dataset, disabled = _a.disabled, value = _a.value;
  15. var multiple = props.multiple, options = props.options, maxSelectedCount = props.maxSelectedCount, minSelectedCount = props.minSelectedCount;
  16. if (disabled || props.disabled) {
  17. return;
  18. }
  19. if (multiple) {
  20. var currentValue_1 = selectorValue || [];
  21. if (currentValue_1.indexOf(value) > -1) {
  22. if (typeof minSelectedCount === 'number' &&
  23. currentValue_1.length <= minSelectedCount) {
  24. triggerEventValues('selectMin', [value, options.find(function (v) { return v.value === value; })], e);
  25. return;
  26. }
  27. currentValue_1 = currentValue_1.filter(function (v) { return v !== value; });
  28. }
  29. else {
  30. if (typeof maxSelectedCount === 'number' &&
  31. currentValue_1.length >= maxSelectedCount) {
  32. triggerEventValues('selectMax', [value, options.find(function (v) { return v.value === value; })], e);
  33. return;
  34. }
  35. currentValue_1 = __spreadArray(__spreadArray([], currentValue_1, true), [value], false);
  36. }
  37. if (!isControlled) {
  38. update(currentValue_1);
  39. }
  40. triggerEventValues('change', [
  41. currentValue_1,
  42. options.filter(function (v) { return currentValue_1.indexOf(v.value) > -1; }),
  43. ], e);
  44. }
  45. else {
  46. if (value === selectorValue) {
  47. if (minSelectedCount === 1) {
  48. triggerEventValues('selectMin', [value, options.find(function (v) { return v.value === value; })], e);
  49. return;
  50. }
  51. if (!isControlled) {
  52. update(undefined);
  53. }
  54. triggerEventValues('change', [undefined, undefined], e);
  55. }
  56. else {
  57. if (!isControlled) {
  58. update(value);
  59. }
  60. triggerEventValues('change', [value, options.find(function (v) { return v.value === value; })], e);
  61. }
  62. }
  63. });
  64. return {
  65. mixin: {
  66. value: selectorValue,
  67. },
  68. };
  69. };
  70. mountComponent(Selector, SelectorFunctionalProps);