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.
1,062 lines (907 loc) • 40.9 kB
JavaScript
let _ = t => t,
_t,
_t2,
_t3,
_t4;
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
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 _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; }
/**
* @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 { classMap } from 'lit-html/directives/class-map';
import { ifDefined } from 'lit-html/directives/if-defined';
import { html, property, query, customElement, LitElement } from 'lit-element';
import ChevronDown16 from "../../icons/chevron--down/16";
import WarningFilled16 from "../../icons/warning--filled/16";
import { FORM_ELEMENT_COLOR_SCHEME } from '../../globals/shared-enums';
import FocusMixin from '../../globals/mixins/focus';
import HostListenerMixin from '../../globals/mixins/host-listener';
import ValidityMixin from '../../globals/mixins/validity';
import HostListener from '../../globals/decorators/host-listener';
import { find, forEach, indexOf } from '../../globals/internal/collection-helpers';
import styles from "./dropdown.css.js";
export { FORM_ELEMENT_COLOR_SCHEME as DROPDOWN_COLOR_SCHEME } from '../../globals/shared-enums';
const {
prefix
} = settings;
/**
* Navigation direction, associated with key symbols.
*/
export const NAVIGATION_DIRECTION = {
Up: -1,
ArrowUp: -1,
Down: 1,
ArrowDown: 1
};
/**
* The keyboard action categories for dropdown.
*/
export let DROPDOWN_KEYBOARD_ACTION;
/**
* Dropdown size.
*/
(function (DROPDOWN_KEYBOARD_ACTION) {
DROPDOWN_KEYBOARD_ACTION["NONE"] = "none";
DROPDOWN_KEYBOARD_ACTION["CLOSING"] = "closing";
DROPDOWN_KEYBOARD_ACTION["NAVIGATING"] = "navigating";
DROPDOWN_KEYBOARD_ACTION["TRIGGERING"] = "triggering";
})(DROPDOWN_KEYBOARD_ACTION || (DROPDOWN_KEYBOARD_ACTION = {}));
export let DROPDOWN_SIZE;
/**
* Dropdown types.
*/
(function (DROPDOWN_SIZE) {
DROPDOWN_SIZE["REGULAR"] = "";
DROPDOWN_SIZE["SMALL"] = "sm";
DROPDOWN_SIZE["EXTRA_LARGE"] = "xl";
})(DROPDOWN_SIZE || (DROPDOWN_SIZE = {}));
export let DROPDOWN_TYPE;
/**
* Dropdown.
* @element bx-dropdown
* @csspart label-text The label text.
* @csspart helper-text The helper text.
* @csspart trigger-button The trigger button.
* @csspart menu-body The menu body.
* @csspart validity-message The validity message.
* @fires bx-dropdown-beingselected
* The custom event fired before a dropdown item is selected upon a user gesture.
* Cancellation of this event stops changing the user-initiated selection.
* @fires bx-dropdown-selected - The custom event fired after a a dropdown item is selected upon a user gesture.
*/
(function (DROPDOWN_TYPE) {
DROPDOWN_TYPE["REGULAR"] = "";
DROPDOWN_TYPE["INLINE"] = "inline";
})(DROPDOWN_TYPE || (DROPDOWN_TYPE = {}));
let BXDropdown = _decorate([customElement(`${prefix}-dropdown`)], function (_initialize, _ValidityMixin) {
class BXDropdown extends _ValidityMixin {
constructor(...args) {
super(...args);
_initialize(this);
}
}
return {
F: BXDropdown,
d: [{
kind: "field",
key: "_selectedItemContent",
value() {
return null;
}
}, {
kind: "field",
key: "_shouldTriggerBeFocusable",
value() {
return true;
}
}, {
kind: "field",
decorators: [query('slot[name="helper-text"]')],
key: "_slotHelperTextNode",
value: void 0
}, {
kind: "field",
decorators: [query('slot[name="label-text"]')],
key: "_slotLabelTextNode",
value: void 0
}, {
kind: "method",
key: "_selectionShouldChange",
value:
/**
* The latest status of this dropdown, for screen reader to accounce.
*/
/**
* The content of the selected item.
*/
/**
* `true` if the trigger button should be focusable.
* Derived class can set `false` to this if the trigger button contains another primary focusable element (e.g. `<input>`).
*/
/**
* The `<slot>` element for the helper text in the shadow DOM.
*/
/**
* The `<slot>` element for the label text in the shadow DOM.
*/
/**
* @param itemToSelect A dropdown item. Absense of this argument means clearing selection.
* @returns `true` if the selection of this dropdown should change if the given item is selected upon user interaction.
*/
function _selectionShouldChange(itemToSelect) {
return !itemToSelect || itemToSelect.value !== this.value;
}
/**
* A callback that runs after change in dropdown selection upon user interaction is confirmed.
* @param itemToSelect
* A dropdown item.
* Absense of this argument means clearing selection, which may be handled by a derived class.
*/
}, {
kind: "method",
key: "_selectionDidChange",
value: function _selectionDidChange(itemToSelect) {
if (itemToSelect) {
this.value = itemToSelect.value;
forEach(this.querySelectorAll(this.constructor.selectorItemSelected), item => {
item.selected = false;
});
itemToSelect.selected = true;
this._assistiveStatusText = this.selectedItemAssistiveText;
this._handleUserInitiatedToggle(false);
}
}
/**
* Handles `click` event on the top-level element in the shadow DOM.
* @param event The event.
*/
}, {
kind: "method",
key: "_handleClickInner",
value: function _handleClickInner(event) {
if (this.shadowRoot.contains(event.target)) {
this._handleUserInitiatedToggle();
} else {
const item = event.target.closest(this.constructor.selectorItem);
if (this.contains(item)) {
this._handleUserInitiatedSelectItem(item);
}
}
}
/**
* Handler for the `keydown` event on the top-level element in the shadow DOM.
*/
}, {
kind: "method",
key: "_handleKeydownInner",
value: function _handleKeydownInner(event) {
const {
key
} = event;
const action = this.constructor.getAction(key);
if (!this.open) {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.NAVIGATING:
this._handleUserInitiatedToggle(true); // If this menu gets open with an arrow key, reset the highlight
this._clearHighlight();
break;
default:
break;
}
} else {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.CLOSING:
this._handleUserInitiatedToggle(false);
break;
case DROPDOWN_KEYBOARD_ACTION.NAVIGATING:
this._navigate(NAVIGATION_DIRECTION[key]);
break;
default:
break;
}
}
}
/**
* Handler for the `keypress` event on the top-level element in the shadow DOM.
*/
}, {
kind: "method",
key: "_handleKeypressInner",
value: function _handleKeypressInner(event) {
const {
key
} = event;
const action = this.constructor.getAction(key);
if (!this.open) {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.TRIGGERING:
this._handleUserInitiatedToggle(true);
break;
default:
break;
}
} else {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.TRIGGERING:
{
const constructor = this.constructor;
const highlightedItem = this.querySelector(constructor.selectorItemHighlighted);
if (highlightedItem) {
this._handleUserInitiatedSelectItem(highlightedItem);
} else {
this._handleUserInitiatedToggle(false);
}
}
break;
default:
break;
}
}
}
/**
* Handles `blur` event handler on the document this element is in.
* @param event The event.
*/
}, {
kind: "method",
decorators: [HostListener('focusout')],
key: "_handleFocusOut",
value: function _handleFocusOut(event) {
if (!this.contains(event.relatedTarget)) {
this._handleUserInitiatedToggle(false);
}
}
/**
* Handles `slotchange` event for the `<slot>` for helper text.
*/
}, {
kind: "method",
key: "_handleSlotchangeHelperText",
value: function _handleSlotchangeHelperText() {
this.requestUpdate();
}
/**
* Handles `slotchange` event for the `<slot>` for label text.
*/
}, {
kind: "method",
key: "_handleSlotchangeLabelText",
value: function _handleSlotchangeLabelText() {
this.requestUpdate();
}
/**
* Handles user-initiated selection of a dropdown item.
* @param [item] The dropdown item user wants to select. Absense of this argument means clearing selection.
*/
}, {
kind: "method",
key: "_handleUserInitiatedSelectItem",
value: function _handleUserInitiatedSelectItem(item) {
if (this._selectionShouldChange(item)) {
const init = {
bubbles: true,
composed: true,
detail: {
item
}
};
const constructor = this.constructor;
const beforeSelectEvent = new CustomEvent(constructor.eventBeforeSelect, _objectSpread({}, init, {
cancelable: true
}));
if (this.dispatchEvent(beforeSelectEvent)) {
this._selectionDidChange(item);
const afterSelectEvent = new CustomEvent(constructor.eventSelect, init);
this.dispatchEvent(afterSelectEvent);
}
}
}
/**
* Handles user-initiated toggling the open state.
* @param [force] If specified, forces the open state to the given one.
*/
}, {
kind: "method",
key: "_handleUserInitiatedToggle",
value: function _handleUserInitiatedToggle(force = !this.open) {
this.open = force;
if (this.open) {
this._assistiveStatusText = this.selectingItemsAssistiveText;
} else {
const {
selectedItemAssistiveText,
triggerContent,
_assistiveStatusText: assistiveStatusText,
_selectedItemContent: selectedItemContent
} = this;
const selectedItemText = selectedItemContent && selectedItemContent.textContent || triggerContent;
if (selectedItemText && assistiveStatusText !== selectedItemAssistiveText) {
this._assistiveStatusText = selectedItemText;
}
forEach(this.querySelectorAll(this.constructor.selectorItemHighlighted), item => {
item.highlighted = false;
});
}
this.requestUpdate();
}
/**
* Clears the selection of dropdown items.
*/
}, {
kind: "method",
key: "_clearHighlight",
value: function _clearHighlight() {
forEach(this.querySelectorAll(this.constructor.selectorItem), item => {
item.highlighted = false;
});
}
/**
* Navigate through dropdown items.
* @param direction `-1` to navigate backward, `1` to navigate forward.
*/
}, {
kind: "method",
key: "_navigate",
value: function _navigate(direction) {
const constructor = this.constructor;
const items = this.querySelectorAll(constructor.selectorItem);
const highlightedItem = this.querySelector(constructor.selectorItemHighlighted);
const highlightedIndex = indexOf(items, highlightedItem);
let nextIndex = highlightedIndex + direction;
if (nextIndex < 0) {
nextIndex = items.length - 1;
}
if (nextIndex >= items.length) {
nextIndex = 0;
}
forEach(items, (item, i) => {
item.highlighted = i === nextIndex;
});
const nextItem = items[nextIndex]; // Using `{ block: 'nearest' }` to prevent scrolling unless scrolling is absolutely necessary.
// `scrollIntoViewOptions` seems to work in latest Safari despite of MDN/caniuse table.
// IE falls back to the old behavior.
nextItem.scrollIntoView({
block: 'nearest'
});
const nextItemText = nextItem.textContent;
if (nextItemText) {
this._assistiveStatusText = nextItemText;
}
this.requestUpdate();
}
/* eslint-disable class-methods-use-this */
/**
* @returns The content preceding the trigger button.
*/
}, {
kind: "method",
key: "_renderPrecedingTriggerContent",
value: function _renderPrecedingTriggerContent() {
return undefined;
}
/* eslint-enable class-methods-use-this */
/**
* @returns The main content of the trigger button.
*/
}, {
kind: "method",
key: "_renderTriggerContent",
value: function _renderTriggerContent() {
const {
triggerContent,
_selectedItemContent: selectedItemContent
} = this;
return html(_t || (_t = _`
<span id="trigger-label" class="${0}--list-box__label">${0}</span>
`), prefix, selectedItemContent || triggerContent);
}
/* eslint-disable class-methods-use-this */
/**
* @returns The content following the trigger button.
*/
}, {
kind: "method",
key: "_renderFollowingTriggerContent",
value: function _renderFollowingTriggerContent() {
return undefined;
}
/* eslint-enable class-methods-use-this */
/**
* The color scheme.
*/
}, {
kind: "field",
decorators: [property({
attribute: 'color-scheme',
reflect: true
})],
key: "colorScheme",
value() {
return FORM_ELEMENT_COLOR_SCHEME.REGULAR;
}
}, {
kind: "field",
decorators: [property({
type: Boolean,
reflect: true
})],
key: "disabled",
value() {
return false;
}
}, {
kind: "field",
decorators: [property({
attribute: 'helper-text'
})],
key: "helperText",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
type: Boolean,
reflect: true
})],
key: "invalid",
value() {
return false;
}
}, {
kind: "field",
decorators: [property({
attribute: 'label-text'
})],
key: "labelText",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
type: Boolean,
reflect: true
})],
key: "open",
value() {
return false;
}
}, {
kind: "field",
decorators: [property({
type: Boolean,
reflect: true
})],
key: "required",
value() {
return false;
}
}, {
kind: "field",
decorators: [property({
attribute: 'required-validity-message'
})],
key: "requiredValidityMessage",
value() {
return 'Please fill out this field.';
}
}, {
kind: "field",
decorators: [property({
attribute: 'selecting-items-assistive-text'
})],
key: "selectingItemsAssistiveText",
value() {
return 'Selecting items. Use up and down arrow keys to navigate.';
}
}, {
kind: "field",
decorators: [property({
attribute: 'selected-item-assistive-text'
})],
key: "selectedItemAssistiveText",
value() {
return 'Selected an item.';
}
}, {
kind: "field",
decorators: [property({
reflect: true
})],
key: "size",
value() {
return DROPDOWN_SIZE.REGULAR;
}
}, {
kind: "field",
decorators: [property({
attribute: 'toggle-label-closed'
})],
key: "toggleLabelClosed",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
attribute: 'toggle-label-open'
})],
key: "toggleLabelOpen",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
attribute: 'trigger-content'
})],
key: "triggerContent",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
reflect: true
})],
key: "type",
value() {
return DROPDOWN_TYPE.REGULAR;
}
}, {
kind: "field",
decorators: [property({
attribute: 'validity-message'
})],
key: "validityMessage",
value() {
return '';
}
}, {
kind: "field",
decorators: [property({
reflect: true
})],
key: "value",
value() {
return '';
}
}, {
kind: "method",
key: "createRenderRoot",
value:
/**
* `true` if this dropdown should be disabled.
*/
/**
* The helper text.
*/
/**
* `true` to show the UI of the invalid state.
*/
/**
* The label text.
*/
/**
* `true` if this dropdown should be open.
*/
/**
* `true` if the value is required.
*/
/**
* The special validity message for `required`.
*/
/**
* An assistive text for screen reader to announce, telling the open state.
*/
/**
* An assistive text for screen reader to announce, telling that an item is selected.
*/
/**
* Dropdown size.
*/
/**
* The `aria-label` attribute for the UI indicating the closed state.
*/
/**
* The `aria-label` attribute for the UI indicating the open state.
*/
/**
* The content of the trigger button.
*/
/**
* `true` if this dropdown should use the inline UI variant.
*/
/**
* The validity message.
*/
/**
* The value of the selected item.
*/
function createRenderRoot() {
return this.attachShadow({
mode: 'open',
delegatesFocus: true
});
}
}, {
kind: "method",
key: "shouldUpdate",
value: function shouldUpdate(changedProperties) {
const {
selectorItem
} = this.constructor;
if (changedProperties.has('size')) {
forEach(this.querySelectorAll(selectorItem), elem => {
elem.size = this.size;
});
}
if (changedProperties.has('value')) {
// `<bx-multi-select>` updates selection beforehand
// because our rendering logic for `<bx-multi-select>` looks for selected items via `qSA()`
forEach(this.querySelectorAll(selectorItem), elem => {
elem.selected = elem.value === this.value;
});
const item = find(this.querySelectorAll(selectorItem), elem => elem.value === this.value);
if (item) {
const range = this.ownerDocument.createRange();
range.selectNodeContents(item);
this._selectedItemContent = range.cloneContents();
} else {
this._selectedItemContent = null;
}
}
return true;
}
}, {
kind: "method",
key: "updated",
value: function updated(changedProperties) {
const {
helperText,
type
} = this;
const inline = type === DROPDOWN_TYPE.INLINE;
const {
selectorItem
} = this.constructor;
if (changedProperties.has('disabled')) {
const {
disabled
} = this; // Propagate `disabled` attribute to descendants until `:host-context()` gets supported in all major browsers
forEach(this.querySelectorAll(selectorItem), elem => {
elem.disabled = disabled;
});
}
if ((changedProperties.has('helperText') || changedProperties.has('type')) && helperText && inline) {
// eslint-disable-next-line no-console
console.warn('Found `helperText` property/attribute usage in inline mode, that is not supported, at:', this);
}
}
}, {
kind: "method",
key: "render",
value: function render() {
const {
colorScheme,
disabled,
helperText,
invalid,
labelText,
open,
toggleLabelClosed,
toggleLabelOpen,
size,
type,
validityMessage,
_assistiveStatusText: assistiveStatusText,
_shouldTriggerBeFocusable: shouldTriggerBeFocusable,
_handleClickInner: handleClickInner,
_handleKeydownInner: handleKeydownInner,
_handleKeypressInner: handleKeypressInner,
_handleSlotchangeHelperText: handleSlotchangeHelperText,
_handleSlotchangeLabelText: handleSlotchangeLabelText,
_slotHelperTextNode: slotHelperTextNode,
_slotLabelTextNode: slotLabelTextNode
} = this;
const inline = type === DROPDOWN_TYPE.INLINE;
const selectedItemsCount = this.querySelectorAll(this.constructor.selectorItemSelected).length;
const classes = classMap({
[`${prefix}--dropdown`]: true,
[`${prefix}--list-box`]: true,
[`${prefix}--list-box--${colorScheme}`]: colorScheme,
[`${prefix}--list-box--disabled`]: disabled,
[`${prefix}--list-box--inline`]: inline,
[`${prefix}--list-box--expanded`]: open,
[`${prefix}--list-box--${size}`]: size,
[`${prefix}--dropdown--invalid`]: invalid,
[`${prefix}--dropdown--inline`]: inline,
[`${prefix}--dropdown--selected`]: selectedItemsCount > 0
});
const labelClasses = classMap({
[`${prefix}--label`]: true,
[`${prefix}--label--disabled`]: disabled
});
const helperClasses = classMap({
[`${prefix}--form__helper-text`]: true,
[`${prefix}--form__helper-text--disabled`]: disabled
});
const iconContainerClasses = classMap({
[`${prefix}--list-box__menu-icon`]: true,
[`${prefix}--list-box__menu-icon--open`]: open
});
const toggleLabel = (open ? toggleLabelOpen : toggleLabelClosed) || undefined;
const hasHelperText = helperText || slotHelperTextNode && slotHelperTextNode.assignedNodes().length > 0;
const hasLabelText = labelText || slotLabelTextNode && slotLabelTextNode.assignedNodes().length > 0;
const validity = !invalid ? undefined : html(_t2 || (_t2 = _`
<div part="validity-message" class=${0}>
<slot name="validity-message">${0}</slot>
</div>
`), `${prefix}--form-requirement`, validityMessage);
const validityIcon = !invalid ? undefined : WarningFilled16({
class: `${prefix}--list-box__invalid-icon`,
'aria-label': toggleLabel
});
const menuBody = !open ? undefined : html(_t3 || (_t3 = _`
<div id="menu-body" part="menu-body" class="${0}--list-box__menu" role="listbox" tabindex="-1">
<slot></slot>
</div>
`), prefix);
return html(_t4 || (_t4 = _`
<label part="label-text" class="${0}" ?hidden="${0}">
<slot name="label-text" ="${0}">${0}</slot>
</label>
<div part="helper-text" class="${0}" ?hidden="${0}">
<slot name="helper-text" ="${0}">${0}</slot>
</div>
<div
role="listbox"
class="${0}"
?data-invalid=${0}
=${0}
=${0}
=${0}
>
${0}
<div
part="trigger-button"
role="${0}"
class="${0}--list-box__field"
tabindex="${0}"
aria-labelledby="trigger-label"
aria-expanded="${0}"
aria-haspopup="listbox"
aria-owns="menu-body"
aria-controls="menu-body"
>
${0}${0}${0}
<div class="${0}">
${0}
</div>
</div>
${0}
</div>
${0}
<div class="${0}--assistive-text" role="status" aria-live="assertive" aria-relevant="additions text">
${0}
</div>
`), labelClasses, !hasLabelText, handleSlotchangeLabelText, labelText, helperClasses, inline || !hasHelperText, handleSlotchangeHelperText, helperText, classes, invalid, handleClickInner, handleKeydownInner, handleKeypressInner, validityIcon, ifDefined(!shouldTriggerBeFocusable ? undefined : 'button'), prefix, ifDefined(!shouldTriggerBeFocusable ? undefined : '0'), String(open), this._renderPrecedingTriggerContent(), this._renderTriggerContent(), this._renderFollowingTriggerContent(), iconContainerClasses, ChevronDown16({
'aria-label': toggleLabel
}), menuBody, validity, prefix, assistiveStatusText);
}
/**
* Symbols of keys that triggers opening/closing menu and selecting/deselecting menu item.
*/
}, {
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}-dropdown-item[highlighted]`;
}
/**
* A selector that will return dropdown items.
*/
}, {
kind: "get",
static: true,
key: "selectorItem",
value: function selectorItem() {
return `${prefix}-dropdown-item`;
}
/**
* A selector that will return selected items.
*/
}, {
kind: "get",
static: true,
key: "selectorItemSelected",
value: function selectorItemSelected() {
return `${prefix}-dropdown-item[selected]`;
}
/**
* The name of the custom event fired before a dropdown 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}-dropdown-beingselected`;
}
/**
* The name of the custom event fired after a a dropdown item is selected upon a user gesture.
*/
}, {
kind: "get",
static: true,
key: "eventSelect",
value: function eventSelect() {
return `${prefix}-dropdown-selected`;
}
}, {
kind: "field",
static: true,
key: "styles",
value() {
return styles;
}
}, {
kind: "method",
static: true,
key: "getAction",
value:
/**
* @returns A action for dropdown for the given key symbol.
*/
function getAction(key) {
if (key === 'Escape') {
return DROPDOWN_KEYBOARD_ACTION.CLOSING;
}
if (key in NAVIGATION_DIRECTION) {
return DROPDOWN_KEYBOARD_ACTION.NAVIGATING;
}
if (this.TRIGGER_KEYS.has(key)) {
return DROPDOWN_KEYBOARD_ACTION.TRIGGERING;
}
return DROPDOWN_KEYBOARD_ACTION.NONE;
}
}]
};
}, ValidityMixin(HostListenerMixin(FocusMixin(LitElement))));
export default BXDropdown;
//# sourceMappingURL=dropdown.js.map