# Tables, state and loading · Divan

> Every table is TanStack Table through <DataTable>. What a person is looking at (filter, search, sort, page) lives in the address; preferences live in the browser and follow across tabs; changes made in place go through SvelteKit remote functions and show at once. Everything below the first screen loads only when it is needed.

Part of Divan, the DivanWorks design system. Web page: https://brand.divanworks.com/data · All topics: https://brand.divanworks.com/llms.txt

## Rules

- Tables: <DataTable> from src/lib/components/ui/data-table. Columns are ColumnDef objects (meta.align "end" for numbers, meta.class for cells, renderSnippet for rich cells), with getRowId and a first sort. Add search for long tables, urlKey to keep the view in the address, pageSize for pages (or nothing, and rows are drawn as they scroll into view). Persian pages pass labels={DATA_TABLE_FA} and dir="rtl"; on a card, surface="none".
- Lists that are not tables (cards, rows that open) still use TanStack’s model when they filter, sort or tick rows: createSvelteTable with getFilteredRowModel, getSortedRowModel and rowSelection.
- View state goes in the address: new UrlState(key, fallback, codec) from src/lib/state/url.svelte.ts, with codec.string, codec.count, codec.oneOf([...]) or codec.sorting. The default value keeps the address clean, and every change goes through one queue of shallow replaceState calls.
- A backoffice form posts to actionUrl('name') from src/lib/action-url.ts, never to "?/name": SvelteKit lands an enhanced form on the address it posted to, so a bare action drops the view's query (filters, days, the chosen row). Public pages drop their one-time results (?google=linked) that way on purpose. pnpm divan:lint flags it (form-action-drops-view).
- Preferences go in the browser: new Persisted(key, fallback, isValid) from src/lib/state/persisted.svelte.ts at module level, connect() in onMount, .current anywhere. It starts at the fallback so the first render matches the server, and other tabs follow at once.
- Dates and times: every moment Studio, the backoffice and the site show is in Tehran time, so the page the server draws (in UTC) and the one the browser draws (in the viewer’s zone) agree. Format with formatTime(at, lang, options) or timeFormat(lang, options) from src/lib/time.ts (a day in full, with its weekday, with fullDay(at, lang): one Persian format with the weekday and the year puts the year first), group rows by day with dayOf, and give a schedule field (<input type="datetime-local">) wallClock and fromWallClock, saying beside it that it is Tehran time. A calendar day kept as YYYY-MM-DD formats at noon with timeZone: 'UTC'. The visitor’s own zone is for the public round’s end and for Learning’s free times and sessions, where a learner and a teacher each read their own clock (viewerZone, zoneName and clockIn from src/lib/learning/zones.ts), always with the zone’s name. pnpm divan:lint flags a format with no timeZone and the local clock read by hand (time-without-zone).
- Changes made in place go through a remote function (*.remote.ts with command or query from $app/server; kit.experimental.remoteFunctions is on). Show the new value at once as an optimistic override, call the command, invalidate, then drop the override: the server’s answer wins. A remote function runs at /_app/remote, outside the route’s guards, so it checks the user itself (requireAdmin(getRequestEvent().locals)).
- Live data: Supabase Realtime says what changed and the page reads it again (connectLive in src/lib/episode-live.svelte.ts).
- Images below the first screen get loading="lazy" decoding="async"; the first big picture gets fetchpriority="high"; art with a phone and a wide version is one <picture>, so only one file downloads.
- Heavy code loads with import() when it is needed: Plotly when a chart comes near the screen, the Supabase clients when a page goes live or someone signs in, PostHog after the page shows.
- Long sections far below the first screen get the defer-render utility (content-visibility), never one above a section an in-page link jumps to. Slow, secondary data streams: return the promise from load and show it with {#await} behind a Skeleton.

## Components

### DataTable

Every table of data, on TanStack Table, ending with Created and Updated (stampColumns: date and time, Tehran time). Sortable headers, optional search, pages (pageSize) or rows drawn as they scroll into view, and sort/search/page kept in the address with urlKey. Rows alternate tones; no grid lines. Tables of text pass stack, so phones show each row as a card. Persian pages pass labels={DATA_TABLE_FA} and dir="rtl". Filters kept outside the table (a bar, a Sheet) pass pageKey={view} so it returns to page 1 when they change.

```ts
import { DataTable, renderSnippet, stampColumns, type ColumnDef } from '#lib/components/ui/data-table/index.js';
```

```svelte
<script lang="ts">
	import { DataTable, renderSnippet, stampColumns, type ColumnDef } from '#lib/components/ui/data-table/index.js';
	import { Status } from '#lib/components/ui/status/index.js';

	type Donor = { id: string; name: string; total: number; status: 'Counted' | 'Held'; createdAt: string; updatedAt: string };
	let { donors }: { donors: Donor[] } = $props();

	const columns: ColumnDef<Donor>[] = [
		{ accessorKey: 'name', header: 'Donor' },
		{ accessorKey: 'status', header: 'Status', cell: ({ row }) => renderSnippet(status, row.original) },
		{ accessorKey: 'total', header: 'Total', cell: ({ row }) => row.original.total.toLocaleString('en-GB'), meta: { align: 'end' } },
		...stampColumns<Donor>({ created: (d) => d.createdAt, updated: (d) => d.updatedAt, lang: 'en' })
	];
</script>

{#snippet status(d: Donor)}<Status tone={d.status === 'Counted' ? 'success' : 'attention'}>{d.status}</Status>{/snippet}

<DataTable data={donors} {columns} getRowId={(d) => d.id} sorting={[{ id: 'total', desc: true }]} search urlKey="donors" minWidth="32rem" />
```
