datePicker.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /* eslint-disable jsx-a11y/click-events-have-key-events,jsx-a11y/interactive-supports-focus */
  2. /* eslint-disable max-len */
  3. /* eslint-disable jsx-a11y/click-events-have-key-events */
  4. /* eslint-disable jsx-a11y/no-static-element-interactions */
  5. import React from 'react';
  6. import classnames from 'classnames';
  7. import PropTypes from 'prop-types';
  8. import { noop, stubFalse, isDate, get, isFunction, isEqual } from 'lodash';
  9. import ConfigContext, { ContextValue } from '../configProvider/context';
  10. import DatePickerFoundation, { DatePickerAdapter, DatePickerFoundationProps, DatePickerFoundationState, DayStatusType, PresetType, Type, RangeType } from '@douyinfe/semi-foundation/datePicker/foundation';
  11. import { cssClasses, strings, numbers } from '@douyinfe/semi-foundation/datePicker/constants';
  12. import { strings as popoverStrings, numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
  13. import BaseComponent from '../_base/baseComponent';
  14. import Popover from '../popover/index';
  15. import DateInput, { DateInputProps } from './dateInput';
  16. import MonthsGrid, { MonthsGridProps } from './monthsGrid';
  17. import QuickControl from './quickControl';
  18. import Footer from './footer';
  19. import Trigger from '../trigger';
  20. import YearAndMonth, { YearAndMonthProps } from './yearAndMonth';
  21. import '@douyinfe/semi-foundation/datePicker/datePicker.scss';
  22. import { Locale } from '../locale/interface';
  23. import { TimePickerProps } from '../timePicker/TimePicker';
  24. import { InsetInputValue, InsetInputChangeProps } from '@douyinfe/semi-foundation/datePicker/inputFoundation';
  25. export interface DatePickerProps extends DatePickerFoundationProps {
  26. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  27. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  28. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  29. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  30. 'aria-required'?: React.AriaAttributes['aria-required'];
  31. timePickerOpts?: TimePickerProps;
  32. bottomSlot?: React.ReactNode;
  33. insetLabel?: React.ReactNode;
  34. insetLabelId?: string;
  35. prefix?: React.ReactNode;
  36. topSlot?: React.ReactNode;
  37. renderDate?: (dayNumber?: number, fullDate?: string) => React.ReactNode;
  38. renderFullDate?: (dayNumber?: number, fullDate?: string, dayStatus?: DayStatusType) => React.ReactNode;
  39. triggerRender?: (props: DatePickerProps) => React.ReactNode;
  40. onBlur?: React.MouseEventHandler<HTMLInputElement>;
  41. onClear?: React.MouseEventHandler<HTMLDivElement>;
  42. onFocus?: (e: React.MouseEvent, rangeType: RangeType) => void;
  43. onPresetClick?: (item: PresetType, e: React.MouseEvent<HTMLDivElement>) => void;
  44. locale?: Locale['DatePicker'];
  45. dateFnsLocale?: Locale['dateFnsLocale'];
  46. }
  47. export type DatePickerState = DatePickerFoundationState;
  48. export default class DatePicker extends BaseComponent<DatePickerProps, DatePickerState> {
  49. static contextType = ConfigContext;
  50. static propTypes = {
  51. 'aria-describedby': PropTypes.string,
  52. 'aria-errormessage': PropTypes.string,
  53. 'aria-invalid': PropTypes.bool,
  54. 'aria-labelledby': PropTypes.string,
  55. 'aria-required': PropTypes.bool,
  56. type: PropTypes.oneOf(strings.TYPE_SET),
  57. size: PropTypes.oneOf(strings.SIZE_SET),
  58. density: PropTypes.oneOf(strings.DENSITY_SET),
  59. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object, PropTypes.array]),
  60. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object, PropTypes.array]),
  61. defaultPickerValue: PropTypes.oneOfType([
  62. PropTypes.string,
  63. PropTypes.number,
  64. PropTypes.object,
  65. PropTypes.array,
  66. ]),
  67. disabledTime: PropTypes.func,
  68. disabledTimePicker: PropTypes.bool,
  69. hideDisabledOptions: PropTypes.bool,
  70. format: PropTypes.string,
  71. disabled: PropTypes.bool,
  72. multiple: PropTypes.bool,
  73. max: PropTypes.number, // only work when multiple is true
  74. placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  75. presets: PropTypes.array,
  76. onChange: PropTypes.func,
  77. onChangeWithDateFirst: PropTypes.bool,
  78. weekStartsOn: PropTypes.number,
  79. disabledDate: PropTypes.func,
  80. timePickerOpts: PropTypes.object, // When dateTime, dateTimeRange, pass through the props to timePicker
  81. showClear: PropTypes.bool, // Whether to show the clear button
  82. onOpenChange: PropTypes.func,
  83. open: PropTypes.bool,
  84. defaultOpen: PropTypes.bool,
  85. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]),
  86. className: PropTypes.string,
  87. prefixCls: PropTypes.string,
  88. prefix: PropTypes.node,
  89. insetLabel: PropTypes.node,
  90. insetLabelId: PropTypes.string,
  91. zIndex: PropTypes.number,
  92. position: PropTypes.oneOf(popoverStrings.POSITION_SET),
  93. getPopupContainer: PropTypes.func,
  94. onCancel: PropTypes.func,
  95. onConfirm: PropTypes.func,
  96. needConfirm: PropTypes.bool,
  97. inputStyle: PropTypes.object,
  98. timeZone: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  99. triggerRender: PropTypes.func,
  100. stopPropagation: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  101. autoAdjustOverflow: PropTypes.bool,
  102. onBlur: PropTypes.func,
  103. onFocus: PropTypes.func,
  104. onClear: PropTypes.func,
  105. style: PropTypes.object,
  106. autoFocus: PropTypes.bool,
  107. inputReadOnly: PropTypes.bool, // Text box can be entered
  108. validateStatus: PropTypes.oneOf(strings.STATUS),
  109. renderDate: PropTypes.func,
  110. renderFullDate: PropTypes.func,
  111. spacing: PropTypes.number,
  112. startDateOffset: PropTypes.func,
  113. endDateOffset: PropTypes.func,
  114. autoSwitchDate: PropTypes.bool,
  115. dropdownClassName: PropTypes.string,
  116. dropdownStyle: PropTypes.object,
  117. topSlot: PropTypes.node,
  118. bottomSlot: PropTypes.node,
  119. dateFnsLocale: PropTypes.object, // isRequired, but no need to add isRequired key. ForwardStatics function pass static properties to index.jsx, so there is no need for user to pass the prop.
  120. // Support synchronous switching of months
  121. syncSwitchMonth: PropTypes.bool,
  122. // Callback function for panel date switching
  123. onPanelChange: PropTypes.func,
  124. rangeSeparator: PropTypes.string,
  125. };
  126. static defaultProps = {
  127. onChangeWithDateFirst: true,
  128. autoAdjustOverflow: true,
  129. stopPropagation: true,
  130. motion: true,
  131. prefixCls: cssClasses.PREFIX,
  132. // position: 'bottomLeft',
  133. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  134. type: 'date',
  135. size: 'default',
  136. density: 'default',
  137. disabled: false,
  138. multiple: false,
  139. defaultOpen: false,
  140. disabledHours: noop,
  141. disabledMinutes: noop,
  142. disabledSeconds: noop,
  143. hideDisabledOptions: false,
  144. onBlur: noop,
  145. onFocus: noop,
  146. onClear: noop,
  147. onCancel: noop,
  148. onConfirm: noop,
  149. onChange: noop,
  150. onOpenChange: noop,
  151. onPanelChange: noop,
  152. onPresetClick: noop,
  153. weekStartsOn: numbers.WEEK_START_ON,
  154. disabledDate: stubFalse,
  155. disabledTime: stubFalse,
  156. inputReadOnly: false,
  157. spacing: numbers.SPACING,
  158. autoSwitchDate: true,
  159. syncSwitchMonth: false,
  160. rangeSeparator: strings.DEFAULT_SEPARATOR_RANGE,
  161. insetInput: false,
  162. };
  163. triggerElRef: React.MutableRefObject<HTMLElement>;
  164. panelRef: React.RefObject<HTMLDivElement>;
  165. monthGrid: React.RefObject<MonthsGrid>;
  166. rangeInputStartRef: React.RefObject<HTMLElement>;
  167. rangeInputEndRef: React.RefObject<HTMLElement>;
  168. focusRecordsRef: React.RefObject<{ rangeStart: boolean; rangeEnd: boolean }>;
  169. clickOutSideHandler: (e: MouseEvent) => void;
  170. _mounted: boolean;
  171. foundation: DatePickerFoundation;
  172. context: ContextValue;
  173. constructor(props: DatePickerProps) {
  174. super(props);
  175. this.state = {
  176. panelShow: props.open || props.defaultOpen,
  177. isRange: false,
  178. inputValue: null, // Staging input values
  179. value: [], // The currently selected date, each date is a Date object
  180. cachedSelectedValue: null, // Save last selected date
  181. prevTimeZone: null,
  182. motionEnd: false, // Monitor if popover animation ends
  183. rangeInputFocus: undefined, // Optional'rangeStart ',' rangeEnd ', false
  184. autofocus: props.autoFocus || (this.isRangeType(props.type, props.triggerRender) && (props.open || props.defaultOpen)),
  185. insetInputValue: null,
  186. triggerDisabled: undefined,
  187. };
  188. this.adapter.setCache('cachedSelectedValue', null);
  189. this.triggerElRef = React.createRef();
  190. this.panelRef = React.createRef();
  191. this.monthGrid = React.createRef();
  192. this.rangeInputStartRef = React.createRef();
  193. this.rangeInputEndRef = React.createRef();
  194. this.focusRecordsRef = React.createRef();
  195. // @ts-ignore ignore readonly
  196. this.focusRecordsRef.current = {
  197. rangeStart: false,
  198. rangeEnd: false
  199. };
  200. this.foundation = new DatePickerFoundation(this.adapter);
  201. }
  202. get adapter(): DatePickerAdapter {
  203. return {
  204. ...super.adapter,
  205. togglePanel: panelShow => {
  206. this.setState({ panelShow });
  207. if (!panelShow) {
  208. this.focusRecordsRef.current.rangeEnd = false;
  209. this.focusRecordsRef.current.rangeStart = false;
  210. }
  211. },
  212. registerClickOutSide: () => {
  213. if (this.clickOutSideHandler) {
  214. this.adapter.unregisterClickOutSide();
  215. this.clickOutSideHandler = null;
  216. }
  217. this.clickOutSideHandler = e => {
  218. if (this.adapter.needConfirm()) {
  219. return;
  220. }
  221. const triggerEl = this.triggerElRef && this.triggerElRef.current;
  222. const panelEl = this.panelRef && this.panelRef.current;
  223. const isInTrigger = triggerEl && triggerEl.contains(e.target as Node);
  224. const isInPanel = panelEl && panelEl.contains(e.target as Node);
  225. if (!isInTrigger && !isInPanel && this._mounted) {
  226. this.foundation.closePanel(e);
  227. }
  228. };
  229. document.addEventListener('mousedown', this.clickOutSideHandler);
  230. },
  231. unregisterClickOutSide: () => {
  232. document.removeEventListener('mousedown', this.clickOutSideHandler);
  233. },
  234. notifyBlur: (...args) => this.props.onBlur(...args),
  235. notifyFocus: (...args) => this.props.onFocus(...args),
  236. notifyClear: (...args) => this.props.onClear(...args),
  237. notifyChange: (...args) => this.props.onChange(...args),
  238. notifyCancel: (...args) => this.props.onCancel(...args),
  239. notifyConfirm: (...args) => this.props.onConfirm(...args),
  240. notifyOpenChange: (...args) => this.props.onOpenChange(...args),
  241. notifyPresetsClick: (...args) => this.props.onPresetClick(...args),
  242. updateValue: value => this.setState({ value }),
  243. updatePrevTimezone: prevTimeZone => this.setState({ prevTimeZone }),
  244. updateCachedSelectedValue: cachedSelectedValue => {
  245. let _cachedSelectedValue = cachedSelectedValue;
  246. if (cachedSelectedValue && !Array.isArray(cachedSelectedValue)) {
  247. _cachedSelectedValue = [...cachedSelectedValue as any];
  248. }
  249. this.setState({ cachedSelectedValue: _cachedSelectedValue });
  250. },
  251. updateInputValue: inputValue => {
  252. this.setState({ inputValue });
  253. },
  254. updateInsetInputValue: (insetInputValue: InsetInputValue) => {
  255. const { insetInput } = this.props;
  256. if (insetInput && !isEqual(insetInputValue, this.state.insetInputValue)) {
  257. this.setState({ insetInputValue });
  258. }
  259. },
  260. needConfirm: () =>
  261. ['dateTime', 'dateTimeRange'].includes(this.props.type) && this.props.needConfirm === true,
  262. typeIsYearOrMonth: () => ['month', 'year'].includes(this.props.type),
  263. setMotionEnd: motionEnd => this.setState({ motionEnd }),
  264. setRangeInputFocus: rangeInputFocus => {
  265. if (rangeInputFocus !== this.state.rangeInputFocus) {
  266. this.setState({ rangeInputFocus });
  267. }
  268. switch (rangeInputFocus) {
  269. case 'rangeStart':
  270. const inputStartNode = get(this, 'rangeInputStartRef.current');
  271. inputStartNode && inputStartNode.focus();
  272. /**
  273. * 解决选择完startDate,切换到endDate后panel被立马关闭的问题。
  274. * 用户打开panel,选了startDate后,会执行setRangeInputFocus('rangeEnd'),focus到endDateInput,
  275. * 同时会走到datePicker/foundation.js中的handleSelectedChange方法,在这个方法里会根据focusRecordsRef来判断是否可以关闭panel。
  276. * 如果在setRangeInputFocus里同步修改了focusRecordsRef的状态为true,那在handleSelectedChange里会误判startDate和endDate都已经完成选择,
  277. * 导致endDate还没选就关闭了panel
  278. *
  279. * Fix the problem that the panel is closed immediately after switching to endDate after starting Date is selected.
  280. * The user opens the panel and after starting Date is selected, setRangeInputFocus ('rangeEnd') will be executed, focus to endDateInput,
  281. * At the same time, it will go to the handleSelectedChange method in datePicker/foundation.js, where it will be determined whether the panel can be closed according to focusRecordsRef.
  282. * If the status of focusRecordsRef is modified synchronously in setRangeInputFocus to true, then in handleSelectedChange it will be misjudged that both begDate and endDate have completed the selection,
  283. * resulting in the panel being closed before endDate is selected
  284. */
  285. setTimeout(() => {
  286. this.focusRecordsRef.current.rangeStart = true;
  287. }, 0);
  288. break;
  289. case 'rangeEnd':
  290. const inputEndNode = get(this, 'rangeInputEndRef.current');
  291. inputEndNode && inputEndNode.focus();
  292. /**
  293. * 解决选择完startDate,切换到endDate后panel被立马关闭的问题。
  294. * 用户打开panel,选了startDate后,会执行setRangeInputFocus('rangeEnd'),focus到endDateInput,
  295. * 同时会走到datePicker/foundation.js中的handleSelectedChange方法,在这个方法里会根据focusRecordsRef来判断是否可以关闭panel。
  296. * 如果在setRangeInputFocus里同步修改了focusRecordsRef的状态为true,那在handleSelectedChange里会误判startDate和endDate都已经完成选择,
  297. * 导致endDate还没选就关闭了panel
  298. *
  299. * Fix the problem that the panel is closed immediately after switching to endDate after starting Date is selected.
  300. * The user opens the panel and after starting Date is selected, setRangeInputFocus ('rangeEnd') will be executed, focus to endDateInput,
  301. * At the same time, it will go to the handleSelectedChange method in datePicker/foundation.js, where it will be determined whether the panel can be closed according to focusRecordsRef.
  302. * If the status of focusRecordsRef is modified synchronously in setRangeInputFocus to true, then in handleSelectedChange it will be misjudged that both begDate and endDate have completed the selection,
  303. * resulting in the panel being closed before endDate is selected
  304. */
  305. setTimeout(() => {
  306. this.focusRecordsRef.current.rangeEnd = true;
  307. }, 0);
  308. break;
  309. default:
  310. return;
  311. }
  312. },
  313. couldPanelClosed: () => this.focusRecordsRef.current.rangeStart && this.focusRecordsRef.current.rangeEnd,
  314. isEventTarget: e => e && e.target === e.currentTarget,
  315. setInsetInputFocus: () => {
  316. const { rangeInputFocus } = this.state;
  317. switch (rangeInputFocus) {
  318. case 'rangeEnd':
  319. if (document.activeElement !== this.rangeInputEndRef.current) {
  320. const inputEndNode = get(this, 'rangeInputEndRef.current');
  321. inputEndNode && inputEndNode.focus();
  322. }
  323. break;
  324. case 'rangeStart':
  325. default:
  326. if (document.activeElement !== this.rangeInputStartRef.current) {
  327. const inputStartNode = get(this, 'rangeInputStartRef.current');
  328. inputStartNode && inputStartNode.focus();
  329. }
  330. break;
  331. }
  332. },
  333. setTriggerDisabled: (disabled: boolean) => {
  334. this.setState({ triggerDisabled: disabled });
  335. }
  336. };
  337. }
  338. isRangeType(type: Type, triggerRender: DatePickerProps['triggerRender']) {
  339. return /range/i.test(type) && !isFunction(triggerRender);
  340. }
  341. componentDidUpdate(prevProps: DatePickerProps) {
  342. if (prevProps.value !== this.props.value) {
  343. this.foundation.initFromProps({
  344. ...this.props,
  345. });
  346. } else if (this.props.timeZone !== prevProps.timeZone) {
  347. this.foundation.initFromProps({
  348. value: this.state.value,
  349. timeZone: this.props.timeZone,
  350. prevTimeZone: prevProps.timeZone,
  351. });
  352. }
  353. if (prevProps.open !== this.props.open) {
  354. this.foundation.initPanelOpenStatus();
  355. if (!this.props.open) {
  356. this.foundation.clearRangeInputFocus();
  357. }
  358. }
  359. }
  360. componentDidMount() {
  361. this._mounted = true;
  362. super.componentDidMount();
  363. }
  364. componentWillUnmount() {
  365. this._mounted = false;
  366. super.componentWillUnmount();
  367. }
  368. setTriggerRef = (node: HTMLDivElement) => (this.triggerElRef.current = node);
  369. // Called when changes are selected by clicking on the selected date
  370. handleSelectedChange: MonthsGridProps['onChange'] = (v, options) => this.foundation.handleSelectedChange(v, options);
  371. // Called when the year and month change
  372. handleYMSelectedChange: YearAndMonthProps['onSelect'] = item => this.foundation.handleYMSelectedChange(item);
  373. disabledDisposeDate: MonthsGridProps['disabledDate'] = (date, ...rest) => this.foundation.disabledDisposeDate(date, ...rest);
  374. disabledDisposeTime: MonthsGridProps['disabledTime'] = (date, ...rest) => this.foundation.disabledDisposeTime(date, ...rest);
  375. renderMonthGrid(locale: Locale['DatePicker'], localeCode: string, dateFnsLocale: Locale['dateFnsLocale']) {
  376. const {
  377. type,
  378. multiple,
  379. max,
  380. weekStartsOn,
  381. timePickerOpts,
  382. defaultPickerValue,
  383. format,
  384. hideDisabledOptions,
  385. disabledTimePicker,
  386. renderDate,
  387. renderFullDate,
  388. startDateOffset,
  389. endDateOffset,
  390. autoSwitchDate,
  391. density,
  392. syncSwitchMonth,
  393. onPanelChange,
  394. timeZone,
  395. triggerRender,
  396. insetInput
  397. } = this.props;
  398. const { value, cachedSelectedValue, motionEnd, rangeInputFocus } = this.state;
  399. // const cachedSelectedValue = this.adapter.getCache('cachedSelectedValue');
  400. let defaultValue = value;
  401. if (this.adapter.needConfirm()) {
  402. defaultValue = cachedSelectedValue;
  403. }
  404. return (
  405. <MonthsGrid
  406. ref={this.monthGrid}
  407. locale={locale}
  408. localeCode={localeCode}
  409. dateFnsLocale={dateFnsLocale}
  410. weekStartsOn={weekStartsOn}
  411. type={type}
  412. multiple={multiple}
  413. max={max}
  414. format={format}
  415. disabledDate={this.disabledDisposeDate}
  416. hideDisabledOptions={hideDisabledOptions}
  417. disabledTimePicker={disabledTimePicker}
  418. disabledTime={this.disabledDisposeTime}
  419. defaultValue={defaultValue}
  420. defaultPickerValue={defaultPickerValue}
  421. timePickerOpts={timePickerOpts}
  422. isControlledComponent={!this.adapter.needConfirm() && this.isControlled('value')}
  423. onChange={this.handleSelectedChange}
  424. renderDate={renderDate}
  425. renderFullDate={renderFullDate}
  426. startDateOffset={startDateOffset}
  427. endDateOffset={endDateOffset}
  428. autoSwitchDate={autoSwitchDate}
  429. motionEnd={motionEnd}
  430. density={density}
  431. rangeInputFocus={rangeInputFocus}
  432. setRangeInputFocus={this.handleSetRangeFocus}
  433. isAnotherPanelHasOpened={this.isAnotherPanelHasOpened}
  434. syncSwitchMonth={syncSwitchMonth}
  435. onPanelChange={onPanelChange}
  436. timeZone={timeZone}
  437. focusRecordsRef={this.focusRecordsRef}
  438. triggerRender={triggerRender}
  439. insetInput={insetInput}
  440. />
  441. );
  442. }
  443. renderQuickControls() {
  444. const { presets, type } = this.props;
  445. return (
  446. <QuickControl
  447. type={type}
  448. presets={presets}
  449. onPresetClick={(item, e) => this.foundation.handlePresetClick(item, e)}
  450. />
  451. );
  452. }
  453. handleOpenPanel = () => this.foundation.openPanel();
  454. handleInputChange: DatePickerFoundation['handleInputChange'] = (...args) => this.foundation.handleInputChange(...args);
  455. handleInsetInputChange = (options: InsetInputChangeProps) => this.foundation.handleInsetInputChange(options);
  456. handleInputComplete: DatePickerFoundation['handleInputComplete'] = v => this.foundation.handleInputComplete(v);
  457. handleInputBlur: DateInputProps['onBlur'] = e => this.foundation.handleInputBlur(get(e, 'nativeEvent.target.value'), e);
  458. handleInputFocus: DatePickerFoundation['handleInputFocus'] = (...args) => this.foundation.handleInputFocus(...args);
  459. handleInputClear: DatePickerFoundation['handleInputClear'] = e => this.foundation.handleInputClear(e);
  460. handleTriggerWrapperClick: DatePickerFoundation['handleTriggerWrapperClick'] = e => this.foundation.handleTriggerWrapperClick(e);
  461. handleSetRangeFocus: DatePickerFoundation['handleSetRangeFocus'] = rangeInputFocus => this.foundation.handleSetRangeFocus(rangeInputFocus);
  462. handleRangeInputBlur = (value: any, e: any) => this.foundation.handleRangeInputBlur(value, e);
  463. handleRangeInputClear: DatePickerFoundation['handleRangeInputClear'] = e => this.foundation.handleRangeInputClear(e);
  464. handleRangeEndTabPress: DatePickerFoundation['handleRangeEndTabPress'] = e => this.foundation.handleRangeEndTabPress(e);
  465. isAnotherPanelHasOpened = (currentRangeInput: RangeType) => {
  466. if (currentRangeInput === 'rangeStart') {
  467. return this.focusRecordsRef.current.rangeEnd;
  468. } else {
  469. return this.focusRecordsRef.current.rangeStart;
  470. }
  471. };
  472. handleInsetDateFocus = (e: React.FocusEvent, rangeType: 'rangeStart' | 'rangeEnd') => {
  473. const monthGridFoundation = get(this, 'monthGrid.current.foundation');
  474. if (monthGridFoundation) {
  475. monthGridFoundation.showDatePanel(strings.PANEL_TYPE_LEFT);
  476. monthGridFoundation.showDatePanel(strings.PANEL_TYPE_RIGHT);
  477. }
  478. this.handleInputFocus(e, rangeType);
  479. }
  480. handleInsetTimeFocus = () => {
  481. const monthGridFoundation = get(this, 'monthGrid.current.foundation');
  482. if (monthGridFoundation) {
  483. monthGridFoundation.showTimePicker(strings.PANEL_TYPE_LEFT);
  484. monthGridFoundation.showTimePicker(strings.PANEL_TYPE_RIGHT);
  485. }
  486. }
  487. handlePanelVisibleChange = (visible: boolean) => {
  488. this.foundation.handlePanelVisibleChange(visible);
  489. }
  490. renderInner(extraProps?: Partial<DatePickerProps>) {
  491. const {
  492. type,
  493. format,
  494. multiple,
  495. disabled,
  496. showClear,
  497. insetLabel,
  498. insetLabelId,
  499. placeholder,
  500. validateStatus,
  501. inputStyle,
  502. prefix,
  503. locale,
  504. dateFnsLocale,
  505. triggerRender,
  506. size,
  507. inputReadOnly,
  508. rangeSeparator,
  509. insetInput,
  510. } = this.props;
  511. const { value, inputValue, rangeInputFocus, triggerDisabled } = this.state;
  512. // This class is not needed when triggerRender is function
  513. const isRangeType = this.isRangeType(type, triggerRender);
  514. const inputDisabled = disabled || insetInput && triggerDisabled;
  515. const inputCls = classnames(`${cssClasses.PREFIX}-input`, {
  516. [`${cssClasses.PREFIX}-range-input`]: isRangeType,
  517. [`${cssClasses.PREFIX}-range-input-${size}`]: isRangeType && size,
  518. [`${cssClasses.PREFIX}-range-input-active`]: isRangeType && rangeInputFocus && !inputDisabled,
  519. [`${cssClasses.PREFIX}-range-input-disabled`]: isRangeType && inputDisabled,
  520. [`${cssClasses.PREFIX}-range-input-${validateStatus}`]: isRangeType && validateStatus,
  521. });
  522. const phText = placeholder || locale.placeholder[type]; // i18n
  523. // These values should be passed to triggerRender, do not delete any key if it is not necessary
  524. const props = {
  525. ...extraProps,
  526. placeholder: phText,
  527. disabled: inputDisabled,
  528. inputValue,
  529. value: value as Date[],
  530. onChange: this.handleInputChange,
  531. onEnterPress: this.handleInputComplete,
  532. // TODO: remove in next major version
  533. block: true,
  534. inputStyle,
  535. showClear,
  536. insetLabel,
  537. insetLabelId,
  538. type,
  539. format,
  540. multiple,
  541. validateStatus,
  542. inputReadOnly: inputReadOnly || insetInput,
  543. // onClick: this.handleOpenPanel,
  544. onBlur: this.handleInputBlur,
  545. onFocus: this.handleInputFocus,
  546. onClear: this.handleInputClear,
  547. prefix,
  548. size,
  549. autofocus: this.state.autofocus,
  550. dateFnsLocale,
  551. rangeInputFocus,
  552. rangeSeparator,
  553. onRangeBlur: this.handleRangeInputBlur,
  554. onRangeClear: this.handleRangeInputClear,
  555. onRangeEndTabPress: this.handleRangeEndTabPress,
  556. rangeInputStartRef: insetInput ? null : this.rangeInputStartRef,
  557. rangeInputEndRef: insetInput ? null : this.rangeInputEndRef,
  558. };
  559. return (
  560. <div
  561. // tooltip will mount a11y props to children
  562. // eslint-disable-next-line jsx-a11y/role-has-required-aria-props
  563. role="combobox"
  564. aria-label={Array.isArray(value) && value.length ? "Change date" : "Choose date"}
  565. aria-disabled={disabled}
  566. onClick={this.handleTriggerWrapperClick}
  567. className={inputCls}>
  568. {typeof triggerRender === 'function' ? (
  569. <Trigger
  570. {...props}
  571. triggerRender={triggerRender}
  572. componentName="DatePicker"
  573. componentProps={{ ...this.props }}
  574. />
  575. ) : (
  576. <DateInput {...props} />
  577. )}
  578. </div>
  579. );
  580. }
  581. handleConfirm = (e: React.MouseEvent) => this.foundation.handleConfirm();
  582. handleCancel = (e: React.MouseEvent) => this.foundation.handleCancel();
  583. renderFooter = (locale: Locale['DatePicker'], localeCode: string) => {
  584. if (this.adapter.needConfirm()) {
  585. return (
  586. <Footer
  587. {...this.props}
  588. locale={locale}
  589. localeCode={localeCode}
  590. onConfirmClick={this.handleConfirm}
  591. onCancelClick={this.handleCancel}
  592. />
  593. );
  594. }
  595. return null;
  596. };
  597. renderPanel = (locale: Locale['DatePicker'], localeCode: string, dateFnsLocale: Locale['dateFnsLocale']) => {
  598. const { dropdownClassName, dropdownStyle, density, topSlot, bottomSlot, insetInput, type, format, rangeSeparator } = this.props;
  599. const { insetInputValue, value } = this.state;
  600. const wrapCls = classnames(
  601. cssClasses.PREFIX,
  602. {
  603. [cssClasses.PANEL_YAM]: this.adapter.typeIsYearOrMonth(),
  604. [`${cssClasses.PREFIX}-compact`]: density === 'compact',
  605. },
  606. dropdownClassName
  607. );
  608. const insetInputProps = {
  609. dateFnsLocale,
  610. format,
  611. insetInputValue,
  612. rangeSeparator,
  613. type,
  614. value: value as Date[],
  615. handleInsetDateFocus: this.handleInsetDateFocus,
  616. handleInsetTimeFocus: this.handleInsetTimeFocus,
  617. onInsetInputChange: this.handleInsetInputChange,
  618. rangeInputStartRef: this.rangeInputStartRef,
  619. rangeInputEndRef: this.rangeInputEndRef,
  620. density,
  621. };
  622. return (
  623. <div ref={this.panelRef} className={wrapCls} style={dropdownStyle}>
  624. {topSlot && <div className={`${cssClasses.PREFIX}-topSlot`}>{topSlot}</div>}
  625. {insetInput && <DateInput {...insetInputProps} insetInput={true} />}
  626. {this.adapter.typeIsYearOrMonth() ?
  627. this.renderYearMonthPanel(locale, localeCode) :
  628. this.renderMonthGrid(locale, localeCode, dateFnsLocale)}
  629. {this.renderQuickControls()}
  630. {bottomSlot && <div className={`${cssClasses.PREFIX}-bottomSlot`}>{bottomSlot}</div>}
  631. {this.renderFooter(locale, localeCode)}
  632. </div>
  633. );
  634. };
  635. renderYearMonthPanel = (locale: Locale['DatePicker'], localeCode: string) => {
  636. const { density } = this.props;
  637. const date = this.state.value[0];
  638. let year = 0;
  639. let month = 0;
  640. if (isDate(date)) {
  641. year = date.getFullYear();
  642. month = date.getMonth() + 1;
  643. }
  644. return (
  645. <YearAndMonth
  646. locale={locale}
  647. localeCode={localeCode}
  648. disabledDate={this.disabledDisposeDate}
  649. noBackBtn
  650. monthCycled
  651. onSelect={this.handleYMSelectedChange}
  652. currentYear={year}
  653. currentMonth={month}
  654. density={density}
  655. />
  656. );
  657. };
  658. wrapPopover = (children: React.ReactNode) => {
  659. const { panelShow } = this.state;
  660. // rtl changes the default position
  661. const { direction } = this.context;
  662. const defaultPosition = direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
  663. const {
  664. motion,
  665. zIndex,
  666. position = defaultPosition,
  667. getPopupContainer,
  668. locale,
  669. localeCode,
  670. dateFnsLocale,
  671. stopPropagation,
  672. autoAdjustOverflow,
  673. spacing,
  674. } = this.props;
  675. const mergedMotion = this.foundation.getMergedMotion(motion);
  676. return (
  677. <Popover
  678. getPopupContainer={getPopupContainer}
  679. // wrapWhenSpecial={false}
  680. autoAdjustOverflow={autoAdjustOverflow}
  681. zIndex={zIndex}
  682. motion={mergedMotion}
  683. content={this.renderPanel(locale, localeCode, dateFnsLocale)}
  684. trigger="custom"
  685. position={position}
  686. visible={panelShow}
  687. stopPropagation={stopPropagation}
  688. spacing={spacing}
  689. onVisibleChange={this.handlePanelVisibleChange}
  690. >
  691. {children}
  692. </Popover>
  693. );
  694. };
  695. render() {
  696. const { style, className, prefixCls } = this.props;
  697. const outerProps = {
  698. style,
  699. className: classnames(className, { [prefixCls]: true }),
  700. ref: this.setTriggerRef,
  701. 'aria-invalid': this.props['aria-invalid'],
  702. 'aria-errormessage': this.props['aria-errormessage'],
  703. 'aria-labelledby': this.props['aria-labelledby'],
  704. 'aria-describedby': this.props['aria-describedby'],
  705. 'aria-required': this.props['aria-required'],
  706. };
  707. const inner = this.renderInner();
  708. const wrappedInner = this.wrapPopover(inner);
  709. return <div {...outerProps}>{wrappedInner}</div>;
  710. }
  711. }