TimePicker.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /* eslint-disable no-unused-vars */
  2. import React from 'react';
  3. import PropTypes from 'prop-types';
  4. import classNames from 'classnames';
  5. import { noop, get } from 'lodash';
  6. import ConfigContext from '../configProvider/context';
  7. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  8. import { strings, cssClasses } from '@douyinfe/semi-foundation/timePicker/constants';
  9. import Popover from '../popover';
  10. import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
  11. import TimePickerFoundation, { TimePickerAdapter } from '@douyinfe/semi-foundation/timePicker/foundation';
  12. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  13. import Combobox from './Combobox';
  14. import TimeInput from './TimeInput';
  15. import { PanelShape, PanelShapeDefaults } from './PanelShape';
  16. import { TimeShape } from './TimeShape';
  17. import '@douyinfe/semi-foundation/timePicker/timePicker.scss';
  18. import Trigger from '../trigger';
  19. import { InputSize } from '../input';
  20. import { Position } from '../tooltip';
  21. import { ScrollItemProps } from '../scrollList/scrollItem';
  22. import { Locale } from '../locale/interface';
  23. import { Motion } from '../_base/base';
  24. export interface Panel {
  25. panelHeader?: React.ReactNode;
  26. panelFooter?: React.ReactNode;
  27. }
  28. export type BaseValueType = string | number | Date;
  29. export type Type = 'time' | 'timeRange';
  30. export type TimePickerProps = {
  31. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  32. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  33. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  34. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  35. 'aria-required'?: React.AriaAttributes['aria-required'];
  36. autoAdjustOverflow?: boolean;
  37. autoFocus?: boolean; // TODO: autoFocus did not take effect
  38. className?: string;
  39. clearText?: string;
  40. dateFnsLocale?: Locale['dateFnsLocale'];
  41. defaultOpen?: boolean;
  42. defaultValue?: BaseValueType | BaseValueType[];
  43. disabled?: boolean;
  44. disabledHours?: () => number[];
  45. disabledMinutes?: (selectedHour: number) => number[];
  46. disabledSeconds?: (selectedHour: number, selectedMinute: number) => number[];
  47. focusOnOpen?: boolean;
  48. format?: string;
  49. getPopupContainer?: () => HTMLElement;
  50. hideDisabledOptions?: boolean;
  51. hourStep?: number;
  52. id?: string;
  53. inputReadOnly?: boolean;
  54. inputStyle?: React.CSSProperties;
  55. insetLabel?: React.ReactNode;
  56. insetLabelId?: string;
  57. locale?: Locale['TimePicker'];
  58. localeCode?: string;
  59. minuteStep?: number;
  60. motion?: Motion;
  61. open?: boolean;
  62. panelFooter?: React.ReactNode;
  63. panelHeader?: React.ReactNode;
  64. panels?: Panel[]; // FIXME:
  65. placeholder?: string;
  66. popupClassName?: string;
  67. popupStyle?: React.CSSProperties;
  68. position?: Position;
  69. prefixCls?: string;
  70. rangeSeparator?: string;
  71. scrollItemProps?: ScrollItemProps<any>;
  72. secondStep?: number;
  73. showClear?: boolean;
  74. size?: InputSize;
  75. style?: React.CSSProperties;
  76. timeZone?: string | number;
  77. triggerRender?: (props?: any) => React.ReactNode;
  78. type?: Type;
  79. use12Hours?: boolean;
  80. validateStatus?: ValidateStatus;
  81. value?: BaseValueType | BaseValueType[];
  82. zIndex?: number | string;
  83. onBlur?: React.FocusEventHandler<HTMLInputElement>;
  84. onChange?: TimePickerAdapter['notifyChange'];
  85. onChangeWithDateFirst?: boolean;
  86. onFocus?: React.FocusEventHandler<HTMLInputElement>;
  87. onOpenChange?: (open: boolean) => void;
  88. };
  89. export interface TimePickerState {
  90. open: boolean;
  91. value: Date[];
  92. inputValue: string;
  93. currentSelectPanel: string | number;
  94. isAM: [boolean, boolean];
  95. showHour: boolean;
  96. showMinute: boolean;
  97. showSecond: boolean;
  98. invalid: boolean;
  99. }
  100. export default class TimePicker extends BaseComponent<TimePickerProps, TimePickerState> {
  101. static contextType = ConfigContext;
  102. static propTypes = {
  103. 'aria-labelledby': PropTypes.string,
  104. 'aria-invalid': PropTypes.bool,
  105. 'aria-errormessage': PropTypes.string,
  106. 'aria-describedby': PropTypes.string,
  107. 'aria-required': PropTypes.bool,
  108. prefixCls: PropTypes.string,
  109. clearText: PropTypes.string,
  110. value: TimeShape,
  111. inputReadOnly: PropTypes.bool,
  112. disabled: PropTypes.bool,
  113. showClear: PropTypes.bool,
  114. defaultValue: TimeShape,
  115. open: PropTypes.bool,
  116. defaultOpen: PropTypes.bool,
  117. onOpenChange: PropTypes.func,
  118. position: PropTypes.any,
  119. getPopupContainer: PropTypes.func,
  120. placeholder: PropTypes.string,
  121. format: PropTypes.string,
  122. style: PropTypes.object,
  123. className: PropTypes.string,
  124. popupClassName: PropTypes.string,
  125. popupStyle: PropTypes.object,
  126. disabledHours: PropTypes.func,
  127. disabledMinutes: PropTypes.func,
  128. disabledSeconds: PropTypes.func,
  129. hideDisabledOptions: PropTypes.bool,
  130. onChange: PropTypes.func,
  131. use12Hours: PropTypes.bool,
  132. hourStep: PropTypes.number,
  133. minuteStep: PropTypes.number,
  134. secondStep: PropTypes.number,
  135. focusOnOpen: PropTypes.bool,
  136. autoFocus: PropTypes.bool,
  137. size: PropTypes.oneOf(strings.SIZE),
  138. panels: PropTypes.arrayOf(PropTypes.shape(PanelShape)),
  139. onFocus: PropTypes.func,
  140. onBlur: PropTypes.func,
  141. locale: PropTypes.object,
  142. localeCode: PropTypes.string,
  143. dateFnsLocale: PropTypes.object,
  144. zIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  145. insetLabel: PropTypes.node,
  146. insetLabelId: PropTypes.string,
  147. validateStatus: PropTypes.oneOf(strings.STATUS),
  148. type: PropTypes.oneOf<TimePickerProps['type']>(strings.TYPES),
  149. rangeSeparator: PropTypes.string,
  150. triggerRender: PropTypes.func,
  151. timeZone: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  152. scrollItemProps: PropTypes.object,
  153. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]),
  154. autoAdjustOverflow: PropTypes.bool,
  155. ...PanelShape,
  156. inputStyle: PropTypes.object,
  157. };
  158. static defaultProps = {
  159. autoAdjustOverflow: true,
  160. getPopupContainer: () => document.body,
  161. showClear: true,
  162. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  163. rangeSeparator: strings.DEFAULT_RANGE_SEPARATOR,
  164. onOpenChange: noop,
  165. clearText: 'clear',
  166. prefixCls: cssClasses.PREFIX,
  167. inputReadOnly: false,
  168. style: {},
  169. className: '',
  170. popupClassName: '',
  171. popupStyle: { left: '0px', top: '0px' },
  172. disabledHours: () => [] as number[],
  173. disabledMinutes: () => [] as number[],
  174. disabledSeconds: () => [] as number[],
  175. hideDisabledOptions: false,
  176. // position: 'bottomLeft',
  177. onFocus: noop,
  178. onBlur: noop,
  179. onChange: noop,
  180. onChangeWithDateFirst: true,
  181. use12Hours: false,
  182. focusOnOpen: false,
  183. onKeyDown: noop,
  184. size: 'default' as const,
  185. type: strings.DEFAULT_TYPE,
  186. ...PanelShapeDefaults,
  187. // format: strings.DEFAULT_FORMAT,
  188. // open and value controlled
  189. };
  190. foundation: TimePickerFoundation;
  191. timePickerRef: React.MutableRefObject<HTMLDivElement>;
  192. savePanelRef: React.RefObject<HTMLDivElement>;
  193. clickOutSideHandler: (e: MouseEvent) => void;
  194. constructor(props: TimePickerProps) {
  195. super(props);
  196. const { format = strings.DEFAULT_FORMAT } = props;
  197. this.state = {
  198. open: props.open || props.defaultOpen || false,
  199. value: [], // Date[]
  200. inputValue: '', // time string
  201. currentSelectPanel: 0,
  202. isAM: [true, false],
  203. showHour: Boolean(format.match(/HH|hh|H|h/g)),
  204. showMinute: Boolean(format.match(/mm/g)),
  205. showSecond: Boolean(format.match(/ss/g)),
  206. invalid: undefined
  207. };
  208. this.foundation = new TimePickerFoundation(this.adapter);
  209. this.timePickerRef = React.createRef();
  210. this.savePanelRef = React.createRef();
  211. }
  212. get adapter(): TimePickerAdapter<TimePickerProps, TimePickerState> {
  213. return {
  214. ...super.adapter,
  215. togglePanel: show => {
  216. this.setState({ open: show });
  217. },
  218. registerClickOutSide: () => {
  219. if (this.clickOutSideHandler) {
  220. this.adapter.unregisterClickOutSide();
  221. }
  222. this.clickOutSideHandler = e => {
  223. const panel = this.savePanelRef && this.savePanelRef.current;
  224. const isInPanel = e.target && panel && panel.contains(e.target as Node);
  225. const isInTimepicker =
  226. this.timePickerRef &&
  227. this.timePickerRef.current &&
  228. this.timePickerRef.current.contains(e.target as Node);
  229. if (!isInTimepicker && !isInPanel) {
  230. const clickedOutside = true;
  231. this.foundation.hanldePanelClose(clickedOutside, e);
  232. }
  233. };
  234. document.addEventListener('mousedown', this.clickOutSideHandler);
  235. },
  236. setInputValue: (inputValue, cb) => this.setState({ inputValue }, cb),
  237. unregisterClickOutSide: () => {
  238. if (this.clickOutSideHandler) {
  239. document.removeEventListener('mousedown', this.clickOutSideHandler);
  240. this.clickOutSideHandler = null;
  241. }
  242. },
  243. notifyOpenChange: (...args) => this.props.onOpenChange(...args),
  244. notifyChange: (agr1, arg2) => this.props.onChange && this.props.onChange(agr1, arg2),
  245. notifyFocus: (...args) => this.props.onFocus && this.props.onFocus(...args),
  246. notifyBlur: (...args) => this.props.onBlur && this.props.onBlur(...args),
  247. isRangePicker: () => this.props.type === strings.TYPE_TIME_RANGE_PICKER,
  248. };
  249. }
  250. static getDerivedStateFromProps(nextProps: TimePickerProps, prevState: TimePickerState) {
  251. if ('open' in nextProps && nextProps.open !== prevState.open) {
  252. return {
  253. open: nextProps.open,
  254. };
  255. }
  256. return null;
  257. }
  258. componentDidUpdate(prevProps: TimePickerProps) {
  259. // if (this.isControlled('open') && this.props.open != null && this.props.open !== prevProps.open) {
  260. // this.foundation.setPanel(this.props.open);
  261. // }
  262. if (this.isControlled('value') && this.props.value !== prevProps.value) {
  263. this.foundation.refreshProps({
  264. ...this.props,
  265. });
  266. } else if (this.props.timeZone !== prevProps.timeZone) {
  267. this.foundation.refreshProps({
  268. timeZone: this.props.timeZone,
  269. __prevTimeZone: prevProps.timeZone,
  270. value: this.state.value,
  271. });
  272. }
  273. }
  274. onCurrentSelectPanelChange = (currentSelectPanel: string) => {
  275. this.setState({ currentSelectPanel });
  276. };
  277. handlePanelChange = (
  278. value: { isAM: boolean; value: string; timeStampValue: number },
  279. index: number
  280. ) => this.foundation.handlePanelChange(value, index);
  281. handleInput = (value: string) => this.foundation.handleInputChange(value);
  282. createPanelProps = (index = 0) => {
  283. const { panels, panelFooter, panelHeader, locale } = this.props;
  284. const panelProps = {
  285. panelHeader,
  286. panelFooter,
  287. };
  288. if (this.adapter.isRangePicker()) {
  289. const defaultHeaderMap = {
  290. 0: locale.begin,
  291. 1: locale.end,
  292. };
  293. panelProps.panelHeader = get(
  294. panels,
  295. index,
  296. isNullOrUndefined(panelHeader) ? get(defaultHeaderMap, index, null) : panelHeader
  297. );
  298. panelProps.panelFooter = get(panels, index, panelFooter) as React.ReactNode;
  299. }
  300. return panelProps;
  301. };
  302. getPanelElement() {
  303. const { prefixCls, type } = this.props;
  304. const { isAM, value } = this.state;
  305. const format = this.foundation.getDefaultFormatIfNeed();
  306. const timePanels = [
  307. <Combobox
  308. {...this.props}
  309. key={0}
  310. format={format}
  311. isAM={isAM[0]}
  312. timeStampValue={value[0]}
  313. prefixCls={`${prefixCls}-panel`}
  314. onChange={v => this.handlePanelChange(v, 0)}
  315. onCurrentSelectPanelChange={this.onCurrentSelectPanelChange}
  316. {...this.createPanelProps(0)}
  317. />,
  318. ];
  319. if (type === strings.TYPE_TIME_RANGE_PICKER) {
  320. timePanels.push(
  321. <Combobox
  322. {...this.props}
  323. key={1}
  324. format={format}
  325. isAM={isAM[1]}
  326. timeStampValue={value[1]}
  327. prefixCls={`${prefixCls}-panel`}
  328. onChange={v => this.handlePanelChange(v, 1)}
  329. onCurrentSelectPanelChange={this.onCurrentSelectPanelChange}
  330. {...this.createPanelProps(1)}
  331. />
  332. );
  333. }
  334. const wrapCls = classNames({
  335. [cssClasses.RANGE_PANEL_LISTS]: this.adapter.isRangePicker(),
  336. });
  337. return (
  338. <div ref={this.savePanelRef} className={wrapCls}>
  339. {timePanels.map(panel => panel)}
  340. </div>
  341. );
  342. }
  343. getPopupClassName() {
  344. const { use12Hours, prefixCls, popupClassName } = this.props;
  345. const { showHour, showMinute, showSecond } = this.state;
  346. let selectColumnCount = 0;
  347. if (showHour) {
  348. selectColumnCount += 1;
  349. }
  350. if (showMinute) {
  351. selectColumnCount += 1;
  352. }
  353. if (showSecond) {
  354. selectColumnCount += 1;
  355. }
  356. if (use12Hours) {
  357. selectColumnCount += 1;
  358. }
  359. return classNames(
  360. `${prefixCls}-panel`,
  361. popupClassName,
  362. {
  363. [`${prefixCls}-panel-narrow`]: (!showHour || !showMinute || !showSecond) && !use12Hours,
  364. [cssClasses.RANGE_PICKER]: this.adapter.isRangePicker(),
  365. },
  366. `${prefixCls}-panel-column-${selectColumnCount}`
  367. );
  368. }
  369. focus() {
  370. // TODO this.picker is undefined, confirm keep this func or not
  371. // this.picker.focus();
  372. }
  373. blur() {
  374. // TODO this.picker is undefined, confirm keep this func or not
  375. // this.picker.blur();
  376. }
  377. handlePanelVisibleChange = (visible: boolean) => this.foundation.handleVisibleChange(visible);
  378. openPanel = () => {
  379. this.foundation.handlePanelOpen();
  380. };
  381. handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
  382. this.foundation.handleFocus(e);
  383. };
  384. handleBlur = (e: React.FocusEvent<HTMLInputElement>) => this.foundation.handleInputBlur(e);
  385. setTimePickerRef: React.LegacyRef<HTMLDivElement> = node => (this.timePickerRef.current = node);
  386. render() {
  387. const {
  388. prefixCls,
  389. placeholder,
  390. disabled,
  391. defaultValue,
  392. className,
  393. popupStyle,
  394. size,
  395. style,
  396. locale,
  397. localeCode,
  398. zIndex,
  399. getPopupContainer,
  400. insetLabel,
  401. insetLabelId,
  402. inputStyle,
  403. showClear,
  404. panelHeader,
  405. panelFooter,
  406. rangeSeparator,
  407. onOpenChange,
  408. onChangeWithDateFirst,
  409. popupClassName: propPopupClassName,
  410. hideDisabledOptions,
  411. use12Hours,
  412. minuteStep,
  413. hourStep,
  414. secondStep,
  415. scrollItemProps,
  416. triggerRender,
  417. motion,
  418. autoAdjustOverflow,
  419. ...rest
  420. } = this.props;
  421. const format = this.foundation.getDefaultFormatIfNeed();
  422. const position = this.foundation.getPosition();
  423. const useCustomTrigger = typeof triggerRender === 'function';
  424. const { open, inputValue, invalid, value } = this.state;
  425. const popupClassName = this.getPopupClassName();
  426. const headerPrefix = classNames({
  427. [`${prefixCls}-header`]: true,
  428. });
  429. const panelPrefix = classNames({
  430. [`${prefixCls}-panel`]: true,
  431. [`${prefixCls}-panel-${size}`]: size,
  432. });
  433. const inputProps = {
  434. ...rest,
  435. disabled,
  436. prefixCls,
  437. size,
  438. showClear: disabled ? false : showClear,
  439. style: inputStyle,
  440. value: inputValue,
  441. onFocus: this.handleFocus,
  442. insetLabel,
  443. insetLabelId,
  444. format,
  445. locale,
  446. localeCode,
  447. invalid,
  448. placeholder,
  449. onChange: this.handleInput,
  450. onBlur: this.handleBlur,
  451. };
  452. const outerProps = {} as { onClick: () => void };
  453. if (useCustomTrigger) {
  454. outerProps.onClick = this.openPanel;
  455. }
  456. return (
  457. <div
  458. ref={this.setTimePickerRef}
  459. className={classNames({ [prefixCls]: true }, className)}
  460. style={style}
  461. {...outerProps}
  462. >
  463. <Popover
  464. getPopupContainer={getPopupContainer}
  465. zIndex={zIndex as number}
  466. prefixCls={panelPrefix}
  467. contentClassName={popupClassName}
  468. style={popupStyle}
  469. content={this.getPanelElement()}
  470. trigger={'custom'}
  471. position={position}
  472. visible={disabled ? false : Boolean(open)}
  473. motion={motion}
  474. autoAdjustOverflow={autoAdjustOverflow}
  475. >
  476. {useCustomTrigger ? (
  477. <Trigger
  478. triggerRender={triggerRender}
  479. disabled={disabled}
  480. value={value}
  481. inputValue={inputValue}
  482. onChange={this.handleInput}
  483. placeholder={placeholder}
  484. componentName={'TimePicker'}
  485. componentProps={{ ...this.props }}
  486. />
  487. ) : (
  488. <span className={headerPrefix}>
  489. <TimeInput {...inputProps} />
  490. </span>
  491. )}
  492. </Popover>
  493. </div>
  494. );
  495. }
  496. }