Recipes

Examples.

Inline examples that render Streaming UI Script live. Switch to the source tab to see the exact text the renderer receives, and use the theme picker to test contrast.

Need to wire up behaviour (timers, fetch, focus, animations, clipboard) inside an assistant response? See the dedicated JavaScript interactions page — the LLM can always author Script(...) and @Js(...) for anything the declarative components don't cover.

Looking for end-to-end demos?

Every standalone live demo — chat bots, tools, routing, rich patterns, commerce, inbox, CRM, pricing — now lives in one searchable catalog.

Browse the live examples →

Inline examples

Chat-style assistant response

root = Stack([intro, steps, follow])
intro = Card([CardHeader("Onboarding plan", "3 steps to set up your workspace")])
steps = Steps([
  StepsItem("Invite teammates", "Open the Members tab and send invites."),
  StepsItem("Connect a data source", "Settings → Integrations → choose a provider."),
  StepsItem("Pick a starter template", "Seed the workspace with sample content.")
])
follow = FollowUpBlock([
  FollowUpItem("Show invite link"),
  FollowUpItem("List supported integrations"),
  FollowUpItem("Open the templates gallery")
])

Searchable, sortable table (reactive state)

$search = ""
$sortBy = "stars"
data = Query("get_repos", {}, {rows: [
  {name: "ui-lang", stars: 1820, forks: 220},
  {name: "rich-ui", stars: 940, forks: 80},
  {name: "ai-toolkit", stars: 2300, forks: 412}
]})
filtered = @Filter(data.rows, "name", "contains", $search)
sorted = @Sort(filtered, $sortBy, "desc")
searchBox = FormControl("Search", Input("search", "Filter repos...", "text", null, $search))
sortSelect = FormControl("Sort by", Select("sortBy", [SelectItem("stars","Stars"), SelectItem("forks","Forks")], null, null, $sortBy))
controls = Stack([searchBox, sortSelect], "row", "m")
tbl = Table([
  Col("Name", sorted.name),
  Col("Stars", sorted.stars, "number"),
  Col("Forks", sorted.forks, "number")
])
empty = TextContent("No results match your search.", "small", "muted")
view = @Count(filtered) > 0 ? tbl : empty
root = Stack([Card([CardHeader("Repositories"), controls, view])])

Form with state and a submit action

$title = ""
$priority = "medium"
$lastSaved = "Nothing yet"
saveBtn = Button("Save", Action([@Set($lastSaved, "" + $title + " (" + $priority + ")"), @Reset($title, $priority)]), "primary")
form = Form("ticket", saveBtn, [
  FormControl("Title", Input("title", "Short summary", "text", ["required","minLength:3"], $title)),
  FormControl("Priority", Select("priority", [SelectItem("low","Low"), SelectItem("medium","Medium"), SelectItem("high","High")], null, null, $priority))
])
status = Card([CardHeader("Last saved"), Markdown("`" + $lastSaved + "`")])
root = Stack([form, status])

Dashboard with KPIs and chart

$range = "q3"
header = PageHeader("Q3 performance", "Updated nightly · all amounts in USD",
  ["Workspace", "Analytics", "Q3"],
  [Button("Export", Action([@ToAssistant("Export Q3 performance as PDF")]), "secondary"),
   Button("Schedule digest", Action([@ToAssistant("Schedule a weekly digest")]), "primary")],
  Badge("Live", "success"))
toolbar = Toolbar([
  FormControl("Range", Select("range", [SelectItem("q1","Q1"), SelectItem("q2","Q2"), SelectItem("q3","Q3")], null, null, $range))
], [StatusDot("Streaming", "success", true)])
kpis = MetricGrid([
  StatCard("Revenue",     "$48,230", "up",   "+12% vs Q2", "sack-dollar"),
  StatCard("Active users","12,540",  "up",   "+8% vs Q2",  "users"),
  StatCard("Churn",       "2.1%",    "down", "-0.4 pp",    "arrow-trend-down"),
  StatCard("NPS",         "62",      "flat", "+1",         "star")
])
trafficCard = Card([SectionHeader("Daily traffic", "Visits vs signups", null, Tag("On track", null, "sm", "success")),
  LineChart(["Mon","Tue","Wed","Thu","Fri"], [Series("Visits",[120,180,160,210,250]), Series("Signups",[12,18,15,22,28])])])
mixCard = Card([SectionHeader("Plan mix", "Active subscribers by tier", null, null),
  PieChart(["Free","Pro","Team"], [240, 95, 32])])
charts = Grid([trafficCard, mixCard], 2, "l")
topAccounts = Card([SectionHeader("Top accounts", "Largest MRR contributors", null, null,
  [Button("View all", Action([@ToAssistant("Open the accounts list")]), "ghost", "button", "small")]), Table([
  Col("Account", ["Acme","Globex","Initech"]),
  Col("MRR", [4200, 2400, 1850], "currency"),
  Col("Plan", [Tag("Team",null,"sm","primary"), Tag("Pro",null,"sm","success"), Tag("Free",null,"sm","neutral")])
])])
follow = FollowUpBlock(["Drill into churn", "Compare to last quarter", "Open billing"])
root = Stack([header, toolbar, kpis, charts, topAccounts, follow], "column", "l")

Tabs with shared state

$days = "7"
filter = FormControl("Range", Select("days", [SelectItem("7","7d"), SelectItem("14","14d"), SelectItem("30","30d")], null, null, $days))
overview = TabItem("overview", "Overview", [
  Markdown("Showing data for the last **" + $days + " days**."),
  LineChart(["d1","d2","d3","d4","d5"], [Series("Events",[400,500,460,520,580])])
])
errors = TabItem("errors", "Errors", [
  Callout("success", "System healthy", "No incidents in the selected range.")
])
tabs = Tabs([overview, errors])
root = Stack([Card([CardHeader("Operations"), filter, tabs])])

Tags, separators, and a code block

