Native Shell (NSH) UI Development
Build one UI that renders natively on 8 platforms from a shared Rust reactive engine. When language/delivery is unspecified, prefer TSX for new UI screens (faster iteration with hot-reload); use Rust when shipping in a binary without a JS runtime.
0. Install the nsh CLI
macOS / Linux:
curl -fsSL https://nsh.dev/install.sh | sh # stable
curl -fsSL https://nsh.dev/install.sh | sh -s -- --nightly # nightly
curl -fsSL https://nsh.dev/install.sh | sh -s -- --source # build from source
brew install longbridge/tap/nsh # Homebrew
Windows (PowerShell):
irm https://nsh.dev/install.ps1 | iex
Verify before starting:
nsh --version
cargo --version # needed only for `rust` / `mixed` templates
If nsh is missing or a target won't build, read references/installation.md for
per-platform dependencies, command availability, and troubleshooting.
1. Scaffold
# TSX-only app (hot-reload, no Rust toolchain needed)
nsh init my-app --template ts
# Rust app (binary, no JS VM)
nsh init my-app --template rust
# Mixed: TSX screens importing Rust components
nsh init my-app --template mixed
Project layout (TSX):
App.tsx # entry; calls mount(App)
nsh.json # app metadata + capabilities
tsconfig.json
src/
pages/ # one file per NavPage
components/ # app-owned styled components
store.ts # signals + state functions
*.test.tsx # tests beside what they test
A working counter app (App.tsx, App.test.tsx, nsh.json, tsconfig.json)
lives in assets/counter/ — copy it as a starting point or read it alongside
section 2. Release apps must set a real id (default prefix com.example.).
2. First App — Minimal TSX
import { mount, signal, Text, View } from "nsh";
function App() {
const count = signal(0);
return (
<View class="flex-1 items-center justify-center gap-4 bg-background">
<Text class="text-foreground text-lg">Count: {count()}</Text>
<View
class="rounded-lg bg-primary px-5 py-3 active:bg-primary/90"
onPress={() => count.update((n) => n + 1)}
>
<Text class="text-primary-foreground">Tap</Text>
</View>
</View>
);
}
mount(App);
Key rule: a component body runs once. {count()} is a reactive binding — it
re-evaluates only when count changes. Do not read signals as plain values in the body.
3. Reactivity Cheat Sheet
| Concept | TSX | Rust |
|---------|-----|------|
| Create signal | const x = signal(0) | let x = signal(0_i32) |
| Read (tracks) | x() | x.get() |
| Write | x.set(5) / x.update(\|n\| n + 1) | x.set(5) / x.update(\|n\| *n += 1) |
| Derived | computed(() => x() * 2) | computed(\|_\| x.get() * 2) |
| Side effect | effect(() => { ... }) | effect(move \|\| { ... }) |
| Async load | resource(fetcher) | resource(\|\| Some(()), fetcher) |
| Batch writes | batch(() => { a.set(1); b.set(2) }) | batch(\|\| { ... }) |
| Read w/o track | untracked(() => x()) | x.get_untracked() |
| Cleanup | cleanup(() => clearInterval(id)) | Owner disposes automatically |
Never sync two signals with an effect — use computed instead.
Never read signals in event handlers; capture Copy handles in closures.
4. Styling — Theme Tokens Only
Presentation code must never contain raw hex/rgba/hsl or arbitrary pixel values.
// ✅ correct: semantic token classes
<View class="bg-background text-foreground rounded-lg border-border" />
// ❌ wrong: raw color / arbitrary value
<View class="bg-[#1a1a2e] p-[13px]" />
| Token class (TSX) | Rust equivalent | Semantic |
|---|---|---|
| bg-primary | theme().primary | Primary action color |
| bg-background | theme().background | Screen background |
| text-foreground | theme().foreground | Default text |
| text-muted-foreground | theme().muted_foreground | Secondary text |
| border-border | theme().border | Divider/border color |
| rounded-lg | .rounded(theme().radius) | Corner radius from theme |
State variants (applied natively — no JS during press feedback):
hover:bg-accent focus:ring-2 focus:ring-primary
active:bg-primary/90 disabled:opacity-50
selected:bg-primary-foreground/10
5. Core Elements
| Element | TSX tag | Purpose |
|---|---|---|
| View | <View> | Layout container (flex column by default) |
| Text | <Text> | Styled text; use inside pressable views for labels |
| Image | <Image> | Remote or local images |
| Scroll | <Scroll> | Scrollable region (one owner per region) |
| List | <List> | Virtualized recycling list — use for growable data |
| Canvas | <Canvas> | 2D drawing surface |
| If / Each | <If>, <For> | Conditional and keyed iteration |
View layout: default is flex column. Use class="flex" for row.
Use scale classes (p-2, gap-3, w-64) — never p-[13px].
6. Base Components (nsh/base)
Unstyled behavior components — wrap and style them once in your UI library:
Form: Button, Checkbox, Radio, Switch, Input, NumberInput, OtpInput, Slider, Select, Combobox, DatePicker, TimeField, Calendar, ColorPicker
Navigation: NavStack, Tabs, Toolbar, Tree, DataTable, Dock, Accordion, Collapsible, Carousel
Overlays: Dialog, AlertDialog, Popover, Sheet, Menu, ContextMenu, Tooltip, HoverCard, Toast, Progress
Content: TextView (Markdown/HTML), RichEditor, DiffView, Editor (code), Plot (charts), Avatar, Pagination, Link, Command (Cmd+K)
7. Controlled Component Pattern
function Toggle({ value, onChange }: { value: () => boolean; onChange: (v: boolean) => void }) {
return (
<Switch
checked={value()}
onCheckedChange={(next) => onChange(next)}
/>
);
}
// Usage
const showHidden = signal(false);
<Toggle value={() => showHidden()} onChange={(v) => showHidden.set(v)} />
In Rust:
switch()
.checked(show_hidden.get())
.on_change(move |next: &bool| show_hidden.set(*next))
.child(text("Show hidden files"))
Decisions are props, not callbacks. Set disabled={!canSubmit()}, maxLength={200}
on the element — don't check them inside onPress.
8. Virtualized Lists
function ProjectList({ projects }: { projects: () => Project[] }) {
return (
<List
items={projects()}
key={(p) => p.id}
estimatedItemSize={56}
renderItem={(p) => (
<ProjectRow project={p} />
)}
/>
);
}
Rules:
- Keep per-item state in the data (keyed by id), never in row-local signals
- Use stable domain ids as keys — never array index
- Update arrays immutably:
items.update((list) => [...list, item])
9. Navigation
import { NavStack, NavPage, useNav } from "nsh";
function App() {
return (
<NavStack>
<NavPage name="home" component={Home} />
<NavPage name="detail" component={Detail} />
</NavStack>
);
}
// Navigate
const nav = useNav();
nav.push("detail", { id: projectId });
nav.pop();
nav.replace("home");
10. Async with resource
function UserList() {
const users = resource(async () => {
const res = await fetch("/api/users");
return res.json();
});
return (
<If condition={users.loading()}>
<Spinner />
</If>
<If condition={users.error()}>
<Text class="text-destructive">{users.error()?.message}</Text>
</If>
<For each={users() ?? []} key={(u) => u.id}>
{(u) => <UserRow user={u} />}
</For>
);
}
Rust:
let users = resource(
|| Some(()),
move |_, _| async move { fetch_users().await },
);
// users.get() → Option<Vec<User>>
// users.loading() → bool
// users.error() → Option<Error>
11. Verification Loop
# TSX
nsh check # TypeScript type check (tsc on generated .nsh/types)
nsh build # bundler — warns = findings
nsh test # headless *.test.tsx (behavior, not look)
nsh run # launch on target
# Rust
nsh check # cargo check
cargo test # headless via nsh_testing::Headless
nsh run --target macos # or ios, android, web, linux, windows, tui, gpui
Headless tests prove behavior only — screenshot or run visually for layout/styling.
Example headless test (Rust):
#[test]
fn tap_increments_count() {
let mut app = Headless::start(EngineConfig::new(Root::of::<App>())).unwrap();
app.wait_for("Count: 0").unwrap();
app.press("Tap").unwrap();
app.wait_for("Count: 1").unwrap();
}
12. Platform-Specific Props
<View
desktop={{ minWidth: 400 }}
mobile={{ fullBleed: true }}
ios={{ largeTitle: true }}
android={{ statusBarColor: "transparent" }}
web={{ role: "main" }}
/>
Tailwind platform variants:
<View class="desktop:flex-row mobile:flex-col" />
Environment (reactive):
const os = platform.os; // "ios" | "android" | "macos" | ...
const dark = colorScheme(); // reactive: "light" | "dark"
const scale = fontScale(); // reactive: user text size
13. Checklist Before Finishing
Common pitfalls (verified in Rust)
- Element constructors are not all in the prelude.
nsh_core::prelude::*exportsview()/text()but not thensh/basebuilders:input(),button(),switch(),tree()come fromnsh_base. Missing this is an unresolved-name error at the first control. - Don't name app types after prelude elements.
View,Text,Input,Scrollare glob-imported; an enumViewshadows the element and breaks everyview()call. UsePage/Screen/Route. - Full-window overlays block every click. An
absolute inset-0layer is a hit-test surface even when transparent. Make it pass-through (pointer-events-none, orpointer_events(PointerEvents::BoxNone)in Rust) and let only its children take input. Treerows show only the label by default. No indent, no chevron, so nested items look flat. ProviderenderItem/render_item(one concreteAnyElementin Rust), addgrouptoitemClass, and turn the chevron withgroup-aria-expanded:rotate-90. Press selects and toggles; only loaded folders (items withchildren) can expand.eachrows andwhenbranches are reactive.eachhands the rowReadSignal<T>/ReadSignal<usize>; awhenbranch is made once per flip. Read signals insidetext(move || …)bindings, not when the row or branch is made.
Checklist
- [ ] No raw colors or arbitrary pixel values in presentation code
- [ ] Every
nsh/basecomponent wrapped in app-owned styled component - [ ]
nsh checkpasses - [ ]
nsh testpasses - [ ] Visual result inspected on target (not just headless)
- [ ] Virtualized
Listused for any growable collection - [ ] Stable domain ids as keys (no index keys)
- [ ] Async uses
resource, not effects that write signals - [ ] State in narrowest owner; pages don't write each other's state
- [ ] Accessibility:
accessibilityLabelon icon-only buttons - [ ] Rust: constructors imported from
nsh_base, no prelude name shadowed - [ ] Overlay layers pass presses through (
pointer-events-none/BoxNone) - [ ]
TreeusesrenderItemwhen indentation, chevrons or row states matter
References
Detailed recipes in references/:
| File | When to read |
|---|---|
| references/tsx-recipe.md | Building TSX screens, forms, navigation |
| references/rust-recipe.md | Building Rust screens, components, stores |
| references/installation.md | Installing nsh, per-platform deps, command matrix, troubleshooting |
| references/components.md | Full component API reference |
| references/styling.md | Theme tokens, Tailwind utilities, dark mode |
| references/layout.md | Flexbox/Grid patterns, safe area, responsive |
| references/testing.md | Headless testing, selectors, interaction tests |
| references/platform-notes.md | Per-platform differences and requirements |
| references/app-icon.md | Windows: embedding exe + title-bar icon (build.rs + winresource, resource ID 1) |
A runnable starter lives in assets/counter/ (see its README.md).
Online docs: https://nsh.dev/llms.txt (full index) · https://nsh.dev/zh-CN/ (中文) Source: https://github.com/longbridge/nsh

Scan to join WeChat group