Setup
pnpm add @cailabs/components.data svelte-headless-table <script>
import { Datatable } from '@cailabs/components.data';
</script> See Installation.
Features
- Full CRUD Operations: Create, read, update, and delete records
- Advanced Filtering: Search, date range filtering, and custom filters
- Pagination: Configurable page sizes and navigation
- Customizable UI: Flexible styling and layout options
- URL Persistence: Option to persist filters and pagination state in URL
- Responsive Design: Works across various screen sizes
- Custom Editors: Flexible form editors for creating/editing records
- Loading States: Built-in loading indicators
Usage
Basic Implementation
<script>
import { Datatable } from '@cailabs/components.data';
// Sample data fetching function
async function fetchData(skip, take, filter) {
const response = await fetch(`/api/data?skip=${skip}&take=${take}`);
return await response.json();
}
// Sample create function
async function createItem(data) {
const response = await fetch('/api/data', {
method: 'POST',
body: JSON.stringify(data)
});
return await response.json();
}
</script>
<Datatable
read={fetchData}
createEntry={createItem}
columns={[
{ header: 'ID', accessor: 'id' },
{ header: 'Name', accessor: 'name' },
{ header: 'Email', accessor: 'email' }
]}
/> Advanced Implementation with Custom Editor
<script>
import { Input, Select } from '@cailabs/components.forms';
import { Datatable } from '@cailabs/components.data';
// Your data functions
async function fetchData(skip, take, filter) {
// Implementation
}
async function createItem(data) {
// Implementation
}
async function updateItem(data) {
// Implementation
}
async function deleteItem(id) {
// Implementation
}
// Define columns
const columns = [
{ header: 'ID', accessor: 'id', width: 80 },
{ header: 'Name', accessor: 'name' },
{ header: 'Email', accessor: 'email' },
{ header: 'Status', accessor: 'status' },
{ header: 'Created', accessor: 'createdAt', type: 'date' }
];
</script>
<Datatable
{columns}
read={fetchData}
createEntry={createItem}
updateEntry={updateItem}
deleteEntry={deleteItem}
persitFiltersToUrl={true}
showFilterDateRange={true}
addButtonLabel="Add User"
addNewHeading="Create New User"
updateHeading="Edit User"
{editor}
/>
{#snippet editor({ recordId, data, onChange, readonly })}
<div class="space-y-4">
<Input
name="name"
label="Full Name"
value={data?.name || ''}
oninput={(e) => onChange({ values: { name: e.target.value } })}
disabled={readonly}
required
/>
<Input
name="email"
type="email"
label="Email Address"
value={data?.email || ''}
oninput={(e) => onChange({ values: { email: e.target.value } })}
disabled={readonly}
required
/>
<Select
name="status"
label="Status"
value={data?.status || 'active'}
options={[
{ value: 'active', label: 'Active' },
{ value: 'inactive', label: 'Inactive' },
{ value: 'pending', label: 'Pending' }
]}
onchange={(e) => onChange({ values: { status: e.value } })}
disabled={readonly}
/>
</div>
{/snippet} Props
DatatableProps extends TableProps (see Table). Datatable-specific props:
Data / CRUD
| Prop | Type | Default | Description |
|---|---|---|---|
read | (skip?, take?, filter?) => PaginatedResult \| Promise \| null | — | Fetch page of rows |
createEntry | (entry) => CrudResult \| Promise \| null | — | Create handler |
updateEntry | (entry) => CrudResult \| Promise \| null | — | Update handler |
deleteEntry | (id) => CrudResult \| Promise \| null | — | Delete handler |
tableColumns | TableColumn[] | — | Column definitions (from TableProps; required) |
take | number | — | Default page size |
busy | boolean | — | External busy flag |
query | string | — | Initial / bound search query |
newRecord | Record<string, any> | — | Defaults for the create form |
customFilterValues | Record<string, any> | — | Extra filter values |
Display & behavior
| Prop | Type | Default | Description |
|---|---|---|---|
persistFiltersToUrl | boolean | — | Persist filters in the URL |
persitFiltersToUrl | boolean | — | Deprecated alias of persistFiltersToUrl |
fillSpace | boolean | — | Fill available vertical space |
showTopActionsBackground | boolean | — | Background on the top action bar |
hideSearchBox | boolean | — | Hide search input |
showAdd | boolean | — | Show add button |
addButtonLabel | string | — | Add button label |
searchPlaceholder | string | — | Search placeholder |
addNewHeading | string | — | Create modal heading |
updateHeading | string | — | Edit modal heading |
showFilterDateRange | boolean | — | Show date-range filter |
modalSize | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | — | Editor modal size |
loadingBodySize | number | — | Skeleton body rows while loading |
loadingHeaderSize | number | — | Skeleton header sizing |
allowLoadAfterCreate | boolean | — | Refetch after create |
allowDispatchAfterAction | boolean | — | Dispatch after CRUD |
showModalButtons | boolean | — | Show default modal footer buttons |
Snippets & callbacks
| Prop | Type | Description |
|---|---|---|
editor | Snippet<[DatatableEditorFormProps]> | Custom add/edit form |
customFilter | Snippet<[TableFilter]> | Custom filter UI |
modalFooter | Snippet | Custom modal footer |
customAddAction | Snippet | Replace default add button |
onAddNew | () => void | Custom add handler |
onAfterAction | ({ type, values?, data? }) => void | After create/update/delete/custom |
onRowClicked | (val) => void | Row click (from TableProps) |
onActionClicked | ({ name, row }) => void | Custom row action |
DatatableEditorFormProps
| Prop | Type | Description |
|---|---|---|
recordId | string | number | null | Editing id |
data | Record<string, any> | null | Current record |
onChange | IFormChangeProp | Form change bridge |
onDone | Function | Close / complete |
readonly | boolean | Read-only mode |
API Reference
Data Functions
All data functions should return a specific response format:
Read Function
async function read(skip: number, take: number, filter: TableFilter): Promise<PaginatedResult<T>> {
return {
success: true,
message: '',
data: {
pageInfo: {
hasNextPage: boolean,
hasPreviousPage: boolean
},
totalCount: number,
items: T[]
}
};
} Create/Update/Delete Functions
async function operation(data: any): Promise<CrudResult<T>> {
return {
success: boolean,
message: string,
data: T // for create/update
};
} TableFilter Interface
interface TableFilter<T = any> {
search?: string;
startDate?: Date | string | null;
endDate?: Date | string | null;
dateRange?: string;
filter?: Partial<T>;
order?: Array<{ field: keyof T; direction: 'asc' | 'desc' }>;
pageSize?: number;
currentPage?: number;
} Events
The Datatable component emits several events that can be handled:
reFetchTableData: Custom event to trigger data refetching- Row click events
- Action button events (edit, view, delete)
Examples
Custom Filter Example
<Datatable {columns} {read} {createEntry} {updateEntry} {customFilter} />
{#snippet customFilter({ pageSize, currentPage, search })}
<div class="mb-4 flex gap-4">
<Select
label="Category"
options={[
{ value: 'all', label: 'All Categories' },
{ value: 'electronics', label: 'Electronics' },
{ value: 'clothing', label: 'Clothing' }
]}
onchange={(e) => {
// Update custom filter values
customFilterValues = { ...customFilterValues, category: e.value };
fetchData(currentPage, { search });
}}
/>
<Select
label="Status"
options={[
{ value: 'all', label: 'All Statuses' },
{ value: 'active', label: 'Active' },
{ value: 'archived', label: 'Archived' }
]}
onchange={(e) => {
customFilterValues = { ...customFilterValues, status: e.value };
fetchData(currentPage, { search });
}}
/>
</div>
{/snippet} Programmatic Refresh
You can trigger a refresh of the table data programmatically:
import { refetchDatatable } from '@cailabs/components.data';
// Refresh with current filters
refetchDatatable();
// Refresh with new filters
refetchDatatable({
search: 'new search term',
filter: { status: 'active' }
}); Kitchen Sink
Page Size
100
1/0
(0) <script lang="ts">
import { Accordion, AccordionItem, type DatatableEditorFormProps, type CrudResult, type PaginatedResult, type TableFilter } from '@cailabs/components.base';
import { FormDatepicker, Form, FormInput, FormSelect, Select, Input } from '@cailabs/components.forms';
import { Datatable } from '@cailabs/components.data';
import { refetchDatatable } from '$lib/ui/datatable/Datatable.svelte';
interface User {}
function read(skip?: number, take?: number, defn?: TableFilter): Promise<PaginatedResult<User>> {
console.log(defn);
return new Promise((resolve) => {
setTimeout(() => {
resolve({
success: true,
message: '',
data: {
pageInfo: { hasNextPage: false, hasPreviousPage: false },
totalCount: 3,
items: [
{
id: 1,
name: 'Alice',
email: 'alice@example.com',
role: 'Admin',
status: 'Active',
dob: '1990-05-12'
},
{
id: 2,
name: 'Bob',
email: 'bob@example.com',
role: 'User',
status: 'Inactive',
dob: '1988-11-23'
},
{
id: 3,
name: 'Charlie',
email: 'charlie@example.com',
role: 'User',
status: 'Active',
dob: '1995-07-04'
}
]
}
});
}, 1000);
});
}
function create(params: any): Promise<CrudResult<any>> {
console.log({ params });
return new Promise((resolve) => {
setTimeout(() => {
resolve({
success: true,
message: 'Successfully created record'
});
}, 700);
});
}
function update(params: any): Promise<CrudResult<any>> {
console.log({ params });
return new Promise((resolve) => {
setTimeout(() => {
resolve({
success: true,
message: 'Successfully updated record'
});
}, 700);
});
}
function doDelete(id: any): Promise<CrudResult<any>> {
console.log({ id });
return new Promise((resolve) => {
setTimeout(() => {
resolve({
success: true,
message: 'Successfully deleted record'
});
}, 700);
});
}
// Table configuration
const columns = [
{ header: 'ID', accessor: 'id' },
{ header: 'Name', accessor: 'name' },
{ header: 'Email', accessor: 'email' },
{ header: 'Role', accessor: 'role' },
{ header: 'Status', accessor: 'status' }
];
function handleRowClick(event: any) {
console.log({ event });
// console.log('Row clicked:', event.detail);
}
// Custom filter values
let customFilterValues = $state({
role: '',
status: '',
minAge: '',
maxAge: ''
});
</script>
<div class="h-full w-full">
<Datatable
showFilterDateRange
tableColumns={columns}
showActions
rowClickable
showEdit
showDelete
{read}
createEntry={create}
updateEntry={update}
deleteEntry={doDelete}
onRowClicked={handleRowClick}
modalSize="xl"
{editor}
{customFilter}
></Datatable>
</div>
{#snippet editor({ recordId, data, onChange, readonly }: DatatableEditorFormProps)}
<Form {schema} initialValues={data || initialValues} {onChange} class="space-y-2">
<FormInput name="name" label="Name" required {readonly} />
<FormInput name="email" label="Email" required type="email" {readonly} />
<FormDatepicker name="dob" label="Date of birth" disabled={readonly} required />
<FormSelect name="role" label="Role" required options={['Admin', 'User']} disabled={readonly} />
</Form>
{/snippet}
{#snippet customFilter({ pageSize, currentPage, search })}
<div>
<Accordion flush>
<AccordionItem class="flex h-10 items-center px-4 hover:bg-gray-100">
{#snippet header()}
<span class="flex items-center gap-2">
<iconify-icon icon="mdi:report-bar"></iconify-icon>
Advanced Search</span
>
{/snippet}
<div class="flex flex-row flex-wrap items-center gap-4 px-4">
<div class="w-full max-w-sm">
<Select
minHeight={40}
value={customFilterValues.role}
options={[
{ value: '', label: 'All Roles' },
{ value: 'Admin', label: 'Admin' },
{ value: 'User', label: 'User' },
{ value: 'Manager', label: 'Manager' }
]}
onChange={(e) => {
customFilterValues.role = e.value;
refetchDatatable({
filter: { ...customFilterValues },
search: search
});
}}
/>
</div>
<div class="w-full max-w-sm">
<Select
minHeight={40}
value={customFilterValues.status}
options={[
{ value: '', label: 'All Statuses' },
{ value: 'Active', label: 'Active' },
{ value: 'Inactive', label: 'Inactive' },
{ value: 'Pending', label: 'Pending' }
]}
onChange={(e) => {
customFilterValues.status = e.value;
refetchDatatable({
filter: { ...customFilterValues },
search: search
});
}}
/>
</div>
<div class="w-full max-w-sm">
<Input
type="number"
value={customFilterValues.maxAge}
placeholder="Max age"
oninput={(e) => {
customFilterValues.maxAge = e.target.value;
refetchDatatable({
filter: { ...customFilterValues },
search: search
});
}}
/>
</div>
</div>
</AccordionItem>
</Accordion>
</div>
{/snippet}