{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "table",
  "type": "registry:ui",
  "title": "<ui-table>",
  "description": "Carbon `cds-table`: a table built from elements — `<ui-table-head>` with a `<ui-table-header-row>` of `<ui-table-header-cell>`s, and `<ui-table-body>` with `<ui-table-row>`s of `<ui-table-cell>`s. CSS table layout (the columns line up as in a `<table>`), `role=table` / `rowgroup` / `row` / `columnheader` / `cell`. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "lit@^3.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/button",
    "@kanok-ui/checkbox",
    "@kanok-ui/core-column-resize",
    "@kanok-ui/core-csv",
    "@kanok-ui/core-grid",
    "@kanok-ui/core-table",
    "@kanok-ui/pagination",
    "@kanok-ui/popover",
    "@kanok-ui/radio",
    "@kanok-ui/search",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-events",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-localize",
    "@kanok-ui/shared-skeleton",
    "@kanok-ui/tooltip",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/table/defs.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/defs.ts",
      "content": "/** Row heights: xs 24 · sm 32 · md 40 · lg 48 (Carbon default) · xl 64. */\nexport type TableSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl';\n\n/** A column's sort state (Carbon `TABLE_SORT_DIRECTION`). */\nexport type TableSortDirection = 'none' | 'ascending' | 'descending';\n\n/** The states a header steps through on each click (Carbon `TABLE_SORT_CYCLE`). */\nexport type TableSortCycle = 'bi-states-from-ascending' | 'bi-states-from-descending' | 'tri-states-from-ascending' | 'tri-states-from-descending';\n\n/** Carbon `TABLE_SORT_CYCLES`. */\nexport const TABLE_SORT_CYCLES: Record<TableSortCycle, readonly TableSortDirection[]> = {\n    'bi-states-from-ascending': ['ascending', 'descending'],\n    'bi-states-from-descending': ['descending', 'ascending'],\n    'tri-states-from-ascending': ['none', 'ascending', 'descending'],\n    'tri-states-from-descending': ['none', 'descending', 'ascending'],\n};\n\n/** The direction after `current` in `cycle` (Carbon `_getNextSort`; an unsorted column starts the cycle). */\nexport function nextTableSort(current: TableSortDirection, cycle: TableSortCycle = 'tri-states-from-ascending'): TableSortDirection {\n    const directions = TABLE_SORT_CYCLES[cycle];\n    const index = directions.indexOf(current);\n    if (index < 0) return directions[0];\n    return directions[(index + 1) % directions.length];\n}\n\n/** `ui-table-header-cell-sort` detail (cancelable: `preventDefault()` keeps the rows where they are). */\nexport interface TableHeaderCellSortDetail {\n    oldSortDirection: TableSortDirection;\n    sortDirection: TableSortDirection;\n}\n\n/** `ui-table-sorted` detail. */\nexport interface TableSortedDetail {\n    sortedHeader: HTMLElement;\n}\n\n/** `ui-table-row-change-selection` / `ui-table-change-selection-all` detail (cancelable). */\nexport interface TableSelectionDetail {\n    selected: boolean;\n}\n\n/** `ui-table-row-expando-beingtoggled` (cancelable) / `ui-table-row-expando-toggled` detail. */\nexport interface TableExpandoDetail {\n    expanded: boolean;\n}\n\n/** `ui-table-row-selected` detail: the row the user chose or released, and every chosen row. */\nexport interface TableRowSelectedDetail {\n    selectedRow: HTMLElement;\n    selectedRows: HTMLElement[];\n}\n\n/** `ui-table-row-all-selected` detail: every chosen row after select-all (or Cancel). */\nexport interface TableAllSelectedDetail {\n    selectedRows: HTMLElement[];\n}\n\n/** `ui-table-filtered` detail: the rows the search left in. */\nexport interface TableFilteredDetail {\n    unfilteredRows: HTMLElement[];\n}\n\n/** `ui-table-column-resize` detail: the column (its `column`, else its place) and its new width in px. */\nexport interface TableColumnResizeDetail {\n    column: string;\n    width: number;\n}\n\n/** `ui-table-columns-change` detail: every hidden column, and the one the user just showed or hid ('' after Reset). */\nexport interface TableColumnsChangeDetail {\n    hiddenColumns: string[];\n    column: string;\n    hidden: boolean;\n}\n\n/** `ui-table-page-change` detail. */\nexport interface TablePageChangeDetail {\n    page: number;\n    pageSize: number;\n}\n\n/** The editor of a column whose cells can be edited in place (a header's `editable`). */\nexport type TableCellEditor = 'text' | 'number' | 'select';\n\n/** A choice of a `select` column (a header's `options`): the value saved and the label shown. */\nexport interface TableEditOption {\n    value: string;\n    label: string;\n}\n\n/**\n * `ui-table-cell-edit` detail (cancelable, before the cell changes): the row, the cell, its column, the new value\n * (a number in a `number` column, unless left empty) and the one it had (its `sort-value`, else its text).\n */\nexport interface TableCellEditDetail {\n    row: HTMLElement;\n    cell: HTMLElement;\n    column: string;\n    value: string | number;\n    previous: string;\n}\n\n/** Which rows CSV takes: those the search shows (every page, in their order), the chosen ones, or all. */\nexport type TableCsvScope = 'shown' | 'selected' | 'all';\n\n/** `ui-table-csv-export` detail (cancelable): what the toolbar's Export CSV button is about to download. */\nexport interface TableCsvExportDetail {\n    csv: string;\n    rows: HTMLElement[];\n    fileName: string;\n}\n"
    },
    {
      "path": "src/primitives/table/table-batch-actions.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-batch-actions.ts",
      "content": "import { html, css, nothing } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-batch-actions`: the brand-coloured bar that slides over the toolbar while rows are chosen\n * (`active`, the table sets it with `selected-rows-count`): \"3 items selected\", the `<ui-button>`s you put in it,\n * and Cancel, which releases every row. With `total-rows-count` it offers \"Select all (N)\" for rows the table\n * doesn't hold (server paging): it fires `ui-table-batch-actions-select-all-clicked`, choose them yourself.\n *\n * @slot - The actions (`<ui-button>`s; the bar sizes them to the toolbar)\n * @slot cancel-button-content - Cancel's text (default: the translation)\n * @slot select-all-button-content - \"Select all (N)\"'s text\n * @csspart batch-summary - The selected-count text\n * @csspart select-all-button - \"Select all (N)\"\n * @csspart cancel-button - Cancel\n * @fires ui-table-batch-actions-cancel-clicked - Cancel was clicked (the table releases every row)\n * @fires ui-table-batch-actions-select-all-clicked - \"Select all (N)\" was clicked\n * @cssprop --ui-batch-background / --ui-batch-ink / --ui-batch-divider - The bar's fill, text and the rule before Cancel (default Carbon's brand bar: background-brand, text-on-color)\n * @cssprop --ui-batch-button / --ui-batch-button-ink / --ui-batch-button-hover / --ui-batch-button-active / --ui-batch-focus - Its buttons and their focus ring (default the primary button's colours, a layer-coloured ring)\n */\n@customElement('ui-table-batch-actions')\nexport class UiTableBatchActions extends UiElement {\n    static override readonly styles = css`\n        :host {\n            position: absolute;\n            inset-block-end: 0;\n            inset-inline: 0;\n            display: flex;\n            align-items: center;\n            justify-content: space-between;\n            block-size: var(--_toolbar, 48px);\n            /* --ui-batch-*: Carbon's brand bar; a design can make it a tinted row with ink text and text buttons */\n            background-color: var(--ui-batch-background, var(--ui-background-brand));\n            clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);\n            opacity: 0;\n            pointer-events: none;\n            transform: translate3d(0, var(--_toolbar, 48px), 0);\n            transition:\n                transform var(--ui-duration-moderate) var(--ui-easing),\n                clip-path var(--ui-duration-moderate) var(--ui-easing),\n                opacity var(--ui-duration-moderate) var(--ui-easing);\n        }\n\n        :host([active]) {\n            z-index: 1;\n            clip-path: polygon(0 0, 300% 0, 300% 300%, 0 300%);\n            opacity: 1;\n            pointer-events: all;\n            transform: translate3d(0, 0, 0);\n        }\n\n        .summary {\n            display: flex;\n            align-items: center;\n            min-inline-size: 0;\n        }\n\n        .batch-summary {\n            display: flex;\n            align-items: center;\n            min-block-size: var(--_toolbar, 48px);\n            margin: 0;\n            padding: 0 var(--ui-space-md);\n            color: var(--ui-batch-ink, var(--ui-on-primary));\n            font: var(--ui-font-body-sm);\n            line-height: 18px; /* body-compact-01 */\n            letter-spacing: var(--ui-tracking-body);\n            white-space: nowrap;\n        }\n\n        /* Carbon .batch-summary__divider */\n        .divider {\n            color: var(--ui-batch-ink, var(--ui-on-primary));\n            font: var(--ui-font-body-sm);\n        }\n\n        .action-list {\n            display: flex;\n            align-items: center;\n            block-size: 100%;\n        }\n\n        ::slotted(*) {\n            flex-shrink: 0;\n            --ui-button-padding-start: 16px; /* Carbon .action-list .btn */\n            --ui-button-padding-end: 16px;\n        }\n\n        .select-all,\n        .cancel {\n            position: relative;\n            block-size: var(--_toolbar, 48px);\n            margin: 0;\n            padding: 0 var(--ui-space-md);\n            border: 0;\n            background-color: var(--ui-batch-button, var(--ui-primary));\n            color: var(--ui-batch-button-ink, var(--ui-on-primary));\n            font: var(--ui-font-button);\n            letter-spacing: var(--ui-tracking-body);\n            white-space: nowrap;\n            cursor: pointer;\n            /* Carbon .cds--btn: the fill and the ring change in fast-01 with the entrance easing */\n            transition:\n                background-color var(--ui-duration-fast) var(--ui-easing-entrance),\n                outline var(--ui-duration-fast) var(--ui-easing-entrance);\n        }\n\n        .select-all:hover,\n        .cancel:hover {\n            background-color: var(--ui-batch-button-hover, var(--ui-blue-hover));\n        }\n\n        .select-all:active,\n        .cancel:active {\n            background-color: var(--ui-batch-button-active, var(--ui-blue-80));\n        }\n\n        .select-all:focus-visible,\n        .cancel:focus-visible {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-batch-focus, var(--ui-surface-1));\n            outline-offset: -2px; /* inside the bar: its light ring is drawn on the bar's own colour */\n            border-radius: var(--ui-focus-radius, 0); /* a ring with corners (Kanok: 6px) */\n        }\n\n        /* 1px divider before Cancel, hidden while it (or the last action) is hovered */\n        .cancel::before {\n            content: '';\n            position: absolute;\n            inset-block-start: calc((var(--_toolbar, 48px) - 16px) / 2);\n            inset-inline-start: 0;\n            inline-size: 1px;\n            block-size: 16px;\n            background-color: var(--ui-batch-divider, var(--ui-on-primary));\n            opacity: var(--_divider-opacity, 1);\n            transition: opacity var(--ui-duration-moderate) var(--ui-easing);\n        }\n\n        .cancel:hover::before {\n            opacity: 0;\n            transition: opacity 250ms cubic-bezier(0.5, 0, 0.1, 1); /* Carbon $transition-base, $standard-easing */\n        }\n\n        @media (prefers-reduced-motion: reduce) {\n            :host,\n            .cancel::before,\n            .cancel:hover::before {\n                transition: none;\n            }\n        }\n\n        @media (forced-colors: active) {\n            :host {\n                outline: 1px solid CanvasText;\n                outline-offset: -1px;\n            }\n        }\n    `;\n\n    /** Showing over the toolbar (rows are chosen). */\n    @property({ type: Boolean, reflect: true }) active = false;\n\n    /** How many rows are chosen (the table sets it; set it yourself for a selection kept across pages). */\n    @property({ type: Number, attribute: 'selected-rows-count' }) selectedRowsCount = 0;\n\n    /** Every row there is (server paging): above the count, \"Select all (N)\" shows. */\n    @property({ type: Number, attribute: 'total-rows-count' }) totalRowsCount = 0;\n\n    /** The table's size, normalized to xs / sm / lg (the table sets it): sizes the action buttons. */\n    @property({ reflect: true }) size: 'xs' | 'sm' | 'lg' = 'lg';\n\n    /** The count text (Carbon `formatSelectedItemsCount`); default: the translation. */\n    @property({ attribute: false }) formatSelectedItemsCount?: (options: { count: number }) => string;\n\n    private readonly localize = new LocalizeController(this);\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('active')) this.inert = !this.active;\n        if (changed.has('size')) this.sizeButtons();\n    }\n\n    /** The actions take the toolbar's height (Carbon sets each `cds-button`'s size). */\n    private readonly sizeButtons = () => {\n        const size = this.size === 'lg' ? 'lg' : 'sm';\n        for (const button of this.querySelectorAll(':scope > ui-button')) button.setAttribute('size', size);\n    };\n\n    /** The last action hovered: the divider before Cancel goes (Carbon). */\n    private readonly onSlotPointer = (event: Event) => {\n        const actions = [...this.children];\n        if (event.target !== actions.at(-1)) return;\n        this.style.setProperty('--_divider-opacity', event.type === 'mouseover' ? '0' : '1');\n    };\n\n    private readonly onCancel = () => {\n        this.dispatchEvent(new CustomEvent('ui-table-batch-actions-cancel-clicked', { bubbles: true, composed: true }));\n    };\n\n    private readonly onSelectAll = () => {\n        this.dispatchEvent(new CustomEvent('ui-table-batch-actions-select-all-clicked', { bubbles: true, composed: true }));\n    };\n\n    override render() {\n        const t = this.localize.t.dataTable;\n        const count = this.selectedRowsCount;\n        const text = this.formatSelectedItemsCount?.({ count }) ?? t.selectedCount(count);\n        const selectAll = this.totalRowsCount > count;\n        return html`<div class=\"summary\">\n                <p class=\"batch-summary\" part=\"batch-summary\" role=\"status\">${text}</p>\n                ${selectAll\n                    ? html`<span class=\"divider\" aria-hidden=\"true\">|</span>\n                          <button class=\"select-all\" part=\"select-all-button\" type=\"button\" @click=${this.onSelectAll}><slot name=\"select-all-button-content\">${t.selectAllCount(this.totalRowsCount)}</slot></button>`\n                    : nothing}\n            </div>\n            <div class=\"action-list\" @mouseover=${this.onSlotPointer} @mouseout=${this.onSlotPointer}>\n                <slot @slotchange=${this.sizeButtons}></slot>\n                <button class=\"cancel\" part=\"cancel-button\" type=\"button\" @click=${this.onCancel}><slot name=\"cancel-button-content\">${t.cancel}</slot></button>\n            </div>`;\n    }\n}\n\nexport interface UiTableBatchActionsEventMap extends HTMLElementEventMap {\n    'ui-table-batch-actions-cancel-clicked': CustomEvent<null>;\n    'ui-table-batch-actions-select-all-clicked': CustomEvent<null>;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-batch-actions': UiTableBatchActions;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-body.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-body.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\nimport type { UiTableRow } from './table-row.ts';\n\n/**\n * Carbon `cds-table-body`: the body row group of a `<ui-table>` (`role=rowgroup`). With\n * `use-zebra-styles` (the table sets it) it marks its rows `even` / `odd` whenever they change.\n *\n * @slot - The `<ui-table-row>`s\n * @fires ui-table-body-content-change - its rows were added, removed or reordered (the table listens)\n */\n@customElement('ui-table-body')\nexport class UiTableBody extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: table-row-group;\n            background-color: var(--ui-table-background, var(--ui-surface-1));\n        }\n    `;\n\n    /** Stripe every second row (the table passes its `use-zebra-styles`). */\n    @property({ type: Boolean, reflect: true, attribute: 'use-zebra-styles' }) useZebraStyles = false;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'rowgroup');\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('useZebraStyles')) this.updateZebra();\n    }\n\n    /** Marks the rows `even` / `odd` in document order (Carbon `_updateZebra`), counting only the rows shown (search, page). */\n    updateZebra() {\n        let index = 0;\n        for (const row of this.children) {\n            if (row.localName !== 'ui-table-row' || (row as UiTableRow).filtered || (row as UiTableRow).pagedOut) continue;\n            index++;\n            const even = index % 2 === 0;\n            (row as UiTableRow).even = this.useZebraStyles && even;\n            (row as UiTableRow).odd = this.useZebraStyles && !even;\n        }\n    }\n\n    private readonly onSlotChange = () => {\n        this.updateZebra();\n        this.dispatchEvent(new Event('ui-table-body-content-change', { bubbles: true }));\n    };\n\n    override render() {\n        return html`<slot @slotchange=${this.onSlotChange}></slot>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-body': UiTableBody;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-cell.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-cell.ts",
      "content": "import { html, css, svg, nothing } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { live } from 'lit/directives/live.js';\nimport { UiElement } from '../shared/element.ts';\nimport type { TableCellEditDetail, TableCellEditor, TableEditOption } from './defs.ts';\nimport { pinnedCellBackground, tableColumnStyles } from './table-column.styles.ts';\n\n/** Carbon ChevronDown 16, as in ui-select. */\nconst chevronDown = svg`<path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" />`;\n\nconst pencil = svg`<path d=\"M2 13h12v1H2zm10.7-8.3L11.3 3.3a1 1 0 0 0-1.4 0L4 9.2V12h2.8l5.9-5.9a1 1 0 0 0 0-1.4ZM6.4 11H5V9.6l4-4L10.4 7Zm4.7-4.7L9.7 4.9l1-1 1.4 1.4Z\" />`;\n\nconst option = (choice: TableEditOption, selected: boolean) => html`<option value=${choice.value} ?selected=${selected}>${choice.label}</option>`;\n\n/**\n * Carbon `cds-table-cell`: one cell of a `<ui-table-row>` (`role=cell`). Its padding follows the table's\n * `size`; its rules and text colour follow the row (zebra stripe, hover).\n *\n * Sorting reads the cell's `sort-value` attribute when it has one, else its text: give a date or an\n * amount shown as \"12,000 ฿\" its plain value (`sort-value=\"12000\"`). CSV reads `csv-value`, else the text.\n *\n * The table sets `column-hidden`, `pinned` and `editable` from the cell's column header, and `editing` while\n * the cell's editor is open (an editable column: a pencil after the value on hover and focus).\n *\n * @slot - The cell's content\n * @csspart content - The box inside the cell that holds its padding\n * @csspart edit-icon - The pencil of an editable cell\n * @csspart editor - The input or select while editing\n * @csspart error - The `validate` message under the editor\n * @cssprop --ui-table-cell-ink - Text colour of a row at rest (default `--ui-ink-muted`; Kanok: `--ui-ink`)\n */\n@customElement('ui-table-cell')\nexport class UiTableCell extends UiElement {\n    static override readonly styles = [\n        tableColumnStyles,\n        pinnedCellBackground,\n        css`\n            /*\n             * The padding and the rule are drawn in the shadow root, not on :host: a page-level reset\n             * (Tailwind preflight's * { padding: 0; border: 0 }) beats :host rules.\n             */\n            :host {\n                display: table-cell;\n                /* only a rule below (Carbon web components): border-subtle (00 on the page, 01 / 02 in layers) */\n                box-shadow:\n                    var(--_pin-edge, 0 0 #0000),\n                    inset 0 -1px 0 var(--_row-rule-end, var(--ui-hairline));\n                /* Carbon: secondary text until hovered or chosen; --ui-table-cell-ink lets a design use primary text */\n                color: var(--_row-ink, var(--ui-table-cell-ink, var(--ui-ink-muted)));\n                font: var(--ui-font-body-sm);\n                line-height: 18px; /* body-compact-01 */\n                letter-spacing: var(--ui-tracking-body);\n                text-align: start;\n                vertical-align: var(--_align, middle);\n            }\n\n            /* the rule takes the cell's last pixel, as a collapsed 1px border did */\n            .content {\n                padding-block: var(--_cell-pad-start, 0px) calc(var(--_cell-pad-end, 0px) + 1px);\n                padding-inline: var(--ui-space-md);\n            }\n\n            /* a grid cell (an editable table): Carbon's focus ring inside the cell */\n            :host(:focus-visible) {\n                outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n                outline-offset: -2px;\n            }\n\n            :host([editable]) {\n                position: relative;\n                cursor: text;\n            }\n\n            /* right after the value, so it reads as that value's control (hidden but in place: nothing shifts on hover) */\n            .edit-icon {\n                inline-size: 16px;\n                block-size: 16px;\n                margin-inline-start: var(--ui-space-xs);\n                vertical-align: text-bottom;\n                fill: var(--ui-ink-muted);\n                opacity: 0;\n                cursor: pointer;\n            }\n\n            :host([editable]:hover) .edit-icon,\n            :host([editable]:focus) .edit-icon {\n                opacity: 1;\n            }\n\n            :host([editing]) .content {\n                padding: 0 0 1px;\n            }\n\n            .editor {\n                box-sizing: border-box;\n                display: block;\n                inline-size: 100%;\n                min-block-size: calc(var(--_row, 48px) - 1px); /* the cell keeps its rule below */\n                margin: 0;\n                padding-inline: var(--ui-space-md);\n                border: none;\n                border-radius: 0;\n                background-color: var(--ui-surface-1);\n                color: var(--ui-ink);\n                font: var(--ui-font-body-sm);\n                font-size: var(--ui-field-font-size, 14px);\n                letter-spacing: var(--ui-tracking-body);\n                text-align: inherit;\n                outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n                outline-offset: -2px;\n            }\n\n            /* Carbon select: own chevron 16px from the end, room for it in the padding, the same in every browser */\n            select.editor {\n                appearance: none;\n                padding-inline-end: calc(var(--ui-space-md) * 2 + 16px);\n                cursor: pointer;\n            }\n\n            .chevron {\n                position: absolute;\n                inset-block-start: calc(50% - 8px);\n                inset-inline-end: var(--ui-space-md);\n                inline-size: 16px;\n                block-size: 16px;\n                fill: var(--ui-ink);\n                pointer-events: none;\n            }\n\n            .editor[aria-invalid='true'] {\n                outline-color: var(--ui-error);\n            }\n\n            .error {\n                position: absolute;\n                z-index: 1;\n                inset-block-start: 100%;\n                inset-inline-start: 0;\n                padding: var(--ui-space-xxs) var(--ui-space-xs);\n                background-color: var(--ui-surface-1);\n                box-shadow: 0 2px 6px rgb(0 0 0 / 0.3);\n                color: var(--ui-error-text, var(--ui-error));\n                font: var(--ui-font-caption);\n                letter-spacing: var(--ui-tracking-caption);\n                white-space: nowrap;\n            }\n\n            @media (forced-colors: active) {\n                :host {\n                    border-block-end: 1px solid; /* shadows are dropped */\n                }\n\n                .edit-icon,\n                .chevron {\n                    fill: CanvasText;\n                }\n            }\n        `,\n    ];\n\n    /** Its column is hidden (the table follows the header's `column-hidden`). */\n    @property({ type: Boolean, reflect: true, attribute: 'column-hidden' }) columnHidden = false;\n\n    /** Its column is pinned (the table follows the header's `pinned`). */\n    @property({ reflect: true }) pinned?: 'start' | 'end';\n\n    /** Its column's editor (the table follows the header's `editable`). */\n    @property({ reflect: true }) editable?: TableCellEditor;\n\n    /** The editor is open (the table sets it). */\n    @property({ type: Boolean, reflect: true }) editing = false;\n\n    /** The editor's text while editing (the table sets where it starts). */\n    @property({ attribute: false }) draft = '';\n\n    /** The editor's name for screen readers: the column and the row (the table sets it). */\n    @property({ attribute: false }) editorLabel = '';\n\n    /** A select editor's choices (the header's `options`). */\n    @property({ attribute: false }) editorOptions: TableEditOption[] = [];\n\n    /** The header's `validate` message for the value in the editor. */\n    @property({ attribute: false }) editorError = '';\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'cell');\n    }\n\n    /** What the editor holds now. */\n    get editorValue() {\n        return this.renderRoot.querySelector<HTMLInputElement | HTMLSelectElement>('.editor')?.value ?? this.draft;\n    }\n\n    /** Focuses the open editor; `select` selects a text editor's text (else the caret goes to the end). */\n    focusEditor(select: boolean) {\n        const editor = this.renderRoot.querySelector<HTMLInputElement | HTMLSelectElement>('.editor');\n        editor?.focus();\n        if (!(editor instanceof HTMLInputElement)) return;\n        if (select) editor.select();\n        else if (editor.type === 'text') editor.setSelectionRange(editor.value.length, editor.value.length);\n    }\n\n    private readonly onDraft = (event: Event) => {\n        this.draft = (event.target as HTMLInputElement | HTMLSelectElement).value;\n    };\n\n    private renderError() {\n        return this.editorError ? html`<span class=\"error\" id=\"error\" part=\"error\" role=\"alert\">${this.editorError}</span>` : nothing;\n    }\n\n    private renderEditor() {\n        const invalid = this.editorError ? 'true' : 'false';\n        const describedBy = this.editorError ? 'error' : nothing;\n        if (this.editable === 'select') {\n            return html`<select class=\"editor\" part=\"editor\" aria-label=${this.editorLabel} aria-invalid=${invalid} aria-describedby=${describedBy} @input=${this.onDraft} @change=${this.onDraft}>\n                    ${this.editorOptions.map((choice) => option(choice, choice.value === this.draft))}\n                </select><svg class=\"chevron\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">${chevronDown}</svg>${this.renderError()}`;\n        }\n        const numeric = this.editable === 'number';\n        return html`<input\n                class=\"editor\"\n                part=\"editor\"\n                type=${numeric ? 'number' : 'text'}\n                inputmode=${numeric ? 'decimal' : nothing}\n                .value=${live(this.draft)}\n                aria-label=${this.editorLabel}\n                aria-invalid=${invalid}\n                aria-describedby=${describedBy}\n                @input=${this.onDraft}\n            />${this.renderError()}`;\n    }\n\n    private renderContent() {\n        if (this.editing) return this.renderEditor();\n        if (!this.editable) return html`<slot></slot>`;\n        return html`<slot></slot><svg class=\"edit-icon\" part=\"edit-icon\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">${pencil}</svg>`;\n    }\n\n    override render() {\n        return html`<div class=\"content\" part=\"content\">${this.renderContent()}</div>`;\n    }\n}\n\nexport interface UiTableCellEventMap extends HTMLElementEventMap {\n    /** The table's grid fires it from the cell before writing an edited value (cancelable). */\n    'ui-table-cell-edit': CustomEvent<TableCellEditDetail>;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-cell': UiTableCell;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-column-resize.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-column-resize.ts",
      "content": "import { html, css, isServer, nothing } from 'lit';\nimport { clampColumnWidth, columnMax, columnMin, resizeKeyWidth } from '../../core/column-resize.ts';\nimport type { TableColumnResizeDetail } from './defs.ts';\n\n/** What the resize handle needs from its header cell. */\nexport interface ResizableHeader extends HTMLElement {\n    width?: number;\n    minWidth?: number;\n    maxWidth?: number;\n    /** The column's key (its `column`, else its place). */\n    readonly columnKey: string;\n    /** The header's text, for the handle's name. */\n    readonly labelText: string;\n}\n\n/** The table's side: freeze the automatic layout (and say how wide the scroll box is). */\nexport interface ResizeTable extends HTMLElement {\n    freezeColumns(): void;\n    readonly contentWidth: number;\n}\n\n/**\n * Column resizing on a `<ui-table-header-cell>`, after IBM Products Datagrid (Carbon's DataTable has none): a handle\n * on the header's end edge — drag it, or Tab to it (a native range input: screen readers get a slider named after the\n * column, with its width in pixels) and use the arrow keys (2px; Shift, Page Up / Down 16px; Home / End narrowest /\n * widest). The first resize freezes the table's automatic layout into fixed widths. Each finished resize (one drag,\n * one key press) fires `ui-table-column-resize`.\n */\nexport class HeaderResize {\n    private drag: { startX: number; startWidth: number } | null = null;\n    /** A width shown but not reported yet. */\n    private pending = false;\n\n    private readonly host: ResizableHeader;\n\n    constructor(host: ResizableHeader) {\n        this.host = host;\n    }\n\n    private get table() {\n        if (isServer) return null; // render() reads the view width; there's no DOM on a server\n        return this.host.closest('ui-table') as ResizeTable | null;\n    }\n\n    private get rtl() {\n        return this.host.matches(':dir(rtl)');\n    }\n\n    private get viewWidth() {\n        return this.table?.contentWidth ?? 0;\n    }\n\n    private get current() {\n        return this.host.width ?? Math.floor(this.host.getBoundingClientRect().width);\n    }\n\n    private freeze() {\n        this.table?.freezeColumns();\n    }\n\n    private apply(width: number) {\n        this.host.width = clampColumnWidth(this.host, width, this.viewWidth);\n        this.pending = true;\n    }\n\n    private commit() {\n        if (!this.pending) return;\n        this.pending = false;\n        const detail: TableColumnResizeDetail = { column: this.host.columnKey, width: this.host.width ?? this.current };\n        this.host.dispatchEvent(new CustomEvent('ui-table-column-resize', { detail, bubbles: true, composed: true }));\n    }\n\n    private readonly onPointerDown = (event: PointerEvent) => {\n        if (event.button !== 0) return;\n        event.preventDefault(); // no native slider drag, no text selection\n        this.freeze();\n        const input = event.currentTarget as HTMLInputElement;\n        input.focus({ preventScroll: true });\n        input.setPointerCapture?.(event.pointerId);\n        this.drag = { startX: event.clientX, startWidth: this.current };\n        this.host.dataset.resizing = '';\n    };\n\n    private readonly onPointerMove = (event: PointerEvent) => {\n        if (!this.drag) return;\n        this.apply(this.drag.startWidth + (event.clientX - this.drag.startX) * (this.rtl ? -1 : 1));\n    };\n\n    private readonly onPointerEnd = () => {\n        if (!this.drag) return;\n        this.drag = null;\n        delete this.host.dataset.resizing;\n        this.commit();\n    };\n\n    private readonly onKeyDown = (event: KeyboardEvent) => {\n        const width = resizeKeyWidth(event.key, { shift: event.shiftKey, rtl: this.rtl, current: this.current, column: this.host, viewWidth: this.viewWidth });\n        if (width === undefined) return;\n        event.preventDefault(); // the native slider would move by its own step\n        event.stopPropagation(); // not a key for the header's sort button\n        this.freeze();\n        this.apply(width);\n    };\n\n    private readonly onKeyUp = () => {\n        if (!this.drag) this.commit();\n    };\n\n    /** A value set some other way (assistive technology increments the slider). */\n    private readonly onInput = (event: Event) => {\n        if (this.drag) return;\n        this.freeze();\n        this.apply(Number((event.currentTarget as HTMLInputElement).value));\n        this.commit();\n    };\n\n    /** Focusing the handle freezes the layout, so the slider reads the column's real width. */\n    private readonly onFocus = () => this.freeze();\n\n    private readonly onBlur = () => {\n        if (!this.drag) this.commit();\n    };\n\n    render(messages: { resizeColumn: (header: string) => string; columnWidth: (px: number) => string }) {\n        const width = this.host.width;\n        const min = columnMin(this.host);\n        return html`<input\n                class=\"resizer\"\n                part=\"resizer\"\n                type=\"range\"\n                min=${min}\n                max=${columnMax(this.host, width ?? 0, this.viewWidth)}\n                step=\"1\"\n                .value=${String(width ?? min)}\n                aria-label=${messages.resizeColumn(this.host.labelText)}\n                aria-valuetext=${width === undefined ? nothing : messages.columnWidth(width)}\n                @pointerdown=${this.onPointerDown}\n                @pointermove=${this.onPointerMove}\n                @pointerup=${this.onPointerEnd}\n                @pointercancel=${this.onPointerEnd}\n                @keydown=${this.onKeyDown}\n                @keyup=${this.onKeyUp}\n                @input=${this.onInput}\n                @focus=${this.onFocus}\n                @blur=${this.onBlur}\n                @click=${(e: Event) => e.stopPropagation()}\n            /><span class=\"resize-bar\" aria-hidden=\"true\"></span><span class=\"guide\" aria-hidden=\"true\"></span>`;\n    }\n}\n\n/** IBM Products Datagrid resizer: hover strip and line on the header's end edge, a blue line and dot for the keyboard. */\nexport const headerResizeStyles = css`\n    :host([resizable]:not([pinned])) {\n        position: relative;\n    }\n\n    @media (any-hover: hover) {\n        :host([resizable]:hover) {\n            background-color: var(--ui-table-sort-hover, var(--ui-layer-selected-hover)); /* the header's hover (table-header-cell.ts) */\n        }\n    }\n\n    /* grab area centred on the edge (IBM: 16px; 24px for WCAG 2.2 target size); the native slider is invisible */\n    .resizer {\n        position: absolute;\n        z-index: 2;\n        inset-block-start: 0;\n        inset-inline-end: -12px;\n        box-sizing: border-box;\n        inline-size: 24px;\n        block-size: 100%;\n        margin: 0;\n        padding: 0;\n        appearance: none;\n        background: transparent;\n        cursor: col-resize;\n        touch-action: none;\n    }\n\n    .resizer::-webkit-slider-thumb {\n        inline-size: 16px;\n        block-size: 16px;\n        border: 0;\n        appearance: none;\n        background: transparent;\n    }\n\n    .resizer::-moz-range-thumb {\n        visibility: hidden;\n    }\n\n    .resizer:focus {\n        outline: none;\n    }\n\n    /* the 4px strip and its 2px line, 3px either side of the edge (IBM .datagrid__resizer) */\n    .resize-bar {\n        position: absolute;\n        z-index: 1;\n        inset-block: 0;\n        inset-inline-end: -3px;\n        inline-size: 4px;\n        border-inline-end: 2px solid transparent;\n        pointer-events: none;\n    }\n\n    @media (any-hover: hover) {\n        :host([resizable]:hover) .resize-bar {\n            border-inline-end-color: var(--ui-hairline-strong);\n            background-color: var(--ui-canvas-selected-hover);\n        }\n    }\n\n    :host([data-resizing]) .resize-bar {\n        border-inline-end-color: var(--ui-secondary-hover);\n    }\n\n    /* keyboard: a 2px focus line the height of the header with an 8px dot, and a 1px guide down the body */\n    .resizer:focus-visible + .resize-bar {\n        border-inline-end-color: transparent;\n        background: none;\n    }\n\n    .resizer:focus-visible + .resize-bar::before {\n        position: absolute;\n        inset-block: 0;\n        inset-inline-end: -1px;\n        inline-size: 2px;\n        background-color: var(--ui-focus);\n        content: '';\n    }\n\n    .resizer:focus-visible + .resize-bar::after {\n        position: absolute;\n        inset-block-start: calc(50% - 4px);\n        inset-inline-end: -4px;\n        inline-size: 8px;\n        block-size: 8px;\n        border-radius: 50%;\n        background-color: var(--ui-focus);\n        content: '';\n    }\n\n    .guide {\n        position: absolute;\n        z-index: 1;\n        inset-block-start: 100%;\n        inset-inline-end: -0.5px;\n        display: none;\n        inline-size: 1px;\n        block-size: var(--_resize-guide, 0);\n        background-color: var(--ui-ghost-active);\n        pointer-events: none;\n    }\n\n    :host([data-resizing]) .guide,\n    .resizer:focus-visible ~ .guide {\n        display: block;\n    }\n\n    @media (forced-colors: active) {\n        .resizer:focus-visible + .resize-bar::before,\n        .resizer:focus-visible + .resize-bar::after,\n        .guide {\n            background-color: Highlight;\n        }\n\n        :host([data-resizing]) .resize-bar,\n        :host([resizable]:hover) .resize-bar {\n            border-inline-end-color: Highlight;\n        }\n    }\n`;\n"
    },
    {
      "path": "src/primitives/table/table-column-settings.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-column-settings.ts",
      "content": "import { html, css, isServer } from 'lit';\nimport { customElement, query, state } from 'lit/decorators.js';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { toolbarActionStyles } from './table-toolbar-action.styles.ts';\nimport type { UiCheckbox } from '../checkbox/checkbox.ts';\nimport type { UiTooltip } from '../tooltip/tooltip.ts';\nimport '../popover/popover.ts';\nimport '../checkbox/checkbox.ts';\nimport '../checkbox/checkbox-group.ts';\nimport '../button/button.ts';\nimport '../tooltip/tooltip.ts';\nimport { isOwnEvent } from '../shared/events.ts';\n\n/** Carbon `Column` 16. */\nconst columnIcon = html`<svg viewBox=\"0 0 32 32\" aria-hidden=\"true\"><path d=\"M24 4h2v24h-2zM18 6v20h-4V6h4m0-2h-4a2 2 0 0 0-2 2v20a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2ZM6 4h2v24H6z\" /></svg>`;\n\n/** What the settings need from their `<ui-table>`. */\ninterface ColumnsTable extends HTMLElement {\n    readonly columns: Array<HTMLElement & { columnKey: string; columnHidden: boolean; hideable: boolean; labelText: string }>;\n    readonly hiddenColumns: string[];\n    readonly columnsChanged: boolean;\n    isColumnLocked(column: string): boolean;\n    setColumnHidden(column: string, hidden: boolean): boolean;\n    resetColumns(): void;\n}\n\n/**\n * Column settings for a `<ui-table>` (no Carbon counterpart; Carbon keeps the toolbar for \"table display\n * settings\"): a Column-icon toolbar action in `<ui-table-toolbar-content>` that opens a \"Columns\" checkbox list —\n * unticking hides a column at once; the last column shown and a header with `hideable=\"false\"` can't be hidden.\n * Reset goes back to the columns hidden in the markup. The table fires `ui-table-columns-change`.\n *\n * @csspart button - The toolbar action\n * @csspart panel - The \"Columns\" list\n */\n@customElement('ui-table-column-settings')\nexport class UiTableColumnSettings extends UiElement {\n    static override readonly styles = [\n        toolbarActionStyles,\n        css`\n        :host {\n            display: block;\n            flex-shrink: 0;\n        }\n\n        /* Carbon toolbar menu: layer-02 while open */\n        .button[aria-expanded='true'] {\n            background-color: var(--ui-layer-2);\n        }\n\n        /* as Carbon's toolbar menu: flush under the button, layer-02, the menu shadow */\n        ui-popover::part(content) {\n            background-color: var(--ui-layer-2);\n            box-shadow: var(--ui-menu-shadow, 0 2px 6px rgb(0 0 0 / 0.3));\n        }\n\n        .panel {\n            box-sizing: border-box;\n            min-inline-size: 160px;\n            max-block-size: 320px;\n            padding: var(--ui-space-md) var(--ui-space-md) var(--ui-space-xs);\n            overflow-y: auto;\n            overscroll-behavior: contain;\n        }\n\n        /* the label lines up with the boxes above */\n        .reset {\n            margin-block-start: var(--ui-space-xs);\n            margin-inline-start: calc(-1 * var(--ui-space-md));\n        }\n    `,\n    ];\n\n    @state() private open = false;\n\n    @query('.button') private readonly button?: HTMLButtonElement;\n    @query('ui-tooltip') private readonly tip?: UiTooltip;\n\n    private readonly localize = new LocalizeController(this);\n\n    private get table() {\n        if (isServer) return null; // no DOM to search on a server; the panel renders closed there anyway\n        return this.closest('ui-table') as ColumnsTable | null;\n    }\n\n    override connectedCallback() {\n        super.connectedCallback();\n        this.table?.addEventListener('ui-table-columns-change', this.refresh);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.table?.removeEventListener('ui-table-columns-change', this.refresh);\n    }\n\n    private readonly refresh = () => this.requestUpdate();\n\n    protected override updated() {\n        // the button's tooltip names it and opens on its hover / focus (the button is the popover's trigger)\n        const tip = this.tip;\n        const button = this.button ?? null;\n        if (tip && tip.anchor !== button) tip.anchor = button;\n    }\n\n    private readonly onCheck = (event: Event) => {\n        event.stopPropagation();\n        const box = event.target as UiCheckbox;\n        const changed = this.table?.setColumnHidden(box.dataset.column ?? '', !box.checked);\n        if (!changed) box.checked = !box.checked; // locked: put it back\n        this.requestUpdate();\n    };\n\n    private readonly onReset = () => {\n        this.table?.resetColumns();\n    };\n\n    private renderPanel(table: ColumnsTable) {\n        const t = this.localize.t.dataTable;\n        const columns = table.columns;\n        return html`<div class=\"panel\" part=\"panel\">\n            <ui-checkbox-group label=${t.columns}>\n                ${columns.map(\n                    (c) =>\n                        html`<ui-checkbox data-column=${c.columnKey} .checked=${!c.columnHidden || !c.hideable} ?disabled=${table.isColumnLocked(c.columnKey)} @change=${this.onCheck}>${c.labelText}</ui-checkbox>`,\n                )}\n            </ui-checkbox-group>\n            <ui-button class=\"reset\" kind=\"ghost\" size=\"sm\" ?disabled=${!table.columnsChanged} @click=${this.onReset}>${t.resetColumns}</ui-button>\n        </div>`;\n    }\n\n    override render() {\n        const t = this.localize.t.dataTable;\n        const table = this.table;\n        return html`<ui-popover placement=\"bottom-end\" caret=\"false\" drop-shadow=\"false\" auto-close .open=${this.open} @ui-toggle=${(e: CustomEvent<{ open: boolean }>) => { if (isOwnEvent(e)) this.open = e.detail.open; }}>\n                <button slot=\"trigger\" class=\"button\" part=\"button\" type=\"button\" aria-label=${t.columns} aria-expanded=${this.open ? 'true' : 'false'} @click=${() => (this.open = !this.open)}>${columnIcon}</button>\n                ${this.open && table ? this.renderPanel(table) : html``}\n            </ui-popover>\n            <ui-tooltip as-label text=${t.columns} placement=\"top\"></ui-tooltip>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-column-settings': UiTableColumnSettings;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-column.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-column.styles.ts",
      "content": "import { css } from 'lit';\n\n/**\n * What a header cell and a body cell share as part of a column: hidden by the column settings, and pinned to\n * the start (the first column, from 672px wide, as IBM Products) or the end (the last) while the table scrolls\n * sideways — on the row's colours, with a border-subtle rule on the inner edge (shadows travel with sticky\n * cells; collapsed borders don't). The rule is `--_pin-edge`, a shadow each cell adds to its own.\n */\nexport const tableColumnStyles = css`\n    :host([column-hidden]) {\n        display: none;\n    }\n\n    :host([pinned='end']) {\n        position: sticky;\n        inset-inline-end: 0;\n        z-index: 1;\n        --_pin-edge: inset calc(1px * var(--_dir, 1)) 0 0 var(--ui-hairline);\n    }\n\n    @media (min-width: 672px) {\n        :host([pinned='start']) {\n            position: sticky;\n            inset-inline-start: var(--_pin-first-at, 0px);\n            z-index: 1;\n            --_pin-edge: inset calc(-1px * var(--_dir, 1)) 0 0 var(--ui-hairline);\n        }\n    }\n`;\n\n/**\n * A pinned body cell paints its row's colour itself (the row's own background stays behind the cells that\n * scroll under it): the row's tint (hover, translucent) over its base (zebra, chosen, else the layer).\n */\nexport const pinnedCellBackground = css`\n    :host([pinned]) {\n        background: linear-gradient(var(--_row-tint, transparent), var(--_row-tint, transparent)), var(--_row-base, var(--ui-surface-1));\n    }\n`;\n"
    },
    {
      "path": "src/primitives/table/table-csv-export.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-csv-export.ts",
      "content": "import { html, css, isServer } from 'lit';\nimport { customElement, property, query } from 'lit/decorators.js';\nimport { downloadCsv } from '../../core/csv.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\nimport type { UiTooltip } from '../tooltip/tooltip.ts';\nimport '../tooltip/tooltip.ts';\nimport type { TableCsvExportDetail, TableCsvScope } from './defs.ts';\nimport { toolbarActionStyles } from './table-toolbar-action.styles.ts';\n\n/** Carbon `Download` 16. */\nconst downloadIcon = html`<svg viewBox=\"0 0 32 32\" aria-hidden=\"true\"><path d=\"M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4ZM26 14l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10 10-10z\" /></svg>`;\n\n/** What the button needs from its `<ui-table>`. */\ninterface CsvTable extends HTMLElement {\n    csvRows(scope: TableCsvScope): HTMLElement[];\n    toCsv(options?: { scope?: TableCsvScope }): string;\n    readonly csvFileName: string;\n}\n\n/**\n * An \"Export CSV\" toolbar action for a `<ui-table>` (no Carbon counterpart), in `<ui-table-toolbar-content>`:\n * a Download-icon button that downloads the rows the search shows (every page) and the columns shown, for Excel\n * (UTF-8 with a byte order mark, every cell quoted, formulas defused). A cell writes its `csv-value`, else its text.\n * It fires a cancelable `ui-table-csv-export` first (`preventDefault()` to export another way). `file-name` names\n * the file (default: the table's title, else \"table\"). The table's `toCsv()` / `downloadCsv()` export any rows.\n *\n * @csspart button - The toolbar action\n * @fires ui-table-csv-export - cancelable; detail: { csv, rows, fileName } before the download\n */\n@customElement('ui-table-csv-export')\nexport class UiTableCsvExport extends UiElement {\n    static override readonly styles = [\n        toolbarActionStyles,\n        css`\n            :host {\n                display: block;\n                flex-shrink: 0;\n            }\n        `,\n    ];\n\n    /** The downloaded file's name (`.csv` is added); default: the table's title, else \"table\". */\n    @property({ attribute: 'file-name' }) fileName = '';\n\n    @query('.button') private readonly button?: HTMLButtonElement;\n    @query('ui-tooltip') private readonly tip?: UiTooltip;\n\n    private readonly localize = new LocalizeController(this);\n\n    private get table() {\n        if (isServer) return null;\n        return this.closest('ui-table') as CsvTable | null;\n    }\n\n    protected override updated() {\n        // the button's tooltip names it and opens on its hover / focus\n        const tip = this.tip;\n        const button = this.button ?? null;\n        if (tip && tip.anchor !== button) tip.anchor = button;\n    }\n\n    private readonly onClick = () => {\n        const table = this.table;\n        if (!table) return;\n        const detail: TableCsvExportDetail = { csv: table.toCsv(), rows: table.csvRows('shown'), fileName: this.fileName || table.csvFileName };\n        const go = this.dispatchEvent(new CustomEvent('ui-table-csv-export', { detail, bubbles: true, composed: true, cancelable: true }));\n        if (go) downloadCsv(detail.csv, detail.fileName);\n    };\n\n    override render() {\n        const label = this.localize.t.dataTable.exportCsv;\n        return html`<button class=\"button\" part=\"button\" type=\"button\" aria-label=${label} @click=${this.onClick}>${downloadIcon}</button>\n            <ui-tooltip as-label text=${label} placement=\"top\"></ui-tooltip>`;\n    }\n}\n\nexport interface UiTableCsvExportEventMap extends HTMLElementEventMap {\n    'ui-table-csv-export': CustomEvent<TableCsvExportDetail>;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-csv-export': UiTableCsvExport;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-expanded-row.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-expanded-row.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-expanded-row`: the full-width content under the `<ui-table-row>` right before it, shown while\n * that row is `expanded`. The table sets `colspan` to the number of columns; hovering either row tints both.\n *\n * @slot - The content\n * @csspart cell - The full-width cell\n */\n@customElement('ui-table-expanded-row')\nexport class UiTableExpandedRow extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: table-row;\n            transition: background-color var(--ui-duration-fast) var(--ui-easing-entrance);\n        }\n\n        :host(:not([expanded])),\n        :host([filtered]),\n        :host([paged-out]) {\n            display: none;\n        }\n\n        /* Carbon web components: background-hover while its row is chosen or hovered, the text then primary */\n        :host([selected]) {\n            --_expanded-ink: var(--ui-ink);\n\n            background-color: var(--ui-canvas-hover);\n        }\n\n        @media (any-hover: hover) {\n            :host(:hover),\n            :host([highlighted]) {\n                --_expanded-ink: var(--ui-ink);\n\n                background-color: var(--ui-canvas-hover);\n            }\n\n            :host([selected][highlighted]) {\n                background-color: var(--ui-layer-accent);\n            }\n        }\n\n        /* Carbon web components: 64px in, no padding above or below (xl: 16 / 16 / 8) */\n        td {\n            box-sizing: border-box;\n            padding: var(--_expanded-pad, 0 0 0 64px);\n            border-block-end: 1px solid var(--ui-hairline);\n            color: var(--_expanded-ink, var(--ui-ink-muted));\n            font: var(--ui-font-body-sm);\n            line-height: 18px;\n            letter-spacing: var(--ui-tracking-body);\n            vertical-align: middle;\n        }\n\n        @media (prefers-reduced-motion: reduce) {\n            :host {\n                transition: none;\n            }\n        }\n    `;\n\n    /** How many columns it spans (the table sets it). */\n    @property({ type: Number, attribute: 'colspan' }) colSpan = 1;\n\n    /** Shown (follows the row before it). */\n    @property({ type: Boolean, reflect: true }) expanded = false;\n\n    /** Left out by the table's search, with its row. */\n    @property({ type: Boolean, reflect: true }) filtered = false;\n\n    /** On another page, with its row. */\n    @property({ type: Boolean, reflect: true, attribute: 'paged-out' }) pagedOut = false;\n\n    /** Hovered with its row. */\n    @property({ type: Boolean, reflect: true }) highlighted = false;\n\n    /** Its row is chosen. */\n    @property({ type: Boolean, reflect: true }) selected = false;\n\n    /** The table is a grid (an editable column): a grid cell (the table sets it). */\n    @property({ type: Boolean, attribute: false }) grid = false;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'row');\n        this.addEventListener('mouseover', this.onPointer);\n        this.addEventListener('mouseout', this.onPointer);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('mouseover', this.onPointer);\n        this.removeEventListener('mouseout', this.onPointer);\n    }\n\n    private readonly onPointer = (event: MouseEvent) => {\n        const row = this.previousElementSibling;\n        if (row?.localName === 'ui-table-row') (row as HTMLElement & { highlighted: boolean }).highlighted = event.type === 'mouseover';\n    };\n\n    override render() {\n        return html`<td role=${this.grid ? 'gridcell' : 'cell'} part=\"cell\" colspan=${this.colSpan}><slot></slot></td>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-expanded-row': UiTableExpandedRow;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-grid.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-grid.ts",
      "content": "import type { ReactiveControllerHost } from 'lit';\nimport { gridMove, cellEditKey, parseCellValue } from '../../core/grid.ts';\nimport type { TableCellEditDetail } from './defs.ts';\nimport type { UiTableCell } from './table-cell.ts';\nimport type { UiTableHeaderCell } from './table-header-cell.ts';\nimport type { UiTableRow } from './table-row.ts';\n\n/** Controls a cell may hold (selection, expand, author content); in a grid they leave the Tab order and the cell activates them. */\nexport const CELL_CONTROLS = 'button, a[href], input, select, textarea, [tabindex], ui-checkbox, ui-radio, ui-button, ui-link';\n\n/**\n * Takes a control out of the Tab order, including what it delegates focus to: a negative tabindex on a\n * shadow host (ui-checkbox, ui-radio) leaves the native control inside it tabbable.\n */\nexport function removeFromTabOrder(control: HTMLElement) {\n    control.tabIndex = -1;\n    const inner = () => {\n        for (const el of control.shadowRoot?.querySelectorAll<HTMLElement>('button, a[href], input, select, textarea, [tabindex]') ?? []) el.tabIndex = -1;\n    };\n    inner();\n    // a child element renders later, so its native control may not exist yet\n    void (control as Partial<ReactiveControllerHost>).updateComplete?.then(inner);\n}\n\n/** What the grid reads from its `<ui-table>`. */\nexport interface GridSource {\n    /** The body rows on screen (not left out by the search, on this page). */\n    shownRows(): UiTableRow[];\n    /** The column headers, in order. */\n    columns(): UiTableHeaderCell[];\n    /** \"Press Enter to edit\". */\n    editHint(): string;\n}\n\n/** Where the Tab stop is: a row and the index of the cell among its grid cells. */\ninterface Position {\n    row: UiTableRow;\n    index: number;\n}\n\n/**\n * WAI-ARIA APG editable data grid for `<ui-table>` (Carbon's DataTable has no inline editing, so this follows the\n * APG pattern with Carbon styling, as `ui-data-table` did). Active while a header has `editable`.\n *\n * - The table becomes `role=grid` with one Tab stop among the body cells (roving tabindex), the chevron and\n *   checkbox cells included; arrow keys, Home / End and Ctrl+Home / End move it. Controls inside cells leave\n *   the Tab order: Enter or Space on their cell activates them.\n * - On an editable cell (a pencil after the value on hover and focus), Enter, F2, a double click, the pencil or\n *   typing a character opens the editor; Enter saves, Escape cancels, Tab / Shift+Tab save and edit the next /\n *   previous editable cell, leaving the cell saves. The header's `validate(value, cell)` returning a message keeps\n *   the editor open.\n * - Saving fires a cancelable `ui-table-cell-edit` from the cell, then writes the value into the cell (its text,\n *   a select column's label; `sort-value` follows, `csv-value` goes). Canceled, the cell stays as it was: write\n *   it yourself (a framework that renders the rows).\n */\nexport class TableGrid {\n    private readonly table: HTMLElement;\n    private readonly source: GridSource;\n    private active: Position | null = null;\n    /** The cell holding tabindex 0. */\n    private stop: HTMLElement | null = null;\n    /** The open editor's cell and the value it started from. */\n    private editing: { cell: UiTableCell; previous: string } | null = null;\n    /** Cells this grid gave a tabindex and role (handed back when the grid ends). */\n    private readonly touched = new Set<UiTableCell>();\n    /** Controls already taken out of the Tab order (each once, not on every sync). */\n    private readonly outOfTabOrder = new WeakSet<HTMLElement>();\n    private enabled = false;\n\n    constructor(table: HTMLElement, source: GridSource) {\n        this.table = table;\n        this.source = source;\n    }\n\n    get on() {\n        return this.enabled;\n    }\n\n    /** The body cell that takes Tab (null when the grid is off). */\n    get stopCell() {\n        return this.enabled ? this.stop : null;\n    }\n\n    /** After the rows, columns or pages changed: roles, the Tab stop, the controls out of the Tab order. */\n    sync() {\n        const headers = this.source.columns();\n        const enabled = headers.some((h) => !!h.editable);\n        if (!enabled && !this.enabled) return;\n        this.enabled = enabled;\n        const role = this.table.getAttribute('role');\n        if (role === 'table' || role === 'grid') this.table.setAttribute('role', enabled ? 'grid' : 'table');\n        for (const row of this.table.querySelectorAll<UiTableRow & { grid: boolean }>(':scope > ui-table-head > ui-table-header-row, :scope > ui-table-body > ui-table-row, :scope > ui-table-body > ui-table-expanded-row')) row.grid = enabled;\n        if (!enabled) {\n            this.release();\n            return;\n        }\n        for (const row of this.table.querySelectorAll<UiTableRow>(':scope > ui-table-body > ui-table-row')) this.syncCells(row);\n        const rows = this.source.shownRows();\n        if (!this.active || !rows.includes(this.active.row)) this.active = rows[0] ? { row: rows[0], index: 0 } : null;\n        void Promise.all(rows.map((row) => row.updateComplete)).then(() => this.settle());\n    }\n\n    /** Every body cell out of the Tab order (but the stop), grid roles, the edit hint, controls out of the Tab order. */\n    private syncCells(row: UiTableRow) {\n        for (const cell of row.querySelectorAll<UiTableCell>(':scope > ui-table-cell')) {\n            this.touched.add(cell);\n            if (cell.getAttribute('role') === 'cell') cell.setAttribute('role', 'gridcell');\n            if (cell !== this.stop) cell.tabIndex = -1;\n            if (cell.editable) {\n                cell.removeAttribute('aria-readonly');\n                cell.setAttribute('aria-description', this.source.editHint());\n            } else {\n                cell.setAttribute('aria-readonly', 'true');\n                cell.removeAttribute('aria-description');\n            }\n            for (const control of cell.querySelectorAll<HTMLElement>(CELL_CONTROLS)) {\n                if (this.outOfTabOrder.has(control)) continue;\n                this.outOfTabOrder.add(control);\n                removeFromTabOrder(control);\n            }\n        }\n    }\n\n    /** Once the rows rendered their chevron and checkbox cells: the stop takes tabindex 0. */\n    private settle() {\n        if (!this.enabled) return;\n        const cells = this.active?.row.gridCells() ?? [];\n        if (this.active && this.active.index >= cells.length) this.active.index = 0;\n        const cell = cells[this.active?.index ?? 0];\n        if (cell) this.setStop(cell);\n    }\n\n    /** The grid ended (no header is editable): the cells go back to a table's. */\n    private release() {\n        for (const cell of this.touched) {\n            if (cell.getAttribute('role') === 'gridcell') cell.setAttribute('role', 'cell');\n            cell.removeAttribute('tabindex');\n            cell.removeAttribute('aria-readonly');\n            cell.removeAttribute('aria-description');\n        }\n        this.touched.clear();\n        this.active = null;\n        this.stop = null;\n    }\n\n    private setStop(cell: HTMLElement) {\n        if (this.stop && this.stop !== cell) this.stop.tabIndex = -1;\n        cell.tabIndex = 0;\n        this.stop = cell;\n    }\n\n    /** The grid cell an event happened in: its row (on screen) and its place among the row's grid cells. */\n    private cellOf(event: Event): (Position & { cell: HTMLElement }) | null {\n        const path = event.composedPath();\n        const rows = this.source.shownRows();\n        const at = path.findIndex((node) => rows.includes(node as UiTableRow));\n        if (at < 0) return null;\n        const row = path[at] as UiTableRow;\n        const cells = row.gridCells();\n        for (let i = at - 1; i >= 0; i--) {\n            const index = cells.indexOf(path[i] as HTMLElement);\n            if (index >= 0) return { row, index, cell: cells[index] };\n        }\n        return null;\n    }\n\n    private moveTo(row: UiTableRow | undefined, index: number) {\n        const cell = row?.gridCells()[index];\n        if (!row || !cell) return;\n        this.active = { row, index };\n        this.setStop(cell);\n        cell.focus();\n    }\n\n    private headerOf(cell: UiTableCell) {\n        const index = [...(cell.parentElement?.children ?? [])].filter((c) => c.localName === 'ui-table-cell').indexOf(cell);\n        return this.source.columns()[index];\n    }\n\n    /** Arrow keys and friends on a focused cell; Enter / F2 / a character edit, Enter / Space activate a control. */\n    readonly onKeydown = (e: Event) => {\n        const event = e as KeyboardEvent;\n        if (!this.enabled) return;\n        if (this.editing) {\n            if (event.composedPath()[0] === this.editorOf(this.editing.cell)) this.onEditorKeydown(event, this.editing.cell);\n            return;\n        }\n        const at = this.cellOf(event);\n        if (event.composedPath()[0] !== at?.cell) return; // the cell itself, not a control in it\n        const rows = this.source.shownRows();\n        const target = gridMove(event.key, event.ctrlKey || event.metaKey, { row: rows.indexOf(at.row), cell: at.index }, rows.length, at.row.gridCells().length);\n        if (target) {\n            event.preventDefault();\n            this.moveTo(rows[target.row], target.cell);\n            return;\n        }\n        const cell = at.cell as UiTableCell;\n        if (cell.editable) {\n            const action = cellEditKey(event, cell.editable);\n            if (!action) return;\n            event.preventDefault();\n            this.start(cell, action === 'type' ? event.key : undefined);\n        } else if (event.key === 'Enter' || event.key === ' ') {\n            const control = cell.querySelector<HTMLElement>(CELL_CONTROLS);\n            if (!control) return;\n            event.preventDefault();\n            control.click();\n        }\n    };\n\n    /** Whatever focuses a body cell (a click, a script, a screen reader) makes it the Tab stop. */\n    readonly onFocusIn = (event: Event) => {\n        if (!this.enabled) return;\n        const at = this.cellOf(event);\n        if (!at || (this.active?.row === at.row && this.active.index === at.index)) return;\n        this.active = { row: at.row, index: at.index };\n        this.setStop(at.cell);\n    };\n\n    readonly onClick = (event: Event) => {\n        if (!this.enabled) return;\n        const at = this.cellOf(event);\n        if (!at || (at.cell as UiTableCell).editing) return;\n        if ((event.composedPath()[0] as Element).closest?.('.edit-icon')) this.start(at.cell as UiTableCell);\n        else if (!at.cell.matches(':focus-within')) at.cell.focus(); // a browser that didn't focus what was clicked (Safari)\n    };\n\n    readonly onDoubleClick = (event: Event) => {\n        if (!this.enabled) return;\n        const cell = this.cellOf(event)?.cell as UiTableCell | undefined;\n        if (cell?.editable && !cell.editing) this.start(cell);\n    };\n\n    /** Leaving the editor saves (an invalid value keeps it open). */\n    readonly onFocusOut = (event: Event) => {\n        const editing = this.editing;\n        if (!editing || event.composedPath()[0] !== this.editorOf(editing.cell)) return;\n        if ((event as FocusEvent).relatedTarget === editing.cell) return; // still in the cell\n        if (!this.commit()) void editing.cell.updateComplete.then(() => editing.cell.focusEditor(false));\n    };\n\n    private editorOf(cell: UiTableCell) {\n        return cell.shadowRoot?.querySelector('.editor') ?? null;\n    }\n\n    /** The cell's value as the editor starts it: its `sort-value`, a select's value by label, else its text. */\n    private valueOf(cell: UiTableCell, header: UiTableHeaderCell | undefined) {\n        const sortValue = cell.getAttribute('sort-value');\n        if (sortValue !== null) return sortValue;\n        const text = cell.textContent?.trim() ?? '';\n        if (cell.editable !== 'select') return text;\n        return header?.options.find((o) => o.label === text)?.value ?? text;\n    }\n\n    private start(cell: UiTableCell, typed?: string) {\n        const header = this.headerOf(cell);\n        const row = cell.parentElement as UiTableRow;\n        const previous = this.valueOf(cell, header);\n        this.editing = { cell, previous };\n        const rowName = row.querySelector(':scope > ui-table-cell')?.textContent?.trim();\n        cell.editorLabel = (header?.labelText ?? '') + (rowName ? `, ${rowName}` : '');\n        cell.editorOptions = header?.options ?? [];\n        cell.editorError = '';\n        cell.draft = typed ?? previous;\n        cell.editing = true;\n        void cell.updateComplete.then(() => cell.focusEditor(typed === undefined));\n    }\n\n    private stopEditing(cell: UiTableCell, focus: boolean) {\n        this.editing = null;\n        cell.editing = false;\n        cell.editorError = '';\n        if (focus) void cell.updateComplete.then(() => cell.focus());\n    }\n\n    /** Validate, ask with `ui-table-cell-edit`, write the value into the cell; false while the value is invalid. */\n    private commit(focus = false): boolean {\n        const editing = this.editing;\n        if (!editing) return true;\n        const { cell, previous } = editing;\n        const header = this.headerOf(cell);\n        const value = parseCellValue(cell.editable ?? 'text', cell.editorValue);\n        const message = header?.validate?.(value, cell) ?? '';\n        if (message) {\n            cell.editorError = message;\n            return false;\n        }\n        this.stopEditing(cell, focus);\n        if (String(value) === previous) return true;\n        const row = cell.parentElement as UiTableRow;\n        const detail: TableCellEditDetail = { row, cell, column: header?.columnKey ?? '', value, previous };\n        const allowed = cell.dispatchEvent(new CustomEvent('ui-table-cell-edit', { detail, bubbles: true, composed: true, cancelable: true }));\n        if (allowed) this.write(cell, value, header);\n        return true;\n    }\n\n    private write(cell: UiTableCell, value: string | number, header: UiTableHeaderCell | undefined) {\n        const text = String(value);\n        const select = cell.editable === 'select';\n        cell.textContent = select ? (header?.options.find((o) => o.value === text)?.label ?? text) : text;\n        if (select || cell.hasAttribute('sort-value')) cell.setAttribute('sort-value', text);\n        cell.removeAttribute('csv-value');\n    }\n\n    private onEditorKeydown(event: KeyboardEvent, cell: UiTableCell) {\n        event.stopPropagation(); // the grid's arrow keys belong to the editor now\n        if (event.key === 'Escape') {\n            event.preventDefault();\n            this.stopEditing(cell, true);\n        } else if (event.key === 'Enter') {\n            event.preventDefault();\n            this.commit(true);\n        } else if (event.key === 'Tab') {\n            event.preventDefault();\n            const next = this.nextEditable(cell, event.shiftKey ? -1 : 1);\n            if (!this.commit(!next)) return;\n            if (next) this.start(next);\n        }\n    }\n\n    /** The next / previous editable cell on screen, in reading order. */\n    private nextEditable(from: UiTableCell, step: 1 | -1) {\n        const cells = this.source.shownRows().flatMap((row) => [...row.querySelectorAll<UiTableCell>(':scope > ui-table-cell')].filter((c) => c.editable && !c.columnHidden));\n        return cells[cells.indexOf(from) + step] ?? null;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-head.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-head.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-head`: the header row group of a `<ui-table>` (`role=rowgroup`).\n *\n * @slot - A `<ui-table-header-row>`\n */\n@customElement('ui-table-head')\nexport class UiTableHead extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: table-header-group;\n            background-color: var(--ui-table-header-background, var(--ui-layer-accent));\n        }\n    `;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'rowgroup');\n    }\n\n    override render() {\n        return html`<slot></slot>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-head': UiTableHead;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-header-cell.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-header-cell.ts",
      "content": "import { html, css, svg, isServer, nothing } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { defaultTrue, setManagedAttribute, srOnlyStyles } from '../shared/field.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { nextTableSort, type TableCellEditor, type TableEditOption, type TableHeaderCellSortDetail, type TableSortCycle, type TableSortDirection } from './defs.ts';\nimport { tableColumnStyles } from './table-column.styles.ts';\nimport { HeaderResize, headerResizeStyles } from './table-column-resize.ts';\n\nconst arrowUp = svg`<path d=\"M16 4 6 14l1.41 1.41L15 7.83V28h2V7.83l7.59 7.58L26 14 16 4z\" />`;\nconst arrowsVertical = svg`<path d=\"M27.6 20.6 24 24.2V4h-2v20.2l-3.6-3.6L17 22l6 6 6-6-1.4-1.4zM9 4l-6 6 1.4 1.4L8 7.8V28h2V7.8l3.6 3.6L15 10 9 4z\" />`;\n\n/**\n * Carbon `cds-table-header-cell`: a column header (`role=columnheader`). Sortable (`is-sortable`, or the\n * table's `is-sortable`), it is a button that steps through `sort-cycle` (default none → ascending →\n * descending → none) and fires a cancelable `ui-table-header-cell-sort`; the table then sorts its rows.\n * `aria-sort` follows `sort-direction` (Carbon React; Carbon web components set none).\n *\n * Columns (no Carbon counterpart): `column` names the column for events and the column settings (default: its\n * place); `column-hidden` hides it and its cells (`hideable=\"false\"` keeps it out of the column settings' reach);\n * `pinned=\"start\"` (first header) / `\"end\"` (last header) keeps the column in view while the table scrolls\n * sideways; `resizable` (or the table's) puts a resize handle on its end edge, and `width` / `min-width` /\n * `max-width` (px) size it. `editable=\"text|number|select\"` lets its cells be edited in place (the table becomes a\n * grid): `options` lists a select column's choices (a property, or JSON in the attribute), `validate` checks a value.\n *\n * @slot - The header's label\n * @csspart content - The box inside the header that holds its padding\n * @csspart sort-button - The button of a sortable header\n * @csspart label-text - The label\n * @csspart sort-icon - The sort arrow\n * @csspart resizer - The resize handle (an invisible range input over the end edge)\n * @fires ui-table-header-cell-sort - cancelable; detail: { oldSortDirection, sortDirection } before the column sorts (`preventDefault()` keeps the rows and this header as they are: sort the data yourself and set `sort-direction`)\n * @cssprop --ui-table-header-background - Fill of the header (default `--ui-layer-accent`; Kanok: the table's fill)\n * @cssprop --ui-table-header-ink - Text colour of the header (default `--ui-ink`; Kanok: secondary text)\n * @cssprop --ui-table-sort-hover / --ui-table-sorted-background / --ui-table-sorted-icon - A sortable header: hover fill, the sorted column's fill and arrow (default layer-selected-hover, icon-primary; Kanok: the header fill, an `--ui-icon-interactive` arrow)\n */\n@customElement('ui-table-header-cell')\nexport class UiTableHeaderCell extends UiElement {\n    static override readonly shadowRootOptions = { ...UiElement.shadowRootOptions, delegatesFocus: true };\n\n    static override readonly styles = [\n        srOnlyStyles,\n        tableColumnStyles,\n        headerResizeStyles,\n        css`\n            /* the padding is the shadow root's .content, not :host's: a page-level reset (Tailwind preflight) beats :host rules */\n            :host {\n                display: table-cell;\n                background-color: var(--ui-table-header-background, var(--ui-layer-accent));\n                color: var(--ui-table-header-ink, var(--ui-ink));\n                font: var(--ui-font-body-emphasis);\n                font-weight: 600;\n                line-height: 1.42857; /* heading-01, unitless as Carbon's token: 20px would put the label 1px lower */\n                letter-spacing: var(--ui-tracking-body);\n                text-align: start;\n                vertical-align: var(--_align, middle);\n            }\n\n            .content {\n                padding-block-start: var(--_head-pad, 0px);\n                padding-inline: var(--ui-space-md);\n            }\n\n            :host([sort-direction]) .content {\n                padding-inline: 0;\n            }\n\n            /* pinned headers stay over the header cells scrolling under them */\n            :host([pinned]) {\n                z-index: 3;\n            }\n\n            /* the table's sticky-header: the header stays at the top of the scroll box, a rule under it */\n            :host {\n                position: var(--_head-position, static);\n                inset-block-start: 0;\n                z-index: var(--_head-z, auto);\n                box-shadow:\n                    var(--_pin-edge, 0 0 #0000),\n                    var(--_head-edge, 0 0 #0000);\n            }\n\n            :host([resizable]:not([pinned])) {\n                position: var(--_head-anchor, relative);\n            }\n\n            .sort {\n                display: flex;\n                align-items: center;\n                justify-content: space-between;\n                box-sizing: border-box;\n                inline-size: 100%;\n                min-block-size: var(--_sort-row, 48px);\n                margin: 0;\n                padding: 0;\n                padding-inline-start: var(--ui-space-md);\n                border: 0;\n                background-color: var(--ui-table-header-background, var(--ui-layer-accent));\n                color: var(--ui-table-header-ink, var(--ui-ink));\n                font: inherit;\n                letter-spacing: inherit;\n                text-align: start;\n                cursor: pointer;\n                transition:\n                    background-color var(--ui-duration-fast) var(--ui-easing-entrance),\n                    outline var(--ui-duration-fast) var(--ui-easing-entrance); /* Carbon .cds--table-sort, fast-01 entrance */\n            }\n\n            /* in the button the label is 18px tall (Carbon .cds--table-sort); a plain header keeps heading-01's 20px */\n            .sort .label {\n                line-height: 18px;\n            }\n\n            /* data-table-column-hover, under the pointer and on the sorted column; --ui-table-sort-hover / --ui-table-sorted-background:\n               a design can keep the sorted header on the header fill (its arrow shows the sort) */\n            .sort:hover,\n            :host([sort-active]) .sort:hover {\n                background-color: var(--ui-table-sort-hover, var(--ui-layer-selected-hover));\n            }\n\n            :host([sort-active]) .sort:not(:hover) {\n                background-color: var(--ui-table-sorted-background, var(--ui-layer-selected-hover));\n            }\n\n            :host([sort-active]) .icon-sorted {\n                fill: var(--ui-table-sorted-icon, var(--ui-icon-primary));\n            }\n\n            .sort:focus-visible {\n                outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n                outline-offset: -2px;\n            }\n\n            svg {\n                flex-shrink: 0;\n                inline-size: 20px;\n                min-inline-size: 16px;\n                block-size: 20px;\n                margin-inline: var(--ui-space-xs);\n                fill: var(--ui-icon-primary);\n            }\n\n            .icon-unsorted {\n                opacity: 0;\n            }\n\n            .sort:hover .icon-unsorted,\n            .sort:focus-visible .icon-unsorted {\n                opacity: 1;\n            }\n\n            .icon-sorted {\n                transition: transform 250ms cubic-bezier(0.5, 0, 0.1, 1); /* Carbon $transition-base, $standard-easing */\n            }\n\n            :host([sort-direction='descending']) .icon-sorted {\n                transform: rotate(180deg);\n            }\n\n            @media (prefers-reduced-motion: reduce) {\n                .icon-sorted {\n                    transition: none;\n                }\n            }\n\n            @media (forced-colors: active) {\n                svg {\n                    fill: ButtonText;\n                }\n\n                :host([sort-active]) .sort {\n                    outline: 1px solid Highlight;\n                    outline-offset: -1px;\n                }\n            }\n        `,\n    ];\n\n    /** Sortable on its own (the table's `is-sortable` sets every header). */\n    @property({ type: Boolean, reflect: true, attribute: 'is-sortable' }) isSortable = false;\n\n    /** The column the rows are sorted by (set with the direction). */\n    @property({ type: Boolean, reflect: true, attribute: 'sort-active' }) sortActive = false;\n\n    /** The states each click steps through. */\n    @property({ reflect: true, attribute: 'sort-cycle' }) sortCycle?: TableSortCycle;\n\n    /** Sorted ascending, descending or not; a sortable header without one starts at none. */\n    @property({ reflect: true, attribute: 'sort-direction' }) sortDirection?: TableSortDirection;\n\n    /** The column's name in events and the column settings (default: its place, \"0\", \"1\" …). */\n    @property({ reflect: true }) column = '';\n\n    /** Hidden with its cells (the column settings set it; set it in the markup to start hidden). */\n    @property({ type: Boolean, reflect: true, attribute: 'column-hidden' }) columnHidden = false;\n\n    /** Can be hidden from the column settings (`hideable=\"false\"` keeps it shown). */\n    @property({ reflect: true, converter: defaultTrue }) hideable = true;\n\n    /** Stays in view while the table scrolls sideways: `start` on the first header, `end` on the last. */\n    @property({ reflect: true }) pinned?: 'start' | 'end';\n\n    /** A resize handle on its end edge (the table's `resizable` sets every header). */\n    @property({ type: Boolean, reflect: true }) resizable = false;\n\n    /** The column's width in px (a resize sets it). */\n    @property({ type: Number, reflect: true }) width?: number;\n\n    /** The narrowest a resize makes it (default 50). */\n    @property({ type: Number, attribute: 'min-width' }) minWidth?: number;\n\n    /** The widest a resize makes it (default: the table's width). */\n    @property({ type: Number, attribute: 'max-width' }) maxWidth?: number;\n\n    /** Its cells can be edited in place, with this editor (no Carbon counterpart; the table becomes a grid). */\n    @property({ reflect: true }) editable?: TableCellEditor;\n\n    /** A `select` column's choices: the value saved and the label shown (JSON in the attribute). */\n    @property({ type: Array }) options: TableEditOption[] = [];\n\n    /** Checks an edited value before it's saved: a message keeps the editor open and shows it. */\n    @property({ attribute: false }) validate?: (value: string | number, cell: HTMLElement) => string;\n\n    private readonly resize = new HeaderResize(this);\n\n    private readonly localize = new LocalizeController(this);\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'columnheader');\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        if (this.isSortable && !this.sortDirection) this.sortDirection = 'none';\n        if (changed.has('sortDirection')) this.sortActive = !!this.sortDirection && this.sortDirection !== 'none';\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('sortDirection')) setManagedAttribute(this, 'aria-sort', this.sortDirection ?? null);\n        if (changed.has('width')) this.style.inlineSize = this.width === undefined ? '' : `${this.width}px`;\n    }\n\n    /** The label as text (the button's title, the screen reader hint, the column settings). */\n    get labelText() {\n        return isServer ? '' : (this.textContent ?? '').trim();\n    }\n\n    /** The column's key: `column`, else its place among the headers. */\n    get columnKey() {\n        if (this.column) return this.column;\n        return String(this.parentElement ? [...this.parentElement.children].filter((c) => c.localName === this.localName).indexOf(this) : 0);\n    }\n\n    private renderResize() {\n        return this.resizable ? this.resize.render(this.localize.t.dataTable) : nothing;\n    }\n\n    private readonly onSortClick = () => {\n        const oldSortDirection = this.sortDirection ?? 'none';\n        const sortDirection = nextTableSort(oldSortDirection, this.sortCycle);\n        const detail: TableHeaderCellSortDetail = { oldSortDirection, sortDirection };\n        const event = new CustomEvent('ui-table-header-cell-sort', { detail, bubbles: true, composed: true, cancelable: true });\n        if (this.dispatchEvent(event)) this.sortDirection = sortDirection;\n    };\n\n    /** What the next click does, for screen readers (the data table's wording). */\n    private sortHint(label: string) {\n        const t = this.localize.t.dataTable;\n        const next = nextTableSort(this.sortDirection ?? 'none', this.sortCycle);\n        let text = t.unsort;\n        if (next === 'ascending') text = t.sortAscending;\n        else if (next === 'descending') text = t.sortDescending;\n        return text.replaceAll('{header}', label);\n    }\n\n    override render() {\n        const label = html`<span class=\"label\" part=\"label-text\"><slot @slotchange=${() => this.requestUpdate()}></slot></span>`;\n        if (!this.sortDirection) return html`<div class=\"content\" part=\"content\">${label}</div>${this.renderResize()}`;\n        const text = this.labelText;\n        const active = this.sortDirection !== 'none';\n        return html`<div class=\"content\" part=\"content\"><button class=\"sort\" part=\"sort-button\" type=\"button\" title=${text} aria-describedby=\"hint\" @click=${this.onSortClick}>\n                ${label}\n                ${active\n                    ? html`<svg class=\"icon-sorted\" part=\"sort-icon\" viewBox=\"0 0 32 32\" aria-hidden=\"true\">${arrowUp}</svg>`\n                    : html`<svg class=\"icon-unsorted\" part=\"sort-icon\" viewBox=\"0 0 32 32\" aria-hidden=\"true\">${arrowsVertical}</svg>`}\n            </button></div>\n            <span class=\"sr-only\" id=\"hint\">${this.sortHint(text)}</span>${this.renderResize()}`;\n    }\n}\n\nexport interface UiTableHeaderCellEventMap extends HTMLElementEventMap {\n    'ui-table-header-cell-sort': CustomEvent<TableHeaderCellSortDetail>;\n}\n\n/** Typed listeners for UiTableHeaderCell's events (declaration merging with the class). */\nexport interface UiTableHeaderCell {\n    addEventListener<K extends keyof UiTableHeaderCellEventMap>(type: K, listener: (this: UiTableHeaderCell, event: UiTableHeaderCellEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiTableHeaderCellEventMap>(type: K, listener: (this: UiTableHeaderCell, event: UiTableHeaderCellEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-header-cell': UiTableHeaderCell;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-header-description.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-header-description.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-header-description`: a line under the title, in the table's `description` slot\n * (body-compact-01).\n *\n * @slot - The description\n */\n@customElement('ui-table-header-description')\nexport class UiTableHeaderDescription extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: block;\n            margin: 0;\n            color: var(--ui-ink-muted);\n            font: var(--ui-font-body-sm);\n            line-height: 18px; /* body-compact-01 */\n            letter-spacing: var(--ui-tracking-body);\n        }\n    `;\n\n    override render() {\n        return html`<slot></slot>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-header-description': UiTableHeaderDescription;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-header-row.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-header-row.ts",
      "content": "import { css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { UiTableRowBase } from './table-row.ts';\nimport type { TableSelectionDetail } from './defs.ts';\n\n/**\n * Carbon `cds-table-header-row`: the row of `<ui-table-header-cell>`s inside `<ui-table-head>`. With selection its\n * first cell is the select-all checkbox (checked while rows are chosen, partly while only some are); with\n * `batch-expansion` its chevron opens and closes every row.\n *\n * @slot - The `<ui-table-header-cell>`s\n * @fires ui-table-change-selection-all - cancelable; detail: { selected } before every row is chosen or released\n */\n@customElement('ui-table-header-row')\nexport class UiTableHeaderRow extends UiTableRowBase {\n    static override readonly styles = [\n        UiTableRowBase.styles,\n        css`\n            .select,\n            .expand,\n            .filler {\n                position: var(--_head-position, static);\n                inset-block-start: 0;\n                z-index: var(--_head-z, auto);\n                border: 0;\n                box-shadow: var(--_head-edge, none);\n                background: var(--ui-table-header-background, var(--ui-layer-accent)); /* as the header cells */\n            }\n\n            .pin {\n                z-index: 3;\n            }\n\n            /* a pinned first column's chevron / checkbox header cells stick sideways too (the rule above set position) */\n            @media (min-width: 672px) {\n                .pin {\n                    position: sticky;\n                }\n            }\n        `,\n    ];\n\n    protected override readonly header = true;\n}\n\nexport interface UiTableHeaderRowEventMap extends HTMLElementEventMap {\n    'ui-table-change-selection-all': CustomEvent<TableSelectionDetail>;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-header-row': UiTableHeaderRow;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-header-title.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-header-title.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-header-title`: the table's title, in its `title` slot (heading-03). Give it a heading level\n * with `role=\"heading\" aria-level=\"2\"` where the page needs one.\n *\n * @slot - The title\n */\n@customElement('ui-table-header-title')\nexport class UiTableHeaderTitle extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: block;\n            margin: 0;\n            color: var(--ui-ink);\n            font: var(--ui-font-subhead); /* heading-03 */\n        }\n    `;\n\n    override render() {\n        return html`<slot></slot>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-header-title': UiTableHeaderTitle;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-row.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-row.ts",
      "content": "import { html, css, nothing, svg, isServer, type CSSResultGroup } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\nimport type { UiCheckbox } from '../checkbox/checkbox.ts';\nimport '../checkbox/checkbox.ts';\nimport '../radio/radio.ts';\nimport type { TableExpandoDetail, TableSelectionDetail } from './defs.ts';\nimport { removeFromTabOrder } from './table-grid.ts';\n\nconst chevronRight = svg`<path d=\"M11 8 6 13l-.7-.7L9.6 8 5.3 3.7 6 3z\" />`;\n\n/**\n * What a body row and the header row share (Carbon's header row extends its row): a `role=row` table row as tall as\n * the table's size, with the cells the table adds before the author's — the expand chevron and the selection\n * checkbox or radio.\n *\n * @slot - The row's cells\n * @csspart expand-cell - The cell of the expand chevron\n * @csspart expand-button - The chevron button\n * @csspart selection-cell - The cell of the checkbox or radio\n */\nexport class UiTableRowBase extends UiElement {\n    static override readonly styles: CSSResultGroup = css`\n        :host {\n            display: table-row;\n            block-size: var(--_row, 48px);\n        }\n\n        /* left out by the table's search, or on another page */\n        :host([filtered]),\n        :host([paged-out]) {\n            display: none;\n        }\n\n        /* pinned first column: the chevron and checkbox cells before it stay in view too (from 672px, as IBM Products) */\n        @media (min-width: 672px) {\n            .pin {\n                position: sticky;\n                z-index: 1;\n                background: linear-gradient(var(--_row-tint, transparent), var(--_row-tint, transparent)), var(--_row-base, var(--ui-table-background, var(--ui-surface-1)));\n            }\n\n            .expand.pin {\n                inset-inline-start: 0;\n            }\n\n            .select.pin {\n                inset-inline-start: var(--_pin-select-at, 0px);\n            }\n        }\n\n        /* after a resize the columns keep their widths; this cell takes the rest of the row */\n        .filler {\n            display: table-cell;\n            padding: 0;\n            box-shadow: inset 0 -1px 0 var(--_row-rule-end, var(--ui-hairline));\n        }\n\n        /* the cells the row adds before its own: a rule below like the author's cells (a shadow, as theirs) */\n        .select,\n        .expand {\n            display: table-cell;\n            box-sizing: border-box;\n            box-shadow: inset 0 -1px 0 var(--_row-rule-end, var(--ui-hairline));\n            vertical-align: var(--_align, middle);\n        }\n\n        @media (forced-colors: active) {\n            .filler,\n            .select,\n            .expand {\n                border-block-end: 1px solid; /* shadows are dropped */\n            }\n        }\n\n        /* grid cells (an editable table) */\n        .select:focus-visible,\n        .expand:focus-visible {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n            outline-offset: -2px;\n        }\n\n        /* selection column (Carbon web components .cds--table-column-checkbox): a 32px checkbox + 16 / 4 padding */\n        .select {\n            box-sizing: content-box;\n            inline-size: 32px;\n            padding-block: var(--_select-pad, 0);\n            padding-inline: var(--ui-space-md) var(--ui-space-xxs);\n        }\n\n        /* beside the chevron column it tightens to 6 / 6 (Carbon web components: xs, sm, md and xl; lg keeps 16 / 4) */\n        .select.after-expand {\n            padding-inline: var(--_select-inline-after-expand, var(--ui-space-md) var(--ui-space-xxs));\n        }\n\n        /* radio column: as wide as Carbon web components' (its header keeps a hidden 42px checkbox), the circle at the start */\n        .select.radio {\n            inline-size: 42px;\n            padding-block-start: var(--_radio-pad, var(--_select-pad, 0));\n        }\n\n        /* the square 3px in and 1px down a 21px checkbox (Carbon .cds--checkbox-label::before) */\n        .select ui-checkbox {\n            display: block;\n            block-size: 21px;\n            margin-inline-start: 3px;\n        }\n\n        .select ui-checkbox::part(base) {\n            padding-block: 0;\n        }\n\n        /* Carbon radio cell: the 18px circle 2px in, margins 1 / -2 / 2 / 2, in a 21px row */\n        .select ui-radio {\n            justify-content: flex-start;\n            gap: 0;\n            block-size: 21px;\n            min-height: 0;\n            padding-block: 0;\n        }\n\n        .select ui-radio::part(circle) {\n            margin: 1px -2px 2px 2px;\n        }\n\n        /* expand column (Carbon .table-expand): 40px, padding 8 / 0 / 8 / 8, a 32px chevron button */\n        .expand {\n            inline-size: 40px;\n            padding: var(--_expand-pad, 8px 0 8px 8px);\n        }\n\n        .expand-button {\n            display: inline-flex;\n            align-items: center;\n            justify-content: center;\n            box-sizing: border-box;\n            inline-size: 32px;\n            block-size: var(--_expand-button, 32px);\n            margin: 0;\n            padding: 0 var(--ui-space-xs);\n            border: 0;\n            border-radius: var(--ui-icon-control-radius, 0); /* round in a design that rounds icon controls (Kanok); the ring follows */\n            background: transparent;\n            cursor: pointer;\n            vertical-align: middle;\n        }\n\n        .expand-button:focus-visible {\n            outline: none;\n            box-shadow: inset 0 0 0 var(--ui-focus-width, 2px) var(--ui-focus);\n        }\n\n        .expand-button svg {\n            inline-size: 16px;\n            block-size: 16px;\n            fill: var(--ui-icon-primary);\n            transform: rotate(90deg);\n            transition: transform 150ms var(--ui-easing); /* Carbon $duration-moderate-01 */\n        }\n\n        .expand-button[aria-expanded='true'] svg {\n            transform: rotate(270deg);\n        }\n\n        @media (prefers-reduced-motion: reduce) {\n            .expand-button svg {\n                transition: none;\n            }\n        }\n    `;\n\n    /** Chosen (Carbon `selected`); the table keeps the header's select-all and the batch actions in step. */\n    @property({ type: Boolean, reflect: true }) selected = false;\n\n    /** Can't be chosen. */\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    /** A single-choice radio instead of a checkbox (the table's `radio` sets it). */\n    @property({ type: Boolean, reflect: true }) radio = false;\n\n    /** No checkbox in the selection cell (the header row of a radio table). */\n    @property({ type: Boolean, reflect: true, attribute: 'hide-checkbox' }) hideCheckbox = false;\n\n    /** Shows the selection cell: the checkbox's name (the table's `is-selectable` sets one). */\n    @property({ attribute: 'selection-name' }) selectionName = '';\n\n    /** The checkbox's value. */\n    @property({ attribute: 'selection-value' }) selectionValue = '';\n\n    /** The checkbox's accessible name; default \"Select row\" with the row's first cell. */\n    @property({ attribute: 'selection-label' }) selectionLabel = '';\n\n    /** Has a `<ui-table-expanded-row>` after it (the table's `expandable` sets it). */\n    @property({ type: Boolean, reflect: true }) expandable = false;\n\n    /** Its expanded row is open. */\n    @property({ type: Boolean, reflect: true }) expanded = false;\n\n    /** The header row's chevron opens and closes every row (the table's `batch-expansion` sets it). */\n    @property({ type: Boolean, reflect: true, attribute: 'batch-expansion' }) batchExpansion = false;\n\n    /** Left out by the table's search. */\n    @property({ type: Boolean, reflect: true }) filtered = false;\n\n    /** Hovered with its expanded row (the two tint together). */\n    @property({ type: Boolean, reflect: true }) highlighted = false;\n\n    /** The table has an expand column: every row gets the cell, expandable ones the chevron. */\n    @property({ type: Boolean, attribute: false }) expandColumn = false;\n\n    /** The header's select-all is partly checked (some rows chosen); the table sets it. */\n    @property({ type: Boolean, attribute: false }) indeterminate = false;\n\n    /** The radio of a radio table that takes Tab (the chosen row, else the first); the table sets it. */\n    @property({ type: Boolean, attribute: false }) tabStop = false;\n\n    /** On another page of the table's pagination (the table sets it). */\n    @property({ type: Boolean, reflect: true, attribute: 'paged-out' }) pagedOut = false;\n\n    /** The first column is pinned: the chevron and checkbox cells stick too (the table sets it). */\n    @property({ type: Boolean, attribute: false }) pinStart = false;\n\n    /** A filler cell after the cells takes the rest of the row once the columns are resized (the table sets it). */\n    @property({ type: Boolean, attribute: false }) filler = false;\n\n    /** The table is a grid (an editable column): grid cells, the body's cells and controls out of the Tab order (the table sets it). */\n    @property({ type: Boolean, attribute: false }) grid = false;\n\n    protected readonly localize = new LocalizeController(this);\n\n    /** The header row: select-all / expand-all instead of the row's own. */\n    protected readonly header: boolean = false;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'row');\n        this.addEventListener('mouseover', this.onPointer);\n        this.addEventListener('mouseout', this.onPointer);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('mouseover', this.onPointer);\n        this.removeEventListener('mouseout', this.onPointer);\n    }\n\n    /** The expanded row after this one, if any. */\n    protected get expandedRow() {\n        const next = this.nextElementSibling;\n        return next?.localName === 'ui-table-expanded-row' ? (next as HTMLElement & { expanded: boolean; selected: boolean; highlighted: boolean }) : null;\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        // in a grid the cell takes the arrow keys and Enter / Space; its checkbox or radio leaves the Tab order\n        if (this.grid && !this.header) for (const control of this.renderRoot.querySelectorAll<HTMLElement>('.select ui-checkbox, .select ui-radio')) removeFromTabOrder(control);\n        const next = this.expandedRow;\n        if (!next) return;\n        if (changed.has('expanded')) next.expanded = this.expanded;\n        if (changed.has('selected')) next.selected = this.selected;\n        if (changed.has('highlighted')) next.highlighted = this.highlighted;\n    }\n\n    /** Hovering a row tints its expanded row too (Carbon). */\n    private readonly onPointer = (event: MouseEvent) => {\n        if (this.header) return;\n        const next = this.expandedRow;\n        if (next) next.highlighted = event.type === 'mouseover';\n    };\n\n    /** Opens or closes, unless the cancelable `ui-table-row-expando-beingtoggled` is canceled. */\n    toggleExpanded(expanded = !this.expanded) {\n        const detail: TableExpandoDetail = { expanded };\n        const init = { detail, bubbles: true, composed: true, cancelable: true };\n        if (!this.dispatchEvent(new CustomEvent('ui-table-row-expando-beingtoggled', init))) return;\n        this.expanded = expanded;\n        this.dispatchEvent(new CustomEvent('ui-table-row-expando-toggled', { ...init, cancelable: false }));\n    }\n\n    /** The row's first cell as text, which tells its controls apart for screen readers (\"Select row, Lease\"). */\n    private get rowName() {\n        if (isServer) return '';\n        const first = this.querySelector(':scope > ui-table-cell')?.textContent?.trim();\n        return first ? `, ${first}` : '';\n    }\n\n    private renderExpandCell() {\n        const t = this.localize.t.dataTable;\n        const button = this.header ? this.batchExpansion : this.expandable;\n        let label = this.expanded ? t.collapseRow : t.expandRow;\n        if (this.header) label = this.expanded ? t.collapseAll : t.expandAll;\n        else label += this.rowName;\n        const expanded = this.expanded ? 'true' : 'false';\n        const chevron = html`<button class=\"expand-button\" part=\"expand-button\" type=\"button\" tabindex=${this.bodyGridIndex} aria-label=${label} aria-expanded=${expanded} @click=${() => this.toggleExpanded()}>\n            <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">${chevronRight}</svg>\n        </button>`;\n        return html`<div class=\"expand ${this.pinStart ? 'pin' : ''}\" part=\"expand-cell\" role=${this.cellRole} tabindex=${this.bodyGridIndex} aria-readonly=${this.grid ? 'true' : nothing}>${button ? chevron : nothing}</div>`;\n    }\n\n    /** The checkbox (or radio) changed: ask with a cancelable event, then keep the new state or put the old one back. */\n    private readonly onSelectionChange = (event: Event) => {\n        event.stopPropagation();\n        const control = event.target as UiCheckbox;\n        const selected = this.radio || control.checked;\n        const detail: TableSelectionDetail = { selected };\n        const type = this.header ? 'ui-table-change-selection-all' : 'ui-table-row-change-selection';\n        const allowed = this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true, cancelable: true }));\n        if (allowed && !this.header) this.selected = selected;\n        else control.checked = this.selected;\n    };\n\n    /** Arrow keys between the rows' radios (as native radios, ← / → mirrored right-to-left): the table moves the choice. */\n    private readonly onRadioKeydown = (event: KeyboardEvent) => {\n        const rtl = getComputedStyle(this).direction === 'rtl';\n        const step: Record<string, number> = { ArrowDown: 1, ArrowRight: rtl ? -1 : 1, ArrowUp: -1, ArrowLeft: rtl ? 1 : -1 };\n        const delta = step[event.key];\n        if (delta === undefined) return;\n        event.preventDefault();\n        this.dispatchEvent(new CustomEvent('ui-table-radio-move', { detail: { delta }, bubbles: true }));\n    };\n\n    private get cellRole() {\n        return this.grid ? 'gridcell' : 'cell';\n    }\n\n    /** A body row's cells and controls in a grid: out of the Tab order (the grid moves its one stop among the cells). */\n    private get bodyGridIndex() {\n        return this.grid && !this.header ? '-1' : nothing;\n    }\n\n    /** The cells the grid's arrow keys move through: the chevron and checkbox cells, then the shown author cells. */\n    gridCells(): HTMLElement[] {\n        const own = [...this.renderRoot.querySelectorAll<HTMLElement>('.expand, .select')];\n        const cells = [...this.querySelectorAll<HTMLElement & { columnHidden: boolean }>(':scope > ui-table-cell')].filter((cell) => !cell.columnHidden);\n        return [...own, ...cells];\n    }\n\n    /** Focuses this row's selection control (a radio the arrow keys moved to). */\n    focusSelection() {\n        this.renderRoot.querySelector<HTMLElement>('.select ui-radio, .select ui-checkbox')?.focus();\n    }\n\n    /** The header's select-all checkbox (none in a radio table). */\n    private renderSelectAll() {\n        if (this.radio || this.hideCheckbox) return nothing;\n        const t = this.localize.t.dataTable;\n        const label = this.selected || this.indeterminate ? t.unselectAll : t.selectAll;\n        return html`<ui-checkbox hide-label .checked=${this.selected} .indeterminate=${this.indeterminate} ?disabled=${this.disabled} @change=${this.onSelectionChange}>${this.selectionLabel || label}</ui-checkbox>`;\n    }\n\n    /** A body row's checkbox or radio, named with the row's first cell. */\n    private renderRowSelection() {\n        const t = this.localize.t.dataTable;\n        const label = this.selectionLabel || (this.selected ? t.unselectRow : t.selectRow) + this.rowName;\n        if (this.radio) {\n            return html`<ui-radio aria-label=${label} value=${this.selectionValue} .checked=${this.selected} ?disabled=${this.disabled} tabindex=${this.tabStop ? 0 : -1} @click=${this.onSelectionChange} @keydown=${this.onRadioKeydown}></ui-radio>`;\n        }\n        if (this.hideCheckbox) return nothing;\n        return html`<ui-checkbox hide-label name=${this.selectionName} value=${this.selectionValue || 'on'} .checked=${this.selected} ?disabled=${this.disabled} @change=${this.onSelectionChange}>${label}</ui-checkbox>`;\n    }\n\n    private renderSelectCell() {\n        const control = this.header ? this.renderSelectAll() : this.renderRowSelection();\n        const classes = ['select', this.radio ? 'radio' : '', this.expandColumn ? 'after-expand' : '', this.pinStart ? 'pin' : ''].join(' ');\n        return html`<div class=${classes} part=\"selection-cell\" role=${this.cellRole} tabindex=${this.bodyGridIndex} aria-readonly=${this.grid ? 'true' : nothing}>${control}</div>`;\n    }\n\n    override render() {\n        const filler = this.filler ? html`<div class=\"filler\" aria-hidden=\"true\"></div>` : nothing;\n        return html`${this.expandColumn ? this.renderExpandCell() : nothing}${this.selectionName ? this.renderSelectCell() : nothing}<slot></slot>${filler}`;\n    }\n}\n\n/**\n * Carbon `cds-table-row`: a body row of `<ui-table-cell>`s. Hovering it tints the row and its rules. With\n * `use-zebra-styles` on the table, its body marks every second row `even` (striped) and the others `odd`.\n *\n * Selection (the table's `is-selectable` / `radio`): a checkbox (or radio) cell before the cells; choosing fires\n * the cancelable `ui-table-row-change-selection` and sets `selected`. Expansion (the table's `expandable`): a\n * chevron cell that opens the `<ui-table-expanded-row>` right after it, through the cancelable\n * `ui-table-row-expando-beingtoggled`, then `ui-table-row-expando-toggled`.\n *\n * @slot - The row's `<ui-table-cell>`s\n * @fires ui-table-row-change-selection - cancelable; detail: { selected } before the row is chosen or released\n * @fires ui-table-row-expando-beingtoggled - cancelable; detail: { expanded } before the row opens or closes\n * @fires ui-table-row-expando-toggled - detail: { expanded } after the row opened or closed\n * @cssprop --ui-table-row-selected - Fill of a chosen row (default `--ui-layer-accent`; Kanok: `--ui-highlight`)\n * @cssprop --ui-table-row-thread - `background-image` of a chosen row's first cell, for a mark on its start edge (default none; Kanok: a 3px `--ui-border-interactive` mark)\n * @cssprop --ui-icon-control-radius - Corners of its small icon buttons, their hover fill and ring (default 0; Kanok: round)\n */\n@customElement('ui-table-row')\nexport class UiTableRow extends UiTableRowBase {\n    static override readonly styles = [\n        UiTableRowBase.styles,\n        css`\n            :host {\n                transition: background-color var(--ui-duration-fast) var(--ui-easing-entrance); /* Carbon fast-01, entrance */\n            }\n\n            /*\n             * zebra: the body marks the rows; the cells read the rules from these properties (and pinned cells the row's\n             * colour: --_row-base under --_row-tint)\n             */\n            :host([odd]) {\n                --_row-rule-end: var(--ui-surface-1);\n            }\n\n            :host([even]) {\n                --_row-rule-end: var(--ui-layer-background);\n                --_row-base: var(--ui-layer-background);\n\n                background-color: var(--ui-layer-background);\n            }\n\n            /* the chosen row's mark on its start edge, in its first cell: none in Carbon (Kanok: a border-interactive mark) */\n            :host([selected]) :is(.expand, .select):first-child,\n            :host([selected]) slot:first-child::slotted(:first-child) {\n                background-image: var(--ui-table-row-thread, none);\n            }\n\n            /* chosen (Carbon web components: layer-accent; the rule below stays border-subtle) */\n            :host([selected]) {\n                --_row-ink: var(--ui-ink);\n                --_row-base: var(--ui-table-row-selected, var(--ui-layer-accent));\n\n                background-color: var(--ui-table-row-selected, var(--ui-layer-accent));\n            }\n\n            /* open: a subtle rule joins it to its expanded row, none under the chevron */\n            :host([expanded]) {\n                --_row-rule-end: var(--ui-hairline);\n            }\n\n            :host([expanded]) .expand {\n                box-shadow: none;\n            }\n\n            @media (any-hover: hover) {\n                /* Carbon web components: background-hover (translucent) under the cells, layer-hover rules, primary text */\n                :host(:hover),\n                :host([highlighted]) {\n                    --_row-rule-end: var(--ui-ghost-hover);\n                    --_row-ink: var(--ui-ink);\n                    --_row-tint: var(--ui-canvas-hover);\n\n                    background-color: var(--ui-canvas-hover);\n                }\n\n                :host([selected]:hover),\n                :host([selected][highlighted]) {\n                    --_row-rule-end: var(--ui-layer-selected-hover);\n                    --_row-base: var(--ui-layer-selected-hover);\n                    --_row-tint: transparent;\n\n                    background-color: var(--ui-layer-selected-hover); /* data-table-column-hover */\n                }\n\n                :host([expanded]:hover),\n                :host([expanded][highlighted]) {\n                    --_row-rule-end: var(--ui-hairline);\n                }\n            }\n\n            @media (prefers-reduced-motion: reduce) {\n                :host {\n                    transition: none;\n                }\n            }\n\n            @media (forced-colors: active) {\n                :host([selected]) {\n                    --_row-rule-end: Highlight;\n                }\n            }\n        `,\n    ];\n\n    /** A striped row (set by the body with `use-zebra-styles`). */\n    @property({ type: Boolean, reflect: true }) even = false;\n\n    /** An unstriped row of a zebra table (set by the body). */\n    @property({ type: Boolean, reflect: true }) odd = false;\n}\n\nexport interface UiTableRowEventMap extends HTMLElementEventMap {\n    'ui-table-row-change-selection': CustomEvent<TableSelectionDetail>;\n    'ui-table-row-expando-beingtoggled': CustomEvent<TableExpandoDetail>;\n    'ui-table-row-expando-toggled': CustomEvent<TableExpandoDetail>;\n}\n\n/** Typed listeners for UiTableRow's events (declaration merging with the class). */\nexport interface UiTableRow {\n    addEventListener<K extends keyof UiTableRowEventMap>(type: K, listener: (this: UiTableRow, event: UiTableRowEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiTableRowEventMap>(type: K, listener: (this: UiTableRow, event: UiTableRowEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-row': UiTableRow;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-skeleton.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-skeleton.ts",
      "content": "import { html, css, nothing } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { defaultTrue } from '../shared/field.ts';\nimport { skeletonStyles } from '../shared/skeleton.ts';\nimport { UiElement } from '../shared/element.ts';\n\nconst bone = html`<span class=\"bone bar\"></span>`;\n\n/**\n * Carbon `cds-table-skeleton`: a table-shaped placeholder while the data loads — a title and description bar\n * (`show-header`), a toolbar (`show-toolbar`), header bars (or `headers` texts) and `row-count` × `column-count`\n * cell bars (default 5 × 5), striped with `zebra`. Hidden from screen readers; say \"Loading\" elsewhere.\n *\n * @csspart table - The `<table>`\n */\n@customElement('ui-table-skeleton')\nexport class UiTableSkeleton extends UiElement {\n    static override readonly styles = [\n        skeletonStyles,\n        css`\n            :host {\n                display: block;\n            }\n\n            .container {\n                padding-block-start: 2px; /* spacing-01 */\n            }\n\n            .header {\n                padding-block: var(--ui-space-md) var(--ui-space-lg);\n                padding-inline: var(--ui-space-md);\n                background-color: var(--ui-surface-1);\n            }\n\n            .bar {\n                display: block;\n                inline-size: 64px;\n                block-size: 16px;\n            }\n\n            .title-bar {\n                inline-size: 120px;\n                block-size: 24px;\n            }\n\n            .description-bar {\n                inline-size: 160px;\n                margin-block-start: var(--ui-space-xs);\n            }\n\n            .toolbar {\n                display: flex;\n                justify-content: flex-end;\n                block-size: 48px;\n                background-color: var(--ui-surface-1);\n            }\n\n            .toolbar .bar {\n                inline-size: 150px;\n                block-size: 100%;\n            }\n\n            table {\n                inline-size: 100%;\n                border-collapse: collapse;\n                border-spacing: 0;\n            }\n\n            tr {\n                block-size: 48px;\n            }\n\n            th,\n            td {\n                box-sizing: border-box;\n                padding-inline: var(--ui-space-md);\n                text-align: start;\n                vertical-align: middle;\n            }\n\n            th {\n                background-color: var(--ui-table-header-background, var(--ui-layer-accent));\n                color: var(--ui-ink);\n                font: var(--ui-font-body-emphasis);\n                font-weight: 600;\n                line-height: 1.42857; /* heading-01 */\n                letter-spacing: var(--ui-tracking-body);\n            }\n\n            th .bar {\n                background-color: var(--ui-skeleton-element);\n            }\n\n            /* narrower than its columns (a phone), the bars shrink with their cells instead of widening the page */\n            table .bar {\n                inline-size: min(64px, 100%);\n            }\n\n            tbody {\n                background-color: var(--ui-surface-1);\n            }\n\n            td {\n                border-block-end: 1px solid var(--ui-hairline);\n            }\n\n            :host([zebra]) tbody tr:nth-child(odd) td {\n                border-block-end-color: var(--ui-surface-1);\n            }\n\n            :host([zebra]) tbody tr:nth-child(even) {\n                background-color: var(--ui-layer-background);\n            }\n\n            :host([zebra]) tbody tr:nth-child(even) td {\n                border-block-end-color: var(--ui-layer-background);\n            }\n        `,\n    ];\n\n    /** Header texts to show instead of bars (Carbon `headers`); their number sets the columns. */\n    @property({ attribute: false }) headers: string[] = [];\n\n    @property({ type: Number, reflect: true, attribute: 'column-count' }) columnCount = 5;\n\n    @property({ type: Number, reflect: true, attribute: 'row-count' }) rowCount = 5;\n\n    /** The title / description bars (Carbon `show-header`; `show-header=\"false\"` hides them). */\n    @property({ reflect: true, attribute: 'show-header', converter: defaultTrue }) showHeader = true;\n\n    /** The toolbar bar (Carbon `show-toolbar`; `show-toolbar=\"false\"` hides it). */\n    @property({ reflect: true, attribute: 'show-toolbar', converter: defaultTrue }) showToolbar = true;\n\n    /** Stripe every second row. */\n    @property({ type: Boolean, reflect: true }) zebra = false;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        this.setAttribute('aria-hidden', 'true');\n    }\n\n    private renderHeaderCell(index: number) {\n        return html`<th>${this.headers[index] ?? bone}</th>`;\n    }\n\n    private renderRow(cells: number[]) {\n        const cell = html`<td>${bone}</td>`;\n        return html`<tr>${cells.map(() => cell)}</tr>`;\n    }\n\n    override render() {\n        const columns = this.headers.length || Math.max(1, this.columnCount);\n        const cells = Array.from({ length: columns }, (_, i) => i);\n        const rows = Array.from({ length: Math.max(0, this.rowCount) }, (_, i) => i);\n        const header = this.showHeader ? html`<div class=\"header\"><span class=\"bone bar title-bar\"></span><span class=\"bone bar description-bar\"></span></div>` : nothing;\n        const toolbar = this.showToolbar ? html`<div class=\"toolbar\"><span class=\"bone bar\"></span></div>` : nothing;\n        return html`<div class=\"container\">\n            ${header}${toolbar}\n            <table part=\"table\">\n                <thead>\n                    <tr>\n                        ${cells.map((i) => this.renderHeaderCell(i))}\n                    </tr>\n                </thead>\n                <tbody>\n                    ${rows.map(() => this.renderRow(cells))}\n                </tbody>\n            </table>\n        </div>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-skeleton': UiTableSkeleton;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-toolbar-action.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-toolbar-action.styles.ts",
      "content": "import { css } from 'lit';\n\n/** Carbon toolbar action (TableToolbarMenu / .cds--toolbar-action): an icon button as tall as the toolbar, field-hover. */\nexport const toolbarActionStyles = css`\n    .button {\n        display: grid;\n        place-items: center;\n        inline-size: var(--_toolbar, 48px);\n        block-size: var(--_toolbar, 48px);\n        padding: 0;\n        border: none;\n        background-color: transparent;\n        color: var(--ui-icon-primary);\n        cursor: pointer;\n        transition: background-color var(--ui-duration-moderate) var(--ui-easing-entrance); /* Carbon .cds--toolbar-action, fast-02 */\n        border-radius: var(--ui-icon-control-radius, 0); /* round in a design that rounds icon controls (Kanok) */\n    }\n\n    .button svg {\n        inline-size: 16px;\n        block-size: 16px;\n        fill: currentColor;\n    }\n\n    @media (any-hover: hover) {\n        .button:hover {\n            background-color: var(--ui-ghost-hover); /* field-hover */\n        }\n    }\n\n    .button:focus-visible {\n        outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n        outline-offset: var(--ui-focus-offset, -2px);\n    }\n\n    @media (prefers-reduced-motion: reduce) {\n        .button {\n            transition: none;\n        }\n    }\n`;\n"
    },
    {
      "path": "src/primitives/table/table-toolbar-content.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-toolbar-content.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-toolbar-content`: the toolbar's controls, at its end — a `<ui-table-toolbar-search>`, toolbar\n * actions, a primary `<ui-button>`. While rows are chosen (`has-batch-actions`, the table sets it) it slides away\n * under the batch actions and leaves the Tab order.\n *\n * @slot - The controls\n */\n@customElement('ui-table-toolbar-content')\nexport class UiTableToolbarContent extends UiElement {\n    static override readonly styles = css`\n        :host {\n            display: flex;\n            justify-content: flex-end;\n            inline-size: 100%;\n            block-size: var(--_toolbar, 48px);\n            transform: translate3d(0, 0, 0);\n            transition:\n                transform var(--ui-duration-moderate) var(--ui-easing),\n                clip-path var(--ui-duration-moderate) var(--ui-easing);\n        }\n\n        :host([has-batch-actions]) {\n            clip-path: polygon(0 0, 100% 0, 100% 0, 0 0);\n            transform: translate3d(0, var(--_toolbar, 48px), 0);\n        }\n\n        /* the controls keep their size; the search shrinks to what is left (it is 100% wide when open), so it stays in the toolbar */\n        ::slotted(:not(ui-table-toolbar-search)) {\n            flex-shrink: 0;\n        }\n\n        @media (prefers-reduced-motion: reduce) {\n            :host {\n                transition: none;\n            }\n        }\n    `;\n\n    /** The batch actions are showing (rows are chosen). */\n    @property({ type: Boolean, reflect: true, attribute: 'has-batch-actions' }) hasBatchActions = false;\n\n    protected override updated(changed: Map<string, unknown>) {\n        // under the batch actions: out of sight and out of reach (Carbon sets tabindex -1; inert keeps its controls out too)\n        if (changed.has('hasBatchActions')) this.inert = this.hasBatchActions;\n    }\n\n    override render() {\n        return html`<slot></slot>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-toolbar-content': UiTableToolbarContent;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-toolbar-search.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-toolbar-search.ts",
      "content": "import { css, type PropertyValues } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiSearch } from '../search/search.ts';\n\n/**\n * Carbon `cds-table-toolbar-search`: a `<ui-search>` for `<ui-table-toolbar-content>` that filters the table as you\n * type (the table hides the rows whose text doesn't contain it). Collapsed to its magnifier (a square of the toolbar's\n * height) until focused, then as wide as the toolbar; it collapses again when it loses focus empty. `persistent`\n * keeps it open. Its name and placeholder default to \"Filter table\".\n * @cssprop --ui-field-open-background - The box's fill while a search is under way (default the layer's field fill)\n */\n@customElement('ui-table-toolbar-search')\nexport class UiTableToolbarSearch extends UiSearch {\n    static override readonly styles = [\n        ...UiSearch.styles,\n        css`\n            :host {\n                flex: 0 1 auto;\n                min-inline-size: 0;\n            }\n\n            input {\n                background-color: var(--ui-surface-1);\n                transition:\n                    outline-color var(--ui-duration-moderate) var(--ui-easing),\n                    background-color var(--ui-duration-moderate) var(--ui-easing); /* Carbon .cds--search-input, fast-02 */\n            }\n\n            :host([persistent]),\n            :host([expanded]) {\n                inline-size: 100%;\n            }\n\n            :host([persistent]) input {\n                border-block-end: none;\n            }\n\n            /* collapsed: a magnifier square; the text box is there but unseen (Carbon .cds--toolbar-search-container-expandable) */\n            :host(:not([persistent])) {\n                inline-size: var(--_toolbar, 48px);\n                transition:\n                    inline-size 300ms cubic-bezier(0.5, 0, 0.1, 1),\n                    background-color var(--ui-duration-moderate) var(--ui-easing-entrance);\n            }\n\n            :host(:not([persistent])[expanded]) {\n                inline-size: 100%;\n            }\n\n            :host(:not([persistent]):not([expanded])) input {\n                padding: 0;\n                opacity: 0;\n                cursor: pointer;\n            }\n\n            @media (any-hover: hover) {\n                :host(:not([persistent]):not([expanded]):hover) {\n                    background-color: var(--ui-ghost-hover); /* field-hover */\n                }\n\n                :host([persistent]) input:hover {\n                    background-color: var(--ui-ghost-hover);\n                }\n            }\n\n            /* a search under way keeps a fill (--ui-field-open-background: a design can keep the field's own) */\n            :host([data-has-value]) input {\n                background-color: var(--ui-field-open-background, var(--ui-ghost-hover));\n            }\n\n            @media (prefers-reduced-motion: reduce) {\n                :host,\n                input {\n                    transition: none;\n                }\n            }\n        `,\n    ];\n\n    /** Always open (Carbon `persistent`). */\n    @property({ type: Boolean, reflect: true }) persistent = false;\n\n    private readonly tableLocalize = new LocalizeController(this);\n\n    override connectedCallback() {\n        super.connectedCallback();\n        this.addEventListener('focusin', this.onToolbarFocusIn);\n        this.addEventListener('focusout', this.onToolbarFocusOut);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.removeEventListener('focusin', this.onToolbarFocusIn);\n        this.removeEventListener('focusout', this.onToolbarFocusOut);\n    }\n\n    protected override firstUpdated(changed: PropertyValues<this>) {\n        super.firstUpdated(changed);\n        this.renderRoot.addEventListener('beforeinput', this.onBeforeInput);\n        this.renderRoot.addEventListener('input', this.keepCaret);\n    }\n\n    /** Where the caret belongs after the text being typed goes in: after it. */\n    private caretAfter: number | null = null;\n\n    private readonly onBeforeInput = (event: Event) => {\n        const { inputType, data, target } = event as InputEvent;\n        const input = target as HTMLInputElement;\n        this.caretAfter = inputType === 'insertText' && data && input.selectionStart !== null ? input.selectionStart + data.length : null;\n    };\n\n    /**\n     * While the box is still widening from its magnifier (right after the click), Chrome leaves the caret where it\n     * was after text that goes in by insertion (an IME, voice input, a test's insertText): typed fast, \"สมชาย\"\n     * came out \"ยาชมส\". Puts the caret back after what went in.\n     */\n    private readonly keepCaret = (event: Event) => {\n        const input = event.target as HTMLInputElement;\n        const at = this.caretAfter;\n        this.caretAfter = null;\n        if (at !== null && input.selectionStart !== at && at <= input.value.length) input.setSelectionRange(at, at);\n    };\n\n    protected override willUpdate() {\n        const t = this.tableLocalize.t.dataTable;\n        if (!this.label) this.label = t.searchLabel;\n        if (!this.placeholder) this.placeholder = t.searchPlaceholder;\n        super.willUpdate();\n    }\n\n    private readonly onToolbarFocusIn = () => {\n        this.expanded = true;\n    };\n\n    /** Empty and left: back to the magnifier, once focus has settled (moving to the clear button keeps it open). */\n    private readonly onToolbarFocusOut = () => {\n        setTimeout(() => {\n            if (!this.persistent && this.value === '' && !this.matches(':focus-within')) this.expanded = false;\n        });\n    };\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-toolbar-search': UiTableToolbarSearch;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table-toolbar.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table-toolbar.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { setManagedAttribute } from '../shared/field.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\n\n/**\n * Carbon `cds-table-toolbar`: the bar above the table, in its `toolbar` slot (`role=toolbar`): a\n * `<ui-table-batch-actions>` and a `<ui-table-toolbar-content>`. As tall as the table's size (24px xs, 32px sm,\n * 48px otherwise).\n *\n * @slot - `<ui-table-batch-actions>` and `<ui-table-toolbar-content>`\n */\n@customElement('ui-table-toolbar')\nexport class UiTableToolbar extends UiElement {\n    static override readonly styles = css`\n        :host {\n            position: relative;\n            z-index: 1;\n            display: flex;\n            inline-size: 100%;\n            block-size: var(--_toolbar, 48px);\n            min-block-size: var(--_toolbar, 48px);\n            background-color: var(--ui-table-background, var(--ui-surface-1));\n        }\n    `;\n\n    private readonly localize = new LocalizeController(this);\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'toolbar');\n    }\n\n    protected override updated() {\n        setManagedAttribute(this, 'aria-label', this.localize.t.dataTable.toolbar);\n    }\n\n    override render() {\n        return html`<slot></slot>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table-toolbar': UiTableToolbar;\n    }\n}\n"
    },
    {
      "path": "src/primitives/table/table.styles.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table.styles.ts",
      "content": "import { css } from 'lit';\n\n/** Styles of `<ui-table>`. */\nexport const tableStyles = css`\n    /*\n     * per size (Carbon web components data-table.scss, measured on its storybook): row height, cell padding, the\n     * header's top padding and the sort button's height (32px from sm down, 48px in xl, under a 16px top)\n     */\n    :host {\n        /* a table inside another's expanded row doesn't take the outer one's sticky header */\n        --_head-position: static;\n        --_head-anchor: relative; /* a resizable header holds its handle */\n        --_head-z: auto;\n        --_head-edge: var(--ui-table-header-rule, 0 0 #0000); /* a design's rule under the header (Kanok: a hairline) */\n        /* lg, the default size (always reflected): 48px rows in Carbon; --ui-table-row-height lets a design change it */\n        --_row: var(--ui-table-row-height, 48px);\n        --_cell-pad-start: 0px;\n        --_cell-pad-end: 0px;\n        --_head-pad: 0px;\n        --_sort-row: var(--ui-table-row-height, 48px);\n        --_align: middle;\n\n        display: block;\n    }\n\n    :host([size='xs']) {\n        --_row: 24px;\n        --_cell-pad-start: 2px;\n        --_cell-pad-end: 2px;\n        --_sort-row: 32px;\n    }\n\n    :host([size='sm']) {\n        --_row: 32px;\n        --_cell-pad-start: 7px;\n        --_cell-pad-end: 6px;\n        --_sort-row: 32px;\n    }\n\n    :host([size='md']) {\n        --_row: 40px;\n        --_cell-pad-start: 7px;\n        --_cell-pad-end: 6px;\n        --_sort-row: 40px;\n    }\n\n    :host([size='xl']) {\n        --_row: 64px;\n        --_cell-pad-start: 16px;\n        --_head-pad: 16px;\n        --_align: top;\n    }\n\n    /* toolbar, selection and expand columns per size (Carbon --data-table--{size} toolbar, .table-column-checkbox, .table-expand) */\n    :host {\n        --_toolbar: 48px;\n    }\n\n    :host([size='xs']) {\n        --_toolbar: 24px;\n        --_expand-pad: 0 0 0 8px;\n        --_expand-button: 24px;\n        --_select-inline-after-expand: 6px;\n    }\n\n    :host([size='sm']) {\n        --_toolbar: 32px;\n        --_select-pad: 3px;\n        --_expand-pad: 0 0 0 8px;\n        --_select-inline-after-expand: 6px;\n    }\n\n    :host([size='md']) {\n        --_select-pad: 3px;\n        --_expand-pad: 4px 0 4px 8px;\n        --_select-inline-after-expand: 6px;\n    }\n\n    :host([size='xl']) {\n        --_select-pad: 10px 0 0;\n        --_radio-pad: 16px;\n        --_expand-pad: 10px 0 22px 8px;\n        --_select-inline-after-expand: 6px;\n        --_expanded-pad: 16px 16px 8px 64px;\n    }\n\n    /* --ui-table-border / -radius / -overflow: Carbon's table is an open block; a design can frame it as its cards */\n    .container {\n        position: relative;\n        padding-block-start: 2px; /* spacing-01 */\n        border: var(--ui-table-border, none);\n        border-radius: var(--ui-table-radius, 0);\n        overflow: var(--ui-table-overflow, visible);\n        background-color: var(--ui-table-background, transparent); /* a design can give the table its cards' fill */\n    }\n\n    :host([use-static-width]) .container {\n        inline-size: fit-content;\n    }\n\n    .header {\n        padding-block: var(--ui-space-md) var(--ui-space-lg);\n        padding-inline: var(--ui-space-md);\n        background-color: var(--ui-table-background, var(--ui-surface-1));\n    }\n\n    .header[hidden] {\n        display: none;\n    }\n\n    :host(:dir(rtl)) {\n        --_dir: -1;\n    }\n\n    .content {\n        display: block;\n        overflow-x: auto;\n        isolation: isolate; /* the pinned cells' layers stay inside the table */\n    }\n\n    /* the box takes focus when it scrolls, so keyboard users can scroll it (Carbon .data-table-content:focus) */\n    .content:focus-visible {\n        outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n        outline-offset: -2px;\n        border-radius: var(--ui-table-radius, 0); /* inside the table's frame, its corners (Kanok: 12px) */\n    }\n\n    /* sticky header (Carbon React stickyHeader): the body scrolls under the header inside a box (Carbon 300px) */\n    :host([sticky-header]) {\n        --_head-position: sticky;\n        --_head-anchor: sticky;\n        --_head-z: 2; /* over pinned body cells scrolling under it */\n        --_head-edge: inset 0 -1px 0 var(--ui-ghost-active); /* collapsed borders don't travel with sticky cells */\n    }\n\n    :host([sticky-header]) .content {\n        max-block-size: var(--ui-table-max-height, 300px);\n        overflow-y: auto;\n        scroll-padding-block-start: var(--_row); /* focused rows don't hide under the sticky header (WCAG 2.4.11) */\n    }\n\n    .table {\n        display: table;\n        inline-size: 100%;\n        border-collapse: collapse;\n        border-spacing: 0;\n    }\n\n    /* resized: the columns keep their widths (long words wrap inside), the filler cells take the rest */\n    :host([data-fixed]:not([use-static-width])) .table {\n        table-layout: fixed;\n    }\n\n    :host([data-fixed]) {\n        overflow-wrap: anywhere;\n    }\n\n    ui-pagination {\n        display: block;\n    }\n\n    :host([use-static-width]) .table {\n        inline-size: auto;\n    }\n\n    /* loading: skeleton rows in the columns instead of the body (Carbon DataTableSkeleton bars, 4rem × 1rem) */\n    :host([loading]) ::slotted(ui-table-body) {\n        display: none;\n    }\n\n    .loading {\n        display: table-row-group;\n    }\n\n    .loading-row {\n        display: table-row;\n        block-size: var(--_row);\n    }\n\n    .loading-cell {\n        display: table-cell;\n        box-sizing: border-box;\n        padding-inline: var(--ui-space-md);\n        border-block-end: 1px solid var(--ui-hairline);\n        background-color: var(--ui-surface-1);\n        vertical-align: middle;\n    }\n\n    :host([use-zebra-styles]) .loading-row:nth-child(odd) .loading-cell {\n        border-block-end-color: var(--ui-surface-1);\n    }\n\n    :host([use-zebra-styles]) .loading-row:nth-child(even) .loading-cell {\n        border-block-end-color: var(--ui-layer-background);\n        background-color: var(--ui-layer-background);\n    }\n\n    .loading-bar {\n        display: block;\n        inline-size: 64px;\n        max-inline-size: 100%;\n        block-size: 16px;\n    }\n\n    /* no rows: a message as wide as the table under its headers */\n    .empty {\n        display: table-caption;\n        caption-side: bottom;\n    }\n\n    .empty-cell {\n        display: block;\n        padding: var(--ui-space-md);\n        border-block-end: 1px solid var(--ui-hairline);\n        background-color: var(--ui-surface-1);\n        color: var(--ui-ink-muted);\n        font: var(--ui-font-body-sm);\n        line-height: 18px; /* body-compact-01 */\n        letter-spacing: var(--ui-tracking-body);\n        text-align: start;\n    }\n`;\n"
    },
    {
      "path": "src/primitives/table/table.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/table/table.ts",
      "content": "import { html, isServer, nothing } from 'lit';\nimport { customElement, property, state } from 'lit/decorators.js';\nimport { columnLocked, compareCells, pageCount } from '../../core/table.ts';\nimport { downloadCsv as saveCsv, toCsv as buildCsv } from '../../core/csv.ts';\nimport type { PaginationChangeDetail, PaginationSize } from '../pagination/pagination.ts';\nimport '../pagination/pagination.ts';\nimport { deepActiveElement, hasData, setManagedAttribute, srOnlyStyles } from '../shared/field.ts';\nimport { skeletonStyles } from '../shared/skeleton.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport { UiElement } from '../shared/element.ts';\nimport type {\n    TableAllSelectedDetail,\n    TableCellEditDetail,\n    TableCsvExportDetail,\n    TableColumnResizeDetail,\n    TableColumnsChangeDetail,\n    TableCsvScope,\n    TablePageChangeDetail,\n    TableExpandoDetail,\n    TableFilteredDetail,\n    TableHeaderCellSortDetail,\n    TableRowSelectedDetail,\n    TableSelectionDetail,\n    TableSize,\n    TableSortDirection,\n    TableSortedDetail,\n} from './defs.ts';\nimport { UiTableBody } from './table-body.ts';\nimport { UiTableHeaderCell } from './table-header-cell.ts';\nimport type { UiTableHeaderRow } from './table-header-row.ts';\nimport type { UiTableCell } from './table-cell.ts';\nimport type { UiTableRow } from './table-row.ts';\nimport type { UiTableExpandedRow } from './table-expanded-row.ts';\nimport type { UiTableBatchActions } from './table-batch-actions.ts';\nimport type { UiTableToolbarContent } from './table-toolbar-content.ts';\nimport type { UiTableToolbarSearch } from './table-toolbar-search.ts';\nimport { TableGrid } from './table-grid.ts';\nimport './table-cell.ts';\nimport './table-head.ts';\nimport './table-header-row.ts';\nimport './table-row.ts';\nimport './table-expanded-row.ts';\nimport './table-header-title.ts';\nimport './table-header-description.ts';\nimport './table-toolbar.ts';\nimport './table-toolbar-content.ts';\nimport './table-toolbar-search.ts';\nimport './table-batch-actions.ts';\nimport './table-skeleton.ts';\nimport './table-column-settings.ts';\nimport './table-csv-export.ts';\nimport { tableStyles } from './table.styles.ts';\n\nexport * from './defs.ts';\nexport { UiTableBody } from './table-body.ts';\nexport { UiTableCell, type UiTableCellEventMap } from './table-cell.ts';\nexport { UiTableHead } from './table-head.ts';\nexport { UiTableHeaderCell, type UiTableHeaderCellEventMap } from './table-header-cell.ts';\nexport { UiTableHeaderRow, type UiTableHeaderRowEventMap } from './table-header-row.ts';\nexport { UiTableRow, UiTableRowBase, type UiTableRowEventMap } from './table-row.ts';\nexport { UiTableExpandedRow } from './table-expanded-row.ts';\nexport { UiTableHeaderTitle } from './table-header-title.ts';\nexport { UiTableHeaderDescription } from './table-header-description.ts';\nexport { UiTableToolbar } from './table-toolbar.ts';\nexport { UiTableToolbarContent } from './table-toolbar-content.ts';\nexport { UiTableToolbarSearch } from './table-toolbar-search.ts';\nexport { UiTableBatchActions, type UiTableBatchActionsEventMap } from './table-batch-actions.ts';\nexport { UiTableSkeleton } from './table-skeleton.ts';\nexport { UiTableColumnSettings } from './table-column-settings.ts';\nexport { UiTableCsvExport, type UiTableCsvExportEventMap } from './table-csv-export.ts';\n\n/** Carbon's default `filterRows`: true leaves the row out (its text doesn't contain the search). */\nconst filterOut = (rowText: string, searchString: string) => !rowText.toLowerCase().includes(searchString.toLowerCase());\n\n/** A cell as CSV: its `csv-value`, else its text; a number written as one stays a number (no formula guard). */\nfunction csvValue(cell: Element | undefined): unknown {\n    const text = cell?.getAttribute('csv-value') ?? cell?.textContent?.trim() ?? '';\n    const number = Number(text);\n    return text !== '' && String(number) === text ? number : text;\n}\n\n/** A skeleton cell of a loading row: a bar in a data column, empty in the chevron, checkbox and filler columns. */\nconst loadingBar = html`<div class=\"loading-cell\"><span class=\"bone loading-bar\"></span></div>`;\nconst loadingBlank = html`<div class=\"loading-cell\"></div>`;\n\n/** Whether `node` sits inside `container`, through the shadow roots between them. */\nfunction containsDeep(container: Node, node: Node | null): boolean {\n    let current: Node | null = node;\n    while (current) {\n        if (container.contains(current)) return true;\n        const root = current.getRootNode();\n        current = root instanceof ShadowRoot ? root.host : null;\n    }\n    return false;\n}\n\n/**\n * Carbon `cds-table`: a table built from elements — `<ui-table-head>` with a `<ui-table-header-row>` of\n * `<ui-table-header-cell>`s, and `<ui-table-body>` with `<ui-table-row>`s of `<ui-table-cell>`s. CSS table\n * layout (the columns line up as in a `<table>`), `role=table` / `rowgroup` / `row` / `columnheader` / `cell`.\n *\n * Sizes xs / sm / md / lg (default) / xl, `use-zebra-styles`, `use-static-width` (as wide as its content).\n *\n * Sorting (`is-sortable`, or `is-sortable` on single headers): a header click steps its `sort-direction`\n * through its `sort-cycle`, the other headers go back to none, and the table moves the body's rows into\n * that order (an expanded row moves with the row before it), then fires `ui-table-sorted`. A cell sorts by\n * its `sort-value`, else its text: numbers by value, text by `locale` (default: the page's `lang`);\n * `customSortRow` replaces the comparison. None restores the order the rows came in. Sorting keeps the\n * focus and the scroll position.\n *\n * Rows rendered by a framework (React, Vue): call `preventDefault()` on `ui-table-header-cell-sort`, sort\n * the data, render the rows in that order and set the header's `sort-direction` — moving rows a framework\n * owns makes its later updates go wrong.\n *\n * Selection (`is-selectable`, or `radio` for one row): every row gets a checkbox (radio) cell and the header\n * row a select-all checkbox — checked while rows are chosen, partly while only some are; clicking it then\n * releases them all. Choices fire `ui-table-row-selected` / `ui-table-row-all-selected`; a `<ui-table-batch-actions>`\n * in the toolbar shows the count and Cancel while rows are chosen. Disabled rows can't be chosen; select-all\n * takes only the rows the search shows. Radio rows take one Tab stop and the arrow keys.\n *\n * Title and toolbar (Carbon TableContainer / TableToolbar): `<ui-table-header-title slot=\"title\">`,\n * `<ui-table-header-description slot=\"description\">` and `<ui-table-toolbar slot=\"toolbar\">`. Typing in a\n * `<ui-table-toolbar-search>` leaves out (`filtered`) the rows whose text doesn't contain it — `filterRows`\n * replaces the test — and fires `ui-table-filtered`; the zebra stripes follow the rows shown.\n *\n * Expansion (`expandable`): a `<ui-table-expanded-row>` right after a row makes it expandable — a chevron cell\n * opens it underneath; `batch-expansion` puts an expand-all chevron in the header row.\n *\n * Paging (no Carbon counterpart on the table; Carbon pages with a separate Pagination): `page-size` adds a\n * `<ui-pagination>` under the table that shows that many of the rows the sort and search leave (`page`,\n * `page-sizes`; `ui-table-page-change`). Select-all then takes the page, and the batch bar offers \"Select all (N)\"\n * for every row the search shows. Server paging: give the table one page of rows and use your own `<ui-pagination>`.\n *\n * Columns (no Carbon counterpart): a `<ui-table-column-settings>` in the toolbar hides and shows columns\n * (`ui-table-columns-change`; `hiddenColumns`, `setColumnHidden()`, `resetColumns()`); the search skips hidden\n * columns. `pinned` on the first / last header keeps that column in view while the table scrolls sideways (a\n * pinned first column takes the chevron and checkbox columns with it). `resizable` puts a resize handle on every\n * header: the first resize freezes the columns at their widths and an empty filler cell takes the rest of the row.\n *\n * Editing (no Carbon counterpart; the WAI-ARIA APG grid): `editable=\"text|number|select\"` on a header lets its cells\n * be edited in place. The table becomes a grid with one Tab stop among the body cells (arrow keys, Home / End);\n * Enter, F2, typing or a double click opens a cell's editor, Enter saves, Escape cancels, Tab saves and goes to the\n * next editable cell. Saving fires a cancelable `ui-table-cell-edit` from the cell, then writes the value into it.\n *\n * CSV (no Carbon counterpart): a `<ui-table-csv-export>` in the toolbar downloads the rows the search shows;\n * `toCsv({ scope })` / `downloadCsv({ scope, fileName })` export `'shown'`, `'selected'` or `'all'` rows.\n *\n * Loading and empty (Carbon's DataTable leaves both to the app): `loading` shows skeleton rows in the columns\n * (`loading-rows`, default the rows shown, else the page size, else 5) with the table `aria-busy`. With no rows\n * the table shows the `empty` slot (\"No data\"), or `no-results` (\"No results found…\") while the search leaves none.\n *\n * Differs from Carbon web components, which: sort numbers as text (\"10\" before \"9\"); leave none in no set\n * order; sort the rows even when the event was canceled; set no `aria-sort`; give the checkbox and chevron\n * cells no role; and keep zebra stripes on rows the search hid.\n *\n * @slot - `<ui-table-head>` and `<ui-table-body>`\n * @slot title - A `<ui-table-header-title>`\n * @slot description - A `<ui-table-header-description>`\n * @slot toolbar - A `<ui-table-toolbar>`\n * @slot empty - Shown when there are no rows (default: \"No data\")\n * @slot no-results - Shown when the search leaves no rows (default: \"No results found. Try a different search.\")\n * @csspart header - The title / description block\n * @csspart content - The horizontal scroll container\n * @csspart table - The box laid out as a table\n * @csspart empty - The message under the headers when there are no rows\n * @fires ui-table-sorted - detail: { sortedHeader } after the rows were sorted by a header click\n * @fires ui-table-row-selected - detail: { selectedRow, selectedRows } after the user chose or released a row\n * @fires ui-table-row-all-selected - detail: { selectedRows } after select-all or Cancel\n * @fires ui-table-filtered - detail: { unfilteredRows } after the search changed which rows show\n * @fires ui-table-page-change - detail: { page, pageSize } after the built-in pagination changed (`page-size`)\n * @fires ui-table-cell-edit - from the cell, cancelable; detail: { row, cell, column, value, previous } before an edited value is written into the cell (`preventDefault()` to write it yourself)\n * @fires ui-table-columns-change - detail: { hiddenColumns, column, hidden } after a column was shown or hidden (`column` is '' after Reset)\n * @csspart pagination - The built-in `<ui-pagination>` (`page-size`)\n * @cssprop --ui-table-max-height - Height of the scrolling box with `sticky-header` (default 300px)\n * @cssprop --ui-table-row-height - Row height of the default size, lg (default 48px; Kanok: 40px)\n * @cssprop --ui-table-border / --ui-table-radius / --ui-table-overflow - A frame around the table (default none, 0, visible; Kanok: none, 12px, clip)\n * @cssprop --ui-table-background - Fill of the table: its title, toolbar and rows (default transparent, rows `--ui-surface-1`; Kanok: the cards' fill)\n * @cssprop --ui-table-header-rule - `box-shadow` under the header cells (default none; Kanok: a hairline)\n */\n@customElement('ui-table')\nexport class UiTable extends UiElement {\n    static override readonly styles = [\n        skeletonStyles,\n        srOnlyStyles,\n        tableStyles,\n    ];\n\n    @property({ reflect: true }) size: TableSize = 'lg';\n\n    /** Every header sorts the rows (Carbon `is-sortable`). */\n    @property({ type: Boolean, reflect: true, attribute: 'is-sortable' }) isSortable = false;\n\n    /** Stripe every second body row (Carbon `use-zebra-styles`). */\n    @property({ type: Boolean, reflect: true, attribute: 'use-zebra-styles' }) useZebraStyles = false;\n\n    /** As wide as its content instead of its container (Carbon `use-static-width`). */\n    @property({ type: Boolean, reflect: true, attribute: 'use-static-width' }) useStaticWidth = false;\n\n    /** The language text sorts in; empty: the page's `lang`. */\n    @property({ reflect: true }) locale = '';\n\n    /** A checkbox on every row and select-all in the header row (Carbon `is-selectable`). */\n    @property({ type: Boolean, reflect: true, attribute: 'is-selectable' }) isSelectable = false;\n\n    /** One row at a time, with radios (Carbon `radio`). */\n    @property({ type: Boolean, reflect: true }) radio = false;\n\n    /** Rows followed by a `<ui-table-expanded-row>` open it with a chevron (Carbon `expandable`). */\n    @property({ type: Boolean, reflect: true }) expandable = false;\n\n    /** An expand-all chevron in the header row (Carbon `batch-expansion`). */\n    @property({ type: Boolean, reflect: true, attribute: 'batch-expansion' }) batchExpansion = false;\n\n    /** The title / description block shows (set from the `title` / `description` slots, as Carbon). */\n    @property({ type: Boolean, reflect: true, attribute: 'with-header' }) withHeader = false;\n\n    /** Whether the search leaves a row out: true hides it (Carbon `filterRows`; default: its text doesn't contain the search). */\n    @property({ attribute: false }) filterRows: (rowText: string, searchString: string) => boolean = filterOut;\n\n    /** A resize handle on every header (or `resizable` on single headers). */\n    @property({ type: Boolean, reflect: true }) resizable = false;\n\n    /** Rows per page: above 0 a `<ui-pagination>` pages the rows the sort and search leave. */\n    @property({ type: Number, attribute: 'page-size' }) pageSize = 0;\n\n    /** The page shown (from 1). */\n    @property({ type: Number }) page = 1;\n\n    /** The page sizes the pagination offers (comma-separated). */\n    @property({ attribute: 'page-sizes' }) pageSizes = '10,25,50';\n\n    /** Skeleton rows instead of the body while the data loads (the table is `aria-busy`). */\n    @property({ type: Boolean, reflect: true }) loading = false;\n\n    /** How many skeleton rows `loading` shows (default: the rows shown now, else the page size, else 5). */\n    @property({ type: Number, attribute: 'loading-rows' }) loadingRows = 0;\n\n    /** Keeps the header in view while the body scrolls inside a box (Carbon React `stickyHeader`; `--ui-table-max-height`, default 300px). */\n    @property({ type: Boolean, reflect: true, attribute: 'sticky-header' }) stickyHeader = false;\n\n    /** What the live region says (\"Loading data\" when `loading` turns on). */\n    @state() private announcement = '';\n\n    /** The columns are wider than the box: it scrolls sideways (and takes focus, WCAG 2.1.1). */\n    @state() private scrollable = false;\n\n    private resizeObserver?: ResizeObserver;\n\n    /** The hidden columns when the table first got its headers (what Reset restores). */\n    private initialHidden: string[] | null = null;\n    /** The batch bar's \"Select all (N)\" is the table's own (paging), not the author's (server paging). */\n    private ownsTotal = false;\n\n    private readonly localize = new LocalizeController(this);\n\n    private readonly grid = new TableGrid(this, {\n        shownRows: () => this.rows.filter((row) => !row.filtered && !row.pagedOut),\n        columns: () => this.headerCells,\n        editHint: () => this.localize.t.dataTable.editHint,\n    });\n\n    /** Each row's place in the order the rows came in (what none restores). */\n    private readonly order = new WeakMap<Element, number>();\n    private nextIndex = 0;\n    /** A header with a `sort-direction` in the markup has sorted the first rows. */\n    private initiallySorted = false;\n\n    /**\n     * Compares two cells' sort values (Carbon `customSortRow`) for ascending order: numbers by value, text\n     * with `collator`. Replace it on the element to sort another way.\n     */\n    customSortRow(lhs: string, rhs: string, collator: Intl.Collator): number {\n        return compareCells(lhs, rhs, collator.resolvedOptions().locale);\n    }\n\n    override connectedCallback() {\n        super.connectedCallback();\n        if (!this.hasAttribute('role')) this.setAttribute('role', 'table');\n        for (const [type, listener] of this.listeners) this.addEventListener(type, listener);\n        if (this.hasUpdated) this.observeSize();\n    }\n\n    protected override firstUpdated() {\n        this.observeSize();\n    }\n\n    private observeSize() {\n        const content = this.renderRoot.querySelector<HTMLElement>('.content');\n        const table = content?.querySelector('.table');\n        if (!content || !table || typeof ResizeObserver === 'undefined') return;\n        this.resizeObserver = new ResizeObserver(() => {\n            this.scrollable = content.scrollWidth > content.clientWidth + 1;\n        });\n        this.resizeObserver.observe(content);\n        this.resizeObserver.observe(table);\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.resizeObserver?.disconnect();\n        this.resizeObserver = undefined;\n        for (const [type, listener] of this.listeners) this.removeEventListener(type, listener);\n    }\n\n    private get listeners(): Array<[string, (event: Event) => void]> {\n        return [\n            ['ui-table-header-cell-sort', this.onSort],\n            ['ui-table-body-content-change', this.onContentChange],\n            ['ui-table-row-change-selection', this.onRowSelection],\n            ['ui-table-change-selection-all', this.onSelectAll],\n            ['ui-table-batch-actions-cancel-clicked', this.onCancel],\n            ['ui-table-radio-move', this.onRadioMove],\n            ['ui-table-row-expando-toggled', this.onExpando],\n            ['input', this.onSearch],\n            ['ui-clear', this.onSearch],\n            ['ui-table-batch-actions-select-all-clicked', this.onSelectAllPages],\n            ['keydown', this.grid.onKeydown],\n            ['focusin', this.grid.onFocusIn],\n            ['focusout', this.grid.onFocusOut],\n            ['click', this.grid.onClick],\n            ['dblclick', this.grid.onDoubleClick],\n        ];\n    }\n\n    private get body() {\n        return this.querySelector<UiTableBody>(':scope > ui-table-body');\n    }\n\n    private get headerCells() {\n        return [...this.querySelectorAll<UiTableHeaderCell>(':scope > ui-table-head > ui-table-header-row > ui-table-header-cell')];\n    }\n\n    private get rows() {\n        return [...(this.body?.children ?? [])].filter((row): row is UiTableRow => row.localName === 'ui-table-row');\n    }\n\n    private get headerRow() {\n        return this.querySelector<UiTableHeaderRow>(':scope > ui-table-head > ui-table-header-row');\n    }\n\n    private get batchActions() {\n        return this.querySelector<UiTableBatchActions>(':scope > ui-table-toolbar > ui-table-batch-actions');\n    }\n\n    private get toolbarContent() {\n        return this.querySelector<UiTableToolbarContent>(':scope > ui-table-toolbar > ui-table-toolbar-content');\n    }\n\n    /** The rows select-all and the arrow keys reach: shown (search, page) and not disabled. */\n    private get selectableRows() {\n        return this.rows.filter((row) => !row.filtered && !row.pagedOut && !row.disabled);\n    }\n\n    /** The column headers, in order (the column settings list them). */\n    get columns(): UiTableHeaderCell[] {\n        return this.headerCells;\n    }\n\n    /** The keys of the hidden columns. */\n    get hiddenColumns(): string[] {\n        return this.headerCells.filter((h) => h.columnHidden).map((h) => h.columnKey);\n    }\n\n    /** Whether `column` can't be hidden or shown now: not hideable, or the last one shown. */\n    isColumnLocked(column: string) {\n        return columnLocked(this.columnModel, this.hiddenColumns, column);\n    }\n\n    /** The headers as the core column helpers see them. */\n    private get columnModel() {\n        return this.headerCells.map((h) => ({ key: h.columnKey, hideable: h.hideable }));\n    }\n\n    /** Width of the horizontal scroll box (a resize stops a column there). */\n    get contentWidth() {\n        return this.renderRoot.querySelector<HTMLElement>('.content')?.clientWidth ?? 0;\n    }\n\n    /** The chosen rows. */\n    get selectedRows(): UiTableRow[] {\n        return this.rows.filter((row) => row.selected);\n    }\n\n    private get sortedHeader() {\n        return this.headerCells.find((cell) => cell.sortDirection === 'ascending' || cell.sortDirection === 'descending');\n    }\n\n    protected override willUpdate(changed: Map<string, unknown>) {\n        if (changed.has('loading') && changed.get('loading') !== undefined) this.announcement = this.loading ? this.localize.t.dataTable.loading : '';\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('loading')) setManagedAttribute(this, 'aria-busy', this.loading ? 'true' : null);\n        if (changed.has('useZebraStyles')) this.syncBody();\n        const sortable = changed.has('isSortable') && (this.isSortable || changed.get('isSortable') === true);\n        const resizable = changed.has('resizable') && (this.resizable || changed.get('resizable') === true);\n        if (sortable || resizable) this.syncHeaders();\n        if (['isSelectable', 'radio', 'expandable', 'batchExpansion', 'size', 'useStaticWidth'].some((key) => changed.has(key))) this.syncRows();\n        if (changed.has('pageSize') || changed.has('page')) this.syncPaging();\n    }\n\n    /** New head, body or toolbar: pass the table's settings down. */\n    private readonly onSlotChange = () => {\n        this.syncBody();\n        if (this.isSortable || this.resizable) this.syncHeaders();\n        this.syncRows();\n    };\n\n    /** A title or description came or went: the header block shows while there is one (Carbon `withHeader`). */\n    private readonly onHeaderSlotChange = () => {\n        this.withHeader = !!this.querySelector(':scope > [slot=\"title\"], :scope > [slot=\"description\"]');\n    };\n\n    /** Selection and expand settings onto the rows, the expanded rows' span, the toolbar's size. */\n    private syncRows() {\n        const selectable = this.isSelectable || this.radio;\n        const header = this.headerRow;\n        const rows = this.rows;\n        if (header) {\n            if (selectable && !header.selectionName) header.selectionName = 'header';\n            header.radio = this.radio;\n            header.expandColumn = this.expandable;\n            header.batchExpansion = this.expandable && this.batchExpansion;\n        }\n        rows.forEach((row, index) => {\n            if (selectable && !row.selectionName) row.selectionName = String(index);\n            row.radio = this.radio;\n            row.expandColumn = this.expandable;\n            row.expandable = this.expandable && row.nextElementSibling?.localName === 'ui-table-expanded-row';\n        });\n        this.syncColumns();\n        const toolbarSize = this.size === 'xs' || this.size === 'sm' ? this.size : 'lg';\n        const batch = this.batchActions;\n        if (batch) batch.size = toolbarSize;\n        for (const search of this.querySelectorAll<UiTableToolbarSearch>(':scope > ui-table-toolbar > ui-table-toolbar-content > ui-table-toolbar-search')) search.size = toolbarSize === 'lg' ? 'lg' : 'sm';\n        this.syncPaging();\n    }\n\n    /** The columns' hidden and pinned states onto every row's cells, the expanded rows' span, the pin offsets. */\n    private syncColumns() {\n        const headers = this.headerCells;\n        this.initialHidden ??= headers.length ? headers.filter((h) => h.columnHidden).map((h) => h.columnKey) : null;\n        const last = headers.length - 1;\n        const pinStart = headers[0]?.pinned === 'start';\n        const pinEnd = last > 0 && headers[last].pinned === 'end';\n        const pinnedAt = (index: number) => {\n            if (index === 0 && pinStart) return 'start';\n            if (index === last && pinEnd) return 'end';\n            return undefined;\n        };\n        const filler = this.dataset.fixed !== undefined && !this.useStaticWidth;\n        const header = this.headerRow;\n        for (const row of [...(header ? [header] : []), ...this.rows]) {\n            row.pinStart = pinStart;\n            row.filler = filler;\n        }\n        for (const row of this.rows) {\n            row.querySelectorAll<UiTableCell>(':scope > ui-table-cell').forEach((cell, index) => {\n                cell.columnHidden = !!headers[index]?.columnHidden;\n                cell.pinned = pinnedAt(index);\n                cell.editable = headers[index]?.editable;\n            });\n        }\n        const selectable = this.isSelectable || this.radio;\n        const shown = headers.filter((h) => !h.columnHidden).length;\n        const columns = shown + (selectable ? 1 : 0) + (this.expandable ? 1 : 0) + (filler ? 1 : 0);\n        for (const expanded of this.querySelectorAll<UiTableExpandedRow>(':scope > ui-table-body > ui-table-expanded-row')) expanded.colSpan = columns;\n        if (pinStart) void header?.updateComplete.then(() => this.measurePins());\n    }\n\n    /** A pinned first column sits after the chevron and checkbox columns, which stick before it. */\n    private measurePins() {\n        const header = this.headerRow;\n        const width = (selector: string) => header?.renderRoot.querySelector(selector)?.getBoundingClientRect().width ?? 0;\n        const expand = width('.expand');\n        this.style.setProperty('--_pin-select-at', `${expand}px`);\n        this.style.setProperty('--_pin-first-at', `${expand + width('.select')}px`);\n    }\n\n    /** Shows or hides a column (and its cells); false when it can't change (not hideable, or the last one shown). */\n    setColumnHidden(column: string, hidden: boolean) {\n        const header = this.headerCells.find((h) => h.columnKey === column);\n        if (!header || header.columnHidden === hidden || this.isColumnLocked(column)) return false;\n        header.columnHidden = hidden;\n        this.afterColumnsChange(column, hidden);\n        return true;\n    }\n\n    /** Columns were shown or hidden since the markup (Reset has something to do). */\n    get columnsChanged() {\n        const initial = this.initialHidden ?? [];\n        const hidden = this.hiddenColumns;\n        return hidden.length !== initial.length || hidden.some((key) => !initial.includes(key));\n    }\n\n    /** Back to the columns hidden in the markup. */\n    resetColumns() {\n        const initial = new Set(this.initialHidden ?? []);\n        for (const header of this.headerCells) header.columnHidden = initial.has(header.columnKey);\n        this.afterColumnsChange('', false);\n    }\n\n    private afterColumnsChange(column: string, hidden: boolean) {\n        this.syncColumns();\n        this.applySearch(); // the search skips hidden columns\n        const detail: TableColumnsChangeDetail = { hiddenColumns: this.hiddenColumns, column, hidden };\n        this.dispatchEvent(new CustomEvent('ui-table-columns-change', { detail, bubbles: true, composed: true }));\n    }\n\n    /**\n     * The first resize freezes the automatic layout: every shown column keeps its width, a filler cell takes the rest\n     * of the row (none in a static-width table, which ends at its columns).\n     */\n    freezeColumns() {\n        const body = this.body;\n        this.style.setProperty('--_resize-guide', `${body?.getBoundingClientRect().height ?? 0}px`);\n        if (this.dataset.fixed !== undefined) return;\n        for (const header of this.headerCells) header.width ??= header.columnHidden ? undefined : Math.floor(header.getBoundingClientRect().width);\n        this.dataset.fixed = '';\n        this.syncColumns();\n    }\n\n    /** The widths given or resized, by column. */\n    get columnWidths(): Record<string, number> {\n        const widths: Record<string, number> = {};\n        for (const header of this.headerCells) if (header.width !== undefined) widths[header.columnKey] = header.width;\n        return widths;\n    }\n\n    /** Built-in paging: the rows the search shows, one page of them on screen; the pagination and select-all follow. */\n    private syncPaging() {\n        const shown = this.rows.filter((row) => !row.filtered);\n        const size = this.pageSize;\n        const pages = pageCount(shown.length, size);\n        const page = Math.min(Math.max(1, this.page), pages);\n        const start = (page - 1) * size;\n        shown.forEach((row, index) => {\n            row.pagedOut = size > 0 && (index < start || index >= start + size);\n        });\n        for (const row of this.rows) {\n            if (row.filtered) row.pagedOut = false;\n            const next = row.nextElementSibling;\n            if (next?.localName === 'ui-table-expanded-row') (next as UiTableExpandedRow).pagedOut = row.pagedOut;\n        }\n        this.body?.updateZebra();\n        this.grid.sync();\n        this.syncTotal(shown);\n        this.syncSelection();\n        this.requestUpdate();\n    }\n\n    /** With paging, \"Select all (N)\" offers every row the search shows (unless the author set the count). */\n    private syncTotal(shown: UiTableRow[]) {\n        const batch = this.batchActions;\n        if (!batch) return;\n        const own = this.pageSize > 0 && (this.ownsTotal || !batch.hasAttribute('total-rows-count'));\n        if (own) batch.totalRowsCount = shown.filter((row) => !row.disabled).length;\n        else if (this.ownsTotal) batch.totalRowsCount = 0;\n        this.ownsTotal = own;\n    }\n\n    private readonly onPageChange = (event: CustomEvent<PaginationChangeDetail>) => {\n        event.stopPropagation();\n        this.page = event.detail.page;\n        this.pageSize = event.detail.pageSize;\n        const detail: TablePageChangeDetail = { page: this.page, pageSize: this.pageSize };\n        this.dispatchEvent(new CustomEvent('ui-table-page-change', { detail, bubbles: true, composed: true }));\n    };\n\n    /** The table's own \"Select all (N)\": choose every row the search shows, on every page. */\n    private readonly onSelectAllPages = (event: Event) => {\n        if (!this.ownsTotal || (event.target as Element).closest('ui-table') !== this) return;\n        for (const row of this.rows) if (!row.filtered && !row.disabled) row.selected = true;\n        this.syncSelection();\n        const detail: TableAllSelectedDetail = { selectedRows: this.selectedRows };\n        this.dispatchEvent(new CustomEvent('ui-table-row-all-selected', { detail, bubbles: true, composed: true }));\n    };\n\n    private renderPagination() {\n        if (this.pageSize <= 0) return nothing;\n        const sizes: Record<TableSize, PaginationSize> = { xs: 'sm', sm: 'sm', md: 'md', lg: 'lg', xl: 'lg' };\n        const total = isServer ? 0 : this.rows.filter((row) => !row.filtered).length; // the rows count once they're in a DOM\n        return html`<ui-pagination\n            part=\"pagination\"\n            size=${sizes[this.size]}\n            .page=${Math.min(Math.max(1, this.page), pageCount(total, this.pageSize))}\n            .pageSize=${this.pageSize}\n            .pageSizes=${this.pageSizes}\n            .totalItems=${total}\n            @ui-change=${this.onPageChange}\n        ></ui-pagination>`;\n    }\n\n    /** The header's select-all, the radios' Tab stop and the batch actions follow the chosen rows. */\n    private syncSelection() {\n        const rows = this.rows;\n        const chosen = rows.filter((row) => row.selected);\n        const reachable = this.selectableRows;\n        const header = this.headerRow;\n        if (header) {\n            const chosenReachable = reachable.filter((row) => row.selected).length;\n            header.selected = chosen.length > 0;\n            header.indeterminate = chosenReachable > 0 && chosenReachable < reachable.length;\n            header.disabled = reachable.length === 0;\n        }\n        if (this.radio) {\n            const stop = reachable.find((row) => row.selected) ?? reachable[0];\n            for (const row of rows) row.tabStop = !this.grid.on && row === stop; // a grid keeps its own Tab stop\n        }\n        const active = !this.radio && chosen.length > 0;\n        const batch = this.batchActions;\n        if (batch) {\n            batch.active = active;\n            batch.selectedRowsCount = chosen.length;\n        }\n        const content = this.toolbarContent;\n        if (content) content.hasBatchActions = active && !!batch;\n    }\n\n    /** After every listener ran (a canceled event leaves things to whoever canceled it). */\n    private afterListeners(event: Event, then: () => void) {\n        queueMicrotask(() => {\n            if (!event.defaultPrevented) then();\n        });\n    }\n\n    private readonly onRowSelection = (event: Event) => {\n        const row = event.target as UiTableRow;\n        if (row.closest('ui-table') !== this) return;\n        this.afterListeners(event, () => {\n            if (this.radio) for (const other of this.rows) if (other !== row) other.selected = false;\n            this.syncSelection();\n            const detail: TableRowSelectedDetail = { selectedRow: row, selectedRows: this.selectedRows };\n            this.dispatchEvent(new CustomEvent('ui-table-row-selected', { detail, bubbles: true, composed: true }));\n        });\n    };\n\n    /** Choose or release every row the search shows (disabled rows keep their state). */\n    private selectAll(selected: boolean) {\n        for (const row of this.selectableRows) row.selected = selected;\n        if (!selected) for (const row of this.rows) if (!row.disabled) row.selected = false;\n        this.syncSelection();\n        const detail: TableAllSelectedDetail = { selectedRows: this.selectedRows };\n        this.dispatchEvent(new CustomEvent('ui-table-row-all-selected', { detail, bubbles: true, composed: true }));\n    }\n\n    private readonly onSelectAll = (event: Event) => {\n        if ((event.target as Element).closest('ui-table') !== this) return;\n        const { selected } = (event as CustomEvent<TableSelectionDetail>).detail;\n        this.afterListeners(event, () => this.selectAll(selected));\n    };\n\n    /** Cancel releases every row; focus goes to select-all, as out of a closing dialog (the bar it was in goes inert). */\n    private readonly onCancel = (event: Event) => {\n        if ((event.target as Element).closest('ui-table') !== this) return;\n        for (const row of this.rows) row.selected = false;\n        this.selectAll(false);\n        this.headerRow?.focusSelection();\n    };\n\n    /** Arrow keys on a radio: the next (or previous) reachable row is chosen and focused, wrapping around. */\n    private readonly onRadioMove = (event: Event) => {\n        const from = event.target as UiTableRow;\n        const rows = this.selectableRows;\n        if (!rows.length) return;\n        const { delta } = (event as CustomEvent<{ delta: number }>).detail;\n        const target = rows[(rows.indexOf(from) + delta + rows.length) % rows.length];\n        const detail: TableSelectionDetail = { selected: true };\n        const allowed = target.dispatchEvent(new CustomEvent('ui-table-row-change-selection', { detail, bubbles: true, composed: true, cancelable: true }));\n        if (allowed) target.selected = true;\n        void target.updateComplete.then(() => target.focusSelection());\n    };\n\n    /** The header's chevron opens or closes every row; a row's keeps the header's in step. */\n    private readonly onExpando = (event: Event) => {\n        const source = event.target as Element;\n        if (source.closest('ui-table') !== this) return;\n        const { expanded } = (event as CustomEvent<TableExpandoDetail>).detail;\n        const header = this.headerRow;\n        const expandable = this.rows.filter((row) => row.expandable);\n        if (source === header) for (const row of expandable) row.expanded = expanded;\n        else if (header) header.expanded = expandable.length > 0 && expandable.every((row) => row.expanded);\n    };\n\n    /** The search text (the toolbar search's). */\n    private searchValue = '';\n\n    /** The toolbar search changed: leave out the rows whose text (or their expanded row's) doesn't contain it. */\n    private readonly onSearch = (event: Event) => {\n        const search = event.target as UiTableToolbarSearch;\n        if (search.localName !== 'ui-table-toolbar-search' || search.closest('ui-table') !== this) return;\n        if (event.type === 'input') event.stopPropagation(); // the search is the table's: no stray page-level input\n        if (search.value === this.searchValue) return;\n        this.searchValue = search.value;\n        this.page = 1;\n        const unfilteredRows = this.applySearch();\n        const detail: TableFilteredDetail = { unfilteredRows };\n        this.dispatchEvent(new CustomEvent('ui-table-filtered', { detail, bubbles: true, composed: true }));\n    };\n\n    /** A row's text for the search: its shown cells (hidden columns don't count). */\n    private rowText(row: UiTableRow) {\n        return [...row.querySelectorAll<UiTableCell>(':scope > ui-table-cell')]\n            .filter((cell) => !cell.columnHidden)\n            .map((cell) => cell.textContent?.trim() ?? '')\n            .join(' ');\n    }\n\n    /** Marks the rows the search leaves out; returns the rest. */\n    private applySearch() {\n        const value = this.searchValue;\n        const unfilteredRows: UiTableRow[] = [];\n        for (const row of this.rows) {\n            const expanded = row.nextElementSibling?.localName === 'ui-table-expanded-row' ? (row.nextElementSibling as UiTableExpandedRow) : null;\n            let filtered = value !== '' && this.filterRows(this.rowText(row), value);\n            if (filtered && expanded) filtered = this.filterRows(expanded.textContent?.trim() ?? '', value);\n            row.filtered = filtered;\n            if (expanded) expanded.filtered = filtered;\n            if (!filtered) unfilteredRows.push(row);\n        }\n        this.syncPaging();\n        return unfilteredRows;\n    }\n\n    private syncBody() {\n        const body = this.body;\n        if (body) body.useZebraStyles = this.useZebraStyles;\n    }\n\n    private syncHeaders() {\n        for (const cell of this.headerCells) {\n            if (this.isSortable || cell.isSortable) cell.isSortable = this.isSortable;\n            if (this.resizable || cell.resizable) cell.resizable = this.resizable;\n        }\n    }\n\n    /** Rows came, went or moved: while nothing is sorted, their order is the one none restores. */\n    private readonly onContentChange = (event: Event) => {\n        if (event.target !== this.body) return;\n        this.syncRows();\n        // rows added while a search is typed (live updates, load more) are searched too\n        if (this.searchValue !== '') this.applySearch();\n        if (this.sortedHeader) this.indexNewRows();\n        else {\n            this.nextIndex = 0;\n            for (const row of this.rows) this.order.set(row, this.nextIndex++);\n        }\n        // a header that came sorted (sort-direction in the markup) sorts the rows it finds\n        const sorted = this.sortedHeader;\n        if (sorted && !this.initiallySorted) {\n            this.initiallySorted = true;\n            this.sortRows(sorted, sorted.sortDirection!);\n        }\n    };\n\n    private indexNewRows() {\n        for (const row of this.rows) if (!this.order.has(row)) this.order.set(row, this.nextIndex++);\n    }\n\n    private readonly onSort = (event: Event) => {\n        const header = event.target;\n        if (!(header instanceof UiTableHeaderCell) || header.closest('ui-table') !== this) return;\n        const { sortDirection } = (event as CustomEvent<TableHeaderCellSortDetail>).detail;\n        // after every listener ran: a canceled event leaves the rows to whoever canceled it\n        queueMicrotask(() => {\n            this.initiallySorted = true; // from now on the rows' order is the sorter's: new rows don't re-sort them\n            if (event.defaultPrevented) return;\n            for (const cell of this.headerCells) if (cell !== header && cell.sortDirection && cell.sortDirection !== 'none') cell.sortDirection = 'none';\n            this.sortRows(header, sortDirection);\n            const detail: TableSortedDetail = { sortedHeader: header };\n            this.dispatchEvent(new CustomEvent('ui-table-sorted', { detail, bubbles: true, composed: true }));\n        });\n    };\n\n    /**\n     * Each body row with what follows it until the next row (an expanded row), and the text and comment nodes before\n     * it (whitespace, a framework's markers): they move with the row. Left behind they would pile up before the rows,\n     * and Chrome moves rows past such a pile slowly (3,000 rows: 90ms a sort instead of 12).\n     */\n    private rowGroups(body: Element) {\n        const lead: Node[] = [];\n        const groups: Node[][] = [];\n        let pending: Node[] = [];\n        for (const child of body.childNodes) {\n            if (!(child instanceof Element)) pending.push(child);\n            else if (child.localName === 'ui-table-row') groups.push([...pending, child]);\n            else if (groups.length) groups.at(-1)!.push(...pending, child);\n            else lead.push(...pending, child);\n            if (child instanceof Element) pending = [];\n        }\n        return { lead, groups, tail: pending };\n    }\n\n    /** The row a group of nodes is for. */\n    private rowOf(group: Node[]) {\n        return group.find((node): node is UiTableRow => node instanceof Element && node.localName === 'ui-table-row')!;\n    }\n\n    private sortRows(header: UiTableHeaderCell, direction: TableSortDirection) {\n        const body = this.body;\n        const column = this.headerCells.indexOf(header);\n        if (!body || column < 0) return;\n        this.indexNewRows();\n        const { lead, groups, tail } = this.rowGroups(body);\n        let ordered: Node[][];\n        if (direction === 'none') {\n            ordered = groups.toSorted((a, b) => (this.order.get(this.rowOf(a)) ?? 0) - (this.order.get(this.rowOf(b)) ?? 0));\n        } else {\n            const collator = new Intl.Collator(this.locale || this.localize.lang());\n            const factor = direction === 'ascending' ? 1 : -1;\n            const keyed = groups.map((group) => {\n                const cell = this.rowOf(group).querySelectorAll(':scope > ui-table-cell')[column];\n                return { group, key: cell?.getAttribute('sort-value') ?? cell?.textContent?.trim() ?? '' };\n            });\n            ordered = keyed.toSorted((a, b) => factor * this.customSortRow(a.key, b.key, collator)).map((k) => k.group);\n        }\n        this.reorder(body, [...lead, ...ordered.flat(), ...tail]);\n    }\n\n    /**\n     * Puts the body's children in `children` order. The body leaves the page meanwhile: WebKit reassigns a\n     * slot's nodes on every move, which makes moving rows inside it quadratic (1,000 rows: seconds).\n     */\n    private reorder(body: UiTableBody, children: Node[]) {\n        const focused = deepActiveElement();\n        const keepFocus = focused !== null && containsDeep(body, focused);\n        const content = this.renderRoot.querySelector<HTMLElement>('.content');\n        const scroll = { top: content?.scrollTop ?? 0, left: content?.scrollLeft ?? 0, x: scrollX, y: scrollY };\n        const parent = body.parentNode!;\n        const next = body.nextSibling;\n        body.remove();\n        body.append(...children);\n        if (next) next.before(body);\n        else parent.appendChild(body);\n        if (content) {\n            content.scrollTop = scroll.top;\n            content.scrollLeft = scroll.left;\n        }\n        if (keepFocus) focused.focus({ preventScroll: true });\n        if (scrollX !== scroll.x || scrollY !== scroll.y) scrollTo(scroll.x, scroll.y);\n        this.syncPaging(); // the pages follow the new order\n    }\n\n    /** The rows CSV takes: those the search shows (every page, in their order), the chosen ones, or all. */\n    csvRows(scope: TableCsvScope = 'shown'): UiTableRow[] {\n        if (scope === 'selected') return this.selectedRows;\n        if (scope === 'all') return this.rows;\n        return this.rows.filter((row) => !row.filtered);\n    }\n\n    /** The columns shown and the rows of `scope` as CSV (a cell writes its `csv-value`, else its text). */\n    toCsv({ scope = 'shown' }: { scope?: TableCsvScope } = {}): string {\n        const columns = this.headerCells.flatMap((header, index) => (header.columnHidden ? [] : [{ key: String(index), header: header.labelText }]));\n        const rows = this.csvRows(scope).map((row, index) => ({ id: String(index), cells: [...row.querySelectorAll(':scope > ui-table-cell')] }));\n        return buildCsv(columns, rows, (row, column) => csvValue(row.cells[Number(column.key)]));\n    }\n\n    /** Downloads `toCsv({ scope })` as `fileName` (default: the title, else \"table\"; `.csv` is added). */\n    downloadCsv({ scope = 'shown', fileName }: { scope?: TableCsvScope; fileName?: string } = {}) {\n        saveCsv(this.toCsv({ scope }), fileName ?? this.csvFileName);\n    }\n\n    /** The file name a CSV download takes by default: the title's text. */\n    get csvFileName() {\n        return this.querySelector(':scope > [slot=\"title\"]')?.textContent?.trim() ?? '';\n    }\n\n    /** Skeleton rows in the table's columns while `loading`. */\n    private renderLoading() {\n        if (!this.loading) return nothing;\n        const headers = isServer ? [] : this.headerCells.filter((header) => !header.columnHidden);\n        const shown = isServer ? 0 : this.rows.filter((row) => !row.filtered && !row.pagedOut).length;\n        const count = this.loadingRows || shown || this.pageSize || 5;\n        const blanks = (this.expandable ? 1 : 0) + (this.isSelectable || this.radio ? 1 : 0);\n        const cells = [...Array.from({ length: blanks }, () => loadingBlank), ...headers.map(() => loadingBar)];\n        if (hasData(this, 'fixed') && !this.useStaticWidth) cells.push(loadingBlank);\n        const rows = Array.from({ length: count }, () => cells);\n        return html`<div class=\"loading\" aria-hidden=\"true\">${rows.map((row) => this.renderLoadingRow(row))}</div>`;\n    }\n\n    private renderLoadingRow(cells: unknown[]) {\n        return html`<div class=\"loading-row\">${cells}</div>`;\n    }\n\n    /** No rows: the `empty` slot, or `no-results` while the search leaves none. */\n    private renderEmpty() {\n        if (this.loading || isServer || this.rows.some((row) => !row.filtered)) return nothing;\n        const t = this.localize.t.dataTable;\n        const message = this.searchValue === '' ? this.renderSlot('empty', t.noRows) : this.renderSlot('no-results', t.noResults);\n        return html`<div class=\"empty\" role=\"row\"><div class=\"empty-cell\" part=\"empty\" role=${this.grid.on ? 'gridcell' : 'cell'}>${message}</div></div>`;\n    }\n\n    private renderSlot(name: string, fallback: string) {\n        return html`<slot name=${name}>${fallback}</slot>`;\n    }\n\n    /**\n     * Focuses the table's first stop: the scroll box when it scrolls, else select-all, a sort button, the grid's\n     * Tab stop, or the first row's checkbox, radio or chevron.\n     */\n    override focus(options?: FocusOptions) {\n        const box = this.renderRoot.querySelector<HTMLElement>('.content[tabindex]');\n        const selectAll = this.headerRow?.renderRoot.querySelector<HTMLElement>('.select ui-checkbox');\n        const sortable = this.headerCells.find((header) => !header.columnHidden && header.sortDirection);\n        const row = this.rows.find((r) => !r.filtered && !r.pagedOut);\n        const rowControl = row?.renderRoot.querySelector<HTMLElement>('.select ui-checkbox, .select ui-radio[tabindex=\"0\"], .expand-button');\n        const target = box ?? selectAll ?? sortable ?? this.grid.stopCell ?? rowControl;\n        if (target) target.focus(options);\n        else super.focus(options);\n    }\n\n    /** The scroll box's name: the table's `aria-label`, else its title. */\n    private get regionLabel() {\n        if (isServer) return this.getAttribute('aria-label') ?? nothing;\n        return this.getAttribute('aria-label') || this.csvFileName || nothing;\n    }\n\n    override render() {\n        // a scrolling box must be reachable by keyboard (WCAG 2.1.1): sticky-header scrolls down, a wide table sideways\n        const scrolls = this.stickyHeader || this.scrollable;\n        return html`<div class=\"container\">\n            <div class=\"header\" part=\"header\" ?hidden=${!this.withHeader}>\n                <slot name=\"title\" @slotchange=${this.onHeaderSlotChange}></slot>\n                <slot name=\"description\" @slotchange=${this.onHeaderSlotChange}></slot>\n            </div>\n            <slot name=\"toolbar\" @slotchange=${this.onSlotChange}></slot>\n            <div class=\"content\" part=\"content\" tabindex=${scrolls ? '0' : nothing} role=${scrolls ? 'region' : nothing} aria-label=${scrolls ? this.regionLabel : nothing}><div class=\"table\" part=\"table\"><slot @slotchange=${this.onSlotChange}></slot>${this.renderLoading()}${this.renderEmpty()}</div></div>\n            ${this.renderPagination()}\n            <span class=\"sr-only\" role=\"status\">${this.announcement}</span>\n        </div>`;\n    }\n}\n\nexport interface UiTableEventMap extends HTMLElementEventMap {\n    /** From a header (it bubbles): listen on the table to sort the data yourself. */\n    'ui-table-header-cell-sort': CustomEvent<TableHeaderCellSortDetail>;\n    'ui-table-sorted': CustomEvent<TableSortedDetail>;\n    /** From a row (it bubbles), cancelable. */\n    'ui-table-row-change-selection': CustomEvent<TableSelectionDetail>;\n    /** From the header row (it bubbles), cancelable. */\n    'ui-table-change-selection-all': CustomEvent<TableSelectionDetail>;\n    'ui-table-row-selected': CustomEvent<TableRowSelectedDetail>;\n    'ui-table-row-all-selected': CustomEvent<TableAllSelectedDetail>;\n    /** From a row (it bubbles), cancelable. */\n    'ui-table-row-expando-beingtoggled': CustomEvent<TableExpandoDetail>;\n    'ui-table-row-expando-toggled': CustomEvent<TableExpandoDetail>;\n    'ui-table-filtered': CustomEvent<TableFilteredDetail>;\n    'ui-table-page-change': CustomEvent<TablePageChangeDetail>;\n    'ui-table-columns-change': CustomEvent<TableColumnsChangeDetail>;\n    /** From a cell (it bubbles), cancelable. */\n    'ui-table-cell-edit': CustomEvent<TableCellEditDetail>;\n    /** From the `<ui-table-csv-export>` (it bubbles), cancelable. */\n    'ui-table-csv-export': CustomEvent<TableCsvExportDetail>;\n    /** From a header (it bubbles). */\n    'ui-table-column-resize': CustomEvent<TableColumnResizeDetail>;\n}\n\n/** Typed listeners for UiTable's events (declaration merging with the class). */\nexport interface UiTable {\n    addEventListener<K extends keyof UiTableEventMap>(type: K, listener: (this: UiTable, event: UiTableEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiTableEventMap>(type: K, listener: (this: UiTable, event: UiTableEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-table': UiTable;\n    }\n}\n"
    }
  ]
}
