foundation.ts 17 KB

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