Duolith docs

production

Consent (a banner and a privacy screen, with Global Privacy Control), analytics, crash reports and translation from @duolith/adapters, in English and Arabic (right to left), with a Reports screen showing what was sent; duolith scan examples/production checks its two vendored packages.

Run it

cargo run -p duolith-cli -- dev examples/production     # live, reloads on save
cargo run -p duolith-cli -- build examples/production   # static output in examples/production/dist

The folder on the web: examples/production.

Features it shows

FeatureWhereScreenshot
Native source maps: a thrown error's frames map back to the page line (scripts/map-frames.ts)production pages/index.duo ("Report a test error")packages/engine/test/native-production-in-browser.test.ts, crates/emit-native/src/lib.rs tests
Consent by category, remembered on the device, with Global Privacy Control (startConsent, consent())production pages/_layout.duo, components/ConsentBanner.duo, pages/settings.duoproduction-consent-banner.png, production-settings.png
Analytics: automatic screen views, typed track(), batches sent by beacon on hide (startAnalytics)production pages/_layout.duo, pages/index.duoproduction-home.png
Crash reports with the screen, breadcrumbs and source-mapped frames (startCrashReporting, captureError)production pages/index.duo ("Report a test error"), pages/reports.duoproduction-reports.png
Translation: t() with ICU plurals and selects, locales/*.json checked at build (E0280 to E0283)production locales/en.json, locales/ar.jsonproduction-home.png, production-settings-ar.png
Locale detection, setLocale(), right-to-left dir, number, date and relative-time formattingproduction pages/settings.duo (Language)production-settings-ar.png
duolith scan: a verdict per npm dependency for web, iOS and Android (E0285 to E0289)production package.json (vendor/tiny-ordinal, vendor/dom-tooltip)none: shown under CLI

Source

components/ConsentBanner.duo
---
// The consent banner: shown until the person chooses, styled with the kit's
// tokens and Buttons. Copy it into an app's components/ folder and change the
// words in locales/; see docs/guide/production.md.
import { navigate } from "@duolith/client";
import { Button } from "@duolith/kit";
import { consent, t } from "@duolith/adapters";

function choose() {
  navigate("/settings");
}
---

<show when={!consent().decided}>
  <view
    class="banner gap-3 p-4 bg-surface border border-border rounded-xl shadow-lg"
    role="group"
    labelled-by="consent-title"
  >
    <text id="consent-title" role="heading" class="text-heading text-ink">
      {t("consent.title")}
    </text>
    <text class="text-body text-muted">{t("consent.body")}</text>
    <show when={consent().globalPrivacyControl}>
      <text class="text-caption text-muted">{t("consent.gpc")}</text>
    </show>
    <view class="row wrap gap-2 justify-end">
      <Button label={t("consent.choose")} variant="ghost" onPress={choose} />
      <Button
        label={t("consent.refuse")}
        variant="secondary"
        onPress={() => consent().refuseAll()}
      />
      <Button label={t("consent.accept")} onPress={() => consent().acceptAll()} />
    </view>
  </view>
</show>

<style>
  .banner {
    position: fixed;
    inset-inline: 12px;
    bottom: calc(76px + env(safe-area-inset-bottom));
    z-index: 20;
    max-width: 560px;
    margin-inline: auto;
  }
</style>
components/sent.ts
import type { AnalyticsBatch, CrashReport } from "@duolith/adapters";

/** One payload the layout's transports were given, as the Reports screen lists it. */
export type SentEntry =
  | { id: number; kind: "crash"; payload: CrashReport; leaving: boolean }
  | { id: number; kind: "analytics"; payload: AnalyticsBatch; leaving: boolean };