root = Stack([header, tags, sep, snippet, group])
header = CardHeader("Release notes", "v1.2 highlights")
tags = TagBlock(["new", "tabs", "callout", "separator"], "primary", "sm")
sep = Separator("horizontal")
snippet = CodeBlock("ts", "import { defineElement } from \"streaming-ui-script\";\ndefineElement();")
group = CheckBoxGroup("notifications", [
  CheckBoxItem("Product updates", "product", "Major releases & changelogs", true),
  CheckBoxItem("Security alerts", "security", "Critical fixes", true),
  CheckBoxItem("Newsletter", "newsletter", "Monthly digest")
])

Rich layouts (production-quality)

These compositions show what the LLM should reach for by default: a full app shell, a detail page, and a pricing page — all built from the same component vocabulary as the smaller examples above. Use them as a baseline for any "build me an app" request.

App shell with sidebar nav

root = AppShell(nav, content, topbar)

nav = Sidebar([
  SidebarSection("Workspace", [
    SidebarItem("Overview",  "house", true),
    SidebarItem("Projects",  "folder", false, "12"),
    SidebarItem("Calendar",  "calendar"),
    SidebarItem("Messages",  "comments", false, "3")
  ]),
  SidebarSection("Insights", [
    SidebarItem("Analytics", "chart-pie"),
    SidebarItem("Reports",   "chart-line"),
    SidebarItem("Billing",   "credit-card")
  ])
], "Acme HQ", "Production · v2.3",
  Stack([Avatar("Asha Patel", null, "sm"),
   Button("Settings", Action([@ToAssistant("Open settings")]), "ghost", "button", "small")], 2))

topbar = [StatusDot("Realtime", "success", true),
  Buttons([Button("Invite", null, "ghost", "button", "small"),
           Button("Upgrade", null, "primary", "button", "small")])]

header = PageHeader("Overview", "Everything happening across your workspace",
  null,
  [Button("New project", Action([@ToAssistant("Start a new project")]), "primary")],
  Badge("Live", "success"))

kpis = MetricGrid([
  StatCard("MRR",          "$48.2k", "up",   "+12%", "sack-dollar"),
  StatCard("Active users", "2,184",  "up",   "+184", "users"),
  StatCard("Open tickets", "23",     "down", "-9",   "ticket"),
  StatCard("NPS",          "62",     "flat", "+1",   "star")
])

projects = Card([SectionHeader("Active projects", null, "WORK", null,
  [Button("View all", null, "ghost", "button", "small")]),
  List([
    ListItem("Streaming UI v2.4", "Ada Lovelace · 3 open issues", "rocket"),
    ListItem("Auth SDK rewrite",  "Linus T · 1 open issue",       "shield-halved"),
    ListItem("Onboarding revamp", "Grace Hopper · awaiting QA",   "bullseye")
  ])])

systemCard = Card([SectionHeader("System status", null, "OPS",
  Tag("All normal", null, "sm", "success")),
  Stack([
    StatusDot("API",       "success"),
    StatusDot("Database",  "success"),
    StatusDot("Webhooks",  "warning"),
    StatusDot("Streaming", "success", true)
  ], "column", "s")])

activity = Card([SectionHeader("Recent activity"), Timeline([
  TimelineItem("Ada merged PR #248",    "5m ago",   "Patterns ready for review",   "code-pull-request", "primary"),
  TimelineItem("QA caught regression",  "1h ago",   "Quota dashboard double-count","triangle-exclamation", "warning"),
  TimelineItem("Tokenizer 2.1 shipped", "Yesterday","Latency -14%",                "circle-check", "success")
])])

content = [header, kpis, Grid([projects, systemCard], 2, "l"), activity,
  FollowUpBlock(["Show at-risk projects", "Open billing", "Invite my team"])]

Detail page (PageHeader + DescriptionList + activity)

header = PageHeader("Alex Rivera", "Product Designer · alex@acme.com",
  ["Team", "Engineering"],
  [Button("Message", Action([@ToAssistant("Open chat with Alex")]), "primary"),
   Button("Edit", Action([@ToAssistant("Edit Alex's profile")]), "ghost")],
  Tag("Online", "circle-check", "sm", "success"))

profile = ProfileCard("Alex Rivera", "Product Designer", "",
  "Designs the future of generative UI at Acme.",
  ["design", "ux", "typography"],
  [Button("Follow", Action([@ToAssistant("Follow Alex")]), "primary", "button", "small"),
   Button("Resume", Action([@OpenUrl("/resume.pdf")]), "ghost", "button", "small")])

details = Card([SectionHeader("Profile details", null, "OVERVIEW"),
  DescriptionList([
    DescriptionItem("Team",     "Design Systems", "users"),
    DescriptionItem("Manager",  "Margaret Hamilton"),
    DescriptionItem("Location", "Berlin, DE", "location-dot"),
    DescriptionItem("Joined",   "Mar 2022"),
    DescriptionItem("Slack",    Tag("@alex", null, "sm", "primary")),
    DescriptionItem("Status",   StatusDot("Active", "success"))
  ], 2)])

activity = Card([SectionHeader("Recent activity", "Last 14 days"), Timeline([
  TimelineItem("Shipped v2.0",         "2h ago",     "Updated 14 components and added the patterns API.", "rocket", "success"),
  TimelineItem("Joined Design Review", "Yesterday",  "Reviewed the dashboard wireframes.",                "palette", "primary"),
  TimelineItem("Profile updated",      "3 days ago", "",                                                  "pen")
])])

danger = Card([SectionHeader("Danger zone", "Irreversible — proceed with care"),
  Buttons([Button("Delete account", Action([@ToAssistant("Delete Alex's account")]), "danger")])])

follow = FollowUpBlock(["Show Alex's projects", "Open inbox", "Schedule a 1:1"])

root = Stack([header, Grid([profile, details], 2, "l"), activity, danger, follow], "column", "l")

Pricing page (Hero + PricingTable + FAQ)

hero = Hero(
  "Pricing that scales with you",
  "Start free, upgrade as your team grows. No hidden fees.",
  Button("Compare plans", Action([@OpenUrl("#tiers")]), "primary"),
  Button("Contact sales", Action([@OpenUrl("/contact")]), "secondary"),
  "PRICING",
  ["Free for hobby projects", "Cancel anytime", "Annual discount: 20%"]
)

pricing = PricingTable([
  PricingCard("Starter", "$0", "/mo", "For hobby projects and side experiments.",
    ["1 workspace", "Up to 5 contributors", "Community support", "1 GB storage"],
    Button("Get started", Action([@OpenUrl("/signup?plan=starter")]), "secondary"),
    null, false),
  PricingCard("Pro", "$29", "/mo", "For teams shipping LLM features in production.",
    ["Unlimited workspaces", "All themes + patterns", "Priority support", "100 GB storage", "SOC2 audit logs"],
    Button("Start free trial", Action([@OpenUrl("/signup?plan=pro")]), "primary"),
    "Most popular", true),
  PricingCard("Scale", "Talk to us", null, "For companies with custom requirements.",
    ["Dedicated success manager", "Custom themes", "SSO + SCIM", "99.99% SLA", "On-prem available"],
    Button("Contact sales", Action([@OpenUrl("/contact")]), "ghost"),
    null, false)
])

faqs = Card([SectionHeader("Frequently asked questions"), Accordion([
  AccordionItem("Can I switch plans later?", [Markdown("Yes — upgrade or downgrade any time from **Billing → Subscription**.")]),
  AccordionItem("Do you offer student discounts?", [Markdown("**50% off Pro** for verified students and educators.")]),
  AccordionItem("How does the free trial work?", [Markdown("14-day Pro trial. No credit card. Cancel any time.")])
])])

closing = Banner("Still deciding?", "Talk to a real human about your use case.",
  Button("Book a call", Action([@OpenUrl("/contact")]), "primary"), "comments", "primary")

follow = FollowUpBlock(["Compare to competitors", "Show the enterprise plan", "Open the FAQ"])

root = Stack([hero, pricing, faqs, closing, follow], "column", "xl")

Richer composition primitives

Bite-sized examples for the newer high-density patterns — Cover, MediaCard, Stats, Tile, Notification, PersonChip, Quote, Note, Rating, ProgressRing, ChatBubble, and SearchBar. Use them whenever you'd otherwise be stitching primitives together by hand.

Cover hero with caption + actions

root = Cover(
  "Build the future of generative UI",
  "https://images.unsplash.com/photo-1551434678-e076c223a692?w=1600&q=80",
  "From a single LLM prompt to a streaming, themeable, interactive UI — in 90 seconds.",
  "Spring release",
  "Cancel anytime · no credit card to start",
  [Button("Get started", Action([@ToAssistant("Start the free plan")]), "primary"),
   Button("Watch the demo", Action([@OpenUrl("https://example.com/demo")]), "ghost")],
  "primary",
  "300px"
)

MediaCard grid + Rating

root = Stack([
  Grid([
    MediaCard("Aurora Headphones",
              "https://images.unsplash.com/photo-1518443895914-83a35c1eed90?w=900&q=80",
              "Studio-grade sound, 40-hour battery.",
              ["wireless", "ANC"],
              "$249 · 4.8 stars",
              [Button("Add to cart", Action([@ToAssistant("Add Aurora to cart")]), "primary")]),
    MediaCard("Aurora Earbuds",
              "https://images.unsplash.com/photo-1606220588913-b3aacb4d2f46?w=900&q=80",
              "Same DAC, in-ear comfort.",
              ["wireless", "in-ear"],
              "$149 · 4.7 stars",
              [Button("Add to cart", Action([@ToAssistant("Add earbuds to cart")]), "primary")])
  ], 2, "m"),
  Rating(4.8, 5, "Average rating", 1284, "md", false)
], "column", "l")

Stats trust strip

root = Stats([
  {label: "Teams trust it",   value: "2,400+",  hint: "In 40 countries",        tone: "primary"},
  {label: "Uptime SLA",       value: "99.99%",  hint: "Multi-region",           tone: "success"},
  {label: "Time to first UI", value: "<90 sec", hint: "Signup → render",        tone: "info"},
  {label: "Support reply",    value: "<1 hr",   hint: "Median weekday reply",   tone: "warning"}
], "center")

Tile grid quick-actions

root = Grid([
  Tile("Total contacts",   "users", "2,481",  "+128 this week",            "primary",  Action([@ToAssistant("Show contacts")])),
  Tile("Active deals",     "briefcase", "47",     "$418k ARR pipeline",        "info",     Action([@ToAssistant("Show deals")])),
  Tile("At-risk accounts", "triangle-exclamation", "12",     "Needs follow-up this week", "warning",  Action([@ToAssistant("Show at-risk")])),
  Tile("Champions",        "trophy", "63",     "NPS 9 or 10 in last 30d",   "success",  Action([@ToAssistant("Show champions")]))
], 4, "m")

Notification panel

root = Stack([
  Notification("Stripe receipts",
               "Receipt for Pro plan — $29.00 charged today.",
               "10:24 AM", null,
               "https://i.pravatar.cc/64?img=12",
               "primary", true,
               [Button("Open", Action([@ToAssistant("Open the receipt")]), "ghost", "button", "small")]),
  Notification("GitHub digest",
               "12 new pull requests waiting for review across 3 repos.",
               "Yesterday", "code-branch", null,
               "info", false,
               [Button("Open", Action([@OpenUrl("https://github.com/")]), "ghost", "button", "small")]),
  Notification("Linus Torvalds",
               "Perf review attached. Some easy wins on the parser.",
               "Mon", null,
               "https://i.pravatar.cc/64?img=11",
               "default", false,
               [Button("Reply", Action([@ToAssistant("Reply to Linus")]), "ghost", "button", "small")])
], "column", "s")

PersonChip + Quote + Note

