carbon-custom-elements
Version:
A Carbon Design System variant that's as easy to use as native HTML elements, with no framework tax, no framework silo.
421 lines (361 loc) • 23.9 kB
JavaScript
let _ = t => t,
_t,
_t2;
function _decorate(decorators, factory, superClass, mixins) { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); }
function _getDecoratorsApi() { _getDecoratorsApi = function () { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], initializeInstanceElements: function (O, elements) { ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, initializeClassElements: function (F, elements) { var proto = F.prototype; ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { var placement = element.placement; if (element.kind === kind && (placement === "static" || placement === "prototype")) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, defineClassElement: function (receiver, element) { var descriptor = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver) }; } Object.defineProperty(receiver, element.key, descriptor); }, decorateClass: function (elements, decorators) { var newElements = []; var finishers = []; var placements = { static: [], prototype: [], own: [] }; elements.forEach(function (element) { this.addElementPlacement(element, placements); }, this); elements.forEach(function (element) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras = this.decorateElement(element, placements); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result = this.decorateConstructor(newElements, decorators); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, addElementPlacement: function (element, placements, silent) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, decorateElement: function (element, placements) { var extras = []; var finishers = []; for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject = this.fromElementDescriptor(element); var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, decorateConstructor: function (elements, decorators) { var finishers = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj = this.fromClassDescriptor(elements); var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { throw new TypeError("Duplicated element (" + elements[j].key + ")"); } } } } } return { elements: elements, finishers: finishers }; }, fromElementDescriptor: function (element) { var obj = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, toElementDescriptors: function (elementObjects) { if (elementObjects === undefined) return; return _toArray(elementObjects).map(function (elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, toElementDescriptor: function (elementObject) { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); } var key = _toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if (placement !== "static" && placement !== "prototype" && placement !== "own") { throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); } var descriptor = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor) }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function (elementObject) { var element = this.toElementDescriptor(elementObject); var finisher = _optionalCallableProperty(elementObject, "finisher"); var extras = this.toElementDescriptors(elementObject.extras); return { element: element, finisher: finisher, extras: extras }; }, fromClassDescriptor: function (elements) { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this) }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, toClassDescriptor: function (obj) { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, runClassFinishers: function (constructor, finishers) { for (var i = 0; i < finishers.length; i++) { var newConstructor = (0, finishers[i])(constructor); if (newConstructor !== undefined) { if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function (obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; }
function _createElementDescriptor(def) { var key = _toPropertyKey(def.key); var descriptor; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; }
function _coalesceGetterSetter(element, other) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } }
function _coalesceClassElements(elements) { var newElements = []; var isSameElement = function isSameElement(other) { return other.kind === "method" && other.key === element.key && other.placement === element.placement; }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var other; if (element.kind === "method" && (other = newElements.find(isSameElement))) { if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; }
function _hasDecorators(element) { return element.decorators && element.decorators.length; }
function _isDataDescriptor(desc) { return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); }
function _optionalCallableProperty(obj, name) { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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 _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
/**
* @license
*
* Copyright IBM Corp. 2019, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import settings from 'carbon-components/es/globals/js/settings';
import { html, property, query, customElement } from 'lit-element';
import Close16 from "../../icons/close/16";
import { findIndex, forEach } from '../../globals/internal/collection-helpers';
import BXDropdown, { DROPDOWN_KEYBOARD_ACTION } from '../dropdown/dropdown';
import styles from "./combo-box.css.js";
export { DROPDOWN_COLOR_SCHEME, DROPDOWN_SIZE, DROPDOWN_TYPE } from '../dropdown/dropdown';
const {
prefix
} = settings;
/**
* Combo box.
* @element bx-combo-box
* @fires bx-combo-box-beingselected
* The custom event fired before a combo box item is selected upon a user gesture.
* Cancellation of this event stops changing the user-initiated selection.
* @fires bx-combo-box-selected - The custom event fired after a a combo box item is selected upon a user gesture.
*/
let BXComboBox = _decorate([customElement(`${prefix}-combo-box`)], function (_initialize, _BXDropdown) {
class BXComboBox extends _BXDropdown {
constructor(...args) {
super(...args);
_initialize(this);
}
}
return {
F: BXComboBox,
d: [{
kind: "field",
key: "_filterInputValue",
value() {
return '';
}
}, {
kind: "field",
key: "_shouldTriggerBeFocusable",
value() {
return false;
}
}, {
kind: "field",
decorators: [query('#selection-button')],
key: "_selectionButtonNode",
value: void 0
}, {
kind: "field",
decorators: [query('input')],
key: "_filterInputNode",
value: void 0
}, {
kind: "method",
key: "_testItemWithQueryText",
value:
/**
* The text content that should be set to the `<input>` for filtering.
*/
/**
* The selection button.
*/
/**
* The `<input>` for filtering.
*/
/**
* @param item A combo box item.
* @returns `true` if the given combo box item matches the query text user types.
*/
function _testItemWithQueryText(item) {
return (this.itemMatches || this._defaultItemMatches)(item, this._filterInputNode.value);
}
/* eslint-disable class-methods-use-this */
/**
* The default item matching callback.
* @param item The combo box item.
* @param queryText The query text user types.
* @returns `true` if the given combo box item matches the given query text.
*/
}, {
kind: "method",
key: "_defaultItemMatches",
value: function _defaultItemMatches(item, queryText) {
return item.textContent.toLowerCase().indexOf(queryText.toLowerCase()) >= 0;
}
/* eslint-enable class-methods-use-this */
/**
* Handles `input` event on the `<input>` for filtering.
*/
}, {
kind: "method",
key: "_handleInput",
value: function _handleInput() {
const items = this.querySelectorAll(this.constructor.selectorItem);
const index = !this._filterInputNode.value ? -1 : findIndex(items, this._testItemWithQueryText, this);
forEach(items, (item, i) => {
item.highlighted = i === index;
});
const {
_filterInputNode: filterInput
} = this;
this._filterInputValue = !filterInput ? '' : filterInput.value;
this.open = true;
this.requestUpdate(); // If the only change is to `_filterInputValue`, auto-update doesn't happen
}
}, {
kind: "method",
key: "_handleClickInner",
value: function _handleClickInner(event) {
var _this$_selectionButto;
if ((_this$_selectionButto = this._selectionButtonNode) === null || _this$_selectionButto === void 0 ? void 0 : _this$_selectionButto.contains(event.target)) {
this._handleUserInitiatedClearInput();
} else {
_get(_getPrototypeOf(BXComboBox.prototype), "_handleClickInner", this).call(this, event);
}
}
}, {
kind: "method",
key: "_handleKeypressInner",
value: function _handleKeypressInner(event) {
var _this$_selectionButto2;
const {
key
} = event;
const action = this.constructor.getAction(key);
const {
TRIGGERING
} = DROPDOWN_KEYBOARD_ACTION;
if (((_this$_selectionButto2 = this._selectionButtonNode) === null || _this$_selectionButto2 === void 0 ? void 0 : _this$_selectionButto2.contains(event.target)) && ( // Space key should be handled by `<input>` unless "clear selection" button has focus
action === TRIGGERING || key === ' ')) {
this._handleUserInitiatedClearInput();
} else {
_get(_getPrototypeOf(BXComboBox.prototype), "_handleKeypressInner", this).call(this, event);
}
}
/**
* Handles user-initiated clearing the `<input>` for filtering.
*/
}, {
kind: "method",
key: "_handleUserInitiatedClearInput",
value: function _handleUserInitiatedClearInput() {
forEach(this.querySelectorAll(this.constructor.selectorItem), item => {
item.highlighted = false;
});
this._filterInputValue = '';
this._filterInputNode.focus();
this.open = false;
this.requestUpdate();
}
}, {
kind: "method",
key: "_handleUserInitiatedSelectItem",
value: function _handleUserInitiatedSelectItem(item) {
if (item && !this._selectionShouldChange(item)) {
// Escape hatch for `shouldUpdate()` logic that updates `._filterInputValue()` when selection changes,
// given we want to update the `<input>` and close the dropdown even if selection doesn't update.
// Use case:
// 1. Select the 2nd item in combo box drop down
// 2. Type some text in the `<input>`
// 3. Re-select the 2nd item in combo box drop down,
// the `<input>` has to updated with the 2nd item and the dropdown should be closed,
// even if there is no change in the selected value
this._filterInputValue = item.textContent || '';
this.open = false;
this.requestUpdate();
}
_get(_getPrototypeOf(BXComboBox.prototype), "_handleUserInitiatedSelectItem", this).call(this, item);
}
}, {
kind: "method",
key: "_renderTriggerContent",
value: function _renderTriggerContent() {
const {
disabled,
inputLabel,
triggerContent,
_filterInputValue: filterInputValue,
_handleInput: handleInput
} = this;
return html(_t || (_t = _`
<input
id="trigger-label"
class="${0}--text-input"
?disabled=${0}
placeholder="${0}"
.value=${0}
role="combobox"
aria-label="${0}"
aria-controls="menu-body"
aria-autocomplete="list"
=${0}
/>
`), prefix, disabled, triggerContent, filterInputValue, inputLabel, handleInput);
}
}, {
kind: "method",
key: "_renderFollowingTriggerContent",
value: function _renderFollowingTriggerContent() {
const {
clearSelectionLabel,
_filterInputValue: filterInputValue
} = this;
return filterInputValue.length === 0 ? undefined : html(_t2 || (_t2 = _`
<div
id="selection-button"
role="button"
class="${0}--list-box__selection"
tabindex="0"
title="${0}"
>
${0}
</div>
`), prefix, clearSelectionLabel, Close16({
'aria-label': clearSelectionLabel
}));
}
/**
* The `aria-label` attribute for the icon to clear selection.
*/
}, {
kind: "field",
decorators: [property({
attribute: 'clear-selection-label'
})],
key: "clearSelectionLabel",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
attribute: 'input-label'
})],
key: "inputLabel",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
attribute: false
})],
key: "itemMatches",
value: void 0
}, {
kind: "method",
key: "shouldUpdate",
value:
/**
* The `aria-label` attribute for the `<input>` for filtering.
*/
/**
* The custom item matching callback.
*/
function shouldUpdate(changedProperties) {
_get(_getPrototypeOf(BXComboBox.prototype), "shouldUpdate", this).call(this, changedProperties);
const {
_selectedItemContent: selectedItemContent
} = this;
if (selectedItemContent && changedProperties.has('value')) {
this._filterInputValue = (selectedItemContent === null || selectedItemContent === void 0 ? void 0 : selectedItemContent.textContent) || '';
}
return true;
} // For combo box, open/selection with space key is disabled given the input box should take it over
}, {
kind: "field",
static: true,
key: "TRIGGER_KEYS",
value() {
return new Set(['Enter']);
}
}, {
kind: "get",
static: true,
key: "selectorItemHighlighted",
value:
/**
* A selector that will return highlighted items.
*/
function selectorItemHighlighted() {
return `${prefix}-combo-box-item[highlighted]`;
}
/**
* A selector that will return combo box items.
*/
}, {
kind: "get",
static: true,
key: "selectorItem",
value: function selectorItem() {
return `${prefix}-combo-box-item`;
}
/**
* A selector that will return selected items.
*/
}, {
kind: "get",
static: true,
key: "selectorItemSelected",
value: function selectorItemSelected() {
return `${prefix}-combo-box-item[selected]`;
}
/**
* The name of the custom event fired before a combo box item is selected upon a user gesture.
* Cancellation of this event stops changing the user-initiated selection.
*/
}, {
kind: "get",
static: true,
key: "eventBeforeSelect",
value: function eventBeforeSelect() {
return `${prefix}-combo-box-beingselected`;
}
/**
* The name of the custom event fired after a a combo box item is selected upon a user gesture.
*/
}, {
kind: "get",
static: true,
key: "eventSelect",
value: function eventSelect() {
return `${prefix}-combo-box-selected`;
}
}, {
kind: "field",
static: true,
key: "styles",
value() {
return styles;
}
}]
};
}, BXDropdown);
export default BXComboBox;
//# sourceMappingURL=combo-box.js.map