monthsGridFoundation.ts 40 KB

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