root = Stack([
  Stack([
    PersonChip("Naomi Rivers", "VP Engineering · Looplog", "https://i.pravatar.cc/64?img=47", "md", "online"),
    PersonChip("Marc Lee",     "Head of Data · Northwind", "https://i.pravatar.cc/64?img=11", "md", "busy"),
    PersonChip("Grace Hopper", "Founder · Atlasworks",     "https://i.pravatar.cc/64?img=32", "md", "online")
  ], "row", "s", "stretch", "start", true),
  Quote("Streaming-ui-script took our recap email from 4k lines of glue to 40.",
        "Naomi · last QBR", "primary"),
  Note("Owner: Mei Tanaka · ARR $84,000 · renewal in Q3", "tip")
], "column", "m")

SearchBar + ProgressRing + ChatBubble thread

$query = ""

root = Stack([
  SearchBar("q", "Search the catalog…", $query, "/"),
  Stack([
    ProgressRing(72, 100, null, "In stock",  "success"),
    ProgressRing(28, 100, null, "Backlog",   "warning"),
    ProgressRing(100, 100, "circle-check", "Shipped",   "primary")
  ], "row", "l", "center"),
  ChatBubble("Support",
             "Hi! Tracking shows your package landed in the local hub this morning.",
             "9:12 AM", null, "agent", "delivered"),
  ChatBubble("You",
             "Perfect — I can wait. Thank you!",
             "9:15 AM", null, "me", "read")
], "column", "m")

Menus, overlays & toasts

Click-triggered surfaces for everything that doesn't belong on the page all the time — DropdownMenu for action menus, Popover for filter panels and rich tooltips, Toast /Toasts for transient feedback. All three keep their open/closed state across re-renders, so unrelated state changes (typing into an input, ticking a checkbox…) never collapse them mid-interaction.

DropdownMenu with sections, icons & danger action

root = Stack([
  TextContent("Click the avatar to open the menu.", "small-muted"),
  DropdownMenu(
    Avatar("Alex Rivera", "https://i.pravatar.cc/64?img=12", "md"),
    [
      MenuLabel("Account"),
      MenuItem("Profile",   Action([@ToAssistant("Open profile")]),   "user"),
      MenuItem("Settings",  Action([@ToAssistant("Open settings")]),  "gear",         "⌘,"),
      MenuItem("Keyboard shortcuts", Action([@ToAssistant("Show shortcuts")]), "keyboard", "?"),
      MenuSeparator(),
      MenuLabel("Workspace"),
      MenuItem("Invite teammates", Action([@ToAssistant("Open invite dialog")]), "user-plus"),
      MenuItem("Billing",          Action([@ToAssistant("Open billing")]),       "credit-card"),
      MenuSeparator(),
      MenuItem("Sign out",  Action([@ToAssistant("Sign out")]), "right-from-bracket", null, "danger")
    ],
    "bottom",
    "start"
  )
], "column", "s")

Popover filter panel

$status   = "any"
$priority = "any"

statusItems = [SelectItem("any","Any"), SelectItem("open","Open"), SelectItem("closed","Closed")]
priorityItems = [SelectItem("any","Any"), SelectItem("high","High"), SelectItem("medium","Medium"), SelectItem("low","Low")]

root = Stack([
  Popover(
    Button("Filters", null, "secondary"),
    [
      FormControl("Status",   Select("status",   statusItems,   null, "Pick a status",   $status)),
      FormControl("Priority", Select("priority", priorityItems, null, "Pick a priority", $priority)),
      Stack([
        Button("Reset",   Action([@Set($status, "any"), @Set($priority, "any")]), "ghost", "button", "small"),
        Button("Apply",   Action([@ToAssistant("Apply filters")]), "primary", "button", "small")
      ], "row", "s", "stretch", "between", true)
    ],
    "Filter board",
    "bottom",
    "start",
    "320px"
  ),
  TextContent("Current: status=" + $status + " · priority=" + $priority, "small-muted")
], "row", "m", "center", "start")

Toast stack (bottom-right)

// Every toast shows a × close button. Pass `duration` (ms) to auto-dismiss;
// omit it for a persistent toast the user must close manually.

root = Toasts([
  Toast("Changes saved",
        "Your draft was synced across all devices.",
        "success", "circle-check",
        4000),                       // auto-dismiss after 4s
  Toast("Heads up",
        "Two reviewers were notified for approval.",
        "info", "circle-info",
        6000),                       // auto-dismiss after 6s
  Toast("Couldn't reach the server",
        "Your edits are queued — we'll retry automatically.",
        "warning", "triangle-exclamation",
        null,                         // no auto-dismiss
        Button("Retry now", Action([@ToAssistant("Retry the save")]), "ghost", "button", "small"))
], "bottom-right")

Extended form inputs

Beyond Input/Select: Slider, NumberInput, DatePicker, FileUpload, and the searchable Combobox. Pass a $variable as value to get two-way binding for free; the renderer keeps the input in step with reactive state on every render.

Slider + NumberInput + DatePicker

$volume  = 60
$qty     = 2
$date    = "2026-06-01"

root = Card([
  CardHeader("Configure your order", "Live preview reflects the bound state"),
  Form("order",
    Buttons([Button("Save", Action([@ToAssistant("Save order")]), "primary")]),
    [
      FormControl("Quantity",      NumberInput("qty",  $qty,    1,  99,  1)),
      FormControl("Delivery date", DatePicker("date",  $date,   null, "2026-01-01", "2026-12-31")),
      FormControl("Volume",        Slider("vol",       0, 100,  5,  $volume, null, true))
    ]
  ),
  Note("Quantity: " + $qty + " · Date: " + $date + " · Volume: " + $volume + "%", "tip")
])

Combobox + FileUpload

$country = "us"

countries = [
  SelectItem("us", "United States"),
  SelectItem("uk", "United Kingdom"),
  SelectItem("ca", "Canada"),
  SelectItem("au", "Australia"),
  SelectItem("de", "Germany"),
  SelectItem("fr", "France"),
  SelectItem("jp", "Japan"),
  SelectItem("br", "Brazil")
]

root = Card([
  CardHeader("Profile setup", "Pick a country and add a photo"),
  Form("setup",
    Buttons([Button("Continue", Action([@ToAssistant("Save profile")]), "primary")]),
    [
      FormControl("Country",
        Combobox("country", countries, $country, "Search countries…"),
        "Start typing to filter the list."),
      FormControl("Profile photo",
        FileUpload("avatar", "Click or drop a PNG / JPG", "image/*", false, "Up to 5 MB"),
        "We'll resize and crop it for you.")
    ]
  )
])

