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.
566 lines (489 loc) • 26.5 kB
JavaScript
let _ = t => t,
_t;
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 { classMap } from 'lit-html/directives/class-map';
import { html, property, customElement, LitElement } from 'lit-element';
import CaretLeft24 from "../../icons/caret--left/24";
import CaretRight24 from "../../icons/caret--right/24";
import settings from 'carbon-components/es/globals/js/settings';
import on from 'carbon-components/es/globals/js/misc/on';
import FocusMixin from '../../globals/mixins/focus';
import { forEach } from '../../globals/internal/collection-helpers';
import styles from "./pagination.css.js";
const {
prefix
} = settings;
/**
* Pagination UI.
* @element bx-pagination
* @slot page-sizes-select - Where to put in the `<page-sizes-select>`.
* @fires bx-pages-select-changed - The custom event fired after the current page is changed from `<bx-pages-select>`.
* @fires bx-page-sizes-select-changed
* The custom event fired after the number of rows per page is changed from `<bx-page-sizes-select>`.
*/
let BXPagination = _decorate([customElement(`${prefix}-pagination`)], function (_initialize, _FocusMixin) {
class BXPagination extends _FocusMixin {
constructor(...args) {
super(...args);
_initialize(this);
}
}
return {
F: BXPagination,
d: [{
kind: "field",
key: "_hChangePage",
value() {
return null;
}
}, {
kind: "field",
key: "_hChangePageSize",
value() {
return null;
}
}, {
kind: "method",
key: "_renderStatusText",
value:
/**
* The handle for the listener of `${prefix}-pages-select-changed` event.
*/
/**
* The handle for the listener of `${prefix}-page-sizes-select-changed` event.
*/
/**
* @returns Page status text.
*/
function _renderStatusText() {
const {
atLastPage,
start,
pageSize,
total,
formatStatusWithDeterminateTotal,
formatStatusWithIndeterminateTotal
} = this; // * Regular: `1-10 of 100 items`
// * Indeterminate total: `Item 1-10` (`Item 11-` at the last page)
const end = atLastPage ? undefined : Math.min(start + pageSize, total == null ? Infinity : total);
const format = total == null ? formatStatusWithIndeterminateTotal : formatStatusWithDeterminateTotal; // `start`/`end` properties starts with zero, whereas we want to show number starting with 1
return format({
start: start + 1,
end,
count: total
});
}
/**
* Handles user-initiated change in the row number the current page starts with.
* @param start The new current row number, index that starts with zero.
*/
}, {
kind: "method",
key: "_handleUserInitiatedChangeStart",
value: function _handleUserInitiatedChangeStart(start) {
this.start = start;
this.dispatchEvent(new CustomEvent(this.constructor.eventChangeCurrent, {
bubbles: true,
composed: true,
detail: {
start
}
}));
}
/**
* Handles `click` event on the previous button.
*/
}, {
kind: "method",
key: "_handleClickPrevButton",
value: function _handleClickPrevButton() {
const {
start: oldStart,
pageSize
} = this;
const newStart = Math.max(oldStart - pageSize, 0);
if (newStart !== oldStart) {
this._handleUserInitiatedChangeStart(newStart);
}
}
/**
* Handles `click` event on the next button.
*/
}, {
kind: "method",
key: "_handleClickNextButton",
value: function _handleClickNextButton() {
const {
start: oldStart,
pageSize,
total
} = this;
const newStart = oldStart + pageSize;
if (newStart < (total == null ? Infinity : total)) {
this._handleUserInitiatedChangeStart(newStart);
}
}
/**
* Handles user-initiated change in current page.
* @param event The event.
*/
}, {
kind: "method",
key: "_handleChangePage",
value: function _handleChangePage({
detail
}) {
const {
value
} = detail;
const {
pageSize
} = this;
this._handleUserInitiatedChangeStart(value * pageSize);
}
/**
* Handles user-initiated change in number of rows per page.
* @param event The event.
*/
}, {
kind: "method",
key: "_handleChangePageSize",
value: function _handleChangePageSize({
detail
}) {
this.pageSize = detail.value;
}
/**
* The formatter, used with determinate the total pages. Should be changed upon the locale the UI is rendered with.
*/
}, {
kind: "field",
decorators: [property({
attribute: false
})],
key: "formatStatusWithDeterminateTotal",
value() {
return ({
start,
end,
count
}) => `${start}–${end} of ${count} item${count <= 1 ? '' : 's'}`;
}
}, {
kind: "field",
decorators: [property({
attribute: false
})],
key: "formatStatusWithIndeterminateTotal",
value() {
return ({
start,
end
}) => end == null ? `Item ${start}–` : `Item ${start}–${end}`;
}
}, {
kind: "field",
decorators: [property({
type: Boolean,
attribute: 'at-last-page'
})],
key: "atLastPage",
value: void 0
}, {
kind: "field",
decorators: [property({
type: Boolean,
reflect: true
})],
key: "disabled",
value() {
return false;
}
}, {
kind: "field",
decorators: [property({
attribute: 'next-button-text'
})],
key: "nextButtonText",
value() {
return 'Next page';
}
}, {
kind: "field",
decorators: [property({
type: Number,
attribute: 'page-size'
})],
key: "pageSize",
value() {
return 10;
}
}, {
kind: "field",
decorators: [property({
attribute: 'page-size-label-text'
})],
key: "pageSizeLabelText",
value: void 0
}, {
kind: "field",
decorators: [property({
attribute: 'prev-button-text'
})],
key: "prevButtonText",
value() {
return 'Previous page';
}
}, {
kind: "field",
decorators: [property({
type: Number
})],
key: "start",
value() {
return 0;
}
}, {
kind: "field",
decorators: [property({
type: Number
})],
key: "total",
value: void 0
}, {
kind: "method",
key: "createRenderRoot",
value:
/**
* The formatter, used with indeterminate the total pages. Should be changed upon the locale the UI is rendered with.
*/
/**
* `true` to explicitly state that user is at the last page.
*/
/**
* `true` if the pagination UI should be disabled.
*/
/**
* The assistive text for the button to go to next page.
*/
/**
* Number of items per page.
*/
/**
* The label text for the UI to select page size.
*/
/**
* The assistive text for the button to go to previous page.
*/
/**
* The row number where current page start with, index that starts with zero.
*/
/**
* The number of total items.
*/
function createRenderRoot() {
return this.attachShadow({
mode: 'open',
delegatesFocus: true
});
}
}, {
kind: "method",
key: "connectedCallback",
value: function connectedCallback() {
_get(_getPrototypeOf(BXPagination.prototype), "connectedCallback", this).call(this); // Manually hooks the event listeners on the host element to make the event names configurable
const {
eventChangePage,
eventChangePageSize
} = this.constructor;
this._hChangePage = on(this, eventChangePage, this._handleChangePage);
this._hChangePageSize = on(this, eventChangePageSize, this._handleChangePageSize);
}
}, {
kind: "method",
key: "disconnectedCallback",
value: function disconnectedCallback() {
if (this._hChangePageSize) {
this._hChangePageSize = this._hChangePageSize.release();
}
if (this._hChangePage) {
this._hChangePage = this._hChangePage.release();
}
_get(_getPrototypeOf(BXPagination.prototype), "disconnectedCallback", this).call(this);
}
}, {
kind: "method",
key: "updated",
value: function updated(changedProperties) {
const {
pageSize
} = this;
const {
selectorPageSizesSelect,
selectorPagesSelect
} = this.constructor;
if (changedProperties.has('pageSize')) {
forEach(this.querySelectorAll(selectorPageSizesSelect), elem => {
elem.value = pageSize;
});
}
if (changedProperties.has('pageSize') || changedProperties.has('start')) {
const {
start
} = this;
forEach(this.querySelectorAll(selectorPagesSelect), elem => {
elem.value = Math.floor(start / pageSize);
});
}
if (changedProperties.has('pageSize') || changedProperties.has('total')) {
const {
total
} = this;
forEach(this.querySelectorAll(selectorPagesSelect), elem => {
elem.total = Math.ceil(total / pageSize);
});
}
}
}, {
kind: "method",
key: "render",
value: function render() {
const {
disabled,
nextButtonText,
prevButtonText,
pageSize,
start,
total,
_handleClickPrevButton: handleClickPrevButton,
_handleClickNextButton: handleClickNextButton
} = this;
const {
atLastPage = start + pageSize >= total
} = this;
const prevButtonDisabled = disabled || start === 0;
const nextButtonDisabled = disabled || atLastPage;
const prevButtonClasses = classMap({
[`${prefix}--pagination__button`]: true,
[`${prefix}--pagination__button--backward`]: true,
[`${prefix}--pagination__button--no-index`]: prevButtonDisabled
});
const nextButtonClasses = classMap({
[`${prefix}--pagination__button`]: true,
[`${prefix}--pagination__button--forward`]: true,
[`${prefix}--pagination__button--no-index`]: nextButtonDisabled
});
return html(_t || (_t = _`
<div class="${0}--pagination__left">
<slot name="page-sizes-select"></slot>
<div class="${0}-ce--pagination__divider"></div>
<span class="${0}--pagination__text">${0}</span>
</div>
<div class="${0}-ce--pagination__divider"></div>
<div class="${0}--pagination__right">
<slot></slot>
<button
?disabled="${0}"
class="${0}"
title="${0}"
="${0}"
>
${0}
</button>
<button
?disabled="${0}"
class="${0}"
title="${0}"
="${0}"
>
${0}
</button>
</div>
`), prefix, prefix, prefix, this._renderStatusText(), prefix, prefix, prevButtonDisabled, prevButtonClasses, prevButtonText, handleClickPrevButton, CaretLeft24(), nextButtonDisabled, nextButtonClasses, nextButtonText, handleClickNextButton, CaretRight24());
}
/**
* A selector that will return the select box for the current page.
*/
}, {
kind: "get",
static: true,
key: "selectorPagesSelect",
value: function selectorPagesSelect() {
return `${prefix}-pages-select`;
}
/**
* A selector that will return the select box for page sizes.
*/
}, {
kind: "get",
static: true,
key: "selectorPageSizesSelect",
value: function selectorPageSizesSelect() {
return `${prefix}-page-sizes-select`;
}
/**
* The name of the custom event fired after the current row number is changed.
*/
}, {
kind: "get",
static: true,
key: "eventChangeCurrent",
value: function eventChangeCurrent() {
return `${prefix}-pagination-changed-current`;
}
/**
* The name of the custom event fired after the current page is changed from `<bx-pages-select>`.
*/
}, {
kind: "get",
static: true,
key: "eventChangePage",
value: function eventChangePage() {
return `${prefix}-pages-select-changed`;
}
/**
* The name of the custom event fired after the number of rows per page is changed from `<bx-page-sizes-select>`.
*/
}, {
kind: "get",
static: true,
key: "eventChangePageSize",
value: function eventChangePageSize() {
return `${prefix}-page-sizes-select-changed`;
}
}, {
kind: "field",
static: true,
key: "styles",
value() {
return styles;
}
}]
};
}, FocusMixin(LitElement));
export default BXPagination;
//# sourceMappingURL=pagination.js.map