@spooky-sync/client-svelte 0.0.0-stage → 0.0.1-canary.384
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +118 -0
- package/QUICK_START.md +153 -0
- package/README.md +63 -2
- package/dist/Blurhash.svelte +25 -0
- package/dist/Blurhash.svelte.d.ts +18 -0
- package/dist/BucketImage.svelte +57 -0
- package/dist/BucketImage.svelte.d.ts +32 -0
- package/dist/Sp00kyProvider.svelte +50 -0
- package/dist/Sp00kyProvider.svelte.d.ts +26 -0
- package/dist/context.d.ts +28 -0
- package/dist/context.js +31 -0
- package/dist/db.d.ts +124 -0
- package/dist/db.js +275 -0
- package/dist/files.svelte.d.ts +106 -0
- package/dist/files.svelte.js +292 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +12 -0
- package/dist/query.svelte.d.ts +130 -0
- package/dist/query.svelte.js +266 -0
- package/dist/realtime.svelte.d.ts +51 -0
- package/dist/realtime.svelte.js +141 -0
- package/dist/status.svelte.d.ts +185 -0
- package/dist/status.svelte.js +314 -0
- package/dist/types.d.ts +62 -0
- package/dist/types.js +1 -0
- package/package.json +70 -4
- package/skills/sp00ky-svelte/SKILL.md +84 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# `@spooky-sync/client-svelte`: agent guide
|
|
2
|
+
|
|
3
|
+
## What this package is
|
|
4
|
+
|
|
5
|
+
The **Svelte 5** binding for sp00ky, built on runes (peer `svelte@^5.29.0`; Svelte 4 is not supported). Same `SyncedDb` and the same hook set as `@spooky-sync/client-react` / `client-solid2`, written the Svelte way:
|
|
6
|
+
|
|
7
|
+
- A hook returns an object whose fields are **reactive getters**: `posts.data`, `posts.isLoading`. Read them in markup, `$derived` or `$effect`. **Never destructure** a result: `const { data } = useQuery(...)` is a one-time copy.
|
|
8
|
+
- An input that should follow state is a **getter**: `useQuery(() => db.query('post').where({ author: id }).build())`, `useCrdtField('post', () => postId, 'body')`, `useDownloadFile('covers', () => path)`. A plain value is read once.
|
|
9
|
+
- A hook with a single value returns `{ current }` (the `svelte/reactivity` convention): `usePendingMutations().current`, `useCrdtField(...).current`.
|
|
10
|
+
|
|
11
|
+
Browser only. The core client runs SurrealDB / SQLite as WebAssembly with IndexedDB / OPFS and web workers, and does not load on the server. In SvelteKit set `export const ssr = false` in the root `+layout.ts`.
|
|
12
|
+
|
|
13
|
+
Internals: `useQuery` keeps rows in `$state.raw` and structurally shares each live emission with the previous one (`share` in `src/query.svelte.ts`): rows matched by `id` keep their object identity, a deep-equal emission is the same value, rows are plain objects (never deep proxies). Status hooks are built on `createSubscriber` (subscribed only while read, reading the engine's own current value). Registrations, CRDT fields, channels and file leases live in `$effect` and end with the component. `SyncedDb` writes copy plain objects / arrays (`plain()`) so a `$state` proxy never reaches the workers, leaving `RecordId` / `Date` / bytes untouched (`$state.snapshot` would turn a RecordId into a string via `toJSON`).
|
|
14
|
+
|
|
15
|
+
The package ships Svelte source built by `svelte-package` (`.svelte`, `.svelte.js`, `.d.ts`; `svelte` export condition), compiled by the app's own compiler.
|
|
16
|
+
|
|
17
|
+
## Setup pattern
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
// src/lib/db.ts
|
|
21
|
+
import type { SyncedDbConfig } from '@spooky-sync/client-svelte';
|
|
22
|
+
import { schema, SURQL_SCHEMA } from './schema.gen'; // generated by `spky generate`
|
|
23
|
+
|
|
24
|
+
export const dbConfig: SyncedDbConfig<typeof schema> = {
|
|
25
|
+
schema,
|
|
26
|
+
schemaSurql: SURQL_SCHEMA,
|
|
27
|
+
database: {
|
|
28
|
+
namespace: 'main',
|
|
29
|
+
database: 'app',
|
|
30
|
+
endpoint: 'ws://localhost:8666/rpc',
|
|
31
|
+
store: 'indexeddb',
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```svelte
|
|
37
|
+
<!-- src/routes/+layout.svelte -->
|
|
38
|
+
<script lang="ts">
|
|
39
|
+
import { Sp00kyProvider } from '@spooky-sync/client-svelte';
|
|
40
|
+
import { dbConfig } from '$lib/db';
|
|
41
|
+
let { children } = $props();
|
|
42
|
+
</script>
|
|
43
|
+
|
|
44
|
+
<Sp00kyProvider config={dbConfig}>
|
|
45
|
+
{#snippet fallback()}<Splash />{/snippet}
|
|
46
|
+
{@render children()}
|
|
47
|
+
</Sp00kyProvider>
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Provider props: `config` (read once at mount; wrap in `{#key}` to switch databases), `fallback` (snippet), `preload` (awaited before children render, best-effort), `onReady`, `onError`, `children`. The client is created in `onMount`, so server renders show the fallback. A client that was handed to the tree is deliberately not closed on destroy; one whose init outlived the provider is.
|
|
51
|
+
|
|
52
|
+
Without the provider: create `new SyncedDb(config)`, `await db.init()` (e.g. in a SvelteKit `load`), and call `setDbContext(db)` while the root layout initialises.
|
|
53
|
+
|
|
54
|
+
Vite needs `vite-plugin-wasm`, `build.target: 'esnext'`, `optimizeDeps.exclude: ['@spooky-sync/client-svelte', '@spooky-sync/core', '@spooky-sync/ssp-wasm', '@surrealdb/wasm', '@surrealdb/wasm-native', '@sqlite.org/sqlite-wasm']` and `optimizeDeps.include: ['@spooky-sync/core > pino', '@spooky-sync/core > fast-json-patch']`. Pre-bundled, the client looks for its `.wasm` files and workers in the wrong folder (dev only: a 404 or `expected magic word`); `vite-plugin-top-level-await` is not needed and crashes with current `@swc/core`.
|
|
55
|
+
|
|
56
|
+
## Key API
|
|
57
|
+
|
|
58
|
+
Hooks that read context (`useDb`, and every hook without an explicit `db`) or open something must run while a component initialises (top level of `<script>`), or inside `$effect.root` with an explicit `db`.
|
|
59
|
+
|
|
60
|
+
- **`useDb<typeof schema>()`**: the `SyncedDb<S>`. `create`, `update`, `delete`, `query`, `preload`, `run`, `channel`, `bucket`, `remoteQuery`, `useRemote`, `auth` / `signOut`, `pendingMutationCount`, `syncHealth` / `storageHealth` and their subscribe methods. Throws outside a provider.
|
|
61
|
+
- **`useQuery(query, options?)`** (or `useQuery(db, query, options?)`): live query. `query` is a getter returning a BUILT query (`.build()`, `.one().build()`) or `null` / `undefined` to skip; a fixed built query can be passed directly. Re-registration keys on the identity hash (surql + vars), not on rebuilds. Result getters:
|
|
62
|
+
- `data`: rows, or the row / `null` for `.one()`. `[]` / `null` before the first result. Structurally shared.
|
|
63
|
+
- `error`: registration / sync failure (e.g. SSP 503 NOT_READY). Never thrown; the scheduler retries.
|
|
64
|
+
- `isLoading`: cold first load only (nothing painted for this identity, server not heard, no error).
|
|
65
|
+
- `isFetching`: a fetch cycle is in flight.
|
|
66
|
+
- `isAuthoritative`: `data` holds the rendered rows of a known membership. Latched until the identity changes.
|
|
67
|
+
- `hasData`: rows for a list, a row for `.one()`.
|
|
68
|
+
- `isEmpty`: authoritative AND no data. Empty states go on this, never on `!hasData`.
|
|
69
|
+
- `isSettled`: authoritative AND idle. Gate windowed-list end detection and create-if-missing on it. Not monotonic.
|
|
70
|
+
- Options: `enabled?: boolean | (() => boolean)`, `deregisterOnCleanup?: boolean`.
|
|
71
|
+
- On an identity change the previous `data` stays until the new identity emits (flags reset), so growing `.limit()` never flashes empty.
|
|
72
|
+
- **`usePreload(query, options?)`** (or `(db, query, options?)`): fire-and-forget prewarm of a likely-next query, keyed on its identity. Options: `enabled?`, `signal?`.
|
|
73
|
+
- **`useSubmission(fn)`**: `{ submit, pending, error, result, clearError }`. `submit` never rejects. Needs no component or provider.
|
|
74
|
+
- **`usePendingMutations(db?)`**: `{ current: number }`.
|
|
75
|
+
- **`useSyncStatus(db?)`**: `{ health, status, isHealthy, isDegraded, everConnected, isOffline, connection, isReconnecting }`. With an explicit `db` it works in a shared `.svelte.ts` module.
|
|
76
|
+
- **`useSyncActivity(options?)`** (or `(db, options?)`): `{ fetchingQueries, pendingMutations, isDownloading, isUploading }`, debounced on (`downloadDelayMs` 200, `uploadDelayMs` 150, `uploadThreshold` 0), off at once. Owns timers: component init or `$effect.root`.
|
|
77
|
+
- **`useStorageStatus(db?)`**: `{ health, status, isPersistent, isMemoryFallback }`.
|
|
78
|
+
- **`useImpersonation({ rendersBanner? }, db?)`**: `{ impersonation, isImpersonating, stop }`.
|
|
79
|
+
- **`useFeatureFlag(key, { fallback?, ttl? }, db?)`**: `{ variant, payload, enabled }`. The handle closes with the component.
|
|
80
|
+
- **`useAppRelease({ app, currentVersion, ttl? }, db?)`**: `{ latestVersion, updateAvailable, mandatory, cacheBust, reload }`.
|
|
81
|
+
- **`useCrdtField(table, recordId, field, db?)`**: `{ current: CrdtField | null }`, `null` until loaded. `recordId` is a getter (or value).
|
|
82
|
+
- **`useChannel(query, peers, db?)`** (experimental): WebRTC channel for the component's lifetime for the rows `query` matches (a builder, built query, or list, on a `-- @channel` table; only its `where` counts; `null` closes it). Both arguments may be getters, compared by value. Returns `{ status, peers, update, create, delete }`. See `/docs/client/channels`.
|
|
83
|
+
- **Files**: `useFileUpload(bucket)` (`{ upload, download, remove, exists, isUploading, error, clearError }`, validates `maxSize` / `allowedExtensions`), `useDownloadFile(bucket, path, options?)` (`{ url, isLoading, error, refetch }`, refcounted shared object URL, OPFS-persisted by default, previous URL kept until the next is ready), `useBlurhash(bucket, path)`, `useBucketImage(bucket, path, options?)` (adds `blurhash`, `ready`, and `gate`, an attachment: `<img {@attach image.gate} alt="" />` that sets `src` itself; do not also bind `src`). Every file hook also takes `(db, bucket, ...)`; `path` is a getter or value.
|
|
84
|
+
- **Components**: `<BucketImage bucket path class imgClass fit transition easing blurhash options>` with an optional `fallback` snippet; `<Blurhash hash width height punch class style />`.
|
|
85
|
+
- **`setDbContext(db)`**: provide a self-created client to the tree instead of rendering `<Sp00kyProvider>`.
|
|
86
|
+
- **`plain(value)`**, **`share(prev, next)`**, **`sameValue(a, b)`**: the pure helpers above, exported for tests and custom stores.
|
|
87
|
+
|
|
88
|
+
## Mutations
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
await db.create('post:' + crypto.randomUUID(), { title: 'Hi' });
|
|
92
|
+
await db.update('post', 'post:xyz', { title: 'Edited' });
|
|
93
|
+
await db.delete('post', row.id); // a row's RecordId works directly
|
|
94
|
+
await db.run('backend', 'sendMail', { to });
|
|
95
|
+
|
|
96
|
+
let draft = $state({ title: '' });
|
|
97
|
+
await db.create('post:' + crypto.randomUUID(), draft); // proxies are copied, fine
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Track a backend job by querying its outbox row: `useQuery(() => db.query('job_outbox').where({ id: jobId }).one().build())`.
|
|
101
|
+
|
|
102
|
+
## Common gotchas
|
|
103
|
+
|
|
104
|
+
- **Queries need `.build()`** (or `.one().build()`). A bare `db.query('post')` is a builder.
|
|
105
|
+
- **Pass a getter**, not a value, when the query depends on props or state; `useQuery(db.query('post').where({ id }).build())` captures `id` once.
|
|
106
|
+
- **Do not destructure** results; read `result.field`.
|
|
107
|
+
- **Call hooks during component init**, not in event handlers or after `await`.
|
|
108
|
+
- **No suspense mode.** There is no `ready()` like Solid 2; branch on `isLoading` / `isEmpty`.
|
|
109
|
+
- **`config` is read once.** Changing the provider's `config` does nothing; remount it with `{#key}`.
|
|
110
|
+
- **SvelteKit SSR must be off** for routes that render the provider (`export const ssr = false`).
|
|
111
|
+
- **Keys**: row ids are `RecordId` instances; use `{#each rows as row (String(row.id))}`.
|
|
112
|
+
|
|
113
|
+
## Pointers
|
|
114
|
+
|
|
115
|
+
- Walkthrough: `QUICK_START.md` (same content as the docs' [Svelte guide](https://mono424.github.io/sp00ky/docs/guide/svelte))
|
|
116
|
+
- Skill for coding agents: `skills/sp00ky-svelte/SKILL.md`
|
|
117
|
+
- Sync engine: `node_modules/@spooky-sync/core/AGENTS.md`
|
|
118
|
+
- Query builder DSL: `node_modules/@spooky-sync/query-builder/AGENTS.md`
|
package/QUICK_START.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Quick start: Sp00ky with Svelte 5
|
|
2
|
+
|
|
3
|
+
The same content as the docs' [Svelte guide](https://mono424.github.io/sp00ky/docs/guide/svelte).
|
|
4
|
+
|
|
5
|
+
## 1. Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @spooky-sync/core @spooky-sync/client-svelte
|
|
9
|
+
pnpm add -D vite-plugin-wasm
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## 2. Configure Vite
|
|
13
|
+
|
|
14
|
+
The core client loads its engines as WebAssembly and starts web workers, both found next to its own files. Keep the client's packages out of dependency pre-bundling (pre-bundled, they look in the wrong folder), pre-bundle the core's CommonJS dependencies instead, and build for `esnext`:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
// vite.config.ts
|
|
18
|
+
import { defineConfig } from 'vite';
|
|
19
|
+
import { svelte } from '@sveltejs/vite-plugin-svelte'; // SvelteKit: sveltekit() from '@sveltejs/kit/vite'
|
|
20
|
+
import wasm from 'vite-plugin-wasm';
|
|
21
|
+
|
|
22
|
+
export default defineConfig({
|
|
23
|
+
plugins: [svelte(), wasm()],
|
|
24
|
+
optimizeDeps: {
|
|
25
|
+
// Served as is: pre-bundled, these look for their .wasm files and
|
|
26
|
+
// workers in the wrong folder.
|
|
27
|
+
exclude: [
|
|
28
|
+
'@spooky-sync/client-svelte',
|
|
29
|
+
'@spooky-sync/core',
|
|
30
|
+
'@spooky-sync/ssp-wasm',
|
|
31
|
+
'@surrealdb/wasm',
|
|
32
|
+
'@surrealdb/wasm-native',
|
|
33
|
+
'@sqlite.org/sqlite-wasm',
|
|
34
|
+
],
|
|
35
|
+
// The excluded core's CommonJS dependencies, pre-bundled for it.
|
|
36
|
+
include: ['@spooky-sync/core > pino', '@spooky-sync/core > fast-json-patch'],
|
|
37
|
+
},
|
|
38
|
+
// The client uses top-level await.
|
|
39
|
+
build: { target: 'esnext' },
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
In SvelteKit the client is browser-only, so turn server rendering off:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// src/routes/+layout.ts
|
|
47
|
+
export const ssr = false;
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## 3. Generate types and configure the client
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
spky generate
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// src/lib/db.ts
|
|
58
|
+
import type { SyncedDbConfig } from '@spooky-sync/client-svelte';
|
|
59
|
+
import { schema, SURQL_SCHEMA } from './schema.gen';
|
|
60
|
+
|
|
61
|
+
export const dbConfig: SyncedDbConfig<typeof schema> = {
|
|
62
|
+
schema,
|
|
63
|
+
schemaSurql: SURQL_SCHEMA,
|
|
64
|
+
database: {
|
|
65
|
+
namespace: 'main',
|
|
66
|
+
database: 'main',
|
|
67
|
+
endpoint: 'ws://localhost:8666/rpc', // spky dev
|
|
68
|
+
store: 'indexeddb',
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 4. Mount the provider
|
|
74
|
+
|
|
75
|
+
```svelte
|
|
76
|
+
<!-- src/routes/+layout.svelte -->
|
|
77
|
+
<script lang="ts">
|
|
78
|
+
import { Sp00kyProvider } from '@spooky-sync/client-svelte';
|
|
79
|
+
import { dbConfig } from '$lib/db';
|
|
80
|
+
|
|
81
|
+
let { children } = $props();
|
|
82
|
+
</script>
|
|
83
|
+
|
|
84
|
+
<Sp00kyProvider config={dbConfig} onError={(e) => console.error(e)}>
|
|
85
|
+
{#snippet fallback()}<div>Initializing database…</div>{/snippet}
|
|
86
|
+
{@render children()}
|
|
87
|
+
</Sp00kyProvider>
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`config` is read once at mount (wrap the provider in `{#key}` to switch databases). `preload` is
|
|
91
|
+
awaited before the children render. The client is created in `onMount`, so a server render only
|
|
92
|
+
shows the fallback.
|
|
93
|
+
|
|
94
|
+
## 5. Query
|
|
95
|
+
|
|
96
|
+
```svelte
|
|
97
|
+
<script lang="ts">
|
|
98
|
+
import { useDb, useQuery } from '@spooky-sync/client-svelte';
|
|
99
|
+
import type { schema } from '$lib/schema.gen';
|
|
100
|
+
|
|
101
|
+
let { authorId }: { authorId: string | null } = $props();
|
|
102
|
+
const db = useDb<typeof schema>();
|
|
103
|
+
|
|
104
|
+
// A getter: re-read when `authorId` changes, re-registered only when the
|
|
105
|
+
// query's identity (surql + vars) changes. Returning null skips.
|
|
106
|
+
const posts = useQuery(() =>
|
|
107
|
+
authorId ? db.query('post').where({ author: authorId }).limit(20).build() : null
|
|
108
|
+
);
|
|
109
|
+
</script>
|
|
110
|
+
|
|
111
|
+
{#if posts.isLoading}
|
|
112
|
+
<p>Loading…</p>
|
|
113
|
+
{:else if posts.isEmpty}
|
|
114
|
+
<p>Nothing here.</p>
|
|
115
|
+
{:else}
|
|
116
|
+
{#each posts.data as post (String(post.id))}<p>{post.title}</p>{/each}
|
|
117
|
+
{/if}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Fields are getters: never `const { data } = useQuery(...)`, that copy never updates.
|
|
121
|
+
|
|
122
|
+
## 6. Write
|
|
123
|
+
|
|
124
|
+
```svelte
|
|
125
|
+
<script lang="ts">
|
|
126
|
+
import { useDb, useSubmission } from '@spooky-sync/client-svelte';
|
|
127
|
+
|
|
128
|
+
const db = useDb<typeof schema>();
|
|
129
|
+
let title = $state('');
|
|
130
|
+
const save = useSubmission((t: string) =>
|
|
131
|
+
db.create('post:' + crypto.randomUUID(), { title: t })
|
|
132
|
+
);
|
|
133
|
+
</script>
|
|
134
|
+
|
|
135
|
+
<input bind:value={title} />
|
|
136
|
+
<button disabled={save.pending} onclick={() => save.submit(title)}>Save</button>
|
|
137
|
+
{#if save.error}<p>{save.error.message}</p>{/if}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The write commits locally first; the live query above re-renders before the server confirms.
|
|
141
|
+
|
|
142
|
+
## 7. Status
|
|
143
|
+
|
|
144
|
+
```svelte
|
|
145
|
+
<script lang="ts">
|
|
146
|
+
import { useSyncStatus, usePendingMutations } from '@spooky-sync/client-svelte';
|
|
147
|
+
|
|
148
|
+
const sync = useSyncStatus();
|
|
149
|
+
const pending = usePendingMutations();
|
|
150
|
+
</script>
|
|
151
|
+
|
|
152
|
+
{#if sync.isDegraded}<div>Offline, {pending.current} change(s) queued.</div>{/if}
|
|
153
|
+
```
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spooky-sync/client-svelte
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Svelte 5 bindings for the Sp00ky reactive local-first SurrealDB framework, built on runes. Needs
|
|
4
|
+
Svelte 5.29 or newer (attachments); Svelte 4 is not supported. Browser only: the core client runs
|
|
5
|
+
its engines as WebAssembly with IndexedDB / OPFS storage, so in SvelteKit turn server rendering off
|
|
6
|
+
(`export const ssr = false` in the root `+layout.ts`).
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pnpm add @spooky-sync/core @spooky-sync/client-svelte
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```svelte
|
|
13
|
+
<!-- Posts.svelte -->
|
|
14
|
+
<script lang="ts">
|
|
15
|
+
import { useDb, useQuery } from '@spooky-sync/client-svelte';
|
|
16
|
+
|
|
17
|
+
const db = useDb<typeof schema>();
|
|
18
|
+
const posts = useQuery(() => db.query('post').orderBy('created_at', 'desc').limit(20).build());
|
|
19
|
+
</script>
|
|
20
|
+
|
|
21
|
+
{#if posts.isLoading}
|
|
22
|
+
<p>Loading…</p>
|
|
23
|
+
{:else if posts.isEmpty}
|
|
24
|
+
<p>No posts yet.</p>
|
|
25
|
+
{:else}
|
|
26
|
+
<ul>
|
|
27
|
+
{#each posts.data as post (String(post.id))}<li>{post.title}</li>{/each}
|
|
28
|
+
</ul>
|
|
29
|
+
{/if}
|
|
30
|
+
|
|
31
|
+
<!-- +layout.svelte -->
|
|
32
|
+
<Sp00kyProvider config={dbConfig}>
|
|
33
|
+
{#snippet fallback()}<Splash />{/snippet}
|
|
34
|
+
{@render children()}
|
|
35
|
+
</Sp00kyProvider>
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
What "native" means here:
|
|
39
|
+
|
|
40
|
+
- Runes, no stores. A hook returns an object whose fields are reactive getters (`posts.data`,
|
|
41
|
+
`posts.isLoading`); inputs that follow state are getters (`() => db.query(...).build()`).
|
|
42
|
+
- `useQuery` keeps rows in `$state.raw` with structural sharing between live emissions: rows are
|
|
43
|
+
matched by `id`, unchanged rows keep their object identity (a keyed `{#each}` only updates what
|
|
44
|
+
changed), and a deep-equal emission changes nothing. Rows are plain objects, never proxies.
|
|
45
|
+
- Status hooks (`useSyncStatus`, `usePendingMutations`, `useStorageStatus`, ...) are built on
|
|
46
|
+
`createSubscriber`: subscribed only while read, always the engine's current value.
|
|
47
|
+
- Registrations, CRDT fields, channels and file leases live in `$effect` and end with the component.
|
|
48
|
+
- Writes copy `$state` proxies before they reach the core's workers, leaving `RecordId`, `Date` and
|
|
49
|
+
bytes as they are.
|
|
50
|
+
- Mutations stay plain `await db.create(...)` calls: the engine is already optimistic local-first.
|
|
51
|
+
`useSubmission` only adds button pending and error state.
|
|
52
|
+
|
|
53
|
+
The query flags (`isLoading`, `isFetching`, `isAuthoritative`, `hasData`, `isEmpty`, `isSettled`)
|
|
54
|
+
follow the same contract as `@spooky-sync/client-react` and `client-solid2`.
|
|
55
|
+
|
|
56
|
+
The package ships Svelte source (`.svelte`, `.svelte.js`) built by `svelte-package`, compiled by the
|
|
57
|
+
app's own Svelte compiler. See `QUICK_START.md` for a walkthrough, `AGENTS.md` for the full API, and
|
|
58
|
+
the [Svelte guide](https://mono424.github.io/sp00ky/docs/guide/svelte).
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pnpm --filter @spooky-sync/client-svelte test
|
|
62
|
+
pnpm --filter @spooky-sync/client-svelte type-check
|
|
63
|
+
pnpm --filter @spooky-sync/client-svelte build
|
|
64
|
+
```
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<script lang="ts" module></script>
|
|
2
|
+
|
|
3
|
+
<script lang="ts">import { decodeBlurhash } from "@spooky-sync/core";
|
|
4
|
+
let { hash, width = 32, height = 32, punch = 1, class: className, style } = $props();
|
|
5
|
+
function paint(canvas) {
|
|
6
|
+
canvas.width = width;
|
|
7
|
+
canvas.height = height;
|
|
8
|
+
if (!hash) return;
|
|
9
|
+
try {
|
|
10
|
+
const pixels = decodeBlurhash(hash, width, height, punch);
|
|
11
|
+
const ctx = canvas.getContext("2d");
|
|
12
|
+
if (!ctx) return;
|
|
13
|
+
const imageData = ctx.createImageData(width, height);
|
|
14
|
+
imageData.data.set(pixels);
|
|
15
|
+
ctx.putImageData(imageData, 0, 0);
|
|
16
|
+
} catch {
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
</script>
|
|
20
|
+
|
|
21
|
+
<!--
|
|
22
|
+
A blurhash painted onto a canvas. Size it with `class` / `style` (e.g.
|
|
23
|
+
`absolute inset-0 w-full h-full`); the decode resolution stays tiny.
|
|
24
|
+
-->
|
|
25
|
+
<canvas class={className} {style} {@attach paint}></canvas>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ClassValue } from 'svelte/elements';
|
|
2
|
+
export interface BlurhashProps {
|
|
3
|
+
/** The blurhash string. Nullish paints nothing (transparent canvas). */
|
|
4
|
+
hash: string | null | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Decode resolution. 32x32 is plenty: a blurhash carries at most 9x9 DCT
|
|
7
|
+
* components, and the canvas is meant to be CSS-scaled to fill.
|
|
8
|
+
*/
|
|
9
|
+
width?: number;
|
|
10
|
+
height?: number;
|
|
11
|
+
/** Contrast punch, see the blurhash reference decoder. Defaults to 1. */
|
|
12
|
+
punch?: number;
|
|
13
|
+
class?: ClassValue;
|
|
14
|
+
style?: string;
|
|
15
|
+
}
|
|
16
|
+
declare const Blurhash: import("svelte").Component<BlurhashProps, {}, "">;
|
|
17
|
+
type Blurhash = ReturnType<typeof Blurhash>;
|
|
18
|
+
export default Blurhash;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
<script lang="ts" module></script>
|
|
2
|
+
|
|
3
|
+
<script lang="ts">import { untrack } from "svelte";
|
|
4
|
+
import { prefersReducedMotion } from "svelte/motion";
|
|
5
|
+
import { useBucketImage } from "./files.svelte.js";
|
|
6
|
+
import Blurhash from "./Blurhash.svelte";
|
|
7
|
+
let {
|
|
8
|
+
bucket,
|
|
9
|
+
path,
|
|
10
|
+
alt = "",
|
|
11
|
+
class: className,
|
|
12
|
+
imgClass,
|
|
13
|
+
fit = "cover",
|
|
14
|
+
fallback,
|
|
15
|
+
transition = 300,
|
|
16
|
+
easing = "cubic-bezier(0.16, 1, 0.3, 1)",
|
|
17
|
+
blurhash = true,
|
|
18
|
+
options
|
|
19
|
+
} = $props();
|
|
20
|
+
const LAYER = "position:absolute;inset:0;width:100%;height:100%;";
|
|
21
|
+
const image = untrack(
|
|
22
|
+
() => useBucketImage(bucket, () => path, { ...options, blurhash })
|
|
23
|
+
);
|
|
24
|
+
let settled = $state(false);
|
|
25
|
+
$effect(() => {
|
|
26
|
+
if (!image.ready) {
|
|
27
|
+
settled = false;
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const wait = (prefersReducedMotion.current ? 0 : transition) + 120;
|
|
31
|
+
const timer = setTimeout(() => settled = true, wait);
|
|
32
|
+
return () => clearTimeout(timer);
|
|
33
|
+
});
|
|
34
|
+
const imgStyle = $derived(
|
|
35
|
+
LAYER + `object-fit:${fit};opacity:${image.ready ? 1 : 0};transition:${prefersReducedMotion.current ? "none" : `opacity ${transition}ms ${easing}`};`
|
|
36
|
+
);
|
|
37
|
+
function anchor(node) {
|
|
38
|
+
if (getComputedStyle(node).position === "static") node.style.position = "relative";
|
|
39
|
+
}
|
|
40
|
+
</script>
|
|
41
|
+
|
|
42
|
+
<!--
|
|
43
|
+
A bucket image that never pops in: bottom to top, your `fallback` plate, the
|
|
44
|
+
stored blurhash, and the real image, which stays transparent until its bitmap
|
|
45
|
+
is DECODED and then crossfades over the placeholders.
|
|
46
|
+
-->
|
|
47
|
+
<div class={className} {@attach anchor}>
|
|
48
|
+
{#if !settled}
|
|
49
|
+
<div style={LAYER}>
|
|
50
|
+
{#if fallback}
|
|
51
|
+
<div style={LAYER}>{@render fallback()}</div>
|
|
52
|
+
{/if}
|
|
53
|
+
<Blurhash hash={image.blurhash} style={LAYER} />
|
|
54
|
+
</div>
|
|
55
|
+
{/if}
|
|
56
|
+
<img class={imgClass} {alt} decoding="async" style={imgStyle} {@attach image.gate} />
|
|
57
|
+
</div>
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Snippet } from 'svelte';
|
|
2
|
+
import type { ClassValue } from 'svelte/elements';
|
|
3
|
+
import type { UseBucketImageOptions } from './files.svelte.js';
|
|
4
|
+
export interface BucketImageProps {
|
|
5
|
+
/** Bucket name from the schema. */
|
|
6
|
+
bucket: string;
|
|
7
|
+
/** Path within the bucket. Nullish renders only the placeholder layers. */
|
|
8
|
+
path: string | null | undefined;
|
|
9
|
+
alt?: string;
|
|
10
|
+
/** Classes for the container element (sizing / positioning). */
|
|
11
|
+
class?: ClassValue;
|
|
12
|
+
/** Classes for the inner `<img>` (the layout styles are inline). */
|
|
13
|
+
imgClass?: ClassValue;
|
|
14
|
+
/** `object-fit` for the image. Defaults to `cover`. */
|
|
15
|
+
fit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down';
|
|
16
|
+
/**
|
|
17
|
+
* Bottom placeholder layer (your own plate / skeleton), shown until the
|
|
18
|
+
* image settles. The blurhash paints on top of it once the sidecar resolves.
|
|
19
|
+
*/
|
|
20
|
+
fallback?: Snippet;
|
|
21
|
+
/** Crossfade duration in ms. Defaults to 300. */
|
|
22
|
+
transition?: number;
|
|
23
|
+
/** Crossfade easing. Defaults to an ease-out-expo curve. */
|
|
24
|
+
easing?: string;
|
|
25
|
+
/** Resolve the blurhash sidecar. Defaults to true. */
|
|
26
|
+
blurhash?: boolean;
|
|
27
|
+
/** Download tuning, forwarded to `useDownloadFile`. Read once. */
|
|
28
|
+
options?: UseBucketImageOptions;
|
|
29
|
+
}
|
|
30
|
+
declare const BucketImage: import("svelte").Component<BucketImageProps, {}, "">;
|
|
31
|
+
type BucketImage = ReturnType<typeof BucketImage>;
|
|
32
|
+
export default BucketImage;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
<script lang="ts" generics="S extends SchemaStructure">import { onMount } from "svelte";
|
|
2
|
+
import { SyncedDb } from "./db.js";
|
|
3
|
+
import { setDbContext } from "./context.js";
|
|
4
|
+
let { config, fallback, onError, onReady, preload, children } = $props();
|
|
5
|
+
let db = $state.raw(void 0);
|
|
6
|
+
setDbContext({
|
|
7
|
+
get db() {
|
|
8
|
+
return db;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
onMount(() => {
|
|
12
|
+
let destroyed = false;
|
|
13
|
+
void (async () => {
|
|
14
|
+
try {
|
|
15
|
+
const instance = new SyncedDb(config);
|
|
16
|
+
await instance.init();
|
|
17
|
+
if (destroyed) {
|
|
18
|
+
await instance.close();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (preload) {
|
|
22
|
+
try {
|
|
23
|
+
await preload(instance);
|
|
24
|
+
} catch (e) {
|
|
25
|
+
console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (destroyed) {
|
|
29
|
+
await instance.close();
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
db = instance;
|
|
33
|
+
onReady?.(instance);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
36
|
+
if (onError) onError(error);
|
|
37
|
+
else console.error("Sp00kyProvider: Failed to initialize database", error);
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
|
+
return () => {
|
|
41
|
+
destroyed = true;
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
</script>
|
|
45
|
+
|
|
46
|
+
{#if db}
|
|
47
|
+
{@render children()}
|
|
48
|
+
{:else}
|
|
49
|
+
{@render fallback?.()}
|
|
50
|
+
{/if}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { Sp00kyProviderProps } from './types.js';
|
|
3
|
+
declare function $$render<S extends SchemaStructure>(): {
|
|
4
|
+
props: Sp00kyProviderProps<S>;
|
|
5
|
+
exports: {};
|
|
6
|
+
bindings: "";
|
|
7
|
+
slots: {};
|
|
8
|
+
events: {};
|
|
9
|
+
};
|
|
10
|
+
declare class __sveltets_Render<S extends SchemaStructure> {
|
|
11
|
+
props(): ReturnType<typeof $$render<S>>['props'];
|
|
12
|
+
events(): ReturnType<typeof $$render<S>>['events'];
|
|
13
|
+
slots(): ReturnType<typeof $$render<S>>['slots'];
|
|
14
|
+
bindings(): "";
|
|
15
|
+
exports(): {};
|
|
16
|
+
}
|
|
17
|
+
interface $$IsomorphicComponent {
|
|
18
|
+
new <S extends SchemaStructure>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<S>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<S>['props']>, ReturnType<__sveltets_Render<S>['events']>, ReturnType<__sveltets_Render<S>['slots']>> & {
|
|
19
|
+
$$bindings?: ReturnType<__sveltets_Render<S>['bindings']>;
|
|
20
|
+
} & ReturnType<__sveltets_Render<S>['exports']>;
|
|
21
|
+
<S extends SchemaStructure>(internal: unknown, props: ReturnType<__sveltets_Render<S>['props']> & {}): ReturnType<__sveltets_Render<S>['exports']>;
|
|
22
|
+
z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
|
|
23
|
+
}
|
|
24
|
+
declare const Sp00kyProvider: $$IsomorphicComponent;
|
|
25
|
+
type Sp00kyProvider<S extends SchemaStructure> = InstanceType<typeof Sp00kyProvider<S>>;
|
|
26
|
+
export default Sp00kyProvider;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { SyncedDb } from './db.js';
|
|
3
|
+
import type { MaybeGetter } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* What the provider puts in context. A holder, not the client itself: context
|
|
6
|
+
* is set synchronously while the provider initialises, the client is ready
|
|
7
|
+
* later, and the children (the only readers) render after it is.
|
|
8
|
+
*/
|
|
9
|
+
interface DbHolder {
|
|
10
|
+
readonly db: SyncedDb<any> | undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Put a client in context for the components below, instead of rendering
|
|
14
|
+
* `<Sp00kyProvider>`. For apps that create and `init()` the `SyncedDb`
|
|
15
|
+
* themselves (a SvelteKit `+layout.ts`, a test). Call it while a component
|
|
16
|
+
* initialises, like `setContext`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function setDbContext(db: SyncedDb<any> | DbHolder): void;
|
|
19
|
+
/**
|
|
20
|
+
* The `SyncedDb` of the nearest `<Sp00kyProvider>`. Like every context read it
|
|
21
|
+
* must run while a component initialises (top level of `<script>`, or a
|
|
22
|
+
* function called from there), not in an event handler or after an `await`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function useDb<S extends SchemaStructure>(): SyncedDb<S>;
|
|
25
|
+
/** Read a `MaybeGetter`, tracking whatever the getter reads. */
|
|
26
|
+
export declare function read<T>(value: MaybeGetter<T>): T;
|
|
27
|
+
export declare function toError(e: unknown): Error;
|
|
28
|
+
export {};
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { getContext, hasContext, setContext } from 'svelte';
|
|
2
|
+
const KEY = Symbol.for('@spooky-sync/client-svelte/db');
|
|
3
|
+
/**
|
|
4
|
+
* Put a client in context for the components below, instead of rendering
|
|
5
|
+
* `<Sp00kyProvider>`. For apps that create and `init()` the `SyncedDb`
|
|
6
|
+
* themselves (a SvelteKit `+layout.ts`, a test). Call it while a component
|
|
7
|
+
* initialises, like `setContext`.
|
|
8
|
+
*/
|
|
9
|
+
export function setDbContext(db) {
|
|
10
|
+
setContext(KEY, 'getSp00ky' in db ? { db } : db);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The `SyncedDb` of the nearest `<Sp00kyProvider>`. Like every context read it
|
|
14
|
+
* must run while a component initialises (top level of `<script>`, or a
|
|
15
|
+
* function called from there), not in an event handler or after an `await`.
|
|
16
|
+
*/
|
|
17
|
+
export function useDb() {
|
|
18
|
+
const db = hasContext(KEY) ? getContext(KEY).db : undefined;
|
|
19
|
+
if (!db) {
|
|
20
|
+
throw new Error('useDb must be used within a <Sp00kyProvider>. Wrap your app in <Sp00kyProvider config={...}>, ' +
|
|
21
|
+
'or pass the SyncedDb explicitly.');
|
|
22
|
+
}
|
|
23
|
+
return db;
|
|
24
|
+
}
|
|
25
|
+
/** Read a `MaybeGetter`, tracking whatever the getter reads. */
|
|
26
|
+
export function read(value) {
|
|
27
|
+
return typeof value === 'function' ? value() : value;
|
|
28
|
+
}
|
|
29
|
+
export function toError(e) {
|
|
30
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
31
|
+
}
|