import type { UntypedClientTable } from '../sdk/client_table.ts'; import { getByAccessorPath } from '../lib/accessor_path.ts'; import { createSignal, onCleanup, createMemo, createComputed, untrack, } from 'solid-js'; import { useSpacetimeDB } from './useSpacetimeDB.ts'; import { type EventContextInterface } from '../sdk/db_connection_impl.ts'; import type { UntypedRemoteModule } from '../sdk/spacetime_module.ts'; import type { RowType, UntypedTableDef } from '../lib/table.ts'; import type { Prettify } from '../lib/type_util.ts'; import { type Query, type BooleanExpr, toSql, evaluateBooleanExpr, getQueryAccessorName, getQueryWhereClause, } from '../lib/query.ts'; import { createStore, reconcile } from 'solid-js/store'; export interface UseTableCallbacks { onInsert?: (row: RowType) => void; onDelete?: (row: RowType) => void; onUpdate?: (oldRow: RowType, newRow: RowType) => void; /** Whether the subscription is active. Defaults to `true`. */ enabled?: () => boolean; } type MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut'; function classifyMembership( whereExpr: BooleanExpr | undefined, oldRow: Record, newRow: Record ): MembershipChange { if (!whereExpr) return 'stayIn'; const oldIn = evaluateBooleanExpr(whereExpr, oldRow); const newIn = evaluateBooleanExpr(whereExpr, newRow); if (oldIn && !newIn) return 'leave'; if (!oldIn && newIn) return 'enter'; if (oldIn && newIn) return 'stayIn'; return 'stayOut'; } /** * SolidJS primitive to subscribe to a table in SpacetimeDB and receive live updates. * * Accepts a query builder expression as the first argument: * - `tables.user` — subscribe to all rows * - `tables.user.where(r => r.online.eq(true))` — subscribe with a filter * * @param query - A query builder expression (table reference or filtered query). * @param callbacks - Optional callbacks for row insert, delete, and update events. * @returns A tuple of [rows, isReady]. * * @example * ```tsx * const [rows, isReady] = useTable(tables.user); * const [onlineUsers, isReady] = useTable( * tables.user.where(r => r.online.eq(true)), * { onInsert: (row) => console.log('New user:', row) } * ); * ``` */ export function useTable( query: () => Query, callbacks?: UseTableCallbacks>> ): [readonly Prettify>[], () => boolean] { type UseTableRowType = RowType; const enabled = callbacks?.enabled ?? (() => true); const q = createMemo(query); const accessorName = createMemo(() => getQueryAccessorName(q())); const whereExpr = createMemo(() => getQueryWhereClause(q())); const querySql = createMemo(() => toSql(q())); let connectionState: import('./connection_state.ts').ConnectionState; try { connectionState = useSpacetimeDB(); } catch { throw new Error( 'Could not find SpacetimeDB client! Did you forget to add a ' + '`SpacetimeDBProvider`? `useTable` must be used in the SolidJS component tree ' + 'under a `SpacetimeDBProvider` component.' ); } const [rows, setRows] = createStore[]>([]); let latestTransactionEventId: string | null = null; const computeSnapshot = (): readonly Prettify[] => { if (!enabled()) { return []; } const connection = connectionState.getConnection(); if (!connection) { return []; } const table = getByAccessorPath( connection.db, accessorName() ); const result: readonly Prettify[] = whereExpr() ? (Array.from(table.iter()).filter(row => evaluateBooleanExpr(whereExpr()!, row as Record) ) as Prettify[]) : (Array.from(table.iter()) as Prettify[]); return result; }; const [appliedConnectionId, setAppliedConnectionId] = createSignal< string | null >(null); const isReady = () => connectionState.isActive && appliedConnectionId() === connectionState.connectionId.toHexString(); createComputed(() => { setAppliedConnectionId(null); if (!enabled()) { setRows(reconcile([])); return; } const connection = connectionState.getConnection(); if (!connection) { setRows(reconcile([])); return; } const cancel = connection .subscriptionBuilder() .onApplied(() => { setAppliedConnectionId(connection.connectionId.toHexString()); }) .onError(() => setAppliedConnectionId(null)) .subscribe(querySql()); onCleanup(() => { cancel.unsubscribe(); }); // Bind to table events const table = getByAccessorPath( connection.db, accessorName() ); const onInsert = ( ctx: EventContextInterface, row: any ) => { if (whereExpr() && !evaluateBooleanExpr(whereExpr()!, row)) { return; } callbacks?.onInsert?.(row); if (ctx.event.id !== latestTransactionEventId) { latestTransactionEventId = ctx.event.id; setRows(reconcile(computeSnapshot())); } }; const onDelete = ( ctx: EventContextInterface, row: any ) => { if (whereExpr() && !evaluateBooleanExpr(whereExpr()!, row)) { return; } callbacks?.onDelete?.(row); if (ctx.event.id !== latestTransactionEventId) { latestTransactionEventId = ctx.event.id; setRows(reconcile(computeSnapshot())); } }; const onUpdate = ( ctx: EventContextInterface, oldRow: any, newRow: any ) => { const change = classifyMembership(whereExpr(), oldRow, newRow); switch (change) { case 'leave': callbacks?.onDelete?.(oldRow); break; case 'enter': callbacks?.onInsert?.(newRow); break; case 'stayIn': callbacks?.onUpdate?.(oldRow, newRow); break; case 'stayOut': return; // no-op } if (ctx.event.id !== latestTransactionEventId) { latestTransactionEventId = ctx.event.id; setRows(reconcile(computeSnapshot())); } }; table.onInsert(onInsert); table.onDelete(onDelete); table.onUpdate?.(onUpdate); // Load initial snapshot untrack(() => setRows(reconcile(computeSnapshot()))); onCleanup(() => { table.removeOnInsert(onInsert); table.removeOnDelete(onDelete); table.removeOnUpdate?.(onUpdate); }); }); return [rows, isReady]; }