effects
Every platform effect on the web: sign-in (password, magic link, Apple and Google with PKCE against a mock backend and a pretend provider), a guarded account screen, key-value and secure storage, notifications with a permission explainer, camera, purchases (not available on the web, and a mock store), share, haptics, lifecycle and the minimum-version check. No network is used.
Run it
cargo run -p duolith-cli -- dev examples/effects # live, reloads on save
cargo run -p duolith-cli -- build examples/effects # static output in examples/effects/dist
The folder on the web: examples/effects.
Features it shows
| Feature | Where | Screenshot |
|---|---|---|
autocomplete on fields, TextField's autocomplete | data pages/signup.duo; effects pages/sign-in.duo | data-signup-errors.png |
| Sign-in: email and password, magic link, Apple and Google with PKCE, a mock backend | effects pages/sign-in.duo, pages/_layout.duo, pages/mock-provider.duo, pages/callback.duo | the Sign in screen |
A screen guarded by the session (guard(signIn.required(...))) | effects pages/account.duo | the Account screen |
| Secure storage (WebCrypto AES-GCM, key in IndexedDB) | effects pages/storage.duo | the Storage screen |
| Key-value storage, typed and reactive across windows | effects pages/storage.duo | the Storage screen |
| Push: permission with an explainer, local notifications that open a screen, web push with a VAPID key | effects pages/push.duo, components/Explainer.duo | the Push screen |
| Permissions with an explainer, and the Info.plist and Android manifest declarations a build writes | effects components/Explainer.duo; dist/native/ after a build | the Push and Camera screens |
| Purchases: "not available" on the web, a mock store for the flow | effects pages/purchases.duo | the Purchases screen |
| Share with a copy fallback, haptics | effects pages/share.duo | the Share screen |
| Camera capture | effects pages/camera.duo | the Camera screen |
| Lifecycle (foreground, background, online, offline) and the minimum-version check | effects pages/device.duo | the Device screen |
| A magic link that opens the app signs in, for the screen it was sent from; a native build refuses it until the shells deliver links (E0402) | effects pages/sign-in.duo; packages/effects/test/native-account-and-device.test.ts | none (a build error on native) |
| Push's Firebase configuration, checked by the build (E0400, E0401) | effects google-services.json | none (a build error) |
| A photo from the library, through the picker with no permission | effects pages/camera.duo | the Camera screen |
Source
components/Explainer.duo
---
// The app's own explanation, shown before the system's permission prompt.
// permissions.request(name, { reason }) sets permissions.explaining and waits
// for an answer; only "Continue" goes on to the prompt, so a "Not now" keeps
// the one-time system prompt for later.
import { Button, Dialog } from "@duolith/kit";
import { permissions } from "@duolith/effects";
const titles = {
camera: "Use the camera?",
notifications: "Turn on notifications?",
location: "Use your location?",
contacts: "Read the contact you pick?",
microphone: "Use the microphone?",
calendar: "Add to your calendar?",
speech: "Listen to what you say?",
};
---
<Dialog
title={permissions.explaining ? titles[permissions.explaining.name] : ""}
message={permissions.explaining?.reason}
open={permissions.explaining !== undefined}
dismissible={false}
>
<piece name="actions">
<Button label="Not now" variant="ghost" onPress={() => permissions.answer(false)} />
<Button label="Continue" onPress={() => permissions.answer(true)} />
</piece>
</Dialog>google-services.json
{
"project_info": {
"project_number": "000000000000",
"project_id": "duolith-effects-example-placeholder",
"storage_bucket": "duolith-effects-example-placeholder.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:000000000000:android:0000000000000000000000",
"android_client_info": { "package_name": "dev.duolith.shell" }
},
"oauth_client": [],
"api_key": [{ "current_key": "placeholder-not-a-real-key" }],
"services": { "appinvite_service": { "other_platform_oauth_client": [] } }
}
],
"configuration_version": "1"
}pages/_layout.duo
---
import { state } from "@duolith/client";
import { Toast } from "@duolith/kit";
import { mockSignInBackend, signIn } from "@duolith/effects";
// The layout's script runs before every screen's, once per visit, so the
// whole app signs in against one backend. This one is a mock: no network.
// The sign-in screen shows its outbox, through shared state.
const backend = mockSignInBackend();
let mockBackend = state(backend, { shared: "mock-sign-in-backend" });
signIn.useBackend(backend);
// Apple and Google send the user to this app's own pretend provider, which
// returns an authorization code bound to the PKCE challenge. Both are screens
// of the app, written as paths, so this works on the web and on a phone.
for (const provider of ["apple", "google"] as const) {
signIn.configure(provider, {
clientId: "effects-example",
redirectUri: "/callback",
authorizationEndpoint: `/mock-provider?provider=${provider}`,
});
}
---
<view class="bg-canvas">
<slot />
<Toast />
</view>pages/account.duo
---
import { guard, navigate } from "@duolith/client";
import { Avatar, Button, ListRow, Section } from "@duolith/kit";
import { signIn } from "@duolith/effects";
// Signed out, this screen sends the user to /sign-in?next=/account. The
// guard follows the session, so signing out here (or in another window)
// leaves the screen at once.
guard(signIn.required("/sign-in"));
async function signOut() {
await signIn.signOut();
navigate("/", { replace: true });
}
---
<screen title="Account" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<view class="row items-center gap-3">
<Avatar name={signIn.session.user?.name ?? signIn.session.user?.email ?? "?"} size="lg" />
<view class="gap-1">
<text role="heading" class="text-title text-ink">
{signIn.session.user?.name ?? signIn.session.user?.email}
</text>
<text class="text-caption text-muted">Signed in with {signIn.session.user?.provider}</text>
</view>
</view>
<Section
title="Session"
footer="Who is signed in is kept in key-value storage, so guards know at once; the tokens are encrypted in secure storage."
>
<ListRow title="User id" value={signIn.session.user?.id} />
<ListRow title="Email" value={signIn.session.user?.email ?? "none"} />
</Section>
<Button label="Sign out" variant="danger" full onPress={signOut} />
</view>
</screen>pages/callback.duo
---
import { navigate } from "@duolith/client";
import { Button, Spinner } from "@duolith/kit";
import { signIn } from "@duolith/effects";
// The provider returns here. completeRedirect checks the state of this
// screen's address, then swaps the code and the PKCE verifier for credentials.
signIn.completeRedirect().then((signedIn) => {
if (signedIn) navigate("/account", { replace: true });
});
---
<screen title="Signing in" class="bg-canvas">
<view class="gap-4 p-4 md:p-8 items-center">
<show when={signIn.session.error}>
<text role="alert" class="text-body text-danger">{signIn.session.error}</text>
<Button
label="Back to sign in"
variant="secondary"
onPress={() => navigate("/sign-in", { replace: true })}
/>
</show>
<otherwise>
<Spinner label="Signing in" />
</otherwise>
</view>
</screen>pages/camera.duo
---
import { onDispose, state } from "@duolith/client";
import { Button, EmptyState, Image, Section } from "@duolith/kit";
import { camera, permissions, picker } from "@duolith/effects";
import Explainer from "../components/Explainer.duo";
let photo = state<{ url: string; width: number; height: number } | undefined>(undefined);
let problem = state("");
// The camera closes with this screen; it also closes by itself when the app leaves the screen.
const leaving = new AbortController();
onDispose(() => leaving.abort());
// A photo from the library comes through the system's picker, which runs
// outside the app and hands over only what was chosen: no permission.
async function chooseFromLibrary() {
problem = "";
try {
const [chosen] = await picker.pick({ kind: "image" });
if (chosen !== undefined) photo = { url: chosen.url, width: 0, height: 0 };
} catch (failure) {
problem = (failure as Error).message;
}
}
async function takePhoto(facing: "user" | "environment") {
problem = "";
const status = await permissions.request("camera", { reason: "Take a photo to add to your profile. Nothing is uploaded." });
if (status !== "granted") return;
try {
photo = (await camera.capture({ facing, maxWidth: 1200, signal: leaving.signal })) ?? photo;
} catch (failure) {
problem = (failure as Error).message;
}
}
---
<screen title="Camera" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<text role="heading" class="text-title text-ink">Camera</text>
<Section
title="Photo"
footer={`Camera ${camera.available ? "available" : "not available"} · permission ${permissions.status("camera")}`}
>
<view class="gap-3 p-4">
<show when={photo}>
<Image src={photo?.url ?? ""} alt="The photo you took" ratio="4:3" radius="md" />
<show when={photo?.width}>
<text class="text-caption text-muted">{photo?.width} × {photo?.height}</text>
</show>
</show>
<otherwise>
<EmptyState
title="No photo yet"
message="Take one with the front or back camera."
icon="camera"
/>
</otherwise>
<view class="row gap-2">
<Button label="Back camera" icon="camera" onPress={() => takePhoto("environment")} />
<Button label="Front camera" variant="secondary" onPress={() => takePhoto("user")} />
</view>
<show when={problem}>
<text role="alert" class="text-caption text-danger">{problem}</text>
</show>
</view>
</Section>
<Section
title="Photo library"
footer={picker.available ? "The system's picker: the app sees only the photo you choose." : picker.unavailableReason}
>
<view class="gap-3 p-4">
<Button label="Choose from the library" variant="secondary" onPress={chooseFromLibrary} />
</view>
</Section>
</view>
<Explainer />
</screen>pages/device.duo
---
import { network, onDispose, state } from "@duolith/client";
import { Badge, Button, ListRow, Section, ToggleRow } from "@duolith/kit";
import { lifecycle, minimumVersion } from "@duolith/effects";
let returns = state(0);
// A listener stops with the screen.
onDispose(lifecycle.onForeground(() => (returns += 1)));
// A pretend server answer: the oldest version it supports.
let serverMinimum = state("1.0.0");
function check() {
minimumVersion.check({ current: "1.4.2", load: async () => ({ minimum: serverMinimum }) });
}
check();
---
<screen title="Lifecycle and version" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<text role="heading" class="text-title text-ink">Lifecycle and version</text>
<Section title="Lifecycle" footer="Switch to another tab and back to count a return.">
<ListRow title="Phase" value={lifecycle.phase} />
<ListRow title="Visible" value={lifecycle.visible ? "yes" : "no"} />
<ListRow title="Returns to the foreground" value={String(returns)} />
<ListRow title="Network" value={lifecycle.online ? "online" : "offline"} />
<ToggleRow
label="Pretend to be offline"
checked={network.pretendingOffline}
onChange={(offline) => network.pretendOffline(offline)}
/>
</Section>
<Section
title="Minimum version"
footer={`This app is ${minimumVersion.current}; the server supports ${minimumVersion.minimum || "…"} and newer.`}
>
<view class="gap-3 p-4">
<view class="row wrap gap-2">
<Button
label="Server needs 1.0.0"
size="sm"
variant="secondary"
onPress={() => ((serverMinimum = "1.0.0"), check())}
/>
<Button
label="Server needs 2.0.0"
size="sm"
variant="secondary"
onPress={() => ((serverMinimum = "2.0.0"), check())}
/>
</view>
<view class="row items-center gap-2">
<text class="text-body text-ink">Status</text>
<Badge
label={minimumVersion.status}
tone={minimumVersion.status === "update-required" ? "danger" : "success"}
/>
</view>
</view>
</Section>
<show when={minimumVersion.status === "update-required"}>
<view role="alert" class="gap-2 p-4 rounded-lg bg-surface border">
<text class="text-label text-ink">Update to keep going</text>
<text class="text-body text-muted">
This version is too old for the server. On the web, updating loads the newest version.
</text>
<Button label="Update" icon="download" onPress={() => minimumVersion.update()} />
</view>
</show>
</view>
</screen>pages/index.duo
---
import { ListRow, Section } from "@duolith/kit";
import { lifecycle, signIn } from "@duolith/effects";
---
<screen title="Effects" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<view class="gap-1">
<text role="heading" class="text-title text-ink">Effects</text>
<text class="text-body text-muted">
Every platform effect, on the web and on iOS and Android. Sign-in uses a mock backend and a
pretend provider: nothing leaves the app.
</text>
<text class="text-caption text-muted">
{signIn.session.signedIn ? `Signed in as ${signIn.session.user?.name ?? signIn.session.user?.email}` : "Signed out"}
· {lifecycle.online ? "online" : "offline"} · {lifecycle.phase}
</text>
</view>
<Section title="Account">
<ListRow
title="Sign in"
subtitle="Password, magic link, Apple and Google with PKCE"
icon="user"
href="/sign-in"
chevron
/>
<ListRow
title="Account"
subtitle="A screen guarded by the session"
icon="lock"
href="/account"
chevron
/>
</Section>
<Section title="Storage">
<ListRow
title="Storage"
subtitle="Key-value values that follow every window, and secure values"
icon="bookmark"
href="/storage"
chevron
/>
</Section>
<Section title="Device">
<ListRow
title="Notifications"
subtitle="Permission with an explainer, local notifications, web push"
icon="bell"
href="/push"
chevron
/>
<ListRow title="Camera" subtitle="Take a photo" icon="camera" href="/camera" chevron />
<ListRow
title="Share and haptics"
subtitle="The share sheet, or a copied link"
icon="share"
href="/share"
chevron
/>
<ListRow
title="Lifecycle and version"
subtitle="Foreground, background, online, and the minimum version"
icon="info"
href="/device"
chevron
/>
</Section>
<Section title="Store">
<ListRow
title="Purchases"
subtitle="The App Store or Google Play; a mock store to try the flow"
icon="star"
href="/purchases"
chevron
/>
</Section>
</view>
</screen>pages/mock-provider.duo
---
import { navigate, route } from "@duolith/client";
import { Button, Section } from "@duolith/kit";
// A pretend Apple or Google: it shows a consent screen and sends the user
// back with an authorization code the mock backend accepts only together
// with the verifier behind this challenge. A real provider checks the
// client id and redirect address; this one trusts them, and goes back to the
// redirect address's screen in this app.
let { query } = route();
const provider = query["provider"] === "apple" ? "Apple" : "Google";
function back(answer: Record<string, string>) {
const screen = (query["redirect_uri"] ?? "/").replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, "") || "/";
const parameters = new URLSearchParams({ ...answer, state: query["state"] ?? "" });
navigate(`${screen}?${parameters.toString()}`, { replace: true });
}
---
<screen title={`Sign in with ${provider}`} class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<view class="gap-1">
<text role="heading" class="text-title text-ink">Sign in with {provider}</text>
<text class="text-body text-muted">
A pretend provider for the example. effects-example wants to know who you are.
</text>
</view>
<Section
title="Request"
footer="The challenge is the SHA-256 of a verifier that stayed in the app."
>
<view class="gap-1 p-4">
<text class="text-caption text-muted">client_id: {query["client_id"]}</text>
<text class="text-caption text-muted">
code_challenge_method: {query["code_challenge_method"]}
</text>
<text class="text-caption text-muted">code_challenge: {query["code_challenge"]}</text>
</view>
</Section>
<view class="gap-3">
<Button
label={`Continue as ${provider} user`}
full
onPress={() => back({ code: `mock.${query["code_challenge"]}` })}
/>
<Button
label="Cancel"
variant="ghost"
full
onPress={() => back({ error: "access_denied" })}
/>
</view>
</view>
</screen>pages/purchases.duo
---
import { state, toast } from "@duolith/client";
import { Badge, Button, ListRow, Section } from "@duolith/kit";
import { mockStore, purchases } from "@duolith/effects";
// On the web there is no store: purchases says so, and buying is refused. On
// a phone the store is the App Store or Google Play. The button swaps in a
// mock store, on any target, to show the flow without a store account.
let mock = state(false);
function useMock() {
mock = true;
purchases.useStore(
mockStore(
[
{ id: "pro", title: "Pro", description: "Every feature, for good", price: "€4.99" },
{ id: "themes", title: "Theme pack", description: "Twelve more themes", price: "€1.99" },
],
{ owned: ["themes"] },
),
);
purchases.load(["pro", "themes"]);
}
async function buy(id: string) {
const outcome = await purchases.buy(id).catch((failure: Error) => failure.message);
toast(outcome === "purchased" ? "Purchased" : outcome, { tone: outcome === "purchased" ? "success" : "neutral" });
}
async function restore() {
const owned = await purchases.restore().catch(() => []);
toast(`Restored ${owned.length} purchase(s)`);
}
---
<screen title="Purchases" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<view class="row items-center gap-2">
<text role="heading" class="text-title text-ink">Purchases</text>
<Badge
label={purchases.available ? "available" : "not available"}
tone={purchases.available ? "success" : "neutral"}
/>
</view>
<show when={!purchases.available}>
<view class="gap-1 p-4 rounded-lg bg-surface border">
<text class="text-label text-ink">No store here</text>
<text class="text-body text-muted">{purchases.unavailableReason}</text>
</view>
</show>
<show when={!mock}>
<Section
title="Try it"
footer="The apps get the same flow from the App Store and Google Play."
>
<ListRow title="Use a mock store" icon="star" onPress={useMock} />
</Section>
</show>
<show when={purchases.available}>
<Section title="Products">
<list each={purchases.products} as="product" key={product.id}>
<view class="row items-center justify-between gap-3 p-4">
<view class="gap-1 grow">
<text class="text-label text-ink">{product.title}</text>
<text class="text-caption text-muted">{product.description}</text>
</view>
<show when={purchases.owns(product.id)}>
<Badge label="Owned" tone="success" />
</show>
<otherwise>
<Button label={product.price} size="sm" onPress={() => buy(product.id)} />
</otherwise>
</view>
</list>
<ListRow title="Restore purchases" icon="refresh" onPress={restore} />
</Section>
</show>
</view>
</screen>pages/push.duo
---
import { onDispose, state, toast } from "@duolith/client";
import { Badge, Button, ListRow, Section, TextField } from "@duolith/kit";
import { permissions, push } from "@duolith/effects";
import Explainer from "../components/Explainer.duo";
// A VAPID public key, as an app server would publish it. Subscribing needs
// the browser's push service, so it fails without a network; the error says so.
let vapidPublicKey = state("BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U");
let problem = state("");
let lastTap = state("");
// While this screen shows, a tap is reported here instead of opening its
// screen; the listener stops with the screen.
onDispose(push.onTap((tap) => (lastTap = `${tap.title} → ${tap.screen ?? "no screen"}`)));
async function ask() {
const status = await permissions.request("notifications", { reason: "Hear when someone replies to you, even with the app closed." });
toast(`Notifications: ${status}`);
}
async function notifyNow() {
problem = "";
try {
await push.notify("Your photo is ready", { body: "Tap to open it.", screen: "/camera", tag: "photo" });
toast("Notification shown", { tone: "success" });
} catch (failure) {
problem = (failure as Error).message;
}
}
async function subscribe() {
problem = "";
try {
await push.subscribe({ vapidPublicKey });
} catch (failure) {
problem = (failure as Error).message;
}
}
---
<screen title="Notifications" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<view class="row items-center gap-2">
<text role="heading" class="text-title text-ink">Notifications</text>
<Badge
label={push.permission}
tone={push.permission === "granted" ? "success" : push.permission === "denied" ? "danger" : "neutral"}
/>
</view>
<Section
title="Permission"
footer="The explainer comes first; the system's prompt only after Continue."
>
<view class="p-4">
<Button label="Ask for notifications" onPress={ask} />
</view>
</Section>
<Section
title="Local notification"
footer="A tap opens the screen it names (on the web, through the push service worker)."
>
<view class="p-4">
<Button label="Notify me" icon="bell" onPress={notifyNow} />
</view>
<ListRow title="Last tap" value={lastTap || "none yet"} />
</Section>
<Section
title="Remote push"
footer="On the web, Web Push with the server's VAPID key; on a phone, the APNs or FCM token for the server."
>
<view class="gap-3 p-4">
<TextField label="VAPID public key" bind:value={vapidPublicKey} />
<Button label="Subscribe" variant="secondary" onPress={subscribe} />
</view>
<ListRow title="Endpoint" value={push.subscription?.endpoint ?? "not subscribed"} />
</Section>
<show when={problem}>
<text role="alert" class="text-caption text-danger">{problem}</text>
</show>
</view>
<Explainer />
</screen>pages/share.duo
---
import { toast } from "@duolith/client";
import { Button, ListRow, Section } from "@duolith/kit";
import { haptics, share } from "@duolith/effects";
async function shareLake() {
const outcome = await share({ title: "Lake Bled", text: "Look at this lake", url: "https://example.com/lake-bled" });
if (outcome === "copied") toast("Link copied", { tone: "success" });
else if (outcome === "unavailable") toast("Sharing is not available here", { tone: "danger" });
}
---
<screen title="Share and haptics" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<text role="heading" class="text-title text-ink">Share and haptics</text>
<Section
title="Share"
footer="The share sheet where the browser has one; otherwise the link is copied."
>
<view class="p-4">
<Button label="Share this lake" icon="share" onPress={shareLake} />
</view>
</Section>
<Section
title="Haptics"
footer={haptics.available ? "This browser vibrates." : "This browser has no vibration, so these do nothing, as they should."}
>
<ListRow title="Light impact" onPress={() => haptics.impact("light")} />
<ListRow title="Heavy impact" onPress={() => haptics.impact("heavy")} />
<ListRow title="Selection" onPress={() => haptics.selection()} />
<ListRow title="Success" onPress={() => haptics.notification("success")} />
<ListRow title="Error" onPress={() => haptics.notification("error")} />
</Section>
</view>
</screen>pages/share.test.ts
// The share and camera screens with their effects mocked: run with
// duolith test examples/effects (no device, share sheet or camera needed).
import { effectError, expect, render, test } from "@duolith/testing";
test("where there is no share sheet, the link is copied and the toast says so", async () => {
const screen = await render("/share", { effects: { share: () => "copied" } });
await screen.byRole("button", { name: "Share this lake" }).press();
await expect(screen.byText("Link copied")).toBeShown();
expect(await screen.effectCalls("share")).toEqual([
[{ title: "Lake Bled", text: "Look at this lake", url: "https://example.com/lake-bled" }],
]);
});
test("where sharing is not possible at all, the toast says that", async () => {
const screen = await render("/share", { effects: { share: () => "unavailable" } });
await screen.byRole("button", { name: "Share this lake" }).press();
await expect(screen.byText("Sharing is not available here")).toBeShown();
});
test("the camera's photo is shown at its size", async () => {
const screen = await render("/camera", {
effects: {
permissions: { request: () => "granted", status: () => "granted" },
camera: { available: true, capture: () => ({ url: "data:image/gif;base64,R0lGODlhAQABAAAAACw=", width: 640, height: 480 }) },
},
});
await screen.byRole("button", { name: "Back camera" }).press();
await expect(screen.byText("640 × 480")).toBeShown();
expect((await screen.effectCalls("camera.capture"))[0]).toEqual([{ facing: "environment", maxWidth: 1200, signal: "<signal>" }]);
});
test("a camera that fails shows why", async () => {
const screen = await render("/camera", {
effects: {
permissions: { request: () => "granted", status: () => "granted" },
camera: { capture: effectError("E0230", "The camera stopped before the photo was taken.") },
},
});
await screen.byRole("button", { name: "Front camera" }).press();
await expect(screen.byRole("alert")).toHaveText("E0230: The camera stopped before the photo was taken.");
});pages/sign-in.duo
---
import { navigate, route, state } from "@duolith/client";
import { Button, Divider, Section, TextField } from "@duolith/kit";
import { signIn } from "@duolith/effects";
let { query } = route();
// The layout shares its mock backend; the first value of a shared state wins, so this one is only its shape.
let mockBackend = state<{ outbox: { to: string; link: string }[] }>({ outbox: [] }, { shared: "mock-sign-in-backend" });
let email = state("ada@example.com");
let password = state("");
let sent = state(false);
// `next` comes from the address, so follow it only when it is a path in this
// app: one "/" and then not another "/" or a "\", which browsers read as "//".
const next = query["next"] !== undefined && /^\/(?![/\\])/.test(query["next"]) ? query["next"] : "/account";
// The magic link brings the user back here with ?magic-link=... On a device
// that did not ask for it, signing in waits for the user to confirm below.
// On a phone the link may already have been finished as it opened the app:
// finishing it again gives the same answer.
if (query["magic-link"] !== undefined) {
signIn.completeMagicLink().then(carryOn);
}
function carryOn(signedIn: boolean) {
if (signedIn) navigate(next, { replace: true });
}
async function withPassword() {
carryOn(await signIn.withPassword(email, password));
}
async function confirmLink() {
carryOn(await signIn.confirmMagicLink());
}
// The link comes back to this screen. An app with a real backend passes the
// address of its own site, which opens the app on a phone (an app link).
async function sendLink() {
sent = await signIn.sendMagicLink(email);
}
/** The screen a link in the outbox opens: its path and query in this app. */
function screenOf(link: string): string {
return link.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, "");
}
---
<screen title="Sign in" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<view class="gap-1">
<text role="heading" class="text-title text-ink">Sign in</text>
<text class="text-body text-muted">Try ada@example.com with the password lovelace.</text>
</view>
<show when={signIn.session.awaitingConfirmation}>
<Section
title="Finish signing in?"
footer="This sign-in link was asked for on another device or browser. Sign in only if you asked for it yourself."
>
<view class="gap-3 p-4">
<Button
label="Sign in on this device"
full
loading={signIn.session.pending}
onPress={confirmLink}
/>
</view>
</Section>
</show>
<Section title="Email">
<view class="gap-3 p-4">
<TextField label="Email" type="email" autocomplete="username" bind:value={email} />
<TextField
label="Password"
type="password"
autocomplete="current-password"
bind:value={password}
/>
<Button label="Sign in" full loading={signIn.session.pending} onPress={withPassword} />
<Button label="Email me a sign-in link" variant="secondary" full onPress={sendLink} />
<show when={signIn.session.error}>
<text role="alert" class="text-caption text-danger">{signIn.session.error}</text>
</show>
</view>
</Section>
<show when={sent}>
<Section
title="Mock outbox"
footer="The mock backend keeps the emails it would send. Open the newest link to sign in."
>
<list each={mockBackend.outbox} as="message" key={message.link} class="gap-2 p-4">
<view class="gap-1">
<text class="text-caption text-muted">To {message.to}</text>
<text class="text-label text-primary" href={screenOf(message.link)}>
Open the sign-in link
</text>
</view>
</list>
</Section>
</show>
<Divider />
<Section
title="Providers"
footer="These go to the provider with PKCE (on a phone, the platform's own sign-in or the system's browser sheet); here the provider is a pretend one inside this app."
>
<view class="gap-3 p-4">
<Button
label="Continue with Apple"
variant="secondary"
full
onPress={() => signIn.withProvider("apple")}
/>
<Button
label="Continue with Google"
variant="secondary"
full
onPress={() => signIn.withProvider("google")}
/>
</view>
</Section>
</view>
</screen>pages/storage.duo
---
import { state, toast } from "@duolith/client";
import { Button, ListRow, Section, TextField } from "@duolith/kit";
import { secureStorage, storage } from "@duolith/effects";
// Key-value storage: typed, reactive, and the same in every window. Open
// this screen in two windows and change the choice in one.
const layout = storage.value<string>("example.layout", "list");
const visits = storage.value<number>("example.visits", 0);
visits.value += 1;
function choose(next: string) {
layout.value = next;
}
// Secure storage: encrypted with a key this browser cannot export.
let secret = state("");
let revealed = state("");
async function keep() {
await secureStorage.set("example.secret", secret);
secret = "";
toast("Kept in secure storage", { tone: "success" });
}
async function reveal() {
revealed = (await secureStorage.get("example.secret")) ?? "(nothing stored)";
}
---
<screen title="Storage" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Effects</text>
<text role="heading" class="text-title text-ink">Storage</text>
<Section
title="Key-value storage"
footer="Kept in localStorage under duolith:, and updated when another window changes it."
>
<view class="gap-3 p-4">
<view class="row gap-2">
<Button
label="List"
size="sm"
variant={layout.value === "list" ? "primary" : "secondary"}
onPress={() => choose("list")}
/>
<Button
label="Grid"
size="sm"
variant={layout.value === "grid" ? "primary" : "secondary"}
onPress={() => choose("grid")}
/>
</view>
</view>
<ListRow title="Stored layout" value={layout.value} />
<ListRow title="Visits to this screen" value={String(visits.value)} />
<ListRow title="Stored keys" value={String(storage.keys().length)} />
</Section>
<Section
title="Secure storage"
footer="On the web: AES-GCM with a non-extractable WebCrypto key in IndexedDB. The effects README says what that does and does not protect against."
>
<view class="gap-3 p-4">
<TextField label="A secret" type="password" bind:value={secret} />
<view class="row gap-2">
<Button label="Keep it" onPress={keep} />
<Button label="Read it back" variant="secondary" onPress={reveal} />
</view>
<text class="text-body text-ink">{revealed}</text>
</view>
</Section>
</view>
</screen>