monthsGridFoundation.ts 38 KB

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