From f19b795ac5fdd43a8b40ef6a4284b811c5cb71a3 Mon Sep 17 00:00:00 2001 From: Akira Sudoh Date: Fri, 10 Jan 2020 09:51:53 +0900 Subject: [PATCH] fix(DatePicker): fix programmatic set of date in range mode (#4814) This change adds a logic to re-format dates in `` when Flatpickr's `setDate()` API is called. Flatpickr's range plugin has a similar logic to do that, but runs only if the second argument is `true`. Fixes #4803. --- .../DatePicker/plugins/rangePlugin.js | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/react/src/components/DatePicker/plugins/rangePlugin.js b/packages/react/src/components/DatePicker/plugins/rangePlugin.js index 225c7aee32fa..46f64fec936f 100644 --- a/packages/react/src/components/DatePicker/plugins/rangePlugin.js +++ b/packages/react/src/components/DatePicker/plugins/rangePlugin.js @@ -5,11 +5,38 @@ import rangePlugin from 'flatpickr/dist/plugins/rangePlugin'; * @returns {Plugin} An extension of Flatpickr `rangePlugin` that does the following: * * Better ensures the calendar dropdown is always aligned to the `` for the starting date. * Workaround for: https://github.com/flatpickr/flatpickr/issues/1944 + * * A logic to ensure `fp.setDate()` call won't end up with "startDate to endDate" set to the first `` */ export default config => { const factory = rangePlugin(Object.assign({ position: 'left' }, config)); - return fp => - Object.assign(factory(fp), { + return fp => { + const origSetDate = fp.setDate; + + const init = () => { + fp.setDate = function setDate(dates, triggerChange, format) { + origSetDate.call(this, dates, triggerChange, format); + // If `triggerChange` is `true`, `onValueUpdate` Flatpickr event is fired + // where Flatpickr's range plugin takes care of fixing the first `` + if (!triggerChange) { + const { _input: inputFrom } = fp; + const { input: inputTo } = config; + [inputFrom, inputTo].forEach((input, i) => { + if (input) { + input.value = !dates[i] + ? '' + : fp.formatDate(new Date(dates[i]), fp.config.dateFormat); + } + }); + } + }; + }; + + const origRangePlugin = factory(fp); + const { onReady: origOnReady } = origRangePlugin; + + return Object.assign(origRangePlugin, { + onReady: [init, origOnReady], onPreCalendarPosition() {}, }); + }; };