UNPKG

19.7 kBJavaScriptView Raw
1function _typeof(obj) {
2 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
3 _typeof = function _typeof(obj) {
4 return typeof obj;
5 };
6 } else {
7 _typeof = function _typeof(obj) {
8 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
9 };
10 }
11
12 return _typeof(obj);
13}
14
15function _classCallCheck(instance, Constructor) {
16 if (!(instance instanceof Constructor)) {
17 throw new TypeError("Cannot call a class as a function");
18 }
19}
20
21function _defineProperties(target, props) {
22 for (var i = 0; i < props.length; i++) {
23 var descriptor = props[i];
24 descriptor.enumerable = descriptor.enumerable || false;
25 descriptor.configurable = true;
26 if ("value" in descriptor) descriptor.writable = true;
27 Object.defineProperty(target, descriptor.key, descriptor);
28 }
29}
30
31function _createClass(Constructor, protoProps, staticProps) {
32 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
33 if (staticProps) _defineProperties(Constructor, staticProps);
34 return Constructor;
35}
36
37function _possibleConstructorReturn(self, call) {
38 if (call && (_typeof(call) === "object" || typeof call === "function")) {
39 return call;
40 }
41
42 return _assertThisInitialized(self);
43}
44
45function _get(target, property, receiver) {
46 if (typeof Reflect !== "undefined" && Reflect.get) {
47 _get = Reflect.get;
48 } else {
49 _get = function _get(target, property, receiver) {
50 var base = _superPropBase(target, property);
51
52 if (!base) return;
53 var desc = Object.getOwnPropertyDescriptor(base, property);
54
55 if (desc.get) {
56 return desc.get.call(receiver);
57 }
58
59 return desc.value;
60 };
61 }
62
63 return _get(target, property, receiver || target);
64}
65
66function _superPropBase(object, property) {
67 while (!Object.prototype.hasOwnProperty.call(object, property)) {
68 object = _getPrototypeOf(object);
69 if (object === null) break;
70 }
71
72 return object;
73}
74
75function _getPrototypeOf(o) {
76 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
77 return o.__proto__ || Object.getPrototypeOf(o);
78 };
79 return _getPrototypeOf(o);
80}
81
82function _inherits(subClass, superClass) {
83 if (typeof superClass !== "function" && superClass !== null) {
84 throw new TypeError("Super expression must either be null or a function");
85 }
86
87 subClass.prototype = Object.create(superClass && superClass.prototype, {
88 constructor: {
89 value: subClass,
90 writable: true,
91 configurable: true
92 }
93 });
94 if (superClass) _setPrototypeOf(subClass, superClass);
95}
96
97function _setPrototypeOf(o, p) {
98 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
99 o.__proto__ = p;
100 return o;
101 };
102
103 return _setPrototypeOf(o, p);
104}
105
106function _assertThisInitialized(self) {
107 if (self === void 0) {
108 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
109 }
110
111 return self;
112}
113/**
114 * Copyright IBM Corp. 2016, 2018
115 *
116 * This source code is licensed under the Apache-2.0 license found in the
117 * LICENSE file in the root directory of this source tree.
118 */
119
120
121import Flatpickr from 'flatpickr';
122import settings from '../../globals/js/settings';
123import mixin from '../../globals/js/misc/mixin';
124import createComponent from '../../globals/js/mixins/create-component';
125import initComponentBySearch from '../../globals/js/mixins/init-component-by-search';
126import handles from '../../globals/js/mixins/handles';
127import on from '../../globals/js/misc/on';
128import { componentsX } from '../../globals/js/feature-flags';
129/* eslint no-underscore-dangle: [2, { "allow": ["_input", "_updateClassNames", "_updateInputFields"], "allowAfterThis": true }] */
130// `this.options` create-component mix-in creates prototype chain
131// so that `options` given in constructor argument wins over the one defined in static `options` property
132// 'Flatpickr' wants flat structure of object instead
133
134function flattenOptions(options) {
135 var o = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax
136
137 for (var key in options) {
138 o[key] = options[key];
139 }
140
141 return o;
142} // Weekdays shorthand for english locale
143
144
145Flatpickr.l10ns.en.weekdays.shorthand.forEach(function (day, index) {
146 var currentDay = Flatpickr.l10ns.en.weekdays.shorthand;
147
148 if (currentDay[index] === 'Thu' || currentDay[index] === 'Th') {
149 currentDay[index] = 'Th';
150 } else {
151 currentDay[index] = currentDay[index].charAt(0);
152 }
153});
154
155var toArray = function toArray(arrayLike) {
156 return Array.prototype.slice.call(arrayLike);
157};
158
159var DatePicker =
160/*#__PURE__*/
161function (_mixin) {
162 _inherits(DatePicker, _mixin);
163 /**
164 * DatePicker.
165 * @extends CreateComponent
166 * @extends InitComponentBySearch
167 * @extends Handles
168 * @param {HTMLElement} element The element working as an date picker.
169 */
170
171
172 function DatePicker(element, options) {
173 var _this;
174
175 _classCallCheck(this, DatePicker);
176
177 _this = _possibleConstructorReturn(this, _getPrototypeOf(DatePicker).call(this, element, options));
178
179 _this._handleFocus = function () {
180 if (_this.calendar) {
181 _this.calendar.open();
182 }
183 };
184
185 _this._handleBlur = function (event) {
186 if (_this.calendar) {
187 var focusTo = event.relatedTarget;
188
189 if (!focusTo || !_this.element.contains(focusTo) && (!_this.calendar.calendarContainer || !_this.calendar.calendarContainer.contains(focusTo))) {
190 _this.calendar.close();
191 }
192 }
193 };
194
195 _this._initDatePicker = function (type) {
196 if (type === 'range') {
197 // Given FlatPickr assumes one `<input>` even in range mode,
198 // use a hidden `<input>` for such purpose, separate from our from/to `<input>`s
199 var doc = _this.element.ownerDocument;
200 var rangeInput = doc.createElement('input');
201 rangeInput.className = _this.options.classVisuallyHidden;
202 rangeInput.setAttribute('aria-hidden', 'true');
203
204 _this.element.appendChild(rangeInput);
205
206 _this._rangeInput = rangeInput; // An attempt to open the date picker dropdown when this component gets focus,
207 // and close the date picker dropdown when this component loses focus
208
209 var w = doc.defaultView;
210 var hasFocusin = 'onfocusin' in w;
211 var hasFocusout = 'onfocusout' in w;
212 var focusinEventName = hasFocusin ? 'focusin' : 'focus';
213 var focusoutEventName = hasFocusout ? 'focusout' : 'blur';
214
215 _this.manage(on(_this.element, focusinEventName, _this._handleFocus, !hasFocusin));
216
217 _this.manage(on(_this.element, focusoutEventName, _this._handleBlur, !hasFocusout));
218
219 _this.manage(on(_this.element.querySelector(_this.options.selectorDatePickerIcon), focusoutEventName, _this._handleBlur, !hasFocusout));
220 }
221
222 var self = _assertThisInitialized(_assertThisInitialized(_this));
223
224 var date = type === 'range' ? _this._rangeInput : _this.element.querySelector(_this.options.selectorDatePickerInput);
225 var _this$options = _this.options,
226 _onClose = _this$options.onClose,
227 _onChange = _this$options.onChange,
228 _onMonthChange = _this$options.onMonthChange,
229 _onYearChange = _this$options.onYearChange,
230 _onOpen = _this$options.onOpen,
231 _onValueUpdate = _this$options.onValueUpdate;
232 var calendar = new Flatpickr(date, Object.assign(flattenOptions(_this.options), {
233 allowInput: true,
234 mode: type,
235 positionElement: type === 'range' && _this.element.querySelector(_this.options.selectorDatePickerInputFrom),
236 onClose: function onClose(selectedDates) {
237 // An attempt to disable Flatpickr's focus tracking system,
238 // which has adverse effect with our old set up with two `<input>`s or our latest setup with a hidden `<input>`
239 if (self.shouldForceOpen) {
240 if (self.calendar.calendarContainer) {
241 self.calendar.calendarContainer.classList.add('open');
242 }
243
244 self.calendar.isOpen = true;
245 }
246
247 for (var _len = arguments.length, remainder = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
248 remainder[_key - 1] = arguments[_key];
249 }
250
251 if (!_onClose || _onClose.call.apply(_onClose, [this, selectedDates].concat(remainder)) !== false) {
252 self._updateClassNames(calendar);
253
254 self._updateInputFields(selectedDates, type);
255 }
256 },
257 onChange: function onChange() {
258 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
259 args[_key2] = arguments[_key2];
260 }
261
262 if (!_onChange || _onChange.call.apply(_onChange, [this].concat(args)) !== false) {
263 self._updateClassNames(calendar);
264
265 if (type === 'range') {
266 if (calendar.selectedDates.length === 1 && calendar.isOpen) {
267 self.element.querySelector(self.options.selectorDatePickerInputTo).classList.add(self.options.classFocused);
268 } else {
269 self.element.querySelector(self.options.selectorDatePickerInputTo).classList.remove(self.options.classFocused);
270 }
271 }
272 }
273 },
274 onMonthChange: function onMonthChange() {
275 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
276 args[_key3] = arguments[_key3];
277 }
278
279 if (!_onMonthChange || _onMonthChange.call.apply(_onMonthChange, [this].concat(args)) !== false) {
280 self._updateClassNames(calendar);
281 }
282 },
283 onYearChange: function onYearChange() {
284 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
285 args[_key4] = arguments[_key4];
286 }
287
288 if (!_onYearChange || _onYearChange.call.apply(_onYearChange, [this].concat(args)) !== false) {
289 self._updateClassNames(calendar);
290 }
291 },
292 onOpen: function onOpen() {
293 // An attempt to disable Flatpickr's focus tracking system,
294 // which has adverse effect with our old set up with two `<input>`s or our latest setup with a hidden `<input>`
295 self.shouldForceOpen = true;
296 setTimeout(function () {
297 self.shouldForceOpen = false;
298 }, 0);
299
300 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
301 args[_key5] = arguments[_key5];
302 }
303
304 if (!_onOpen || _onOpen.call.apply(_onOpen, [this].concat(args)) !== false) {
305 self._updateClassNames(calendar);
306 }
307 },
308 onValueUpdate: function onValueUpdate() {
309 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
310 args[_key6] = arguments[_key6];
311 }
312
313 if ((!_onValueUpdate || _onValueUpdate.call.apply(_onValueUpdate, [this].concat(args)) !== false) && type === 'range') {
314 self._updateInputFields(self.calendar.selectedDates, type);
315 }
316 },
317 nextArrow: _this._rightArrowHTML(),
318 prevArrow: _this._leftArrowHTML()
319 }));
320
321 if (type === 'range') {
322 _this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputFrom), 0);
323
324 _this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputTo), 1);
325 }
326
327 _this.manage(on(_this.element.querySelector(_this.options.selectorDatePickerIcon), 'click', function () {
328 calendar.open();
329 }));
330
331 _this._updateClassNames(calendar);
332
333 if (type !== 'range') {
334 _this._addInputLogic(date);
335 }
336
337 return calendar;
338 };
339
340 _this._addInputLogic = function (input, index) {
341 if (!isNaN(index) && (index < 0 || index > 1)) {
342 throw new RangeError("The index of <input> (".concat(index, ") is out of range."));
343 }
344
345 var inputField = input;
346
347 _this.manage(on(inputField, 'change', function (evt) {
348 if (evt.isTrusted || evt.detail && evt.detail.isNotFromFlatpickr) {
349 var inputDate = _this.calendar.parseDate(inputField.value);
350
351 if (inputDate && !isNaN(inputDate.valueOf())) {
352 if (isNaN(index)) {
353 _this.calendar.setDate(inputDate);
354 } else {
355 var selectedDates = _this.calendar.selectedDates;
356 selectedDates[index] = inputDate;
357
358 _this.calendar.setDate(selectedDates);
359 }
360 }
361 }
362
363 _this._updateClassNames(_this.calendar);
364 })); // An attempt to temporarily set the `<input>` being edited as the one FlatPicker manages,
365 // as FlatPicker attempts to take over `keydown` event handler on `document` to run on the date picker dropdown.
366
367
368 _this.manage(on(inputField, 'keydown', function (evt) {
369 var origInput = _this.calendar._input;
370 _this.calendar._input = evt.target;
371 setTimeout(function () {
372 _this.calendar._input = origInput;
373 });
374 }));
375 };
376
377 _this._updateClassNames = function (_ref) {
378 var calendarContainer = _ref.calendarContainer,
379 selectedDates = _ref.selectedDates;
380
381 if (calendarContainer) {
382 calendarContainer.classList.add(_this.options.classCalendarContainer);
383 calendarContainer.querySelector('.flatpickr-month').classList.add(_this.options.classMonth);
384 calendarContainer.querySelector('.flatpickr-weekdays').classList.add(_this.options.classWeekdays);
385 calendarContainer.querySelector('.flatpickr-days').classList.add(_this.options.classDays);
386 toArray(calendarContainer.querySelectorAll('.flatpickr-weekday')).forEach(function (item) {
387 var currentItem = item;
388 currentItem.innerHTML = currentItem.innerHTML.replace(/\s+/g, '');
389 currentItem.classList.add(_this.options.classWeekday);
390 });
391 toArray(calendarContainer.querySelectorAll('.flatpickr-day')).forEach(function (item) {
392 item.classList.add(_this.options.classDay);
393
394 if (item.classList.contains('today') && selectedDates.length > 0) {
395 item.classList.add('no-border');
396 } else if (item.classList.contains('today') && selectedDates.length === 0) {
397 item.classList.remove('no-border');
398 }
399 });
400 }
401 };
402
403 _this._updateInputFields = function (selectedDates, type) {
404 if (type === 'range') {
405 if (selectedDates.length === 2) {
406 _this.element.querySelector(_this.options.selectorDatePickerInputFrom).value = _this._formatDate(selectedDates[0]);
407 _this.element.querySelector(_this.options.selectorDatePickerInputTo).value = _this._formatDate(selectedDates[1]);
408 } else if (selectedDates.length === 1) {
409 _this.element.querySelector(_this.options.selectorDatePickerInputFrom).value = _this._formatDate(selectedDates[0]);
410 }
411 } else if (selectedDates.length === 1) {
412 _this.element.querySelector(_this.options.selectorDatePickerInput).value = _this._formatDate(selectedDates[0]);
413 }
414
415 _this._updateClassNames(_this.calendar);
416 };
417
418 _this._formatDate = function (date) {
419 return _this.calendar.formatDate(date, _this.calendar.config.dateFormat);
420 };
421
422 var _type = _this.element.getAttribute(_this.options.attribType);
423
424 _this.calendar = _this._initDatePicker(_type);
425
426 if (_this.calendar.calendarContainer) {
427 _this.manage(on(_this.element, 'keydown', function (e) {
428 if (e.which === 40) {
429 _this.calendar.calendarContainer.focus();
430 }
431 }));
432
433 _this.manage(on(_this.calendar.calendarContainer, 'keydown', function (e) {
434 if (e.which === 9 && _type === 'range') {
435 _this._updateClassNames(_this.calendar);
436
437 _this.element.querySelector(_this.options.selectorDatePickerInputFrom).focus();
438 }
439 }));
440 }
441
442 return _this;
443 }
444 /**
445 * Opens the date picker dropdown when this component gets focus.
446 * Used only for range mode for now.
447 * @private
448 */
449
450
451 _createClass(DatePicker, [{
452 key: "_rightArrowHTML",
453 value: function _rightArrowHTML() {
454 return componentsX ? "\n <svg\n focusable=\"false\"\n preserveAspectRatio=\"xMidYMid meet\"\n style=\"will-change: transform;\"\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n aria-hidden=\"true\">\n <path d=\"M11 8l-5 5-.7-.7L9.6 8 5.3 3.7 6 3z\"></path>\n </svg>" : "\n <svg width=\"8\" height=\"12\" viewBox=\"0 0 8 12\" fill-rule=\"evenodd\">\n <path d=\"M0 10.6L4.7 6 0 1.4 1.4 0l6.1 6-6.1 6z\"></path>\n </svg>";
455 }
456 }, {
457 key: "_leftArrowHTML",
458 value: function _leftArrowHTML() {
459 return componentsX ? "\n <svg\n focusable=\"false\"\n preserveAspectRatio=\"xMidYMid meet\"\n style=\"will-change: transform;\"\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n aria-hidden=\"true\"\n >\n <path d=\"M5 8l5-5 .7.7L6.4 8l4.3 4.3-.7.7z\"></path>\n </svg>" : "\n <svg width=\"8\" height=\"12\" viewBox=\"0 0 8 12\" fill-rule=\"evenodd\">\n <path d=\"M7.5 10.6L2.8 6l4.7-4.6L6.1 0 0 6l6.1 6z\"></path>\n </svg>";
460 }
461 }, {
462 key: "release",
463 value: function release() {
464 if (this._rangeInput && this._rangeInput.parentNode) {
465 this._rangeInput.parentNode.removeChild(this._rangeInput);
466 }
467
468 if (this.calendar) {
469 try {
470 this.calendar.destroy();
471 } catch (err) {} // eslint-disable-line no-empty
472
473
474 this.calendar = null;
475 }
476
477 return _get(_getPrototypeOf(DatePicker.prototype), "release", this).call(this);
478 }
479 /**
480 * The component options.
481 * If `options` is specified in the constructor,
482 * {@linkcode DatePicker.create .create()}, or {@linkcode DatePicker.init .init()},
483 * properties in this object are overriden for the instance being create and how {@linkcode DatePicker.init .init()} works.
484 * @property {string} selectorInit The CSS selector to find date picker UIs.
485 */
486
487 }], [{
488 key: "options",
489 get: function get() {
490 var prefix = settings.prefix;
491 return {
492 selectorInit: '[data-date-picker]',
493 selectorDatePickerInput: '[data-date-picker-input]',
494 selectorDatePickerInputFrom: '[data-date-picker-input-from]',
495 selectorDatePickerInputTo: '[data-date-picker-input-to]',
496 selectorDatePickerIcon: '[data-date-picker-icon]',
497 classCalendarContainer: "".concat(prefix, "--date-picker__calendar"),
498 classMonth: "".concat(prefix, "--date-picker__month"),
499 classWeekdays: "".concat(prefix, "--date-picker__weekdays"),
500 classDays: "".concat(prefix, "--date-picker__days"),
501 classWeekday: "".concat(prefix, "--date-picker__weekday"),
502 classDay: "".concat(prefix, "--date-picker__day"),
503 classFocused: "".concat(prefix, "--focused"),
504 classVisuallyHidden: "".concat(prefix, "--visually-hidden"),
505 attribType: 'data-date-picker-type',
506 dateFormat: 'm/d/Y'
507 };
508 }
509 /**
510 * The map associating DOM element and date picker UI instance.
511 * @type {WeakMap}
512 */
513
514 }]);
515
516 DatePicker.components = new WeakMap();
517 return DatePicker;
518}(mixin(createComponent, initComponentBySearch, handles));
519
520export default DatePicker;
\No newline at end of file