carbon-components
Version:
The Carbon Design System is IBM’s open-source design system for products and experiences.
1,403 lines (1,172 loc) • 438 kB
JavaScript
var CarbonComponents = (function (exports) {
'use strict';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
/**
* 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 references 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"`.
* @property {string} [selectorFocusable]
* CSS selector that selects major nodes that are click focusable
* This property is identical to selectorTabbable with the exception of
* the `:not([tabindex='-1'])` pseudo class
*/
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 ",
selectorFocusable: "\n a[href], area[href], input:not([disabled]),\n button:not([disabled]),select:not([disabled]),\n textarea:not([disabled]),\n iframe, object, embed, *[tabindex], *[contenteditable=true]\n "
};
var settings_1 = settings;
var settings$1 = settings_1;
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
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 = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
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);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
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 _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
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
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 _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
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;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get() {
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(arguments.length < 3 ? target : receiver);
}
return desc.value;
};
}
return _get.apply(this, arguments);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_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 _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
/**
* 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 _createClass(_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);
var _super = _createSuper(CreateComponent);
/**
* 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's 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 = _super.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",
value:
/**
* Releases this component's instance from the associated element.
*/
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);
var _super = _createSuper(InitComponentBySearch);
function InitComponentBySearch() {
_classCallCheck(this, InitComponentBySearch);
return _super.apply(this, arguments);
}
_createClass(InitComponentBySearch, null, [{
key: "init",
value:
/**
* 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.
*/
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);
var _super = _createSuper(Handles);
function Handles() {
var _this;
_classCallCheck(this, Handles);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_defineProperty(_assertThisInitialized(_this), "handles", new Set());
return _this;
}
_createClass(Handles, [{
key: "manage",
value:
/**
* Manages the given handle.
* @param {Handle} handle The handle to manage.
* @returns {Handle} The given handle.
*/
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);
var _super = _createSuper(Checkbox);
/**
* 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 = _super.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",
get:
/**
* The component options.
* If `options` is specified in the constructor, {@linkcode Checkbox.create .create()}, or {@linkcode Checkbox.init .init()},
* properties in this object are overridden 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.
*/
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", new WeakMap());
_defineProperty(Checkbox, "stateChangeTypes", stateChangeTypes);
var Checkbox$1 = Checkbox;
/**
* 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);
var _super = _createSuper(EventedState);
function EventedState() {
_classCallCheck(this, EventedState);
return _super.apply(this, arguments);
}
_createClass(EventedState, [{
key: "_changeState",
value:
/* 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
*/
function _changeState() {
throw new Error('_changeState() should be overridden 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$b = function toArray(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
var FileUploader = /*#__PURE__*/function (_mixin) {
_inherits(FileUploader, _mixin);
var _super = _createSuper(FileUploader);
/**
* 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 = _super.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, _this.options.selectorCloseButton);
if (target) {
_this.changeState('delete-filename-fileuploader', {
initialEvt: evt,
filenameElement: target.closest(_this.options.selectorSelectedFile)
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleDragDrop", function (evt) {
var isOfSelf = _this.element.contains(evt.target); // In IE11 `evt.dataTransfer.types` is a `DOMStringList` instead of an array
if (Array.prototype.indexOf.call(evt.dataTransfer.types, 'Files') >= 0 && !eventMatches(evt, _this.options.selectorOtherDropContainers)) {
var inArea = isOfSelf && eventMatches(evt, _this.options.selectorDropContainer);
if (evt.type === 'dragover') {
evt.preventDefault();
var dropEffect = inArea ? 'copy' : 'none';
if (Array.isArray(evt.dataTransfer.types)) {
// IE11 throws a "permission denied" error accessing `.effectAllowed`
evt.dataTransfer.effectAllowed = dropEffect;
}
evt.dataTransfer.dropEffect = dropEffect;
_this.dropContainer.classList.toggle(_this.options.classDragOver, Boolean(inArea));
}
if (evt.type === 'dragleave') {
_this.dropContainer.classList.toggle(_this.options.classDragOver, false);
}
if (inArea && evt.type === 'drop') {
evt.preventDefault();
_this._displayFilenames(evt.dataTransfer.files);
_this.dropContainer.classList.remove(_this.options.classDragOver);
}
}
});
_this.input = _this.element.querySelector(_this.options.selectorInput);
_this.container = _this.element.querySelector(_this.options.selectorContainer);
_this.dropContainer = _this.element.querySelector(_this.options.selectorDropContainer);
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));
_this.manage(on(_this.element.ownerDocument, 'dragleave', _this._handleDragDrop));
_this.manage(on(_this.dropContainer, 'dragover', _this._handleDragDrop));
_this.manage(on(_this.dropContainer, 'drop', _this._handleDragDrop));
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 class=\"".concat(this.options.classLoadingAnimation, "\">\n <div data-inline-loading-spinner class=\"").concat(this.options.classLoading, "\">\n <svg class=\"").concat(this.options.classLoadingSvg, "\" viewBox=\"-75 -75 150 150\">\n <circle class=\"").concat(this.options.classLoadingBackground, "\" cx=\"0\" cy=\"0\" r=\"37.5\" />\n <circle class=\"").concat(this.options.classLoadingStroke, "\" cx=\"0\" cy=\"0\" r=\"37.5\" />\n </svg>\n </div>\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 focusable=\"false\"\n preserveAspectRatio=\"xMidYMid meet\"\n style=\"will-change: transform;\"\n xmlns=\"http://www.w3.org/2000/svg\"\n class=\"".concat(this.options.classFileComplete, "\"\n width=\"16\" height=\"16\" viewBox=\"0 0 16 16\"\n aria-hidden=\"true\">\n <path d=\"M8 1C4.1 1 1 4.1 1 8s3.1 7 7 7 7-3.1 7-7-3.1-7-7-7zM7 11L4.3 8.3l.9-.8L7 9.3l4-3.9.9.8L7 11z\"></path>\n <path d=\"M7 11L4.3 8.3l.9-.8L7 9.3l4-3.9.9.8L7 11z\" data-icon-path=\"inner-path\" opacity=\"0\"></path>\n </svg>\n ");
}
}, {
key: "_getStateContainers",
value: function _getStateContainers() {
var stateContainers = toArray$b(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.
* @param {File[]} files The files to upload.
*/
}, {
key: "_displayFilenames",
value: function _displayFilenames() {
var _this2 = this;
var files = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.input.files;
var container = this.element.querySelector(this.options.selectorContainer);
var HTMLString = toArray$b(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"),
selectorSelectedFile: ".".concat(prefix, "--file__selected-file"),
selectorDropContainer: "[data-file-drop-container]",
selectorOtherDropContainers: '[data-drop-container]',
classLoading: "".concat(prefix, "--loading ").concat(prefix, "--loading--small"),
classLoadingAnimation: "".concat(prefix, "--inline-loading__animation"),
classLoadingSvg: "".concat(prefix, "--loading__svg"),
classLoadingBackground: "".concat(prefix, "--loading__background"),
classLoadingStroke: "".concat(prefix, "--loading__stroke"),
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"),
classDragOver: "".concat(prefix, "--file__drop-container--drag-over"),
eventBeforeDeleteFilenameFileuploader: 'fileuploader-before-delete-filename',
eventAfterDeleteFilenameFileuploader: 'fileuploader-after-delete-filename'
};
}
}]);
return FileUploader;
}(mixin(createComponent, initComponentBySearch, eventedState, handles));
_defineProperty(FileUploader, "components", new WeakMap());
var FileUploader$1 = FileUploader;
var toArray$a = function toArray(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
var ContentSwitcher = /*#__PURE__*/function (_mixin) {
_inherits(ContentSwitcher, _mixin);
var _super = _createSuper(ContentSwitcher);
/**
* 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 = _super.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$a(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$a(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$a(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$a(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",
get:
/**
* The component options.
* If `options` is specified in the constructor,
* {@linkcode ContentSwitcher.create .create()}, or {@linkcode ContentSwitcher.init .init()},
* props in this object are overridden for the instance being created 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.
*/
function get() {
var prefix = settings$1.prefix;
return {
selectorInit: '[