Skip to content

Commit 4e9d0c6

Browse files
docs: Added Vanilla sorting example (#5854)
* #4928 Added Vanilla sorting example * ci: apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent 489a012 commit 4e9d0c6

12 files changed

+440
-93
lines changed

docs/config.json

+4
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,10 @@
745745
{
746746
"to": "framework/vanilla/examples/pagination",
747747
"label": "Pagination"
748+
},
749+
{
750+
"to": "framework/vanilla/examples/sorting",
751+
"label": "Sorting"
748752
}
749753
]
750754
}

examples/vanilla/sorting/.gitignore

+5
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

examples/vanilla/sorting/README.md

+6
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`

examples/vanilla/sorting/index.html

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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 + TS</title>
7+
<script type="module" src="https://cdn.skypack.dev/twind/shim"></script>
8+
</head>
9+
<body>
10+
<div id="root" class="p-2">
11+
<div id="wrapper"></div>
12+
</div>
13+
<script type="module" src="/src/main.ts"></script>
14+
</body>
15+
</html>

examples/vanilla/sorting/package.json

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "tanstack-table-example-vanilla-sorting",
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+
"devDependencies": {
12+
"@faker-js/faker": "^8.4.1",
13+
"@rollup/plugin-replace": "^5.0.7",
14+
"typescript": "5.4.5",
15+
"vite": "^5.3.2"
16+
},
17+
"dependencies": {
18+
"@tanstack/table-core": "^8.20.5",
19+
"nanostores": "^0.11.3"
20+
}
21+
}
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
html {
2+
font-family: sans-serif;
3+
font-size: 14px;
4+
}
5+
6+
table {
7+
border: 1px solid lightgray;
8+
}
9+
10+
tbody {
11+
border-bottom: 1px solid lightgray;
12+
}
13+
14+
th {
15+
border-bottom: 1px solid lightgray;
16+
border-right: 1px solid lightgray;
17+
padding: 2px 4px;
18+
}
19+
20+
tfoot {
21+
color: gray;
22+
}
23+
24+
tfoot th {
25+
font-weight: normal;
26+
}
27+
28+
button:disabled {
29+
opacity: 0.5;
30+
}

examples/vanilla/sorting/src/main.ts

+142
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import './index.css'
2+
3+
import {
4+
type SortingFn,
5+
createColumnHelper,
6+
getCoreRowModel,
7+
getSortedRowModel,
8+
} from '@tanstack/table-core'
9+
10+
import { makeData, Person } from './makeData'
11+
import { flexRender, useTable } from './useTable'
12+
13+
const data = makeData(1000)
14+
15+
// Custom sorting logic for one of our enum columns
16+
const sortStatusFn: SortingFn<Person> = (rowA, rowB, _columnId) => {
17+
const statusA = rowA.original.status
18+
const statusB = rowB.original.status
19+
const statusOrder = ['single', 'complicated', 'relationship']
20+
return statusOrder.indexOf(statusA) - statusOrder.indexOf(statusB)
21+
}
22+
23+
const columnHelper = createColumnHelper<Person>()
24+
25+
const columns = [
26+
columnHelper.accessor('firstName', {
27+
cell: info => info.getValue(),
28+
// This column will sort in ascending order by default since it is a string column
29+
}),
30+
columnHelper.accessor(row => row.lastName, {
31+
id: 'lastName',
32+
cell: info => `<i>${info.getValue()}</i>`,
33+
header: () => '<span>Last Name</span>',
34+
sortUndefined: 'last', // Force undefined values to the end
35+
sortDescFirst: false, // First sort order will be ascending (nullable values can mess up auto detection of sort order)
36+
}),
37+
columnHelper.accessor('age', {
38+
header: () => 'Age',
39+
cell: info => info.renderValue(),
40+
// This column will sort in descending order by default since it is a number column
41+
}),
42+
columnHelper.accessor('visits', {
43+
header: () => '<span>Visits</span>',
44+
sortUndefined: 'last', // Force undefined values to the end
45+
}),
46+
columnHelper.accessor('status', {
47+
header: 'Status',
48+
sortingFn: sortStatusFn, // Use our custom sorting function for this enum column
49+
}),
50+
columnHelper.accessor('progress', {
51+
header: 'Profile Progress',
52+
enableSorting: false, // Disable sorting for this column
53+
}),
54+
columnHelper.accessor('rank', {
55+
header: 'Rank',
56+
invertSorting: true, // Invert the sorting order (golf score-like where smaller is better)
57+
}),
58+
columnHelper.accessor('createdAt', {
59+
header: 'Created At',
60+
}),
61+
]
62+
63+
const renderTable = () => {
64+
// Create table elements
65+
const tableElement = document.createElement('table')
66+
const theadElement = document.createElement('thead')
67+
const tbodyElement = document.createElement('tbody')
68+
69+
tableElement.classList.add('mb-2')
70+
71+
tableElement.appendChild(theadElement)
72+
tableElement.appendChild(tbodyElement)
73+
74+
// Render table headers
75+
table.getHeaderGroups().forEach(headerGroup => {
76+
const trElement = document.createElement('tr')
77+
headerGroup.headers.forEach(header => {
78+
const thElement = document.createElement('th')
79+
thElement.colSpan = header.colSpan
80+
const divElement = document.createElement('div')
81+
divElement.classList.add(
82+
'w-36',
83+
...(header.column.getCanSort() ? ['cursor-pointer', 'select-none'] : [])
84+
)
85+
;(divElement.onclick = e => header.column.getToggleSortingHandler()?.(e)),
86+
(divElement.innerHTML = header.isPlaceholder
87+
? ''
88+
: flexRender(header.column.columnDef.header, header.getContext()))
89+
divElement.innerHTML +=
90+
{
91+
asc: ' 🔼',
92+
desc: ' 🔽',
93+
}[header.column.getIsSorted() as string] ?? ''
94+
thElement.appendChild(divElement)
95+
trElement.appendChild(thElement)
96+
})
97+
theadElement.appendChild(trElement)
98+
})
99+
100+
// Render table rows
101+
table
102+
.getRowModel()
103+
.rows.slice(0, 10)
104+
.forEach(row => {
105+
const trElement = document.createElement('tr')
106+
row.getVisibleCells().forEach(cell => {
107+
const tdElement = document.createElement('td')
108+
tdElement.innerHTML = flexRender(
109+
cell.column.columnDef.cell,
110+
cell.getContext()
111+
)
112+
trElement.appendChild(tdElement)
113+
})
114+
tbodyElement.appendChild(trElement)
115+
})
116+
117+
// Render table state info
118+
const stateInfoElement = document.createElement('pre')
119+
stateInfoElement.textContent = JSON.stringify(
120+
{
121+
sorting: table.getState().sorting,
122+
},
123+
null,
124+
2
125+
)
126+
127+
// Clear previous content and append new content
128+
const wrapperElement = document.getElementById('wrapper') as HTMLDivElement
129+
wrapperElement.innerHTML = ''
130+
wrapperElement.appendChild(tableElement)
131+
wrapperElement.appendChild(stateInfoElement)
132+
}
133+
134+
const table = useTable<Person>({
135+
data,
136+
columns,
137+
getCoreRowModel: getCoreRowModel(),
138+
getSortedRowModel: getSortedRowModel(),
139+
onStateChange: () => renderTable(),
140+
})
141+
142+
renderTable()
+52
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
6+
age: number
7+
visits: number
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: faker.person.lastName(),
27+
age: faker.number.int(40),
28+
visits: faker.number.int(1000),
29+
progress: faker.number.int(100),
30+
status: faker.helpers.shuffle<Person['status']>([
31+
'relationship',
32+
'complicated',
33+
'single',
34+
])[0]!,
35+
rank: faker.number.int(100),
36+
createdAt: faker.date.anytime(),
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+
}
+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { atom } from 'nanostores'
2+
3+
import {
4+
type RowData,
5+
type TableOptions,
6+
type TableOptionsResolved,
7+
createTable,
8+
} from '@tanstack/table-core'
9+
10+
export const flexRender = <TProps extends object>(comp: any, props: TProps) => {
11+
if (typeof comp === 'function') {
12+
return comp(props)
13+
}
14+
return comp
15+
}
16+
17+
export const useTable = <TData extends RowData>(
18+
options: TableOptions<TData>
19+
) => {
20+
// Compose in the generic options to the user options
21+
const resolvedOptions: TableOptionsResolved<TData> = {
22+
state: {}, // Dummy state
23+
onStateChange: () => {}, // noop
24+
renderFallbackValue: null,
25+
...options,
26+
}
27+
28+
// Create a new table
29+
const table = createTable<TData>(resolvedOptions)
30+
31+
// By default, manage table state here using the table's initial state
32+
const state = atom(table.initialState)
33+
34+
// Subscribe to state changes
35+
state.subscribe(currentState => {
36+
table.setOptions(prev => ({
37+
...prev,
38+
...options,
39+
state: {
40+
...currentState,
41+
...options.state,
42+
},
43+
// Similarly, we'll maintain both our internal state and any user-provided state
44+
onStateChange: updater => {
45+
if (typeof updater === 'function') {
46+
const newState = updater(currentState)
47+
state.set(newState)
48+
} else {
49+
state.set(updater)
50+
}
51+
options.onStateChange?.(updater)
52+
},
53+
}))
54+
})
55+
56+
return table
57+
}
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
"emitDecoratorMetadata": true,
14+
"noEmit": true,
15+
"jsx": "react-jsx",
16+
"experimentalDecorators": true,
17+
"useDefineForClassFields": false,
18+
19+
/* Linting */
20+
"strict": true,
21+
"noUnusedLocals": false,
22+
"noUnusedParameters": true,
23+
"noFallthroughCasesInSwitch": true
24+
},
25+
"include": ["src"]
26+
}
+15
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+
})

0 commit comments

Comments
 (0)