datePicker.tsx 38 KB

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