TimePicker.tsx 19 KB

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