locales/ar.json
{
  "tabs": {
    "home": "الرئيسية",
    "settings": "الإعدادات",
    "reports": "التقارير"
  },
  "home": {
    "title": "اليوم",
    "greeting": "سعداء برؤيتك يا {name}",
    "posts": "{count, plural, =0 {لا منشورات جديدة} one {منشور جديد واحد} two {منشوران جديدان} few {# منشورات جديدة} many {# منشورًا جديدًا} other {# منشور جديد}}",
    "numbers": "بلغتك",
    "error": "أبلغ عن خطأ تجريبي",
    "errorHint": "يرمي خطأً عمدًا لإنشاء تقرير أعطال."
  },
  "post": {
    "likes": "{count, plural, =0 {لا إعجابات بعد} one {إعجاب واحد} two {إعجابان} few {# إعجابات} many {# إعجابًا} other {# إعجاب}}",
    "like": "إعجاب",
    "posted": "نُشر {when}"
  },
  "stats": {
    "readers": "القرّاء",
    "share": "قرؤوا حتى النهاية",
    "joined": "عضو منذ"
  },
  "consent": {
    "title": "خصوصيتك",
    "body": "نودّ أن نعرف أي الشاشات تُستخدم وأن نتلقى تقارير الأعطال لتحسين التطبيق. لا يُرسل شيء حتى تختار.",
    "gpc": "متصفحك يطلب من المواقع عدم مشاركة بياناتك، لذا تبقى التحليلات متوقفة.",
    "accept": "قبول الكل",
    "refuse": "رفض",
    "choose": "اختيار"
  },
  "settings": {
    "title": "الإعدادات",
    "privacy": "الخصوصية",
    "analytics": "تحليلات الاستخدام",
    "analyticsHint": "أي الشاشات تُفتح وما الذي يُعجبك، دون معرفة هويتك.",
    "crashes": "تقارير الأعطال",
    "crashesHint": "ما الذي حدث خطأً، والشاشات التي سبقته.",
    "gpcOn": "التحكم العالمي في الخصوصية مفعّل، لذا تبقى التحليلات متوقفة.",
    "saved": "يُحفظ على هذا الجهاز.",
    "askAgain": "اسألني مجددًا",
    "language": "اللغة"
  },
  "reports": {
    "title": "التقارير",
    "empty": "لم يُرسل شيء بعد",
    "emptyHint": "اقبل التحليلات أو تقارير الأعطال، ثم استخدم التطبيق.",
    "batch": "{count, plural, zero {لا أحداث} one {حدث واحد} two {حدثان} few {# أحداث} many {# حدثًا} other {# حدث}}",
    "crash": "عطل: {message}",
    "beacon": "أُرسل عبر إشارة",
    "screen": "في {screen}"
  }
}
locales/en.json
{
  "tabs": {
    "home": "Home",
    "settings": "Settings",
    "reports": "Reports"
  },
  "home": {
    "title": "Today",
    "greeting": "Good to see you, {name}",
    "posts": "{count, plural, =0 {No new posts} one {# new post} other {# new posts}}",
    "numbers": "In your language",
    "error": "Report a test error",
    "errorHint": "Throws an error on purpose, so a crash report is made."
  },
  "post": {
    "likes": "{count, plural, =0 {No likes yet} one {# like} other {# likes}}",
    "like": "Like",
    "posted": "Posted {when}"
  },
  "stats": {
    "readers": "Readers",
    "share": "Read to the end",
    "joined": "Member since"
  },
  "consent": {
    "title": "Your privacy",
    "body": "We'd like to count which screens are used and receive crash reports, to make the app better. Nothing is sent until you choose.",
    "gpc": "Your browser asks sites not to share your data, so analytics stays off.",
    "accept": "Accept all",
    "refuse": "Refuse",
    "choose": "Choose"
  },
  "settings": {
    "title": "Settings",
    "privacy": "Privacy",
    "analytics": "Usage analytics",
    "analyticsHint": "Which screens are opened and what is liked, never who you are.",
    "crashes": "Crash reports",
    "crashesHint": "What went wrong, and the screens before it.",
    "gpcOn": "Global Privacy Control is on, so analytics stays off.",
    "saved": "Kept on this device.",
    "askAgain": "Ask me again",
    "language": "Language"
  },
  "reports": {
    "title": "Reports",
    "empty": "Nothing sent yet",
    "emptyHint": "Accept analytics or crash reports, then use the app.",
    "batch": "{count, plural, one {# event} other {# events}}",
    "crash": "Crash: {message}",
    "beacon": "sent by beacon",
    "screen": "on {screen}"
  }
}
package.json
{
  "name": "duolith-example-production",
  "private": true,
  "description": "Lists two small vendored packages so `duolith scan examples/production` has something to check: one works on every target, one only on the web.",
  "dependencies": {
    "tiny-ordinal": "file:./vendor/tiny-ordinal",
    "dom-tooltip": "file:./vendor/dom-tooltip"
  }
}
pages/_layout.duo
---
import { state } from "@duolith/client";
import { TabBar, TabBarItem } from "@duolith/kit";
import { consoleTransport, startAnalytics, startConsent, startCrashReporting, startTranslation, t } from "@duolith/adapters";
import type { AnalyticsBatch, CrashReport, Transport } from "@duolith/adapters";
import ConsentBanner from "../components/ConsentBanner.duo";
import type { SentEntry } from "../components/sent.ts";

