import Alpine from 'alpinejs'
import {
FlexRender,
createSortedRowModel,
createTable,
rowSortingFeature,
sortFn_alphanumeric,
sortFn_datetime,
sortFn_text,
tableFeatures,
} from '@tanstack/alpine-table'
import { makeData } from './makeData'
import './index.css'
import type { ColumnDef, SortFn } from '@tanstack/alpine-table'
import type { Person } from './makeData'
const features = tableFeatures({
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
sortFns: {
alphanumeric: sortFn_alphanumeric,
datetime: sortFn_datetime,
text: sortFn_text,
},
})
const sortStatusFn: SortFn<typeof features, 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: Array<ColumnDef<typeof features, Person>> = [
{
accessorKey: 'firstName',
cell: (info) => info.getValue(),
},
{
accessorFn: (row) => row.lastName,
id: 'lastName',
cell: (info) => info.getValue(),
header: () => '<span>Last Name</span>',
sortUndefined: 'last',
sortDescFirst: false,
},
{
accessorKey: 'age',
header: () => 'Age',
},
{
accessorKey: 'visits',
header: () => '<span>Visits</span>',
sortUndefined: 'last',
},
{
accessorKey: 'status',
header: 'Status',
sortFn: sortStatusFn,
},
{
accessorKey: 'progress',
header: 'Profile Progress',
},
{
accessorKey: 'rank',
header: 'Rank',
invertSorting: true,
},
{
accessorKey: 'createdAt',
header: 'Created At',
},
]
const baseData: Array<Person> = makeData(1_000)
Alpine.data('table', () => {
const local = Alpine.reactive({
data: [...baseData],
multiplier: 1,
})
const table = createTable({
features,
columns,
get data() {
return local.data
},
debugTable: true,
})
return {
table,
FlexRender,
sortIndicator(isSorted: false | 'asc' | 'desc') {
return { asc: ' 🔼', desc: ' 🔽' }[isSorted as string] ?? ''
},
applyMultiplier(value: string) {
local.multiplier = Number(value) || 1
local.data = baseData.map((d) => ({
...d,
visits: d.visits ? d.visits * local.multiplier : undefined,
}))
},
refreshData() {
local.data = makeData(1_000)
},
stressTest() {
local.data = makeData(1_000_000)
},
}
})
window.Alpine = Alpine
Alpine.start()