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
9 changes: 9 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ members = [
"tools/xtask-llm-benchmark",
"crates/bindings-typescript/test-app/server",
"crates/bindings-typescript/test-react-router-app/server",
"crates/bindings-typescript/test-solid-router/server",
"crates/query-builder",
]
default-members = ["crates/cli", "crates/standalone", "crates/update"]
Expand Down
85 changes: 85 additions & 0 deletions crates/bindings-typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,91 @@ function App() {
}
```

#### SolidJS Usage

This module also includes SolidJS primitives to subscribe to tables under the `spacetimedb/solid` subpath. The SolidJS integration uses Solid's fine-grained reactivity system (`createSignal`, `createStore`, `createMemo`, `createComputed`) for optimal rendering performance. Reactive updates are scoped to only the data that actually changed.

In order to use SpacetimeDB SolidJS primitives in your project, first add a `SpacetimeDBProvider` at the top of your component hierarchy:

```tsx
import { SpacetimeDBProvider } from 'spacetimedb/solid';
import { DbConnection, tables } from './module_bindings';

const connectionBuilder = DbConnection.builder()
.withUri('ws://localhost:3000')
.withDatabaseName('MODULE_NAME')
.withLightMode(true)
.onDisconnect(() => {
console.log('disconnected');
})
.onConnectError(() => {
console.log('client_error');
})
.onConnect((conn, identity, _token) => {
console.log(
'Connected to SpacetimeDB with identity:',
identity.toHexString()
);

conn.subscriptionBuilder().subscribe(tables.player);
})
.withToken('TOKEN');

render(() => (
<SpacetimeDBProvider connectionBuilder={connectionBuilder}>
<App />
</SpacetimeDBProvider>
), document.getElementById('root')!);
```

Once you add a `SpacetimeDBProvider` to your hierarchy, you can use the SpacetimeDB SolidJS primitives in your components:

```tsx
import { useSpacetimeDB, useTable, useReducer, useProcedure } from 'spacetimedb/solid';

