foundation.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /* eslint-disable no-nested-ternary */
  2. /* eslint-disable max-len, max-depth, */
  3. import { format, isValid, isSameSecond, isEqual as isDateEqual, isDate } from 'date-fns';
  4. import { get, isObject, isString, isEqual } from 'lodash-es';
  5. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  6. import { isValidDate, isTimestamp } from './_utils/index';
  7. import isNullOrUndefined from '../utils/isNullOrUndefined';
  8. import { utcToZonedTime, zonedTimeToUtc } from '../utils/date-fns-extra';
  9. import { compatiableParse } from './_utils/parser';
  10. import { getDefaultFormatTokenByType } from './_utils/getDefaultFormatToken';
  11. import { strings } from './constants';
  12. import { strings as inputStrings } from '../input/constants';
  13. import { Type, DateInputFoundationProps } from './inputFoundation';
  14. import { MonthsGridFoundationProps } from './monthsGridFoundation';
  15. import { WeekStartNumber } from './_utils/getMonthTable';
  16. import { ArrayElement, Motion } from '../utils/type';
  17. export type ValidateStatus = ArrayElement<typeof strings.STATUS>;
  18. export type InputSize = ArrayElement<typeof strings.SIZE_SET>;
  19. export type Position = ArrayElement<typeof strings.POSITION_SET>;
  20. export type BaseValueType = string | number | Date;
  21. export type DayStatusType = {
  22. isToday?: boolean; // Current day
  23. isSelected?: boolean; // Selected
  24. isDisabled?: boolean; // Disabled
  25. isSelectedStart?: boolean; // Select Start
  26. isSelectedEnd?: boolean; // End of selection
  27. isInRange?: boolean; // Range within the selected date
  28. isHover?: boolean; // Date between selection and hover date
  29. isOffsetRangeStart?: boolean; // Week selection start
  30. isOffsetRangeEnd?: boolean; // End of week selection
  31. isHoverInOffsetRange?: boolean; // Hover in the week selection
  32. };
  33. export type DisabledDateOptions = {
  34. rangeStart?: string;
  35. rangeEnd?: string;
  36. };
  37. export type PresetType = {
  38. start?: string | Date | number;
  39. end?: string | Date | number;
  40. text?: string;
  41. };
  42. export type TriggerRenderProps = {
  43. [x: string]: any;
  44. value?: ValueType;
  45. inputValue?: string;
  46. placeholder?: string | string[];
  47. autoFocus?: boolean;
  48. size?: InputSize;
  49. disabled?: boolean;
  50. inputReadOnly?: boolean;
  51. componentProps?: DatePickerFoundationProps;
  52. };
  53. export type DateOffsetType = (selectedDate?: Date) => Date;
  54. export type DensityType = 'default' | 'compact';
  55. export type DisabledDateType = (date?: Date, options?: DisabledDateOptions) => boolean;
  56. export type DisabledTimeType = (date?: Date | Date[], panelType?: string) => ({
  57. disabledHours?: () => number[];
  58. disabledMinutes?: (hour: number) => number[];
  59. disabledSeconds?: (hour: number, minute: number) => number[];
  60. });
  61. export type OnCancelType = (date: Date | Date[], dateStr: string | string[]) => void;
  62. export type OnPanelChangeType = (date: Date | Date[], dateStr: string | string[]) => void;
  63. export type OnChangeType = (date?: Date | Date[] | string | string[], dateStr?: string | string[] | Date | Date[]) => void;
  64. export type OnConfirmType = (date: Date | Date[], dateStr: string | string[]) => void;
  65. // type OnPresetClickType = (item: PresetType, e: React.MouseEvent<HTMLDivElement>) => void;
  66. export type OnPresetClickType = (item: PresetType, e: any) => void;
  67. export type PresetsType = Array<PresetType | (() => PresetType)>;
  68. // type RenderDateType = (dayNumber?: number, fullDate?: string) => React.ReactNode;
  69. export type RenderDateType = (dayNumber?: number, fullDate?: string) => any;
  70. // type RenderFullDateType = (dayNumber?: number, fullDate?: string, dayStatus?: DayStatusType) => React.ReactNode;
  71. export type RenderFullDateType = (dayNumber?: number, fullDate?: string, dayStatus?: DayStatusType) => any;
  72. // type TriggerRenderType = (props: TriggerRenderProps) => React.ReactNode;
  73. export type TriggerRenderType = (props: TriggerRenderProps) => any;
  74. export type ValueType = BaseValueType | BaseValueType[];
  75. export interface ElementProps {
  76. bottomSlot?: any;
  77. insetLabel?: any;
  78. prefix?: any;
  79. topSlot?: any;
  80. }
  81. export interface RenderProps {
  82. renderDate?: RenderDateType;
  83. renderFullDate?: RenderFullDateType;
  84. triggerRender?: TriggerRenderType;
  85. }
  86. export interface EventHandlerProps {
  87. onCancel?: OnCancelType;
  88. onChange?: OnChangeType;
  89. onOpenChange?: (status: boolean) => void;
  90. onPanelChange?: OnPanelChangeType;
  91. onConfirm?: OnConfirmType;
  92. // properties below need overwrite
  93. // onBlur?: React.MouseEventHandler<HTMLInputElement>;
  94. onBlur?: (e: any) => void;
  95. // onClear?: React.MouseEventHandler<HTMLDivElement>;
  96. onClear?: (e: any) => void;
  97. // onFocus?: React.MouseEventHandler<HTMLInputElement>;
  98. onFocus?: (e: any, rangType: 'rangeStart' | 'rangeEnd') => void;
  99. onPresetClick?: OnPresetClickType;
  100. }
  101. export interface DatePickerFoundationProps extends ElementProps, RenderProps, EventHandlerProps {
  102. autoAdjustOverflow?: boolean;
  103. autoFocus?: boolean;
  104. autoSwitchDate?: boolean;
  105. className?: string;
  106. defaultOpen?: boolean;
  107. defaultPickerValue?: ValueType;
  108. defaultValue?: ValueType;
  109. density?: DensityType;
  110. disabled?: boolean;
  111. disabledDate?: DisabledDateType;
  112. disabledTime?: DisabledTimeType;
  113. dropdownClassName?: string;
  114. dropdownStyle?: React.CSSProperties;
  115. endDateOffset?: DateOffsetType;
  116. format?: string;
  117. getPopupContainer?: () => HTMLElement;
  118. inputReadOnly?: boolean;
  119. inputStyle?: React.CSSProperties;
  120. max?: number;
  121. motion?: Motion;
  122. multiple?: boolean;
  123. needConfirm?: boolean;
  124. onChangeWithDateFirst?: boolean;
  125. open?: boolean;
  126. placeholder?: string | string[];
  127. position?: Position;
  128. prefixCls?: string;
  129. presets?: PresetsType;
  130. showClear?: boolean;
  131. size?: InputSize;
  132. spacing?: number;
  133. startDateOffset?: DateOffsetType;
  134. stopPropagation?: boolean | string;
  135. style?: React.CSSProperties;
  136. timePickerOpts?: any; // TODO import timePicker props
  137. timeZone?: string | number;
  138. type?: Type;
  139. validateStatus?: ValidateStatus;
  140. value?: ValueType;
  141. weekStartsOn?: WeekStartNumber;
  142. zIndex?: number;
  143. syncSwitchMonth?: boolean;
  144. hideDisabledOptions?: MonthsGridFoundationProps['hideDisabledOptions'];
  145. disabledTimePicker?: MonthsGridFoundationProps['disabledTimePicker'];
  146. locale?: any;
  147. dateFnsLocale?: any;
  148. localeCode?: string;
  149. rangeSeparator?: string;
  150. }
  151. export interface DatePickerFoundationState {
  152. panelShow: boolean;
  153. isRange: boolean;
  154. inputValue: string;
  155. value: ValueType;
  156. cachedSelectedValue: ValueType;
  157. prevTimeZone: string | number;
  158. motionEnd: boolean;
  159. rangeInputFocus: 'rangeStart' | 'rangeEnd' | boolean;
  160. autofocus: boolean;
  161. }
  162. export { Type, DateInputFoundationProps };
  163. export interface DatePickerAdapter extends DefaultAdapter<DatePickerFoundationProps, DatePickerFoundationState> {
  164. togglePanel: (panelShow: boolean) => void;
  165. registerClickOutSide: () => void;
  166. unregisterClickOutSide: () => void;
  167. notifyBlur: DatePickerFoundationProps['onBlur'];
  168. notifyFocus: DatePickerFoundationProps['onFocus'];
  169. notifyClear: DatePickerFoundationProps['onClear'];
  170. notifyChange: DatePickerFoundationProps['onChange'];
  171. notifyCancel: DatePickerFoundationProps['onCancel'];
  172. notifyConfirm: DatePickerFoundationProps['onConfirm'];
  173. notifyOpenChange: DatePickerFoundationProps['onOpenChange'];
  174. notifyPresetsClick: DatePickerFoundationProps['onPresetClick'];
  175. updateValue: (value: ValueType) => void;
  176. updatePrevTimezone: (prevTimeZone: string | number) => void;
  177. updateCachedSelectedValue: (cachedSelectedValue: ValueType) => void;
  178. updateInputValue: (inputValue: string) => void;
  179. needConfirm: () => boolean;
  180. typeIsYearOrMonth: () => boolean;
  181. setMotionEnd: (motionEnd: boolean) => void;
  182. setRangeInputFocus: (rangeInputFocus: DatePickerFoundationState['rangeInputFocus']) => void;
  183. couldPanelClosed: () => boolean;
  184. isEventTarget: (e: any) => boolean;
  185. }
  186. /**
  187. * The datePicker foundation.js is responsible for maintaining the date value and the input box value, as well as the callback of both
  188. * task 1. Accept the selected date change, update the date value, and update the input box value according to the date = > Notify the change
  189. * task 2. When the input box changes, update the date value = > Notify the change
  190. */
  191. export default class DatePickerFoundation extends BaseFoundation<DatePickerAdapter> {
  192. constructor(adapter: DatePickerAdapter) {
  193. super({ ...adapter });
  194. }
  195. init() {
  196. const timeZone = this.getProp('timeZone');
  197. if (this._isControlledComponent()) {
  198. this.initFromProps({ timeZone, value: this.getProp('value') });
  199. } else if (this._isInProps('defaultValue')) {
  200. this.initFromProps({ timeZone, value: this.getProp('defaultValue') });
  201. }
  202. this.initPanelOpenStatus(this.getProp('defaultOpen'));
  203. }
  204. isValidTimeZone(timeZone?: string | number) {
  205. const propTimeZone = this.getProp('timeZone');
  206. const _timeZone = isNullOrUndefined(timeZone) ? propTimeZone : timeZone;
  207. return ['string', 'number'].includes(typeof _timeZone) && _timeZone !== '';
  208. }
  209. initFromProps({ value, timeZone, prevTimeZone }: Pick<DatePickerFoundationProps, 'value' | 'timeZone'> & { prevTimeZone?: string | number }) {
  210. const _value = (Array.isArray(value) ? [...value] : (value || value === 0) && [value]) || [];
  211. const result = this.parseWithTimezone(_value, timeZone, prevTimeZone);
  212. this._adapter.updatePrevTimezone(prevTimeZone);
  213. this._adapter.updateInputValue(null);
  214. this._adapter.updateValue(result);
  215. if (this._adapter.needConfirm()) {
  216. this._adapter.updateCachedSelectedValue(result);
  217. }
  218. }
  219. parseWithTimezone(value: ValueType, timeZone: string | number, prevTimeZone: string | number) {
  220. const result: Date[] = [];
  221. if (Array.isArray(value) && value.length) {
  222. for (const v of value) {
  223. let parsedV = (v || v === 0) && this._parseValue(v);
  224. if (parsedV) {
  225. if (this.isValidTimeZone(prevTimeZone)) {
  226. parsedV = zonedTimeToUtc(parsedV, prevTimeZone as string);
  227. }
  228. result.push(this.isValidTimeZone(timeZone) ? utcToZonedTime(parsedV, timeZone as string) : parsedV);
  229. }
  230. }
  231. }
  232. return result;
  233. }
  234. _isMultiple() {
  235. return Boolean(this.getProp('multiple'));
  236. }
  237. /**
  238. *
  239. * Verify and parse the following three format inputs
  240. *
  241. 1. Date object
  242. 2. ISO 9601-compliant string
  243. 3. ts timestamp
  244. Unified here to format the incoming value and output it as a Date object
  245. *
  246. */
  247. _parseValue(value: BaseValueType): Date {
  248. const dateFnsLocale = this._adapter.getProp('dateFnsLocale');
  249. let dateObj: Date;
  250. if (!value && value !== 0) {
  251. return new Date();
  252. }
  253. if (isValidDate(value)) {
  254. dateObj = value as Date;
  255. } else if (isString(value)) {
  256. dateObj = compatiableParse(value, this.getProp('format'), undefined, dateFnsLocale);
  257. } else if (isTimestamp(value)) {
  258. dateObj = new Date(value);
  259. } else {
  260. throw new TypeError('defaultValue should be valid Date object/timestamp or string');
  261. }
  262. return dateObj;
  263. }
  264. destroy() {
  265. // Ensure that event listeners will be uninstalled and users may not trigger closePanel
  266. // this._adapter.togglePanel(false);
  267. this._adapter.unregisterClickOutSide();
  268. }
  269. initPanelOpenStatus(defaultOpen?: boolean) {
  270. if ((this.getProp('open') || defaultOpen) && !this.getProp('disabled')) {
  271. this._adapter.togglePanel(true);
  272. this._adapter.registerClickOutSide();
  273. } else {
  274. this._adapter.togglePanel(false);
  275. this._adapter.unregisterClickOutSide();
  276. }
  277. }
  278. openPanel() {
  279. if (!this.getProp('disabled')) {
  280. if (!this._isControlledComponent('open')) {
  281. this._adapter.togglePanel(true);
  282. this._adapter.registerClickOutSide();
  283. }
  284. this._adapter.notifyOpenChange(true);
  285. }
  286. }
  287. /**
  288. * do these side effects when type is dateRange or dateTimeRange
  289. * 1. trigger input blur, if input value is invalid, set input value and state value to previous status
  290. * 2. set cachedSelectedValue using given dates(in needConfirm mode)
  291. * - directly closePanel without click confirm will set cachedSelectedValue to state value
  292. * - select one date(which means that the selection value is incomplete) and click confirm also set cachedSelectedValue to state value
  293. * @param {String} inputValue
  294. * @param {Date[]} dates
  295. */
  296. rangeTypeSideEffectsWhenClosePanel(inputValue: string, dates: Date[]) {
  297. if (this._isRangeType()) {
  298. this._adapter.setRangeInputFocus(false);
  299. /**
  300. * inputValue is string when it is not disabled or can't parsed
  301. * when inputValue is null, picker value will back to last selected value
  302. */
  303. this.handleInputBlur(inputValue);
  304. const { value, cachedSelectedValue } = this._adapter.getStates();
  305. const newCachedSelectedValue = Array.isArray(dates) && dates.length ? dates : value;
  306. if (!isEqual(newCachedSelectedValue, cachedSelectedValue)) {
  307. this._adapter.updateCachedSelectedValue(newCachedSelectedValue);
  308. }
  309. }
  310. }
  311. /**
  312. * timing to call closePanel
  313. * 1. click confirm button
  314. * 2. click cancel button
  315. * 3. select date, time, year, month
  316. * - date type and not multiple, close panel after select date
  317. * - dateRange type, close panel after select rangeStart and rangeEnd
  318. * 4. click outside
  319. * @param {Event} e
  320. * @param {String} inputValue
  321. * @param {Date[]} dates
  322. */
  323. closePanel(e?: any, inputValue: string = null, dates: Date[] = []) {
  324. if (!this._isControlledComponent('open')) {
  325. this._adapter.togglePanel(false);
  326. this._adapter.unregisterClickOutSide();
  327. }
  328. // range type picker, closing panel requires the following side effects
  329. this.rangeTypeSideEffectsWhenClosePanel(inputValue, dates);
  330. this._adapter.notifyOpenChange(false);
  331. this._adapter.notifyBlur(e);
  332. }
  333. /**
  334. * Callback when the content of the input box changes
  335. * Update the date panel if the changed value is a legal date, otherwise only update the input box
  336. * @param {String} input The value of the input box after the change
  337. * @param {Event} e
  338. */
  339. handleInputChange(input: string, e: any) {
  340. const result = this._isMultiple() ? this.parseMultipleInput(input) : this.parseInput(input);
  341. const { value: stateValue } = this.getStates();
  342. // Enter a valid date or empty
  343. if ((result && result.length) || input === '') {
  344. // If you click the clear button
  345. if (get(e, inputStrings.CLEARBTN_CLICKED_EVENT_FLAG) && this._isControlledComponent('value')) {
  346. this._notifyChange(result);
  347. return;
  348. }
  349. this._updateValueAndInput(result, input === '', input);
  350. // Updates the selected value when entering a valid date
  351. const changedDates = this._getChangedDates(result);
  352. if (!this._someDateDisabled(changedDates)) {
  353. if (this._adapter.needConfirm()) {
  354. this._adapter.updateCachedSelectedValue(result);
  355. }
  356. if (!isEqual(result, stateValue)) {
  357. this._notifyChange(result);
  358. }
  359. }
  360. } else {
  361. this._adapter.updateInputValue(input);
  362. }
  363. }
  364. /**
  365. * Input box blur
  366. * @param {String} input
  367. * @param {Event} e
  368. */
  369. handleInputBlur(input = '', e?: any) {
  370. const parsedResult = input ?
  371. this._isMultiple() ?
  372. this.parseMultipleInput(input, ',', true) :
  373. this.parseInput(input) :
  374. [];
  375. const stateValue = this.getState('value');
  376. // console.log(input, parsedResult);
  377. if (parsedResult && parsedResult.length) {
  378. this._updateValueAndInput(parsedResult, input === '');
  379. } else if (input === '') {
  380. this._updateValueAndInput('' as any, true);
  381. } else {
  382. this._updateValueAndInput(stateValue);
  383. }
  384. }
  385. /**
  386. * called when range type rangeEnd input tab press
  387. * @param {Event} e
  388. */
  389. handleRangeEndTabPress(e: any) {
  390. this._adapter.setRangeInputFocus(false);
  391. }
  392. /**
  393. * called when the input box is focused
  394. * @param {Event} e input focus event
  395. * @param {String} range 'rangeStart' or 'rangeEnd', use when type is range
  396. */
  397. handleInputFocus(e: any, range: 'rangeStart' | 'rangeEnd') {
  398. const rangeInputFocus = this._adapter.getState('rangeInputFocus');
  399. range && this._adapter.setRangeInputFocus(range);
  400. /**
  401. * rangeType: only notify when range is false
  402. * not rangeType: notify when focus
  403. */
  404. if (!range || !['rangeStart', 'rangeEnd'].includes(rangeInputFocus)) {
  405. this._adapter.notifyFocus(e, range);
  406. }
  407. }
  408. handleSetRangeFocus(rangeInputFocus: boolean | 'rangeStart' | 'rangeEnd') {
  409. this._adapter.setRangeInputFocus(rangeInputFocus);
  410. }
  411. handleInputClear(e: any) {
  412. this._adapter.notifyClear(e);
  413. }
  414. /**
  415. * 范围选择清除按钮回调
  416. * 因为清除按钮没有集成在Input内,因此需要手动清除 value、inputValue、cachedValue
  417. *
  418. * callback of range input clear button
  419. * Since the clear button is not integrated in Input, you need to manually clear value, inputValue, cachedValue
  420. */
  421. handleRangeInputClear(e: any) {
  422. const value: Date[] = [];
  423. const inputValue = '';
  424. if (!this._isControlledComponent('value')) {
  425. this._updateValueAndInput(value, true, inputValue);
  426. if (this._adapter.needConfirm()) {
  427. this._adapter.updateCachedSelectedValue(value);
  428. }
  429. }
  430. this._notifyChange(value);
  431. this._adapter.notifyClear(e);
  432. }
  433. // eslint-disable-next-line @typescript-eslint/no-empty-function
  434. handleRangeInputBlur(value: any, e: any) {
  435. }
  436. // Parses input only after user returns
  437. handleInputComplete(input: any = '') {
  438. // console.log(input);
  439. let parsedResult = input ?
  440. this._isMultiple() ?
  441. this.parseMultipleInput(input, ',', true) :
  442. this.parseInput(input) :
  443. [];
  444. parsedResult = parsedResult && parsedResult.length ? parsedResult : this.getState('value');
  445. // Use the current date as the value when the current input is empty and the last input is also empty
  446. if (!parsedResult || !parsedResult.length) {
  447. const nowDate = new Date();
  448. if (this._isRangeType()) {
  449. parsedResult = [nowDate, nowDate];
  450. } else {
  451. parsedResult = [nowDate];
  452. }
  453. }
  454. this._updateValueAndInput(parsedResult);
  455. const { value: stateValue } = this.getStates();
  456. const changedDates = this._getChangedDates(parsedResult);
  457. if (!this._someDateDisabled(changedDates) && !isEqual(parsedResult, stateValue)) {
  458. this._notifyChange(parsedResult);
  459. }
  460. }
  461. /**
  462. * Parse the input, return the time object if it is valid,
  463. * otherwise return "
  464. *
  465. * @param {string} input
  466. * @returns {Date [] | '}
  467. */
  468. parseInput(input = '') {
  469. let result: Date[] = [];
  470. // console.log(input);
  471. const { dateFnsLocale, rangeSeparator } = this.getProps();
  472. if (input && input.length) {
  473. const type = this.getProp('type');
  474. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  475. let parsedResult,
  476. formatedInput;
  477. const nowDate = new Date();
  478. switch (type) {
  479. case 'date':
  480. case 'dateTime':
  481. case 'month':
  482. parsedResult = input ? compatiableParse(input, formatToken, nowDate, dateFnsLocale) : '';
  483. formatedInput = parsedResult && isValid(parsedResult) && this.localeFormat(parsedResult as Date, formatToken);
  484. if (parsedResult && formatedInput === input) {
  485. result = [parsedResult as Date];
  486. }
  487. break;
  488. case 'dateRange':
  489. case 'dateTimeRange':
  490. const separator = rangeSeparator;
  491. const values = input.split(separator);
  492. parsedResult =
  493. values &&
  494. values.reduce((arr, cur) => {
  495. const parsedVal = cur && compatiableParse(cur, formatToken, nowDate, dateFnsLocale);
  496. parsedVal && arr.push(parsedVal);
  497. return arr;
  498. }, []);
  499. formatedInput =
  500. parsedResult &&
  501. parsedResult.map(v => v && isValid(v) && this.localeFormat(v, formatToken)).join(separator);
  502. if (parsedResult && formatedInput === input) {
  503. parsedResult.sort((d1, d2) => d1.getTime() - d2.getTime());
  504. result = parsedResult;
  505. }
  506. break;
  507. default:
  508. break;
  509. }
  510. }
  511. return result;
  512. }
  513. /**
  514. * Parses the input when multiple is true, if valid,
  515. * returns a list of time objects, otherwise returns an array
  516. *
  517. * @param {string} [input='']
  518. * @param {string} [separator=',']
  519. * @param {boolean} [needDedupe=false]
  520. * @returns {Date[]}
  521. */
  522. parseMultipleInput(input = '', separator: string = strings.DEFAULT_SEPARATOR_MULTIPLE, needDedupe = false) {
  523. const max = this.getProp('max');
  524. const inputArr = input.split(separator);
  525. const result: Date[] = [];
  526. for (const curInput of inputArr) {
  527. let tmpParsed = curInput && this.parseInput(curInput);
  528. tmpParsed = Array.isArray(tmpParsed) ? tmpParsed : tmpParsed && [tmpParsed];
  529. if (tmpParsed && tmpParsed.length) {
  530. if (needDedupe) {
  531. // 20190519 TODO: needs to determine the case where multiple is true and range
  532. !result.filter(r => Boolean(tmpParsed.find(tp => isSameSecond(r, tp)))) && result.push(...tmpParsed);
  533. } else {
  534. result.push(...tmpParsed);
  535. }
  536. } else {
  537. return [];
  538. }
  539. if (max && max > 0 && result.length > max) {
  540. return [];
  541. }
  542. }
  543. return result;
  544. }
  545. /**
  546. * dates[] => string
  547. *
  548. * @param {Date[]} dates
  549. * @returns {string}
  550. */
  551. formatDates(dates: Date[] = []) {
  552. let str = '';
  553. const rangeSeparator = this.getProp('rangeSeparator');
  554. if (Array.isArray(dates) && dates.length) {
  555. const type = this.getProp('type');
  556. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  557. switch (type) {
  558. case 'date':
  559. case 'dateTime':
  560. case 'month':
  561. str = this.localeFormat(dates[0], formatToken);
  562. break;
  563. case 'dateRange':
  564. case 'dateTimeRange':
  565. const startIsTruthy = !isNullOrUndefined(dates[0]);
  566. const endIsTruthy = !isNullOrUndefined(dates[1]);
  567. if (startIsTruthy && endIsTruthy) {
  568. str = `${this.localeFormat(dates[0], formatToken)}${rangeSeparator}${this.localeFormat(dates[1], formatToken)}`;
  569. } else {
  570. if (startIsTruthy) {
  571. str = `${this.localeFormat(dates[0], formatToken)}${rangeSeparator}`;
  572. } else if (endIsTruthy) {
  573. str = `${rangeSeparator}${this.localeFormat(dates[1], formatToken)}`;
  574. }
  575. }
  576. break;
  577. default:
  578. break;
  579. }
  580. }
  581. return str;
  582. }
  583. /**
  584. * dates[] => string
  585. *
  586. * @param {Date[]} dates
  587. * @returns {string}
  588. */
  589. formatMultipleDates(dates: Date[] = [], separator: string = strings.DEFAULT_SEPARATOR_MULTIPLE) {
  590. const strs = [];
  591. if (Array.isArray(dates) && dates.length) {
  592. const type = this.getProp('type');
  593. switch (type) {
  594. case 'date':
  595. case 'dateTime':
  596. case 'month':
  597. dates.forEach(date => strs.push(this.formatDates([date])));
  598. break;
  599. case 'dateRange':
  600. case 'dateTimeRange':
  601. for (let i = 0; i < dates.length; i += 2) {
  602. strs.push(this.formatDates(dates.slice(i, i + 2)));
  603. }
  604. break;
  605. default:
  606. break;
  607. }
  608. }
  609. return strs.join(separator);
  610. }
  611. /**
  612. * Update date value and the value of the input box
  613. * 1. Select Update
  614. * 2. Input Update
  615. * @param {Date|''} value
  616. * @param {Boolean} forceUpdateValue
  617. * @param {String} input
  618. */
  619. _updateValueAndInput(value: Date | Array<Date>, forceUpdateValue?: boolean, input?: string) {
  620. let _value: Array<Date>;
  621. if (forceUpdateValue || value) {
  622. if (!Array.isArray(value)) {
  623. _value = value ? [value] : [];
  624. } else {
  625. _value = value;
  626. }
  627. const changedDates = this._getChangedDates(_value);
  628. // You cannot update the value directly when needConfirm, you can only change the value through handleConfirm
  629. if (!this._isControlledComponent() && !this._someDateDisabled(changedDates) && !this._adapter.needConfirm()) {
  630. this._adapter.updateValue(_value);
  631. }
  632. }
  633. this._adapter.updateInputValue(input);
  634. }
  635. /**
  636. * when changing the selected value through the date panel
  637. * @param {*} value
  638. * @param {*} options
  639. */
  640. handleSelectedChange(value: Date[], options?: { fromPreset?: boolean; needCheckFocusRecord?: boolean }) {
  641. const type = this.getProp('type');
  642. const { value: stateValue } = this.getStates();
  643. const controlled = this._isControlledComponent();
  644. const fromPreset = isObject(options) ? options.fromPreset : options;
  645. const closePanel = get(options, 'closePanel', true);
  646. /**
  647. * It is used to determine whether the panel can be stowed. In a Range type component, it is necessary to select both starting Time and endTime before stowing.
  648. * To determine whether both starting Time and endTime have been selected, it is used to judge whether the two inputs have been Focused.
  649. * This variable is used to indicate whether such a judgment is required. In the scene with shortcut operations, it is not required.
  650. */
  651. const needCheckFocusRecord = get(options, 'needCheckFocusRecord', true);
  652. if (this._adapter.needConfirm()) {
  653. this._adapter.updateCachedSelectedValue(value);
  654. }
  655. const dates = Array.isArray(value) ? [...value] : value ? [value] : [];
  656. const changedDates = this._getChangedDates(dates);
  657. let inputValue;
  658. if (!this._someDateDisabled(changedDates)) {
  659. inputValue = this._isMultiple() ? this.formatMultipleDates(dates) : this.formatDates(dates);
  660. const isRangeTypeAndInputIncomplete = this._isRangeType() && (isNullOrUndefined(dates[0]) || isNullOrUndefined(dates[1]));
  661. /**
  662. * If the input is incomplete when under control, the notifyChange is not triggered because
  663. * You need to update the value of the input box, otherwise there will be a problem that a date is selected but the input box does not show the date #1357
  664. *
  665. * 受控时如果输入不完整,由于没有触发 notifyChange
  666. * 需要组件内更新一下输入框的值,否则会出现选了一个日期但是输入框没有回显日期的问题 #1357
  667. */
  668. if (!this._adapter.needConfirm() || fromPreset) {
  669. if (isRangeTypeAndInputIncomplete) {
  670. // do not change value when selected value is incomplete
  671. this._adapter.updateInputValue(inputValue);
  672. return;
  673. } else {
  674. (!controlled || fromPreset) && this._updateValueAndInput(dates, true, inputValue);
  675. }
  676. }
  677. if (!controlled && this._adapter.needConfirm()) {
  678. // select date only change inputValue when needConfirm is true
  679. this._adapter.updateInputValue(inputValue);
  680. // if inputValue is not complete, don't notifyChange
  681. if (isRangeTypeAndInputIncomplete) {
  682. return;
  683. }
  684. }
  685. if (!isEqual(value, stateValue)) {
  686. this._notifyChange(value);
  687. }
  688. }
  689. const focusRecordChecked = !needCheckFocusRecord || (needCheckFocusRecord && this._adapter.couldPanelClosed());
  690. if ((type === 'date' && !this._isMultiple() && closePanel) || (type === 'dateRange' && this._isRangeValueComplete(dates) && closePanel && focusRecordChecked)) {
  691. this.closePanel(undefined, inputValue, dates);
  692. }
  693. }
  694. /**
  695. * when changing the year and month through the panel when the type is year or month
  696. * @param {*} item
  697. */
  698. handleYMSelectedChange(item: { currentMonth?: number; currentYear?: number } = {}) {
  699. // console.log(item);
  700. const { currentMonth, currentYear } = item;
  701. if (typeof currentMonth === 'number' && typeof currentYear === 'number') {
  702. // Strings with only dates (e.g. "1970-01-01") will be treated as UTC instead of local time #1460
  703. const date = new Date(currentYear, currentMonth - 1);
  704. this.handleSelectedChange([date]);
  705. }
  706. }
  707. handleConfirm() {
  708. const { cachedSelectedValue, value } = this.getStates();
  709. const isRangeValueComplete = this._isRangeValueComplete(cachedSelectedValue);
  710. const newValue = isRangeValueComplete ? cachedSelectedValue : value;
  711. if (this._adapter.needConfirm() && !this._isControlledComponent()) {
  712. this._adapter.updateValue(newValue);
  713. }
  714. // If the input is incomplete, the legal date of the last input is used
  715. this.closePanel(undefined, undefined, newValue);
  716. if (isRangeValueComplete) {
  717. const { notifyValue, notifyDate } = this.disposeCallbackArgs(cachedSelectedValue);
  718. this._adapter.notifyConfirm(notifyDate, notifyValue);
  719. }
  720. }
  721. handleCancel() {
  722. this.closePanel();
  723. const value = this.getState('value');
  724. const { notifyValue, notifyDate } = this.disposeCallbackArgs(value);
  725. this._adapter.notifyCancel(notifyDate, notifyValue);
  726. }
  727. handlePresetClick(item: PresetType, e: any) {
  728. const { type, timeZone } = this.getProps();
  729. const prevTimeZone = this.getState('prevTimezone');
  730. let value;
  731. switch (type) {
  732. case 'month':
  733. case 'dateTime':
  734. case 'date':
  735. value = this.parseWithTimezone([item.start], timeZone, prevTimeZone);
  736. this.handleSelectedChange(value);
  737. break;
  738. case 'dateTimeRange':
  739. case 'dateRange':
  740. value = this.parseWithTimezone([item.start, item.end], timeZone, prevTimeZone);
  741. this.handleSelectedChange(value, { needCheckFocusRecord: false });
  742. break;
  743. default:
  744. break;
  745. }
  746. this._adapter.notifyPresetsClick(item, e);
  747. }
  748. /**
  749. * 根据 type 处理 onChange 返回的参数
  750. *
  751. * - 返回的日期需要把用户时间转换为设置的时区时间
  752. * - 用户时间:用户计算机系统时间
  753. * - 时区时间:通过 ConfigProvider 设置的 timeZone
  754. * - 例子:用户设置时区为+9,计算机所在时区为+8区,然后用户选择了22:00
  755. * - DatePicker 内部保存日期 state 为 +8 的 22:00 => a = new Date("2021-05-25 22:00:00")
  756. * - 传出去时,需要把 +8 的 22:00 => +9 的 22:00 => b = zonedTimeToUtc(a, "+09:00");
  757. *
  758. * According to the type processing onChange returned parameters
  759. *
  760. * - the returned date needs to convert the user time to the set time zone time
  761. * - user time: user computer system time
  762. * - time zone time: timeZone set by ConfigProvider
  763. * - example: the user sets the time zone to + 9, the computer's time zone is + 8 zone, and then the user selects 22:00
  764. * - DatePicker internal save date state is + 8 22:00 = > a = new Date ("2021-05-25 22:00:00")
  765. * - when passed out, you need to + 8 22:00 = > + 9 22:00 = > b = zonedTimeToUtc (a, "+ 09:00");
  766. *
  767. * e.g.
  768. * let a = new Date ("2021-05-25 22:00:00");
  769. * = > Tue May 25 2021 22:00:00 GMT + 0800 (China Standard Time)
  770. * let b = zonedTimeToUtc (a, "+ 09:00");
  771. * = > Tue May 25 2021 21:00:00 GMT + 0800 (China Standard Time)
  772. *
  773. * @param {Date|Date[]} value
  774. * @return {{ notifyDate: Date|Date[], notifyValue: string|string[]}}
  775. */
  776. disposeCallbackArgs(value: Date | Date[]) {
  777. let _value = Array.isArray(value) ? value : (value && [value]) || [];
  778. if (this.isValidTimeZone()) {
  779. const timeZone = this.getProp('timeZone');
  780. _value = _value.map(date => zonedTimeToUtc(date, timeZone));
  781. }
  782. const type = this.getProp('type');
  783. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  784. let notifyValue,
  785. notifyDate;
  786. switch (type) {
  787. case 'date':
  788. case 'dateTime':
  789. case 'month':
  790. if (!this._isMultiple()) {
  791. notifyValue = _value[0] && this.localeFormat(_value[0], formatToken);
  792. [notifyDate] = _value;
  793. } else {
  794. notifyValue = _value.map(v => v && this.localeFormat(v, formatToken));
  795. notifyDate = [..._value];
  796. }
  797. break;
  798. case 'dateRange':
  799. case 'dateTimeRange':
  800. notifyValue = _value.map(v => v && this.localeFormat(v, formatToken));
  801. notifyDate = [..._value];
  802. break;
  803. default:
  804. break;
  805. }
  806. return {
  807. notifyValue,
  808. notifyDate,
  809. };
  810. }
  811. /**
  812. * Notice: Check whether the date is the same as the state value before calling
  813. * @param {Date[]} value
  814. */
  815. _notifyChange(value: Date[]) {
  816. if (this._isRangeType() && !this._isRangeValueComplete(value)) {
  817. return;
  818. }
  819. const { onChangeWithDateFirst } = this.getProps();
  820. const { notifyValue, notifyDate } = this.disposeCallbackArgs(value);
  821. if (onChangeWithDateFirst) {
  822. this._adapter.notifyChange(notifyDate, notifyValue);
  823. } else {
  824. this._adapter.notifyChange(notifyValue, notifyDate);
  825. }
  826. }
  827. /**
  828. * Get the date changed through the date panel or enter
  829. * @param {Date[]} dates
  830. * @returns {Date[]}
  831. */
  832. _getChangedDates(dates: Date[]) {
  833. const type = this._adapter.getProp('type');
  834. const stateValue: Date[] = this._adapter.getState('value');
  835. const changedDates = [];
  836. switch (type) {
  837. case 'dateRange':
  838. case 'dateTimeRange':
  839. const [stateStart, stateEnd] = stateValue;
  840. const [start, end] = dates;
  841. if (!isDateEqual(start, stateStart)) {
  842. changedDates.push(start);
  843. }
  844. if (!isDateEqual(end, stateEnd)) {
  845. changedDates.push(end);
  846. }
  847. break;
  848. default:
  849. const stateValueSet = new Set<number>();
  850. stateValue.forEach(value => stateValueSet.add(isDate(value) && value.valueOf()));
  851. for (const date of dates) {
  852. if (!stateValueSet.has(isDate(date) && date.valueOf())) {
  853. changedDates.push(date);
  854. }
  855. }
  856. }
  857. return changedDates;
  858. }
  859. /**
  860. * Whether a date is disabled
  861. * @param {Array} value
  862. */
  863. _someDateDisabled(value: Date[]) {
  864. const stateValue = this.getState('value');
  865. const disabledOptions = { rangeStart: '', rangeEnd: '' };
  866. // DisabledDate needs to pass the second parameter
  867. if (this._isRangeType() && Array.isArray(stateValue)) {
  868. if (isValid(stateValue[0])) {
  869. const rangeStart = format(stateValue[0], 'yyyy-MM-dd');
  870. disabledOptions.rangeStart = rangeStart;
  871. }
  872. if (isValid(stateValue[1])) {
  873. const rangeEnd = format(stateValue[1], 'yyyy-MM-dd');
  874. disabledOptions.rangeEnd = rangeEnd;
  875. }
  876. }
  877. let isSomeDateDisabled = false;
  878. for (const date of value) {
  879. // skip check if date is null
  880. if (!isNullOrUndefined(date) && this.disabledDisposeDate(date, disabledOptions)) {
  881. isSomeDateDisabled = true;
  882. break;
  883. }
  884. }
  885. return isSomeDateDisabled;
  886. }
  887. getMergedMotion = (motion: any) => {
  888. const mergedMotion = typeof motion === 'undefined' || motion ? {
  889. ...motion,
  890. didEnter: () => {
  891. this._adapter.setMotionEnd(true);
  892. },
  893. didLeave: () => {
  894. this._adapter.setMotionEnd(false);
  895. }
  896. } : false;
  897. return mergedMotion;
  898. };
  899. /**
  900. * Format locale date
  901. * locale get from LocaleProvider
  902. * @param {Date} date
  903. * @param {String} token
  904. */
  905. localeFormat(date: Date, token: string) {
  906. const dateFnsLocale = this._adapter.getProp('dateFnsLocale');
  907. return format(date, token, { locale: dateFnsLocale });
  908. }
  909. _isRangeType = () => {
  910. const type = this._adapter.getProp('type');
  911. return /range/i.test(type);
  912. };
  913. _isRangeValueComplete = (value: Date[] | Date) => {
  914. let result = true;
  915. if (Array.isArray(value)) {
  916. result = !value.some(date => isNullOrUndefined(date));
  917. } else {
  918. result = false;
  919. }
  920. return result;
  921. };
  922. /**
  923. * Convert computer date to UTC date
  924. * Before passing the date to the user, you need to convert the date to UTC time
  925. * dispose date from computer date to utc date
  926. * When given timeZone prop, you should convert computer date to utc date before passing to user
  927. * @param {(date: Date) => Boolean} fn
  928. * @param {Date|Date[]} date
  929. * @returns {Boolean}
  930. */
  931. disposeDateFn(fn: (date: Date, ...rest: any) => boolean, date: Date | Date[], ...rest: any[]) {
  932. const { notifyDate } = this.disposeCallbackArgs(date);
  933. const dateIsArray = Array.isArray(date);
  934. const notifyDateIsArray = Array.isArray(notifyDate);
  935. let disposeDate;
  936. if (dateIsArray === notifyDateIsArray) {
  937. disposeDate = notifyDate;
  938. } else {
  939. disposeDate = dateIsArray ? [notifyDate] : notifyDate[0];
  940. }
  941. return fn(disposeDate, ...rest);
  942. }
  943. /**
  944. * Determine whether the date is disabled
  945. * Whether the date is disabled
  946. * @param {Date} date
  947. * @returns {Boolean}
  948. */
  949. disabledDisposeDate(date: Date, ...rest: any[]) {
  950. const { disabledDate } = this.getProps();
  951. return this.disposeDateFn(disabledDate, date, ...rest);
  952. }
  953. /**
  954. * Determine whether the date is disabled
  955. * Whether the date time is disabled
  956. * @param {Date|Date[]} date
  957. * @returns {Object}
  958. */
  959. disabledDisposeTime(date: Date | Date[], ...rest: any[]) {
  960. const { disabledTime } = this.getProps();
  961. return this.disposeDateFn(disabledTime, date, ...rest);
  962. }
  963. /**
  964. * Trigger wrapper needs to do two things:
  965. * 1. Open Panel when clicking trigger;
  966. * 2. When clicking on a child but the child does not listen to the focus event, manually trigger focus
  967. *
  968. * @param {Event} e
  969. * @returns
  970. */
  971. handleTriggerWrapperClick(e: any) {
  972. const { disabled } = this._adapter.getProps();
  973. const { rangeInputFocus } = this._adapter.getStates();
  974. if (disabled) {
  975. return;
  976. }
  977. /**
  978. * - 非范围选择时,trigger 为原生输入框,已在组件内处理了 focus 逻辑
  979. * - isEventTarget 函数用于判断触发事件的是否为 input wrapper。如果是冒泡上来的不用处理,因为在子级已经处理了 focus 逻辑。
  980. *
  981. * - When type is not range type, Input component will automatically focus in the same case
  982. * - isEventTarget is used to judge whether the event is a bubbling event
  983. */
  984. if (this._isRangeType() && !rangeInputFocus && this._adapter.isEventTarget(e)) {
  985. setTimeout(() => {
  986. // using setTimeout get correct state value 'rangeInputFocus'
  987. this.handleInputFocus(e, 'rangeStart');
  988. this.openPanel();
  989. }, 0);
  990. } else {
  991. this.openPanel();
  992. }
  993. }
  994. }