Skip to content

Commit

Permalink
feat: sorting example working
Browse files Browse the repository at this point in the history
  • Loading branch information
Mor Kadosh committed May 10, 2024
1 parent 924f434 commit a69858d
Show file tree
Hide file tree
Showing 12 changed files with 370 additions and 44 deletions.
26 changes: 0 additions & 26 deletions examples/lit/basic/src/index.css

This file was deleted.

5 changes: 5 additions & 0 deletions examples/lit/sorting/.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/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/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>
20 changes: 20 additions & 0 deletions examples/lit/sorting/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "tanstack-lit-table-example-sorting",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"start": "vite"
},
"dependencies": {
"@tanstack/lit-table": "workspace:*",
"lit": "^3.1.3"
},
"devDependencies": {
"@rollup/plugin-replace": "^5.0.5",
"typescript": "5.4.5",
"vite": "^5.2.10"
}
}
Binary file added examples/lit/sorting/sessionmanager-bundle.zip
Binary file not shown.
199 changes: 199 additions & 0 deletions examples/lit/sorting/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { customElement } from 'lit/decorators.js'
import {
html,
LitElement
} from 'lit'
import {
ColumnDef,
flexRender,
getCoreRowModel,
getSortedRowModel,
SortingFn,
type SortingState,
TableController,
} from '@tanstack/lit-table'
import { repeat } from 'lit/directives/repeat.js'

import { makeData, Person } from './makeData.ts'
import { state } from 'lit/decorators/state.js'

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(100_000)

@customElement('lit-table-example')
class LitTableExample extends LitElement {
@state()
private _sorting: SortingState = []

private tableController = new TableController<Person>(this)

protected render(): unknown {
const table = this.tableController.getTable({
columns,
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`
<table>
<thead>
${repeat(
table.getHeaderGroups(),
headerGroup => headerGroup.id,
headerGroup => html`
<tr>
${repeat(
headerGroup.headers,
header => header.id,
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>
${repeat(
table.getRowModel().rows.slice(0, 10),
row => row.id,
row => html`
<tr>
${repeat(
row.getVisibleCells(),
cell => cell.id,
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/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/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/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'),
},
})
],
})
Loading

0 comments on commit a69858d

Please sign in to comment.