Hierarchical data & top navigation

Tree + TreeNode render file browsers, org charts, category outlines, settings groups — anything that nests. They ride on the native <details> element, so expand/collapse state survives re-renders for free. Pair with Navbar + NavbarItem when you need a sticky top bar across the surface.

File browser tree

root = Card([
  CardHeader("Repository", "src/library/components"),
  Tree([
    TreeNode("src", [
      TreeNode("library", [
        TreeNode("components", [
          TreeNode("menu.ts",     null, "file-code"),
          TreeNode("forms.ts",    null, "file-code"),
          TreeNode("feedback.ts", null, "file-code", false, true),
          TreeNode("data.ts",     null, "file-code")
        ], "folder-open", true, false, "12"),
        TreeNode("index.ts", null, "file-code")
      ], "folder-open", true),
      TreeNode("element.ts", null, "file-code"),
      TreeNode("theme", [
        TreeNode("styles.ts", null, "file-code"),
        TreeNode("index.ts",  null, "file-code")
      ], "folder", false)
    ], "folder-open", true),
    TreeNode("tests", [
      TreeNode("library.test.ts", null, "file-code"),
      TreeNode("element.test.ts", null, "file-code")
    ], "folder", false, false, "11"),
    TreeNode("README.md", null, "file-lines")
  ])
])

Navbar with brand, links & actions

root = Stack([
  Navbar(
    "Acme",
    [
      NavbarItem("Home",    "/",         "house", true),
      NavbarItem("Docs",    "/docs",     "book"),
      NavbarItem("Pricing", "/pricing",  "tag"),
      NavbarItem("Blog",    "/blog",     "newspaper")
    ],
    [
      Button("Sign in",     Action([@ToAssistant("Sign in")]), "ghost"),
      Button("Get started", Action([@ToAssistant("Sign up")]),  "primary")
    ],
    true,
    "default"
  ),
  Card([
    CardHeader("Welcome to Acme", "The Navbar above is sticky"),
    TextContent(
      "Use Navbar at the top of full-page surfaces. Each NavbarItem fires @Navigate when you pass a `to` path, so it integrates with the built-in router.",
      "body"
    )
  ])
], "column", "m")

Real-world blocks

Drop-in patterns for the screens you build on every project. Each one uses only the built-in components, so they render the same in any theme.

Register / sign-up

$name = ""
$email = ""
$password = ""
$plan = "starter"
$accepted = false
$status = "Fill in the form to create your account."

submit = Button("Create account", Action([@Set($status, "Account created for " + $name + " on the " + $plan + " plan.")]), "primary")

form = Form("signup", submit, [
  FormControl("Full name", Input("name", "Ada Lovelace", "text", ["required","minLength:2"], $name)),
  FormControl("Work email", Input("email", "ada@example.com", "email", ["required","email"], $email)),
  FormControl("Password", Input("password", "At least 8 characters", "password", ["required","minLength:8"], $password)),
  FormControl("Plan", Select("plan", [
    SelectItem("starter","Starter — free"),
    SelectItem("pro","Pro — $29/mo"),
    SelectItem("team","Team — $79/mo")
  ], null, null, $plan)),
  FormControl("Terms", Checkbox("accepted", "I agree to the Terms of Service and Privacy Policy", $accepted))
])

card = Card([
  CardHeader("Create your account", "Free 14-day trial · no credit card"),
  form,
  Callout("info", "What happens next?", $status)
])

root = Stack([card])

Login

$email = ""
$password = ""
$remember = true
$msg = ""

login = Button("Sign in", Action([@Set($msg, "Welcome back, " + $email + "!")]), "primary")

actions = Buttons([
  login,
  Button("Continue with Google", null, "secondary"),
  Button("Continue with GitHub", null, "secondary")
])

form = Form("login", login, [
  FormControl("Email", Input("email", "you@example.com", "email", ["required","email"], $email)),
  FormControl("Password", Input("password", "••••••••", "password", ["required"], $password)),
  FormControl("Remember me", Checkbox("remember", "Keep me signed in for 30 days", $remember))
])

footer = Stack([
  Link("Forgot password?", "#"),
  Link("Create an account", "#")
], "row", "s", "center", "between")

card = Card([
  CardHeader("Welcome back", "Sign in to your workspace"),
  form,
  Separator("horizontal", true),
  actions,
  footer,
  $msg == "" ? null : Callout("success", "Signed in", $msg)
])

root = Stack([card])

Product listing

$query = ""
$category = "all"

products = Query("list_products", {}, {rows: [
  {name: "Aurora Headphones", price: 149, category: "audio", rating: 4.7, badge: "New"},
  {name: "Lumen Desk Lamp", price: 79, category: "home", rating: 4.5, badge: ""},
  {name: "Nimbus Backpack", price: 119, category: "travel", rating: 4.8, badge: "Bestseller"},
  {name: "Pulse Smartwatch", price: 229, category: "wearables", rating: 4.4, badge: ""},
  {name: "Echo Bluetooth Speaker", price: 89, category: "audio", rating: 4.6, badge: ""},
  {name: "Drift Travel Pillow", price: 29, category: "travel", rating: 4.3, badge: "Sale"}
]})

filtered = @Filter(products.rows, "category", "equals", $category)
visible = $category == "all" ? products.rows : filtered
hits = @Filter(visible, "name", "contains", $query)

makeCard = @Each(hits, "p", Card([
  Stack([
    TextContent(p.name, "large-heavy"),
    Tag(p.badge, null, "sm", "primary")
  ], "row", "s", "center", "between"),
  TextContent("$" + p.price, "body-heavy", "primary"),
  Stack([
    Tag(p.category, null, "sm", "neutral"),
    Rating(p.rating, 5, "" + p.rating, null, "sm")
  ], "row", "s", "center", "start"),
  Buttons([
    Button("Add to cart", Action([@ToAssistant("Add " + p.name + " to my cart")]), "primary", "normal", "small"),
    Button("Details", null, "secondary", "normal", "small")
  ])
]))

