monthsGridFoundation.ts 39 KB

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