Combobox.tsx 11 KB

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