useDateState.js 3.0 KB

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