1
0

monthsGrid.tsx 27 KB

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