monthsGrid.tsx 28 KB

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