foundation.ts 51 KB

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