carbon-components
Version:
Carbon Components is a component library for IBM Cloud
1,508 lines (1,258 loc) • 343 kB
JavaScript
var CarbonComponents = (function (exports) {
'use strict';
/**
* 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.
*/
var settings = {
prefix: 'bx'
};
var asyncGenerator = function () {
function AwaitValue(value) {
this.value = value;
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function (resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
if (value instanceof AwaitValue) {
Promise.resolve(value.value).then(function (arg) {
resume("next", arg);
}, function (arg) {
resume("throw", arg);
});
} else {
settle(result.done ? "return" : "normal", result.value);
}
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch (type) {
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
return this;
};
}
AsyncGenerator.prototype.next = function (arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function (arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function (arg) {
return this._invoke("return", arg);
};
return {
wrap: function (fn) {
return function () {
return new AsyncGenerator(fn.apply(this, arguments));
};
},
await: function (value) {
return new AwaitValue(value);
}
};
}();
var classCallCheck = function (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;
};
}();
var defineProperty = function (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;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
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);
}
};
var inherits = function (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;
};
var possibleConstructorReturn = function (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 toConsumableArray = function (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);
}
};
/**
* @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 = Array(_len), _key = 0; _key < _len; _key++) {
mixinfns[_key] = arguments[_key];
}
return flatten(mixinfns).reduce(function (Class, mixinfn) {
return mixinfn(Class);
}, function () {
function _class() {
classCallCheck(this, _class);
}
return _class;
}());
}
var createComponent = function (ToMix) {
var CreateComponent = function (_ToMix) {
inherits(CreateComponent, _ToMix);
/**
* 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 options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, CreateComponent);
var _this = possibleConstructorReturn(this, (CreateComponent.__proto__ || Object.getPrototypeOf(CreateComponent)).call(this, element, options));
_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, _this);
return _this;
}
/**
* Instantiates this component of the given element.
* @param {HTMLElement} element The element.
*/
/**
* The component instances managed by this component.
* Releasing this component also releases the components in `this.children`.
* @type {Component[]}
*/
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;
};
var initComponentBySearch = function (ToMix) {
/**
* Mix-in class to instantiate components by searching for their root elements.
* @class InitComponentBySearch
*/
var InitComponentBySearch = function (_ToMix) {
inherits(InitComponentBySearch, _ToMix);
function InitComponentBySearch() {
classCallCheck(this, InitComponentBySearch);
return possibleConstructorReturn(this, (InitComponentBySearch.__proto__ || Object.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 _this2 = 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 {
[].concat(toConsumableArray(target.querySelectorAll(effectiveOptions.selectorInit))).forEach(function (element) {
return _this2.create(element, options);
});
}
}
}]);
return InitComponentBySearch;
}(ToMix);
return InitComponentBySearch;
};
var handles = function (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 = function (_ToMix) {
inherits(Handles, _ToMix);
function Handles() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Handles);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Handles.__proto__ || Object.getPrototypeOf(Handles)).call.apply(_ref, [this].concat(args))), _this), _this.handles = new Set(), _temp), possibleConstructorReturn(_this, _ret);
}
/**
* The handled managed by this component.
* Releasing this component releases the handles.
* @type {Set<Handle>}
*/
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(Handles.prototype.__proto__ || Object.getPrototypeOf(Handles.prototype), "release", this).call(this);
}
}]);
return Handles;
}(ToMix);
return Handles;
};
function on(element) {
for (var _len = arguments.length, args = 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 = 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) {
classCallCheck(this, Checkbox);
var _this = possibleConstructorReturn(this, (Checkbox.__proto__ || Object.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('bx--checkbox-label')) {
this.element.parentElement.setAttribute('data-contained-checkbox-state', '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('bx--checkbox-label')) {
this.element.parentElement.setAttribute('data-contained-checkbox-state', 'false');
}
}
}
}, {
key: '_handleFocus',
value: function _handleFocus() {
if (this.element.parentElement.classList.contains('bx--checkbox-label')) {
this.element.parentElement.classList.add('bx--checkbox-label__focus');
}
}
}, {
key: '_handleBlur',
value: function _handleBlur() {
if (this.element.parentElement.classList.contains('bx--checkbox-label')) {
this.element.parentElement.classList.remove('bx--checkbox-label__focus');
}
}
/**
* 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('[data-contained-checkbox-state]');
if (container) {
container.setAttribute('data-contained-checkbox-state', 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('[data-contained-checkbox-disabled]');
if (container) {
container.setAttribute('data-contained-checkbox-disabled', 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('bx--checkbox-label') && this.element.indeterminate === true) {
this.element.parentElement.setAttribute('data-contained-checkbox-state', 'mixed');
}
}
}, {
key: '_initCheckbox',
value: function _initCheckbox() {
if (this.element.checked === true) {
this.element.setAttribute('aria-checked', 'true');
}
if (this.element.parentElement.classList.contains('bx--checkbox-label') && this.element.checked) {
this.element.parentElement.setAttribute('data-contained-checkbox-state', 'true');
}
if (this.element.parentElement.classList.contains('bx--checkbox-label')) {
this.element.parentElement.setAttribute('data-contained-checkbox-disabled', 'false');
}
if (this.element.parentElement.classList.contains('bx--checkbox-label') && this.element.disabled) {
this.element.parentElement.setAttribute('data-contained-checkbox-disabled', 'true');
}
}
/**
* The map associating DOM element and copy button UI instance.
* @member Checkbox.components
* @type {WeakMap}
*/
/**
* 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.
*/
}]);
return Checkbox;
}(mixin(createComponent, initComponentBySearch, handles));
Checkbox.components = new WeakMap();
Checkbox.options = {
selectorInit: '.bx--checkbox'
};
Checkbox.stateChangeTypes = stateChangeTypes;
var eventedState = function (ToMix) {
/**
* Mix-in class to manage events associated with states.
* @class EventedState
*/
var EventedState = function (_ToMix) {
inherits(EventedState, _ToMix);
function EventedState() {
classCallCheck(this, EventedState);
return possibleConstructorReturn(this, (EventedState.__proto__ || Object.getPrototypeOf(EventedState)).apply(this, arguments));
}
createClass(EventedState, [{
key: '_changeState',
// eslint-disable-next-line 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.');
}
// eslint-disable-next-line jsdoc/check-param-names
/**
* 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 _this2 = this;
for (var _len = arguments.length, args = 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' + 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 (' + 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(_this2.options['eventAfter' + eventNameSuffix], {
bubbles: true,
cancelable: true,
detail: detail
}));
if (callback) {
callback();
}
}]));
}
}
/**
* 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;
};
/**
* @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;
} else if (target.matches(selector + ' *')) {
var closest = target.closest(selector);
if ((currentTarget.nodeType === Node.DOCUMENT_NODE ? currentTarget.documentElement : currentTarget).contains(closest)) {
return closest;
}
}
}
return undefined;
}
var FileUploader = 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 options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, FileUploader);
var _this = possibleConstructorReturn(this, (FileUploader.__proto__ || Object.getPrototypeOf(FileUploader)).call(this, element, options));
_this._changeState = function (state, detail, callback) {
if (state === 'delete-filename-fileuploader') {
_this.container.removeChild(detail.filenameElement);
}
if (typeof callback === 'function') {
callback();
}
};
_this._handleDeleteButton = function (evt) {
var target = eventMatches(evt, '[data-for=' + _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="' + this.options.classSelectedFile + '">\n <p class="' + this.options.classFileName + '">' + name + '</p>\n <span data-for="' + id + '" class="' + this.options.classStateContainer + '"></span>\n </span>';
}
}, {
key: '_uploadHTML',
value: function _uploadHTML() {
return '\n <div data-loading class="' + this.options.classLoading + '">\n <svg class="' + 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 <svg class="' + this.options.classFileClose + '" tabindex="0" 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-8zm3.5 10.1l-1.4 1.4L8\n 9.4l-2.1 2.1-1.4-1.4L6.6 8 4.5 5.9l1.4-1.4L8 6.6l2.1-2.1 1.4 1.4L9.4 8l2.1 2.1z" />\n </svg>';
}
}, {
key: '_checkmarkHTML',
value: function _checkmarkHTML() {
return '\n <svg class="' + 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 = [].concat(toConsumableArray(this.element.querySelectorAll('[data-for=' + 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 = [].concat(toConsumableArray(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$$1() {
var prefix = settings.prefix;
return {
selectorInit: '[data-file]',
selectorInput: 'input[type="file"].' + prefix + '--file-input',
selectorContainer: '[data-file-container]',
selectorCloseButton: '.' + prefix + '--file-close',
classLoading: prefix + '--loading',
classLoadingSvg: prefix + '--loading__svg',
classFileName: prefix + '--file-filename',
classFileClose: prefix + '--file-close',
classFileComplete: prefix + '--file-complete',
classSelectedFile: prefix + '--file__selected-file',
classStateContainer: prefix + '--file__state-container',
eventBeforeDeleteFilenameFileuploader: 'fileuploader-before-delete-filename',
eventAfterDeleteFilenameFileuploader: 'fileuploader-after-delete-filename'
};
}
}]);
return FileUploader;
}(mixin(createComponent, initComponentBySearch, eventedState, handles));
FileUploader.components = new WeakMap();
var initComponentByEvent = function (ToMix) {
/**
* Mix-in class to instantiate components upon events.
* @class InitComponentByEvent
*/
var InitComponentByEvent = function (_ToMix) {
inherits(InitComponentByEvent, _ToMix);
function InitComponentByEvent() {
classCallCheck(this, InitComponentByEvent);
return possibleConstructorReturn(this, (InitComponentByEvent.__proto__ || Object.getPrototypeOf(InitComponentByEvent)).apply(this, arguments));
}
createClass(InitComponentByEvent, null, [{
key: 'init',
/**
* Instantiates this component in the given element.
* If the given element indicates that it's an component of this class, instantiates it.
* Otherwise, instantiates this component by clicking on this component in the given node.
* @param {Node} target The DOM node to instantiate this component in. Should be a document or an element.
* @param {Object} [options] The component options.
* @param {string} [options.selectorInit] The CSS selector to find this component.
* @returns {Handle} The handle to remove the event listener to handle clicking.
*/
value: function init() {
var _this2 = 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 {
// To work around non-bubbling `focus` event, use `focusin` event instead of it's available, and "capture mode" otherwise
var hasFocusin = 'onfocusin' in (target.nodeType === Node.ELEMENT_NODE ? target.ownerDocument : target).defaultView;
var handles = effectiveOptions.initEventNames.map(function (name) {
var eventName = name === 'focus' && hasFocusin ? 'focusin' : name;
return on(target, eventName, function (event) {
var element = eventMatches(event, effectiveOptions.selectorInit);
// Instantiated components handles events by themselves
if (element && !_this2.components.has(element)) {
var component = _this2.create(element, options);
if (typeof component.createdByEvent === 'function') {
component.createdByEvent(event);
}
}
}, name === 'focus' && !hasFocusin);
});
return {
release: function release() {
for (var handle = handles.pop(); handle; handle = handles.pop()) {
handle.release();
}
}
};
}
return '';
}
/**
* `true` suggests that this component is lazily initialized upon an action/event, etc.
* @type {boolean}
*/
}]);
return InitComponentByEvent;
}(ToMix);
InitComponentByEvent.forLazyInit = true;
return InitComponentByEvent;
};
var FabButton = function (_mixin) {
inherits(FabButton, _mixin);
/**
* Floating action button.
* @extends CreateComponent
* @extends InitComponentByEvent
* @extends Handles
* @param {HTMLElement} element The element working as a floting action button.
*/
function FabButton(element) {
classCallCheck(this, FabButton);
var _this = possibleConstructorReturn(this, (FabButton.__proto__ || Object.getPrototypeOf(FabButton)).call(this, element));
_this.manage(on(element, 'click', function (event) {
_this.toggle(event);
}));
return _this;
}
/**
* A method called when this widget is created upon clicking.
* @param {Event} event The event triggering the creation.
*/
createClass(FabButton, [{
key: 'createdByEvent',
value: function createdByEvent(event) {
this.toggle(event);
}
/**
* Toggles this floating action button.
* @param {Event} event The event triggering this method.
*/
}, {
key: 'toggle',
value: function toggle(event) {
if (this.element.tagName === 'A') {
event.preventDefault();
}
if (this.element.dataset.state === 'closed') {
this.element.dataset.state = 'open';
} else {
this.element.dataset.state = 'closed';
}
}
/**
* Instantiates floating action button of the given element.
* @param {HTMLElement} element The element.
*/
}], [{
key: 'create',
value: function create(element) {
return this.components.get(element) || new this(element);
}
/**
* The map associating DOM element and floating action button instance.
* @member FabButton.components
* @type {WeakMap}
*/
/**
* The component options.
* If `options` is specified in the constructor, {@linkcode FabButton.create .create()}, or {@linkcode FabButton.init .init()},
* properties in this object are overriden for the instance being create and how {@linkcode FabButton.init .init()} works.
* @member FabButton.options
* @type {Object}
* @property {string} selectorInit The CSS selector to find floating action buttons.
*/
}]);
return FabButton;
}(mixin(createComponent, initComponentByEvent, handles));
FabButton.components = new WeakMap();
FabButton.options = {
selectorInit: '[data-fab]',
initEventNames: ['click']
};
var ContentSwitcher = 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) {
classCallCheck(this, ContentSwitcher);
var _this = possibleConstructorReturn(this, (ContentSwitcher.__proto__ || Object.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(detail, callback) {
var _this2 = this;
var item = detail.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) {
[].concat(toConsumableArray(this.element.querySelectorAll(this.options.selectorLink))).forEach(function (link) {
if (link !== itemLink) {
link.setAttribute('aria-selected', 'false');
}
});
itemLink.setAttribute('aria-selected', 'true');
}
var selectorButtons = [].concat(toConsumableArray(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);
[].concat(toConsumableArray(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);
[].concat(toConsumableArray(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$$1() {
var prefix = settings.prefix;
return {
selectorInit: '[data-content-switcher]',
selectorButton: 'input[type="radio"], .' + prefix + '--content-switcher-btn',
classActive: prefix + '--content-switcher--selected',
eventBeforeSelected: 'content-switcher-beingselected',
eventAfterSelected: 'content-switcher-selected'
};
}
}]);
return ContentSwitcher;
}(mixin(createComponent, initComponentBySearch, eventedState, handles));
ContentSwitcher.components = new WeakMap();
var Tab = 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) {
classCallCheck(this, Tab);
var _this = possibleConstructorReturn(this, (Tab.__proto__ || Object.getPrototypeOf(Tab)).call(this, element, options));
_this.manage(on(_this.element, 'keydown', function (event) {
_this._handleKeyDown(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(Tab.prototype.__proto__ || Object.getPrototypeOf(Tab.prototype), '_changeState', this).call(this, detail, function (error) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
if (!error) {
_this2._updateTriggerText(detail.item);
}
callback.apply(undefined, [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) {
get(Tab.prototype.__proto__ || Object.getPrototypeOf(Tab.prototype), '_handleClick', this).call(this, event);
this._updateMenuState(false);
}
if (trigger) {
this._updateMenuState();
}
}
/**
* Handles arrow keys on tab container.
* * Left keys are used to go to previous tab.
* * Right keys are used to go to next tab.
* @param {Event} event The event triggering this method.
*/
}, {
key: '_handleKeyDown',
value: function _handleKeyDown(event) {
var _this3 = this;
var triggerNode = eventMatches(event, this.options.selectorTrigger);
if (triggerNode) {
if (event.which === 13) {
this._updateMenuState();
}
return;
}
var direction = {
37: this.constructor.NAVIGATE.BACKWARD,
39: this