function App() {
// Access the connection state (identity, token, connection error, etc.)
const conn = useSpacetimeDB();

// Subscribe to a table — returns a reactive store of rows and an isReady accessor
const [rows, isReady] = useTable(() => tables.message);

// Subscribe to a filtered view
const [onlineUsers, onlineReady] = useTable(
() => tables.user.where(r => r.online.eq(true)),
{
onInsert: (row) => console.log('User came online:', row),
onDelete: (row) => console.log('User went offline:', row),
}
);

// Call a reducer — queues calls made before the connection is ready
const sendMessage = useReducer(reducers.sendMessage);

// Call a procedure — queues calls made before the connection is ready
const getResult = useProcedure(procedures.getSomeResult);

return (
<div>
<Show when={isReady()} fallback={<p>Loading...</p>}>
<p>{rows.length} messages</p>
<For each={rows}>
{(row) => <div>{row.text}</div>}
</For>
</Show>
<button onClick={() => sendMessage('hello')}>Send</button>
</div>
);
}
```

**Key differences from the React API:**

- `useTable` takes a _getter function_ `() => Query<TableDef>` instead of a plain value, so the query can be reactive and update when signals change.
- `useTable` returns `[rows, isReady]` where `rows` is a Solid reactive store and `isReady` is an accessor function `() => boolean`.
- The `enabled` callback option is a getter `() => boolean` instead of a plain boolean, allowing it to depend on reactive state.
- `useReducer` and `useProcedure` queue calls made before the connection is ready and flush them once connected.

### Developer notes

To run the tests, do:
Expand Down
10 changes: 10 additions & 0 deletions crates/bindings-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@
"import": "./dist/angular/index.mjs",
"require": "./dist/angular/index.cjs",
"default": "./dist/angular/index.mjs"
},
"./solid": {
"types": "./dist/solid/index.d.ts",
"import": "./dist/solid/index.mjs",
"require": "./dist/solid/index.cjs",
"default": "./dist/solid/index.mjs"
}
},
"size-limit": [
Expand Down Expand Up @@ -189,6 +195,7 @@
"@angular/core": ">=17.0.0",
"@tanstack/react-query": "^5.0.0",
"react": "^18.0.0 || ^19.0.0-0 || ^19.0.0",
"solid-js": "^1.6.0",
"svelte": "^4.0.0 || ^5.0.0",
"undici": "^6.19.2",
"vue": "^3.3.0"
Expand All @@ -200,6 +207,9 @@
"react": {
"optional": true
},
"solid-js": {
"optional": true
},
"svelte": {
"optional": true
},
Expand Down
97 changes: 97 additions & 0 deletions crates/bindings-typescript/src/solid/SpacetimeDBProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import {
DbConnectionBuilder,
type DbConnectionImpl,
} from '../sdk/db_connection_impl';
import { createEffect, onCleanup, createMemo, createComputed } from 'solid-js';
import { createStore } from 'solid-js/store';
import { SpacetimeDBContext } from './useSpacetimeDB';
import type { ConnectionState } from './connection_state';
import { ConnectionId } from '../lib/connection_id';
import {
ConnectionManager,
type ConnectionState as ManagerConnectionState,
} from '../sdk/connection_manager';

export interface SpacetimeDBProviderProps<
DbConnection extends DbConnectionImpl<any>,
> {
connectionBuilder: DbConnectionBuilder<DbConnection>;
children?: any;
}

export function SpacetimeDBProvider<DbConnection extends DbConnectionImpl<any>>(
props: SpacetimeDBProviderProps<DbConnection>
) {
const uri = () => props.connectionBuilder.getUri();
const moduleName = () => props.connectionBuilder.getModuleName();

const key = createMemo(() => ConnectionManager.getKey(uri(), moduleName()));

const fallbackState: ManagerConnectionState = {
isActive: false,
identity: undefined,
token: undefined,
connectionId: ConnectionId.random(),
connectionError: undefined,
};

const [state, setState] = createStore<ManagerConnectionState>(fallbackState);

// Subscribe to ConnectionManager state changes
createComputed(() => {
const currentKey = key();

const unsubscribe = ConnectionManager.subscribe(currentKey, () => {
const snapshot =
ConnectionManager.getSnapshot(currentKey) ?? fallbackState;
setState(snapshot);
});

// Load initial snapshot
const snapshot = ConnectionManager.getSnapshot(currentKey) ?? fallbackState;
setState(snapshot);

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

const getConnection = () =>
ConnectionManager.getConnection<DbConnection>(key());

const contextValue: ConnectionState = {
get isActive() {
return state.isActive;
},
get identity() {
return state.identity;
},
get token() {
return state.token;
},
get connectionId() {
return state.connectionId;
},
get connectionError() {
return state.connectionError;
},
getConnection,
};

// Retain / release lifecycle
createComputed(() => {
const currentKey = key();
ConnectionManager.retain(currentKey, props.connectionBuilder);

onCleanup(() => {
ConnectionManager.release(currentKey);
});
});

return SpacetimeDBContext.Provider({
value: contextValue,
get children() {
return props.children;
},
});
}
6 changes: 6 additions & 0 deletions crates/bindings-typescript/src/solid/connection_state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { DbConnectionImpl } from '../sdk/db_connection_impl';
import type { ConnectionState as ManagerConnectionState } from '../sdk/connection_manager';

export type ConnectionState = ManagerConnectionState & {
getConnection(): DbConnectionImpl<any> | null;
};
5 changes: 5 additions & 0 deletions crates/bindings-typescript/src/solid/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
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/solid/useProcedure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { createEffect } from 'solid-js';
import type { UntypedProcedureDef } from '../sdk/procedures';
import { useSpacetimeDB } from './useSpacetimeDB';
import type {
ProcedureParamsType,
ProcedureReturnType,
} from '../sdk/type_utils';

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

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

// Flush when we finally have a connection
createEffect(() => {
if (!isActive) return;

const conn = getConnection();
if (!conn) return;

const fn = (conn.procedures as any)[procedureName] as (
...p: ProcedureParamsType<ProcedureDef>
) => Promise<ProcedureReturnType<ProcedureDef>>;

if (queue.length) {
const pending = queue.splice(0);
for (const item of pending) {
fn(...item.params).then(item.resolve, item.reject);
}
}
});

return (...params: ProcedureParamsType<ProcedureDef>) => {
const conn = getConnection();
if (!conn) {
return new Promise<ProcedureReturnType<ProcedureDef>>(
(resolve, reject) => {
queue.push({ params, resolve, reject });
}
);
}
const fn = (conn.procedures as any)[procedureName] as (
...p: ProcedureParamsType<ProcedureDef>
) => Promise<ProcedureReturnType<ProcedureDef>>;
return fn(...params);
};
}
50 changes: 50 additions & 0 deletions crates/bindings-typescript/src/solid/useReducer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { createEffect } from 'solid-js';
import type { UntypedReducerDef } from '../sdk/reducers';
import { useSpacetimeDB } from './useSpacetimeDB';
import type { ParamsType } from '../sdk';

export function useReducer<ReducerDef extends UntypedReducerDef>(
reducerDef: ReducerDef
): (...params: ParamsType<ReducerDef>) => Promise<void> {
const { getConnection, isActive } = useSpacetimeDB();
const reducerName = reducerDef.accessorName;

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

// Flush when we finally have a connection
createEffect(() => {
if (!isActive) return;

const conn = getConnection();
if (!conn) return;

const fn = (conn.reducers as any)[reducerName] as (
...p: ParamsType<ReducerDef>
) => Promise<void>;

if (queue.length) {
const pending = queue.splice(0);
for (const item of pending) {
fn(...item.params).then(item.resolve, item.reject);
}
}
});

return (...params: ParamsType<ReducerDef>) => {
const conn = getConnection();
if (!conn) {
return new Promise<void>((resolve, reject) => {
queue.push({ params, resolve, reject });
});
}
const fn = (conn.reducers as any)[reducerName] as (
...p: ParamsType<ReducerDef>
) => Promise<void>;
return fn(...params);
};
}
18 changes: 18 additions & 0 deletions crates/bindings-typescript/src/solid/useSpacetimeDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createContext, useContext } from 'solid-js';
import type { ConnectionState } from './connection_state';

export const SpacetimeDBContext = createContext<ConnectionState | undefined>(
undefined
);

// Throws an error if used outside of a SpacetimeDBProvider
// Error is caught by other hooks like useTable so they can provide better error messages
export function useSpacetimeDB(): ConnectionState {
const context = useContext(SpacetimeDBContext) as ConnectionState | undefined;
if (!context) {
throw new Error(
'useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?'
);
}
return context;
}
Loading