filters = Stack([
  FormControl("Search", Input("q", "Search products", "text", null, $query)),
  FormControl("Category", Select("cat", [
    SelectItem("all","All"),
    SelectItem("audio","Audio"),
    SelectItem("home","Home"),
    SelectItem("travel","Travel"),
    SelectItem("wearables","Wearables")
  ], null, null, $category))
], "row", "m", "stretch", "start", true)

stats = Stack([
  StatCard("Showing", "" + @Count(hits)),
  StatCard("Avg rating", "" + @Avg(hits.rating)),
  StatCard("Avg price", "$" + @Avg(hits.price))
], "row", "m", "stretch", "start", true)

grid = Stack([makeCard], "row", "m", "stretch", "start", true)

root = Stack([
  Card([CardHeader("Storefront", "Curated essentials"), filters]),
  stats,
  @Count(hits) > 0 ? grid : Callout("info", "No matches", "Try a different search or category.")
])

Changelog

root = Stack([header, releases])

header = Card([CardHeader("Changelog", "Everything we shipped, in reverse chronological order")])

releases = Stack([v14, v13, v12, v11])

v14 = Card([
  Stack([
    TextContent("v1.4.0", "large-heavy"),
    Tag("Latest", null, "sm", "primary")
  ], "row", "s", "center", "start"),
  TextContent("Released May 8, 2026", "small", "muted"),
  TagBlock(["new", "themes", "performance"], "primary", "sm"),
  Markdown("- **Two new themes** — `glass` and `brutalist`.\n- **Background alignment** via the new `transparent` attribute.\n- 18% faster initial render on large programs.")
])

v13 = Card([
  Stack([
    TextContent("v1.3.0", "large-heavy"),
    Tag("Stable", null, "sm", "success")
  ], "row", "s", "center", "start"),
  TextContent("Released April 14, 2026", "small", "muted"),
  TagBlock(["responsive", "tables", "inputs"], "info", "sm"),
  Markdown("- Phone-first layouts across the entire library.\n- Horizontal scroll on overflowing tables.\n- Fix: text inputs no longer lose focus while streaming.")
])

v12 = Card([
  Stack([
    TextContent("v1.2.0", "large-heavy"),
    Tag("Stable", null, "sm", "success")
  ], "row", "s", "center", "start"),
  TextContent("Released March 22, 2026", "small", "muted"),
  TagBlock(["components", "language"], "info", "sm"),
  Markdown("- Added `Separator`, `TagBlock`, and `CheckBoxGroup`.\n- `Tabs` now switches active panels properly.")
])

v11 = Card([
  Stack([
    TextContent("v1.1.0", "large-heavy"),
    Tag("Archived", null, "sm", "neutral")
  ], "row", "s", "center", "start"),
  TextContent("Released February 5, 2026", "small", "muted"),
  TagBlock(["streaming", "errors"], "warning", "sm"),
  Markdown("- Streaming-friendly parser tolerates partial lines.\n- Optional `showerrors` attribute.")
])

FAQ

root = Stack([hero, faq, follow])

hero = Card([CardHeader("Frequently asked questions", "Can't find an answer? Reach out — we read every message.")])

faq = Accordion([
  AccordionItem("Is there a free plan?", [
    Markdown("Yes. The **Starter** plan is free forever for projects up to 5 contributors. Upgrade only when you outgrow it.")
  ]),
  AccordionItem("Can I cancel anytime?", [
    Markdown("Of course. Cancel from **Billing → Subscription** and you'll keep access until the end of the current period.")
  ]),
  AccordionItem("Do you support self-hosting?", [
    Markdown("Self-hosting is included on every paid plan. Download the helm chart from your dashboard, or run the Docker image directly."),
    CodeBlock("bash", "docker run -p 8080:8080 ghcr.io/example/app:latest")
  ]),
  AccordionItem("Which payment methods do you accept?", [
    TagBlock(["Visa", "Mastercard", "Amex", "Apple Pay", "Google Pay", "ACH", "Wire"], "primary", "sm")
  ]),
  AccordionItem("How is my data protected?", [
    Markdown("All data is encrypted in transit (TLS 1.3) and at rest (AES-256). We're SOC 2 Type II certified."),
    Callout("success", "Compliance", "SOC 2 Type II · ISO 27001 · GDPR · HIPAA available on Enterprise.")
  ])
])

follow = FollowUpBlock([
  FollowUpItem("Talk to sales"),
  FollowUpItem("See pricing"),
  FollowUpItem("Read the docs")
])

Order history

$status = "all"

orders = Query("list_orders", {}, {rows: [
  {id: "ORD-2041", date: "May 6", customer: "Ada Lovelace", items: 3, total: 142.40, status: "shipped"},
  {id: "ORD-2040", date: "May 5", customer: "Grace Hopper", items: 1, total: 49.00, status: "processing"},
  {id: "ORD-2039", date: "May 5", customer: "Linus Torvalds", items: 2, total: 88.50, status: "delivered"},
  {id: "ORD-2038", date: "May 4", customer: "Margaret Hamilton", items: 5, total: 312.99, status: "shipped"},
  {id: "ORD-2037", date: "May 3", customer: "Alan Turing", items: 1, total: 19.95, status: "cancelled"},
  {id: "ORD-2036", date: "May 2", customer: "Katherine Johnson", items: 4, total: 240.00, status: "delivered"}
]})

filtered = $status == "all" ? orders.rows : @Filter(orders.rows, "status", "equals", $status)

statusFilter = FormControl("Filter", Select("status", [
  SelectItem("all","All orders"),
  SelectItem("processing","Processing"),
  SelectItem("shipped","Shipped"),
  SelectItem("delivered","Delivered"),
  SelectItem("cancelled","Cancelled")
], null, null, $status))

