-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(lit-table): dynamic data updates in the Lit Table Adapter (#5884)
* this fixes an issue I discussed in discord where with the lit table adapter, updating a data array did not get reflected by the table. It is a one-line change to the TableController, and a new example that demonstrates the difference. * Update packages/lit-table/src/index.ts per suggestion from @kadoshms Co-authored-by: Mor Kadosh <[email protected]> --------- Co-authored-by: Luke Schierer <[email protected]> Co-authored-by: Mor Kadosh <[email protected]>
- Loading branch information
1 parent
190c669
commit 9763877
Showing
9 changed files
with
375 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
node_modules | ||
.DS_Store | ||
dist | ||
dist-ssr | ||
*.local |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
# Example | ||
|
||
To run this example: | ||
|
||
- `npm install` or `yarn` | ||
- `npm run start` or `yarn start` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<!doctype html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8" /> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
<title>Vite App</title> | ||
<script type="module" src="https://cdn.skypack.dev/twind/shim"></script> | ||
</head> | ||
<body> | ||
<div id="root"></div> | ||
<script type="module" src="/src/main.ts"></script> | ||
<lit-table-example></lit-table-example> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
{ | ||
"name": "tanstack-lit-table-example-sorting-dynamic-data", | ||
"version": "0.0.0", | ||
"private": true, | ||
"scripts": { | ||
"dev": "vite", | ||
"build": "vite build", | ||
"serve": "vite preview", | ||
"start": "vite" | ||
}, | ||
"dependencies": { | ||
"@faker-js/faker": "^8.4.1", | ||
"@tanstack/lit-table": "^8.20.5", | ||
"lit": "^3.1.4" | ||
}, | ||
"devDependencies": { | ||
"@rollup/plugin-replace": "^5.0.7", | ||
"typescript": "5.4.5", | ||
"vite": "^5.3.2" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,235 @@ | ||
import { customElement } from 'lit/decorators.js' | ||
import { html, LitElement, PropertyValueMap } from 'lit' | ||
import { repeat } from 'lit/directives/repeat.js' | ||
import { state } from 'lit/decorators/state.js' | ||
import { | ||
ColumnDef, | ||
flexRender, | ||
getCoreRowModel, | ||
getSortedRowModel, | ||
SortingFn, | ||
type SortingState, | ||
TableController, | ||
} from '@tanstack/lit-table' | ||
|
||
import { makeData, Person } from './makeData' | ||
|
||
const sortStatusFn: SortingFn<Person> = (rowA, rowB, _columnId) => { | ||
const statusA = rowA.original.status | ||
const statusB = rowB.original.status | ||
const statusOrder = ['single', 'complicated', 'relationship'] | ||
return statusOrder.indexOf(statusA) - statusOrder.indexOf(statusB) | ||
} | ||
|
||
const columns: ColumnDef<Person>[] = [ | ||
{ | ||
accessorKey: 'firstName', | ||
cell: info => info.getValue(), | ||
//this column will sort in ascending order by default since it is a string column | ||
}, | ||
{ | ||
accessorFn: row => row.lastName, | ||
id: 'lastName', | ||
cell: info => info.getValue(), | ||
header: () => html`<span>Last Name</span>`, | ||
sortUndefined: 'last', //force undefined values to the end | ||
sortDescFirst: false, //first sort order will be ascending (nullable values can mess up auto detection of sort order) | ||
}, | ||
{ | ||
accessorKey: 'age', | ||
header: () => 'Age', | ||
//this column will sort in descending order by default since it is a number column | ||
}, | ||
{ | ||
accessorKey: 'visits', | ||
header: () => html`<span>Visits</span>`, | ||
sortUndefined: 'last', //force undefined values to the end | ||
}, | ||
{ | ||
accessorKey: 'status', | ||
header: 'Status', | ||
sortingFn: sortStatusFn, //use our custom sorting function for this enum column | ||
}, | ||
{ | ||
accessorKey: 'progress', | ||
header: 'Profile Progress', | ||
// enableSorting: false, //disable sorting for this column | ||
}, | ||
{ | ||
accessorKey: 'rank', | ||
header: 'Rank', | ||
invertSorting: true, //invert the sorting order (golf score-like where smaller is better) | ||
}, | ||
{ | ||
accessorKey: 'createdAt', | ||
header: 'Created At', | ||
// sortingFn: 'datetime' //make sure table knows this is a datetime column (usually can detect if no null values) | ||
}, | ||
] | ||
|
||
const data: Person[] = makeData(1000) | ||
|
||
@customElement('lit-table-example') | ||
class LitTableExample extends LitElement { | ||
@state() | ||
private _sorting: SortingState = [] | ||
|
||
@state() | ||
private _multiplier: number = 1 | ||
|
||
@state() | ||
private _data: Person[] = new Array<Person>() | ||
|
||
private tableController = new TableController<Person>(this) | ||
|
||
constructor() { | ||
super() | ||
this._data = [...data] | ||
} | ||
|
||
protected willUpdate( | ||
_changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown> | ||
): void { | ||
super.willUpdate(_changedProperties) | ||
if (_changedProperties.has('_multiplier')) { | ||
const newData: Person[] = data.map(d => { | ||
const p: Person = { | ||
...d, | ||
visits: d.visits ? d.visits * this._multiplier : undefined, | ||
} | ||
return p | ||
}) | ||
this._data.length = 0 | ||
this._data = newData | ||
} | ||
} | ||
protected render() { | ||
const table = this.tableController.table({ | ||
columns, | ||
data: this._data, | ||
state: { | ||
sorting: this._sorting, | ||
}, | ||
onSortingChange: updaterOrValue => { | ||
if (typeof updaterOrValue === 'function') { | ||
this._sorting = updaterOrValue(this._sorting) | ||
} else { | ||
this._sorting = updaterOrValue | ||
} | ||
}, | ||
getSortedRowModel: getSortedRowModel(), | ||
getCoreRowModel: getCoreRowModel(), | ||
}) | ||
|
||
return html` | ||
<input | ||
type="number" | ||
min="1" | ||
max="100" | ||
id="multiplier" | ||
@change="${(e: Event) => { | ||
const inputElement = (e as CustomEvent).target as HTMLInputElement | ||
if (inputElement) { | ||
this._multiplier = +inputElement.value | ||
this.requestUpdate('_multiplier') | ||
} | ||
}}" | ||
/> | ||
<table> | ||
<thead> | ||
${repeat( | ||
table.getHeaderGroups(), | ||
headerGroup => headerGroup.id, | ||
headerGroup => html` | ||
<tr> | ||
${headerGroup.headers.map( | ||
header => html` | ||
<th colspan="${header.colSpan}"> | ||
${header.isPlaceholder | ||
? null | ||
: html`<div | ||
title=${header.column.getCanSort() | ||
? header.column.getNextSortingOrder() === 'asc' | ||
? 'Sort ascending' | ||
: header.column.getNextSortingOrder() === 'desc' | ||
? 'Sort descending' | ||
: 'Clear sort' | ||
: undefined} | ||
@click="${header.column.getToggleSortingHandler()}" | ||
style="cursor: ${header.column.getCanSort() | ||
? 'pointer' | ||
: 'not-allowed'}" | ||
> | ||
${flexRender( | ||
header.column.columnDef.header, | ||
header.getContext() | ||
)} | ||
${{ asc: ' 🔼', desc: ' 🔽' }[ | ||
header.column.getIsSorted() as string | ||
] ?? null} | ||
</div>`} | ||
</th> | ||
` | ||
)} | ||
</tr> | ||
` | ||
)} | ||
</thead> | ||
<tbody> | ||
${table | ||
.getRowModel() | ||
.rows.slice(0, 10) | ||
.map( | ||
row => html` | ||
<tr> | ||
${row | ||
.getVisibleCells() | ||
.map( | ||
cell => html` | ||
<td> | ||
${flexRender( | ||
cell.column.columnDef.cell, | ||
cell.getContext() | ||
)} | ||
</td> | ||
` | ||
)} | ||
</tr> | ||
` | ||
)} | ||
</tbody> | ||
</table> | ||
<pre>${JSON.stringify(this._sorting, null, 2)}</pre> | ||
<style> | ||
* { | ||
font-family: sans-serif; | ||
font-size: 14px; | ||
box-sizing: border-box; | ||
} | ||
table { | ||
border: 1px solid lightgray; | ||
border-collapse: collapse; | ||
} | ||
tbody { | ||
border-bottom: 1px solid lightgray; | ||
} | ||
th { | ||
border-bottom: 1px solid lightgray; | ||
border-right: 1px solid lightgray; | ||
padding: 2px 4px; | ||
} | ||
tfoot { | ||
color: gray; | ||
} | ||
tfoot th { | ||
font-weight: normal; | ||
} | ||
</style> | ||
` | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { faker } from '@faker-js/faker' | ||
|
||
export type Person = { | ||
firstName: string | ||
lastName: string | undefined | ||
age: number | ||
visits: number | undefined | ||
progress: number | ||
status: 'relationship' | 'complicated' | 'single' | ||
rank: number | ||
createdAt: Date | ||
subRows?: Person[] | ||
} | ||
|
||
const range = (len: number) => { | ||
const arr: number[] = [] | ||
for (let i = 0; i < len; i++) { | ||
arr.push(i) | ||
} | ||
return arr | ||
} | ||
|
||
const newPerson = (): Person => { | ||
return { | ||
firstName: faker.person.firstName(), | ||
lastName: Math.random() < 0.1 ? undefined : faker.person.lastName(), | ||
age: faker.number.int(40), | ||
visits: Math.random() < 0.1 ? undefined : faker.number.int(1000), | ||
progress: faker.number.int(100), | ||
createdAt: faker.date.anytime(), | ||
status: faker.helpers.shuffle<Person['status']>([ | ||
'relationship', | ||
'complicated', | ||
'single', | ||
])[0]!, | ||
rank: faker.number.int(100), | ||
} | ||
} | ||
|
||
export function makeData(...lens: number[]) { | ||
const makeDataLevel = (depth = 0): Person[] => { | ||
const len = lens[depth]! | ||
return range(len).map((_d): Person => { | ||
return { | ||
...newPerson(), | ||
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined, | ||
} | ||
}) | ||
} | ||
|
||
return makeDataLevel() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"compilerOptions": { | ||
"target": "ES2020", | ||
"lib": ["ES2020", "DOM", "DOM.Iterable"], | ||
"module": "ESNext", | ||
"skipLibCheck": true, | ||
|
||
/* Bundler mode */ | ||
"moduleResolution": "bundler", | ||
"allowImportingTsExtensions": true, | ||
"resolveJsonModule": true, | ||
"isolatedModules": true, | ||
"noEmit": true, | ||
"experimentalDecorators": true, | ||
"emitDecoratorMetadata": true, | ||
"useDefineForClassFields": false, | ||
|
||
/* Linting */ | ||
"strict": true, | ||
"noUnusedLocals": false, | ||
"noUnusedParameters": true, | ||
"noFallthroughCasesInSwitch": true | ||
}, | ||
"include": ["src"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import { defineConfig } from 'vite' | ||
import rollupReplace from '@rollup/plugin-replace' | ||
|
||
// https://vitejs.dev/config/ | ||
export default defineConfig({ | ||
plugins: [ | ||
rollupReplace({ | ||
preventAssignment: true, | ||
values: { | ||
__DEV__: JSON.stringify(true), | ||
'process.env.NODE_ENV': JSON.stringify('development'), | ||
}, | ||
}), | ||
], | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters