datePicker.tsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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. preventScroll: PropTypes.bool,
  126. };
  127. static defaultProps = {
  128. onChangeWithDateFirst: true,
  129. autoAdjustOverflow: true,
  130. stopPropagation: true,
  131. motion: true,
  132. prefixCls: cssClasses.PREFIX,
  133. // position: 'bottomLeft',
  134. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  135. type: 'date',
  136. size: 'default',
  137. density: 'default',
  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, maybe include null
  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. const { preventScroll } = this.props;
  266. if (rangeInputFocus !== this.state.rangeInputFocus) {
  267. this.setState({ rangeInputFocus });
  268. }
  269. switch (rangeInputFocus) {
  270. case 'rangeStart':
  271. const inputStartNode = get(this, 'rangeInputStartRef.current');
  272. inputStartNode && inputStartNode.focus({ preventScroll });
  273. /**
  274. * 解决选择完startDate,切换到endDate后panel被立马关闭的问题。
  275. * 用户打开panel,选了startDate后,会执行setRangeInputFocus('rangeEnd'),focus到endDateInput,
  276. * 同时会走到datePicker/foundation.js中的handleSelectedChange方法,在这个方法里会根据focusRecordsRef来判断是否可以关闭panel。
  277. * 如果在setRangeInputFocus里同步修改了focusRecordsRef的状态为true,那在handleSelectedChange里会误判startDate和endDate都已经完成选择,
  278. * 导致endDate还没选就关闭了panel
  279. *
  280. * Fix the problem that the panel is closed immediately after switching to endDate after starting Date is selected.
  281. * The user opens the panel and after starting Date is selected, setRangeInputFocus ('rangeEnd') will be executed, focus to endDateInput,
  282. * 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.
  283. * 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,
  284. * resulting in the panel being closed before endDate is selected
  285. */
  286. setTimeout(() => {
  287. this.focusRecordsRef.current.rangeStart = true;
  288. }, 0);
  289. break;
  290. case 'rangeEnd':
  291. const inputEndNode = get(this, 'rangeInputEndRef.current');
  292. inputEndNode && inputEndNode.focus({ preventScroll });
  293. /**
  294. * 解决选择完startDate,切换到endDate后panel被立马关闭的问题。
  295. * 用户打开panel,选了startDate后,会执行setRangeInputFocus('rangeEnd'),focus到endDateInput,
  296. * 同时会走到datePicker/foundation.js中的handleSelectedChange方法,在这个方法里会根据focusRecordsRef来判断是否可以关闭panel。
  297. * 如果在setRangeInputFocus里同步修改了focusRecordsRef的状态为true,那在handleSelectedChange里会误判startDate和endDate都已经完成选择,
  298. * 导致endDate还没选就关闭了panel
  299. *
  300. * Fix the problem that the panel is closed immediately after switching to endDate after starting Date is selected.
  301. * The user opens the panel and after starting Date is selected, setRangeInputFocus ('rangeEnd') will be executed, focus to endDateInput,
  302. * 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.
  303. * 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,
  304. * resulting in the panel being closed before endDate is selected
  305. */
  306. setTimeout(() => {
  307. this.focusRecordsRef.current.rangeEnd = true;
  308. }, 0);
  309. break;
  310. default:
  311. return;
  312. }
  313. },
  314. couldPanelClosed: () => this.focusRecordsRef.current.rangeStart && this.focusRecordsRef.current.rangeEnd,
  315. isEventTarget: e => e && e.target === e.currentTarget,
  316. setInsetInputFocus: () => {
  317. const { preventScroll } = this.props;
  318. const { rangeInputFocus } = this.state;
  319. switch (rangeInputFocus) {
  320. case 'rangeEnd':
  321. if (document.activeElement !== this.rangeInputEndRef.current) {
  322. const inputEndNode = get(this, 'rangeInputEndRef.current');
  323. inputEndNode && inputEndNode.focus({ preventScroll });
  324. }
  325. break;
  326. case 'rangeStart':
  327. default:
  328. if (document.activeElement !== this.rangeInputStartRef.current) {
  329. const inputStartNode = get(this, 'rangeInputStartRef.current');
  330. inputStartNode && inputStartNode.focus({ preventScroll });
  331. }
  332. break;
  333. }
  334. },
  335. setTriggerDisabled: (disabled: boolean) => {
  336. this.setState({ triggerDisabled: disabled });
  337. }
  338. };
  339. }
  340. isRangeType(type: Type, triggerRender: DatePickerProps['triggerRender']) {
  341. return /range/i.test(type) && !isFunction(triggerRender);
  342. }
  343. componentDidUpdate(prevProps: DatePickerProps) {
  344. if (prevProps.value !== this.props.value) {
  345. this.foundation.initFromProps({
  346. ...this.props,
  347. });
  348. } else if (this.props.timeZone !== prevProps.timeZone) {
  349. this.foundation.initFromProps({
  350. value: this.state.value,
  351. timeZone: this.props.timeZone,
  352. prevTimeZone: prevProps.timeZone,
  353. });
  354. }
  355. if (prevProps.open !== this.props.open) {
  356. this.foundation.initPanelOpenStatus();
  357. if (!this.props.open) {
  358. this.foundation.clearRangeInputFocus();
  359. }
  360. }
  361. }
  362. componentDidMount() {
  363. this._mounted = true;
  364. super.componentDidMount();
  365. }
  366. componentWillUnmount() {
  367. this._mounted = false;
  368. super.componentWillUnmount();
  369. }
  370. setTriggerRef = (node: HTMLDivElement) => (this.triggerElRef.current = node);
  371. // Called when changes are selected by clicking on the selected date
  372. handleSelectedChange: MonthsGridProps['onChange'] = (v, options) => this.foundation.handleSelectedChange(v, options);
  373. // Called when the year and month change
  374. handleYMSelectedChange: YearAndMonthProps['onSelect'] = item => this.foundation.handleYMSelectedChange(item);
  375. disabledDisposeDate: MonthsGridProps['disabledDate'] = (date, ...rest) => this.foundation.disabledDisposeDate(date, ...rest);
  376. disabledDisposeTime: MonthsGridProps['disabledTime'] = (date, ...rest) => this.foundation.disabledDisposeTime(date, ...rest);
  377. renderMonthGrid(locale: Locale['DatePicker'], localeCode: string, dateFnsLocale: Locale['dateFnsLocale']) {
  378. const {
  379. type,
  380. multiple,
  381. max,
  382. weekStartsOn,
  383. timePickerOpts,
  384. defaultPickerValue,
  385. format,
  386. hideDisabledOptions,
  387. disabledTimePicker,
  388. renderDate,
  389. renderFullDate,
  390. startDateOffset,
  391. endDateOffset,
  392. autoSwitchDate,
  393. density,
  394. syncSwitchMonth,
  395. onPanelChange,
  396. timeZone,
  397. triggerRender,
  398. insetInput
  399. } = this.props;
  400. const { cachedSelectedValue, motionEnd, rangeInputFocus } = this.state;
  401. const defaultValue = cachedSelectedValue;
  402. return (
  403. <MonthsGrid
  404. ref={this.monthGrid}
  405. locale={locale}
  406. localeCode={localeCode}
  407. dateFnsLocale={dateFnsLocale}
  408. weekStartsOn={weekStartsOn}
  409. type={type}
  410. multiple={multiple}
  411. max={max}
  412. format={format}
  413. disabledDate={this.disabledDisposeDate}
  414. hideDisabledOptions={hideDisabledOptions}
  415. disabledTimePicker={disabledTimePicker}
  416. disabledTime={this.disabledDisposeTime}
  417. defaultValue={defaultValue}
  418. defaultPickerValue={defaultPickerValue}
  419. timePickerOpts={timePickerOpts}
  420. isControlledComponent={!this.adapter.needConfirm() && this.isControlled('value')}
  421. onChange={this.handleSelectedChange}
  422. renderDate={renderDate}
  423. renderFullDate={renderFullDate}
  424. startDateOffset={startDateOffset}
  425. endDateOffset={endDateOffset}
  426. autoSwitchDate={autoSwitchDate}
  427. motionEnd={motionEnd}
  428. density={density}
  429. rangeInputFocus={rangeInputFocus}
  430. setRangeInputFocus={this.handleSetRangeFocus}
  431. isAnotherPanelHasOpened={this.isAnotherPanelHasOpened}
  432. syncSwitchMonth={syncSwitchMonth}
  433. onPanelChange={onPanelChange}
  434. timeZone={timeZone}
  435. focusRecordsRef={this.focusRecordsRef}
  436. triggerRender={triggerRender}
  437. insetInput={insetInput}
  438. />
  439. );
  440. }
  441. renderQuickControls() {
  442. const { presets, type } = this.props;
  443. return (
  444. <QuickControl
  445. type={type}
  446. presets={presets}
  447. onPresetClick={(item, e) => this.foundation.handlePresetClick(item, e)}
  448. />
  449. );
  450. }
  451. handleOpenPanel = () => this.foundation.openPanel();
  452. handleInputChange: DatePickerFoundation['handleInputChange'] = (...args) => this.foundation.handleInputChange(...args);
  453. handleInsetInputChange = (options: InsetInputChangeProps) => this.foundation.handleInsetInputChange(options);
  454. handleInputComplete: DatePickerFoundation['handleInputComplete'] = v => this.foundation.handleInputComplete(v);
  455. handleInputBlur: DateInputProps['onBlur'] = e => this.foundation.handleInputBlur(get(e, 'nativeEvent.target.value'), e);
  456. handleInputFocus: DatePickerFoundation['handleInputFocus'] = (...args) => this.foundation.handleInputFocus(...args);
  457. handleInputClear: DatePickerFoundation['handleInputClear'] = e => this.foundation.handleInputClear(e);
  458. handleTriggerWrapperClick: DatePickerFoundation['handleTriggerWrapperClick'] = e => this.foundation.handleTriggerWrapperClick(e);
  459. handleSetRangeFocus: DatePickerFoundation['handleSetRangeFocus'] = rangeInputFocus => this.foundation.handleSetRangeFocus(rangeInputFocus);
  460. handleRangeInputBlur = (value: any, e: any) => this.foundation.handleRangeInputBlur(value, e);
  461. handleRangeInputClear: DatePickerFoundation['handleRangeInputClear'] = e => this.foundation.handleRangeInputClear(e);
  462. handleRangeEndTabPress: DatePickerFoundation['handleRangeEndTabPress'] = e => this.foundation.handleRangeEndTabPress(e);
  463. isAnotherPanelHasOpened = (currentRangeInput: RangeType) => {
  464. if (currentRangeInput === 'rangeStart') {
  465. return this.focusRecordsRef.current.rangeEnd;
  466. } else {
  467. return this.focusRecordsRef.current.rangeStart;
  468. }
  469. };
  470. handleInsetDateFocus = (e: React.FocusEvent, rangeType: 'rangeStart' | 'rangeEnd') => {
  471. const monthGridFoundation = get(this, 'monthGrid.current.foundation');
  472. if (monthGridFoundation) {
  473. monthGridFoundation.showDatePanel(strings.PANEL_TYPE_LEFT);
  474. monthGridFoundation.showDatePanel(strings.PANEL_TYPE_RIGHT);
  475. }
  476. this.handleInputFocus(e, rangeType);
  477. }
  478. handleInsetTimeFocus = () => {
  479. const monthGridFoundation = get(this, 'monthGrid.current.foundation');
  480. if (monthGridFoundation) {
  481. monthGridFoundation.showTimePicker(strings.PANEL_TYPE_LEFT);
  482. monthGridFoundation.showTimePicker(strings.PANEL_TYPE_RIGHT);
  483. }
  484. }
  485. handlePanelVisibleChange = (visible: boolean) => {
  486. this.foundation.handlePanelVisibleChange(visible);
  487. }
  488. renderInner(extraProps?: Partial<DatePickerProps>) {
  489. const {
  490. type,
  491. format,
  492. multiple,
  493. disabled,
  494. showClear,
  495. insetLabel,
  496. insetLabelId,
  497. placeholder,
  498. validateStatus,
  499. inputStyle,
  500. prefix,
  501. locale,
  502. dateFnsLocale,
  503. triggerRender,
  504. size,
  505. inputReadOnly,
  506. rangeSeparator,
  507. insetInput,
  508. defaultPickerValue
  509. } = this.props;
  510. const { value, inputValue, rangeInputFocus, triggerDisabled } = this.state;
  511. // This class is not needed when triggerRender is function
  512. const isRangeType = this.isRangeType(type, triggerRender);
  513. const inputDisabled = disabled || insetInput && triggerDisabled;
  514. const inputCls = classnames(`${cssClasses.PREFIX}-input`, {
  515. [`${cssClasses.PREFIX}-range-input`]: isRangeType,
  516. [`${cssClasses.PREFIX}-range-input-${size}`]: isRangeType && size,
  517. [`${cssClasses.PREFIX}-range-input-active`]: isRangeType && rangeInputFocus && !inputDisabled,
  518. [`${cssClasses.PREFIX}-range-input-disabled`]: isRangeType && inputDisabled,
  519. [`${cssClasses.PREFIX}-range-input-${validateStatus}`]: isRangeType && validateStatus,
  520. });
  521. const phText = placeholder || locale.placeholder[type]; // i18n
  522. // These values should be passed to triggerRender, do not delete any key if it is not necessary
  523. const props = {
  524. ...extraProps,
  525. placeholder: phText,
  526. disabled: inputDisabled,
  527. inputValue,
  528. value: value as Date[],
  529. defaultPickerValue,
  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, defaultPickerValue } = 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. defaultPickerValue
  622. };
  623. return (
  624. <div ref={this.panelRef} className={wrapCls} style={dropdownStyle}>
  625. {topSlot && (
  626. <div className={`${cssClasses.PREFIX}-topSlot`} x-semi-prop="topSlot">
  627. {topSlot}
  628. </div>
  629. )}
  630. {insetInput && <DateInput {...insetInputProps} insetInput={true} />}
  631. {this.adapter.typeIsYearOrMonth()
  632. ? this.renderYearMonthPanel(locale, localeCode)
  633. : this.renderMonthGrid(locale, localeCode, dateFnsLocale)}
  634. {this.renderQuickControls()}
  635. {bottomSlot && (
  636. <div className={`${cssClasses.PREFIX}-bottomSlot`} x-semi-prop="bottomSlot">
  637. {bottomSlot}
  638. </div>
  639. )}
  640. {this.renderFooter(locale, localeCode)}
  641. </div>
  642. );
  643. };
  644. renderYearMonthPanel = (locale: Locale['DatePicker'], localeCode: string) => {
  645. const { density } = this.props;
  646. const date = this.state.value[0];
  647. let year = 0;
  648. let month = 0;
  649. if (isDate(date)) {
  650. year = date.getFullYear();
  651. month = date.getMonth() + 1;
  652. }
  653. return (
  654. <YearAndMonth
  655. locale={locale}
  656. localeCode={localeCode}
  657. disabledDate={this.disabledDisposeDate}
  658. noBackBtn
  659. monthCycled
  660. onSelect={this.handleYMSelectedChange}
  661. currentYear={year}
  662. currentMonth={month}
  663. density={density}
  664. />
  665. );
  666. };
  667. wrapPopover = (children: React.ReactNode) => {
  668. const { panelShow } = this.state;
  669. // rtl changes the default position
  670. const { direction } = this.context;
  671. const defaultPosition = direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
  672. const {
  673. motion,
  674. zIndex,
  675. position = defaultPosition,
  676. getPopupContainer,
  677. locale,
  678. localeCode,
  679. dateFnsLocale,
  680. stopPropagation,
  681. autoAdjustOverflow,
  682. spacing,
  683. } = this.props;
  684. const mergedMotion = this.foundation.getMergedMotion(motion);
  685. return (
  686. <Popover
  687. getPopupContainer={getPopupContainer}
  688. // wrapWhenSpecial={false}
  689. autoAdjustOverflow={autoAdjustOverflow}
  690. zIndex={zIndex}
  691. motion={mergedMotion}
  692. content={this.renderPanel(locale, localeCode, dateFnsLocale)}
  693. trigger="custom"
  694. position={position}
  695. visible={panelShow}
  696. stopPropagation={stopPropagation}
  697. spacing={spacing}
  698. onVisibleChange={this.handlePanelVisibleChange}
  699. >
  700. {children}
  701. </Popover>
  702. );
  703. };
  704. render() {
  705. const { style, className, prefixCls } = this.props;
  706. const outerProps = {
  707. style,
  708. className: classnames(className, { [prefixCls]: true }),
  709. ref: this.setTriggerRef,
  710. 'aria-invalid': this.props['aria-invalid'],
  711. 'aria-errormessage': this.props['aria-errormessage'],
  712. 'aria-labelledby': this.props['aria-labelledby'],
  713. 'aria-describedby': this.props['aria-describedby'],
  714. 'aria-required': this.props['aria-required'],
  715. };
  716. const inner = this.renderInner();
  717. const wrappedInner = this.wrapPopover(inner);
  718. return <div {...outerProps}>{wrappedInner}</div>;
  719. }
  720. }