stats = Stack([
  StatCard("Orders", "" + @Count(filtered)),
  StatCard("Revenue", "$" + @Sum(filtered.total), "up"),
  StatCard("Avg ticket", "$" + @Round(@Avg(filtered.total), 2))
], "row", "m", "stretch", "start", true)

statusTags = @Each(filtered, "row",
  row.status == "delivered" ? Tag("Delivered", null, "sm", "success") :
  row.status == "shipped"   ? Tag("Shipped",   null, "sm", "info") :
  row.status == "processing"? Tag("Processing",null, "sm", "warning") :
                              Tag("Cancelled", null, "sm", "danger"))

actions = @Each(filtered, "row", Buttons([
  Button("View", Action([@ToAssistant("Show order " + row.id)]), "secondary", "normal", "small"),
  Button("Reorder", Action([@ToAssistant("Reorder " + row.id)]), "ghost", "normal", "small")
]))

table = Table([
  Col("Order", filtered.id),
  Col("Date", filtered.date),
  Col("Customer", filtered.customer),
  Col("Items", filtered.items, "number"),
  Col("Total", filtered.total, "currency"),
  Col("Status", statusTags),
  Col("Actions", actions)
])

root = Stack([
  Card([CardHeader("Order history", "Last 30 days"), statusFilter]),
  stats,
  Card([CardHeader("Orders"), @Count(filtered) > 0 ? table : Callout("info", "Nothing here", "No orders match this filter.")])
])

Shopping cart

cart = Query("get_cart", {}, {items: [
  {sku: "AUR-01", name: "Aurora Headphones", qty: 1, price: 149.00},
  {sku: "LUM-02", name: "Lumen Desk Lamp", qty: 2, price: 79.00},
  {sku: "NIM-03", name: "Nimbus Backpack", qty: 1, price: 119.00}
]})

lineTotals = @Each(cart.items, "i", i.qty * i.price)

subtotal = @Sum(lineTotals)
shipping = subtotal > 200 ? 0 : 12
discount = subtotal > 250 ? @Round(subtotal * 0.10, 2) : 0
tax = @Round((subtotal - discount) * 0.085, 2)
total = subtotal + shipping + tax - discount

qtyTags = @Each(cart.items, "i", Tag("× " + i.qty, null, "sm", "neutral"))
remove = @Each(cart.items, "i", Button("Remove", Action([@ToAssistant("Remove " + i.sku + " from cart")]), "ghost", "normal", "small"))
lineCol = @Each(cart.items, "i", "$" + (i.qty * i.price))

table = Table([
  Col("Item", cart.items.name),
  Col("Qty", qtyTags),
  Col("Unit", cart.items.price, "currency"),
  Col("Line total", lineCol, "currency"),
  Col("", remove)
])

summary = Card([
  CardHeader("Order summary"),
  Stack([TextContent("Subtotal", "small"), TextContent("$" + subtotal, "small-heavy")], "row", "s", "center", "between"),
  Stack([TextContent("Shipping", "small"), TextContent(shipping == 0 ? "Free" : "$" + shipping, "small-heavy")], "row", "s", "center", "between"),
  Stack([TextContent("Tax (8.5%)", "small"), TextContent("$" + tax, "small-heavy")], "row", "s", "center", "between"),
  discount > 0 ? Stack([TextContent("Discount", "small", "success"), TextContent("- $" + discount, "small-heavy", "success")], "row", "s", "center", "between") : null,
  Separator("horizontal", true),
  Stack([TextContent("Total", "large-heavy"), TextContent("$" + total, "large-heavy", "primary")], "row", "s", "center", "between"),
  Buttons([
    Button("Checkout", Action([@ToAssistant("Proceed to checkout")]), "primary"),
    Button("Apply coupon", null, "secondary")
  ])
])

root = Stack([
  Card([CardHeader("Your cart", @Count(cart.items) + " items"), table]),
  summary
])

Services showcase

root = Stack([hero, services, sla, follow])

hero = Card([
  CardHeader("Services we offer", "End-to-end product engineering for ambitious teams"),
  TagBlock(["Strategy","Design","Engineering","Launch","Growth"], "primary", "sm")
])

services = Stack([
  Card([
    Stack([Tag("01", null, "sm", "primary"), TextContent("Product strategy", "large-heavy")], "row", "s", "center", "start"),
    Markdown("Discovery sprints, opportunity mapping, and a roadmap that ships."),
    TagBlock(["workshops","research","roadmaps"], "info", "sm"),
    Buttons([Button("Learn more", null, "ghost", "normal", "small")])
  ]),
  Card([
    Stack([Tag("02", null, "sm", "primary"), TextContent("Design systems", "large-heavy")], "row", "s", "center", "start"),
    Markdown("From brand foundations to a typed component library your engineers will actually use."),
    TagBlock(["tokens","figma","components"], "info", "sm"),
    Buttons([Button("Learn more", null, "ghost", "normal", "small")])
  ]),
  Card([
    Stack([Tag("03", null, "sm", "primary"), TextContent("Web & mobile engineering", "large-heavy")], "row", "s", "center", "start"),
    Markdown("React, Next.js, Vue, Swift, Kotlin — choose your stack and we ship the app."),
    TagBlock(["next.js","react native","node"], "info", "sm"),
    Buttons([Button("Learn more", null, "ghost", "normal", "small")])
  ]),
  Card([
    Stack([Tag("04", null, "sm", "primary"), TextContent("AI integrations", "large-heavy")], "row", "s", "center", "start"),
    Markdown("Production-grade RAG pipelines, agent flows, and evaluation harnesses."),
    TagBlock(["llm","rag","evals"], "info", "sm"),
    Buttons([Button("Learn more", null, "ghost", "normal", "small")])
  ])
], "row", "m", "stretch", "start", true)

sla = Stack([
  StatCard("Avg engagement", "12 wks"),
  StatCard("Client NPS", "73", "up", "+9 YoY"),
  StatCard("Time to MVP", "6 wks", "down", "-2 wks"),
  StatCard("Retention", "94%", "up")
], "row", "m", "stretch", "start", true)

follow = FollowUpBlock([
  FollowUpItem("Book a discovery call"),
  FollowUpItem("See case studies"),
  FollowUpItem("Request a proposal")
])

