foundation.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import { strings } from './constants';
  2. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  3. import {
  4. formatToString,
  5. parseToDate,
  6. hourIsDisabled,
  7. minuteIsDisabled,
  8. secondIsDisabled,
  9. transformToArray,
  10. isTimeFormatLike
  11. } from './utils';
  12. import { split, isUndefined } from 'lodash';
  13. import { isValid, format, getHours, Locale } from 'date-fns';
  14. import isNullOrUndefined from '../utils/isNullOrUndefined';
  15. import { TZDate } from '@date-fns/tz';
  16. export type BaseValueType = string | number | Date | undefined;
  17. export type Type = 'time' | 'timeRange';
  18. export type Position =
  19. | 'top'
  20. | 'topLeft'
  21. | 'topRight'
  22. | 'left'
  23. | 'leftTop'
  24. | 'leftBottom'
  25. | 'right'
  26. | 'rightTop'
  27. | 'rightBottom'
  28. | 'bottom'
  29. | 'bottomLeft'
  30. | 'bottomRight'
  31. | 'leftTopOver'
  32. | 'rightTopOver';
  33. export interface TimePickerFoundationProps {
  34. open?: boolean;
  35. timeZone?: string | number;
  36. dateFnsLocale?: Locale;
  37. rangeSeparator?: string;
  38. autoAdjustOverflow?: boolean;
  39. autoFocus?: boolean; // TODO: autoFocus did not take effect
  40. borderless?: boolean;
  41. className?: string;
  42. clearText?: string;
  43. clearIcon?: any;
  44. defaultOpen?: boolean;
  45. defaultValue?: BaseValueType | BaseValueType[];
  46. disabled?: boolean;
  47. disabledHours?: () => number[];
  48. disabledMinutes?: (selectedHour: number) => number[];
  49. disabledSeconds?: (selectedHour: number, selectedMinute: number) => number[];
  50. focusOnOpen?: boolean;
  51. format?: string;
  52. getPopupContainer?: () => HTMLElement;
  53. hideDisabledOptions?: boolean;
  54. hourStep?: number;
  55. id?: string;
  56. inputReadOnly?: boolean;
  57. inputStyle?: Record<string, any>;
  58. insetLabelId?: string;
  59. localeCode?: string;
  60. minuteStep?: number;
  61. motion?: boolean;
  62. placeholder?: string;
  63. popupClassName?: string;
  64. position?: Position;
  65. prefixCls?: string;
  66. preventScroll?: boolean;
  67. secondStep?: number;
  68. showClear?: boolean;
  69. stopPropagation?: boolean;
  70. triggerRender?: (props?: any) => any;
  71. type?: Type;
  72. use12Hours?: boolean;
  73. value?: BaseValueType | BaseValueType[];
  74. zIndex?: number | string;
  75. onBlur?: (e: any) => void;
  76. onChange?: TimePickerAdapter['notifyChange'];
  77. onChangeWithDateFirst?: boolean;
  78. onFocus?: (e: any) => void;
  79. onOpenChange?: (open: boolean) => void
  80. }
  81. export interface TimePickerFoundationState {
  82. open: boolean;
  83. value: TZDate[];
  84. inputValue: string;
  85. currentSelectPanel: string | number;
  86. isAM: [boolean, boolean];
  87. showHour: boolean;
  88. showMinute: boolean;
  89. showSecond: boolean;
  90. invalid: boolean
  91. }
  92. export interface TimePickerAdapter extends DefaultAdapter<TimePickerFoundationProps, TimePickerFoundationState> {
  93. togglePanel: (show: boolean) => void;
  94. registerClickOutSide: () => void;
  95. setInputValue: (inputValue: string, cb?: () => void) => void;
  96. unregisterClickOutSide: () => void;
  97. notifyOpenChange: (open: boolean) => void;
  98. notifyChange(value: TZDate | TZDate[], input: string | string[]): void;
  99. notifyChange(input: string | string[], value: TZDate | TZDate[]): void;
  100. notifyFocus: (e: any) => void;
  101. notifyBlur: (e: any) => void;
  102. isRangePicker: () => boolean
  103. }
  104. // TODO: split, timePicker different components cannot share a foundation
  105. class TimePickerFoundation extends BaseFoundation<TimePickerAdapter> {
  106. constructor(adapter: TimePickerAdapter) {
  107. super({ ...adapter });
  108. }
  109. init() {
  110. this.initDataFromDefaultValue();
  111. const open = this._isControlledComponent('open') ? this.getProp('open') : this.getProp('defaultOpen');
  112. if (open && !this._isControlledComponent('open')) {
  113. this._adapter.registerClickOutSide();
  114. }
  115. }
  116. getPosition(): Position {
  117. const position = this.getProp('position');
  118. const type = this.getProp('type') || strings.DEFAULT_TYPE;
  119. // rtl change default position
  120. const direction = this.getContext('direction');
  121. const rtlDirection = direction === 'rtl' ? 'bottomRight' : '';
  122. return position || rtlDirection || strings.DEFAULT_POSITION[type];
  123. }
  124. isDisabledHMS({ hours, minutes, seconds }: { hours: number; minutes: number; seconds: number }) {
  125. const { disabledHours, disabledMinutes, disabledSeconds } = this.getProps();
  126. const hDis = !isNullOrUndefined(hours) && hourIsDisabled(disabledHours, hours);
  127. const mDis = !isNullOrUndefined(hours) && !isNullOrUndefined(minutes) && minuteIsDisabled(disabledMinutes, hours, minutes);
  128. const sDis =
  129. !isNullOrUndefined(hours) &&
  130. !isNullOrUndefined(minutes) &&
  131. !isNullOrUndefined(seconds) &&
  132. secondIsDisabled(disabledSeconds, hours, minutes, seconds);
  133. return hDis || mDis || sDis;
  134. }
  135. isValidTimeZone(timeZone: string | number) {
  136. return ['string', 'number'].includes(typeof timeZone) && timeZone !== '';
  137. }
  138. getDefaultFormatIfNeed(): string {
  139. if (this._isInProps('format')) {
  140. return this.getProp('format');
  141. } else if (this.getProp('use12Hours')) {
  142. return strings.DEFAULT_FORMAT_A;
  143. } else {
  144. return strings.DEFAULT_FORMAT;
  145. }
  146. }
  147. /**
  148. * User input value => save timestamp
  149. */
  150. initDataFromDefaultValue() {
  151. const defaultValue = this.getProp('defaultValue');
  152. let value = this.getProp('value');
  153. const timeZone = this.getProp('timeZone');
  154. const formatToken = this.getValidFormat();
  155. const { rangeSeparator, dateFnsLocale } = this.getProps();
  156. value = value || defaultValue;
  157. if (!Array.isArray(value)) {
  158. value = value ? [value] : [];
  159. }
  160. const parsedValues: TZDate[] = [];
  161. let invalid = false;
  162. (value as any[]).forEach(v => {
  163. const pv = parseToDate(v, formatToken, dateFnsLocale);
  164. if (!isNaN(pv.getTime())) {
  165. parsedValues.push(this.isValidTimeZone(timeZone) ? utcToZonedTime(pv, timeZone) : pv);
  166. }
  167. });
  168. const isAM = [true, false];
  169. parsedValues.map((item, idx) => {
  170. isAM[idx] = getHours(item) < 12;
  171. });
  172. if (parsedValues.length === value.length) {
  173. value = parsedValues;
  174. } else {
  175. value = [];
  176. if (value.length) {
  177. invalid = true;
  178. }
  179. }
  180. let inputValue = '';
  181. if (!invalid) {
  182. inputValue = (value as any[]).map(v => formatToString(v, formatToken, dateFnsLocale)).join(rangeSeparator);
  183. }
  184. this.setState({
  185. isAM,
  186. value,
  187. inputValue,
  188. invalid,
  189. } as any);
  190. }
  191. getValidFormat(validFormat?: string) {
  192. let _format = validFormat;
  193. if (isNullOrUndefined(_format)) {
  194. _format = this.getDefaultFormatIfNeed();
  195. }
  196. if (typeof _format !== 'string') {
  197. _format = strings.DEFAULT_FORMAT;
  198. }
  199. return _format;
  200. }
  201. handlePanelChange(result: { isAM: boolean; value: string; timeStampValue: number }, index = 0) {
  202. // console.log(result, index);
  203. const formatToken = this.getValidFormat();
  204. const dateFnsLocale = this.getProp('dateFnsLocale');
  205. const { value: oldValue } = this._adapter.getStates();
  206. let isAM = this.getState('isAM');
  207. const value: TZDate[] = transformToArray(oldValue);
  208. isAM = transformToArray(isAM);
  209. if (result) {
  210. const panelIsAM = Boolean(result.isAM);
  211. const date = parseToDate(result.timeStampValue, formatToken, dateFnsLocale);
  212. value[index] = date;
  213. isAM[index] = panelIsAM;
  214. const inputValue = this.formatValue(value);
  215. if (this.getState('isAM')[index] !== result.isAM) {
  216. this.setState({ isAM } as any);
  217. }
  218. if (!this._isControlledComponent('value')) {
  219. const invalid = this.validateDates(value);
  220. this.setState({
  221. isAM,
  222. value,
  223. inputValue,
  224. invalid,
  225. } as any);
  226. }
  227. if (this._hasChanged(value, oldValue)) {
  228. this._notifyChange(value, inputValue);
  229. }
  230. }
  231. }
  232. refreshProps(props: any = {}) {
  233. const { value, timeZone, __prevTimeZone } = props;
  234. let dates = this.parseValue(value);
  235. let invalid = dates.some(d => isNaN(Number(d)));
  236. if (!invalid) {
  237. if (this.isValidTimeZone(timeZone)) {
  238. dates = dates.map(date =>
  239. utcToZonedTime(
  240. this.isValidTimeZone(__prevTimeZone) ? zonedTimeToUtc(date, __prevTimeZone) : date,
  241. timeZone
  242. )
  243. );
  244. }
  245. invalid = dates.some(d =>
  246. this.isDisabledHMS({ hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds() })
  247. );
  248. }
  249. const inputValue = this.formatValue(dates);
  250. this.setState({
  251. value: dates,
  252. invalid,
  253. inputValue,
  254. } as any);
  255. }
  256. handleFocus(e: any) {
  257. if (!this.getState('open')) {
  258. this.handlePanelOpen();
  259. }
  260. this._adapter.notifyFocus(e);
  261. }
  262. setPanel(open: boolean) {
  263. this._adapter.togglePanel(open);
  264. }
  265. destroy() {
  266. this._adapter.unregisterClickOutSide();
  267. }
  268. handlePanelOpen() {
  269. if (!this._isControlledComponent('open')) {
  270. this._adapter.registerClickOutSide();
  271. this.setPanel(true);
  272. }
  273. this._adapter.notifyOpenChange(true);
  274. }
  275. handlePanelClose(clickedOutside: boolean, e: any) {
  276. if (!this._isControlledComponent('open')) {
  277. this._adapter.unregisterClickOutSide();
  278. this.setPanel(false);
  279. }
  280. this._adapter.notifyOpenChange(false);
  281. this._adapter.notifyBlur(e);
  282. }
  283. /* istanbul ignore next */
  284. handleVisibleChange(visible: boolean) {
  285. if (!this._isControlledComponent('open')) {
  286. this._adapter.togglePanel(visible);
  287. }
  288. this._adapter.notifyOpenChange(visible);
  289. }
  290. handleInputChange(input: string) {
  291. this._adapter.setInputValue(input);
  292. const rangeSeparator = this.getProp('rangeSeparator');
  293. const inputValues = split(input, rangeSeparator);
  294. const formatToken = this.getValidFormat();
  295. /**
  296. * 如果输入的字符串不是formatLike则不进行下一步操作,以免输入过程被打断
  297. * 特殊case
  298. * - 清空时,input 为 '',此时需要跳过isTimeFormatLike判断
  299. *
  300. * If the input string is not formatLike, do not proceed to the next operation to avoid interruption of the input process
  301. * special case
  302. * -when emptying, the input is "', at this time you need to skip isTimeFormatLike judgment
  303. */
  304. if (input !== '' && inputValues.some(time => !isTimeFormatLike(time, formatToken))) {
  305. return;
  306. }
  307. const dates = this.parseInput(input);
  308. const invalid = this.validateDates(dates);
  309. const states: { invalid: boolean; value?: TZDate[] } = { invalid };
  310. const oldValue = this.getState('value');
  311. let value = transformToArray(oldValue);
  312. if (!invalid) {
  313. states.value = dates;
  314. value = [...dates];
  315. }
  316. if (!this._isControlledComponent('value')) {
  317. this.setState(states as any);
  318. }
  319. if (this._hasChanged(value, oldValue)) {
  320. this._notifyChange(value, input);
  321. }
  322. }
  323. /* istanbul ignore next */
  324. doValidate(args: string | Array<TZDate>) {
  325. if (typeof args === 'string') {
  326. return this.validateStr(args);
  327. } else if (Array.isArray(args)) {
  328. return this.validateDates(args);
  329. }
  330. return undefined;
  331. }
  332. validateStr(inputValue = '') {
  333. const dates = this.parseInput(inputValue);
  334. return this.validateDates(dates);
  335. }
  336. validateDates(dates: Array<TZDate> = []) {
  337. let invalid = dates.some(d => isNaN(Number(d)));
  338. if (!invalid) {
  339. invalid = dates.some(d =>
  340. this.isDisabledHMS({ hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds() })
  341. );
  342. }
  343. return invalid;
  344. }
  345. handleInputBlur(e: any) {
  346. const invalid = this.getState('invalid');
  347. const inputValue = this.getState('inputValue');
  348. const value = this.getState('value');
  349. if (inputValue) {
  350. if (invalid) {
  351. this.setState({
  352. inputValue: this.formatValue(value),
  353. invalid: false,
  354. } as any);
  355. } else {
  356. this.setState({
  357. inputValue: this.formatValue(value),
  358. } as any);
  359. }
  360. } else {
  361. this.setState({
  362. inputValue: '',
  363. value: [],
  364. invalid: false,
  365. } as any);
  366. }
  367. }
  368. formatValue(dates: TZDate[]): string {
  369. const validFormat = this.getValidFormat();
  370. const rangeSeparator = this.getProp('rangeSeparator');
  371. const dateFnsLocale = this.getProp('dateFnsLocale');
  372. let _dates = dates;
  373. if (_dates && !Array.isArray(_dates)) {
  374. _dates = _dates[_dates];
  375. }
  376. if (_dates && Array.isArray(_dates)) {
  377. const result = _dates.map(date => {
  378. let str;
  379. if (isUndefined(date)) {
  380. str = '';
  381. } else {
  382. str = formatToString(date, validFormat, dateFnsLocale);
  383. }
  384. return str;
  385. });
  386. return result.join(rangeSeparator);
  387. }
  388. return undefined;
  389. }
  390. parseInput(str: string) {
  391. const validFormat = this.getValidFormat();
  392. const rangeSeparator = this.getProp('rangeSeparator');
  393. const dateFnsLocale = this.getProp('dateFnsLocale');
  394. if (str && typeof str === 'string') {
  395. return split(str, rangeSeparator).map(v => parseToDate(v, validFormat, dateFnsLocale));
  396. }
  397. return [];
  398. }
  399. parseValue(value: string | Date | Array<string | Date> = []): TZDate[] {
  400. const formatToken = this.getValidFormat();
  401. const { dateFnsLocale, timeZone } = this._adapter.getProps();
  402. let _value = value;
  403. if (!Array.isArray(_value)) {
  404. _value = _value ? [_value] : [];
  405. }
  406. if (Array.isArray(_value)) {
  407. return _value.map(v => parseToDate(v, formatToken, dateFnsLocale));
  408. }
  409. return [];
  410. }
  411. _notifyChange(value: TZDate[], inputValue: string) {
  412. let str: string | string[] = inputValue;
  413. let _value: TZDate | TZDate[] = value;
  414. const timeZone = this.getProp('timeZone');
  415. if (this._adapter.isRangePicker()) {
  416. const rangeSeparator = this.getProp('rangeSeparator');
  417. str = split(inputValue, rangeSeparator);
  418. } else {
  419. _value = Array.isArray(_value) ? _value[0] : _value;
  420. }
  421. if (this.isValidTimeZone(timeZone) && _value) {
  422. const formatToken = this.getValidFormat();
  423. if (Array.isArray(_value)) {
  424. _value = _value.map(v => zonedTimeToUtc(v, timeZone));
  425. str = _value.map(v => format(v, formatToken));
  426. } else {
  427. _value = zonedTimeToUtc(_value, timeZone);
  428. str = format(_value, formatToken);
  429. }
  430. }
  431. const onChangeWithDateFirst = this.getProp('onChangeWithDateFirst');
  432. if (onChangeWithDateFirst) {
  433. this._adapter.notifyChange(_value, str);
  434. } else {
  435. this._adapter.notifyChange(str, _value);
  436. }
  437. }
  438. _hasChanged(dates: TZDate[] = [], oldDates: TZDate[] = []) {
  439. const formatToken = this.getValidFormat();
  440. const dateFnsLocale = this.getProp('dateFnsLocale');
  441. return (
  442. dates.length !== oldDates.length ||
  443. dates.some((date, index) => {
  444. const oldDate = oldDates[index];
  445. if (
  446. isValid(date) &&
  447. isValid(oldDate) &&
  448. formatToString(date, formatToken, dateFnsLocale) === formatToString(oldDate, formatToken, dateFnsLocale)
  449. ) {
  450. return false;
  451. }
  452. return true;
  453. })
  454. );
  455. }
  456. }
  457. export default TimePickerFoundation;