Skip to content

Commit 9763877

Browse files
lschiererLuke Schiererkadoshms
authored
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]>
1 parent 190c669 commit 9763877

File tree

9 files changed

+375
-0
lines changed

9 files changed

+375
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
node_modules
2+
.DS_Store
3+
dist
4+
dist-ssr
5+
*.local
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Example
2+
3+
To run this example:
4+
5+
- `npm install` or `yarn`
6+
- `npm run start` or `yarn start`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Vite App</title>
7+
<script type="module" src="https://cdn.skypack.dev/twind/shim"></script>
8+
</head>
9+
<body>
10+
<div id="root"></div>
11+
<script type="module" src="/src/main.ts"></script>
12+
<lit-table-example></lit-table-example>
13+
</body>
14+
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "tanstack-lit-table-example-sorting-dynamic-data",
3+
"version": "0.0.0",
4+
"private": true,
5+
"scripts": {
6+
"dev": "vite",
7+
"build": "vite build",
8+
"serve": "vite preview",
9+
"start": "vite"
10+
},
11+
"dependencies": {
12+
"@faker-js/faker": "^8.4.1",
13+
"@tanstack/lit-table": "^8.20.5",
14+
"lit": "^3.1.4"
15+
},
16+
"devDependencies": {
17+
"@rollup/plugin-replace": "^5.0.7",
18+
"typescript": "5.4.5",
19+
"vite": "^5.3.2"
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
import { customElement } from 'lit/decorators.js'
2+
import { html, LitElement, PropertyValueMap } from 'lit'
3+
import { repeat } from 'lit/directives/repeat.js'
4+
import { state } from 'lit/decorators/state.js'
5+
import {
6+
ColumnDef,
7+
flexRender,
8+
getCoreRowModel,
9+
getSortedRowModel,
10+
SortingFn,
11+
type SortingState,
12+
TableController,
13+
} from '@tanstack/lit-table'
14+
15+
import { makeData, Person } from './makeData'
16+
17+
const sortStatusFn: SortingFn<Person> = (rowA, rowB, _columnId) => {
18+
const statusA = rowA.original.status
19+
const statusB = rowB.original.status
20+
const statusOrder = ['single', 'complicated', 'relationship']
21+
return statusOrder.indexOf(statusA) - statusOrder.indexOf(statusB)
22+
}
23+
24+
const columns: ColumnDef<Person>[] = [
25+
{
26+
accessorKey: 'firstName',
27+
cell: info => info.getValue(),
28+
//this column will sort in ascending order by default since it is a string column
29+
},
30+
{
31+
accessorFn: row => row.lastName,
32+
id: 'lastName',
33+
cell: info => info.getValue(),
34+
header: () => html`<span>Last Name</span>`,
35+
sortUndefined: 'last', //force undefined values to the end
36+
sortDescFirst: false, //first sort order will be ascending (nullable values can mess up auto detection of sort order)
37+
},
38+
{
39+
accessorKey: 'age',
40+
header: () => 'Age',
41+
//this column will sort in descending order by default since it is a number column
42+
},
43+
{
44+
accessorKey: 'visits',
45+
header: () => html`<span>Visits</span>`,
46+
sortUndefined: 'last', //force undefined values to the end
47+
},
48+
{
49+
accessorKey: 'status',
50+
header: 'Status',
51+
sortingFn: sortStatusFn, //use our custom sorting function for this enum column
52+
},
53+
{
54+
accessorKey: 'progress',
55+
header: 'Profile Progress',
56+
// enableSorting: false, //disable sorting for this column
57+
},
58+
{
59+
accessorKey: 'rank',
60+
header: 'Rank',
61+
invertSorting: true, //invert the sorting order (golf score-like where smaller is better)
62+
},
63+
{
64+
accessorKey: 'createdAt',
65+
header: 'Created At',
66+
// sortingFn: 'datetime' //make sure table knows this is a datetime column (usually can detect if no null values)
67+
},
68+
]
69+
70+
const data: Person[] = makeData(1000)
71+
72+
@customElement('lit-table-example')
73+
class LitTableExample extends LitElement {
74+
@state()
75+
private _sorting: SortingState = []
76+
77+
@state()
78+
private _multiplier: number = 1
79+
80+
@state()
81+
private _data: Person[] = new Array<Person>()
82+
83+
private tableController = new TableController<Person>(this)
84+
85+
constructor() {
86+
super()
87+
this._data = [...data]
88+
}
89+
90+
protected willUpdate(
91+
_changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>
92+
): void {
93+
super.willUpdate(_changedProperties)
94+
if (_changedProperties.has('_multiplier')) {
95+
const newData: Person[] = data.map(d => {
96+
const p: Person = {
97+
...d,
98+
visits: d.visits ? d.visits * this._multiplier : undefined,
99+
}
100+
return p
101+
})
102+
this._data.length = 0
103+
this._data = newData
104+
}
105+
}
106+
protected render() {
107+
const table = this.tableController.table({
108+
columns,
109+
data: this._data,
110+
state: {
111+
sorting: this._sorting,
112+
},
113+
onSortingChange: updaterOrValue => {
114+
if (typeof updaterOrValue === 'function') {
115+
this._sorting = updaterOrValue(this._sorting)
116+
} else {
117+
this._sorting = updaterOrValue
118+
}
119+
},
120+
getSortedRowModel: getSortedRowModel(),
121+
getCoreRowModel: getCoreRowModel(),
122+
})
123+
124+
return html`
125+
<input
126+
type="number"
127+
min="1"
128+
max="100"
129+
id="multiplier"
130+
@change="${(e: Event) => {
131+
const inputElement = (e as CustomEvent).target as HTMLInputElement
132+
if (inputElement) {
133+
this._multiplier = +inputElement.value
134+
this.requestUpdate('_multiplier')
135+
}
136+
}}"
137+
/>
138+
<table>
139+
<thead>
140+
${repeat(
141+
table.getHeaderGroups(),
142+
headerGroup => headerGroup.id,
143+
headerGroup => html`
144+
<tr>
145+
${headerGroup.headers.map(
146+
header => html`
147+
<th colspan="${header.colSpan}">
148+
${header.isPlaceholder
149+
? null
150+
: html`<div
151+
title=${header.column.getCanSort()
152+
? header.column.getNextSortingOrder() === 'asc'
153+
? 'Sort ascending'
154+
: header.column.getNextSortingOrder() === 'desc'
155+
? 'Sort descending'
156+
: 'Clear sort'
157+
: undefined}
158+
@click="${header.column.getToggleSortingHandler()}"
159+
style="cursor: ${header.column.getCanSort()
160+
? 'pointer'
161+
: 'not-allowed'}"
162+
>
163+
${flexRender(
164+
header.column.columnDef.header,
165+
header.getContext()
166+
)}
167+
${{ asc: ' 🔼', desc: ' 🔽' }[
168+
header.column.getIsSorted() as string
169+
] ?? null}
170+
</div>`}
171+
</th>
172+
`
173+
)}
174+
</tr>
175+
`
176+
)}
177+
</thead>
178+
<tbody>
179+
${table
180+
.getRowModel()
181+
.rows.slice(0, 10)
182+
.map(
183+
row => html`
184+
<tr>
185+
${row
186+
.getVisibleCells()
187+
.map(
188+
cell => html`
189+
<td>
190+
${flexRender(
191+
cell.column.columnDef.cell,
192+
cell.getContext()
193+
)}
194+
</td>
195+
`
196+
)}
197+
</tr>
198+
`
199+
)}
200+
</tbody>
201+
</table>
202+
<pre>${JSON.stringify(this._sorting, null, 2)}</pre>
203+
<style>
204+
* {
205+
font-family: sans-serif;
206+
font-size: 14px;
207+
box-sizing: border-box;
208+
}
209+
210+
table {
211+
border: 1px solid lightgray;
212+
border-collapse: collapse;
213+
}
214+
215+
tbody {
216+
border-bottom: 1px solid lightgray;
217+
}
218+
219+
th {
220+
border-bottom: 1px solid lightgray;
221+
border-right: 1px solid lightgray;
222+
padding: 2px 4px;
223+
}
224+
225+
tfoot {
226+
color: gray;
227+
}
228+
229+
tfoot th {
230+
font-weight: normal;
231+
}
232+
</style>
233+
`
234+
}
235+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { faker } from '@faker-js/faker'
2+
3+
export type Person = {
4+
firstName: string
5+
lastName: string | undefined
6+
age: number
7+
visits: number | undefined
8+
progress: number
9+
status: 'relationship' | 'complicated' | 'single'
10+
rank: number
11+
createdAt: Date
12+
subRows?: Person[]
13+
}
14+
15+
const range = (len: number) => {
16+
const arr: number[] = []
17+
for (let i = 0; i < len; i++) {
18+
arr.push(i)
19+
}
20+
return arr
21+
}
22+
23+
const newPerson = (): Person => {
24+
return {
25+
firstName: faker.person.firstName(),
26+
lastName: Math.random() < 0.1 ? undefined : faker.person.lastName(),
27+
age: faker.number.int(40),
28+
visits: Math.random() < 0.1 ? undefined : faker.number.int(1000),
29+
progress: faker.number.int(100),
30+
createdAt: faker.date.anytime(),
31+
status: faker.helpers.shuffle<Person['status']>([
32+
'relationship',
33+
'complicated',
34+
'single',
35+
])[0]!,
36+
rank: faker.number.int(100),
37+
}
38+
}
39+
40+
export function makeData(...lens: number[]) {
41+
const makeDataLevel = (depth = 0): Person[] => {
42+
const len = lens[depth]!
43+
return range(len).map((_d): Person => {
44+
return {
45+
...newPerson(),
46+
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
47+
}
48+
})
49+
}
50+
51+
return makeDataLevel()
52+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2020",
4+
"lib": ["ES2020", "DOM", "DOM.Iterable"],
5+
"module": "ESNext",
6+
"skipLibCheck": true,
7+
8+
/* Bundler mode */
9+
"moduleResolution": "bundler",
10+
"allowImportingTsExtensions": true,
11+
"resolveJsonModule": true,
12+
"isolatedModules": true,
13+
"noEmit": true,
14+
"experimentalDecorators": true,
15+
"emitDecoratorMetadata": true,
16+
"useDefineForClassFields": false,
17+
18+
/* Linting */
19+
"strict": true,
20+
"noUnusedLocals": false,
21+
"noUnusedParameters": true,
22+
"noFallthroughCasesInSwitch": true
23+
},
24+
"include": ["src"]
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { defineConfig } from 'vite'
2+
import rollupReplace from '@rollup/plugin-replace'
3+
4+
// https://vitejs.dev/config/
5+
export default defineConfig({
6+
plugins: [
7+
rollupReplace({
8+
preventAssignment: true,
9+
values: {
10+
__DEV__: JSON.stringify(true),
11+
'process.env.NODE_ENV': JSON.stringify('development'),
12+
},
13+
}),
14+
],
15+
})

packages/lit-table/src/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ export class TableController<TData extends RowData>
5555
this.tableInstance.setOptions(prev => ({
5656
...prev,
5757
state: { ...this._tableState, ...options.state },
58+
data: options.data,
59+
columns: options.columns,
5860
onStateChange: (updater: any) => {
5961
this._tableState = updater(this._tableState)
6062
this.host.requestUpdate()

0 commit comments

Comments
 (0)