콘텐츠로 이동

@zwire/svelte

이 콘텐츠는 아직 번역되지 않았습니다.

Svelte 5.7+ runes hooks for @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.

Terminal window
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.

<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>
// 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 }),
}));
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>
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.

<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.

<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.

<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.

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

src/routes/+layout.server.ts
export const load = async () => ({ zwire: { balance: 1000 } });
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.

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 for full signatures and the runnable example.