feat(data-table): support programmatic sorting (#1337)

* refactor(data-table): pass down sortable props instead of using context

* feat(data-table): support programmatic sorting

* test(data-table): assert new props

* docs(data-table): add "Programmatic sorting" example

* refactor(data-table): remove unused tableSortable store

* refactor(data-table): remove unused indices
This commit is contained in:
metonym 2022-06-05 13:37:50 -07:00 committed by GitHub
commit 72c24b83b2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 241 additions and 48 deletions

View file

@ -967,6 +967,8 @@ export interface DataTableCell {
| selectable | No | <code>let</code> | Yes | <code>boolean</code> | <code>false</code> | Set to `true` for the selectable variant<br />Automatically set to `true` if `radio` or `batchSelection` are `true` |
| expandedRowIds | No | <code>let</code> | Yes | <code>ReadonlyArray<DataTableRowId></code> | <code>[]</code> | Specify the row ids to be expanded |
| expandable | No | <code>let</code> | Yes | <code>boolean</code> | <code>false</code> | Set to `true` for the expandable variant<br />Automatically set to `true` if `batchExpansion` is `true` |
| sortDirection | No | <code>let</code> | Yes | <code>"none" &#124; "ascending" &#124; "descending"</code> | <code>"none"</code> | Specify the sort direction |
| sortKey | No | <code>let</code> | Yes | <code>DataTableKey</code> | <code>null</code> | Specify the header key to sort by |
| headers | No | <code>let</code> | No | <code>ReadonlyArray<DataTableHeader></code> | <code>[]</code> | Specify the data table headers |
| rows | No | <code>let</code> | No | <code>ReadonlyArray<DataTableRow></code> | <code>[]</code> | Specify the rows the data table should render<br />keys defined in `headers` are used for the row ids |
| size | No | <code>let</code> | No | <code>"compact" &#124; "short" &#124; "medium" &#124; "tall"</code> | <code>undefined</code> | Set the size of the data table |
@ -3864,12 +3866,14 @@ None.
### Props
| Prop name | Required | Kind | Reactive | Type | Default value | Description |
| :-------------- | :------- | :--------------- | :------- | ------------------------- | ------------------------------------------------ | ------------------------------------------------------ |
| disableSorting | No | <code>let</code> | No | <code>boolean</code> | <code>false</code> | Set to `true` to disable sorting on this specific cell |
| scope | No | <code>let</code> | No | <code>string</code> | <code>"col"</code> | Specify the `scope` attribute |
| translateWithId | No | <code>let</code> | No | <code>() => string</code> | <code>() => ""</code> | Override the default id translations |
| id | No | <code>let</code> | No | <code>string</code> | <code>"ccs-" + Math.random().toString(36)</code> | Set an id for the top-level element |
| Prop name | Required | Kind | Reactive | Type | Default value | Description |
| :-------------- | :------- | :--------------- | :------- | ---------------------------------------------------------- | ------------------------------------------------ | -------------------------------------- |
| sortable | No | <code>let</code> | No | <code>boolean</code> | <code>false</code> | Set to `true` for the sortable variant |
| sortDirection | No | <code>let</code> | No | <code>"none" &#124; "ascending" &#124; "descending"</code> | <code>"none"</code> | Specify the sort direction |
| active | No | <code>let</code> | No | <code>boolean</code> | <code>false</code> | Set to `true` if the column sorting |
| scope | No | <code>let</code> | No | <code>string</code> | <code>"col"</code> | Specify the `scope` attribute |
| translateWithId | No | <code>let</code> | No | <code>() => string</code> | <code>() => ""</code> | Override the default id translations |
| id | No | <code>let</code> | No | <code>string</code> | <code>"ccs-" + Math.random().toString(36)</code> | Set an id for the top-level element |
### Slots

View file

@ -2421,6 +2421,30 @@
"constant": false,
"reactive": false
},
{
"name": "sortKey",
"kind": "let",
"description": "Specify the header key to sort by",
"type": "DataTableKey",
"value": "null",
"isFunction": false,
"isFunctionDeclaration": false,
"isRequired": false,
"constant": false,
"reactive": true
},
{
"name": "sortDirection",
"kind": "let",
"description": "Specify the sort direction",
"type": "\"none\" | \"ascending\" | \"descending\"",
"value": "\"none\"",
"isFunction": false,
"isFunctionDeclaration": false,
"isRequired": false,
"constant": false,
"reactive": true
},
{
"name": "expandable",
"kind": "let",
@ -11843,9 +11867,33 @@
"filePath": "src/DataTable/TableHeader.svelte",
"props": [
{
"name": "disableSorting",
"name": "sortable",
"kind": "let",
"description": "Set to `true` to disable sorting on this specific cell",
"description": "Set to `true` for the sortable variant",
"type": "boolean",
"value": "false",
"isFunction": false,
"isFunctionDeclaration": false,
"isRequired": false,
"constant": false,
"reactive": false
},
{
"name": "sortDirection",
"kind": "let",
"description": "Specify the sort direction",
"type": "\"none\" | \"ascending\" | \"descending\"",
"value": "\"none\"",
"isFunction": false,
"isFunctionDeclaration": false,
"isRequired": false,
"constant": false,
"reactive": false
},
{
"name": "active",
"kind": "let",
"description": "Set to `true` if the column sorting",
"type": "boolean",
"value": "false",
"isFunction": false,

View file

@ -1075,6 +1075,18 @@ and then limit displayed content by using `pageSize` and `page` props, which are
]}"
/>
### Programmatic sorting
Use the reactive `sortKey` and `sortDirection` props for programmatic sorting.
By default, the table is not sorted by a specific key. The `sortKey` value must be a valid `key` specified in the `headers` object.
Possible values for `sortDirection` include `"none"` or `"ascending"` or `"descending"`.
Setting `sortKey` to `null` and `sortDirection` to `"none"` should reset the table rows to their initial order.
<FileSource src="/framed/DataTable/DataTableProgrammaticSorting" />
### Empty column with overflow menu
Some use cases require an empty column in the table body without a corresponding table header.

View file

@ -0,0 +1,97 @@
<script>
import { DataTable, Button } from "carbon-components-svelte";
let sortKey = "port";
let sortDirection = "ascending";
$: console.log("sortKey", sortKey);
$: console.log("sortDirection", sortDirection);
</script>
<Button
kind="tertiary"
disabled="{sortKey === 'port' && sortDirection === 'ascending'}"
on:click="{() => {
sortKey = 'port';
sortDirection = 'ascending';
}}"
>
Sort "port" in ascending order
</Button>
<Button
kind="tertiary"
disabled="{sortKey === 'name' && sortDirection === 'descending'}"
on:click="{() => {
sortKey = 'name';
sortDirection = 'descending';
}}"
>
Sort "name" in descending order
</Button>
<Button
kind="ghost"
on:click="{() => {
sortKey = null;
sortDirection = 'none';
}}"
>
Clear sorting
</Button>
<DataTable
sortable
bind:sortKey
bind:sortDirection
headers="{[
{ key: 'name', value: 'Name' },
{ key: 'protocol', value: 'Protocol', sort: false },
{ key: 'port', value: 'Port' },
{ key: 'rule', value: 'Rule' },
]}"
rows="{[
{
id: 'a',
name: 'Load Balancer 3',
protocol: 'HTTP',
port: 3000,
rule: 'Round robin',
},
{
id: 'b',
name: 'Load Balancer 1',
protocol: 'HTTP',
port: 443,
rule: 'Round robin',
},
{
id: 'c',
name: 'Load Balancer 2',
protocol: 'HTTP',
port: 80,
rule: 'DNS delegation',
},
{
id: 'd',
name: 'Load Balancer 6',
protocol: 'HTTP',
port: 3000,
rule: 'Round robin',
},
{
id: 'e',
name: 'Load Balancer 4',
protocol: 'HTTP',
port: 443,
rule: 'Round robin',
},
{
id: 'f',
name: 'Load Balancer 5',
protocol: 'HTTP',
port: 80,
rule: 'DNS delegation',
},
]}"
/>