// What the transports were given, newest first, so the Reports screen can show
// it. A real app passes httpTransport("https://...") or a provider's transport.
let sent = state<SentEntry[]>([], { shared: "sent" });

const printedCrashes = consoleTransport<CrashReport>({ label: "duolith crash" });
const printedBatches = consoleTransport<AnalyticsBatch>({ label: "duolith analytics" });

const crashes: Transport<CrashReport> = {
  send(payload, delivery) {
    sent = [{ id: sent.length + 1, kind: "crash", payload, leaving: delivery.leaving }, ...sent];
    return printedCrashes.send(payload, delivery);
  },
};

const batches: Transport<AnalyticsBatch> = {
  send(payload, delivery) {
    sent = [{ id: sent.length + 1, kind: "analytics", payload, leaving: delivery.leaving }, ...sent];
    return printedBatches.send(payload, delivery);
  },
};

const consent = startConsent();
startTranslation({ fallback: "en" });
startCrashReporting({ transport: crashes, consent, release: "1.0.0" });
startAnalytics({ transport: batches, consent, flushAfter: 1500 });
---

<view class="lg:row">
  <slot />
  <ConsentBanner />
  <TabBar>
    <TabBarItem label={t("tabs.home")} icon="home" href="/" exact />
    <TabBarItem label={t("tabs.settings")} icon="settings" href="/settings" />
    <TabBarItem label={t("tabs.reports")} icon="inbox" href="/reports" badge={sent.length} />
  </TabBar>
</view>
pages/index.duo
---
import { state } from "@duolith/client";
import { Button, Card, NavHeader, Section, ListRow } from "@duolith/kit";
import { formatDate, formatNumber, formatRelativeTime, t, track } from "@duolith/adapters";

const now = Date.now();
const hour = 3600 * 1000;
let posts = state([
  { id: "p1", title: "Lake at dawn", likes: 0, at: now - 3 * hour },
  { id: "p2", title: "Night market", likes: 1, at: now - 26 * hour },
  { id: "p3", title: "Rooftop garden", likes: 24, at: now - 9 * 24 * hour },
]);

function like(id: string) {
  posts = posts.map((post) => (post.id === id ? { ...post, likes: post.likes + 1 } : post));
  track("post.liked", { id });
}

function reportTestError() {
  throw new Error("A test error from the Home screen");
}
---

<screen title={t("home.title")} class="bg-canvas">
  <NavHeader title={t("home.title")} large />

  <view class="gap-6 p-4 pb-24">
    <view class="gap-1">
      <text class="text-heading text-ink">{t("home.greeting", { name: "Ada" })}</text>
      <text class="text-body text-muted">{t("home.posts", { count: posts.length })}</text>
    </view>

    <list each={posts} as="post" key={post.id} class="gap-3">
      <Card
        title={post.title}
        subtitle={t("post.posted", { when: formatRelativeTime(post.at, now) })}
      >
        <view class="row items-center justify-between">
          <text class="text-caption text-muted">{t("post.likes", { count: post.likes })}</text>
          <Button
            label={t("post.like")}
            icon="heart"
            size="sm"
            variant="secondary"
            onPress={() => like(post.id)}
          />
        </view>
      </Card>
    </list>

    <Section title={t("home.numbers")}>
      <ListRow title={t("stats.readers")} value={formatNumber(1234567.5)} icon="user" />
      <ListRow
        title={t("stats.share")}
        value={formatNumber(0.42, { style: "percent" })}
        icon="check"
      />
      <ListRow
        title={t("stats.joined")}
        value={formatDate(Date.UTC(2024, 2, 9), { dateStyle: "long" })}
        icon="calendar"
      />
    </Section>

    <view class="gap-2">
      <Button
        label={t("home.error")}
        variant="danger"
        icon="alert"
        full
        onPress={reportTestError}
      />
      <text class="text-caption text-muted">{t("home.errorHint")}</text>
    </view>
  </view>
