monthsGridFoundation.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /* eslint-disable max-len */
  2. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  3. import { strings } from './constants';
  4. import {
  5. format,
  6. set,
  7. addMonths,
  8. subMonths,
  9. subYears,
  10. addYears,
  11. differenceInCalendarMonths,
  12. differenceInCalendarYears,
  13. isSameDay,
  14. parseISO
  15. } from 'date-fns';
  16. import { isBefore, isValidDate, getDefaultFormatToken, getFullDateOffset } from './_utils/index';
  17. import { formatFullDate, WeekStartNumber } from './_utils/getMonthTable';
  18. import { compatiableParse } from './_utils/parser';
  19. import { includes, isSet, isEqual } from 'lodash';
  20. import { zonedTimeToUtc } from '../utils/date-fns-extra';
  21. import { getDefaultFormatTokenByType } from './_utils/getDefaultFormatToken';
  22. import isNullOrUndefined from '../utils/isNullOrUndefined';
  23. import { BaseValueType, ValueType } from './foundation';
  24. import { MonthDayInfo } from './monthFoundation';
  25. import { ArrayElement } from '../utils/type';
  26. const dateDiffFns = {
  27. month: differenceInCalendarMonths,
  28. year: differenceInCalendarYears,
  29. };
  30. const dateCalcFns = {
  31. prevMonth: subMonths,
  32. nextMonth: addMonths,
  33. prevYear: subYears,
  34. nextYear: addYears,
  35. };
  36. type Type = ArrayElement<typeof strings.TYPE_SET>;
  37. interface MonthsGridElementProps {
  38. navPrev?: React.ReactNode;
  39. navNext?: React.ReactNode;
  40. renderDate?: () => React.ReactNode;
  41. renderFullDate?: () => React.ReactNode;
  42. }
  43. export type PanelType = 'left' | 'right';
  44. export type YearMonthChangeType = 'prevMonth' | 'nextMonth' | 'prevYear' | 'nextYear';
  45. export interface MonthsGridFoundationProps extends MonthsGridElementProps {
  46. type?: Type;
  47. defaultValue?: ValueType;
  48. defaultPickerValue?: ValueType;
  49. multiple?: boolean;
  50. max?: number;
  51. splitPanels?: boolean;
  52. weekStartsOn?: WeekStartNumber;
  53. disabledDate?: (date: Date, options?: { rangeStart: string; rangeEnd: string }) => boolean;
  54. disabledTime?: (date: Date | Date[], panelType: PanelType) => void;
  55. disabledTimePicker?: boolean;
  56. hideDisabledOptions?: boolean;
  57. onMaxSelect?: (v?: any) => void;
  58. timePickerOpts?: any;
  59. isControlledComponent?: boolean;
  60. rangeStart?: string;
  61. rangeInputFocus?: boolean | string;
  62. locale?: any;
  63. localeCode?: string;
  64. format?: string;
  65. startDateOffset?: () => void;
  66. endDateOffset?: () => void;
  67. autoSwitchDate?: boolean;
  68. motionEnd?: boolean;
  69. density?: string;
  70. dateFnsLocale?: any;
  71. timeZone?: string | number;
  72. syncSwitchMonth?: boolean;
  73. onChange?: (
  74. value: [Date] | [Date, Date],
  75. options?: { closePanel?: boolean; needCheckFocusRecord?: boolean }
  76. ) => void;
  77. onPanelChange?: (date: Date | Date[], dateString: string | string[]) => void;
  78. setRangeInputFocus?: (rangeInputFocus: 'rangeStart' | 'rangeEnd') => void;
  79. isAnotherPanelHasOpened?: (currentRangeInput: 'rangeStart' | 'rangeEnd') => boolean;
  80. focusRecordsRef?: any;
  81. }
  82. export interface MonthInfo {
  83. pickerDate: Date;
  84. showDate: Date;
  85. isTimePickerOpen: boolean;
  86. isYearPickerOpen: boolean;
  87. }
  88. export interface MonthsGridFoundationState {
  89. selected: Set<string>;
  90. monthLeft: MonthInfo;
  91. monthRight: MonthInfo;
  92. maxWeekNum: number; // Maximum number of weeks left and right for manual height adjustment
  93. hoverDay: string; // Real-time hover date
  94. rangeStart: string; // Start date for range selection
  95. rangeEnd: string; // End date of range selection
  96. currentPanelHeight: number; // current month panel height,
  97. offsetRangeStart: string;
  98. offsetRangeEnd: string;
  99. weeksRowNum?: number;
  100. }
  101. export interface MonthsGridDateAdapter {
  102. updateDaySelected: (selected: Set<string>) => void;
  103. }
  104. export interface MonthsGridRangeAdapter {
  105. setRangeStart: (rangeStart: string) => void;
  106. setRangeEnd: (rangeEnd: string) => void;
  107. setHoverDay: (hoverDay: string) => void;
  108. setWeeksHeight: (maxWeekNum: number) => void;
  109. setOffsetRangeStart: (offsetRangeStart: string) => void;
  110. setOffsetRangeEnd: (offsetRangeEnd: string) => void;
  111. }
  112. export interface MonthsGridAdapter extends DefaultAdapter<MonthsGridFoundationProps, MonthsGridFoundationState>, MonthsGridRangeAdapter, MonthsGridDateAdapter {
  113. updateMonthOnLeft: (v: MonthInfo) => void;
  114. updateMonthOnRight: (v: MonthInfo) => void;
  115. notifySelectedChange: MonthsGridFoundationProps['onChange'];
  116. notifyMaxLimit: MonthsGridFoundationProps['onMaxSelect'];
  117. notifyPanelChange: MonthsGridFoundationProps['onPanelChange'];
  118. setRangeInputFocus: MonthsGridFoundationProps['setRangeInputFocus'];
  119. isAnotherPanelHasOpened: MonthsGridFoundationProps['isAnotherPanelHasOpened'];
  120. }
  121. export default class MonthsGridFoundation extends BaseFoundation<MonthsGridAdapter> {
  122. newBiMonthPanelDate: [Date, Date];
  123. constructor(adapter: MonthsGridAdapter) {
  124. super({ ...adapter });
  125. // Date change data when double panels
  126. this.newBiMonthPanelDate = [this.getState('monthLeft').pickerDate, this.getState('monthRight').pickerDate];
  127. }
  128. init() {
  129. const defaultValue = this.getProp('defaultValue');
  130. this.initDefaultPickerValue();
  131. this.updateSelectedFromProps(defaultValue);
  132. }
  133. initDefaultPickerValue() {
  134. const defaultPickerValue = compatiableParse(this.getProp('defaultPickerValue'));
  135. if (defaultPickerValue && isValidDate(defaultPickerValue)) {
  136. this._updatePanelDetail(strings.PANEL_TYPE_LEFT, {
  137. pickerDate: defaultPickerValue,
  138. });
  139. this._updatePanelDetail(strings.PANEL_TYPE_RIGHT, {
  140. pickerDate: addMonths(defaultPickerValue, 1),
  141. });
  142. }
  143. }
  144. updateSelectedFromProps(values: ValueType, refreshPicker = true) {
  145. const type: Type = this.getProp('type');
  146. const { selected, rangeStart, rangeEnd } = this.getStates();
  147. if (values && (values as BaseValueType[]).length) {
  148. switch (type) {
  149. case 'date':
  150. this._initDatePickerFromValue(values as BaseValueType[], refreshPicker);
  151. break;
  152. case 'dateRange':
  153. this._initDateRangePickerFromValue(values as BaseValueType[]);
  154. break;
  155. case 'dateTime':
  156. this._initDateTimePickerFromValue(values as BaseValueType[]);
  157. break;
  158. case 'dateTimeRange':
  159. this._initDateTimeRangePickerFormValue(values as BaseValueType[]);
  160. break;
  161. default:
  162. break;
  163. }
  164. } else if (Array.isArray(values) && !values.length || !values) {
  165. // Empty panel when value is empty Select date
  166. if (isSet(selected) && selected.size) {
  167. this._adapter.updateDaySelected(new Set());
  168. }
  169. if (rangeStart) {
  170. this._adapter.setRangeStart('');
  171. }
  172. if (rangeEnd) {
  173. this._adapter.setRangeEnd('');
  174. }
  175. }
  176. }
  177. calcDisabledTime(panelType: PanelType) {
  178. const { disabledTime, type } = this.getProps();
  179. if (typeof disabledTime === 'function' && panelType && ['dateTime', 'dateTimeRange'].includes(type)) {
  180. const { rangeStart, rangeEnd, monthLeft } = this.getStates();
  181. const selected = [];
  182. if (type === 'dateTimeRange') {
  183. if (rangeStart) {
  184. selected.push(rangeStart);
  185. }
  186. if (rangeStart && rangeEnd) {
  187. selected.push(rangeEnd);
  188. }
  189. } else if (monthLeft && monthLeft.showDate) {
  190. selected.push(monthLeft.showDate);
  191. }
  192. const selectedDates = selected.map(str => (str instanceof Date ? str : parseISO(str)));
  193. const cbDates = type === 'dateTimeRange' ? selectedDates : selectedDates[0];
  194. return disabledTime(cbDates, panelType);
  195. }
  196. }
  197. _initDatePickerFromValue(values: BaseValueType[], refreshPicker = true) {
  198. const monthLeft = this.getState('monthLeft');
  199. const newMonthLeft = { ...monthLeft };
  200. this._adapter.updateMonthOnLeft(newMonthLeft);
  201. const newSelected = new Set<string>();
  202. if (!this._isMultiple()) {
  203. newSelected.add(format(values[0] as Date, strings.FORMAT_FULL_DATE));
  204. } else {
  205. values.forEach(date => {
  206. newSelected.add(format(date as Date, strings.FORMAT_FULL_DATE));
  207. });
  208. }
  209. if (refreshPicker) {
  210. this.handleShowDateAndTime(strings.PANEL_TYPE_LEFT, values[0] || newMonthLeft.pickerDate);
  211. } else {
  212. this.handleShowDateAndTime(strings.PANEL_TYPE_LEFT, newMonthLeft.pickerDate);
  213. }
  214. this._adapter.updateDaySelected(newSelected);
  215. }
  216. _initDateRangePickerFromValue(values: BaseValueType[], withTime = false) {
  217. // init month panel
  218. const monthLeft = this.getState('monthLeft');
  219. const monthRight = this.getState('monthRight');
  220. const adjustResult = this._autoAdjustMonth(
  221. { ...monthLeft, pickerDate: values[0] || monthLeft.pickerDate },
  222. { ...monthRight, pickerDate: values[1] || monthRight.pickerDate }
  223. );
  224. this.handleShowDateAndTime(strings.PANEL_TYPE_LEFT, adjustResult.monthLeft.pickerDate);
  225. this.handleShowDateAndTime(strings.PANEL_TYPE_RIGHT, adjustResult.monthRight.pickerDate);
  226. // init range
  227. const formatToken = withTime ? strings.FORMAT_DATE_TIME : strings.FORMAT_FULL_DATE;
  228. let rangeStart = values[0] && format(values[0] as Date, formatToken);
  229. let rangeEnd = values[1] && format(values[1] as Date, formatToken);
  230. if (this._isNeedSwap(rangeStart, rangeEnd)) {
  231. [rangeStart, rangeEnd] = [rangeEnd, rangeStart];
  232. }
  233. this._adapter.setRangeStart(rangeStart);
  234. this._adapter.setRangeEnd(rangeEnd);
  235. this._adapter.setHoverDay(rangeEnd);
  236. }
  237. _initDateTimePickerFromValue(values: BaseValueType[]) {
  238. this._initDatePickerFromValue(values);
  239. }
  240. _initDateTimeRangePickerFormValue(values: BaseValueType[]) {
  241. this._initDateRangePickerFromValue(values, true);
  242. }
  243. // eslint-disable-next-line @typescript-eslint/no-empty-function
  244. destroy() { }
  245. /**
  246. * sync change another panel month when change months from the else yam panel
  247. * call it when
  248. * - current change panel targe date month is same with another panel date
  249. *
  250. * @example
  251. * - panelType=right, target=new Date('2022-09-01') and left panel is in '2022-09' => call it, left panel minus one month to '2022-08'
  252. * - panelType=left, target=new Date('2021-12-01') and right panel is in '2021-12' => call it, right panel add one month to '2021-01'
  253. */
  254. handleSyncChangeMonths(options: { panelType: PanelType, target: Date }) {
  255. const { panelType, target } = options;
  256. const { type } = this._adapter.getProps();
  257. const { monthLeft, monthRight } = this._adapter.getStates();
  258. if (this.isRangeType(type)) {
  259. if (panelType === 'right' && differenceInCalendarMonths(target, monthLeft.pickerDate) === 0) {
  260. this.handleYearOrMonthChange('prevMonth', 'left', 1, true);
  261. } else if (panelType === 'left' && differenceInCalendarMonths(monthRight.pickerDate, target) === 0) {
  262. this.handleYearOrMonthChange('nextMonth', 'right', 1, true);
  263. }
  264. }
  265. }
  266. /**
  267. * Get the target date based on the panel type and switch type
  268. */
  269. getTargetChangeDate(options: { panelType: PanelType, switchType: YearMonthChangeType }) {
  270. const { panelType, switchType } = options;
  271. const { monthRight, monthLeft } = this._adapter.getStates();
  272. const currentDate = panelType === 'left' ? monthLeft.pickerDate : monthRight.pickerDate;
  273. let target: Date;
  274. switch (switchType) {
  275. case 'prevMonth':
  276. target = addMonths(currentDate, -1);
  277. break;
  278. case 'nextMonth':
  279. target = addMonths(currentDate, 1);
  280. break;
  281. case 'prevYear':
  282. target = addYears(currentDate, -1);
  283. break;
  284. case 'nextYear':
  285. target = addYears(currentDate, 1);
  286. break;
  287. }
  288. return target;
  289. }
  290. /**
  291. * Change month by yam panel
  292. */
  293. toMonth(panelType: PanelType, target: Date) {
  294. const { type } = this._adapter.getProps();
  295. const diff = this._getDiff('month', target, panelType);
  296. this.handleYearOrMonthChange(diff < 0 ? 'prevMonth' : 'nextMonth', panelType, Math.abs(diff), false);
  297. if (this.isRangeType(type)) {
  298. this.handleSyncChangeMonths({ panelType, target });
  299. }
  300. }
  301. toYear(panelType: PanelType, target: Date) {
  302. const diff = this._getDiff('year', target, panelType);
  303. this.handleYearOrMonthChange(diff < 0 ? 'prevYear' : 'nextYear', panelType, Math.abs(diff), false);
  304. }
  305. toYearMonth(panelType: PanelType, target: Date) {
  306. this.toYear(panelType, target);
  307. this.toMonth(panelType, target);
  308. }
  309. isRangeType(type?: Type) {
  310. const { type: typeFromProp } = this.getProps();
  311. const realType = type ? type : typeFromProp;
  312. return typeof realType === 'string' && /range/i.test(realType);
  313. }
  314. handleSwitchMonthOrYear(switchType: YearMonthChangeType, panelType: PanelType) {
  315. const { type, syncSwitchMonth } = this.getProps();
  316. const rangeType = this.isRangeType(type);
  317. // range type and syncSwitchMonth, we should change panels at same time
  318. if (rangeType && syncSwitchMonth) {
  319. this.handleYearOrMonthChange(switchType, 'left', 1, true);
  320. this.handleYearOrMonthChange(switchType, 'right', 1, true);
  321. } else {
  322. this.handleYearOrMonthChange(switchType, panelType);
  323. /**
  324. * default behavior (v2.2.0)
  325. * In order to prevent the two panels from being the same month, this will confuse the user when selecting the range
  326. * https://github.com/DouyinFE/semi-design/issues/260
  327. */
  328. if (rangeType) {
  329. const target = this.getTargetChangeDate({ panelType, switchType });
  330. this.handleSyncChangeMonths({ panelType, target });
  331. }
  332. }
  333. }
  334. prevMonth(panelType: PanelType) {
  335. this.handleSwitchMonthOrYear('prevMonth', panelType);
  336. }
  337. nextMonth(panelType: PanelType) {
  338. this.handleSwitchMonthOrYear('nextMonth', panelType);
  339. }
  340. prevYear(panelType: PanelType) {
  341. this.handleSwitchMonthOrYear('prevYear', panelType);
  342. }
  343. nextYear(panelType: PanelType) {
  344. this.handleSwitchMonthOrYear('nextYear', panelType);
  345. }
  346. /**
  347. * Calculate the year and month difference
  348. */
  349. _getDiff(type: 'month' | 'year', target: Date, panelType: PanelType) {
  350. const panelDetail = this._getPanelDetail(panelType);
  351. const diff = dateDiffFns[type] && dateDiffFns[type](target, panelDetail.pickerDate);
  352. return diff;
  353. }
  354. _getPanelDetail(panelType: PanelType) {
  355. return panelType === strings.PANEL_TYPE_RIGHT ? this.getState('monthRight') : this.getState('monthLeft');
  356. }
  357. /**
  358. * Format locale date
  359. * locale get from LocaleProvider
  360. * @param {Date} date
  361. * @param {String} token
  362. * @returns
  363. */
  364. localeFormat(date: Date, token: string) {
  365. const dateFnsLocale = this._adapter.getProp('dateFnsLocale');
  366. return format(date, token, { locale: dateFnsLocale });
  367. }
  368. isValidTimeZone(timeZone?: string | number) {
  369. const propTimeZone = this.getProp('timeZone');
  370. const _timeZone = isNullOrUndefined(timeZone) ? propTimeZone : timeZone;
  371. return ['string', 'number'].includes(typeof _timeZone) && _timeZone !== '';
  372. }
  373. /**
  374. * 根据 type 处理 onChange 返回的参数
  375. *
  376. * - 返回的日期需要把用户时间转换为设置的时区时间
  377. * - 用户时间:用户计算机系统时间
  378. * - 时区时间:通过 ConfigProvider 设置的 timeZone
  379. * - 例子:用户设置时区为+9,计算机所在时区为+8区,然后用户选择了22:00
  380. * - DatePicker 内部保存日期 state 为 +8 的 22:00 => a = new Date("2021-05-25 22:00:00")
  381. * - 传出去时,需要把 +8 的 22:00 => +9 的 22:00 => b = zonedTimeToUtc(a, "+09:00");
  382. *
  383. * The parameters returned by onChange are processed according to type
  384. *
  385. * -The returned date needs to convert the user time to the set time zone time
  386. * -User time: user computer system time
  387. * -Time zone: timeZone set by ConfigProvider
  388. * -Example: The user sets the time zone to + 9, and the time zone where the computer is located is + 8, and then the user selects 22:00
  389. * -DatePicker internal save date state is + 8 22:00 = > a = new Date ("2021-05-25 22:00:00")
  390. * -When passing out, you need to put + 8's 22:00 = > + 9's 22:00 = > b = zonedTimeToUtc (a, "+ 09:00");
  391. *
  392. * e.g.
  393. * let a = new Date ("2021-05-25 22:00:00");
  394. * = > Tue May 25 2021 22:00:00 GMT + 0800 (China Standard Time)
  395. * let b = zonedTimeToUtc (a, "+ 09:00");
  396. * = > Tue May 25 2021 21:00:00 GMT + 0800 (China Standard Time)
  397. *
  398. * @param {Date|Date[]} value
  399. */
  400. disposeCallbackArgs(value: Date | Date[]) {
  401. let _value = Array.isArray(value) ? value : (value && [value]) || [];
  402. if (this.isValidTimeZone()) {
  403. const timeZone = this.getProp('timeZone');
  404. _value = _value.map(date => zonedTimeToUtc(date, timeZone));
  405. }
  406. const type = this.getProp('type');
  407. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  408. let notifyValue,
  409. notifyDate;
  410. switch (type) {
  411. case 'date':
  412. case 'dateTime':
  413. case 'month':
  414. if (!this._isMultiple()) {
  415. notifyValue = _value[0] && this.localeFormat(_value[0], formatToken);
  416. [notifyDate] = _value;
  417. } else {
  418. notifyValue = _value.map(v => v && this.localeFormat(v, formatToken));
  419. notifyDate = [..._value];
  420. }
  421. break;
  422. case 'dateRange':
  423. case 'dateTimeRange':
  424. notifyValue = _value.map(v => v && this.localeFormat(v, formatToken));
  425. notifyDate = [..._value];
  426. break;
  427. default:
  428. break;
  429. }
  430. return {
  431. notifyValue,
  432. notifyDate,
  433. };
  434. }
  435. handleYearOrMonthChange(
  436. type: YearMonthChangeType,
  437. panelType: PanelType = strings.PANEL_TYPE_LEFT,
  438. step = 1,
  439. notSeparateInRange = false
  440. ) {
  441. const { autoSwitchDate, type: datePanelType } = this.getProps();
  442. const { monthLeft, monthRight } = this.getStates();
  443. const isRangeType = this.isRangeType(datePanelType);
  444. const isLeftPanelInRange = isRangeType && panelType === strings.PANEL_TYPE_LEFT;
  445. const panelDetail = this._getPanelDetail(panelType);
  446. const { pickerDate } = panelDetail;
  447. const fn = dateCalcFns[type];
  448. const targetMonth = fn(pickerDate, step);
  449. // Determine if the date has changed
  450. const panelDateHasUpdate = (panelType === strings.PANEL_TYPE_LEFT && !isEqual(targetMonth, monthLeft.pickerDate)) ||
  451. (panelType === strings.PANEL_TYPE_RIGHT && !isEqual(targetMonth, monthRight.pickerDate));
  452. this._updatePanelDetail(panelType, { pickerDate: targetMonth });
  453. if (panelDateHasUpdate) { // When the date changes
  454. if (!isRangeType) { // Single Panel Type
  455. const { notifyValue, notifyDate } = this.disposeCallbackArgs(targetMonth);
  456. this._adapter.notifyPanelChange(notifyDate, notifyValue);
  457. } else { // Double Panel Type
  458. if (isLeftPanelInRange) { // Left panel
  459. this.newBiMonthPanelDate[0] = targetMonth;
  460. } else { // Right panel
  461. this.newBiMonthPanelDate[1] = targetMonth;
  462. }
  463. if (!(isLeftPanelInRange && notSeparateInRange)) { // Not synchronously switching the left panel in the scene
  464. const { notifyValue, notifyDate } = this.disposeCallbackArgs(this.newBiMonthPanelDate);
  465. this._adapter.notifyPanelChange(notifyDate, notifyValue);
  466. }
  467. }
  468. }
  469. if (autoSwitchDate) {
  470. this.updateDateAfterChangeYM(type, targetMonth);
  471. }
  472. }
  473. /**
  474. * You have chosen to switch the year and month in the future to directly update the Date without closing the date panel
  475. * @param {*} type
  476. * @param {*} targetDate
  477. */
  478. updateDateAfterChangeYM(
  479. type: YearMonthChangeType,
  480. targetDate: Date
  481. ) {
  482. const { multiple, disabledDate } = this.getProps();
  483. const { selected: selectedSet, rangeStart, rangeEnd } = this.getStates();
  484. const includeRange = ['dateRange', 'dateTimeRange'].includes(type);
  485. const options = { closePanel: false };
  486. if (!multiple && !includeRange && selectedSet.size) {
  487. const selectedStr = Array.from(selectedSet)[0] as string;
  488. const selectedDate = new Date(selectedStr);
  489. const year = targetDate.getFullYear();
  490. const month = targetDate.getMonth();
  491. const fullDate = set(selectedDate, { year, month });
  492. if (disabledDate(fullDate, { rangeStart, rangeEnd })) {
  493. return;
  494. }
  495. this._adapter.notifySelectedChange([fullDate], options);
  496. }
  497. }
  498. _isMultiple() {
  499. return Boolean(this.getProp('multiple')) && this.getProp('type') === 'date';
  500. }
  501. _isRange() {
  502. // return this._adapter.getProp('type') === dateRangeTypeKey;
  503. }
  504. handleDayClick(day: MonthDayInfo, panelType: PanelType) {
  505. const type = this.getProp('type');
  506. switch (true) {
  507. case type === 'date' || type === 'dateTime':
  508. this.handleDateSelected(day, panelType);
  509. break;
  510. case type === 'dateRange' || type === 'dateTimeRange':
  511. this.handleRangeSelected(day);
  512. break;
  513. default:
  514. break;
  515. }
  516. }
  517. handleDateSelected(day: { fullDate: string; fullValidDate?: Date }, panelType: PanelType) {
  518. const { max, type, isControlledComponent, dateFnsLocale } = this.getProps();
  519. const multiple = this._isMultiple();
  520. const { selected } = this.getStates();
  521. const monthDetail = this._getPanelDetail(panelType);
  522. const newSelected = new Set(multiple ? [...selected] : []);
  523. const { fullDate } = day;
  524. const time = monthDetail.pickerDate;
  525. const dateStr = type === 'dateTime' ? this._mergeDateAndTime(fullDate, time) : fullDate;
  526. if (!multiple) {
  527. newSelected.add(dateStr);
  528. } else {
  529. if (newSelected.has(dateStr)) {
  530. newSelected.delete(dateStr);
  531. } else if (max && newSelected.size === max) {
  532. this._adapter.notifyMaxLimit();
  533. } else {
  534. newSelected.add(dateStr);
  535. }
  536. }
  537. const dateFormat = this.getValidDateFormat();
  538. // When passed to the upper layer, it is converted into a Date object to ensure that the input parameter format of initFormDefaultValue is consistent
  539. const newSelectedDates = [...newSelected].map(_dateStr => compatiableParse(_dateStr, dateFormat, undefined, dateFnsLocale));
  540. this.handleShowDateAndTime(panelType, time);
  541. if (!isControlledComponent) {
  542. // Uncontrolled components, update internal values when operating, and notify external
  543. // MonthGrid internally uses string to represent fullDate for easy rendering
  544. this._adapter.updateDaySelected(newSelected);
  545. }
  546. this._adapter.notifySelectedChange(newSelectedDates as [Date]);
  547. }
  548. handleShowDateAndTime(panelType: PanelType, pickerDate: number | Date, showDate?: Date) {
  549. const _showDate = showDate || pickerDate;
  550. this._updatePanelDetail(panelType, { showDate: _showDate, pickerDate });
  551. }
  552. /**
  553. * link date and time
  554. *
  555. * @param {Date|string} date
  556. * @param {Date|string} time
  557. * @returns {Date}
  558. */
  559. _mergeDateAndTime(date: Date | string, time: Date | string) {
  560. const dateFnsLocale = this._adapter.getProp('dateFnsLocale');
  561. const dateStr = format(
  562. isValidDate(date) ? date as Date : compatiableParse(date as string, strings.FORMAT_FULL_DATE, undefined, dateFnsLocale),
  563. strings.FORMAT_FULL_DATE
  564. );
  565. const timeStr = format(
  566. isValidDate(time) ? time as Date : compatiableParse(time as string, strings.FORMAT_TIME_PICKER, undefined, dateFnsLocale),
  567. strings.FORMAT_TIME_PICKER
  568. );
  569. const timeFormat = this.getValidTimeFormat();
  570. return compatiableParse(`${dateStr} ${timeStr}`, timeFormat, undefined, dateFnsLocale);
  571. }
  572. handleRangeSelected(day: MonthDayInfo) {
  573. let { rangeStart, rangeEnd } = this.getStates();
  574. const { startDateOffset, endDateOffset, type, dateFnsLocale, rangeInputFocus } = this.getProps();
  575. const { fullDate } = day;
  576. let rangeStartReset = false;
  577. let rangeEndReset = false;
  578. const isDateRangeAndHasOffset = (startDateOffset || endDateOffset) && type === 'dateRange';
  579. if (isDateRangeAndHasOffset) {
  580. rangeStart = getFullDateOffset(startDateOffset, fullDate);
  581. rangeEnd = getFullDateOffset(endDateOffset, fullDate);
  582. } else {
  583. if (rangeInputFocus === 'rangeEnd') {
  584. rangeEnd = fullDate;
  585. // rangStart Parten in dateTime: 'yyyy-MM-dd HH:MM:SS', rangeEnd parten: 'yyyy-MM-dd'
  586. if ((rangeStart && rangeEnd) && isBefore(rangeEnd, rangeStart.trim().split(/\s+/)[0])) {
  587. rangeStart = null;
  588. rangeStartReset = true;
  589. }
  590. // Compatible to select date after opening the panel without click input
  591. } else if (rangeInputFocus === 'rangeStart' || !rangeInputFocus) {
  592. rangeStart = fullDate;
  593. // rangEnd Parten in dateTime: 'yyyy-MM-dd HH:MM:SS', rangeStart parten: 'yyyy-MM-dd'
  594. if ((rangeStart && rangeEnd) && isBefore(rangeEnd.trim().split(/\s+/)[0], rangeStart)) {
  595. rangeEnd = null;
  596. rangeEndReset = true;
  597. }
  598. }
  599. }
  600. // next focus logic
  601. const isRangeType = /range/i.test(type);
  602. if (isRangeType) {
  603. if (isDateRangeAndHasOffset) {
  604. this._adapter.setRangeStart(rangeStart);
  605. this._adapter.setRangeEnd(rangeEnd);
  606. } else {
  607. if (rangeInputFocus === 'rangeEnd') {
  608. this._adapter.setRangeEnd(rangeEnd);
  609. if (rangeStartReset) {
  610. this._adapter.setRangeStart(rangeStart);
  611. }
  612. if (!this._adapter.isAnotherPanelHasOpened('rangeEnd') || !rangeStart) {
  613. this._adapter.setRangeInputFocus('rangeStart');
  614. }
  615. } else if (rangeInputFocus === 'rangeStart' || !rangeInputFocus) {
  616. this._adapter.setRangeStart(rangeStart);
  617. if (rangeEndReset) {
  618. this._adapter.setRangeEnd(rangeEnd);
  619. }
  620. if (!this._adapter.isAnotherPanelHasOpened('rangeStart') || !rangeEnd) {
  621. this._adapter.setRangeInputFocus('rangeEnd');
  622. }
  623. }
  624. }
  625. }
  626. const dateFormat = this.getValidDateFormat();
  627. // only notify when choose completed
  628. if (rangeStart || rangeEnd) {
  629. const [startDate, endDate] = [
  630. compatiableParse(rangeStart, dateFormat, undefined, dateFnsLocale),
  631. compatiableParse(rangeEnd, dateFormat, undefined, dateFnsLocale),
  632. ];
  633. let date: [Date, Date] = [startDate, endDate];
  634. // If the type is dateRangeTime, add the value of time
  635. if (type === 'dateTimeRange') {
  636. const startTime = this.getState('monthLeft').pickerDate;
  637. const endTime = this.getState('monthRight').pickerDate;
  638. const start = rangeStart ? this._mergeDateAndTime(rangeStart, startTime) : null;
  639. const end = rangeEnd ? this._mergeDateAndTime(rangeEnd, endTime) : null;
  640. if (isSameDay(startDate, endDate) && isBefore(end, start)) {
  641. date = [start, start];
  642. } else {
  643. date = [start, end];
  644. }
  645. }
  646. this._adapter.notifySelectedChange(date, { needCheckFocusRecord: !(type === 'dateRange' && isDateRangeAndHasOffset) });
  647. }
  648. }
  649. _isNeedSwap(rangeStart: Date | string, rangeEnd: Date | string) {
  650. // Check whether the start and end are reasonable and whether they need to be reversed
  651. return rangeStart && rangeEnd && isBefore(rangeEnd, rangeStart);
  652. }
  653. /**
  654. * Day may be empty, this is unhover state
  655. * @param {*} day
  656. */
  657. handleDayHover(day = { fullDate: '' }, panelType?: PanelType) {
  658. const { fullDate } = day;
  659. const { startDateOffset, endDateOffset, type } = this.getProps();
  660. this._adapter.setHoverDay(fullDate);
  661. if ((startDateOffset || endDateOffset) && type === 'dateRange') {
  662. const offsetRangeStart = getFullDateOffset(startDateOffset, fullDate);
  663. const offsetRangeEnd = getFullDateOffset(endDateOffset, fullDate);
  664. this._adapter.setOffsetRangeStart(offsetRangeStart);
  665. this._adapter.setOffsetRangeEnd(offsetRangeEnd);
  666. }
  667. }
  668. // Guarantee that monthLeft, monthRight will not appear in the same month or monthLeft is greater than MonthRight
  669. _autoAdjustMonth(monthLeft: MonthInfo, monthRight: MonthInfo) {
  670. let newMonthLeft = monthLeft;
  671. let newMonthRight = monthRight;
  672. const difference = differenceInCalendarMonths(monthLeft.pickerDate, monthRight.pickerDate);
  673. if (difference > 0) {
  674. // The month on the left is larger than the month on the right, swap
  675. newMonthLeft = { ...monthRight };
  676. newMonthRight = { ...monthLeft };
  677. } else if (difference === 0) {
  678. // Around the same month, the number of months on the right + 1
  679. newMonthLeft = monthLeft;
  680. newMonthRight = { ...monthRight, pickerDate: addMonths(monthRight.pickerDate, 1) };
  681. }
  682. return { monthLeft: newMonthLeft, monthRight: newMonthRight };
  683. }
  684. getValidTimeFormat() {
  685. const formatProp = this.getProp('format') || strings.FORMAT_TIME_PICKER;
  686. const timeFormatTokens = [];
  687. if (includes(formatProp, 'h') || includes(formatProp, 'H')) {
  688. timeFormatTokens.push('HH');
  689. }
  690. if (includes(formatProp, 'm')) {
  691. timeFormatTokens.push('mm');
  692. }
  693. if (includes(formatProp, 's')) {
  694. timeFormatTokens.push('ss');
  695. }
  696. return timeFormatTokens.join(':');
  697. }
  698. getValidDateFormat() {
  699. return this.getProp('format') || getDefaultFormatToken(this.getProp('type'));
  700. }
  701. handleTimeChange(newTime: { timeStampValue: number }, panelType: PanelType) {
  702. const { rangeEnd, rangeStart } = this.getStates();
  703. const dateFnsLocale = this.getProp('dateFnsLocale');
  704. const ts = newTime.timeStampValue;
  705. const type = this.getProp('type');
  706. const panelDetail = this._getPanelDetail(panelType);
  707. const { showDate } = panelDetail;
  708. const timeDate = new Date(ts);
  709. const dateFormat = this.getValidDateFormat();
  710. const destRange = panelType === strings.PANEL_TYPE_RIGHT ? rangeEnd : rangeStart;
  711. let year,
  712. monthNo,
  713. date;
  714. // if (pickerDate && isValidDate(pickerDate)) {
  715. // year = pickerDate.getFullYear();
  716. // monthNo = pickerDate.getMonth();
  717. // date = pickerDate.getDate();
  718. // } else
  719. if (type === 'dateTimeRange' && destRange) {
  720. const rangeDate = compatiableParse(destRange, dateFormat, undefined, dateFnsLocale);
  721. year = rangeDate.getFullYear();
  722. monthNo = rangeDate.getMonth();
  723. date = rangeDate.getDate();
  724. } else {
  725. year = showDate.getFullYear();
  726. monthNo = showDate.getMonth();
  727. date = showDate.getDate();
  728. }
  729. const hours = timeDate.getHours();
  730. const minutes = timeDate.getMinutes();
  731. const seconds = timeDate.getSeconds();
  732. const milSeconds = timeDate.getMilliseconds();
  733. const dateArgs = [year, monthNo, date, hours, minutes, seconds, milSeconds] as const;
  734. const fullValidDate = new Date(...dateArgs);
  735. if (type === 'dateTimeRange') {
  736. this.handleShowDateAndTime(panelType, fullValidDate, showDate);
  737. this._updateTimeInDateRange(panelType, fullValidDate);
  738. } else {
  739. const fullDate = formatFullDate(year, monthNo + 1, date);
  740. this.handleDateSelected(
  741. {
  742. fullDate,
  743. fullValidDate,
  744. },
  745. panelType
  746. );
  747. this.handleShowDateAndTime(panelType, fullValidDate);
  748. this._adapter.notifySelectedChange([fullValidDate]);
  749. }
  750. }
  751. /**
  752. * Update the time part in the range
  753. * @param {string} panelType
  754. * @param {Date} timeDate
  755. */
  756. _updateTimeInDateRange(panelType: PanelType, timeDate: Date) {
  757. const { isControlledComponent, dateFnsLocale } = this.getProps();
  758. let rangeStart = this.getState('rangeStart');
  759. let rangeEnd = this.getState('rangeEnd');
  760. const dateFormat = this.getValidDateFormat();
  761. // TODO: Modify a time individually
  762. if (rangeStart && rangeEnd) {
  763. let startDate = compatiableParse(rangeStart, dateFormat, undefined, dateFnsLocale);
  764. let endDate = compatiableParse(rangeEnd, dateFormat, undefined, dateFnsLocale);
  765. // console.log('_updateTimeInDateRange()', rangeStart, rangeEnd, startDate, endDate);
  766. if (panelType === strings.PANEL_TYPE_RIGHT) {
  767. endDate = this._mergeDateAndTime(timeDate, timeDate);
  768. rangeEnd = format(endDate, strings.FORMAT_DATE_TIME);
  769. if (this._isNeedSwap(rangeStart, rangeEnd)) {
  770. [rangeStart, rangeEnd] = [rangeEnd, rangeStart];
  771. [startDate, endDate] = [endDate, startDate];
  772. }
  773. if (!isControlledComponent) {
  774. this._adapter.setRangeEnd(rangeEnd);
  775. }
  776. } else {
  777. startDate = this._mergeDateAndTime(timeDate, timeDate);
  778. rangeStart = format(startDate, strings.FORMAT_DATE_TIME);
  779. if (this._isNeedSwap(rangeStart, rangeEnd)) {
  780. [rangeStart, rangeEnd] = [rangeEnd, rangeStart];
  781. [startDate, endDate] = [endDate, startDate];
  782. }
  783. if (!isControlledComponent) {
  784. this._adapter.setRangeStart(rangeStart);
  785. }
  786. }
  787. // console.log('_updateTimeInDateRange()', rangeStart, rangeEnd, startDate, endDate);
  788. this._adapter.notifySelectedChange([startDate, endDate]);
  789. }
  790. }
  791. _updatePanelDetail(
  792. panelType: PanelType,
  793. kvs: {
  794. showDate?: number | Date;
  795. pickerDate?: number | Date;
  796. isTimePickerOpen?: boolean;
  797. isYearPickerOpen?: boolean;
  798. }
  799. ) {
  800. const { monthLeft, monthRight } = this.getStates();
  801. if (panelType === strings.PANEL_TYPE_RIGHT) {
  802. this._adapter.updateMonthOnRight({ ...monthRight, ...kvs });
  803. } else {
  804. this._adapter.updateMonthOnLeft({ ...monthLeft, ...kvs });
  805. }
  806. }
  807. showYearPicker(panelType: PanelType) {
  808. this._updatePanelDetail(panelType, { isTimePickerOpen: false, isYearPickerOpen: true });
  809. }
  810. showTimePicker(panelType: PanelType, opt?: boolean) {
  811. if (this.getProp('disabledTimePicker')) {
  812. return;
  813. }
  814. this._updatePanelDetail(panelType, { isTimePickerOpen: true, isYearPickerOpen: false });
  815. }
  816. showDatePanel(panelType: PanelType) {
  817. this._updatePanelDetail(panelType, { isTimePickerOpen: false, isYearPickerOpen: false });
  818. }
  819. /**
  820. * Get year and month panel open type
  821. *
  822. * It is useful info to set minHeight of weeks.
  823. * - When yam open type is 'left' or 'right', weeks minHeight should be set
  824. * If the minHeight is not set, the change of the number of weeks will cause the scrollList to be unstable
  825. */
  826. getYAMOpenType() {
  827. const { monthLeft, monthRight } = this._adapter.getStates();
  828. const leftYearPickerOpen = monthLeft.isYearPickerOpen;
  829. const rightYearPickerOpen = monthRight.isYearPickerOpen;
  830. if (leftYearPickerOpen && rightYearPickerOpen) {
  831. return 'both';
  832. } else if (leftYearPickerOpen) {
  833. return 'left';
  834. } else if (rightYearPickerOpen) {
  835. return 'right';
  836. } else {
  837. return 'none';
  838. }
  839. }
  840. }