useDateState.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { __assign } from "tslib";
  2. import dayjs from 'dayjs';
  3. import { useState } from 'functional-mini/component';
  4. import { useMinAndMax } from './hooks';
  5. export function useDateState(props) {
  6. var getMin = useMinAndMax().getMin;
  7. var _a = useState({
  8. pickerType: 'start',
  9. start: null,
  10. end: null,
  11. }), dateState = _a[0], setDateState = _a[1];
  12. var init = function (realValue) {
  13. var currentStartDate = realValue === null || realValue === void 0 ? void 0 : realValue[0];
  14. var currentEndDate = realValue === null || realValue === void 0 ? void 0 : realValue[1];
  15. if (!currentStartDate) {
  16. var min = getMin(props.min).toDate();
  17. var max = props.max;
  18. currentStartDate = new Date();
  19. if ((min && dayjs(currentStartDate).isBefore(min, props.precision)) ||
  20. (max && dayjs(currentStartDate).isAfter(max, props.precision)) ||
  21. (currentEndDate && currentStartDate > currentEndDate)) {
  22. currentStartDate = min;
  23. }
  24. }
  25. var newState = {
  26. pickerType: 'start',
  27. start: currentStartDate,
  28. end: currentEndDate,
  29. };
  30. setDateState(newState);
  31. return newState;
  32. };
  33. var changeType = function (newType) {
  34. var currentStartDate = dateState.start;
  35. var currentEndDate = dateState.end;
  36. if (newType === 'start') {
  37. if (!currentStartDate) {
  38. currentStartDate = currentEndDate;
  39. }
  40. }
  41. else {
  42. // pickerType=end start已存在
  43. // 结束时间默认选中开始
  44. if (!currentEndDate) {
  45. currentEndDate = currentStartDate;
  46. }
  47. }
  48. var newState = {
  49. pickerType: newType,
  50. start: currentStartDate,
  51. end: currentEndDate,
  52. };
  53. setDateState(newState);
  54. return newState;
  55. };
  56. function updateValue(newValue) {
  57. setDateState(function (old) {
  58. if (old.pickerType === 'start') {
  59. var newEnd = old.end;
  60. if (old.end && dayjs(newValue).isAfter(old.end)) {
  61. newEnd = null;
  62. }
  63. return __assign(__assign({}, old), { start: newValue, end: newEnd });
  64. }
  65. var newStart = old.start;
  66. if (old.start && dayjs(newValue).isBefore(old.start)) {
  67. newStart = null;
  68. }
  69. return __assign(__assign({}, old), { end: newValue, start: newStart });
  70. });
  71. }
  72. return {
  73. updateValue: updateValue,
  74. dateState: dateState,
  75. init: init,
  76. changeType: changeType,
  77. };
  78. }