JavaScript interactions

The example below uses an LLM-authored Script(...) body that runs against the always-on JavaScript runtime. Read the full guide on the JavaScript interactions page.

Live ticking counter (Script + @Js)

$count = 0
$running = false
header = Card([CardHeader("Live counter", "Powered by Script() + @Js()")])
display = TextContent("" + $count, "large-heavy")
controls = Buttons([
  Button($running ? "Pause" : "Start", Action([@Set($running, !$running)]), "primary"),
  Button("Reset", Action([@Reset($count, $running)]), "secondary"),
  Button("+10", Action([@Js("ctx.state.set('count', (ctx.state.get('count') ?? 0) + 10);")]), "ghost")
])
ticker = Script("ticker", "if (!ctx.state.get('running')) return; const id = setInterval(() => ctx.state.set('count', (ctx.state.get('count') ?? 0) + 1), 1000); ctx.cleanup(() => clearInterval(id));", ["running"])
root = Stack([header, display, controls, ticker])

Copy to clipboard (@Js + @ToAssistant)

$snippet = "npm install streaming-ui-script"
$copied = false

resetCopied = Script("reset-copied", "if (!ctx.state.get('copied')) return; const id = setTimeout(() => ctx.state.set('copied', false), 1800); ctx.cleanup(() => clearTimeout(id));", ["copied"])

copyBtn = Button($copied ? "Copied" : "Copy", Action([
  @Js("await navigator.clipboard.writeText(ctx.state.get('snippet') ?? ''); ctx.state.set('copied', true);")
]), $copied ? "secondary" : "primary", "normal", "small")

snippetCard = Card([
  CardHeader("Install", "One command via npm"),
  Stack([
    TextContent($snippet, "body-heavy"),
    copyBtn
  ], "row", "m", "center", "between")
], "outlined")

root = Stack([snippetCard, resetCopied])

Live form validation (Script + reactive errors)

$email = ""
$password = ""
$emailError = ""
$pwError = ""
$strength = ""

validator = Script("validate", "const email = (ctx.state.get('email') ?? '').trim(); const pw = ctx.state.get('password') ?? ''; const emailRe = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/; ctx.state.set('emailError', !email ? '' : (emailRe.test(email) ? '' : 'Looks like an invalid email.')); let strength = ''; if (pw.length === 0) strength = ''; else if (pw.length < 8) strength = 'Too short — use at least 8 characters.'; else if (!/\\d/.test(pw) || !/[A-Z]/.test(pw)) strength = 'Add a number and an uppercase letter.'; else strength = 'Strong enough.'; ctx.state.set('strength', strength); ctx.state.set('pwError', pw && pw.length < 8 ? 'Password is too short.' : '');", ["email", "password"])

emailField  = FormControl("Email", Input("email", "you@example.com", "email", null, $email))
emailHint   = $emailError == "" ? null : Callout("error", "Email", $emailError)

pwField     = FormControl("Password", Input("password", "At least 8 characters", "password", null, $password))
pwHint      = $strength == "" ? null : Callout($pwError == "" ? "info" : "warning", "Password strength", $strength)

canSubmit   = $email != "" && $password != "" && $emailError == "" && $pwError == ""
submitBtn   = Button("Create account", Action([@ToAssistant("Account created!")]), canSubmit ? "primary" : "ghost")

root = Stack([
  Card([
    CardHeader("Sign up", "Validation runs in-browser as you type"),
    emailField, emailHint,
    pwField, pwHint,
    submitBtn,
    validator
  ])
])

Todo list (reactive)

$tab = "active"
$selected = {t1: true, t6: true}

todos = Query("list_todos", {}, {rows: [
  {id: "t1", title: "Draft the launch announcement", project: "Marketing", due: "Today", priority: "high", done: true},
  {id: "t2", title: "Review pull requests", project: "Engineering", due: "Today", priority: "medium", done: false},
  {id: "t3", title: "Sync with design on cart UX", project: "Product", due: "Tomorrow", priority: "high", done: false},
  {id: "t4", title: "Update onboarding checklist", project: "Customer success", due: "Fri", priority: "low", done: false},
  {id: "t5", title: "Migrate analytics dashboard", project: "Engineering", due: "Next week", priority: "medium", done: false},
  {id: "t6", title: "Send weekly investor update", project: "Operations", due: "Last week", priority: "low", done: true}
]})

active = @Filter(todos.rows, "done", "equals", false)
done = @Filter(todos.rows, "done", "equals", true)
visible = $tab == "done" ? done : ($tab == "all" ? todos.rows : active)

priorityTag = @Each(visible, "t",
  t.priority == "high"  ? Tag("High",   null, "sm", "danger") :
  t.priority == "medium"? Tag("Medium", null, "sm", "warning") :
                          Tag("Low",    null, "sm", "neutral"))

selectableItems = @Each(visible, "t", CheckBoxItem(t.title, t.id, t.project + " · due " + t.due, t.done))

board = Card([
  Stack([
    TextContent("Today's focus", "large-heavy"),
    Tag("" + @Count(active) + " open", null, "sm", "primary")
  ], "row", "s", "center", "between"),
  CheckBoxGroup("todos", selectableItems, $selected)
])

stats = Stack([
  StatCard("Open", "" + @Count(active)),
  StatCard("Done", "" + @Count(done), "up"),
  StatCard("High priority", "" + @Count(@Filter(active, "priority", "equals", "high")))
], "row", "m", "stretch", "start", true)

filter = Tabs([
  TabItem("active", "Active", [board]),
  TabItem("done", "Done", [board]),
  TabItem("all", "All", [board])
])

addRow = Stack([
  Input("new", "Add a todo and press enter…", "text", null, ""),
  Button("Add", Action([@ToAssistant("Add a todo to my list")]), "primary")
], "row", "s", "center", "stretch", true)

root = Stack([
  Card([CardHeader("Todos", "Snapshot of your week"), addRow]),
  stats,
  Card([CardHeader("Inbox"), filter])
])