</screen>
pages/reports.duo
---
import { state } from "@duolith/client";
import { EmptyState, ListRow, NavHeader, Section } from "@duolith/kit";
import { formatDate, t } from "@duolith/adapters";
import type { SentEntry } from "../components/sent.ts";

// What the layout's transports were given, newest first.
let sent = state<SentEntry[]>([], { shared: "sent" });

function titleOf(entry: SentEntry) {
  if (entry.kind === "crash") return t("reports.crash", { message: entry.payload.error.message });
  return t("reports.batch", { count: entry.payload.events.length });
}

function detailOf(entry: SentEntry) {
  if (entry.kind === "crash") {
    const pattern = entry.payload.screen?.pattern ?? "/";
    return t("reports.screen", { screen: pattern });
  }
  const names = entry.payload.events.map((event) => event.name === "screen" ? event.properties["pattern"] : event.name);
  return names.join(", ") + (entry.leaving ? ` · ${t("reports.beacon")}` : "");
}

function timeOf(entry: SentEntry) {
  const at = entry.kind === "crash" ? entry.payload.at : entry.payload.events[0]?.at;
  return at === undefined ? "" : formatDate(at, { timeStyle: "short" });
}
---

<screen title={t("reports.title")} class="bg-canvas">
  <NavHeader title={t("reports.title")} large />

  <view class="gap-6 p-4 pb-24">
    <show when={sent.length > 0}>
      <Section>
        <list each={sent} as="entry" key={entry.id}>
          <ListRow
            title={titleOf(entry)}
            subtitle={detailOf(entry)}
            value={timeOf(entry)}
            icon={entry.kind === "crash" ? "alert" : "send"}
          />
        </list>
      </Section>
    </show>
    <otherwise>
      <EmptyState title={t("reports.empty")} message={t("reports.emptyHint")} icon="inbox" />
    </otherwise>
  </view>
</screen>
pages/settings.duo
---
import { Button, NavHeader, Section, ToggleRow } from "@duolith/kit";
import { consent, currentLocale, t, translation } from "@duolith/adapters";

const languages = [
  { locale: "en", name: "English" },
  { locale: "ar", name: "العربية" },
];

/** Grants or refuses one category, keeping the person's other choices. */
function setCategory(name: string, granted: boolean) {
  const choices = Object.fromEntries(consent().categories.map((category) => [category.name, consent().granted(category.name)]));
  consent().choose({ ...choices, [name]: granted });
}

function useLanguage(locale: string) {
  translation().setLocale(locale);
}
---

<screen title={t("settings.title")} class="bg-canvas">
  <NavHeader title={t("settings.title")} large />

  <view class="gap-6 p-4 pb-24">
    <Section
      title={t("settings.privacy")}
      footer={consent().globalPrivacyControl ? t("settings.gpcOn") : t("settings.saved")}
    >
      <ToggleRow
        label={t("settings.analytics")}
        hint={t("settings.analyticsHint")}
        icon="eye"
        checked={consent().granted("analytics")}
        disabled={!consent().choosable("analytics")}
        onChange={(on) => setCategory("analytics", on)}
      />
      <ToggleRow
        label={t("settings.crashes")}
        hint={t("settings.crashesHint")}
        icon="alert"
        checked={consent().granted("crashes")}
        onChange={(on) => setCategory("crashes", on)}
      />
    </Section>

    <Button
      label={t("settings.askAgain")}
      variant="ghost"
      icon="refresh"
      onPress={() => consent().reset()}
    />

    <Section title={t("settings.language")}>
      <view class="row gap-2 p-3">
        <list each={languages} as="language" key={language.locale} class="row gap-2">
          <Button
            label={language.name}
            variant={currentLocale() === language.locale ? "primary" : "secondary"}
            onPress={() => useLanguage(language.locale)}
          />
        </list>
      </view>
    </Section>
  </view>
</screen>
vendor/dom-tooltip/package.json
{
  "name": "dom-tooltip",
  "version": "0.4.2",
  "license": "MIT",
  "main": "tooltip.js"
}
vendor/tiny-ordinal/package.json
{
  "name": "tiny-ordinal",
  "version": "1.0.0",
  "license": "MIT",
  "main": "index.js"
}