@carbon/charts
Version:
Carbon charting components
1,410 lines (1,187 loc) • 426 kB
JavaScript
var CarbonComponents = (function (exports) {
'use strict';
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Settings.
* @exports CarbonComponents.settings
* @type Object
* @property {boolean} [disableAutoInit]
* Disables automatic instantiation of components.
* By default (`CarbonComponents.disableAutoInit` is `false`),
* carbon-components attempts to instantiate components automatically
* by searching for elements with `data-component-name` (e.g. `data-loading`) attribute
* or upon DOM events (e.g. clicking) on such elements.
* See each components' static `.init()` methods for details.
* @property {string} [prefix=bx]
* Brand prefix. Should be in sync with `$prefix` Sass variable in carbon-components/src/globals/scss/_vars.scss.
* // @todo given that the default value is so long, is it appropriate to put in the JSDoc?
* @property {string} [selectorTabbable]
* A selector selecting tabbable/focusable nodes.
* By default selectorTabbable refereneces links, areas, inputs, buttons, selects, textareas,
* iframes, objects, embeds, or elements explicitly using tabindex or contenteditable attributes
* as long as the element is not `disabled` or the `tabindex="-1"`.
*/
var settings = {
prefix: 'bx',
selectorTabbable: "\n a[href], area[href], input:not([disabled]):not([tabindex='-1']),\n button:not([disabled]):not([tabindex='-1']),select:not([disabled]):not([tabindex='-1']),\n textarea:not([disabled]):not([tabindex='-1']),\n iframe, object, embed, *[tabindex]:not([tabindex='-1']), *[contenteditable=true]\n "
};
var settings_1 = settings;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @param {Array} a An array.
* @returns {Array} The flattened version of the given array.
*/
function flatten(a) {
return a.reduce(function (result, item) {
if (Array.isArray(item)) {
result.push.apply(result, _toConsumableArray(flatten(item)));
} else {
result.push(item);
}
return result;
}, []);
}
/**
* An interface for defining mix-in classes. Used with {@link mixin}.
* @function mixinfn
* @param {Class} ToMix The class to mix.
* @returns {Class} The class mixed-in with the given ToMix class.
*/
/**
* @function mixin
* @param {...mixinfn} mixinfns The functions generating mix-ins.
* @returns {Class} The class generated with the given mix-ins.
*/
function mixin() {
for (var _len = arguments.length, mixinfns = new Array(_len), _key = 0; _key < _len; _key++) {
mixinfns[_key] = arguments[_key];
}
return flatten(mixinfns).reduce(function (Class, mixinfn) {
return mixinfn(Class);
},
/*#__PURE__*/
function () {
function _class() {
_classCallCheck(this, _class);
}
return _class;
}());
}
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
function createComponent (ToMix) {
var CreateComponent =
/*#__PURE__*/
function (_ToMix) {
_inherits(CreateComponent, _ToMix);
/**
* The component instances managed by this component.
* Releasing this component also releases the components in `this.children`.
* @type {Component[]}
*/
/**
* Mix-in class to manage lifecycle of component.
* The constructor sets up this component's effective options,
* and registers this component't instance associated to an element.
* @implements Handle
* @param {HTMLElement} element The element working as this component.
* @param {object} [options] The component options.
*/
function CreateComponent(element) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, CreateComponent);
_this = _possibleConstructorReturn(this, _getPrototypeOf(CreateComponent).call(this, element, options));
_defineProperty(_assertThisInitialized(_this), "children", []);
if (!element || element.nodeType !== Node.ELEMENT_NODE) {
throw new TypeError('DOM element should be given to initialize this widget.');
}
/**
* The element the component is of.
* @type {Element}
*/
_this.element = element;
/**
* The component options.
* @type {Object}
*/
_this.options = Object.assign(Object.create(_this.constructor.options), options);
_this.constructor.components.set(_this.element, _assertThisInitialized(_this));
return _this;
}
/**
* Instantiates this component of the given element.
* @param {HTMLElement} element The element.
*/
_createClass(CreateComponent, [{
key: "release",
/**
* Releases this component's instance from the associated element.
*/
value: function release() {
for (var child = this.children.pop(); child; child = this.children.pop()) {
child.release();
}
this.constructor.components.delete(this.element);
return null;
}
}], [{
key: "create",
value: function create(element, options) {
return this.components.get(element) || new this(element, options);
}
}]);
return CreateComponent;
}(ToMix);
return CreateComponent;
}
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
function initComponentBySearch (ToMix) {
/**
* Mix-in class to instantiate components by searching for their root elements.
* @class InitComponentBySearch
*/
var InitComponentBySearch =
/*#__PURE__*/
function (_ToMix) {
_inherits(InitComponentBySearch, _ToMix);
function InitComponentBySearch() {
_classCallCheck(this, InitComponentBySearch);
return _possibleConstructorReturn(this, _getPrototypeOf(InitComponentBySearch).apply(this, arguments));
}
_createClass(InitComponentBySearch, null, [{
key: "init",
/**
* Instantiates component in the given node.
* If the given element indicates that it's an component of this class, instantiates it.
* Otherwise, instantiates components by searching for components in the given node.
* @param {Node} target The DOM node to instantiate components in. Should be a document or an element.
* @param {object} [options] The component options.
* @param {boolean} [options.selectorInit] The CSS selector to find components.
*/
value: function init() {
var _this = this;
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var effectiveOptions = Object.assign(Object.create(this.options), options);
if (!target || target.nodeType !== Node.ELEMENT_NODE && target.nodeType !== Node.DOCUMENT_NODE) {
throw new TypeError('DOM document or DOM element should be given to search for and initialize this widget.');
}
if (target.nodeType === Node.ELEMENT_NODE && target.matches(effectiveOptions.selectorInit)) {
this.create(target, options);
} else {
Array.prototype.forEach.call(target.querySelectorAll(effectiveOptions.selectorInit), function (element) {
return _this.create(element, options);
});
}
}
}]);
return InitComponentBySearch;
}(ToMix);
return InitComponentBySearch;
}
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
function handles (ToMix) {
/**
* Mix-in class to manage handles in component.
* Managed handles are automatically released when the component with this class mixed in is released.
* @class Handles
* @implements Handle
*/
var Handles =
/*#__PURE__*/
function (_ToMix) {
_inherits(Handles, _ToMix);
function Handles() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Handles);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Handles)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "handles", new Set());
return _this;
}
_createClass(Handles, [{
key: "manage",
/**
* Manages the given handle.
* @param {Handle} handle The handle to manage.
* @returns {Handle} The given handle.
*/
value: function manage(handle) {
this.handles.add(handle);
return handle;
}
/**
* Stop managing the given handle.
* @param {Handle} handle The handle to stop managing.
* @returns {Handle} The given handle.
*/
}, {
key: "unmanage",
value: function unmanage(handle) {
this.handles.delete(handle);
return handle;
}
}, {
key: "release",
value: function release() {
var _this2 = this;
this.handles.forEach(function (handle) {
handle.release();
_this2.handles.delete(handle);
});
return _get(_getPrototypeOf(Handles.prototype), "release", this).call(this);
}
}]);
return Handles;
}(ToMix);
return Handles;
}
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
function on(element) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
element.addEventListener.apply(element, args);
return {
release: function release() {
element.removeEventListener.apply(element, args);
return null;
}
};
}
var stateChangeTypes = {
true: 'true',
false: 'false',
mixed: 'mixed'
};
var Checkbox =
/*#__PURE__*/
function (_mixin) {
_inherits(Checkbox, _mixin);
/**
* Checkbox UI.
* @extends CreateComponent
* @extends InitComponentBySearch
* @extends Handles
* @param {HTMLElement} element The element working as a checkbox UI.
*/
function Checkbox(element, options) {
var _this;
_classCallCheck(this, Checkbox);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Checkbox).call(this, element, options));
_this.manage(on(_this.element, 'click', function (event) {
_this._handleClick(event);
}));
_this.manage(on(_this.element, 'focus', function (event) {
_this._handleFocus(event);
}));
_this.manage(on(_this.element, 'blur', function (event) {
_this._handleBlur(event);
}));
_this._indeterminateCheckbox();
_this._initCheckbox();
return _this;
}
_createClass(Checkbox, [{
key: "_handleClick",
value: function _handleClick() {
if (this.element.checked === true) {
this.element.setAttribute('checked', '');
this.element.setAttribute('aria-checked', 'true');
this.element.checked = true; // nested checkboxes inside labels
if (this.element.parentElement.classList.contains(this.options.classLabel)) {
this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState, 'true');
}
} else if (this.element.checked === false) {
this.element.removeAttribute('checked');
this.element.setAttribute('aria-checked', 'false');
this.element.checked = false; // nested checkboxes inside labels
if (this.element.parentElement.classList.contains(this.options.classLabel)) {
this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState, 'false');
}
}
}
}, {
key: "_handleFocus",
value: function _handleFocus() {
if (this.element.parentElement.classList.contains(this.options.classLabel)) {
this.element.parentElement.classList.add(this.options.classLabelFocused);
}
}
}, {
key: "_handleBlur",
value: function _handleBlur() {
if (this.element.parentElement.classList.contains(this.options.classLabel)) {
this.element.parentElement.classList.remove(this.options.classLabelFocused);
}
}
/**
* Sets the new checkbox state.
* @param {boolean|string} [state]
* The new checkbox state to set. `mixed` to put checkbox in indeterminate state.
* If omitted, this method simply makes the style reflect `aria-checked` attribute.
*/
}, {
key: "setState",
value: function setState(state) {
if (state === undefined || stateChangeTypes[state] === undefined) {
throw new TypeError('setState expects a value of true, false or mixed.');
}
this.element.setAttribute('aria-checked', state);
this.element.indeterminate = state === stateChangeTypes.mixed;
this.element.checked = state === stateChangeTypes.true;
var container = this.element.closest(this.options.selectorContainedCheckboxState);
if (container) {
container.setAttribute(this.options.attribContainedCheckboxState, state);
}
}
}, {
key: "setDisabled",
value: function setDisabled(value) {
if (value === undefined) {
throw new TypeError('setDisabled expects a boolean value of true or false');
}
if (value === true) {
this.element.setAttribute('disabled', true);
} else if (value === false) {
this.element.removeAttribute('disabled');
}
var container = this.element.closest(this.options.selectorContainedCheckboxDisabled);
if (container) {
container.setAttribute(this.options.attribContainedCheckboxDisabled, value);
}
}
}, {
key: "_indeterminateCheckbox",
value: function _indeterminateCheckbox() {
if (this.element.getAttribute('aria-checked') === 'mixed') {
this.element.indeterminate = true;
}
if (this.element.indeterminate === true) {
this.element.setAttribute('aria-checked', 'mixed');
}
if (this.element.parentElement.classList.contains(this.options.classLabel) && this.element.indeterminate === true) {
this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState, 'mixed');
}
}
}, {
key: "_initCheckbox",
value: function _initCheckbox() {
if (this.element.checked === true) {
this.element.setAttribute('aria-checked', 'true');
}
if (this.element.parentElement.classList.contains(this.options.classLabel) && this.element.checked) {
this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState, 'true');
}
if (this.element.parentElement.classList.contains(this.options.classLabel)) {
this.element.parentElement.setAttribute(this.options.attribContainedCheckboxDisabled, 'false');
}
if (this.element.parentElement.classList.contains(this.options.classLabel) && this.element.disabled) {
this.element.parentElement.setAttribute(this.options.attribContainedCheckboxDisabled, 'true');
}
}
/**
* The map associating DOM element and copy button UI instance.
* @member Checkbox.components
* @type {WeakMap}
*/
}], [{
key: "options",
/**
* The component options.
* If `options` is specified in the constructor, {@linkcode Checkbox.create .create()}, or {@linkcode Checkbox.init .init()},
* properties in this object are overriden for the instance being create and how {@linkcode Checkbox.init .init()} works.
* @member Checkbox.options
* @type {object}
* @property {string} selectorInit The data attribute to find copy button UIs.
* @property {string} selectorContainedCheckboxState The CSS selector to find a container of checkbox preserving checked state.
* @property {string} selectorContainedCheckboxDisabled
* The CSS selector to find a container of checkbox preserving disabled state.
* @property {string} classLabel The CSS class for the label.
* @property {string} classLabelFocused The CSS class for the focused label.
* @property {string} attribContainedCheckboxState The attribute name for the checked state of contained checkbox.
* @property {string} attribContainedCheckboxDisabled The attribute name for the disabled state of contained checkbox.
*/
get: function get() {
var prefix = settings_1.prefix;
return {
selectorInit: ".".concat(prefix, "--checkbox"),
selectorContainedCheckboxState: '[data-contained-checkbox-state]',
selectorContainedCheckboxDisabled: '[data-contained-checkbox-disabled]',
classLabel: "".concat(prefix, "--checkbox-label"),
classLabelFocused: "".concat(prefix, "--checkbox-label__focus"),
attribContainedCheckboxState: 'data-contained-checkbox-state',
attribContainedCheckboxDisabled: 'data-contained-checkbox-disabled'
};
}
}]);
return Checkbox;
}(mixin(createComponent, initComponentBySearch, handles));
_defineProperty(Checkbox, "components",
/* #__PURE_CLASS_PROPERTY__ */
new WeakMap());
_defineProperty(Checkbox, "stateChangeTypes",
/* #__PURE_CLASS_PROPERTY__ */
stateChangeTypes);
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
function eventedState (ToMix) {
/**
* Mix-in class to manage events associated with states.
* @class EventedState
*/
var EventedState =
/*#__PURE__*/
function (_ToMix) {
_inherits(EventedState, _ToMix);
function EventedState() {
_classCallCheck(this, EventedState);
return _possibleConstructorReturn(this, _getPrototypeOf(EventedState).apply(this, arguments));
}
_createClass(EventedState, [{
key: "_changeState",
/* eslint-disable jsdoc/check-param-names */
/**
* The internal implementation for {@link EventedState#changeState `.changeState()`}, performing actual change in state.
* @param {string} [state] The new state. Can be an omitted, which means toggling.
* @param {object} [detail]
* The object that should be put to event details that is fired before/after changing state.
* Can have a `group` property, which specifies what state to be changed.
* @param {EventedState~changeStateCallback} callback The callback called once changing state is finished or is canceled.
* @private
*/
value: function _changeState() {
throw new Error('_changeState() should be overriden to perform actual change in state.');
}
/**
* Changes the state of this component.
* @param {string} [state] The new state. Can be an omitted, which means toggling.
* @param {object} [detail]
* The object that should be put to event details that is fired before/after changing state.
* Can have a `group` property, which specifies what state to be changed.
* @param {EventedState~changeStateCallback} [callback] The callback called once changing state is finished or is canceled.
*/
}, {
key: "changeState",
value: function changeState() {
var _this = this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var state = typeof args[0] === 'string' ? args.shift() : undefined;
var detail = Object(args[0]) === args[0] && typeof args[0] !== 'function' ? args.shift() : undefined;
var callback = typeof args[0] === 'function' ? args.shift() : undefined;
if (typeof this.shouldStateBeChanged === 'function' && !this.shouldStateBeChanged(state, detail)) {
if (callback) {
callback(null, true);
}
return;
}
var data = {
group: detail && detail.group,
state: state
};
var eventNameSuffix = [data.group, state].filter(Boolean).join('-').split('-') // Group or state may contain hyphen
.map(function (item) {
return item[0].toUpperCase() + item.substr(1);
}).join('');
var eventStart = new CustomEvent(this.options["eventBefore".concat(eventNameSuffix)], {
bubbles: true,
cancelable: true,
detail: detail
});
var fireOnNode = detail && detail.delegatorNode || this.element;
var canceled = !fireOnNode.dispatchEvent(eventStart);
if (canceled) {
if (callback) {
var error = new Error("Changing state (".concat(JSON.stringify(data), ") has been canceled."));
error.canceled = true;
callback(error);
}
} else {
var changeStateArgs = [state, detail].filter(Boolean);
this._changeState.apply(this, _toConsumableArray(changeStateArgs).concat([function () {
fireOnNode.dispatchEvent(new CustomEvent(_this.options["eventAfter".concat(eventNameSuffix)], {
bubbles: true,
cancelable: true,
detail: detail
}));
if (callback) {
callback();
}
}]));
}
}
/* eslint-enable jsdoc/check-param-names */
/**
* Tests if change in state should happen or not.
* Classes inheriting {@link EventedState `EventedState`} should override this function.
* @function EventedState#shouldStateBeChanged
* @param {string} [state] The new state. Can be an omitted, which means toggling.
* @param {Object} [detail]
* The object that should be put to event details that is fired before/after changing state.
* Can have a `group` property, which specifies what state to be changed.
* @returns {boolean}
* `false` if change in state shouldn't happen, e.g. when the given new state is the same as the current one.
*/
}]);
return EventedState;
}(ToMix);
/**
* The callback called once changing state is finished or is canceled.
* @callback EventedState~changeStateCallback
* @param {Error} error
* An error object with `true` in its `canceled` property if changing state is canceled.
* Cancellation happens if the handler of a custom event, that is fired before changing state happens,
* calls `.preventDefault()` against the event.
* @param {boolean} keptState
* `true` if the call to {@link EventedState#changeState `.changeState()`} didn't cause actual change in state.
*/
return EventedState;
}
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @param {Event} event The event.
* @param {string} selector The selector.
* @returns {Element}
* The closest ancestor of the event target (or the event target itself) which matches the selectors given in parameter.
*/
function eventMatches(event, selector) {
// <svg> in IE does not have `Element#msMatchesSelector()` (that should be copied to `Element#matches()` by a polyfill).
// Also a weird behavior is seen in IE where DOM tree seems broken when `event.target` is on <svg>.
// Therefore this function simply returns `undefined` when `event.target` is on <svg>.
var target = event.target,
currentTarget = event.currentTarget;
if (typeof target.matches === 'function') {
if (target.matches(selector)) {
// If event target itself matches the given selector, return it
return target;
}
if (target.matches("".concat(selector, " *"))) {
var closest = target.closest(selector);
if ((currentTarget.nodeType === Node.DOCUMENT_NODE ? currentTarget.documentElement : currentTarget).contains(closest)) {
return closest;
}
}
}
return undefined;
}
var toArray = function toArray(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
var FileUploader =
/*#__PURE__*/
function (_mixin) {
_inherits(FileUploader, _mixin);
/**
* File uploader.
* @extends CreateComponent
* @extends InitComponentBySearch
* @extends eventedState
* @extends Handles
* @param {HTMLElement} element The element working as a file uploader.
* @param {object} [options] The component options. See static options.
*/
function FileUploader(element) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, FileUploader);
_this = _possibleConstructorReturn(this, _getPrototypeOf(FileUploader).call(this, element, options));
_defineProperty(_assertThisInitialized(_this), "_changeState", function (state, detail, callback) {
if (state === 'delete-filename-fileuploader') {
_this.container.removeChild(detail.filenameElement);
}
if (typeof callback === 'function') {
callback();
}
});
_defineProperty(_assertThisInitialized(_this), "_handleDeleteButton", function (evt) {
var target = eventMatches(evt, "[data-for=".concat(_this.inputId, "]"));
if (target) {
_this._changeState('delete-filename-fileuploader', {
initialEvt: evt,
filenameElement: target.parentNode
});
}
});
_this.input = _this.element.querySelector(_this.options.selectorInput);
_this.container = _this.element.querySelector(_this.options.selectorContainer);
if (!_this.input) {
throw new TypeError('Cannot find the file input box.');
}
if (!_this.container) {
throw new TypeError('Cannot find the file names container.');
}
_this.inputId = _this.input.getAttribute('id');
_this.manage(on(_this.input, 'change', function () {
return _this._displayFilenames();
}));
_this.manage(on(_this.container, 'click', _this._handleDeleteButton));
return _this;
}
_createClass(FileUploader, [{
key: "_filenamesHTML",
value: function _filenamesHTML(name, id) {
return "<span class=\"".concat(this.options.classSelectedFile, "\">\n <p class=\"").concat(this.options.classFileName, "\">").concat(name, "</p>\n <span data-for=\"").concat(id, "\" class=\"").concat(this.options.classStateContainer, "\"></span>\n </span>");
}
}, {
key: "_uploadHTML",
value: function _uploadHTML() {
return "\n <div data-loading class=\"".concat(this.options.classLoading, "\">\n <svg class=\"").concat(this.options.classLoadingSvg, "\" viewBox=\"-42 -42 84 84\">\n <circle cx=\"0\" cy=\"0\" r=\"37.5\" />\n </svg>\n </div>");
}
}, {
key: "_closeButtonHTML",
value: function _closeButtonHTML() {
return "\n <button class=\"".concat(this.options.classFileClose, "\" type=\"button\" aria-label=\"close\">\n <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" width=\"16\" height=\"16\">\n <path fill=\"#231F20\" d=\"M12 4.7l-.7-.7L8 7.3 4.7 4l-.7.7L7.3 8 4 11.3l.7.7L8 8.7l3.3 3.3.7-.7L8.7 8z\"/>\n </svg>\n </button>");
}
}, {
key: "_checkmarkHTML",
value: function _checkmarkHTML() {
return "\n <svg class=\"".concat(this.options.classFileComplete, "\" viewBox=\"0 0 16 16\" fill-rule=\"evenodd\" width=\"16\" height=\"16\">\n <path d=\"M8 0C3.6 0 0 3.6 0 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8zM6.7 11.5L3.4 8.1l1.4-1.4 1.9 1.9 4.1-4.1 1.4 1.4-5.5 5.6z\"/>\n </svg>");
}
}, {
key: "_getStateContainers",
value: function _getStateContainers() {
var stateContainers = toArray(this.element.querySelectorAll("[data-for=".concat(this.inputId, "]")));
if (stateContainers.length === 0) {
throw new TypeError('State container elements not found; invoke _displayFilenames() first');
}
if (stateContainers[0].dataset.for !== this.inputId) {
throw new TypeError('File input id must equal [data-for] attribute');
}
return stateContainers;
}
/**
* Inject selected files into DOM. Invoked on change event.
*/
}, {
key: "_displayFilenames",
value: function _displayFilenames() {
var _this2 = this;
var container = this.element.querySelector(this.options.selectorContainer);
var HTMLString = toArray(this.input.files).map(function (file) {
return _this2._filenamesHTML(file.name, _this2.inputId);
}).join('');
container.insertAdjacentHTML('afterbegin', HTMLString);
}
}, {
key: "_removeState",
value: function _removeState(element) {
if (!element || element.nodeType !== Node.ELEMENT_NODE) {
throw new TypeError('DOM element should be given to initialize this widget.');
}
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
}, {
key: "_handleStateChange",
value: function _handleStateChange(elements, selectIndex, html) {
var _this3 = this;
if (selectIndex === undefined) {
elements.forEach(function (el) {
_this3._removeState(el);
el.insertAdjacentHTML('beforeend', html);
});
} else {
elements.forEach(function (el, index) {
if (index === selectIndex) {
_this3._removeState(el);
el.insertAdjacentHTML('beforeend', html);
}
});
}
}
/**
* Handles delete button.
* @param {Event} evt The event triggering this action.
* @private
*/
}, {
key: "setState",
value: function setState(state, selectIndex) {
var stateContainers = this._getStateContainers();
if (state === 'edit') {
this._handleStateChange(stateContainers, selectIndex, this._closeButtonHTML());
}
if (state === 'upload') {
this._handleStateChange(stateContainers, selectIndex, this._uploadHTML());
}
if (state === 'complete') {
this._handleStateChange(stateContainers, selectIndex, this._checkmarkHTML());
}
}
/**
* The map associating DOM element and file uploader instance.
* @member FileUploader.components
* @type {WeakMap}
*/
}], [{
key: "options",
get: function get() {
var prefix = settings_1.prefix;
return {
selectorInit: '[data-file]',
selectorInput: "input[type=\"file\"].".concat(prefix, "--file-input"),
selectorContainer: '[data-file-container]',
selectorCloseButton: ".".concat(prefix, "--file-close"),
classLoading: "".concat(prefix, "--loading"),
classLoadingSvg: "".concat(prefix, "--loading__svg"),
classFileName: "".concat(prefix, "--file-filename"),
classFileClose: "".concat(prefix, "--file-close"),
classFileComplete: "".concat(prefix, "--file-complete"),
classSelectedFile: "".concat(prefix, "--file__selected-file"),
classStateContainer: "".concat(prefix, "--file__state-container"),
eventBeforeDeleteFilenameFileuploader: 'fileuploader-before-delete-filename',
eventAfterDeleteFilenameFileuploader: 'fileuploader-after-delete-filename'
};
}
}]);
return FileUploader;
}(mixin(createComponent, initComponentBySearch, eventedState, handles));
_defineProperty(FileUploader, "components",
/* #__PURE_CLASS_PROPERTY__ */
new WeakMap());
var toArray$1 = function toArray(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
var ContentSwitcher =
/*#__PURE__*/
function (_mixin) {
_inherits(ContentSwitcher, _mixin);
/**
* Set of content switcher buttons.
* @extends CreateComponent
* @extends InitComponentBySearch
* @extends EventedState
* @extends Handles
* @param {HTMLElement} element The element working as a set of content switcher buttons.
* @param {object} [options] The component options.
* @param {string} [options.selectorButton] The CSS selector to find switcher buttons.
* @param {string} [options.selectorButtonSelected] The CSS selector to find the selected switcher button.
* @param {string} [options.classActive] The CSS class for switcher button's selected state.
* @param {string} [options.eventBeforeSelected]
* The name of the custom event fired before a switcher button is selected.
* Cancellation of this event stops selection of content switcher button.
* @param {string} [options.eventAfterSelected] The name of the custom event fired after a switcher button is selected.
*/
function ContentSwitcher(element, options) {
var _this;
_classCallCheck(this, ContentSwitcher);
_this = _possibleConstructorReturn(this, _getPrototypeOf(ContentSwitcher).call(this, element, options));
_this.manage(on(_this.element, 'click', function (event) {
_this._handleClick(event);
}));
return _this;
}
/**
* Handles click on content switcher button set.
* If the click is on a content switcher button, activates it.
* @param {Event} event The event triggering this method.
*/
_createClass(ContentSwitcher, [{
key: "_handleClick",
value: function _handleClick(event) {
var button = eventMatches(event, this.options.selectorButton);
if (button) {
this.changeState({
group: 'selected',
item: button,
launchingEvent: event
});
}
}
/**
* Internal method of {@linkcode ContentSwitcher#setActive .setActive()}, to select a content switcher button.
* @private
* @param {object} detail The detail of the event trigging this action.
* @param {HTMLElement} detail.item The button to be selected.
* @param {Function} callback Callback called when change in state completes.
*/
}, {
key: "_changeState",
value: function _changeState(_ref, callback) {
var _this2 = this;
var item = _ref.item;
// `options.selectorLink` is not defined in this class itself, code here primary is for inherited classes
var itemLink = item.querySelector(this.options.selectorLink);
if (itemLink) {
toArray$1(this.element.querySelectorAll(this.options.selectorLink)).forEach(function (link) {
if (link !== itemLink) {
link.setAttribute('aria-selected', 'false');
}
});
itemLink.setAttribute('aria-selected', 'true');
}
var selectorButtons = toArray$1(this.element.querySelectorAll(this.options.selectorButton));
selectorButtons.forEach(function (button) {
if (button !== item) {
button.setAttribute('aria-selected', false);
button.classList.toggle(_this2.options.classActive, false);
toArray$1(button.ownerDocument.querySelectorAll(button.dataset.target)).forEach(function (element) {
element.setAttribute('hidden', '');
element.setAttribute('aria-hidden', 'true');
});
}
});
item.classList.toggle(this.options.classActive, true);
item.setAttribute('aria-selected', true);
toArray$1(item.ownerDocument.querySelectorAll(item.dataset.target)).forEach(function (element) {
element.removeAttribute('hidden');
element.setAttribute('aria-hidden', 'false');
});
if (callback) {
callback();
}
}
/**
* Selects a content switcher button.
* If the selected button has `data-target` attribute, DOM elements it points to as a CSS selector will be shown.
* DOM elements associated with unselected buttons in the same way will be hidden.
* @param {HTMLElement} item The button to be selected.
* @param {ChangeState~callback} callback The callback is called once selection is finished
* or is canceled. Will only invoke callback if it's passed in.
*/
}, {
key: "setActive",
value: function setActive(item, callback) {
this.changeState({
group: 'selected',
item: item
}, function (error) {
if (error) {
if (callback) {
callback(Object.assign(error, {
item: item
}));
}
} else if (callback) {
callback(null, item);
}
});
}
/**
* The map associating DOM element and content switcher set instance.
* @member ContentSwitcher.components
* @type {WeakMap}
*/
}], [{
key: "options",
/**
* The component options.
* If `options` is specified in the constructor,
* {@linkcode ContentSwitcher.create .create()}, or {@linkcode ContentSwitcher.init .init()},
* properties in this object are overriden for the instance being create and how {@linkcode ContentSwitcher.init .init()} works.
* @member ContentSwitcher.options
* @type {object}
* @property {string} selectorInit The CSS selector to find content switcher button set.
* @property {string} [selectorButton] The CSS selector to find switcher buttons.
* @property {string} [selectorButtonSelected] The CSS selector to find the selected switcher button.
* @property {string} [classActive] The CSS class for switcher button's selected state.
* @property {string} [eventBeforeSelected]
* The name of the custom event fired before a switcher button is selected.
* Cancellation of this event stops selection of content switcher button.
* @property {string} [eventAfterSelected] The name of the custom event fired after a switcher button is selected.
*/
get: function get() {
var prefix = settings_1.prefix;
return {
selectorInit: '[data-content-switcher]',
selectorButton: "input[type=\"radio\"], .".concat(prefix, "--content-switcher-btn"),
classActive: "".concat(prefix, "--content-switcher--selected"),
eventBeforeSelected: 'content-switcher-beingselected',
eventAfterSelected: 'content-switcher-selected'
};
}
}]);
return ContentSwitcher;
}(mixin(createComponent, initComponentBySearch, eventedState, handles));
_defineProperty(ContentSwitcher, "components",
/* #__PURE_CLASS_PROPERTY__ */
new WeakMap());
var toArray$2 = function toArray(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
var Tab =
/*#__PURE__*/
function (_ContentSwitcher) {
_inherits(Tab, _ContentSwitcher);
/**
* Container of tabs.
* @extends ContentSwitcher
* @param {HTMLElement} element The element working as a container of tabs.
* @param {object} [options] The component options.
* @param {string} [options.selectorMenu] The CSS selector to find the drop down menu used in narrow mode.
* @param {string} [options.selectorTrigger] The CSS selector to find the button to open the drop down menu used in narrow mode.
* @param {string} [options.selectorTriggerText]
* The CSS selector to find the element used in narrow mode showing the selected tab item.
* @param {string} [options.selectorButton] The CSS selector to find tab containers.
* @param {string} [options.selectorButtonSelected] The CSS selector to find the selected tab.
* @param {string} [options.selectorLink] The CSS selector to find the links in tabs.
* @param {string} [options.classActive] The CSS class for tab's selected state.
* @param {string} [options.classHidden] The CSS class for the drop down menu's hidden state used in narrow mode.
* @param {string} [options.eventBeforeSelected]
* The name of the custom event fired before a tab is selected.
* Cancellation of this event stops selection of tab.
* @param {string} [options.eventAfterSelected] The name of the custom event fired after a tab is selected.
*/
function Tab(element, options) {
var _this;
_classCallCheck(this, Tab);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Tab).call(this, element, options));
_this.manage(on(_this.element, 'keydown', function (event) {
_this._handleKeyDown(event);
}));
_this.manage(on(_this.element.ownerDocument, 'click', function (event) {
_this._handleDocumentClick(event);
}));
var selected = _this.element.querySelector(_this.options.selectorButtonSelected);
if (selected) {
_this._updateTriggerText(selected);
}
return _this;
}
/**
* Internal method of {@linkcode Tab#setActive .setActive()}, to select a tab item.
* @private
* @param {object} detail The detail of the event trigging this action.
* @param {HTMLElement} detail.item The tab item to be selected.
* @param {Function} callback Callback called when change in state completes.
*/
_createClass(Tab, [{
key: "_changeState",
value: function _changeState(detail, callback) {
var _this2 = this;
_get(_getPrototypeOf(Tab.prototype), "_changeState", this).call(this, detail, function (error) {
if (!error) {
_this2._updateTriggerText(detail.item);
}
for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
callback.apply(void 0, [error].concat(data));
});
}
/**
* Handles click on tab container.
* * If the click is on a tab, activates it.
* * If the click is on the button to open the drop down menu, does so.
* @param {Event} event The event triggering this method.
*/
}, {
key: "_handleClick",
value: function _handleClick(event) {
var button = eventMatches(event, this.options.selectorButton);
var trigger = eventMatches(event, this.options.selectorTrigger);
if (button && !button.classList.contains(this.options.classButtonDisabled)) {
_get(_getPrototypeOf(Tab.prototype), "_handleClick", this).call(this, event);
this._upd