UNPKG

@public-ui/components

Version:

Contains all web components that belong to KoliBri - The accessible HTML-Standard.

830 lines (829 loc) 36.4 kB
/*! * KoliBri - The accessible HTML-Standard */ import { h, Host } from "@stencil/core"; import { KolPaginationWcTag, KolTableStatelessWcTag } from "../../core/component-names"; import { translate } from "../../i18n"; import { devHint, emptyStringByArrayHandler, objectObjectHandler, parseJson, setState, validateAllowMultiSort, validateFixedCols, validateHasSettingsMenu, validateLabel, validatePaginationPosition, validateTableData, validateTableDataFoot, validateTableSelection, validateTableStatefulCallbacks, watchValidator, } from "../../schema"; import { Callback } from "../../schema/enums"; import { validateAriaLabelledby } from "../../schema/props/aria-labelledby"; import { attachInternals } from "../../utils/aria-labelledby"; import { dispatchDomEvent, KolEvent } from "../../utils/events"; const PAGINATION_OPTIONS = [10, 20, 50, 100]; const paginationValidator = (value) => value === true || value === '' || (typeof value === 'object' && value !== null); export class KolTableStateful { constructor() { this.resolvedElements = []; this.catchRef = (ref) => { this.tableWcRef = ref; }; this.sortData = []; this.showPagination = false; this.pageStartSlice = 0; this.pageEndSlice = 10; this.disableSort = false; this._paginationPosition = 'bottom'; this.state = { _allowMultiSort: false, _fixedCols: [0, 0], _data: [], _dataFoot: [], _headers: { horizontal: [], vertical: [], }, _label: '', _pagination: { _page: 1, _pageSize: 10, _max: 0, }, _sortedData: [], _paginationPosition: 'bottom', _hasSettingsMenu: false, }; this.handlePagination = { onClick: (event, page) => { var _a; if (typeof ((_a = this.state._pagination._on) === null || _a === void 0 ? void 0 : _a.onClick) === 'function') { this.state._pagination._on.onClick(event, page); } setState(this, '_pagination', Object.assign(Object.assign({}, this.state._pagination), { _page: page })); }, onChangePage: (event, page) => { var _a; if (typeof ((_a = this.state._pagination._on) === null || _a === void 0 ? void 0 : _a.onChangePage) === 'function') { this.state._pagination._on.onChangePage(event, page); } setState(this, '_pagination', Object.assign(Object.assign({}, this.state._pagination), { _page: page })); }, onChangePageSize: (event, pageSize) => { var _a; if (typeof ((_a = this.state._pagination._on) === null || _a === void 0 ? void 0 : _a.onChangePageSize) === 'function') { this.state._pagination._on.onChangePageSize(event, pageSize); } setState(this, '_pagination', Object.assign(Object.assign({}, this.state._pagination), { _pageSize: pageSize })); setState(this, '_pageSize', pageSize); }, }; this.onSelectionChange = (event) => { event.stopPropagation(); }; this.updateSortedData = () => { if (this.disableSort) { setState(this, '_sortedData', this.state._data); return; } const sortedData = [...this.state._data]; if (this.sortData.length > 0) { sortedData.sort((a, b) => { for (let index = 0; index < this.sortData.length; index++) { const data = this.sortData[index]; const result = data.compareFn(a, b, data.direction); if (result !== 0) { return data.direction === 'ASC' ? result : -result; } } return 0; }); } setState(this, '_sortedData', sortedData); }; } validateAriaLabelledby(value) { this.syncExternalLabel(value); } syncExternalLabel(value) { this.resolvedElements = validateAriaLabelledby(this, this.host, this.internals, value); } validateAllowMultiSort(value) { validateAllowMultiSort(this, value, { defaultValue: false }); } validateData(value) { validateTableData(this, value, { afterPatch: () => { setTimeout(this.updateSortedData); }, }); } validateDataFoot(value) { validateTableDataFoot(this, value, { afterPatch: () => { setTimeout(this.updateSortedData); }, }); } validateFixedCols(value) { validateFixedCols(this, value); } validatePaginationPosition(value) { validatePaginationPosition(this, value); } validateHasSettingsMenu(value) { validateHasSettingsMenu(this, value); } changeCellSort(headerCell) { var _a; if (headerCell.type === undefined || headerCell.type === 'default') { if (typeof headerCell.compareFn !== 'function') { return; } if (!this.state._allowMultiSort && headerCell.key !== ((_a = this.sortData[0]) === null || _a === void 0 ? void 0 : _a.key)) { this.sortData = []; } const index = this.sortData.findIndex((value) => value.key === headerCell.key); if (index >= 0) { const settings = this.sortData[index]; switch (settings.direction) { case 'ASC': settings.direction = 'DESC'; break; case 'DESC': this.sortData.splice(index, 1); break; default: settings.direction = 'ASC'; break; } } else if (headerCell.key) { this.sortData.push({ label: headerCell.label, key: headerCell.key, compareFn: headerCell.compareFn, direction: 'ASC', }); } this.updateSortedData(); } } initializeSortFromHeaders(headers) { var _a, _b; let hasSortedCells = false; const applySort = (cells) => { this.sortData = []; cells.forEach((cell) => { if (cell.type !== undefined && cell.type !== 'default') { return; } if (typeof cell.compareFn === 'function' && !cell.key) { devHint(`[KolTableStateful] A sortable column requires the 'key' property.`); return; } const key = cell.key; if (!key) { return; } const sortDirection = cell.sortDirection; if (sortDirection === 'ASC' || sortDirection === 'DESC') { if (typeof cell.compareFn === 'function') { if (this.state._allowMultiSort || this.sortData.length === 0) { this.sortData.push({ label: cell.label, key, compareFn: cell.compareFn, direction: sortDirection }); } hasSortedCells = true; } } }); }; (_a = headers.horizontal) === null || _a === void 0 ? void 0 : _a.forEach(applySort); (_b = headers.vertical) === null || _b === void 0 ? void 0 : _b.forEach(applySort); return hasSortedCells; } validateHeaders(value) { emptyStringByArrayHandler(value, () => { objectObjectHandler(value, () => { try { value = parseJson(value); } catch (_a) { } watchValidator(this, '_headers', (value) => typeof value === 'object' && value !== null, new Set(['KoliBriTableHeaders']), value, { hooks: { beforePatch: (nextValue) => { var _a, _b; const headers = nextValue; const hasSortedCells = this.initializeSortFromHeaders(headers); if (hasSortedCells) { setTimeout(() => this.updateSortedData()); } if (headers.horizontal && headers.vertical && ((_a = headers.horizontal) === null || _a === void 0 ? void 0 : _a.length) > 0 && ((_b = headers.vertical) === null || _b === void 0 ? void 0 : _b.length) > 0) { this.disableSort = true; devHint(`Table: You can not sort the table data, if horizontal and vertical headers are defined at the same time. (https://github.com/public-ui/kolibri/issues/2372)`); } }, }, }); }); }); } validateLabel(value) { validateLabel(this, value, { required: true, }); } validateSelection(value) { validateTableSelection(this, value); } validateOn(value) { validateTableStatefulCallbacks(this, value); } validatePagination(value) { try { value = parseJson(value); } catch (_a) { } this.showPagination = paginationValidator(value); watchValidator(this, '_pagination', paginationValidator, new Set(['boolean', 'KoliBriTablePagination']), value, { defaultValue: { _page: 1, _pageSize: 10, _max: 0, }, }); } componentDidLoad() { var _a; (_a = this.tableWcRef) === null || _a === void 0 ? void 0 : _a.addEventListener(KolEvent.selectionChange, this.onSelectionChange); if (!this.resolvedElements.length) { this.syncExternalLabel(this._ariaLabelledby); } } disconnectedCallback() { var _a; (_a = this.tableWcRef) === null || _a === void 0 ? void 0 : _a.removeEventListener(KolEvent.selectionChange, this.onSelectionChange); } componentWillLoad() { this.internals = attachInternals(this.host); this.syncExternalLabel(this._ariaLabelledby); this.validateAllowMultiSort(this._allowMultiSort); this.validateData(this._data); this.validateDataFoot(this._dataFoot); this.validateFixedCols(this._fixedCols); this.validateHeaders(this._headers); this.validateLabel(this._label); this.validateOn(this._on); this.validatePagination(this._pagination); this.validatePaginationPosition(this._paginationPosition); this.validateSelection(this._selection); this.validateHasSettingsMenu(this._hasSettingsMenu); } selectDisplayedData(data, pageSize, page) { if (typeof pageSize === 'number' && pageSize > 0 && typeof page === 'number' && page > 0) { this.pageStartSlice = pageSize * (page - 1); this.pageEndSlice = pageSize * page > data.length ? data.length : pageSize * page; return data.slice(this.pageStartSlice, this.pageEndSlice); } else { this.pageStartSlice = 0; this.pageEndSlice = data.length; return data; } } renderPagination(position) { const label = translate('kol-table-pagination-label', { placeholders: { label: `${this.state._label} (${translate(`kol-pagination-position-${position}`)})`, }, }); return (h("div", { class: `kol-table-stateful__pagination kol-table-stateful__pagination--${this.state._paginationPosition}` }, h("div", { class: "kol-table-stateful__pagination-wrapper" }, h(KolPaginationWcTag, { _boundaryCount: this.state._pagination._boundaryCount, _customClass: this.state._pagination._customClass, _hasButtons: this.state._pagination._hasButtons, _on: this.handlePagination, _page: this.state._pagination._page, _pageSize: this.state._pagination._pageSize, _pageSizeOptions: this.state._pagination._pageSizeOptions || PAGINATION_OPTIONS, _siblingCount: this.state._pagination._siblingCount, _tooltipAlign: "bottom", _max: this.state._pagination._max || this.state._data.length, _label: label })))); } getHeaderCellSortState(headerCell) { if (headerCell.type !== undefined && headerCell.type !== 'default') { return; } if (!this.disableSort && typeof headerCell.compareFn === 'function') { if (headerCell.key) { const data = this.sortData.find((value) => value.key === headerCell.key); if (data === null || data === void 0 ? void 0 : data.direction) { return data.direction; } } return 'NOS'; } } getHeaderCellSortOrder(headerCell) { if (headerCell.type !== undefined && headerCell.type !== 'default') { return; } if (!this.disableSort && this.state._allowMultiSort && typeof headerCell.compareFn === 'function' && headerCell.key) { const index = this.sortData.findIndex((value) => value.key === headerCell.key); if (index >= 0) { return index + 1; } } } handleSort({ key }) { var _a, _b; const horizontalHeaders = (_a = this.state._headers.horizontal) !== null && _a !== void 0 ? _a : []; const verticalHeaders = (_b = this.state._headers.vertical) !== null && _b !== void 0 ? _b : []; const allHeaders = []; for (const row of horizontalHeaders) { if (Array.isArray(row)) { allHeaders.push(...row); } } for (const row of verticalHeaders) { if (Array.isArray(row)) { allHeaders.push(...row); } } const headerCell = allHeaders.find((cell) => cell.key === key); if (headerCell) { this.changeCellSort(headerCell); } } getSelectedData(selectedKeys) { var _a; const selection = this.state._selection; if (selection) { const keyPropertyName = (_a = selection.keyPropertyName) !== null && _a !== void 0 ? _a : 'id'; const keySet = new Set(selectedKeys.map(String)); const data = this.state._sortedData.filter((item) => keySet.has(String(item[keyPropertyName]))); if (keyPropertyName) return data; } return null; } handleSelectionChange(event, selectedKeys) { var _a; const selection = this.state._selection; if (selection) this.state = Object.assign(Object.assign({}, this.state), { _selection: Object.assign(Object.assign({}, selection), { selectedKeys }) }); const selectedData = this.getSelectedData(selectedKeys); if (typeof ((_a = this.state._on) === null || _a === void 0 ? void 0 : _a[Callback.onSelectionChange]) === 'function') { this.state._on[Callback.onSelectionChange](event, selectedData); } if (this.host) { dispatchDomEvent(this.host, KolEvent.selectionChange, selectedData); } } async getSelection() { var _a; const selectedKeys = ((_a = this.state._selection) === null || _a === void 0 ? void 0 : _a.selectedKeys) || []; return this.getSelectedData(selectedKeys); } async resetSort() { this.initializeSortFromHeaders(this.state._headers); this.updateSortedData(); } render() { var _a, _b, _c, _d, _e, _f; const displayedData = this.selectDisplayedData(this.state._sortedData, this.showPagination ? ((_b = (_a = this.state._pagination) === null || _a === void 0 ? void 0 : _a._pageSize) !== null && _b !== void 0 ? _b : 10) : this.state._sortedData.length, this.state._pagination._page || 1); const paginationTop = this._paginationPosition === 'top' || this._paginationPosition === 'both' ? this.renderPagination('top') : null; const paginationBottom = this._paginationPosition === 'bottom' || this._paginationPosition === 'both' ? this.renderPagination('bottom') : null; const headerCells = { horizontal: (_d = (_c = this.state._headers.horizontal) === null || _c === void 0 ? void 0 : _c.map((row) => row.map((cell) => (Object.assign(Object.assign({}, cell), { sortDirection: this.getHeaderCellSortState(cell), sortOrder: this.getHeaderCellSortOrder(cell) }))))) !== null && _d !== void 0 ? _d : [], vertical: (_f = (_e = this.state._headers.vertical) === null || _e === void 0 ? void 0 : _e.map((column) => column.map((cell) => (Object.assign(Object.assign({}, cell), { sortDirection: this.getHeaderCellSortState(cell), sortOrder: this.getHeaderCellSortOrder(cell) }))))) !== null && _f !== void 0 ? _f : [], }; return (h(Host, { key: 'b0bcf91837e687037e9b5665e39f6fb73bba2552', class: "kol-table-stateful" }, this.pageEndSlice > 0 && this.showPagination && paginationTop, h(KolTableStatelessWcTag, { key: 'e66a607e7596b367b452e08762f2205a335818f0', externalLabelElements: this.resolvedElements, ref: this.catchRef, _data: displayedData, _fixedCols: this._fixedCols, _headerCells: headerCells, _label: this.state._label, _dataFoot: this.state._dataFoot, _on: { onSort: (_, payload) => { this.handleSort(payload); }, onSelectionChange: (event, value) => { this.handleSelectionChange(event, value); }, }, _selection: this.state._selection, _hasSettingsMenu: this.state._hasSettingsMenu, _variant: this._variant }), this.pageEndSlice > 0 && this.showPagination && paginationBottom)); } static get is() { return "kol-table-stateful"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "default": ["./style.scss"] }; } static get styleUrls() { return { "default": ["style.css"] }; } static get properties() { return { "_ariaLabelledby": { "type": "string", "mutable": false, "complexType": { "original": "AriaLabelledbyPropType", "resolved": "string | undefined", "references": { "AriaLabelledbyPropType": { "location": "import", "path": "../../schema/props/aria-labelledby", "id": "src/schema/props/aria-labelledby.ts::AriaLabelledbyPropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "References an external element by ID that serves as the accessible label for this table.\nUses ElementInternals.ariaLabelledByElements to cross the Shadow DOM boundary.\nSupported by desktop screen readers (NVDA, JAWS with Chrome/Firefox).\nNot yet supported by mobile screen readers (TalkBack, VoiceOver iOS) \u2014 use `_label` instead." }, "getter": false, "setter": false, "reflect": false, "attribute": "_aria-labelledby" }, "_allowMultiSort": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean | undefined", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines whether to allow multi sort." }, "getter": false, "setter": false, "reflect": false, "attribute": "_allow-multi-sort" }, "_data": { "type": "string", "mutable": false, "complexType": { "original": "Stringified<KoliBriTableDataType[]>", "resolved": "KoliBriTableDataType[] | string", "references": { "Stringified": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::Stringified" }, "KoliBriTableDataType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::KoliBriTableDataType" } } }, "required": true, "optional": false, "docs": { "tags": [], "text": "Defines the primary table data." }, "getter": false, "setter": false, "reflect": false, "attribute": "_data" }, "_dataFoot": { "type": "string", "mutable": false, "complexType": { "original": "Stringified<KoliBriTableDataType[]>", "resolved": "KoliBriTableDataType[] | string | undefined", "references": { "Stringified": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::Stringified" }, "KoliBriTableDataType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::KoliBriTableDataType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines the data for the table footer." }, "getter": false, "setter": false, "reflect": false, "attribute": "_data-foot" }, "_fixedCols": { "type": "unknown", "mutable": false, "complexType": { "original": "FixedColsPropType", "resolved": "[number, number] | undefined", "references": { "FixedColsPropType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::FixedColsPropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines the fixed number of columns from start and end of the table" }, "getter": false, "setter": false }, "_headers": { "type": "string", "mutable": false, "complexType": { "original": "Stringified<KoliBriTableHeaders>", "resolved": "string | { horizontal?: KoliBriTableHeaderCellWithLogic[][] | undefined; vertical?: KoliBriTableHeaderCellWithLogic[][] | undefined; }", "references": { "Stringified": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::Stringified" }, "KoliBriTableHeaders": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::KoliBriTableHeaders" } } }, "required": true, "optional": false, "docs": { "tags": [], "text": "Defines the horizontal and vertical table headers." }, "getter": false, "setter": false, "reflect": false, "attribute": "_headers" }, "_label": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": true, "optional": false, "docs": { "tags": [], "text": "Defines the visible or semantic label of the component (e.g. aria-label, label, headline, caption, summary, etc.)." }, "getter": false, "setter": false, "reflect": false, "attribute": "_label" }, "_pagination": { "type": "any", "mutable": false, "complexType": { "original": "boolean | Stringified<KoliBriTablePaginationProps>", "resolved": "boolean | string | undefined | { _page: number; } & { _on?: KoliBriPaginationButtonCallbacks | undefined; _page?: number | undefined; _max?: number | undefined; _boundaryCount?: number | undefined; _hasButtons?: boolean | Stringified<PaginationHasButton> | undefined; _pageSize?: number | undefined; _pageSizeOptions?: Stringified<number[]> | undefined; _siblingCount?: number | undefined; _customClass?: string | undefined; _label?: string | undefined; _tooltipAlign?: AlignPropType | undefined; }", "references": { "Stringified": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::Stringified" }, "KoliBriTablePaginationProps": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::KoliBriTablePaginationProps" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines whether to show the data distributed over multiple pages." }, "getter": false, "setter": false, "reflect": false, "attribute": "_pagination" }, "_paginationPosition": { "type": "string", "mutable": false, "complexType": { "original": "PaginationPositionPropType", "resolved": "\"both\" | \"bottom\" | \"top\" | undefined", "references": { "PaginationPositionPropType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::PaginationPositionPropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Controls the position of the pagination." }, "getter": false, "setter": false, "reflect": false, "attribute": "_pagination-position", "defaultValue": "'bottom'" }, "_selection": { "type": "string", "mutable": false, "complexType": { "original": "TableSelectionPropType", "resolved": "string | undefined | ({ disabledKeys?: KoliBriTableSelectionKeys | undefined; keyPropertyName?: string | undefined; label: (row: KoliBriTableDataType) => string; multiple?: boolean | undefined; selectedKeys?: KoliBriTableSelectionKeys | undefined; })", "references": { "TableSelectionPropType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::TableSelectionPropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines how rows can be selected and the current selection." }, "getter": false, "setter": false, "reflect": false, "attribute": "_selection" }, "_on": { "type": "unknown", "mutable": false, "complexType": { "original": "TableStatefulCallbacksPropType", "resolved": "undefined | { onSelectionChange?: EventValueOrEventCallback<Event, StatefulSelectionChangeEventPayload> | undefined; }", "references": { "TableStatefulCallbacksPropType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::TableStatefulCallbacksPropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines the callback functions for table events." }, "getter": false, "setter": false }, "_hasSettingsMenu": { "type": "boolean", "mutable": false, "complexType": { "original": "HasSettingsMenuPropType", "resolved": "boolean | undefined", "references": { "HasSettingsMenuPropType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::HasSettingsMenuPropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Enables the settings menu if true (default: false)." }, "getter": false, "setter": false, "reflect": false, "attribute": "_has-settings-menu" }, "_variant": { "type": "string", "mutable": false, "complexType": { "original": "VariantClassNamePropType", "resolved": "string | undefined", "references": { "VariantClassNamePropType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::VariantClassNamePropType" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Defines which variant should be used for presentation." }, "getter": false, "setter": false, "reflect": false, "attribute": "_variant" } }; } static get states() { return { "resolvedElements": {}, "state": {} }; } static get methods() { return { "getSelection": { "complexType": { "signature": "() => Promise<KoliBriTableDataType[] | null>", "parameters": [], "references": { "Promise": { "location": "global", "id": "global::Promise" }, "KoliBriTableDataType": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::KoliBriTableDataType" }, "KoliBriTableSelectionKeys": { "location": "import", "path": "../../schema", "id": "src/schema/index.ts::KoliBriTableSelectionKeys" } }, "return": "Promise<KoliBriTableDataType[] | null>" }, "docs": { "text": "Returns the selected rows.", "tags": [] } }, "resetSort": { "complexType": { "signature": "() => Promise<void>", "parameters": [], "references": { "Promise": { "location": "global", "id": "global::Promise" } }, "return": "Promise<void>" }, "docs": { "text": "Resets the sort state to the default values defined in the `_headers` prop.", "tags": [] } } }; } static get elementRef() { return "host"; } static get watchers() { return [{ "propName": "_ariaLabelledby", "methodName": "validateAriaLabelledby" }, { "propName": "_allowMultiSort", "methodName": "validateAllowMultiSort" }, { "propName": "_data", "methodName": "validateData" }, { "propName": "_dataFoot", "methodName": "validateDataFoot" }, { "propName": "_fixedCols", "methodName": "validateFixedCols" }, { "propName": "_paginationPosition", "methodName": "validatePaginationPosition" }, { "propName": "_hasSettingsMenu", "methodName": "validateHasSettingsMenu" }, { "propName": "_headers", "methodName": "validateHeaders" }, { "propName": "_label", "methodName": "validateLabel" }, { "propName": "_selection", "methodName": "validateSelection" }, { "propName": "_on", "methodName": "validateOn" }, { "propName": "_pagination", "methodName": "validatePagination" }]; } } //# sourceMappingURL=shadow.js.map