Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 7 additions & 4 deletions crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { setContext, onDestroy } from 'svelte';
import { writable, type Writable } from 'svelte/store';
import { readonly, writable, type Readable } from 'svelte/store';
import {
DbConnectionBuilder,
type DbConnectionImpl,
Expand Down Expand Up @@ -32,7 +32,7 @@ export function createSpacetimeDBProvider<
DbConnection extends DbConnectionImpl<any>,
>(
connectionBuilder: DbConnectionBuilder<DbConnection>
): Writable<ConnectionState> {
): Readable<ConnectionState> {
const key = ConnectionManager.getKey(
connectionBuilder.getUri(),
connectionBuilder.getModuleName()
Expand Down Expand Up @@ -72,6 +72,9 @@ export function createSpacetimeDBProvider<
ConnectionManager.release(key);
});

setContext(SPACETIMEDB_CONTEXT_KEY, store);
return store;
// Hand out a read-only view: the state is owned by the ConnectionManager, so
// writes from components would only be overwritten (or worse, believed).
const readable = readonly(store);
setContext(SPACETIMEDB_CONTEXT_KEY, readable);
return readable;
}
1 change: 1 addition & 0 deletions crates/bindings-typescript/src/svelte/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './SpacetimeDBProvider.ts';
export { useSpacetimeDB } from './useSpacetimeDB.ts';
export { useTable } from './useTable.ts';
export { useReducer } from './useReducer.ts';
export { useProcedure } from './useProcedure.ts';
57 changes: 57 additions & 0 deletions crates/bindings-typescript/src/svelte/useProcedure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { getByAccessorPath } from '../lib/accessor_path.ts';
import { onDestroy } from 'svelte';
import { get } from 'svelte/store';
import type { UntypedProcedureDef } from '../sdk/procedures.ts';
import { useSpacetimeDB } from './useSpacetimeDB.ts';
import type {
ProcedureParamsType,
ProcedureReturnType,
} from '../sdk/type_utils.ts';

export function useProcedure<ProcedureDef extends UntypedProcedureDef>(
procedureDef: ProcedureDef
): (
...params: ProcedureParamsType<ProcedureDef>
) => Promise<ProcedureReturnType<ProcedureDef>> {
const connectionStore = useSpacetimeDB();
const procedureName = procedureDef.accessorName;

// Holds calls made before the connection exists
const queue: {
params: ProcedureParamsType<ProcedureDef>;
resolve: (val: ProcedureReturnType<ProcedureDef>) => void;
reject: (err: unknown) => void;
}[] = [];

// Flush when we finally have a connection
const unsubscribe = connectionStore.subscribe(state => {
const conn = state.getConnection();
if (!conn || !queue.length) return;

const fn = getByAccessorPath(conn.procedures, procedureName) as (
...p: ProcedureParamsType<ProcedureDef>
) => Promise<ProcedureReturnType<ProcedureDef>>;
for (const item of queue.splice(0)) {
fn(...item.params).then(item.resolve, item.reject);
}
});

onDestroy(() => {
unsubscribe();
});

return (...params: ProcedureParamsType<ProcedureDef>) => {
const conn = get(connectionStore).getConnection();
if (!conn) {
return new Promise<ProcedureReturnType<ProcedureDef>>(
(resolve, reject) => {
queue.push({ params, resolve, reject });
}
);
}
const fn = getByAccessorPath(conn.procedures, procedureName) as (
...p: ProcedureParamsType<ProcedureDef>
) => Promise<ProcedureReturnType<ProcedureDef>>;
return fn(...params);
};
}
10 changes: 1 addition & 9 deletions crates/bindings-typescript/src/svelte/useReducer.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import { getByAccessorPath } from '../lib/accessor_path.ts';
import { onDestroy } from 'svelte';
import { get } from 'svelte/store';
import type { InferTypeOfParams } from '../lib/type_builders.ts';
import type { UntypedReducerDef } from '../sdk/reducers.ts';
import type { ParamsType } from '../sdk/type_utils.ts';
import { useSpacetimeDB } from './useSpacetimeDB.ts';
import type { Prettify } from '../lib/type_util.ts';

type IsEmptyObject<T> = [keyof T] extends [never] ? true : false;
type MaybeParams<T> = IsEmptyObject<T> extends true ? [] : [params: T];

type ParamsType<R extends UntypedReducerDef> = MaybeParams<
Prettify<InferTypeOfParams<R['params']>>
>;