View file

@ -53,6 +53,18 @@
/** Set to `true` for the sortable variant */
export let sortable = false;
/**
* Specify the header key to sort by
* @type {DataTableKey}
*/
export let sortKey = null;
/**
* Specify the sort direction
* @type {"none" | "ascending" | "descending"}
*/
export let sortDirection = "none";
/**
* Set to `true` for the expandable variant
* Automatically set to `true` if `batchExpansion` is `true`
@ -132,18 +144,11 @@
};
const dispatch = createEventDispatcher();
const batchSelectedIds = writable(false);
const tableSortable = writable(sortable);
const sortHeader = writable({
id: null,
key: null,
sort: undefined,
sortDirection: "none",
});
const headerItems = writable([]);
const tableRows = writable(rows);
const thKeys = derived(headerItems, () =>
headers
.map(({ key }, i) => ({ key, id: key }))
.map(({ key }) => ({ key, id: key }))
.reduce((a, c) => ({ ...a, [c.key]: c.id }), {})
);
const resolvePath = (object, path) => {
@ -155,8 +160,6 @@
};
setContext("DataTable", {
sortHeader,
tableSortable,
batchSelectedIds,
tableRows,
resetSelectedRowIds: () => {
@ -195,7 +198,6 @@
expanded = expandedRowIds.length === expandableRowIds.length;
}
$: if (radio || batchSelection) selectable = true;
$: tableSortable.set(sortable);
$: headerKeys = headers.map(({ key }) => key);
$: tableCellsByRowId = rows.reduce(
(rows, row) => ({
@ -210,11 +212,11 @@
);
$: $tableRows = rows;
$: sortedRows = [...$tableRows];
$: ascending = $sortHeader.sortDirection === "ascending";
$: sortKey = $sortHeader.key;
$: ascending = sortDirection === "ascending";
$: sorting = sortable && sortKey != null;
$: sortingHeader = headers.find((header) => header.key === sortKey);
$: if (sorting) {
if ($sortHeader.sortDirection === "none") {
if (sortDirection === "none") {
sortedRows = $tableRows;
} else {
sortedRows = [...$tableRows].sort((a, b) => {
@ -225,7 +227,7 @@
? resolvePath(b, sortKey)
: resolvePath(a, sortKey);
if ($sortHeader.sort) return $sortHeader.sort(itemA, itemB);
if (sortingHeader?.sort) return sortingHeader.sort(itemA, itemB);
if (typeof itemA === "number" && typeof itemB === "number")
return itemA - itemB;
@ -337,32 +339,26 @@
/>
</th>
{/if}
{#each headers as header, i (header.key)}
{#each headers as header (header.key)}
{#if header.empty}
<th scope="col" style="{formatHeaderWidth(header)}"></th>
{:else}
<TableHeader
id="{header.key}"
style="{formatHeaderWidth(header)}"
disableSorting="{header.sort === false}"
sortable="{sortable && header.sort !== false}"
sortDirection="{sortDirection}"
active="{sortKey !== null && sortKey === header.key}"
on:click="{() => {
dispatch('click', { header });
if (header.sort === false) {
dispatch('click:header', { header });
} else {
let active = header.key === $sortHeader.key;
let currentSortDirection = active
? $sortHeader.sortDirection
: 'none';
let sortDirection = sortDirectionMap[currentSortDirection];
sortDirection = sortDirectionMap[sortDirection];
sortKey =
sortDirection === 'none' ? null : $thKeys[header.key];
dispatch('click:header', { header, sortDirection });
sortHeader.set({
id: sortDirection === 'none' ? null : $thKeys[header.key],
key: header.key,
sort: header.sort,
sortDirection,
});
}
}}"
>

View file

@ -1,6 +1,15 @@
<script>
/** Set to `true` to disable sorting on this specific cell */
export let disableSorting = false;
/** Set to `true` for the sortable variant */
export let sortable = false;
/**
* Specify the sort direction
* @type {"none" | "ascending" | "descending"}
*/
export let sortDirection = "none";
/** Set to `true` if the column sorting */
export let active = false;
/** Specify the `scope` attribute */
export let scope = "col";
@ -14,21 +23,17 @@
/** Set an id for the top-level element */
export let id = "ccs-" + Math.random().toString(36);
import { getContext } from "svelte";
import ArrowUp from "../icons/ArrowUp.svelte";
import ArrowsVertical from "../icons/ArrowsVertical.svelte";
const { sortHeader, tableSortable } = getContext("DataTable");
$: active = $sortHeader.id === id;
// TODO: translate with id
$: ariaLabel = translateWithId();
</script>
<!-- svelte-ignore a11y-mouse-events-have-key-events -->
{#if $tableSortable && !disableSorting}
{#if sortable}
<th
aria-sort="{active ? $sortHeader.sortDirection : 'none'}"
aria-sort="{active ? sortDirection : 'none'}"
scope="{scope}"
data-header="{id}"
{...$$restProps}
@ -40,7 +45,7 @@
class:bx--table-sort="{true}"
class:bx--table-sort--active="{active}"
class:bx--table-sort--ascending="{active &&
$sortHeader.sortDirection === 'descending'}"
sortDirection === 'descending'}"
on:click
>
<div class:bx--table-header-label="{true}">

