Combobox.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /* eslint-disable max-len */
  2. /* eslint-disable react/no-did-update-set-state */
  3. import React from 'react';
  4. import PropTypes from 'prop-types';
  5. import { format as dateFnsFormat } from 'date-fns';
  6. import { noop } from 'lodash-es';
  7. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  8. import { strings } from '@douyinfe/semi-foundation/timePicker/constants';
  9. import ScrollList from '../scrollList/index';
  10. import ScrollItem from '../scrollList/scrollItem';
  11. import ComboboxFoundation, { formatOption } from '@douyinfe/semi-foundation/timePicker/ComboxFoundation';
  12. import LocaleConsumer from '../locale/localeConsumer';
  13. import { TimePickerProps } from './TimePicker';
  14. import { Locale } from '../locale/interface';
  15. export type ComboboxProps = Pick<TimePickerProps, 'format' | 'prefixCls' | 'disabledHours' |
  16. 'disabledMinutes' |
  17. 'disabledSeconds' |
  18. 'hideDisabledOptions' |
  19. 'use12Hours' |
  20. 'scrollItemProps' |
  21. 'panelFooter' |
  22. 'panelHeader'> & BaseProps & {
  23. defaultOpenValue?: TimePickerProps['value'];
  24. showHour?: boolean;
  25. showMinute?: boolean;
  26. showSecond?: boolean;
  27. onChange?: (value: { isAM: boolean; value: string; timeStampValue: number }) => void;
  28. onCurrentSelectPanelChange?: (range: string) => void;
  29. isAM?: boolean;
  30. timeStampValue?: any;
  31. };
  32. export interface ComboboxState {
  33. showHour: boolean;
  34. showMinute: boolean;
  35. showSecond: boolean;
  36. hourOptions: number[];
  37. minuteOptions: number[];
  38. secondOptions: number[];
  39. }
  40. export type FormatOptionReturn = ReturnType<typeof formatOption>;
  41. export interface AMPMOptionItem {
  42. value: string;
  43. text: string;
  44. }
  45. class Combobox extends BaseComponent<ComboboxProps, ComboboxState> {
  46. static propTypes = {
  47. format: PropTypes.string,
  48. defaultOpenValue: PropTypes.object,
  49. prefixCls: PropTypes.string,
  50. onChange: PropTypes.func,
  51. showHour: PropTypes.bool,
  52. showMinute: PropTypes.bool,
  53. showSecond: PropTypes.bool,
  54. disabledHours: PropTypes.func,
  55. disabledMinutes: PropTypes.func,
  56. disabledSeconds: PropTypes.func,
  57. hideDisabledOptions: PropTypes.bool,
  58. onCurrentSelectPanelChange: PropTypes.func,
  59. use12Hours: PropTypes.bool,
  60. isAM: PropTypes.bool,
  61. timeStampValue: PropTypes.any,
  62. scrollItemProps: PropTypes.object,
  63. };
  64. static defaultProps = {
  65. disabledHours: noop,
  66. disabledMinutes: noop,
  67. disabledSeconds: noop,
  68. format: strings.DEFAULT_FORMAT,
  69. };
  70. foundation: ComboboxFoundation;
  71. constructor(props: ComboboxProps) {
  72. super(props);
  73. this.foundation = new ComboboxFoundation(this.adapter);
  74. this.state = {
  75. ...this.foundation.initData(),
  76. };
  77. }
  78. componentDidUpdate(prevProps: ComboboxProps, prevState: ComboboxState) {
  79. if (prevProps.timeStampValue !== this.props.timeStampValue || prevProps.format !== this.props.format) {
  80. this.setState({
  81. ...this.foundation.initData(),
  82. });
  83. }
  84. }
  85. componentWillUnmount() {
  86. // this.foundation.destroy();
  87. }
  88. componentDidMount() {
  89. // this.foundation.init();
  90. }
  91. cacheRefCurrent = (key: string, current: ScrollItem<FormatOptionReturn> | ScrollItem<AMPMOptionItem>) => {
  92. if (key && typeof key === 'string') {
  93. this.adapter.setCache(key, current);
  94. }
  95. };
  96. reselect = () => {
  97. const currentKeys = ['ampm', 'hour', 'minute', 'second'];
  98. currentKeys.forEach(key => {
  99. const current = this.adapter.getCache(key);
  100. if (current && current.scrollToIndex) {
  101. current.scrollToIndex();
  102. }
  103. });
  104. };
  105. onItemChange = ({ type, value, disabled }: { type?: string; value: string; disabled?: boolean; }) => {
  106. // eslint-disable-next-line prefer-const
  107. let { onChange, use12Hours, isAM, format, timeStampValue } = this.props;
  108. const transformValue = this.foundation.getDisplayDateFromTimeStamp(timeStampValue);
  109. // TODO: foundation
  110. if (type === 'hour') {
  111. if (use12Hours) {
  112. if (isAM) {
  113. transformValue.setHours(Number(value) % 12);
  114. } else {
  115. transformValue.setHours((Number(value) % 12) + 12);
  116. }
  117. } else {
  118. transformValue.setHours(Number(value));
  119. }
  120. } else if (type === 'minute') {
  121. transformValue.setMinutes(Number(value));
  122. } else if (type === 'ampm') {
  123. const ampm = value.toUpperCase();
  124. if (use12Hours) {
  125. if (ampm === 'PM') {
  126. isAM = false;
  127. transformValue.getHours() < 12 && transformValue.setHours((transformValue.getHours() % 12) + 12);
  128. }
  129. if (ampm === 'AM') {
  130. isAM = true;
  131. transformValue.getHours() >= 12 && transformValue.setHours(transformValue.getHours() - 12);
  132. }
  133. }
  134. } else {
  135. transformValue.setSeconds(Number(value));
  136. }
  137. onChange &&
  138. onChange({
  139. isAM,
  140. value: dateFnsFormat(transformValue, format && format.replace(/(\s+)A/g, '$1a')), // dateFns only supports "h: mm: ss a"
  141. timeStampValue: Number(transformValue),
  142. });
  143. };
  144. onEnterSelectPanel = (range: string) => {
  145. const { onCurrentSelectPanelChange } = this.props;
  146. onCurrentSelectPanelChange(range);
  147. };
  148. renderHourSelect(hour: number, locale: Locale['TimePicker']) {
  149. const { prefixCls, disabledHours, use12Hours, scrollItemProps } = this.props;
  150. const { showHour, hourOptions } = this.state;
  151. if (!showHour) {
  152. return null;
  153. }
  154. const disabledOptions = disabledHours();
  155. let hourOptionsAdj,
  156. hourAdj;
  157. if (use12Hours) {
  158. hourOptionsAdj = [12].concat(hourOptions.filter(h => h < 12 && h > 0));
  159. hourAdj = hour % 12 || 12;
  160. } else {
  161. hourOptionsAdj = hourOptions;
  162. hourAdj = hour;
  163. }
  164. const transformHour = (value: string) => value + locale.hour;
  165. const className = `${prefixCls}-list-hour`;
  166. return (
  167. <ScrollItem<FormatOptionReturn>
  168. ref={current => this.cacheRefCurrent('hour', current)}
  169. mode={'wheel'}
  170. transform={transformHour}
  171. cycled={true}
  172. className={className}
  173. list={hourOptionsAdj.map(option => formatOption(option, disabledOptions))}
  174. selectedIndex={hourOptionsAdj.indexOf(hourAdj)}
  175. type="hour"
  176. onSelect={this.onItemChange}
  177. {...scrollItemProps}
  178. />
  179. );
  180. }
  181. renderMinuteSelect(minute: number, locale: Locale['TimePicker']) {
  182. const { prefixCls, disabledMinutes, timeStampValue, scrollItemProps } = this.props;
  183. const { showMinute, minuteOptions } = this.state;
  184. if (!showMinute) {
  185. return null;
  186. }
  187. const value = new Date(timeStampValue);
  188. const disabledOptions = disabledMinutes && disabledMinutes(value.getHours());
  189. const className = `${prefixCls}-list-minute`;
  190. const transformMinute = (min: string) => min + locale.minute;
  191. return (
  192. <ScrollItem<FormatOptionReturn>
  193. ref={current => this.cacheRefCurrent('minute', current)}
  194. mode={'wheel'}
  195. transform={transformMinute}
  196. cycled={true}
  197. list={minuteOptions.map(option => formatOption(option, disabledOptions))}
  198. selectedIndex={minuteOptions.indexOf(minute)}
  199. type="minute"
  200. onSelect={this.onItemChange}
  201. className={className}
  202. {...scrollItemProps}
  203. />
  204. );
  205. }
  206. renderSecondSelect(second: number, locale: Locale['TimePicker']) {
  207. const { prefixCls, disabledSeconds, timeStampValue, scrollItemProps } = this.props;
  208. const { showSecond, secondOptions } = this.state;
  209. if (!showSecond) {
  210. return null;
  211. }
  212. const value = new Date(timeStampValue);
  213. const disabledOptions = disabledSeconds && disabledSeconds(value.getHours(), value.getMinutes());
  214. const className = `${prefixCls}-list-second`;
  215. const transformSecond = (sec: number) => String(sec) + locale.second;
  216. return (
  217. <ScrollItem<FormatOptionReturn>
  218. ref={current => this.cacheRefCurrent('second', current)}
  219. mode={'wheel'}
  220. transform={transformSecond}
  221. cycled={true}
  222. list={secondOptions.map(option => formatOption(option, disabledOptions))}
  223. selectedIndex={secondOptions.indexOf(second)}
  224. className={className}
  225. type="second"
  226. onSelect={this.onItemChange}
  227. {...scrollItemProps}
  228. />
  229. );
  230. }
  231. renderAMPMSelect(locale: Locale['TimePicker'], localeCode: string) {
  232. const { prefixCls, use12Hours, isAM, scrollItemProps } = this.props;
  233. if (!use12Hours) {
  234. return null;
  235. }
  236. const AMPMOptions: AMPMOptionItem[] = [
  237. {
  238. value: 'AM',
  239. text: locale.AM || '上午',
  240. },
  241. {
  242. value: 'PM',
  243. text: locale.PM || '下午',
  244. },
  245. ];
  246. const selected = isAM ? 0 : 1;
  247. const className = `${prefixCls}-list-ampm`;
  248. return (
  249. <ScrollItem<AMPMOptionItem>
  250. ref={current => this.cacheRefCurrent('ampm', current)}
  251. mode={'wheel'}
  252. className={className}
  253. cycled={false}
  254. list={AMPMOptions}
  255. selectedIndex={selected}
  256. type="ampm"
  257. onSelect={this.onItemChange}
  258. {...scrollItemProps}
  259. />
  260. );
  261. }
  262. getDisplayDateFromTimeStamp = (timeStampValue: Date | string) => this.foundation.getDisplayDateFromTimeStamp(timeStampValue);
  263. render() {
  264. const { timeStampValue, panelHeader, panelFooter } = this.props;
  265. const value = this.getDisplayDateFromTimeStamp(timeStampValue);
  266. return (
  267. <LocaleConsumer componentName="TimePicker">
  268. {(locale: Locale['TimePicker'], localeCode: Locale['code']) => (
  269. <ScrollList header={panelHeader} footer={panelFooter}>
  270. {this.renderAMPMSelect(locale, localeCode)}
  271. {this.renderHourSelect(value.getHours(), locale)}
  272. {this.renderMinuteSelect(value.getMinutes(), locale)}
  273. {this.renderSecondSelect(value.getSeconds(), locale)}
  274. </ScrollList>
  275. )}
  276. </LocaleConsumer>
  277. );
  278. }
  279. }
  280. export default Combobox;