export function useReducer<ReducerDef extends UntypedReducerDef>(
reducerDef: ReducerDef
Expand Down
6 changes: 3 additions & 3 deletions crates/bindings-typescript/src/svelte/useSpacetimeDB.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { getContext } from 'svelte';
import type { Writable } from 'svelte/store';
import type { Readable } from 'svelte/store';
import {
SPACETIMEDB_CONTEXT_KEY,
type ConnectionState,
} from './connection_state.ts';

// Throws an error if used outside of a SpacetimeDBProvider
export function useSpacetimeDB(): Writable<ConnectionState> {
const context = getContext<Writable<ConnectionState> | undefined>(
export function useSpacetimeDB(): Readable<ConnectionState> {
const context = getContext<Readable<ConnectionState> | undefined>(
SPACETIMEDB_CONTEXT_KEY
);

Expand Down
42 changes: 18 additions & 24 deletions crates/bindings-typescript/src/svelte/useTable.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { UntypedClientTable } from '../sdk/client_table.ts';
import { getByAccessorPath } from '../lib/accessor_path.ts';
import { onDestroy } from 'svelte';
import { writable, get, type Readable } from 'svelte/store';
import { writable, type Readable } from 'svelte/store';
import { useSpacetimeDB } from './useSpacetimeDB.ts';
import type { ConnectionState } from './connection_state.ts';
import type { EventContextInterface } from '../sdk/db_connection_impl.ts';
Expand Down Expand Up @@ -75,13 +75,17 @@ export function useTable<TableDef extends UntypedTableDef>(
let appliedConnectionId: string | null = null;
let subscribedConnection: ReturnType<ConnectionState['getConnection']> = null;

let latestTransactionEvent: any = null;
// The latest connection state, kept current by the store subscription below.
// Reading it here instead of calling `get(connectionStore)` avoids a
// subscribe/unsubscribe round trip on every transaction.
let currentState: ConnectionState | undefined;

let latestTransactionEventId: string | null = null;
let unsubscribeFromTable: (() => void) | null = null;
let subscriptionHandle: { unsubscribe: () => void } | null = null;

const computeFilteredRows = (): readonly Prettify<Row>[] => {
const state = get(connectionStore);
const connection = state.getConnection();
const connection = currentState?.getConnection();
if (!connection) return [];

const table = getByAccessorPath<UntypedClientTable>(
Expand All @@ -100,8 +104,7 @@ export function useTable<TableDef extends UntypedTableDef>(
};

const setupTableListeners = () => {
const state = get(connectionStore);
const connection = state.getConnection();
const connection = currentState?.getConnection();
if (!connection) return;

const table = getByAccessorPath<UntypedClientTable>(
Expand All @@ -117,11 +120,8 @@ export function useTable<TableDef extends UntypedTableDef>(
if (whereExpr && !evaluateBooleanExpr(whereExpr, row)) return;
callbacks?.onInsert?.(row);

if (
eventCtx.event !== latestTransactionEvent ||
!latestTransactionEvent
) {
latestTransactionEvent = eventCtx.event;
if (eventCtx.event.id !== latestTransactionEventId) {
latestTransactionEventId = eventCtx.event.id;
rows.set(computeFilteredRows());
}
};
Expand All @@ -133,11 +133,8 @@ export function useTable<TableDef extends UntypedTableDef>(
if (whereExpr && !evaluateBooleanExpr(whereExpr, row)) return;
callbacks?.onDelete?.(row);

if (
eventCtx.event !== latestTransactionEvent ||
!latestTransactionEvent
) {
latestTransactionEvent = eventCtx.event;
if (eventCtx.event.id !== latestTransactionEventId) {
latestTransactionEventId = eventCtx.event.id;
rows.set(computeFilteredRows());
}
};
Expand All @@ -163,11 +160,8 @@ export function useTable<TableDef extends UntypedTableDef>(
return;
}

if (
eventCtx.event !== latestTransactionEvent ||
!latestTransactionEvent
) {
latestTransactionEvent = eventCtx.event;
if (eventCtx.event.id !== latestTransactionEventId) {
latestTransactionEventId = eventCtx.event.id;
rows.set(computeFilteredRows());
}
};
Expand All @@ -184,8 +178,7 @@ export function useTable<TableDef extends UntypedTableDef>(
};

const setupSubscription = () => {
const state = get(connectionStore);
const connection = state.getConnection();
const connection = currentState?.getConnection();
if (!connection) return;

subscriptionHandle = connection
Expand All @@ -203,6 +196,7 @@ export function useTable<TableDef extends UntypedTableDef>(
};

const unsubscribeConnection = connectionStore.subscribe(state => {
currentState = state;
const connection = state.getConnection();
isReady.set(
state.isActive && appliedConnectionId === state.connectionId.toHexString()
Expand Down Expand Up @@ -235,7 +229,7 @@ export function useTable<TableDef extends UntypedTableDef>(
unsubscribeConnection();
unsubscribeFromTable?.();
subscriptionHandle?.unsubscribe();
latestTransactionEvent = null;
latestTransactionEventId = null;
});

return [{ subscribe: rows.subscribe }, { subscribe: isReady.subscribe }];
Expand Down
Loading
Loading