monthsGridFoundation.ts 38 KB

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