monthsGrid.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /* eslint-disable react/no-did-update-set-state */
  2. /* eslint-disable max-len */
  3. /* eslint-disable no-nested-ternary */
  4. import React from 'react';
  5. import classnames from 'classnames';
  6. import PropTypes from 'prop-types';
  7. import { format as formatFn, addMonths, isSameDay } from 'date-fns';
  8. import MonthsGridFoundation, { MonthInfo, MonthsGridAdapter, MonthsGridDateAdapter, MonthsGridFoundationProps, MonthsGridFoundationState, MonthsGridRangeAdapter, PanelType } from '@douyinfe/semi-foundation/datePicker/monthsGridFoundation';
  9. import { strings, numbers, cssClasses } from '@douyinfe/semi-foundation/datePicker/constants';
  10. import { compatiableParse } from '@douyinfe/semi-foundation/datePicker/_utils/parser';
  11. import { noop, stubFalse } from 'lodash';
  12. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  13. import Navigation from './navigation';
  14. import Month from './month';
  15. import Combobox from '../timePicker/Combobox';
  16. import YearAndMonth from './yearAndMonth';
  17. import { IconClock, IconCalendar } from '@douyinfe/semi-icons';
  18. import { getDefaultFormatTokenByType } from '@douyinfe/semi-foundation/datePicker/_utils/getDefaultFormatToken';
  19. const prefixCls = cssClasses.PREFIX;
  20. export interface MonthsGridProps extends MonthsGridFoundationProps, BaseProps {
  21. navPrev?: React.ReactNode;
  22. navNext?: React.ReactNode;
  23. renderDate?: () => React.ReactNode;
  24. renderFullDate?: () => React.ReactNode;
  25. focusRecordsRef?: React.RefObject<{ rangeStart: boolean; rangeEnd: boolean }>;
  26. }
  27. export type MonthsGridState = MonthsGridFoundationState;
  28. export default class MonthsGrid extends BaseComponent<MonthsGridProps, MonthsGridState> {
  29. static propTypes = {
  30. type: PropTypes.oneOf(strings.TYPE_SET),
  31. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object, PropTypes.array]),
  32. defaultPickerValue: PropTypes.oneOfType([
  33. PropTypes.string,
  34. PropTypes.number,
  35. PropTypes.object,
  36. PropTypes.array,
  37. ]),
  38. multiple: PropTypes.bool,
  39. max: PropTypes.number, // only work when multiple is true
  40. weekStartsOn: PropTypes.number,
  41. disabledDate: PropTypes.func,
  42. disabledTime: PropTypes.func,
  43. disabledTimePicker: PropTypes.bool,
  44. hideDisabledOptions: PropTypes.bool,
  45. navPrev: PropTypes.node,
  46. navNext: PropTypes.node,
  47. onMaxSelect: PropTypes.func,
  48. timePickerOpts: PropTypes.object,
  49. // Whether the outer datePicker is a controlled component
  50. isControlledComponent: PropTypes.bool,
  51. rangeStart: PropTypes.oneOfType([PropTypes.string]),
  52. rangeInputFocus: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  53. locale: PropTypes.object,
  54. localeCode: PropTypes.string,
  55. format: PropTypes.string,
  56. renderDate: PropTypes.func,
  57. renderFullDate: PropTypes.func,
  58. startDateOffset: PropTypes.func,
  59. endDateOffset: PropTypes.func,
  60. autoSwitchDate: PropTypes.bool,
  61. motionEnd: PropTypes.bool,
  62. density: PropTypes.string,
  63. dateFnsLocale: PropTypes.object.isRequired,
  64. timeZone: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  65. // Support synchronous switching of months
  66. syncSwitchMonth: PropTypes.bool,
  67. // Callback function for panel date switching
  68. onPanelChange: PropTypes.func,
  69. focusRecordsRef: PropTypes.object,
  70. triggerRender: PropTypes.func,
  71. };
  72. static defaultProps = {
  73. type: 'date',
  74. rangeStart: '',
  75. multiple: false,
  76. weekStartsOn: numbers.WEEK_START_ON,
  77. disabledDate: stubFalse,
  78. onMaxSelect: noop,
  79. locale: {},
  80. };
  81. foundation: MonthsGridFoundation;
  82. constructor(props: MonthsGridProps) {
  83. super(props);
  84. let nowDate = Array.isArray(props.defaultPickerValue) ? props.defaultPickerValue[0] : props.defaultPickerValue;
  85. const validFormat = props.format || getDefaultFormatTokenByType(props.type);
  86. if (!nowDate) {
  87. nowDate = new Date();
  88. } else {
  89. nowDate = compatiableParse(nowDate as string, validFormat, undefined, props.dateFnsLocale);
  90. }
  91. let nextDate = Array.isArray(props.defaultPickerValue) ? props.defaultPickerValue[1] : undefined;
  92. if (!nextDate) {
  93. nextDate = addMonths(nowDate, 1);
  94. } else {
  95. nextDate = compatiableParse(nextDate as string, validFormat, undefined, props.dateFnsLocale);
  96. }
  97. const dateState = {
  98. // Direct use of full date string storage, mainly considering the month rendering comparison to save a conversion
  99. // The selected value for single or multiple selection, full date string, eg. {'2019-10-01', '2019-10-02'}
  100. selected: new Set<string>(),
  101. };
  102. const rangeState = {
  103. monthLeft: {
  104. pickerDate: nowDate,
  105. showDate: nowDate,
  106. isTimePickerOpen: false,
  107. isYearPickerOpen: false,
  108. },
  109. monthRight: {
  110. pickerDate: nextDate,
  111. showDate: nextDate,
  112. isTimePickerOpen: false,
  113. isYearPickerOpen: false,
  114. },
  115. maxWeekNum: 0, // Maximum number of weeks left and right for manual height adjustment
  116. hoverDay: '', // Real-time hover date
  117. rangeStart: props.rangeStart, // Start date for range selection
  118. rangeEnd: '', // End date of range selection
  119. currentPanelHeight: 0, // current month panel height,
  120. offsetRangeStart: '',
  121. offsetRangeEnd: '',
  122. };
  123. this.state = {
  124. ...dateState,
  125. ...rangeState,
  126. };
  127. this.foundation = new MonthsGridFoundation(this.adapter);
  128. }
  129. get dateAdapter(): MonthsGridDateAdapter {
  130. return {
  131. updateDaySelected: selected => this.setState({ selected }),
  132. };
  133. }
  134. get rangeAdapter(): MonthsGridRangeAdapter {
  135. return {
  136. setRangeStart: rangeStart => this.setState({ rangeStart }),
  137. setRangeEnd: rangeEnd => this.setState({ rangeEnd }),
  138. setHoverDay: hoverDay => this.setState({ hoverDay }),
  139. setWeeksHeight: maxWeekNum => this.setState({ maxWeekNum }),
  140. setOffsetRangeStart: offsetRangeStart => this.setState({ offsetRangeStart }),
  141. setOffsetRangeEnd: offsetRangeEnd => this.setState({ offsetRangeEnd }),
  142. };
  143. }
  144. get adapter(): MonthsGridAdapter {
  145. return {
  146. ...super.adapter,
  147. ...this.dateAdapter,
  148. ...this.rangeAdapter,
  149. updateMonthOnLeft: v => this.setState({ monthLeft: v }),
  150. updateMonthOnRight: v => this.setState({ monthRight: v }),
  151. notifySelectedChange: (value, options) => this.props.onChange(value, options),
  152. notifyMaxLimit: v => this.props.onMaxSelect(v),
  153. notifyPanelChange: (date, dateString) => this.props.onPanelChange(date, dateString),
  154. setRangeInputFocus: rangeInputFocus => this.props.setRangeInputFocus(rangeInputFocus),
  155. isAnotherPanelHasOpened: currentRangeInput => this.props.isAnotherPanelHasOpened(currentRangeInput)
  156. };
  157. }
  158. componentDidMount() {
  159. super.componentDidMount();
  160. }
  161. componentDidUpdate(prevProps: MonthsGridProps, prevState: MonthsGridState) {
  162. const { defaultValue, defaultPickerValue, motionEnd } = this.props;
  163. if (prevProps.defaultValue !== defaultValue) {
  164. this.foundation.updateSelectedFromProps(defaultValue, false);
  165. }
  166. if (prevProps.defaultPickerValue !== defaultPickerValue) {
  167. this.foundation.initDefaultPickerValue();
  168. }
  169. if (prevProps.motionEnd !== motionEnd && motionEnd === true) {
  170. if (this.foundation.isRangeType()) {
  171. const currentPanelHeight = this.calcScrollListHeight();
  172. this.setState({ currentPanelHeight });
  173. }
  174. }
  175. const isRange = this.foundation.isRangeType();
  176. if (isRange) {
  177. /**
  178. * we have to add these code to ensure that scroll list's selector places center
  179. */
  180. const prevAll = this.leftIsYearOrTime(prevState) && this.rightIsYearOrTime(prevState);
  181. const prevSome =
  182. (this.leftIsYearOrTime(prevState) && !this.rightIsYearOrTime(prevState)) ||
  183. (!this.leftIsYearOrTime(prevState) && this.rightIsYearOrTime(prevState));
  184. const nowAll = this.leftIsYearOrTime() && this.rightIsYearOrTime();
  185. const nowSome =
  186. (this.leftIsYearOrTime() && !this.rightIsYearOrTime()) ||
  187. (!this.leftIsYearOrTime() && this.rightIsYearOrTime());
  188. const prevAllToSome = prevAll && nowSome;
  189. const prevSomeToAll = prevSome && nowAll;
  190. if (prevSomeToAll) {
  191. this.setState({ currentPanelHeight: this.calcScrollListHeight() }, this.reselect);
  192. } else if (prevAllToSome) {
  193. this.reselect();
  194. }
  195. }
  196. }
  197. cacheRefCurrent = (key: string, current: Combobox | YearAndMonth | HTMLDivElement) => {
  198. if (typeof key === 'string' && key.length) {
  199. this.adapter.setCache(key, current);
  200. }
  201. };
  202. leftIsYearOrTime = (state?: MonthsGridState) => {
  203. const { monthLeft } = state || this.state;
  204. if (monthLeft && (monthLeft.isTimePickerOpen || monthLeft.isYearPickerOpen)) {
  205. return true;
  206. } else {
  207. return false;
  208. }
  209. };
  210. rightIsYearOrTime = (state?: MonthsGridState) => {
  211. const { monthRight } = state || this.state;
  212. if (monthRight && (monthRight.isTimePickerOpen || monthRight.isYearPickerOpen)) {
  213. return true;
  214. } else {
  215. return false;
  216. }
  217. };
  218. /**
  219. * Calculate the height of the scrolling list, if the animation is not over, return 0
  220. */
  221. calcScrollListHeight = () => {
  222. const { motionEnd } = this.props;
  223. let wrapLeft, wrapRight, switchLeft, switchRight;
  224. if (motionEnd) {
  225. wrapLeft = this.adapter.getCache(`wrap-${strings.PANEL_TYPE_LEFT}`);
  226. wrapRight = this.adapter.getCache(`wrap-${strings.PANEL_TYPE_RIGHT}`);
  227. switchLeft = this.adapter.getCache(`switch-${strings.PANEL_TYPE_LEFT}`);
  228. switchRight = this.adapter.getCache(`switch-${strings.PANEL_TYPE_RIGHT}`);
  229. }
  230. const leftRect = wrapLeft && wrapLeft.getBoundingClientRect();
  231. const rightRect = wrapRight && wrapRight.getBoundingClientRect();
  232. let leftHeight = (leftRect && leftRect.height) || 0;
  233. let rightHeight = (rightRect && rightRect.height) || 0;
  234. if (switchLeft) {
  235. leftHeight += switchLeft.getBoundingClientRect().height;
  236. }
  237. if (switchRight) {
  238. rightHeight += switchRight.getBoundingClientRect().height;
  239. }
  240. return Math.max(leftHeight, rightHeight);
  241. };
  242. renderPanel(month: Date, panelType: PanelType) {
  243. let monthCls = classnames(`${prefixCls}-month-grid-${panelType}`);
  244. const { monthLeft, monthRight, currentPanelHeight } = this.state;
  245. const panelDetail = panelType === strings.PANEL_TYPE_RIGHT ? monthRight : monthLeft;
  246. const { isTimePickerOpen, isYearPickerOpen } = panelDetail;
  247. const panelContent = this.renderMonth(month, panelType);
  248. const yearAndMonthLayer = isYearPickerOpen ? (
  249. <div className={`${prefixCls}-yam`}>{this.renderYearAndMonth(panelType, panelDetail)}</div>
  250. ) : null;
  251. const timePickerLayer = isTimePickerOpen ? (
  252. <div className={`${prefixCls}-tpk`}>{this.renderTimePicker(panelType, panelDetail)}</div>
  253. ) : null;
  254. const style: React.CSSProperties = {};
  255. const wrapLeft = this.adapter.getCache(`wrap-${strings.PANEL_TYPE_LEFT}`);
  256. const wrapRight = this.adapter.getCache(`wrap-${strings.PANEL_TYPE_RIGHT}`);
  257. const wrap = panelType === strings.PANEL_TYPE_RIGHT ? wrapRight : wrapLeft;
  258. if (this.foundation.isRangeType()) {
  259. if (isYearPickerOpen || isTimePickerOpen) {
  260. style.minWidth = wrap.getBoundingClientRect().width;
  261. }
  262. if (this.leftIsYearOrTime() && this.rightIsYearOrTime()) {
  263. /**
  264. * left和right同时为tpk时,panel会有一个minHeight
  265. * 如果缓存的currentPanelHeight为0,则需要计算滚动列表的高度
  266. * 如果有缓存的值则使用currentPanelHeight(若此高度<实际值,则会影响ScrollList中渲染列表的循环次数)
  267. * 详见 packages/semi-foundation/scrollList/itemFoundation.js initWheelList函数
  268. *
  269. * When left and right are tpk at the same time, the panel will have a minHeight
  270. * If the cached currentPanelHeight is 0, you need to calculate the height of the scrolling list
  271. * If there is a cached value, use currentPanelHeight (if this height is less than the actual value, it will affect the number of cycles in the ScrollList to render the list)
  272. * See packages/semi-foundation/scrollList/itemF oundation.js initWheelList function
  273. */
  274. style.minHeight = currentPanelHeight ? currentPanelHeight : this.calcScrollListHeight();
  275. }
  276. } else if (
  277. this.props.type !== 'year' &&
  278. this.props.type !== 'month' &&
  279. (isTimePickerOpen || isYearPickerOpen)
  280. ) {
  281. monthCls = classnames(monthCls, `${prefixCls}-yam-showing`);
  282. }
  283. return (
  284. <div className={monthCls} key={panelType} style={style}>
  285. {yearAndMonthLayer}
  286. {timePickerLayer}
  287. {/* {isYearPickerOpen || isTimePickerOpen ? null : panelContent} */}
  288. {this.foundation.isRangeType() ? panelContent : isYearPickerOpen || isTimePickerOpen ? null : panelContent}
  289. {this.renderSwitch(panelType)}
  290. </div>
  291. );
  292. }
  293. showYearPicker(panelType: PanelType, e: React.MouseEvent) {
  294. // e.stopPropagation();
  295. // When switching to the year and month, the e.target at this time is generated from Navigation, and the Navigation module will be removed from the DOM after switching
  296. // If you do not prevent the event from spreading to index.jsx, panel.contain (e.target) in clickOutSide will call closePanel because there is no Nav in the Panel and think this click is clickOutSide
  297. // Cause the entire component pop-up window to be closed by mistake
  298. // console.log(this.navRef.current.clientHeight, this.monthRef.current.clientHeight);
  299. // this.wrapRef.current.style.height = this.wrapRef.current.clientHeight + 'px';
  300. // this.wrapRef.current.style.overflow = 'hidden';
  301. e.nativeEvent.stopImmediatePropagation();
  302. this.foundation.showYearPicker(panelType);
  303. }
  304. renderMonth(month: Date, panelType: PanelType) {
  305. const { selected, rangeStart, rangeEnd, hoverDay, maxWeekNum, offsetRangeStart, offsetRangeEnd } = this.state;
  306. const { weekStartsOn, disabledDate, locale, localeCode, renderDate, renderFullDate, startDateOffset, endDateOffset, density, rangeInputFocus, syncSwitchMonth } = this.props;
  307. let monthText = '';
  308. // i18n monthText
  309. if (month) {
  310. // Get the absolute value of the year and month
  311. const yearNumber = month ? formatFn(month, 'yyyy') : '';
  312. const monthNumber = month ? formatFn(month, 'L') : '';
  313. // Display the month as the corresponding language text
  314. const mText = locale.months[monthNumber];
  315. const monthFormatToken = locale.monthText;
  316. // Display the year and month in a specific language format order
  317. monthText = monthFormatToken.replace('${year}', yearNumber).replace('${month}', mText);
  318. }
  319. let style = {};
  320. const detail = panelType === strings.PANEL_TYPE_RIGHT ? this.state.monthRight : this.state.monthLeft;
  321. // Whether to select type for range
  322. const isRangeType = this.foundation.isRangeType();
  323. // Whether to switch synchronously for two panels
  324. const shouldBimonthSwitch = isRangeType && syncSwitchMonth;
  325. if (isRangeType && detail && (detail.isYearPickerOpen || detail.isTimePickerOpen)) {
  326. style = {
  327. visibility: 'hidden',
  328. position: 'absolute',
  329. pointerEvents: 'none',
  330. };
  331. }
  332. return (
  333. <div ref={current => this.cacheRefCurrent(`wrap-${panelType}`, current)} style={style}>
  334. <Navigation
  335. forwardRef={current => this.cacheRefCurrent(`nav-${panelType}`, current)}
  336. monthText={monthText}
  337. density={density}
  338. onMonthClick={e => this.showYearPicker(panelType, e)}
  339. onPrevMonth={() => this.foundation.prevMonth(panelType)}
  340. onNextMonth={() => this.foundation.nextMonth(panelType)}
  341. onNextYear={() => this.foundation.nextYear(panelType)}
  342. onPrevYear={() => this.foundation.prevYear(panelType)}
  343. shouldBimonthSwitch={shouldBimonthSwitch}
  344. panelType={panelType}
  345. />
  346. <Month
  347. locale={locale}
  348. localeCode={localeCode}
  349. forwardRef={current => this.cacheRefCurrent(`month-${panelType}`, current)}
  350. disabledDate={disabledDate}
  351. weekStartsOn={weekStartsOn}
  352. month={month}
  353. selected={selected}
  354. rangeStart={rangeStart}
  355. rangeEnd={rangeEnd}
  356. rangeInputFocus={rangeInputFocus}
  357. offsetRangeStart={offsetRangeStart}
  358. offsetRangeEnd={offsetRangeEnd}
  359. hoverDay={hoverDay}
  360. weeksRowNum={maxWeekNum}
  361. renderDate={renderDate}
  362. renderFullDate={renderFullDate}
  363. onDayClick={day => this.foundation.handleDayClick(day, panelType)}
  364. onDayHover={day => this.foundation.handleDayHover(day, panelType)}
  365. onWeeksRowNumChange={weeksRowNum => this.handleWeeksRowNumChange(weeksRowNum, panelType)}
  366. startDateOffset={startDateOffset}
  367. endDateOffset={endDateOffset}
  368. focusRecordsRef={this.props.focusRecordsRef}
  369. />
  370. </div>
  371. );
  372. }
  373. handleWeeksRowNumChange = (weeksRowNum: number, panelType: PanelType) => {
  374. const isLeft = panelType === strings.PANEL_TYPE_RIGHT;
  375. const isRight = panelType === strings.PANEL_TYPE_RIGHT;
  376. const allIsYearOrTime = this.leftIsYearOrTime() && this.rightIsYearOrTime();
  377. if (this.foundation.isRangeType() && !allIsYearOrTime) {
  378. const states = { weeksRowNum, currentPanelHeight: this.calcScrollListHeight() };
  379. this.setState(states, () => {
  380. if ((this.leftIsYearOrTime() && isRight) || (this.rightIsYearOrTime() && isLeft)) {
  381. this.reselect();
  382. }
  383. });
  384. }
  385. };
  386. reselect = () => {
  387. const refKeys = [
  388. `timepicker-${strings.PANEL_TYPE_LEFT}`,
  389. `timepicker-${strings.PANEL_TYPE_RIGHT}`,
  390. `yam-${strings.PANEL_TYPE_LEFT}`,
  391. `yam-${strings.PANEL_TYPE_RIGHT}`,
  392. ];
  393. refKeys.forEach(key => {
  394. const current = this.adapter.getCache(key);
  395. if (current && typeof current.reselect === 'function') {
  396. current.reselect();
  397. }
  398. });
  399. };
  400. getYAMOpenType = () => {
  401. return this.foundation.getYAMOpenType();
  402. }
  403. renderTimePicker(panelType: PanelType, panelDetail: MonthInfo) {
  404. const { type, locale, format, hideDisabledOptions, timePickerOpts, dateFnsLocale } = this.props;
  405. const { pickerDate } = panelDetail;
  406. const timePanelCls = classnames(`${prefixCls}-time`);
  407. const restProps = {
  408. ...timePickerOpts,
  409. hideDisabledOptions,
  410. };
  411. const disabledOptions = this.foundation.calcDisabledTime(panelType);
  412. if (disabledOptions) {
  413. ['disabledHours', 'disabledMinutes', 'disabledSeconds'].forEach(key => {
  414. if (disabledOptions[key]) {
  415. restProps[key] = disabledOptions[key];
  416. }
  417. });
  418. }
  419. const { rangeStart, rangeEnd } = this.state;
  420. const dateFormat = this.foundation.getValidDateFormat();
  421. let startDate,
  422. endDate;
  423. if (
  424. type === 'dateTimeRange' &&
  425. rangeStart &&
  426. rangeEnd &&
  427. isSameDay(
  428. (startDate = compatiableParse(rangeStart, dateFormat, undefined, dateFnsLocale)),
  429. (endDate = compatiableParse(rangeEnd, dateFormat, undefined, dateFnsLocale))
  430. )
  431. ) {
  432. if (panelType === strings.PANEL_TYPE_RIGHT) {
  433. rangeStart && (restProps.startDate = startDate);
  434. } else {
  435. rangeEnd && (restProps.endDate = endDate);
  436. }
  437. }
  438. // i18n placeholder
  439. const placeholder = locale.selectTime;
  440. return (
  441. <div className={timePanelCls}>
  442. <Combobox
  443. ref={current => this.cacheRefCurrent(`timepicker-${panelType}`, current)}
  444. panelHeader={placeholder}
  445. format={format || strings.FORMAT_TIME_PICKER}
  446. timeStampValue={pickerDate}
  447. onChange={(newTime: { timeStampValue: number }) => this.foundation.handleTimeChange(newTime, panelType)}
  448. {...restProps}
  449. />
  450. </div>
  451. );
  452. }
  453. renderYearAndMonth(panelType: PanelType, panelDetail: MonthInfo) {
  454. const { pickerDate } = panelDetail;
  455. const { locale, localeCode, density } = this.props;
  456. const y = pickerDate.getFullYear();
  457. const m = pickerDate.getMonth() + 1;
  458. return (
  459. <YearAndMonth
  460. ref={current => this.cacheRefCurrent(`yam-${panelType}`, current)}
  461. locale={locale}
  462. localeCode={localeCode}
  463. currentYear={y}
  464. currentMonth={m}
  465. onSelect={item =>
  466. this.foundation.toYearMonth(panelType, new Date(item.currentYear, item.currentMonth - 1))
  467. }
  468. onBackToMain={() => {
  469. this.foundation.showDatePanel(panelType);
  470. const wrapCurrent = this.adapter.getCache(`wrap-${panelType}`);
  471. if (wrapCurrent) {
  472. wrapCurrent.style.height = 'auto';
  473. }
  474. }}
  475. density={density}
  476. />
  477. );
  478. }
  479. renderSwitch(panelType: PanelType) {
  480. const { rangeStart, rangeEnd, monthLeft, monthRight } = this.state;
  481. const { type, locale, disabledTimePicker, density, dateFnsLocale } = this.props;
  482. // Type: date, dateRange, year, month, no rendering required
  483. if (!type.includes('Time')) {
  484. return null;
  485. }
  486. // switch year/month & time
  487. let panelDetail,
  488. dateText;
  489. // i18n
  490. const { FORMAT_SWITCH_DATE } = locale.localeFormatToken;
  491. // Timepicker format is constant and does not change with language
  492. // const FORMAT_TIME_PICKER = strings.FORMAT_TIME_PICKER;
  493. const formatTimePicker = this.foundation.getValidTimeFormat();
  494. const dateFormat = this.foundation.getValidDateFormat();
  495. if (panelType === strings.PANEL_TYPE_LEFT) {
  496. panelDetail = monthLeft;
  497. dateText = rangeStart ? formatFn(compatiableParse(rangeStart, dateFormat, undefined, dateFnsLocale), FORMAT_SWITCH_DATE) : '';
  498. } else {
  499. panelDetail = monthRight;
  500. dateText = rangeEnd ? formatFn(compatiableParse(rangeEnd, dateFormat, undefined, dateFnsLocale), FORMAT_SWITCH_DATE) : '';
  501. }
  502. const { isTimePickerOpen, showDate } = panelDetail;
  503. const monthText = showDate ? formatFn(showDate, FORMAT_SWITCH_DATE) : '';
  504. const timeText = showDate ? formatFn(showDate, formatTimePicker) : '';
  505. const showSwithIcon = ['default'].includes(density);
  506. const switchCls = classnames(`${prefixCls}-switch`);
  507. const dateCls = classnames({
  508. [`${prefixCls }-switch-date`]: true,
  509. [`${prefixCls }-switch-date-active`]: !isTimePickerOpen,
  510. });
  511. const timeCls = classnames({
  512. [`${prefixCls }-switch-time`]: true,
  513. [`${prefixCls}-switch-time-disabled`]: disabledTimePicker,
  514. [`${prefixCls }-switch-date-active`]: isTimePickerOpen,
  515. });
  516. const textCls = classnames(`${prefixCls}-switch-text`);
  517. return (
  518. <div className={switchCls} ref={current => this.adapter.setCache(`switch-${panelType}`, current)}>
  519. <div className={dateCls} onClick={e => this.foundation.showDatePanel(panelType)}>
  520. {showSwithIcon && <IconCalendar />}
  521. <span className={textCls}>{dateText || monthText}</span>
  522. </div>
  523. <div className={timeCls} onClick={e => this.foundation.showTimePicker(panelType, true)}>
  524. {showSwithIcon && <IconClock />}
  525. <span className={textCls}>{timeText}</span>
  526. </div>
  527. </div>
  528. );
  529. }
  530. render() {
  531. const { monthLeft, monthRight } = this.state;
  532. const { type } = this.props;
  533. const monthGridCls = classnames({
  534. [`${prefixCls }-month-grid`]: true,
  535. });
  536. const panelTypeLeft = strings.PANEL_TYPE_LEFT;
  537. const panelTypeRight = strings.PANEL_TYPE_RIGHT;
  538. let content = null;
  539. if (type === 'date' || type === 'dateTime') {
  540. content = this.renderPanel(monthLeft.pickerDate, panelTypeLeft);
  541. } else if (type === 'dateRange' || type === 'dateTimeRange') {
  542. content = [
  543. this.renderPanel(monthLeft.pickerDate, panelTypeLeft),
  544. this.renderPanel(monthRight.pickerDate, panelTypeRight),
  545. ];
  546. } else if (type === 'year' || type === 'month') {
  547. content = 'year month';
  548. }
  549. const yearOpenType = this.getYAMOpenType();
  550. return (
  551. <div
  552. className={monthGridCls}
  553. x-type={type}
  554. x-panel-yearandmonth-open-type={yearOpenType}
  555. ref={current => this.cacheRefCurrent('monthGrid', current)}
  556. >
  557. {content}
  558. </div>
  559. );
  560. }
  561. }