carbon-components
Version:
Carbon Components is a component library for IBM Cloud
366 lines (323 loc) • 14.4 kB
JavaScript
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', 'flatpickr', '../../globals/js/settings', '../../globals/js/misc/mixin', '../../globals/js/mixins/create-component', '../../globals/js/mixins/init-component-by-search', '../../globals/js/mixins/handles', '../../globals/js/misc/on'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('flatpickr'), require('../../globals/js/settings'), require('../../globals/js/misc/mixin'), require('../../globals/js/mixins/create-component'), require('../../globals/js/mixins/init-component-by-search'), require('../../globals/js/mixins/handles'), require('../../globals/js/misc/on'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.flatpickr, global.settings, global.mixin, global.createComponent, global.initComponentBySearch, global.handles, global.on);
global.datePicker = mod.exports;
}
})(this, function (exports, _flatpickr, _settings, _mixin2, _createComponent, _initComponentBySearch, _handles, _on) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _flatpickr2 = _interopRequireDefault(_flatpickr);
var _settings2 = _interopRequireDefault(_settings);
var _mixin3 = _interopRequireDefault(_mixin2);
var _createComponent2 = _interopRequireDefault(_createComponent);
var _initComponentBySearch2 = _interopRequireDefault(_initComponentBySearch);
var _handles2 = _interopRequireDefault(_handles);
var _on2 = _interopRequireDefault(_on);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
var _get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
// `this.options` create-component mix-in creates prototype chain
// so that `options` given in constructor argument wins over the one defined in static `options` property
// 'Flatpickr' wants flat structure of object instead
function flattenOptions(options) {
var o = {};
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (var key in options) {
o[key] = options[key];
}
return o;
}
/**
* Augments Flatpickr instance so that event objects Flatpickr fires is marked as non-user-triggered events.
* @param {Flatpickr} calendar The Flatpickr instance.
* @returns {Flatpickr} The augmented Flatpickr instance.
* @private
*/
function augmentFlatpickr(calendar) {
var container = calendar._;
if (container) {
if (container.changeEvent) {
container._changeEvent = container.changeEvent; // eslint-disable-line no-underscore-dangle
}
Object.defineProperty(container, 'changeEvent', {
get: function get() {
return this._changeEvent;
},
set: function set(value) {
value.detail = Object.assign(value.detail || {}, { fromFlatpickr: true });
this._changeEvent = value;
}
});
}
return calendar;
}
// Weekdays shorthand for english locale
_flatpickr2.default.l10ns.en.weekdays.shorthand.forEach(function (day, index) {
var currentDay = _flatpickr2.default.l10ns.en.weekdays.shorthand;
if (currentDay[index] === 'Thu' || currentDay[index] === 'Th') {
currentDay[index] = 'Th';
} else {
currentDay[index] = currentDay[index].charAt(0);
}
});
var DatePicker = function (_mixin) {
_inherits(DatePicker, _mixin);
/**
* DatePicker.
* @extends CreateComponent
* @extends InitComponentBySearch
* @extends Handles
* @param {HTMLElement} element The element working as an date picker.
*/
function DatePicker(element, options) {
_classCallCheck(this, DatePicker);
var _this = _possibleConstructorReturn(this, (DatePicker.__proto__ || Object.getPrototypeOf(DatePicker)).call(this, element, options));
_initialiseProps.call(_this);
var type = _this.element.getAttribute(_this.options.attribType);
_this.calendar = _this._initDatePicker(type);
_this.manage((0, _on2.default)(_this.element, 'keydown', function (e) {
if (e.which === 40) {
_this.calendar.calendarContainer.focus();
}
}));
_this.manage((0, _on2.default)(_this.calendar.calendarContainer, 'keydown', function (e) {
if (e.which === 9 && type === 'range') {
_this._updateClassNames(_this.calendar);
_this.element.querySelector(_this.options.selectorDatePickerInputFrom).focus();
}
}));
return _this;
}
_createClass(DatePicker, [{
key: '_rightArrowHTML',
value: function _rightArrowHTML() {
return '\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>';
}
}, {
key: '_leftArrowHTML',
value: function _leftArrowHTML() {
return '\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>';
}
}, {
key: 'release',
value: function release() {
if (this.calendar) {
try {
this.calendar.destroy();
} catch (err) {} // eslint-disable-line no-empty
this.calendar = null;
}
return _get(DatePicker.prototype.__proto__ || Object.getPrototypeOf(DatePicker.prototype), 'release', this).call(this);
}
}], [{
key: 'options',
get: function get() {
var prefix = _settings2.default.prefix;
return {
selectorInit: '[data-date-picker]',
selectorDatePickerInput: '[data-date-picker-input]',
selectorDatePickerInputFrom: '[data-date-picker-input-from]',
selectorDatePickerInputTo: '[data-date-picker-input-to]',
selectorDatePickerIcon: '[data-date-picker-icon]',
classCalendarContainer: prefix + '--date-picker__calendar',
classMonth: prefix + '--date-picker__month',
classWeekdays: prefix + '--date-picker__weekdays',
classDays: prefix + '--date-picker__days',
classWeekday: prefix + '--date-picker__weekday',
classDay: prefix + '--date-picker__day',
classFocused: prefix + '--focused',
attribType: 'data-date-picker-type',
dateFormat: 'm/d/Y'
};
}
}]);
return DatePicker;
}((0, _mixin3.default)(_createComponent2.default, _initComponentBySearch2.default, _handles2.default));
DatePicker.components = new WeakMap();
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this._initDatePicker = function (type) {
var date = type === 'single' ? _this2.element.querySelector(_this2.options.selectorDatePickerInput) : _this2.element.querySelector(_this2.options.selectorDatePickerInputFrom);
var calendar = new _flatpickr2.default(date, Object.assign(flattenOptions(_this2.options), {
allowInput: true,
mode: type,
onClose: function onClose(selectedDates) {
_this2._updateClassNames(calendar);
_this2._updateInputFields(selectedDates, type);
if (type === 'range') {
if (calendar.selectedDates.length === 1) {
date.focus();
} else {
_this2.element.querySelector(_this2.options.selectorDatePickerInputTo).focus();
}
_this2.element.querySelector(_this2.options.selectorDatePickerInputTo).classList.remove(_this2.options.classFocused);
}
},
onChange: function onChange() {
_this2._updateClassNames(calendar);
if (type === 'range') {
if (calendar.selectedDates.length === 1 && calendar.isOpen) {
_this2.element.querySelector(_this2.options.selectorDatePickerInputTo).classList.add(_this2.options.classFocused);
} else {
_this2.element.querySelector(_this2.options.selectorDatePickerInputTo).classList.remove(_this2.options.classFocused);
}
}
},
onMonthChange: function onMonthChange() {
_this2._updateClassNames(calendar);
},
onYearChange: function onYearChange() {
_this2._updateClassNames(calendar);
},
onOpen: function onOpen() {
_this2._updateClassNames(calendar);
},
nextArrow: _this2._rightArrowHTML(),
prevArrow: _this2._leftArrowHTML()
}));
if (type === 'range') {
_this2.manage((0, _on2.default)(_this2.element.querySelector(_this2.options.selectorDatePickerInputTo), 'click', function () {
_this2.element.querySelector(_this2.options.selectorDatePickerInputTo).focus();
calendar.open();
_this2._updateClassNames(calendar);
}));
_this2._addInputLogic(_this2.element.querySelector(_this2.options.selectorDatePickerInputTo));
}
_this2.manage((0, _on2.default)(_this2.element.querySelector(_this2.options.selectorDatePickerIcon), 'click', function () {
calendar.open();
}));
_this2._updateClassNames(calendar);
_this2._addInputLogic(date);
return augmentFlatpickr(calendar);
};
this._addInputLogic = function (input) {
var inputField = input;
_this2.manage((0, _on2.default)(inputField, 'change', function (evt) {
if (!evt.detail || !evt.detail.fromFlatpickr) {
var inputDate = _this2.calendar.parseDate(inputField.value);
if (!isNaN(inputDate.valueOf())) {
_this2.calendar.setDate(inputDate);
}
}
_this2._updateClassNames(_this2.calendar);
}));
};
this._updateClassNames = function (calendar) {
var calendarContainer = calendar.calendarContainer;
calendarContainer.classList.add(_this2.options.classCalendarContainer);
calendarContainer.querySelector('.flatpickr-month').classList.add(_this2.options.classMonth);
calendarContainer.querySelector('.flatpickr-weekdays').classList.add(_this2.options.classWeekdays);
calendarContainer.querySelector('.flatpickr-days').classList.add(_this2.options.classDays);
[].concat(_toConsumableArray(calendarContainer.querySelectorAll('.flatpickr-weekday'))).forEach(function (item) {
var currentItem = item;
currentItem.innerHTML = currentItem.innerHTML.replace(/\s+/g, '');
currentItem.classList.add(_this2.options.classWeekday);
});
[].concat(_toConsumableArray(calendarContainer.querySelectorAll('.flatpickr-day'))).forEach(function (item) {
item.classList.add(_this2.options.classDay);
if (item.classList.contains('today') && calendar.selectedDates.length > 0) {
item.classList.add('no-border');
} else if (item.classList.contains('today') && calendar.selectedDates.length === 0) {
item.classList.remove('no-border');
}
});
};
this._updateInputFields = function (selectedDates, type) {
if (type === 'range') {
if (selectedDates.length === 2) {
_this2.element.querySelector(_this2.options.selectorDatePickerInputFrom).value = _this2._formatDate(selectedDates[0]);
_this2.element.querySelector(_this2.options.selectorDatePickerInputTo).value = _this2._formatDate(selectedDates[1]);
} else if (selectedDates.length === 1) {
_this2.element.querySelector(_this2.options.selectorDatePickerInputFrom).value = _this2._formatDate(selectedDates[0]);
}
} else if (selectedDates.length === 1) {
_this2.element.querySelector(_this2.options.selectorDatePickerInput).value = _this2._formatDate(selectedDates[0]);
}
_this2._updateClassNames(_this2.calendar);
};
this._formatDate = function (date) {
return _this2.calendar.formatDate(date, _this2.calendar.config.dateFormat);
};
};
exports.default = DatePicker;
});