foundation.ts 53 KB

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