1
0

monthsGridFoundation.ts 38 KB

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