device-effects
Every device effect on the web, Android and iOS: location, sensors and the compass, device information, the connection, the keyboard, the display, contacts, the calendar, the clipboard, the media and file picker, the browser, biometrics, tracking, store reviews, the app badge, recording, speech and the barcode scanner. "Pretend to be a phone" puts each on its mock.
Run it
cargo run -p duolith-cli -- dev examples/device-effects # live, reloads on save
cargo run -p duolith-cli -- build examples/device-effects # static output in examples/device-effects/dist
The folder on the web: examples/device-effects.
Features it shows
| Feature | Where | Screenshot |
|---|---|---|
| Location: one position and a watch, asked for with its permission | device-effects pages/location.duo | the Where you are screen |
| Sensors: the compass heading and the accelerometer | device-effects pages/location.duo | the Where you are screen |
| Device information: model, version, locale, time zone, safe area, text size, dark mode | device-effects pages/phone.duo | the This device screen |
| The connection: online, type, metered | device-effects pages/phone.duo | the This device screen |
| The keyboard: visible, height, dismiss | device-effects pages/phone.duo | the This device screen |
| The display: keep awake, orientation lock, brightness, "unavailable" where the platform lacks one | device-effects pages/phone.duo | the This device screen |
| Contacts: the system picker, for a phone number or an email address, with no permission | device-effects pages/people.duo | the People and things screen |
| The calendar: add an event through the calendar's own editor ("added", "cancelled" on iOS 17, or "handed-off" on Android and as an .ics on the web) | device-effects pages/people.duo | the People and things screen |
| The clipboard: copy and paste text, read only right after a press | device-effects pages/people.duo | the People and things screen |
| The media and file picker: photos, videos and documents | device-effects pages/people.duo | the People and things screen |
| The browser: in-app (Custom Tabs, SFSafariViewController) or the system's; E0420 for an address that is not http or https | device-effects pages/people.duo | the People and things screen |
| Biometrics with the device credential as a fallback | device-effects pages/trust.duo | the Trust screen |
| App Tracking Transparency, "not-needed" off iOS | device-effects pages/trust.duo | the Trust screen |
| Store reviews, "unavailable" on the web | device-effects pages/trust.duo | the Trust screen |
| The app badge, "unavailable" on Android | device-effects pages/trust.duo | the Trust screen |
| Recording and playback | device-effects pages/sound.duo | the Sound and codes screen |
| Speech: speaking, and listening with what was heard so far | device-effects pages/sound.duo | the Sound and codes screen |
| The barcode scanner, failing loudly with E0425 where unsupported | device-effects pages/sound.duo | the Sound and codes screen |
Source
pages/index.duo
---
import { ListRow, Section } from "@duolith/kit";
import { connection, device } from "@duolith/effects";
// Each effect runs on the platform the app is on. A test swaps any of them
// for its mock with `use` (location.use(mockLocation(...))); a native build
// refuses a mock in a page (E0432), so the app never pretends in a store.
---
<screen title="Device 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">Device effects</text>
<text class="text-body text-muted">
What a phone can do, from one import, on the web, Android and iOS. Where a device cannot do
something, the effect says so: it is never a silent no-op.
</text>
<text class="text-caption text-muted">
{device.os} · {device.model || "a browser"} ·
{connection.online ? connection.type : "offline"}
</text>
</view>
<Section title="Effects">
<ListRow
title="Where you are"
subtitle="Location, the compass and motion sensors"
icon="location"
href="/location"
chevron
/>
<ListRow
title="This device"
subtitle="Model, safe area, connection, keyboard and screen"
icon="phone"
href="/phone"
chevron
/>
<ListRow
title="People and things"
subtitle="Contacts, the calendar, the clipboard, files and the browser"
icon="users"
href="/people"
chevron
/>
<ListRow
title="Trust"
subtitle="Biometrics, tracking, store reviews and the app badge"
icon="lock"
href="/trust"
chevron
/>
<ListRow
title="Sound and codes"
subtitle="Recording, speech and the barcode scanner"
icon="camera"
href="/sound"
chevron
/>
</Section>
</view>
</screen>pages/location.duo
---
import { onDispose, state } from "@duolith/client";
import { Button, ListRow, Section } from "@duolith/kit";
import { location, sensors } from "@duolith/effects";
let problem = state("");
async function findMe() {
problem = "";
try {
await location.current({ accuracy: "high", timeout: 10_000 });
} catch (failure) {
problem = (failure as Error).message;
}
}
// A watch runs until stopped; this screen stops its own when it closes.
let stopWatching = state<(() => void) | undefined>(undefined);
function follow() {
stopWatching?.();
stopWatching = stopWatching ? undefined : location.watch({ distance: 10 });
}
onDispose(() => stopWatching?.());
onDispose(sensors.watch("heading", { interval: 200 }));
onDispose(sensors.watch("accelerometer", { interval: 200 }));
function degrees(value: number | undefined): string {
return value === undefined ? "…" : `${Math.round(value)}°`;
}
---
<screen title="Where you are" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Device effects</text>
<text role="heading" class="text-title text-ink">Where you are</text>
<Section
title="Location"
footer={location.available ? "Asks for the location permission the first time." : location.unavailableReason}
>
<ListRow
title="Latitude"
value={location.position ? location.position.latitude.toFixed(5) : "…"}
/>
<ListRow
title="Longitude"
value={location.position ? location.position.longitude.toFixed(5) : "…"}
/>
<ListRow
title="Accuracy"
value={location.position ? `${Math.round(location.position.accuracy)} m` : "…"}
/>
<view class="row wrap gap-2 p-4">
<Button label="Find me" size="sm" onPress={findMe} />
<Button
label={location.watching ? "Stop following" : "Follow me"}
size="sm"
variant="secondary"
onPress={follow}
/>
</view>
<show when={problem || location.failure}>
<text class="text-caption text-danger px-4 pb-4">
{problem || location.failure?.message}
</text>
</show>
</Section>
<Section
title="Compass"
footer={sensors.available("heading") ? "Clockwise from magnetic north." : sensors.unavailableReason("heading")}
>
<ListRow title="Heading" value={degrees(sensors.reading("heading")?.degrees)} />
</Section>
<Section
title="Motion"
footer={sensors.available("accelerometer") ? "m/s², with gravity: a phone lying face up reads z ≈ 9.8." : sensors.unavailableReason("accelerometer")}
>
<ListRow title="x" value={sensors.reading("accelerometer")?.x.toFixed(2) ?? "…"} />
<ListRow title="y" value={sensors.reading("accelerometer")?.y.toFixed(2) ?? "…"} />
<ListRow title="z" value={sensors.reading("accelerometer")?.z.toFixed(2) ?? "…"} />
</Section>
</view>
</screen>pages/people.duo
---
import { state } from "@duolith/client";
import { Button, Image, ListRow, Section } from "@duolith/kit";
import { browser, calendar, clipboard, contacts, picker } from "@duolith/effects";
let contact = state<{ name: string; phones: string[]; emails: string[] } | undefined>(undefined);
let files = state<{ name: string; type: string; size: number; url: string }[]>([]);
let pasted = state("");
let said = state("");
/** Runs `work`, showing its failure's sentence instead of throwing. */
async function attempt(work: () => Promise<unknown>) {
said = "";
try {
const answer = await work();
if (typeof answer === "string") said = answer;
} catch (failure) {
said = (failure as Error).message;
}
}
const pickContact = (wants: "phone" | "email") => attempt(async () => (contact = await contacts.pick({ wants })));
const pickPhotos = () => attempt(async () => (files = await picker.pick({ kind: "image", multiple: true })));
const pickDocument = () => attempt(async () => (files = await picker.pick({ kind: "document", types: ["application/pdf"] })));
const copy = () => attempt(() => clipboard.writeText("Meet at the tower at noon"));
const paste = () => attempt(async () => (pasted = await clipboard.readText()));
const openTerms = (inApp: boolean) => attempt(() => browser.open("https://example.com/terms", { inApp }));
function addDinner() {
const start = new Date();
start.setDate(start.getDate() + 1);
start.setHours(19, 30, 0, 0);
const end = new Date(start.getTime() + 2 * 60 * 60 * 1000);
return attempt(() => calendar.addEvent({ title: "Dinner", start, end, location: "The tower", notes: "Book a table" }));
}
---
<screen title="People and things" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Device effects</text>
<text role="heading" class="text-title text-ink">People and things</text>
<show when={said}>
<text class="text-body text-muted">{said}</text>
</show>
<Section
title="Contacts"
footer={contacts.available ? "The system picker, with no permission: the app sees only the number or address you pick." : contacts.unavailableReason}
>
<ListRow title="Name" value={contact?.name ?? "…"} />
<ListRow title="Phone" value={contact?.phones[0] ?? "…"} />
<ListRow title="Email" value={contact?.emails[0] ?? "…"} />
<view class="row wrap gap-2 p-4">
<Button
label="A phone number"
size="sm"
disabled={!contacts.available}
onPress={() => pickContact("phone")}
/>
<Button
label="An email address"
size="sm"
variant="secondary"
disabled={!contacts.available}
onPress={() => pickContact("email")}
/>
</view>
</Section>
<Section
title="Calendar"
footer={calendar.available ? "Opens the calendar's own editor with dinner tomorrow at 19:30: no permission." : calendar.unavailableReason}
>
<view class="p-4">
<Button label="Add to the calendar" size="sm" onPress={addDinner} />
</view>
</Section>
<Section
title="Clipboard"
footer={pasted ? `Pasted: ${pasted}` : "Reading works only right after a press, and asks the user on some systems."}
>
<view class="row wrap gap-2 p-4">
<Button label="Copy" size="sm" variant="secondary" onPress={copy} />
<Button label="Paste" size="sm" variant="secondary" onPress={paste} />
</view>
</Section>
<Section
title="Files"
footer={picker.available ? "Chosen files stay on the device, until the app next starts." : picker.unavailableReason}
>
<list each={files} as="file" key={file.url}>
<ListRow title={file.name} value={`${Math.round(file.size / 1024)} KB · ${file.type}`} />
</list>
<show when={files[0]?.type.startsWith("image/")}>
<view class="p-4">
<Image
src={files[0]?.url ?? ""}
alt={`The photo ${files[0]?.name}`}
ratio="4:3"
radius="md"
/>
</view>
</show>
<view class="row wrap gap-2 p-4">
<Button label="Photos" size="sm" variant="secondary" onPress={pickPhotos} />
<Button label="A PDF" size="sm" variant="secondary" onPress={pickDocument} />
</view>
</Section>
<Section
title="Browser"
footer="Only http and https addresses open; the build refuses any other written here."
>
<view class="row wrap gap-2 p-4">
<Button
label="Terms, in the app"
size="sm"
variant="secondary"
onPress={() => openTerms(true)}
/>
<Button
label="Terms, in the browser"
size="sm"
variant="secondary"
onPress={() => openTerms(false)}
/>
</view>
</Section>
</view>
</screen>pages/phone.duo
---
import { state } from "@duolith/client";
import { Button, ListRow, Section, TextField, ToggleRow } from "@duolith/kit";
import { connection, device, display, keyboard } from "@duolith/effects";
let note = state("");
let outcome = state("");
async function keepAwake(on: boolean) {
outcome = await display.keepAwake(on);
}
async function lock(orientation: "portrait" | "landscape" | "any") {
try {
outcome = await display.lockOrientation(orientation);
} catch (failure) {
outcome = (failure as Error).message;
}
}
async function brighten(level: number | undefined) {
outcome = await display.setBrightness(level);
}
function insets(): string {
const { top, right, bottom, left } = device.safeArea;
return `${Math.round(top)} · ${Math.round(right)} · ${Math.round(bottom)} · ${Math.round(left)}`;
}
---
<screen title="This device" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Device effects</text>
<text role="heading" class="text-title text-ink">This device</text>
<Section title="Device" footer="Each value follows the system as it changes.">
<ListRow title="System" value={`${device.os} ${device.osVersion}`} />
<ListRow title="Model" value={device.model || "a browser"} />
<ListRow title="Language" value={device.locale} />
<ListRow title="Time zone" value={device.timeZone} />
<ListRow title="Safe area (top, right, bottom, left)" value={insets()} />
<ListRow title="Text size" value={`${Math.round(device.fontScale * 100)}%`} />
<ListRow title="Dark mode" value={device.dark ? "on" : "off"} />
</Section>
<Section title="Connection" footer="Metered connections cost the user: download less on them.">
<ListRow
title="Online"
value={connection.online ? "yes" : "no"}
icon={connection.online ? "wifi" : "wifi-off"}
/>
<ListRow title="Type" value={connection.type} />
<ListRow title="Metered" value={connection.metered ? "yes" : "no"} />
</Section>
<Section title="Keyboard" footer="Type in the field to open the keyboard.">
<view class="gap-3 p-4">
<TextField label="A note" bind:value={note} />
<text class="text-caption text-muted">
{keyboard.visible ? `The keyboard is open, ${Math.round(keyboard.height)} high.` : "The keyboard is closed."}
</text>
<Button
label="Close the keyboard"
size="sm"
variant="secondary"
onPress={() => keyboard.dismiss()}
/>
</view>
</Section>
<Section
title="Screen"
footer={outcome ? `Last: ${outcome}` : "Unavailable answers come back as a result, not an error."}
>
<ToggleRow label="Keep the screen awake" checked={display.awake} onChange={keepAwake} />
<ListRow title="Orientation" value={display.orientation} />
<view class="row wrap gap-2 p-4">
<Button label="Portrait" size="sm" variant="secondary" onPress={() => lock("portrait")} />
<Button label="Landscape" size="sm" variant="secondary" onPress={() => lock("landscape")} />
<Button label="Any" size="sm" variant="secondary" onPress={() => lock("any")} />
</view>
<ListRow
title="Brightness"
value={display.supports("brightness") ? (display.brightness === undefined ? "the system's" : `${Math.round(display.brightness * 100)}%`) : display.unavailableReason("brightness")}
/>
<view class="row wrap gap-2 p-4">
<Button label="Full" size="sm" variant="secondary" onPress={() => brighten(1)} />
<Button
label="The system's"
size="sm"
variant="secondary"
onPress={() => brighten(undefined)}
/>
</view>
</Section>
</view>
</screen>pages/sound.duo
---
import { onDispose, state } from "@duolith/client";
import { Button, ListRow, Section } from "@duolith/kit";
import { recorder, scanner, speech } from "@duolith/effects";
let recording = state<{ url: string; type: string; duration: number } | undefined>(undefined);
let code = state<Awaited<ReturnType<typeof scanner.scan>>>(undefined);
let problem = state("");
/** Runs `work`, showing its failure's sentence instead of throwing. */
async function attempt(work: () => Promise<unknown>) {
problem = "";
try {
await work();
} catch (failure) {
problem = (failure as Error).message;
}
}
const record = () => attempt(() => recorder.start());
const finish = () => attempt(async () => (recording = (await recorder.stop()) ?? recording));
const play = () => attempt(async () => recording && (await recorder.play(recording)));
const say = () => attempt(() => speech.speak("The tower is two hundred metres ahead.", { language: "en-GB" }));
const hear = () => attempt(() => speech.listen());
// The scanner closes with this screen.
const leaving = new AbortController();
onDispose(() => leaving.abort());
const scan = () => attempt(async () => (code = (await scanner.scan({ formats: ["qr", "ean13"], signal: leaving.signal })) ?? code));
---
<screen title="Sound and codes" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Device effects</text>
<text role="heading" class="text-title text-ink">Sound and codes</text>
<show when={problem}>
<text class="text-body text-danger">{problem}</text>
</show>
<Section
title="Recorder"
footer={recorder.available ? `Now: ${recorder.state}` : recorder.unavailableReason}
>
<ListRow
title="Last recording"
value={recording ? `${recording.duration.toFixed(1)} s, ${recording.type}` : "…"}
/>
<view class="row wrap gap-2 p-4">
<Button
label="Record"
size="sm"
disabled={recorder.state === "recording"}
onPress={record}
/>
<Button
label="Stop"
size="sm"
variant="secondary"
disabled={recorder.state !== "recording"}
onPress={finish}
/>
<Button label="Play" size="sm" variant="secondary" disabled={!recording} onPress={play} />
</view>
</Section>
<Section
title="Speech"
footer={speech.canListen ? (speech.listening ? "Listening…" : "Hearing asks for the speech permission.") : speech.listenUnavailableReason}
>
<ListRow title="Heard" value={speech.heard || "…"} />
<view class="row wrap gap-2 p-4">
<Button
label="Say it"
size="sm"
variant="secondary"
disabled={!speech.canSpeak}
onPress={say}
/>
<Button
label={speech.listening ? "Stop" : "Listen"}
size="sm"
variant="secondary"
disabled={!speech.canListen}
onPress={() => (speech.listening ? speech.stopListening() : hear())}
/>
</view>
</Section>
<Section
title="Scanner"
footer={scanner.available ? "QR codes and EAN-13 barcodes." : scanner.unavailableReason}
>
<ListRow title="Code" value={code ? `${code.value} (${code.format})` : "…"} />
<view class="p-4">
<Button label="Scan" size="sm" onPress={scan} />
</view>
</Section>
</view>
</screen>pages/trust.duo
---
import { state } from "@duolith/client";
import { Badge, Button, ListRow, Section } from "@duolith/kit";
import { badge, biometrics, review, tracking } from "@duolith/effects";
let unlocked = state("");
let reviewed = state("");
let badged = state("");
async function unlock() {
unlocked = await biometrics.authenticate({ reason: "Unlock your notes", allowCredential: true });
}
async function askForReview() {
reviewed = await review.request();
}
async function setBadge(count: number) {
badged = await badge.set(count);
}
---
<screen title="Trust" class="bg-canvas">
<view class="gap-6 p-4 md:p-8">
<text class="text-label text-primary" href="/">‹ Device effects</text>
<text role="heading" class="text-title text-ink">Trust</text>
<Section
title="Biometrics"
footer={biometrics.available ? `Uses ${biometrics.kind}, or the passcode when allowed.` : biometrics.unavailableReason}
>
<view class="row items-center gap-3 p-4">
<Button label="Unlock" size="sm" onPress={unlock} />
<show when={unlocked}>
<Badge label={unlocked} tone={unlocked === "authenticated" ? "success" : "danger"} />
</show>
</view>
</Section>
<Section
title="Tracking"
footer={tracking.needed ? "iOS asks before an app tracks you across other companies' apps." : "This platform has no tracking prompt: the answer is not-needed."}
>
<ListRow title="Status" value={tracking.status} />
<view class="p-4">
<Button label="Ask" size="sm" variant="secondary" onPress={() => tracking.request()} />
</view>
</Section>
<Section
title="Store review"
footer={review.available ? "The store decides whether to show its card." : review.unavailableReason}
>
<view class="row items-center gap-3 p-4">
<Button label="Ask for a review" size="sm" variant="secondary" onPress={askForReview} />
<show when={reviewed}>
<Badge label={reviewed} tone={reviewed === "requested" ? "success" : "neutral"} />
</show>
</view>
</Section>
<Section
title="App badge"
footer={badge.available ? `Showing ${badge.count}.` : badge.unavailableReason}
>
<view class="row items-center gap-3 p-4">
<Button label="Show 3" size="sm" variant="secondary" onPress={() => setBadge(3)} />
<Button label="Clear" size="sm" variant="secondary" onPress={() => setBadge(0)} />
<show when={badged}>
<Badge label={badged} tone={badged === "set" ? "success" : "neutral"} />
</show>
</view>
</Section>
</view>
</screen>