foundation.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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';
  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 as string, 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. */
  294. rangeTypeSideEffectsWhenClosePanel(inputValue: string, willUpdateDates: Date[]) {
  295. if (this._isRangeType()) {
  296. this._adapter.setRangeInputFocus(false);
  297. /**
  298. * inputValue is string when it is not disabled or can't parsed
  299. * when inputValue is null, picker value will back to last selected value
  300. */
  301. this.handleInputBlur(inputValue);
  302. this.resetCachedSelectedValue(willUpdateDates);
  303. }
  304. }
  305. /**
  306. * clear input value when selected date is not confirmed
  307. */
  308. needConfirmSideEffectsWhenClosePanel(willUpdateDates: Date[] | null | undefined) {
  309. if (this._adapter.needConfirm() && !this._isRangeType()) {
  310. /**
  311. * if `null` input element will show `cachedSelectedValue` formatted value(format in DateInput render)
  312. * if `` input element will show `` directly
  313. */
  314. this._adapter.updateInputValue(null);
  315. this.resetCachedSelectedValue(willUpdateDates);
  316. }
  317. }
  318. resetCachedSelectedValue(willUpdateDates?: Date[]) {
  319. const { value, cachedSelectedValue } = this._adapter.getStates();
  320. const newCachedSelectedValue = Array.isArray(willUpdateDates) ? willUpdateDates : value;
  321. if (!isEqual(newCachedSelectedValue, cachedSelectedValue)) {
  322. this._adapter.updateCachedSelectedValue(newCachedSelectedValue);
  323. }
  324. }
  325. /**
  326. * timing to call closePanel
  327. * 1. click confirm button
  328. * 2. click cancel button
  329. * 3. select date, time, year, month
  330. * - date type and not multiple, close panel after select date
  331. * - dateRange type, close panel after select rangeStart and rangeEnd
  332. * 4. click outside
  333. * @param {Event} e
  334. * @param {String} inputValue
  335. * @param {Date[]} dates
  336. */
  337. closePanel(e?: any, inputValue: string = null, dates?: Date[]) {
  338. const { value, cachedSelectedValue } = this._adapter.getStates();
  339. const willUpdateDates = isNullOrUndefined(dates) ? this._adapter.needConfirm() ? value : cachedSelectedValue : dates;
  340. if (!this._isControlledComponent('open')) {
  341. this._adapter.togglePanel(false);
  342. this._adapter.unregisterClickOutSide();
  343. }
  344. // range type picker, closing panel requires the following side effects
  345. this.rangeTypeSideEffectsWhenClosePanel(inputValue, willUpdateDates as Date[]);
  346. this.needConfirmSideEffectsWhenClosePanel(willUpdateDates as Date[]);
  347. this._adapter.notifyOpenChange(false);
  348. this._adapter.notifyBlur(e);
  349. }
  350. /**
  351. * Callback when the content of the input box changes
  352. * Update the date panel if the changed value is a legal date, otherwise only update the input box
  353. * @param {String} input The value of the input box after the change
  354. * @param {Event} e
  355. */
  356. handleInputChange(input: string, e: any) {
  357. const result = this._isMultiple() ? this.parseMultipleInput(input) : this.parseInput(input);
  358. const { value: stateValue } = this.getStates();
  359. // Enter a valid date or empty
  360. if ((result && result.length) || input === '') {
  361. // If you click the clear button
  362. if (get(e, inputStrings.CLEARBTN_CLICKED_EVENT_FLAG) && this._isControlledComponent('value')) {
  363. this._notifyChange(result);
  364. return;
  365. }
  366. this._updateValueAndInput(result, input === '', input);
  367. // Updates the selected value when entering a valid date
  368. const changedDates = this._getChangedDates(result);
  369. if (!this._someDateDisabled(changedDates)) {
  370. if (this._adapter.needConfirm()) {
  371. this._adapter.updateCachedSelectedValue(result);
  372. }
  373. if (!isEqual(result, stateValue)) {
  374. this._notifyChange(result);
  375. }
  376. }
  377. } else {
  378. this._adapter.updateInputValue(input);
  379. }
  380. }
  381. /**
  382. * Input box blur
  383. * @param {String} input
  384. * @param {Event} e
  385. */
  386. handleInputBlur(input = '', e?: any) {
  387. const parsedResult = input ?
  388. this._isMultiple() ?
  389. this.parseMultipleInput(input, ',', true) :
  390. this.parseInput(input) :
  391. [];
  392. const stateValue = this.getState('value');
  393. // console.log(input, parsedResult);
  394. if (parsedResult && parsedResult.length) {
  395. this._updateValueAndInput(parsedResult, input === '');
  396. } else if (input === '') {
  397. // if clear input, set input to `''`
  398. this._updateValueAndInput('' as any, true, '');
  399. } else {
  400. this._updateValueAndInput(stateValue);
  401. }
  402. }
  403. /**
  404. * called when range type rangeEnd input tab press
  405. * @param {Event} e
  406. */
  407. handleRangeEndTabPress(e: any) {
  408. this._adapter.setRangeInputFocus(false);
  409. }
  410. /**
  411. * called when the input box is focused
  412. * @param {Event} e input focus event
  413. * @param {String} range 'rangeStart' or 'rangeEnd', use when type is range
  414. */
  415. handleInputFocus(e: any, range: 'rangeStart' | 'rangeEnd') {
  416. const rangeInputFocus = this._adapter.getState('rangeInputFocus');
  417. range && this._adapter.setRangeInputFocus(range);
  418. /**
  419. * rangeType: only notify when range is false
  420. * not rangeType: notify when focus
  421. */
  422. if (!range || !['rangeStart', 'rangeEnd'].includes(rangeInputFocus)) {
  423. this._adapter.notifyFocus(e, range);
  424. }
  425. }
  426. handleSetRangeFocus(rangeInputFocus: boolean | 'rangeStart' | 'rangeEnd') {
  427. this._adapter.setRangeInputFocus(rangeInputFocus);
  428. }
  429. handleInputClear(e: any) {
  430. this._adapter.notifyClear(e);
  431. }
  432. /**
  433. * 范围选择清除按钮回调
  434. * 因为清除按钮没有集成在Input内,因此需要手动清除 value、inputValue、cachedValue
  435. *
  436. * callback of range input clear button
  437. * Since the clear button is not integrated in Input, you need to manually clear value, inputValue, cachedValue
  438. */
  439. handleRangeInputClear(e: any) {
  440. const value: Date[] = [];
  441. const inputValue = '';
  442. if (!this._isControlledComponent('value')) {
  443. this._updateValueAndInput(value, true, inputValue);
  444. if (this._adapter.needConfirm()) {
  445. this._adapter.updateCachedSelectedValue(value);
  446. }
  447. }
  448. this._notifyChange(value);
  449. this._adapter.notifyClear(e);
  450. }
  451. // eslint-disable-next-line @typescript-eslint/no-empty-function
  452. handleRangeInputBlur(value: any, e: any) {
  453. }
  454. // Parses input only after user returns
  455. handleInputComplete(input: any = '') {
  456. // console.log(input);
  457. let parsedResult = input ?
  458. this._isMultiple() ?
  459. this.parseMultipleInput(input, ',', true) :
  460. this.parseInput(input) :
  461. [];
  462. parsedResult = parsedResult && parsedResult.length ? parsedResult : this.getState('value');
  463. // Use the current date as the value when the current input is empty and the last input is also empty
  464. if (!parsedResult || !parsedResult.length) {
  465. const nowDate = new Date();
  466. if (this._isRangeType()) {
  467. parsedResult = [nowDate, nowDate];
  468. } else {
  469. parsedResult = [nowDate];
  470. }
  471. }
  472. this._updateValueAndInput(parsedResult);
  473. const { value: stateValue } = this.getStates();
  474. const changedDates = this._getChangedDates(parsedResult);
  475. if (!this._someDateDisabled(changedDates) && !isEqual(parsedResult, stateValue)) {
  476. this._notifyChange(parsedResult);
  477. }
  478. }
  479. /**
  480. * Parse the input, return the time object if it is valid,
  481. * otherwise return "
  482. *
  483. * @param {string} input
  484. * @returns {Date [] | '}
  485. */
  486. parseInput(input = '') {
  487. let result: Date[] = [];
  488. // console.log(input);
  489. const { dateFnsLocale, rangeSeparator } = this.getProps();
  490. if (input && input.length) {
  491. const type = this.getProp('type');
  492. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  493. let parsedResult,
  494. formatedInput;
  495. const nowDate = new Date();
  496. switch (type) {
  497. case 'date':
  498. case 'dateTime':
  499. case 'month':
  500. parsedResult = input ? compatiableParse(input, formatToken, nowDate, dateFnsLocale) : '';
  501. formatedInput = parsedResult && isValid(parsedResult) && this.localeFormat(parsedResult as Date, formatToken);
  502. if (parsedResult && formatedInput === input) {
  503. result = [parsedResult as Date];
  504. }
  505. break;
  506. case 'dateRange':
  507. case 'dateTimeRange':
  508. const separator = rangeSeparator;
  509. const values = input.split(separator);
  510. parsedResult =
  511. values &&
  512. values.reduce((arr, cur) => {
  513. const parsedVal = cur && compatiableParse(cur, formatToken, nowDate, dateFnsLocale);
  514. parsedVal && arr.push(parsedVal);
  515. return arr;
  516. }, []);
  517. formatedInput =
  518. parsedResult &&
  519. parsedResult.map(v => v && isValid(v) && this.localeFormat(v, formatToken)).join(separator);
  520. if (parsedResult && formatedInput === input) {
  521. parsedResult.sort((d1, d2) => d1.getTime() - d2.getTime());
  522. result = parsedResult;
  523. }
  524. break;
  525. default:
  526. break;
  527. }
  528. }
  529. return result;
  530. }
  531. /**
  532. * Parses the input when multiple is true, if valid,
  533. * returns a list of time objects, otherwise returns an array
  534. *
  535. * @param {string} [input='']
  536. * @param {string} [separator=',']
  537. * @param {boolean} [needDedupe=false]
  538. * @returns {Date[]}
  539. */
  540. parseMultipleInput(input = '', separator: string = strings.DEFAULT_SEPARATOR_MULTIPLE, needDedupe = false) {
  541. const max = this.getProp('max');
  542. const inputArr = input.split(separator);
  543. const result: Date[] = [];
  544. for (const curInput of inputArr) {
  545. let tmpParsed = curInput && this.parseInput(curInput);
  546. tmpParsed = Array.isArray(tmpParsed) ? tmpParsed : tmpParsed && [tmpParsed];
  547. if (tmpParsed && tmpParsed.length) {
  548. if (needDedupe) {
  549. // 20190519 TODO: needs to determine the case where multiple is true and range
  550. !result.filter(r => Boolean(tmpParsed.find(tp => isSameSecond(r, tp)))) && result.push(...tmpParsed);
  551. } else {
  552. result.push(...tmpParsed);
  553. }
  554. } else {
  555. return [];
  556. }
  557. if (max && max > 0 && result.length > max) {
  558. return [];
  559. }
  560. }
  561. return result;
  562. }
  563. /**
  564. * dates[] => string
  565. *
  566. * @param {Date[]} dates
  567. * @returns {string}
  568. */
  569. formatDates(dates: Date[] = []) {
  570. let str = '';
  571. const rangeSeparator = this.getProp('rangeSeparator');
  572. if (Array.isArray(dates) && dates.length) {
  573. const type = this.getProp('type');
  574. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  575. switch (type) {
  576. case 'date':
  577. case 'dateTime':
  578. case 'month':
  579. str = this.localeFormat(dates[0], formatToken);
  580. break;
  581. case 'dateRange':
  582. case 'dateTimeRange':
  583. const startIsTruthy = !isNullOrUndefined(dates[0]);
  584. const endIsTruthy = !isNullOrUndefined(dates[1]);
  585. if (startIsTruthy && endIsTruthy) {
  586. str = `${this.localeFormat(dates[0], formatToken)}${rangeSeparator}${this.localeFormat(dates[1], formatToken)}`;
  587. } else {
  588. if (startIsTruthy) {
  589. str = `${this.localeFormat(dates[0], formatToken)}${rangeSeparator}`;
  590. } else if (endIsTruthy) {
  591. str = `${rangeSeparator}${this.localeFormat(dates[1], formatToken)}`;
  592. }
  593. }
  594. break;
  595. default:
  596. break;
  597. }
  598. }
  599. return str;
  600. }
  601. /**
  602. * dates[] => string
  603. *
  604. * @param {Date[]} dates
  605. * @returns {string}
  606. */
  607. formatMultipleDates(dates: Date[] = [], separator: string = strings.DEFAULT_SEPARATOR_MULTIPLE) {
  608. const strs = [];
  609. if (Array.isArray(dates) && dates.length) {
  610. const type = this.getProp('type');
  611. switch (type) {
  612. case 'date':
  613. case 'dateTime':
  614. case 'month':
  615. dates.forEach(date => strs.push(this.formatDates([date])));
  616. break;
  617. case 'dateRange':
  618. case 'dateTimeRange':
  619. for (let i = 0; i < dates.length; i += 2) {
  620. strs.push(this.formatDates(dates.slice(i, i + 2)));
  621. }
  622. break;
  623. default:
  624. break;
  625. }
  626. }
  627. return strs.join(separator);
  628. }
  629. /**
  630. * Update date value and the value of the input box
  631. * 1. Select Update
  632. * 2. Input Update
  633. * @param {Date|''} value
  634. * @param {Boolean} forceUpdateValue
  635. * @param {String} input
  636. */
  637. _updateValueAndInput(value: Date | Array<Date>, forceUpdateValue?: boolean, input?: string) {
  638. let _value: Array<Date>;
  639. if (forceUpdateValue || value) {
  640. if (!Array.isArray(value)) {
  641. _value = value ? [value] : [];
  642. } else {
  643. _value = value;
  644. }
  645. const changedDates = this._getChangedDates(_value);
  646. // You cannot update the value directly when needConfirm, you can only change the value through handleConfirm
  647. if (!this._isControlledComponent() && !this._someDateDisabled(changedDates) && !this._adapter.needConfirm()) {
  648. this._adapter.updateValue(_value);
  649. }
  650. }
  651. this._adapter.updateInputValue(input);
  652. }
  653. /**
  654. * when changing the selected value through the date panel
  655. * @param {*} value
  656. * @param {*} options
  657. */
  658. handleSelectedChange(value: Date[], options?: { fromPreset?: boolean; needCheckFocusRecord?: boolean }) {
  659. const type = this.getProp('type');
  660. const { value: stateValue } = this.getStates();
  661. const controlled = this._isControlledComponent();
  662. const fromPreset = isObject(options) ? options.fromPreset : options;
  663. const closePanel = get(options, 'closePanel', true);
  664. /**
  665. * 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.
  666. * To determine whether both starting Time and endTime have been selected, it is used to judge whether the two inputs have been Focused.
  667. * This variable is used to indicate whether such a judgment is required. In the scene with shortcut operations, it is not required.
  668. */
  669. const needCheckFocusRecord = get(options, 'needCheckFocusRecord', true);
  670. if (this._adapter.needConfirm()) {
  671. this._adapter.updateCachedSelectedValue(value);
  672. }
  673. const dates = Array.isArray(value) ? [...value] : value ? [value] : [];
  674. const changedDates = this._getChangedDates(dates);
  675. let inputValue;
  676. if (!this._someDateDisabled(changedDates)) {
  677. inputValue = this._isMultiple() ? this.formatMultipleDates(dates) : this.formatDates(dates);
  678. const isRangeTypeAndInputIncomplete = this._isRangeType() && !this._isRangeValueComplete(dates);
  679. /**
  680. * If the input is incomplete when under control, the notifyChange is not triggered because
  681. * 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
  682. *
  683. * 受控时如果输入不完整,由于没有触发 notifyChange
  684. * 需要组件内更新一下输入框的值,否则会出现选了一个日期但是输入框没有回显日期的问题 #1357
  685. */
  686. if (!this._adapter.needConfirm() || fromPreset) {
  687. if (isRangeTypeAndInputIncomplete) {
  688. // do not change value when selected value is incomplete
  689. this._adapter.updateInputValue(inputValue);
  690. return;
  691. } else {
  692. (!controlled || fromPreset) && this._updateValueAndInput(dates, true, inputValue);
  693. }
  694. }
  695. if (!controlled && this._adapter.needConfirm()) {
  696. // select date only change inputValue when needConfirm is true
  697. this._adapter.updateInputValue(inputValue);
  698. // if inputValue is not complete, don't notifyChange
  699. if (isRangeTypeAndInputIncomplete) {
  700. return;
  701. }
  702. }
  703. if (!isEqual(value, stateValue)) {
  704. this._notifyChange(value);
  705. }
  706. }
  707. const focusRecordChecked = !needCheckFocusRecord || (needCheckFocusRecord && this._adapter.couldPanelClosed());
  708. if ((type === 'date' && !this._isMultiple() && closePanel) || (type === 'dateRange' && this._isRangeValueComplete(dates) && closePanel && focusRecordChecked)) {
  709. this.closePanel(undefined, inputValue, dates);
  710. }
  711. }
  712. /**
  713. * when changing the year and month through the panel when the type is year or month
  714. * @param {*} item
  715. */
  716. handleYMSelectedChange(item: { currentMonth?: number; currentYear?: number } = {}) {
  717. // console.log(item);
  718. const { currentMonth, currentYear } = item;
  719. if (typeof currentMonth === 'number' && typeof currentYear === 'number') {
  720. // Strings with only dates (e.g. "1970-01-01") will be treated as UTC instead of local time #1460
  721. const date = new Date(currentYear, currentMonth - 1);
  722. this.handleSelectedChange([date]);
  723. }
  724. }
  725. handleConfirm() {
  726. const { cachedSelectedValue, value } = this.getStates();
  727. const isRangeValueComplete = this._isRangeValueComplete(cachedSelectedValue);
  728. const newValue = isRangeValueComplete ? cachedSelectedValue : value;
  729. if (this._adapter.needConfirm() && !this._isControlledComponent()) {
  730. this._adapter.updateValue(newValue);
  731. }
  732. // If the input is incomplete, the legal date of the last input is used
  733. this.closePanel(undefined, undefined, newValue);
  734. if (isRangeValueComplete) {
  735. const { notifyValue, notifyDate } = this.disposeCallbackArgs(cachedSelectedValue);
  736. this._adapter.notifyConfirm(notifyDate, notifyValue);
  737. }
  738. }
  739. handleCancel() {
  740. this.closePanel();
  741. const value = this.getState('value');
  742. const { notifyValue, notifyDate } = this.disposeCallbackArgs(value);
  743. this._adapter.notifyCancel(notifyDate, notifyValue);
  744. }
  745. handlePresetClick(item: PresetType, e: any) {
  746. const { type, timeZone } = this.getProps();
  747. const prevTimeZone = this.getState('prevTimezone');
  748. let value;
  749. switch (type) {
  750. case 'month':
  751. case 'dateTime':
  752. case 'date':
  753. value = this.parseWithTimezone([item.start], timeZone, prevTimeZone);
  754. this.handleSelectedChange(value);
  755. break;
  756. case 'dateTimeRange':
  757. case 'dateRange':
  758. value = this.parseWithTimezone([item.start, item.end], timeZone, prevTimeZone);
  759. this.handleSelectedChange(value, { needCheckFocusRecord: false });
  760. break;
  761. default:
  762. break;
  763. }
  764. this._adapter.notifyPresetsClick(item, e);
  765. }
  766. /**
  767. * 根据 type 处理 onChange 返回的参数
  768. *
  769. * - 返回的日期需要把用户时间转换为设置的时区时间
  770. * - 用户时间:用户计算机系统时间
  771. * - 时区时间:通过 ConfigProvider 设置的 timeZone
  772. * - 例子:用户设置时区为+9,计算机所在时区为+8区,然后用户选择了22:00
  773. * - DatePicker 内部保存日期 state 为 +8 的 22:00 => a = new Date("2021-05-25 22:00:00")
  774. * - 传出去时,需要把 +8 的 22:00 => +9 的 22:00 => b = zonedTimeToUtc(a, "+09:00");
  775. *
  776. * According to the type processing onChange returned parameters
  777. *
  778. * - the returned date needs to convert the user time to the set time zone time
  779. * - user time: user computer system time
  780. * - time zone time: timeZone set by ConfigProvider
  781. * - example: the user sets the time zone to + 9, the computer's time zone is + 8 zone, and then the user selects 22:00
  782. * - DatePicker internal save date state is + 8 22:00 = > a = new Date ("2021-05-25 22:00:00")
  783. * - when passed out, you need to + 8 22:00 = > + 9 22:00 = > b = zonedTimeToUtc (a, "+ 09:00");
  784. *
  785. * e.g.
  786. * let a = new Date ("2021-05-25 22:00:00");
  787. * = > Tue May 25 2021 22:00:00 GMT + 0800 (China Standard Time)
  788. * let b = zonedTimeToUtc (a, "+ 09:00");
  789. * = > Tue May 25 2021 21:00:00 GMT + 0800 (China Standard Time)
  790. *
  791. * @param {Date|Date[]} value
  792. * @return {{ notifyDate: Date|Date[], notifyValue: string|string[]}}
  793. */
  794. disposeCallbackArgs(value: Date | Date[]) {
  795. let _value = Array.isArray(value) ? value : (value && [value]) || [];
  796. if (this.isValidTimeZone()) {
  797. const timeZone = this.getProp('timeZone');
  798. _value = _value.map(date => zonedTimeToUtc(date, timeZone));
  799. }
  800. const type = this.getProp('type');
  801. const formatToken = this.getProp('format') || getDefaultFormatTokenByType(type);
  802. let notifyValue,
  803. notifyDate;
  804. switch (type) {
  805. case 'date':
  806. case 'dateTime':
  807. case 'month':
  808. if (!this._isMultiple()) {
  809. notifyValue = _value[0] && this.localeFormat(_value[0], formatToken);
  810. [notifyDate] = _value;
  811. } else {
  812. notifyValue = _value.map(v => v && this.localeFormat(v, formatToken));
  813. notifyDate = [..._value];
  814. }
  815. break;
  816. case 'dateRange':
  817. case 'dateTimeRange':
  818. notifyValue = _value.map(v => v && this.localeFormat(v, formatToken));
  819. notifyDate = [..._value];
  820. break;
  821. default:
  822. break;
  823. }
  824. return {
  825. notifyValue,
  826. notifyDate,
  827. };
  828. }
  829. /**
  830. * Notice: Check whether the date is the same as the state value before calling
  831. * @param {Date[]} value
  832. */
  833. _notifyChange(value: Date[]) {
  834. if (this._isRangeType() && !this._isRangeValueComplete(value)) {
  835. return;
  836. }
  837. const { onChangeWithDateFirst } = this.getProps();
  838. const { notifyValue, notifyDate } = this.disposeCallbackArgs(value);
  839. if (onChangeWithDateFirst) {
  840. this._adapter.notifyChange(notifyDate, notifyValue);
  841. } else {
  842. this._adapter.notifyChange(notifyValue, notifyDate);
  843. }
  844. }
  845. /**
  846. * Get the date changed through the date panel or enter
  847. * @param {Date[]} dates
  848. * @returns {Date[]}
  849. */
  850. _getChangedDates(dates: Date[]) {
  851. const type = this._adapter.getProp('type');
  852. const stateValue: Date[] = this._adapter.getState('value');
  853. const changedDates = [];
  854. switch (type) {
  855. case 'dateRange':
  856. case 'dateTimeRange':
  857. const [stateStart, stateEnd] = stateValue;
  858. const [start, end] = dates;
  859. if (!isDateEqual(start, stateStart)) {
  860. changedDates.push(start);
  861. }
  862. if (!isDateEqual(end, stateEnd)) {
  863. changedDates.push(end);
  864. }
  865. break;
  866. default:
  867. const stateValueSet = new Set<number>();
  868. stateValue.forEach(value => stateValueSet.add(isDate(value) && value.valueOf()));
  869. for (const date of dates) {
  870. if (!stateValueSet.has(isDate(date) && date.valueOf())) {
  871. changedDates.push(date);
  872. }
  873. }
  874. }
  875. return changedDates;
  876. }
  877. /**
  878. * Whether a date is disabled
  879. * @param {Array} value
  880. */
  881. _someDateDisabled(value: Date[]) {
  882. const stateValue = this.getState('value');
  883. const disabledOptions = { rangeStart: '', rangeEnd: '' };
  884. // DisabledDate needs to pass the second parameter
  885. if (this._isRangeType() && Array.isArray(stateValue)) {
  886. if (isValid(stateValue[0])) {
  887. const rangeStart = format(stateValue[0], 'yyyy-MM-dd');
  888. disabledOptions.rangeStart = rangeStart;
  889. }
  890. if (isValid(stateValue[1])) {
  891. const rangeEnd = format(stateValue[1], 'yyyy-MM-dd');
  892. disabledOptions.rangeEnd = rangeEnd;
  893. }
  894. }
  895. let isSomeDateDisabled = false;
  896. for (const date of value) {
  897. // skip check if date is null
  898. if (!isNullOrUndefined(date) && this.disabledDisposeDate(date, disabledOptions)) {
  899. isSomeDateDisabled = true;
  900. break;
  901. }
  902. }
  903. return isSomeDateDisabled;
  904. }
  905. getMergedMotion = (motion: any) => {
  906. const mergedMotion = typeof motion === 'undefined' || motion ? {
  907. ...motion,
  908. didEnter: () => {
  909. this._adapter.setMotionEnd(true);
  910. },
  911. didLeave: () => {
  912. this._adapter.setMotionEnd(false);
  913. }
  914. } : false;
  915. return mergedMotion;
  916. };
  917. /**
  918. * Format locale date
  919. * locale get from LocaleProvider
  920. * @param {Date} date
  921. * @param {String} token
  922. */
  923. localeFormat(date: Date, token: string) {
  924. const dateFnsLocale = this._adapter.getProp('dateFnsLocale');
  925. return format(date, token, { locale: dateFnsLocale });
  926. }
  927. _isRangeType = () => {
  928. const type = this._adapter.getProp('type');
  929. return /range/i.test(type);
  930. };
  931. _isRangeValueComplete = (value: Date[] | Date) => {
  932. let result = false;
  933. if (Array.isArray(value)) {
  934. result = !value.some(date => isNullOrUndefined(date));
  935. }
  936. return result;
  937. };
  938. /**
  939. * Convert computer date to UTC date
  940. * Before passing the date to the user, you need to convert the date to UTC time
  941. * dispose date from computer date to utc date
  942. * When given timeZone prop, you should convert computer date to utc date before passing to user
  943. * @param {(date: Date) => Boolean} fn
  944. * @param {Date|Date[]} date
  945. * @returns {Boolean}
  946. */
  947. disposeDateFn(fn: (date: Date, ...rest: any) => boolean, date: Date | Date[], ...rest: any[]) {
  948. const { notifyDate } = this.disposeCallbackArgs(date);
  949. const dateIsArray = Array.isArray(date);
  950. const notifyDateIsArray = Array.isArray(notifyDate);
  951. let disposeDate;
  952. if (dateIsArray === notifyDateIsArray) {
  953. disposeDate = notifyDate;
  954. } else {
  955. disposeDate = dateIsArray ? [notifyDate] : notifyDate[0];
  956. }
  957. return fn(disposeDate, ...rest);
  958. }
  959. /**
  960. * Determine whether the date is disabled
  961. * Whether the date is disabled
  962. * @param {Date} date
  963. * @returns {Boolean}
  964. */
  965. disabledDisposeDate(date: Date, ...rest: any[]) {
  966. const { disabledDate } = this.getProps();
  967. return this.disposeDateFn(disabledDate, date, ...rest);
  968. }
  969. /**
  970. * Determine whether the date is disabled
  971. * Whether the date time is disabled
  972. * @param {Date|Date[]} date
  973. * @returns {Object}
  974. */
  975. disabledDisposeTime(date: Date | Date[], ...rest: any[]) {
  976. const { disabledTime } = this.getProps();
  977. return this.disposeDateFn(disabledTime, date, ...rest);
  978. }
  979. /**
  980. * Trigger wrapper needs to do two things:
  981. * 1. Open Panel when clicking trigger;
  982. * 2. When clicking on a child but the child does not listen to the focus event, manually trigger focus
  983. *
  984. * @param {Event} e
  985. * @returns
  986. */
  987. handleTriggerWrapperClick(e: any) {
  988. const { disabled } = this._adapter.getProps();
  989. const { rangeInputFocus } = this._adapter.getStates();
  990. if (disabled) {
  991. return;
  992. }
  993. /**
  994. * - 非范围选择时,trigger 为原生输入框,已在组件内处理了 focus 逻辑
  995. * - isEventTarget 函数用于判断触发事件的是否为 input wrapper。如果是冒泡上来的不用处理,因为在子级已经处理了 focus 逻辑。
  996. *
  997. * - When type is not range type, Input component will automatically focus in the same case
  998. * - isEventTarget is used to judge whether the event is a bubbling event
  999. */
  1000. if (this._isRangeType() && !rangeInputFocus && this._adapter.isEventTarget(e)) {
  1001. setTimeout(() => {
  1002. // using setTimeout get correct state value 'rangeInputFocus'
  1003. this.handleInputFocus(e, 'rangeStart');
  1004. this.openPanel();
  1005. }, 0);
  1006. } else {
  1007. this.openPanel();
  1008. }
  1009. }
  1010. }