datePicker.tsx 39 KB

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