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` | | 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 | | 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` | | 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 | | 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 | | 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 | | 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 |
@ -3865,8 +3867,10 @@ None.
### Props ### Props
| Prop name | Required | Kind | Reactive | Type | Default value | Description | | 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 | | 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 | | 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 | | 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 | | id | No | <code>let</code> | No | <code>string</code> | <code>"ccs-" + Math.random().toString(36)</code> | Set an id for the top-level element |

View file

@ -2421,6 +2421,30 @@
"constant": false, "constant": false,
"reactive": 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", "name": "expandable",
"kind": "let", "kind": "let",
@ -11843,9 +11867,33 @@
"filePath": "src/DataTable/TableHeader.svelte", "filePath": "src/DataTable/TableHeader.svelte",
"props": [ "props": [
{ {
"name": "disableSorting", "name": "sortable",
"kind": "let", "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", "type": "boolean",
"value": "false", "value": "false",
"isFunction": 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 ### Empty column with overflow menu
Some use cases require an empty column in the table body without a corresponding table header. 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 */ /** Set to `true` for the sortable variant */
export let sortable = false; 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 * Set to `true` for the expandable variant
* Automatically set to `true` if `batchExpansion` is `true` * Automatically set to `true` if `batchExpansion` is `true`
@ -132,18 +144,11 @@
}; };
const dispatch = createEventDispatcher(); const dispatch = createEventDispatcher();
const batchSelectedIds = writable(false); const batchSelectedIds = writable(false);
const tableSortable = writable(sortable);
const sortHeader = writable({
id: null,
key: null,
sort: undefined,
sortDirection: "none",
});
const headerItems = writable([]); const headerItems = writable([]);
const tableRows = writable(rows); const tableRows = writable(rows);
const thKeys = derived(headerItems, () => const thKeys = derived(headerItems, () =>
headers headers
.map(({ key }, i) => ({ key, id: key })) .map(({ key }) => ({ key, id: key }))
.reduce((a, c) => ({ ...a, [c.key]: c.id }), {}) .reduce((a, c) => ({ ...a, [c.key]: c.id }), {})
); );
const resolvePath = (object, path) => { const resolvePath = (object, path) => {
@ -155,8 +160,6 @@
}; };
setContext("DataTable", { setContext("DataTable", {
sortHeader,
tableSortable,
batchSelectedIds, batchSelectedIds,
tableRows, tableRows,
resetSelectedRowIds: () => { resetSelectedRowIds: () => {
@ -195,7 +198,6 @@
expanded = expandedRowIds.length === expandableRowIds.length; expanded = expandedRowIds.length === expandableRowIds.length;
} }
$: if (radio || batchSelection) selectable = true; $: if (radio || batchSelection) selectable = true;
$: tableSortable.set(sortable);
$: headerKeys = headers.map(({ key }) => key); $: headerKeys = headers.map(({ key }) => key);
$: tableCellsByRowId = rows.reduce( $: tableCellsByRowId = rows.reduce(
(rows, row) => ({ (rows, row) => ({
@ -210,11 +212,11 @@
); );
$: $tableRows = rows; $: $tableRows = rows;
$: sortedRows = [...$tableRows]; $: sortedRows = [...$tableRows];
$: ascending = $sortHeader.sortDirection === "ascending"; $: ascending = sortDirection === "ascending";
$: sortKey = $sortHeader.key;
$: sorting = sortable && sortKey != null; $: sorting = sortable && sortKey != null;
$: sortingHeader = headers.find((header) => header.key === sortKey);
$: if (sorting) { $: if (sorting) {
if ($sortHeader.sortDirection === "none") { if (sortDirection === "none") {
sortedRows = $tableRows; sortedRows = $tableRows;
} else { } else {
sortedRows = [...$tableRows].sort((a, b) => { sortedRows = [...$tableRows].sort((a, b) => {
@ -225,7 +227,7 @@
? resolvePath(b, sortKey) ? resolvePath(b, sortKey)
: resolvePath(a, 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") if (typeof itemA === "number" && typeof itemB === "number")
return itemA - itemB; return itemA - itemB;
@ -337,32 +339,26 @@
/> />
</th> </th>
{/if} {/if}
{#each headers as header, i (header.key)} {#each headers as header (header.key)}
{#if header.empty} {#if header.empty}
<th scope="col" style="{formatHeaderWidth(header)}"></th> <th scope="col" style="{formatHeaderWidth(header)}"></th>
{:else} {:else}
<TableHeader <TableHeader
id="{header.key}" id="{header.key}"
style="{formatHeaderWidth(header)}" style="{formatHeaderWidth(header)}"
disableSorting="{header.sort === false}" sortable="{sortable && header.sort !== false}"
sortDirection="{sortDirection}"
active="{sortKey !== null && sortKey === header.key}"
on:click="{() => { on:click="{() => {
dispatch('click', { header }); dispatch('click', { header });
if (header.sort === false) { if (header.sort === false) {
dispatch('click:header', { header }); dispatch('click:header', { header });
} else { } else {
let active = header.key === $sortHeader.key; sortDirection = sortDirectionMap[sortDirection];
let currentSortDirection = active sortKey =
? $sortHeader.sortDirection sortDirection === 'none' ? null : $thKeys[header.key];
: 'none';
let sortDirection = sortDirectionMap[currentSortDirection];
dispatch('click:header', { header, sortDirection }); 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> <script>
/** Set to `true` to disable sorting on this specific cell */ /** Set to `true` for the sortable variant */
export let disableSorting = false; 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 */ /** Specify the `scope` attribute */
export let scope = "col"; export let scope = "col";
@ -14,21 +23,17 @@
/** Set an id for the top-level element */ /** Set an id for the top-level element */
export let id = "ccs-" + Math.random().toString(36); export let id = "ccs-" + Math.random().toString(36);
import { getContext } from "svelte";
import ArrowUp from "../icons/ArrowUp.svelte"; import ArrowUp from "../icons/ArrowUp.svelte";
import ArrowsVertical from "../icons/ArrowsVertical.svelte"; import ArrowsVertical from "../icons/ArrowsVertical.svelte";
const { sortHeader, tableSortable } = getContext("DataTable");
$: active = $sortHeader.id === id;
// TODO: translate with id // TODO: translate with id
$: ariaLabel = translateWithId(); $: ariaLabel = translateWithId();
</script> </script>
<!-- svelte-ignore a11y-mouse-events-have-key-events --> <!-- svelte-ignore a11y-mouse-events-have-key-events -->
{#if $tableSortable && !disableSorting} {#if sortable}
<th <th
aria-sort="{active ? $sortHeader.sortDirection : 'none'}" aria-sort="{active ? sortDirection : 'none'}"
scope="{scope}" scope="{scope}"
data-header="{id}" data-header="{id}"
{...$$restProps} {...$$restProps}
@ -40,7 +45,7 @@
class:bx--table-sort="{true}" class:bx--table-sort="{true}"
class:bx--table-sort--active="{active}" class:bx--table-sort--active="{active}"
class:bx--table-sort--ascending="{active && class:bx--table-sort--ascending="{active &&
$sortHeader.sortDirection === 'descending'}" sortDirection === 'descending'}"
on:click on:click
> >
<div class:bx--table-header-label="{true}"> <div class:bx--table-header-label="{true}">

View file

@ -70,7 +70,14 @@
} }
</script> </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}"> <DataTable headers="{headers}" rows="{rows}">
<span slot="cell-header" let:header> <span slot="cell-header" let:header>

View file

@ -85,6 +85,18 @@ export interface DataTableProps
*/ */
sortable?: boolean; 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 * Set to `true` for the expandable variant
* Automatically set to `true` if `batchExpansion` is `true` * Automatically set to `true` if `batchExpansion` is `true`

View file

@ -4,10 +4,22 @@ import type { SvelteComponentTyped } from "svelte";
export interface TableHeaderProps export interface TableHeaderProps
extends svelte.JSX.HTMLAttributes<HTMLElementTagNameMap["th"]> { 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 * @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 * Specify the `scope` attribute