Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix dynamic data updates in the Lit Table Adapter #5884

Merged
merged 2 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions examples/lit/sorting-dynamic-data/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
.DS_Store
dist
dist-ssr
*.local
6 changes: 6 additions & 0 deletions examples/lit/sorting-dynamic-data/README.md
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`
14 changes: 14 additions & 0 deletions examples/lit/sorting-dynamic-data/index.html
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>
21 changes: 21 additions & 0 deletions examples/lit/sorting-dynamic-data/package.json
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"
}
}
235 changes: 235 additions & 0 deletions examples/lit/sorting-dynamic-data/src/main.ts
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>
`
}
}
52 changes: 52 additions & 0 deletions examples/lit/sorting-dynamic-data/src/makeData.ts
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()
}
25 changes: 25 additions & 0 deletions examples/lit/sorting-dynamic-data/tsconfig.json
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"]
}
15 changes: 15 additions & 0 deletions examples/lit/sorting-dynamic-data/vite.config.js
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'),
},
}),
],
})
2 changes: 2 additions & 0 deletions packages/lit-table/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export class TableController<TData extends RowData>
this.tableInstance.setOptions(prev => ({
...prev,
state: { ...this._tableState, ...options.state },
data: options.data,
lschierer marked this conversation as resolved.
Show resolved Hide resolved
columns: options.columns,
onStateChange: (updater: any) => {
this._tableState = updater(this._tableState)
this.host.requestUpdate()
Expand Down