Combobox.tsx 11 KB

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