monthsGridFoundation.ts 38 KB

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