monthsGrid.tsx 28 KB

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