UNPKG

carbon-components

Version:

Carbon Components is a component library for IBM Cloud

1,479 lines (1,243 loc) • 473 kB
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. */ var settings = { prefix: 'bx' }; 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, 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(_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(_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(_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. */ /** * This file contains the list of the default values of compile-time feature flags. * * Build toolchain can replace variable here and/or the references * in order to apply non-default values to those feature flags. * * @example Render `foo` if `aFeatureFlag` is `true`, render `bar` otherwise. * // `my-component.config.js` * const { aFeatureFlag } = require('/path/to/feature-flags'); * ... * module.exports = { * variants: [ * { * name: 'default', * label: 'My component', * context: { * aFeatureFlag, * ... * }, * }, * ... * ], * }; * * // `my-component.hbs` * <div> * {{#if aFeatureFlag}} * foo * {{else}} * bar * {{/if}} * </div> * * @example Emit `foo` upon clicking on component's element if `aFeatureFlag` is `true`, emit `bar` otherwise. * import mixin from '/path/to/globals/js/misc/mixin'; * import createComponent from '/path/to/globals/js/mixins/create-component'; * import initComponentBySearch from '/path/to/globals/js/mixins/init-component-by-search'; * import handles from '/path/to/globals/js/mixins/handles'; * import on from '/path/to/globals/js/misc/on'; * * import { aFeatureFlag } from '/path/to/globals/js/feature-flags'; * * class MyClass extends mixin(createComponent, initComponentBySearch, handles) { * constructor(element, options) { * super(element, options); * this.manage( * on(this.element, 'click', () => { * console.log(aFeatureFlag ? 'foo' : 'bar'); * }) * ); * } * } */ var breakingChangesX = false; /** * 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-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 _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(); } }])); } } /** * 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(_assertThisInitialized(_this)), "_changeState", function (state, detail, callback) { if (state === 'delete-filename-fileuploader') { _this.container.removeChild(detail.filenameElement); } if (typeof callback === 'function') { callback(); } }); _defineProperty(_assertThisInitialized(_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 <svg class=\"".concat(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=\"".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()); /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function initComponentByEvent (ToMix) { /** * Mix-in class to instantiate components upon events. * @class InitComponentByEvent */ var InitComponentByEvent = /*#__PURE__*/ function (_ToMix) { _inherits(InitComponentByEvent, _ToMix); function InitComponentByEvent() { _classCallCheck(this, InitComponentByEvent); return _possibleConstructorReturn(this, _getPrototypeOf(InitComponentByEvent).apply(this, arguments)); } _createClass(InitComponentByEvent, null, [{ key: "init", /** * `true` suggests that this component is lazily initialized upon an action/event, etc. * @type {boolean} */ /** * 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 _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 { // 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 && !_this.components.has(element)) { var component = _this.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 ''; } }]); return InitComponentByEvent; }(ToMix); _defineProperty(InitComponentByEvent, "forLazyInit", /* #__PURE_CLASS_PROPERTY__ */ true); return InitComponentByEvent; } /** * @param {string} name The component name. * @returns {Function} A stub of removed component. */ var removedComponent = function removedComponent(name) { var _class, _temp; return _temp = _class = /*#__PURE__*/ function () { function _class() { _classCallCheck(this, _class); } _createClass(_class, null, [{ key: "create", value: function create() { } }, { key: "init", value: function init() { } }]); return _class; }(), _defineProperty(_class, "components", /* #__PURE_CLASS_PROPERTY__ */ new WeakMap()), _defineProperty(_class, "options", /* #__PURE_CLASS_PROPERTY__ */ {}), _temp; }; var FabButton = /*#__PURE__*/ 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) { var _this; _classCallCheck(this, FabButton); _this = _possibleConstructorReturn(this, _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} */ }]); return FabButton; }(mixin(createComponent, initComponentByEvent, handles)); _defineProperty(FabButton, "components", /* #__PURE_CLASS_PROPERTY__ */ new WeakMap()); _defineProperty(FabButton, "options", /* #__PURE_CLASS_PROPERTY__ */ { selectorInit: '[data-fab]', initEventNames: ['click'] }); var fab = !breakingChangesX ? FabButton : removedComponent('FabButton'); 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(t