View file

@ -70,7 +70,14 @@
}
</script>
<DataTable headers="{headers}" rows="{rows}" style="" class="class" />
<DataTable
headers="{headers}"
rows="{rows}"
style=""
sortKey="name"
sortDirection="descending"
class="class"
/>
<DataTable headers="{headers}" rows="{rows}">
<span slot="cell-header" let:header>

View file

@ -85,6 +85,18 @@ export interface DataTableProps
*/
sortable?: boolean;
/**
* Specify the header key to sort by
* @default null
*/
sortKey?: DataTableKey;
/**
* Specify the sort direction
* @default "none"
*/
sortDirection?: "none" | "ascending" | "descending";
/**
* Set to `true` for the expandable variant
* Automatically set to `true` if `batchExpansion` is `true`

View file

@ -4,10 +4,22 @@ import type { SvelteComponentTyped } from "svelte";
export interface TableHeaderProps
extends svelte.JSX.HTMLAttributes<HTMLElementTagNameMap["th"]> {
/**
* Set to `true` to disable sorting on this specific cell
* Set to `true` for the sortable variant
* @default false
*/
disableSorting?: boolean;
sortable?: boolean;
/**
* Specify the sort direction
* @default "none"
*/
sortDirection?: "none" | "ascending" | "descending";
/**
* Set to `true` if the column sorting
* @default false
*/
active?: boolean;
/**
* Specify the `scope` attribute