# @zwire/svelte

> Svelte 5.7+ createSubscriber reactive refs, store contract helpers, ScopeProvider.svelte, and mirror subpath APIs.

Svelte 5.7+ runes hooks for [`@zwire/core`](https://www.npmjs.com/package/@zwire/core): `current` refs, `bind:value` atoms, the store contract, optimistic mutations, incremental lists, async resources and SSR hydration.

The hooks are plain TypeScript and read through to `signal.get()`. The native `ScopeProvider` ships as Svelte source so the application compiler can render it on the client and server.

## Install

```bash
npm install @zwire/core @zwire/svelte
```

| Entry | Mirrors | Exports |
| :--- | :--- | :--- |
| `@zwire/svelte` | `@zwire/core` | `ScopeProvider`, `provideScope`, `useScope`, `useScoped`, `useSignal`, `useAtom`, `useSelector`, `toReadable`, `toWritable` |
| `@zwire/svelte/tx` | `@zwire/core/tx` | `useOptimisticLayer`, `useOptimisticAction`, `useDraft` |
| `@zwire/svelte/collections` | `@zwire/core/collections` | `useCollectionTopK`, `useCollectionRange`, `useCollectionItem`, `useCollectionSize` |
| `@zwire/svelte/resource` | `@zwire/core/resource` | `useResource` |
| `@zwire/svelte/protocol` | `@zwire/core/protocol` | `useHydrate` |

Import `ScopeProvider` from `@zwire/svelte/ScopeProvider.svelte`; Svelte-aware bundlers also support the named export from `@zwire/svelte`. Every hook takes an optional options object as its last argument; `{ scope }` overrides the provided scope. Reactive fields are getters: read them in markup, `$derived` or `$effect`, and do not destructure them.

## Quick start

```svelte
<script>
  import { atom } from '@zwire/core';
  import { toWritable, useAtom, useSelector, useSignal } from '@zwire/svelte';

  const count = atom(0);
  const title = atom('');

  const value = useSignal(count); // { readonly current }
  const parity = useSelector(count, (n) => n % 2);
  const model = useAtom(title); // { current }, works with bind:value
  const store = toWritable(count); // Svelte store contract ($store)
</script>

<input bind:value={model.current} />
<button onclick={() => count.set((n) => n + 1)}>{value.current} ({parity.current}) {$store}</button>
```

## Recipes

### State per scope

```ts
// state/account.ts: a definition at module level, instantiated once per scope
import { scoped } from '@zwire/core';
import { createQueryCollection } from '@zwire/core/collections';
import { hydratable } from '@zwire/core/protocol';
import { resource } from '@zwire/core/resource';

export const account = scoped((scope) => ({
  balance: hydratable('balance', 0, { scope }),
  orders: createQueryCollection<Order, number>({
    scope,
    getId: (order) => order.id,
    compare: (a, b) => b.qty - a.qty,
  }),
  profile: resource((signal) => api.profile({ signal }), { scope, lazy: true }),
}));
```

```svelte
<!-- App.svelte -->
<script>
  import ScopeProvider from '@zwire/svelte/ScopeProvider.svelte';
  import Balance from './Balance.svelte';
</script>

<!-- Without a `scope` prop the provider creates a scope and disposes it with the component. -->
<ScopeProvider><Balance /></ScopeProvider>
```

```svelte
<!-- Balance.svelte -->
<script>
  import { useScoped, useSignal } from '@zwire/svelte';

  const { balance } = useScoped(account); // the instance for the provided scope
  const available = useSignal(balance);
</script>

<output>{available.current}</output>
```

Atoms belong to the scope they were created in. `scoped()` keeps the definition at module level and builds one instance per scope on first use, so a `ScopeProvider` (or a server request) gets its own state. Outside components, call the definition directly: `account(scope).balance.set(1000)`. `provideScope()` does the same as the component from a component's script and returns the scope.

### Optimistic mutation

```svelte
<script>
  import { useScoped } from '@zwire/svelte';
  import { useOptimisticAction } from '@zwire/svelte/tx';

  const { balance } = useScoped(account);

  // One layer per call: reverted if the request fails, settled with the server's answer.
  const reserve = useOptimisticAction(
    async (tx, amount) => {
      tx.update(balance, (b) => b - amount);
      return api.reserve(amount, { signal: tx.signal });
    },
    { settle: (result) => balance.set(result.balance) },
  );
</script>

<button disabled={reserve.pending} onclick={() => reserve.run(150)}>Reserve 150</button>
{#if reserve.error}<p role="alert">Could not reserve</p>{/if}
```

- `run(...args)` never throws; a failure lands in `error`. `runAsync(...args)` returns the promise.
- Calls made while one is in flight run as parallel layers that rebase in order. Pass `concurrency: 'latest'` to abort the earlier call or `'drop'` to ignore the new one.
- A call keeps running if the component is destroyed, so the server's answer still lands. Pass `abortOnUnmount: true` to abort instead.

For a layer the UI holds open itself, `useOptimisticLayer()` returns `{ active, update, settle, revert }`: the first `update` opens the layer, `settle(serverUpdate?)` or `revert()` closes it, and destroying the component reverts it. `useDraft()` gives the same kind of handle for an STM draft (`open`, `get`, `set`, `commit`, `discard`); `draft.get(signal)` is reactive in markup.

### Lists

```svelte
<script>
  import { useScoped } from '@zwire/svelte';
  import { useCollectionRange, useCollectionSize } from '@zwire/svelte/collections';

  let { page } = $props();
  const { orders } = useScoped(account);
  const rows = useCollectionRange(orders, () => page * 20, 20);
  const total = useCollectionSize(orders);
</script>

<p>{total.current} orders</p>
{#each rows.current as order (order.id)}
  <OrderRow id={order.id} />
{/each}
```

Arguments accept getters. In a row component, `useCollectionItem(orders, () => id)` updates only when that row changes. A `filter` option is fixed for the lifetime of the hook.

### Async resources

```svelte
<script>
  import { useScoped } from '@zwire/svelte';
  import { useResource } from '@zwire/svelte/resource';

  const profile = useResource(useScoped(account).profile);
</script>

{#if profile.status === 'pending'}
  <Spinner />
{:else if profile.status === 'error'}
  <button onclick={profile.refetch}>Retry</button>
{:else}
  <p style:opacity={profile.pending ? 0.5 : 1}>{profile.data?.name}</p>
{/if}
```

`data` keeps the last successful value while refreshing and after an error. Reading the view starts a `lazy` resource.

### Scope and SSR

Hydrate the scope before any component reads it. In SvelteKit, return the snapshot from a layout `load` and apply it in the root layout:

```ts
// src/routes/+layout.server.ts
export const load = async () => ({ zwire: { balance: 1000 } });
```

```svelte
<!-- src/routes/+layout.svelte -->
<script>
  import { browser } from '$app/environment';
  import { provideScope } from '@zwire/svelte';
  import { useHydrate } from '@zwire/svelte/protocol';

  let { data, children } = $props();
  // provideScope() returns the scope it creates, so this component can hydrate it first.
  useHydrate(data.zwire, { scope: provideScope(undefined, { mode: browser ? 'client' : 'ssr' }) });
</script>

{@render children()}
```

The snapshot maps the keys of `hydratable(key, ...)` atoms to values. The same object is applied to a scope at most once; call `useHydrate` again with a new object to apply a later one.

When the server serializes state itself, create the scope there, render inside `<ScopeProvider {scope}>`, call `dehydrate(scope)` from `@zwire/core/protocol`, and dispose the scope.

## Migrating from 0.3

| 0.3 | 0.4 |
| :--- | :--- |
| `useStoreScope()` | `useScope()` |
| `useAtomValue(signal)` | `useSignal(signal)` |
| `useSignal(signal, scope)` | `useSignal(signal, { scope })` |
| `useAtom(signal, scope)` | `useAtom(signal, { scope })` |
| `useSelector(src, sel, eq, scope)` | `useSelector(src, sel, { equals: eq, scope })` (`useSelector(src, sel, eq)` is unchanged) |
| `useOptimistic(createOptimisticLayer)` from `@zwire/svelte/hooks`, then `layer().update(...)` | `useOptimisticLayer()` from `@zwire/svelte/tx`, then `layer.update(...)` |
| `useDraft(createDraft)` from `@zwire/svelte/hooks`, then `draft().set(...)` | `useDraft()` from `@zwire/svelte/tx`, then `draft.set(...)` |
| `useCollectionTopK(col, k, scope)` from `@zwire/svelte/hooks` | `useCollectionTopK(col, k, { scope })` from `@zwire/svelte/collections` |
| `toReadable(signal, scope)` / `toWritable(signal, scope)` | `toReadable(signal, { scope })` / `toWritable(signal, { scope })` |

See the [API reference](https://github.com/kjmin-dev/zwire/blob/main/docs/API.md#74-zwiresvelte) for full signatures and the [runnable example](https://github.com/kjmin-dev/zwire/tree/main/examples/adapter-orders).
