Datatable - Bitblue

The Datatable component is a powerful, feature-rich data table implementation for Svelte applications that provides comprehensive CRUD operations, filtering, pagination, and customization options.

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

PropTypeDefaultDescription
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
tableColumnsTableColumn[]—Column definitions (from TableProps; required)
takenumber—Default page size
busyboolean—External busy flag
querystring—Initial / bound search query
newRecordRecord<string, any>—Defaults for the create form
customFilterValuesRecord<string, any>—Extra filter values

Display & behavior

PropTypeDefaultDescription
persistFiltersToUrlboolean—Persist filters in the URL
persitFiltersToUrlboolean—Deprecated alias of persistFiltersToUrl
fillSpaceboolean—Fill available vertical space
showTopActionsBackgroundboolean—Background on the top action bar
hideSearchBoxboolean—Hide search input
showAddboolean—Show add button
addButtonLabelstring—Add button label
searchPlaceholderstring—Search placeholder
addNewHeadingstring—Create modal heading
updateHeadingstring—Edit modal heading
showFilterDateRangeboolean—Show date-range filter
modalSize'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl'—Editor modal size
loadingBodySizenumber—Skeleton body rows while loading
loadingHeaderSizenumber—Skeleton header sizing
allowLoadAfterCreateboolean—Refetch after create
allowDispatchAfterActionboolean—Dispatch after CRUD
showModalButtonsboolean—Show default modal footer buttons

Snippets & callbacks

PropTypeDescription
editorSnippet<[DatatableEditorFormProps]>Custom add/edit form
customFilterSnippet<[TableFilter]>Custom filter UI
modalFooterSnippetCustom modal footer
customAddActionSnippetReplace default add button
onAddNew() => voidCustom add handler
onAfterAction({ type, values?, data? }) => voidAfter create/update/delete/custom
onRowClicked(val) => voidRow click (from TableProps)
onActionClicked({ name, row }) => voidCustom row action

DatatableEditorFormProps

PropTypeDescription
recordIdstring | number | nullEditing id
dataRecord<string, any> | nullCurrent record
onChangeIFormChangePropForm change bridge
onDoneFunctionClose / complete
readonlybooleanRead-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

Actions
ID
Name
Email
Role
Status
No records found
<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}

© 2026 Bitblue is a registered trademark. All Rights Reserved.