# Native Shell > Native Shell is a Rust-first native UI framework: build one app in TSX for iOS, Android, macOS, Windows, Linux and the web, with each platform’s own UI and interaction, and extend it with Rust where it needs to. Apps are written in Rust (compiled to native code) or TSX (run by QuickJS, and by the browser's JavaScript engine on the web), or both, on one native Rust runtime; the toolchain is the single `nsh` binary (`nsh init my-app --template rust|ts`, `nsh run my-app`, `nsh package my-app --target `). Every page below is also served as Markdown at its URL plus `.md`. --- # Introduction Native Shell (NSH for short) is a native UI framework for every platform. You build an app once, with one app model — components, signals, styles and the same API everywhere — and NSH runs it on **iOS, Android, macOS, Windows, Linux and the web**, each time as an app of that platform: made of its own views, edited with its own text system, used the way its users expect. Write the app in **TSX**, and extend it with **Rust** through [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md) where it needs native speed, system access or a crate; an app can also be Rust from start to end, on the same engine. On top of the same engine, apps you have shipped can take new UI at run time — written by your team or generated by a model — as signed modules, in a sandbox the host configures. > [!IMPORTANT] > NSH provides native views and interaction; the app owns its visual design. Components, state and APIs are shared across platforms, while colors, typography, spacing and shapes come from the app. Text input, focus and menus follow each device’s interaction conventions. See [Goals and design principles](https://nsh.dev/versions/v0.7.1/docs/goals.md). ## What native means Native in NSH has two layers: the platform's foundations, and the platform's interaction. Apps define their own visual style and can opt into system materials such as Liquid Glass on supported platforms. **The platform's foundations.** Each platform has a backend of its own, built on the UI that platform already has: | Platform | Views | Text | Text input | |---|---|---|---| | iOS | UIKit | CoreText | The system's text fields and text views | | Android | Android views | `StaticLayout` | `EditText` | | macOS | AppKit, Core Animation | CoreText | `NSTextField`, `NSTextView` | | Windows | Win32 windows drawn with Direct2D | DirectWrite | NSH's editor, with the system's input methods (IMM32) | | Linux | GTK 4 | Pango | GTK's `Text` and `TextView` | | Web | HTML elements styled with CSS | The browser's fonts | The browser's inputs | Text selection and its menu, input methods, accessibility and scrolling come from the platform, and what a new OS release brings to them reaches the app with it. Native components — a map, a web view, a video player, any view the host registers — are one more view in the same hierarchy, laid out, clipped and scrolled with the rest ([Native components](https://nsh.dev/versions/v0.7.1/docs/native-components.md)). **The platform's interaction.** The components NSH provides in [`nsh/base`](https://nsh.dev/versions/v0.7.1/modules/nsh-base.md) behave as each device's users expect, so the app writes them once: | | Desktops (and desktop browsers) | Phones and tablets | |---|---|---| | `Menu` | A popup at its trigger; submenus cascade beside their item | A sheet from the bottom; a submenu replaces its menu's items | | `ContextMenu` | A right click opens it at the pointer | A finger held on the trigger opens it as a sheet | | `Tooltip` | Shown when the pointer rests on the trigger | Shown when the app opens it | | `Popover` | A press outside closes it and reaches what is under the pointer | A press outside closes it | Pages, dialogs, the keyboard and the status bar follow the same idea: navigation stacks push and pop with each platform's motion, and the back button, Escape and swipe-back do what they do there ([Navigation](https://nsh.dev/versions/v0.7.1/docs/navigation.md)). ## From phone to desktop to web Cross-platform in NSH means each device gets the app it expects, not the same screen scaled up or down: - **One app model.** The app's components, state, business logic and screens are shared; each backend maps them to its platform. - **Layouts that reshape.** Flexbox and CSS grid are laid out by [Taffy](https://github.com/DioxusLabs/taffy) on every platform, and Tailwind's breakpoints (`md:`, `lg:`) and the window's size (`window()` in Rust) change the structure, not only the size: a chat app shows its sidebar, conversations and messages side by side in a wide window, and one screen at a time on a phone ([Layout](https://nsh.dev/versions/v0.7.1/docs/layout.md), [Tailwind](https://nsh.dev/versions/v0.7.1/docs/tailwind.md)). - **The input each device expects.** A pointer, hover, right clicks, shortcuts and focus on the desktop; touches, gestures, the software keyboard and page navigation on phones. Where an app wants something of its own per platform, `desktop={{…}}` props and `platform.select` say so ([Platform-specific code](https://nsh.dev/versions/v0.7.1/docs/platform-specific.md)). - **Checked on every target.** `nsh test` runs the app's tests headless, and the same tests in macOS, Windows, Linux and GPUI windows, an iOS simulator, an Android device or a browser, with the platform's own input ([Testing and tracing](https://nsh.dev/versions/v0.7.1/docs/testing-and-trace.md)). Take an app like a chat client. Its developer builds it on the desktop with `nsh run`, opens it in an iOS simulator with `nsh run --target ios` to check the phone layout, then in a browser with `nsh run --target web` — the same project each time — and `nsh package` makes the installable apps and the website. One engineer can carry what used to take a team per platform, while the backend is built alongside. ## Rust first NSH is Rust first: the engine, layout, rendering and every platform layer are Rust, compiled to native code. Apps are written on top of it in TSX, with Rust where it pays off: - **Apps in TSX.** Screens, state, business logic and styles are TSX, with Tailwind classes and signals, and hot updates that keep the app's state on every save. Only the app's own code is JavaScript: the reactive graph, layout, rendering and every module the app imports are Rust ([JSX and components](https://nsh.dev/versions/v0.7.1/docs/jsx-and-components.md)). `nsh init` starts here. - **Rust where the app needs it.** An app's own Rust crate in `ext/`, or an [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md) from crates.io, gives its TSX components, modules and classes: heavy computation, parsing, large data, system APIs and the crates.io ecosystem, at native speed even when TSX calls them. - **Whole apps in Rust.** An app whose core is demanding business logic can be Rust from start to end, compiled to native code with Rust's ownership, types and threads, and no JavaScript runtime ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md)). - **One toolchain.** A single `nsh` executable creates, builds, type-checks, runs with hot reload, tests, packages and signs apps for every target. It brings its own TSX bundler and TypeScript checker, so a TSX app needs nothing but `nsh`; the Rust toolchain comes in when the app has Rust of its own ([Installation](https://nsh.dev/versions/v0.7.1/docs/installation.md), [CLI](https://nsh.dev/versions/v0.7.1/docs/cli.md)). ## An app The same counter, in TSX and in Rust: ```tsx import { mount, signal, Text, View } from "nsh"; import { Window } from "nsh/desktop"; function Counter() { const count = signal(0); return ( {count()} count.update((n) => n + 1)} activeStyle={{ opacity: 0.6 }} class="rounded-lg bg-blue-600 px-5 py-3" > Tap ); } mount(() => ); ``` ```rust use nsh_core::prelude::*; #[component] pub fn Counter() -> impl IntoElement { let count = signal(0); view() .flex_1() .items_center() .justify_center() .gap_3() .child(text(move || count.get().to_string()).text_5xl().font_weight(FontWeight::BOLD)) .child( view() .rounded_lg() .bg(rgb(0x2563eb)) .px_5() .py_3() .active(|s| s.opacity(0.6)) .on_press(move || count.update(|n| *n += 1)) .child(text("Tap").text_lg().text_color(white())), ) } ``` A view (`view()`, ``) becomes a `UIView` on iOS, a `ViewGroup` on Android, an `NSView` on macOS, a GTK widget on Linux, a retained view drawn with Direct2D on Windows and an HTML element on the web; a text becomes a native text view, and the button's press feedback (`.active(..)`, `activeStyle`) runs on the main thread. When you tap, `count.update` changes one signal, and only the text that reads it is updated: the component function does not run again. In the TSX app, only the module's own code is JavaScript; the Rust app is native code from start to end. ## Retained views NSH is retained: every element is a view the platform keeps, and an update changes only what changed. - **Fine-grained updates.** [Signals](https://nsh.dev/versions/v0.7.1/docs/reactivity.md) like Solid's, implemented natively: components run once, and a change runs again only the expressions that read the changed signal. - **Only what changed crosses threads.** The changes of one turn are laid out together and handed to the main thread as one batch of view operations per frame; unchanged styles and frames are not sent, and the views nothing touched stay as they are. - **Animations run natively.** Timing, spring and decay animations, gestures and scroll-linked values are evaluated on the platform's frame clock, without calling into JS per frame ([Animation](https://nsh.dev/versions/v0.7.1/docs/animation.md)). That suits the screens most apps are made of — chats, mail, forms, lists, documents, settings, an AI reply streaming in — where a few views change at a time and the rest wait. Such screens sit near idle between updates, and scrolling and animation hold 120 FPS on ProMotion displays. In the [NSH performance benchmark](https://github.com/longbridge/nsh-perf-bench), a 500-row quote table updated 1,000 times a second uses 18% of a core on Linux in NSH Rust, against 20% for the same screen written directly on [GPUI Fast](https://github.com/longbridge/gpui-fast). Heavy computation belongs in Rust: TSX runs in QuickJS, an interpreter, while a Rust module runs at native speed even when TSX calls it — sorting 100,000 rows takes about 3 ms that way, as in plain Rust ([Performance](https://nsh.dev/versions/v0.7.1/docs/performance.md)). ## How it runs The toolchain is a single `nsh` binary. An app is written in TSX, in Rust, or both, and each takes its own path to the same Rust engine. ### TSX apps A TSX app (a module) is a set of `.tsx` / `.ts` files with an entry, usually `App.tsx`: 1. **Build.** `nsh` bundles the module's files (with rolldown and Oxc) and compiles the JSX with its own compiler. Imports of `nsh` and `nsh/*` stay imports: the runtime serves them natively, so the bundle holds only your code. The bundle is compiled to QuickJS bytecode. 2. **Run.** The engine thread runs the bytecode in [QuickJS](https://github.com/quickjs-ng/quickjs), one VM per view. Compiled JSX calls the native renderer directly, and JavaScript only describes the UI and handles events; parsing styles, resolving Tailwind classes, diffing, layout and text all happen in Rust. ### Rust apps A Rust app is a crate, built entirely with Rust and Native, with no JavaScript runtime: 1. **Build.** `nsh` builds the runner of each target — the iOS, Android, macOS, Windows, Linux or web app — with your crate linked in. Components, state, handlers and the engine are compiled together into native code. 2. **Run.** The app's root component runs on the engine thread as Rust. The runner has no JavaScript engine: QuickJS is not part of a Rust app on any platform. ### The difference | | TSX app | Rust app | |---|---|---| | Written in | TSX (TypeScript and JSX) | Rust | | Built into | QuickJS bytecode, loaded by the runtime | Native code, linked into each target's runner | | JavaScript engine | QuickJS, one VM per view | None | | While developing (`nsh run`) | Hot updates on each save | Rebuilt and restarted on each save | | After release | Ships with the app; also delivered at run time as signed packages, in a sandbox | Ships with the app | | Suits | Most apps, plugins, UI delivered at run time or generated by a model | Apps whose core is heavy computation or system work | The two combine: a TSX app imports Rust components, modules and classes from nshm, its own in `ext/` or published ones, and they run as native code ([nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md)); a Rust app can take TSX screens the same way ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md)). ### The shared engine From the engine on, both paths are the same. Changes are collected per turn, laid out with Taffy (flexbox and CSS grid), and handed to the main thread as one batch of view operations per frame; the main thread applies the batch to native views. Text is measured and laid out once on the engine thread (CoreText on Apple platforms, `StaticLayout` on Android, DirectWrite on Windows, Pango on Linux, the browser's font metrics on the web) and only drawn on the main thread. On the web, the same engine runs in the page: the browser shows HTML elements styled with CSS, scrolls them, selects their text and handles input, and `nsh package --target web` publishes the app as a static site whose files are named by content, ready for any CDN ([Web](https://nsh.dev/versions/v0.7.1/docs/web.md)). > [!NOTE] > The main thread never waits for the app's code. Questions the system asks synchronously (may this input accept another character, may the user swipe back, may this sheet close) are answered natively from props set beforehand, such as `maxLength`, `popOnBack` or `closeOnSwipe`. Events reach the app's handlers afterwards. ## Dynamic UI and AI-generated UI NSH began as a way for native apps to take UI after release, and that stays one of its main uses. An app embeds an `NshAppView` (iOS), `NshView` (Android), `AppView` (macOS, Windows, Linux and GPUI apps) or `createPlayer` (a web page) wherever a module should appear, and NSH runs TSX modules inside it: - **Delivered after release.** A module is a signed package (`.nshpkg`) the app downloads at run time. The app checks its signature against the keys it trusts and against a revocation list before running it ([Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md)). The host app ships the runtime; teams build modules against its API and deliver them on their own schedule. - **The host stays in control.** Each module runs in its own QuickJS VM, with memory, call-time and node limits, and reaches only what the host grants: network hosts, web pages, the status bar ([Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). Several modules run side by side. - **Modules can match the rest of the app.** Modules can reuse the app’s component styles, and the host can register its own native views — a map, a player, a design-system component — for modules to use ([Native components](https://nsh.dev/versions/v0.7.1/docs/native-components.md)). The same mechanism lets an app **answer with an interface**. A model writes a small TSX module (a form, a chart, a booking card), your server checks, builds and signs it, and the app shows it natively: ![From a prompt to native UI: a model writes a TSX module; your server builds, checks and signs it; across the trust boundary, the app verifies the package, runs it in a sandbox with the limits and capabilities it set, and shows it with the platform's own UI.](https://nsh.dev/versions/v0.7.1/diagrams/ai-flow-light.svg) On iOS, the host's part is a few lines: ```swift let app = NshAppView() // a UIView: place it anywhere try app.grantCapabilities(#"{ "network": { "hosts": ["api.example.com"] } }"#) let info = try await app.loadPackage(at: downloadedFile, trust: trust) // verified, then run ``` ## AI-friendly NSH is designed for software written with AI, whole apps as much as generated screens: - **One app model for every platform.** A model learns one way to write UI, and the result runs on phones, desktops and the web; NSH adapts the interaction per platform, so nothing is generated six times. - **TSX, with Rust where it pays.** TSX for apps, screens, plugins and UI generated per request; Rust for performance-critical modules the TSX imports, or for whole apps — on one engine. - **A precise, generated contract.** Every element, prop, style key and module has TypeScript declarations generated from the Rust sources (`.nsh/types`), and Rust APIs are typed, so generated code is checked by a compiler. These docs are served as plain text for models ([`llms.txt`](/llms.txt), [`llms-full.txt`](/llms-full.txt)), and `npx skills add longbridge/nsh` installs the Coding and Design Guides as skills for coding agents. - **One command line for the whole loop.** An agent creates the app, builds it, runs it on a target, runs its tests, reads the result, fixes and packages it, all through `nsh`. `nsh test` runs headless, without a device, and reports errors and the views produced; the compiler also runs in-process (`nsh_bundler::compile_module`) and in the browser ([Playground](/playground)). - **Safe to run when it is not trusted.** Generated code delivered at run time is untrusted code: it arrives signed, runs in a VM with limits and reaches only the capabilities the host grants. ## Where it runs | Platform | Requires | Backend | Embedded with | |---|---|---|---| | [iOS](https://nsh.dev/versions/v0.7.1/docs/ios.md) | iOS 15.0+ | UIKit | `NativeShell.xcframework` | | [Android](https://nsh.dev/versions/v0.7.1/docs/android.md) | Android 8+ | Android views | `nsh.aar` | | [macOS](https://nsh.dev/versions/v0.7.1/docs/macos.md) | macOS 14+ | AppKit | `AppView` | | [Windows](https://nsh.dev/versions/v0.7.1/docs/windows.md) | Windows 10 1809+ | Win32, Direct2D | `AppView` | | [Linux](https://nsh.dev/versions/v0.7.1/docs/linux.md) | GTK 4.14+ | GTK 4 | `AppView` | | [Web](https://nsh.dev/versions/v0.7.1/docs/web.md) | Modern browsers | HTML | `createPlayer`, iframe | | [TUI](https://nsh.dev/versions/v0.7.1/docs/tui.md) | Terminals on macOS, Windows and Linux | ratatui | `AppView` (ratatui area) | | [GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md) | Desktops | GPUI | `AppView` (GPUI, GPUI Kit apps) | As a development tool, Mac Catalyst (`--target catalyst`) runs the iOS backend on a Mac for Catalyst-specific work. ![One module, many hosts: the same bundle and Rust runtime on iOS, Android, Linux, macOS with AppKit and Windows with Win32 / Direct2D, GPUI on all three desktops, and web pages drawn with HTML.](https://nsh.dev/versions/v0.7.1/diagrams/platforms-light.svg) ## Native Shell and GPUI Shell [Longbridge](https://longbridge.com) builds NSH for its own clients. The first need was a plugin layer for the mobile client, and [GPUI Shell](https://gpui-kit.com/shell), which makes [GPUI](https://gpui-kit.com) desktop apps extensible in JavaScript, was the starting point. On phones, UI drawn by GPUI itself would have had to rebuild what the platform already does — text selection and its menu (Copy, Share, Translate, Look Up), input methods, accessibility, the visual materials each iOS release brings — and every mobile team would have taken on a new UI stack. NSH therefore renders with each platform's own UI, and it grew from that plugin layer into a framework for whole apps on every platform. The two are positioned differently. GPUI Shell extends GPUI desktop applications; Native Shell is a framework for native apps on phones, desktops and the web, and its GPUI backend embeds NSH apps in GPUI and GPUI Kit apps ([GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md)). ## How it compares For whole apps, NSH sits among cross-platform frameworks such as React Native, Flutter, Qt, GPUI, Slint, Electron and Tauri; for UI delivered after release, among web views, server-driven UI and mini-program containers. Its choice is each platform's own UI and interaction under one app model, written in TSX on an engine built in Rust, with Rust for the parts that need it. [Comparing approaches](https://nsh.dev/versions/v0.7.1/docs/comparison.md) goes through each. ## Next steps - [Installation](https://nsh.dev/versions/v0.7.1/docs/installation.md) and [Getting started](https://nsh.dev/versions/v0.7.1/docs/getting-started.md): get `nsh`, write a first app and run it on each platform. - [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md): extend a TSX app with Rust components, modules and classes, its own or published ones. - [Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md): apps written in Rust from start to end. - [Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md): what runs where, and how to run, package and embed on each platform. - [JSX and components](https://nsh.dev/versions/v0.7.1/docs/jsx-and-components.md) and [Reactivity](https://nsh.dev/versions/v0.7.1/docs/reactivity.md): the two ideas everything else builds on, in TSX and Rust. - [Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md) and [Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md): deliver modules and decide what they may do. Source: https://nsh.dev/versions/v0.7.1/docs --- # Goals and design principles Native Shell provides native views and interaction across iOS, Android, macOS, Windows, Linux and the web. The app owns its visual design. One component model serves whole apps, embedded features and dynamically delivered UI. ## Native foundations, app-owned design NSH builds on each platform's views, text and input infrastructure, and adapts interaction to the device: keyboard navigation, pointer and touch input, text editing, scrolling and accessibility ([Introduction](https://nsh.dev/versions/v0.7.1/docs.md#what-native-means)). The app defines colors, typography, spacing, shapes, state feedback and animation. A settings screen can follow the app's brand on iOS and Android while input and navigation follow each device's conventions. Designers refine that visual language through styles and component parts. A native view is the rendering foundation. A system-styled control is a particular visual and behavioral choice. NSH's common controls expose shared behavior and customizable parts so applications can build their own design systems. ## Native integration in practice The native foundation includes rendering, frame-driven animation, input and accessibility semantics. On iOS and Android, [Input](https://nsh.dev/versions/v0.7.1/elements/input.md) uses platform text fields: the platform handles editing, selection menus, input methods and supported autofill services. The app describes the field through `autoComplete`, for example `current-password` or `postal-code`, and the system provides the available suggestions according to its settings and services ([Forms and keyboard](https://nsh.dev/versions/v0.7.1/docs/forms-and-keyboard.md)). Styling the field is compatible with keeping this system integration. This is an architectural distinction from drawing a text field entirely within a custom renderer: a custom renderer supplies its own integration with system editing and accessibility services, while NSH uses platform text controls where its backend provides them. Each backend's documentation defines its integration, including NSH's own editor on Windows and the GPUI embedding backend ([Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md)). [GPUI Kit](https://gpui-kit.com)'s separation of component behavior from visual design informs NSH's layers. NSH builds on that principle with platform view and input infrastructure. Native integration and app-owned design work together throughout this model. ## One component model across platforms A switch means the same thing on a phone, a desktop and the web. [`nsh/base`](https://nsh.dev/versions/v0.7.1/modules/nsh-base.md) provides state, input handling, focus and accessibility; the app styles the [Switch](https://nsh.dev/versions/v0.7.1/elements/switch.md)'s track, thumb and states. Buttons, checkboxes and radios follow the same principle. | Responsibility | Home | Example | |---|---|---| | Rendering, layout, reactivity and environment | `nsh-core`, `nsh` and runtime modules | Views, text, signals, styles | | Shared behavior and accessible structure | `nsh-base`, imported as `nsh/base` in TSX | `Button`, `Checkbox`, `Switch`, `Tabs` | | Visual design and styled components | The app or a community library | Branded controls, cards, form rows | | Platform-specific capabilities | `nsh/mobile`, `nsh/desktop` | Mobile navigation bar, desktop window controls | Common controls have one cross-platform home in `nsh/base`. Platform modules are scoped by purpose and platform semantics. [`TabBar`](https://nsh.dev/versions/v0.7.1/modules/nsh-mobile.md#tabbar) serves mobile top-level navigation; [`Tabs`](https://nsh.dev/versions/v0.7.1/elements/tabs.md) switches tabbed content across platforms. Their roles are distinct. `nsh/mobile` accepts capabilities with mobile-specific interaction semantics; differences in a common control’s appearance, size, tint or animation belong within its shared component and app styling. A notification or toast with a shared role should first be designed around one cross-platform contract, with presentation adapted internally. A shared component can adapt its interaction internally: a menu opens as a popup on a desktop and a sheet on a phone, while the app uses one API and supplies its appearance. System-managed presentations such as navigation headers and alerts follow their documented platform presentation rules. Apps can expose their own native components and services through the [embedding interfaces](https://nsh.dev/versions/v0.7.1/docs/native-components.md). ## The unstyled foundation and the component-library layer NSH owns the primitives and the unstyled foundation (`nsh-core` and `nsh-base`). Applications and third-party libraries own the styled component-library layer — the role `gpui-component` plays in [GPUI Kit](https://gpui-kit.com). This division gives each product control over its visual language while reusing the difficult parts of component implementation. The experience behind this choice comes from [GPUI Kit](https://gpui-kit.com). Its styled components grew from work on Longbridge Pro. As applications needed increasingly different designs, customization pressure led users to fork components. Extracting the shared foundation into `gpui-base` made behavior reusable across those designs. Styled components remain useful as a design reference and for applications whose needs fit their customization surface; the foundation gives other applications direct control over presentation. NSH applies this lesson from the start. `nsh/base` owns complex behavior, interaction, reactive state, focus, accessibility and adaptive presentation, with tests at the layer that owns each behavior. This includes larger structures such as [Dock](https://nsh.dev/versions/v0.7.1/elements/dock.md). Applications build diverse designs on that foundation through styles, states, slots and parts. Component contributions follow the same boundary: visual defaults and branded variants belong to application or third-party components. The documented system-managed presentations and `TextView` reading defaults retain their specific contracts ([Architecture](https://nsh.dev/versions/v0.7.1/docs/architecture.md#three-layers)). ### What the Gallery demonstrates The website demos and Gallery are styled example applications. Their gradients, shadows, rounded corners, transitions and motion exercise NSH's customization capabilities and provide source examples. Those choices belong to the demos and Gallery; the reusable base components expose the behavior and parts underneath them. Applications can borrow the examples or build a different visual language. An independently distributed styled library would belong to the application/community layer described above. Gallery styling illustrates one design direction; suitability for a particular product is a design decision for that product. ## Rust and TSX on one engine TSX apps, TSX apps extended with Rust and apps written in Rust share primitives, base components, signals and layout. TSX carries an app's screens, state and logic with rapid iteration, and the same modules can be delivered at run time. Rust provides compiled logic and reusable native components through [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md), or a whole app ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md)). The engine updates bindings that depend on changed signals and batches view operations. Text layout, native animations and input belong to the engine and its platform backends ([Architecture](https://nsh.dev/versions/v0.7.1/docs/architecture.md)). Performance is evaluated with reproducible application workloads ([Performance](https://nsh.dev/versions/v0.7.1/docs/performance.md)). ## Embedding, dynamic delivery and AI An existing native app places an NSH view where a feature belongs and exposes its own native components and host services. Standalone apps use the same runtime and component model ([Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md)). Dynamically delivered TSX modules own their state, logic and layout. Signed packages establish which publishers the host trusts; sandbox limits and capabilities define what modules may do. The host chooses both trust and permissions ([Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md), [Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). AI-generated UI follows that contract: generate TSX against declared APIs, check and test it, build and sign the module, then verify and run it under host policy. Generated declarations, model-readable documentation and CLI tests make the workflow inspectable and repeatable ([Testing and tracing](https://nsh.dev/versions/v0.7.1/docs/testing-and-trace.md)). ## How these goals guide additions 1. Establish the user behavior and whether it is shared across platforms. 2. Put shared behavior in the existing primitive or base component, exposing state and parts for app customization. 3. Put capabilities with platform-specific semantics in their platform module, documenting applicability and composition with shared UI. 4. Build styled components in the app or community library. 5. Verify behavior, accessibility, layout and input on affected platforms, and document the public contract in both languages. These principles keep visual design flexible, shared component APIs coherent and platform integration explicit as NSH grows. Source: https://nsh.dev/versions/v0.7.1/docs/goals --- # Comparing approaches NSH is a framework for whole apps on iOS, Android, macOS, Windows, Linux and the web, and a runtime for UI delivered to apps after release. This page compares it first with the cross-platform frameworks people write apps in, then with the ways apps take UI they did not ship with. Green means the capability is available, yellow that it needs more of the app's own work or a separate project, and red that it is not provided; the marks describe availability, not performance. Versions are each framework's documented minimums at the time of writing: check them for the release you use. This page is written for teams on Electron, Tauri, React Native, Flutter, GPUI, Qt or Slint: where NSH comes from, what each cell of the comparison rests on, the challenge NSH puts to each framework, what moving to NSH gains and costs, and when another option fits better. **Native UI, a web-style developer experience, Rust performance, low resource use, and one framework for desktop, mobile, web and terminal.** Cross-platform UI frameworks have long faced the same trade-off: developer experience, native interaction, platform reach, performance or resource use — which comes first? Electron chose the browser; Tauri kept web UI but switched to the system web view; React Native brought React to native views; Flutter traded for consistency with its own renderer; GPUI gives desktop apps high-performance UI with Rust and the GPU; Qt built a mature system for professional desktop and embedded software; Slint keeps pushing lightweight, embedded and declarative UI. Each has real strengths and clear architectural trade-offs. **The question NSH sets out to answer: can developers stop having to pick one of these needs over the others?** ## Where NSH comes from [Longbridge](https://longbridge.com) needed a desktop client first. To get away from what Electron costs on the desktop — high memory, slow start, unsteady frame rates, a loose fit with the system — Longbridge built [Longbridge Pro](https://longbridge.com/desktop) on [GPUI](https://gpui-kit.com), the Rust GPU UI framework behind the [Zed](https://zed.dev) editor, and grew the [GPUI Kit](https://gpui-kit.com) components and the [GPUI Fast](https://github.com/longbridge/gpui-fast) fork on top of it. A trading client is demanding: high-frequency quotes, order books, candlesticks and linked charts stay open for hours without dropping frames or holding the CPU, and the desktop needs dependable windows, text input and system integration. NSH started as a plugin layer for the mobile clients (the idea of [GPUI Shell](https://gpui-kit.com/shell), taken to phones) and then carried the same app model — components, signals, layout, modules — to iOS, Android, macOS, Windows, Linux and the web ([Introduction](https://nsh.dev/versions/v0.7.1/docs.md#native-shell-and-gpui-shell)). So: - **The desktop is not an add-on.** macOS (AppKit), Windows (Win32 with Direct2D) and Linux (GTK 4) are backends of the same framework as phones and the web, built from one repository, tested by one suite and shipped in one release. - **Performance is a constraint of the architecture, not a later pass.** The renderer, layout, animation and list virtualization run in Rust; Rust apps link no JavaScript engine, and in TSX apps the main thread never waits on JS ([Architecture](https://nsh.dev/versions/v0.7.1/docs/architecture.md)). - **Delivered UI was required to be safe from day one.** A plugin layer runs code someone else wrote, so signed packages, revocation lists, a sandboxed virtual machine and capability grants were design goals from the start ([Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md), [Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). Legend: Yes · Partial · No. ## Cross-platform frameworks | Capability | NSH | Electron | React Native | Flutter | Qt 6 | GPUI / GPUI Fast | Slint | |---|---|---|---|---|---|---|---| | **Platforms** | | | | | | | | | iOS | 15+ | | 15.1+ | 15+ | 17+ | | Rust | | Android | 9+ | | 7+ | 7+ | 9+ | | | | macOS | 14+ | 12+ | Separate project | 12+ | 13+ | 12+ | 13+ | | Windows | 10 1809+ | 10+ | Separate project | 10+ | 10 1809+ | 10+ | 10+ | | Linux | GTK 4.14+ | | | | | Vulkan | | | Web | HTML | Separate web app | Library | Canvas | Canvas | | Canvas | | Terminal (TUI) | ratatui | | | | | | | | **Rendering and runtime** | | | | | | | | | Drawn by | Platform UI | Chromium | Platform views | Own engine | Own (Widgets, Quick) | Own, GPU | Own renderer | | Update model | Fine-grained signals, retained views | Web framework on the DOM | React re-render and diff | Widget rebuild and diff | Property bindings | Rebuilt every frame; Fast reuses unchanged views | Property bindings | | Where layout, animation, lists run | Rust | JS and Chromium | Yoga (C++), list logic in JS | Dart | C++ | Rust | Rust | | App language | Rust, TSX | JS, TS | JS, TS | Dart | C++, QML, Python | Rust | Slint + Rust, C++, JS, Python | | No JS runtime | Rust apps | Node + Chromium | Hermes | | C++ Widgets | | | | **Text, input and accessibility** | | | | | | | | | System text editing | Platform editors | Chromium's | | Own | Own | Own | Own | | System accessibility tree | Native views | Chromium | | Semantics tree | | Limited | | | Per-device interaction | Built into base components | | | | | | | | **Desktop and embedding** | | | | | | | | | Windows, menus, tray | | | Separate projects | Plugins | | No tray | | | Embed in an existing native app | One view | | Brownfield | Add-to-app | | | | | Embed in a GPUI app | GPUI backend | | | | | Native | | | **Tooling and delivery** | | | | | | | | | Toolchain | One nsh executable, no Node | Node, npm, packager | Node, Metro, CocoaPods, Gradle | flutter CLI, Xcode, Gradle | CMake, Qt Creator | cargo | cargo, CMake | | Hot reload | | | Fast Refresh | | QML | | Live preview | | Signed, sandboxed delivered UI | | | OTA of trusted code | | Loads QML | GPUI Shell | | | License | Apache-2.0 | MIT | MIT | BSD-3-Clause | LGPL, GPL, commercial | Apache-2.0 | GPL, royalty-free, commercial | GPUI and GPUI Fast share a column: they run on the same platforms, and GPUI Fast adds retained rendering on top of GPUI. "GPUI Shell" is [GPUI Shell](https://gpui-kit.com/shell). Read down the NSH column: it is the only one green in every group. In particular, no other framework here combines - **seven targets from one app** — iOS, Android, macOS, Windows, Linux, the web as HTML, and terminals — in one repository and one release; - **the platform's own views, text editors and accessibility tree** with **no JavaScript runtime** for Rust apps; - **interaction that adapts per device inside the base components**, instead of in each app; - **embedding as a single view** into existing iOS, Android, desktop and GPUI apps; - **signed, sandboxed UI delivered after release**, with revocation and rollback; - **one executable for the whole toolchain**. ### What the rows mean - **Electron.** Chromium plus Node in every app: the desktop's widest web-content path, with no phones. Minimums follow [Electron's supported platforms](https://www.electronjs.org/docs/latest/tutorial/support#supported-platforms); its web version is the same code deployed as a separate site. - **Drawn by, update model.** NSH mounts each platform's own views and keeps them (retained mode): a change updates only the views it touched. React Native also mounts platform views, on iOS and Android. Flutter, Qt Quick, GPUI and Slint draw with their own renderers; GPUI builds the element tree each frame (immediate mode), and [GPUI Fast](https://github.com/longbridge/gpui-fast) reuses what did not change. - **Platforms.** NSH's minimums are its own ([Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md)). The others come from [React Native 0.76](https://reactnative.dev/blog/2024/10/23/release-0.76-new-architecture) (iOS 15.1, Android 7 / API 24; macOS and Windows through the separate react-native-macos and react-native-windows projects, the web through the react-native-web library), [Flutter 3.47](https://docs.flutter.dev/reference/supported-platforms), [Qt 6.10](https://doc.qt.io/qt-6.10/supported-platforms.html), [Zed's requirements](https://zed.dev/docs/installation) for GPUI, and [Slint's platform guides](https://docs.slint.dev/latest/docs/slint/guide/platforms/mobile/general/) (iOS from Rust). "Canvas" means the framework draws into a canvas on the page; NSH's web apps are HTML elements styled with CSS, which the browser scrolls, selects and edits ([Web](https://nsh.dev/versions/v0.7.1/docs/web.md)). Layout is computed in Rust by Taffy; it is not full browser CSS layout. - **System text.** NSH's text fields are the platform's editors — `UITextView`, `EditText`, `NSTextView`, GTK's `TextView`, the browser's — with the system's input methods, selection handles and editing menus; on Windows, NSH's own editor works with DirectWrite and the system's input methods (IMM32). React Native also uses the platform's text inputs. The self-drawn frameworks implement text editing themselves and connect it to the system's input methods. - **Per-device UX.** NSH's base components follow the device: the same `Menu` is a popup at its trigger with a pointer and a sheet from the bottom on a phone, and a `ContextMenu` opens on a right click or a held finger. In the others, adapting interaction per device is mostly the app's own work. - **Where layout, animation and lists run.** In NSH they run in Rust off the JavaScript path: a busy TSX handler does not stall scrolling or an animation ([Architecture](https://nsh.dev/versions/v0.7.1/docs/architecture.md)). React Native lays out with Yoga in C++ while list windowing and most animation logic stay in JS unless a library moves them. - **Accessibility.** NSH's elements are native views, so VoiceOver, TalkBack and the desktop screen readers read the real hierarchy; apps add labels, roles and actions ([Accessibility](https://nsh.dev/versions/v0.7.1/docs/accessibility.md)). GPUI exposes little to assistive technology today. - **Windows, menus, tray.** `nsh/desktop` provides windows, menus, the tray and Dock badges on macOS, Windows and Linux ([nsh/desktop](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md)). GPUI has windows and menus but no tray; Flutter takes them from plugins. - **Embedding.** An NSH app embeds as one view in an existing iOS, Android or desktop app ([Embedding](https://nsh.dev/versions/v0.7.1/docs/embedding.md)), and as a view in GPUI and GPUI Kit apps through its GPUI backend ([GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md)). React Native (brownfield) and Flutter (add-to-app) also embed, each bringing its own runtime. - **Terminal.** The same component model renders terminal apps through ratatui ([TUI](https://nsh.dev/versions/v0.7.1/docs/tui.md)). - **Toolchain, hot reload.** One `nsh` executable creates, runs with hot reload, tests on real platforms, packages and signs for every target, and TSX needs no Node or npm ([CLI](https://nsh.dev/versions/v0.7.1/docs/cli.md)). - **Native engine, thin script.** In a TSX app only the app's own code is JavaScript; the reactive graph, layout, rendering and modules are Rust, and a Rust app's runners link no JavaScript engine on any platform. Qt Quick's QML runs on Qt's JavaScript engine; Qt Widgets in C++ do not. - **Signed delivery.** NSH verifies signed `.nshpkg` packages against the keys it trusts and a revocation list, and runs each in a VM with the limits and capabilities the host grants ([Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md), [Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). A packaged NSH app takes its own TSX over the air the same way, iOS and Android included, and rolls back a release that fails to start ([OTA Updates](https://nsh.dev/versions/v0.7.1/docs/ota-updates.md)). React Native's over-the-air updates ship trusted app code; Qt can load QML files; GPUI apps take JavaScript modules through [GPUI Shell](https://gpui-kit.com/shell). ### What sets NSH apart - **Native on every platform, in both senses.** Each backend builds on its platform's own views, text and input methods — UIKit, Android views, AppKit, Win32 with Direct2D, GTK 4, HTML — and each platform's interaction comes with them. Text selection, input methods and accessibility are the system's, and what a new OS release brings to them reaches the app ([Introduction](https://nsh.dev/versions/v0.7.1/docs.md#what-native-means)). - **Phones, desktops and the web from one app.** Six platforms are backends of one framework, sharing one reactive graph, renderer, Taffy layout and module system, with layouts that reshape and input that follows the device; on the web, the app is HTML, published as a static site. - **Rust first, with apps in TSX.** The engine is Rust, compiled to native code. Apps are written in TSX with hot updates, and only their own code is JavaScript. Rust [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md), the app's own or published, give the TSX native components and modules where speed, the platform or crates.io are needed, and a whole app can be Rust from start to end, with no JavaScript runtime ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md)). - **Retained views for everyday apps.** Components run once and fine-grained signals send only the properties that changed, so chats, forms, lists and documents sit near idle at rest ([Introduction](https://nsh.dev/versions/v0.7.1/docs.md#retained-views), [Reactivity](https://nsh.dev/versions/v0.7.1/docs/reactivity.md)). - **UI delivered after release, signed and sandboxed.** Apps built with NSH — and native apps written with each platform's own tools — take TSX modules at run time, written by a team or generated by AI ([Dynamic UI](https://nsh.dev/versions/v0.7.1/docs.md#dynamic-ui-and-ai-generated-ui)). - **One toolchain, for people and agents.** One `nsh` executable creates, runs, hot-reloads, tests on real platforms, packages and signs apps for every target; TSX needs no Node or npm ([CLI](https://nsh.dev/versions/v0.7.1/docs/cli.md), [Installation](https://nsh.dev/versions/v0.7.1/docs/installation.md)). ### Components for professional applications Consider a research workstation. A trader selects cells while quotes arrive, reads a report as it streams in, and moves a panel while editing a note. Each interaction needs a durable implementation. NSH carries the layering developed in GPUI Kit across its hosts. [NSH Base](https://nsh.dev/versions/v0.7.1/modules/nsh-base.md) owns behavior, state, focus and accessibility. Product teams build their visual language above it and can use the same interaction conventions across applications. | Base component | What an application can reuse | |---|---| | [DataTable](https://nsh.dev/versions/v0.7.1/elements/data-table.md) | Virtualization on both axes creates only visible cells. A quote grid can combine pinned columns, paged data and keyboard selection. | | [Editor](https://nsh.dev/versions/v0.7.1/elements/editor.md) | Visible rows and incremental highlighting limit work after an edit. A strategy editor can reuse multiple carets, folding, diagnostics and find-and-replace. | | [TextView](https://nsh.dev/versions/v0.7.1/elements/text-view.md) | Rust parses streamed Markdown into text and views, including tables, code and links, so a research assistant can render a reply as it arrives. | | [RichEditor](https://nsh.dev/versions/v0.7.1/elements/rich-editor.md) | A schema constrains document structure and transactions record edits. Teams can add mentions or commands while retaining edit history. | | [DiffView](https://nsh.dev/versions/v0.7.1/elements/diff-view.md) | Render a patch or compare two texts with aligned or unified views, word-level highlights and review annotations. | | [Dock](https://nsh.dev/versions/v0.7.1/elements/dock.md) | The component handles splitting, resizing and moving tabs. Panels retain their content when moved and the app owns the layout data. | These choices affect performance, stability and extensibility in different ways. The grid bounds cell creation, the document schema keeps edits valid, and moving a tab preserves its content. Apps can supply cells, document types and panels while reusing scrolling, undo and drag behavior. The quote workload below measures runtime performance; the linked component examples demonstrate the individual behaviors. ### Measured numbers These come from the [performance report](https://nsh.dev/versions/v0.7.1/docs/performance-report.md) and the [NSH performance benchmark](https://github.com/longbridge/nsh-perf-bench), all release builds; reproduce them on your own devices with `nsh`'s trace ([Measuring an app](https://nsh.dev/versions/v0.7.1/docs/performance-report.md#measuring-an-app)). | Measurement | Result | |---|---| | Engine start | ~75–155 µs | | Counter app first frame (Mac Catalyst) | ~1.05–1.15 ms | | One tap (JS plus commit) | ~0.12 ms | | Rust app memory on macOS | ~19 MB, against ~17 MB for an AppKit window with one label | | Sorting 100,000 rows in a Rust module called from TSX | ~3 ms, on par with pure Rust | | 500-row quote table, 1,000 updates a second (Linux) | NSH Rust 18% of one core, GPUI Fast 20% | | Stocks demo: 22 live sparklines, intraday chart, order book, trades (Linux) | 117–120 FPS, 25–29% CPU | ## Challenging the mainstream UI frameworks Each section below puts a question to one framework: what it does well, where it costs, how NSH handles the same problem, and what carries over or costs when moving. For performance data, see the [measured numbers](#measured-numbers) above. > This compares architectural choices and fit for typical apps; it does not claim any framework loses under every workload. Performance numbers come from NSH's own tests or development experience, and are a strict cross-framework benchmark only when device, app, workload and measurement method are the same. ## Challenging Electron: why ship a whole browser to build a native app? Electron's success is beyond question: HTML, CSS, JavaScript, React and the web ecosystem made desktop development very productive. Its costs are just as clear. **Electron apps bundle Chromium and Node.js.** Electron "inherits its multi-process architecture from Chromium": every app has a Node.js main process and spawns "a separate renderer process for each open `BrowserWindow`" ([Electron process model](https://www.electronjs.org/docs/latest/tutorial/process-model)). Every Electron app therefore carries its own copy of Chromium and Node.js. Where that hurts: - **Size and memory.** A browser engine and a JavaScript runtime come with every app and every window, before the app draws anything. In practice a typical Electron app starts at an installer of around 150 MB and often uses 1 GB of memory or more once in use (typical figures from experience, not a benchmark); a desktop with several Electron apps runs several browsers. For comparison, NSH's measured Linux packages are 9.7–11.7 MB archives (hello worlds, and real apps such as sysmon and Omasend), and a Rust app on macOS uses ~19 MB of memory ([App size](https://nsh.dev/versions/v0.7.1/docs/performance-report.md#app-size)). - **Memory can grow after a tab closes.** Suppose a global quote feed still holds a callback for a closed panel. If the callback references a detached DOM node, the garbage collector can see a path to it and the whole subtree can stay alive. Reopening and closing the panel can accumulate old views and callbacks that still run on every tick. Both memory use and input latency can grow over a long session. [Chrome DevTools memory guide](https://developer.chrome.com/docs/devtools/memory-problems) - **Start-up.** The app waits for Chromium and Node.js to start, then for its JavaScript to load, parse and run, before the first frame. - **Steady-state CPU.** Live data updates the DOM, which goes through style recalculation, layout and painting in the page; long lists and frequent updates are exactly what web pages handle worst. - **The page is not the system.** Text fields, selection, context menus, scrolling and accessibility are the browser's implementations inside a window, not the operating system's controls. Native menus, dialogs and tray icons exist, but only through the main process, across an IPC boundary from the UI. - **No phones.** Electron is desktop only; a mobile client is a second project. - **Security is the app's job.** Renderers can be given Node.js access, and Electron's own security checklist (context isolation, sandboxing, no remote content with Node integration) is something every app has to follow correctly. How NSH answers: | Electron's cost | NSH | |---|---| | Chromium + Node.js in every app | No browser engine. Rust apps link no JavaScript engine at all; TSX apps run app code in QuickJS while rendering, layout and animation run in Rust ([Architecture](https://nsh.dev/versions/v0.7.1/docs/architecture.md)) | | ~150 MB installers, often 1 GB+ memory (typical) | 9.7–11.7 MB Linux archives for hello worlds, sysmon and Omasend ([App size](https://nsh.dev/versions/v0.7.1/docs/performance-report.md#app-size)); ~19 MB for a Rust app on macOS, against ~17 MB for an AppKit window with one label ([Performance report](https://nsh.dev/versions/v0.7.1/docs/performance-report.md)) | | Detached DOM retained after closing a panel | Native NSH controls run on the Rust runtime and create no DOM subtree to retain. Pure Rust apps also avoid JS garbage collection. TSX apps still need to release callbacks held by application code. | | Slow start | Engine start ~75–155 µs; counter app first frame ~1.05–1.15 ms | | DOM layout under live data | Fine-grained signals push only the properties that changed to platform views; a 500-row quote table at 1,000 updates a second uses 18% of one core on Linux | | Browser text, menus and accessibility | AppKit, Win32 + Direct2D and GTK 4 controls, input methods and accessibility ([Introduction](https://nsh.dev/versions/v0.7.1/docs.md#what-native-means)) | | Desktop only | The same app on iOS, Android and the web ([Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md)) | | App-managed security | Delivered UI runs in a sandboxed VM with host-granted capabilities and signed, revocable packages ([Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)) | **What carries over.** TSX reads like JSX and styling reads like CSS and [Tailwind](https://nsh.dev/versions/v0.7.1/docs/tailwind.md), so most of a web team's experience applies; an existing page can still be shown in a [web view](https://nsh.dev/versions/v0.7.1/docs/web-view-and-video.md). **What it costs.** DOM code and npm component libraries that depend on a browser do not carry over; screens are rewritten with NSH elements. Chat and AI apps gain the most. Many AI products render their conversations as web pages, and long sessions bring dropped frames while scrolling, awkward input methods and selection, and weak integration with system accessibility and gestures. NSH renders rich text, code blocks, tables, images and streamed output with the platform's text views and editors ([Text](https://nsh.dev/versions/v0.7.1/docs/text.md), [Lists](https://nsh.dev/versions/v0.7.1/docs/lists.md)). For a multi-pane review tool, inventory the web grid, docking library and diff renderer separately. Map them to DataTable, Dock and DiffView, then port custom cells and review actions. Existing DOM widgets need replacement or an embedded web view. **The challenge: The Web development experience. Without the browser.** ## Challenging Tauri: Chromium is gone, so why is the UI still a web view? Tauri's system web view and Rust backend changed Electron's runtime cost structure, and suit teams that already have a web app and want a light desktop or mobile client quickly. The UI is still a web page. **Tauri uses the system webview.** Tauri avoids bundling Chromium by using whatever the OS provides: WebView2 (Chromium) on Windows, WKWebView (WebKit) on macOS and iOS, `webkit2gtk` (WebKit) on Linux, and the device's Android WebView ([Tauri webview versions](https://v2.tauri.app/reference/webview-versions/)). Apps get smaller; the UI is still a web page. Where that hurts: - **Three engines, many versions.** The same app runs on Chromium on Windows and Android and on WebKit on Apple platforms and Linux. Tauri's own reference notes that on Android "the runtime version depends on the device's currently selected WebView provider", that "unsupported macOS versions **do not** receive WebKit updates", and that on Linux "it is very hard to compile accurate information about WebKitGTK on the various distros" ([source](https://v2.tauri.app/reference/webview-versions/)). Rendering bugs and missing web features are tested per engine and per OS version. - **Still a page.** Text, scrolling, selection and accessibility are the web view's, not the system's controls; performance under live data is the DOM's. - **A Rust backend cannot release references inside the page.** For example, after navigating away from a chart, a timer in the WebView can keep the old chart and its price history alive through a closure. Leaving one timer behind on each visit accumulates both memory and background redraw work. Even after the Rust backend releases its resources, the page still needs to cancel the timer and release its references. [Tauri process model](https://v2.tauri.app/concept/process-model/) - **Two languages across a bridge.** UI in JavaScript, logic in Rust, joined by IPC calls and serialization. How NSH answers: the UI is the platform's own views, the same on every OS version the platform supports, with no web engine in between; TSX and Rust run in one process on one reactive graph, and a TSX screen calls a Rust module directly — sorting 100,000 rows from TSX takes ~3 ms, on par with pure Rust ([Performance report](https://nsh.dev/versions/v0.7.1/docs/performance-report.md)). Tauri's best idea — Rust for the core — is NSH's default, and Rust is the core of the whole UI rather than a backend: heavy computation, file indexing, audio and video processing and OS APIs come in as [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md) modules. When an app needs to show a real web page, NSH still embeds a [web view](https://nsh.dev/versions/v0.7.1/docs/web-view-and-video.md) without turning the whole app into one. **What it costs.** An existing web UI is rewritten with NSH elements. If the goal is to wrap an existing website as a client as quickly as possible, Tauri's reuse still wins; NSH fits products that want a native UI from the start. On native NSH targets, a chart can draw into a native Canvas and tie its update logic to a reactive scope. Disposing the scope tears down its owned computations and runs registered cleanup callbacks. Application-created timers and external quote subscriptions still need cancellation handlers. A screen that embeds a WebView still manages browser resources inside that view. [Reactive runtime implementation](https://github.com/longbridge/nsh/blob/d2c6e800dac5985c112e61626b89e30ace2d2f83/crates/nsh-core/src/reactive.rs#L1169) A Rust backend can keep producing report data. Replace a Markdown web panel with TextView first, then check links, tables and streamed updates using the same documents on each target. **The challenge: Rust at the core. Native UI, not a WebView.** ## Challenging React Native: a native framework, so why are desktop, mobile and web still separate? React Native is one of NSH's most direct competitors. It proved that TypeScript/JavaScript and native platform views fit together well, and its iOS and Android ecosystem is mature. The issue is not that it is not native enough; it is how its platforms are organized and its default update model. **React Native drives native views from JavaScript.** React Native is closest to NSH in intent: both aim to cut duplicated client work and both use platform views. But app logic and React reconciliation always run in a JavaScript engine, and the New Architecture (Fabric, TurboModules, JSI) makes the bridge faster without changing that ([React Native architecture](https://reactnative.dev/architecture/landing-page)). Where that hurts: - **The JS thread is the frame budget.** React Native's own performance guide treats a JavaScript thread that is busy for a frame as a dropped frame ([Performance](https://reactnative.dev/docs/performance)). Every state change re-renders components and diffs the result in JavaScript, so frequent updates — quotes, chat streams, timers — compete with input handling on that thread. Teams fight it with `memo`, `useMemo`, `useCallback` and dependency arrays. - **Desktop and web are other people's projects.** macOS and Windows are `react-native-macos` and `react-native-windows`, maintained by Microsoft; the web is the community `react-native-web`; there is no Linux platform except through the community React Native Skia renderer ([Out-of-tree platforms](https://reactnative.dev/docs/out-of-tree-platforms)). Each has its own release train, gaps and lag behind the core. - **The app owns per-device behavior.** A phone and a desktop need different menus, hover, keyboard and pointer behavior; React Native's components leave that to the app. - **Over-the-air updates are trusted code.** Code-push style updates replace the app's own JavaScript; there is no sandbox for code written by someone else. - **A long toolchain.** Node, npm, Metro, CocoaPods, Gradle and native build tools, each with its own versions to keep aligned. How NSH answers: | | React Native | NSH | |---|---|---| | Runtime | Always a JS engine (Hermes), with app logic and reconciliation in JS | Rust apps have no JS engine; TSX apps run only app code on QuickJS, while the reactive graph, renderer, layout, animation and list virtualization run in Rust | | Update model | Re-render after a state change, then diff | Fine-grained signals (Solid-style): components run once and push only changed properties; no memoization, no dependency arrays ([Reactivity](https://nsh.dev/versions/v0.7.1/docs/reactivity.md)) | | One tap | — | ~0.12 ms, JS plus commit ([Performance report](https://nsh.dev/versions/v0.7.1/docs/performance-report.md)) | | Desktop | Separate Microsoft-maintained projects, no Linux | AppKit, Win32 + Direct2D and GTK 4, in the same framework, tests and release as phones | | Web | Community react-native-web | A framework backend producing HTML and CSS | | Per-device UX | Left to the app | Base components adapt: `Menu` pops at the pointer on desktop and rises from the bottom on phones | | Heavy computation | Native module plus bridge code | Write it in Rust in the same app and call it from TSX: 100,000 rows sorted in ~3 ms | | Updates after release | OTA delivery of a trusted JS bundle | Signed `.nshpkg`, revocation lists, a sandboxed VM with host-set capabilities and limits, automatic rollback of versions that fail to start ([OTA Updates](https://nsh.dev/versions/v0.7.1/docs/ota-updates.md)) | | Toolchain | Node, Metro, CocoaPods, Gradle and more | One `nsh` executable; TSX needs no Node or npm ([CLI](https://nsh.dev/versions/v0.7.1/docs/cli.md)) | Fabric, JSI, TurboModules and Reanimated have removed many bottlenecks, and React Native can reach Rust through native modules. The difference is not that only NSH can call Rust, but where Rust sits: an NSH app can be written entirely in Rust with no JavaScript VM, and a TSX app's reactive graph, scheduling and mount batches run in Rust too. For a product that needs professional desktop windows, live quote tables, phones and an HTML web build at once, these are official backends of one framework rather than several projects stitched together. **What carries over.** TSX looks much like JSX, and components, props and events stay; hooks become signals. **What it costs.** NSH is not a compatibility layer for React Native, by design: it replaces React reconciliation with a more efficient model, so React Native packages do not run on it. The framework provides lists, navigation, animation, gestures, text, canvas, web views and video natively, visual components are the app's own ([Design guides](https://nsh.dev/versions/v0.7.1/docs/design-guides.md)), and an existing native SDK becomes a [native component](https://nsh.dev/versions/v0.7.1/docs/native-components.md) or a Rust [module](https://nsh.dev/versions/v0.7.1/docs/platform-extensions.md). The [core component catalog](https://reactnative.dev/docs/components-and-apis) includes lists and text inputs. A virtualized two-axis quote grid with pinned columns, or a schema-driven editor with undo, requires additional choices. With NSH the starting points are DataTable and RichEditor. Port the data source, document schema and product styling, and test selection and undo on the target devices. **The challenge: Beyond React Native. One framework for desktop, mobile, and Web.** ## Challenging Flutter: why reimplement UI the operating system already does well? Flutter draws with its own engine for highly controllable, consistent visuals across platforms — a strength, especially for heavily customized UI. Drawing everything also means the framework has to adapt many system behaviours itself. **Flutter draws widgets with its own rendering engine.** Flutter renders the whole UI itself, so an app looks the same everywhere — and none of it is the platform's. Where that hurts: - **Text and input are reimplemented.** Text editing, input methods, the selection menu, focus, keyboard navigation and accessibility semantics are Flutter's reimplementation of each platform's behavior. Flutter has mature implementations of all of them; the question is who maintains them over time, since what a new OS release brings waits for Flutter to rebuild it. - **Native views are expensive guests.** Flutter's own documentation says "platform views in Flutter come with performance trade-offs": with hybrid composition on Android, Flutter "merges the raster thread into the platform thread", "potentially causing lower application FPS and frame drops"; the texture-layer mode may cause "jankiness on quick scrolling (such as a web view)" and "broken accessibility for `SurfaceView`s" ([Hosting native Android views](https://docs.flutter.dev/platform-integration/android/platform-views)). Maps, web views, video and payment SDKs are exactly these views. - **The web is not the web.** Flutter "is not suitable for static websites with text-rich flow-based content", and its output "doesn't align with what search engines need to properly index"; the Flutter team itself recommends Jaspr or plain HTML for document-like content, and moved its own docs to Jaspr ([Flutter web FAQ](https://docs.flutter.dev/platform-integration/web/faq)). - **Dart only.** Logic and UI are Dart; systems code and existing native libraries go through platform channels or FFI. How NSH answers: each backend is the platform's own views — UIKit, Android views, AppKit, Win32, GTK 4 — so a map or web view is just another view in the tree, not a composited guest; text editing, input methods, selection and accessibility are the system's ([Introduction](https://nsh.dev/versions/v0.7.1/docs.md#what-native-means)); the web build is real HTML that can be selected, indexed and read by screen readers, with semantic markup, links and ARIA; and the languages are Rust, with its crates and native threads, plus TSX for quick screens. **What it costs.** Apps can share branded styles across platforms. System fonts and materials can still render differently on each platform. On Windows some controls are drawn by NSH with Direct2D, so evaluate them control by control; on the web, layout is computed by Taffy and is not full browser CSS layout. Flutter already offers tables and text fields. For a code-review screen, compare the work above those widgets: Editor supplies diagnostics and folding, and DiffView supplies aligned hunks and annotations. Dart widget implementations still need porting. **The challenge: Why recreate what the operating system already does best?** ## Challenging GPUI: high-performance UI, so why keep the CPU and GPU busy? GPUI proved that Rust and the GPU can build an app as complex as Zed, and it matters for high-performance custom drawing, complex editor UI and GPU control. But real performance is more than frame rate: it is also low idle cost, low power and longer battery life. **GPUI provides GPU rendering for the Zed desktop editor.** [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui) is the Rust UI framework of the Zed editor; [GPUI Fast](https://github.com/longbridge/gpui-fast) is Longbridge's fork with retained rendering, scroll layers and native window compositing, and NSH comes from the same team. Where that hurts, for a general app: - **Desktop only.** GPUI's README covers macOS, Linux/FreeBSD and Windows; phones and the web are not targets ([GPUI README](https://github.com/zed-industries/zed/blob/main/crates/gpui/README.md)). - **An editor's framework, moving with the editor.** GPUI is "still pre-1.0" and "there will often be breaking changes between versions"; the README's advice for learning it is to "read the Zed source code or drop a question in the Zed Discord" ([same source](https://github.com/zed-industries/zed/blob/main/crates/gpui/README.md)). - **Everything is drawn.** Text fields, selection and menus are drawn by the framework rather than being the platform's controls, so system text behavior is reimplemented, as in Flutter. - **Rust only, nothing delivered.** There is no scripting path for quick screens and no sandbox for UI delivered after release (GPUI Kit adds JavaScript modules through [GPUI Shell](https://gpui-kit.com/shell), the idea NSH grew from). - **High frame rates are not low cost.** Rebuilding the element tree every frame can mean rebuilding and redrawing when nothing changed. That costs CPU, and GPU drawing, compositing and wake-ups cost power too. For everyday apps, performance also means idle cost, power use and battery life. - **No terminal.** A drawn architecture could in principle reach more platforms, but today there are no iOS, Android, HTML web or TUI backends like NSH's. How NSH answers: the same Rust-first engine, with apps in TSX and Rust where it pays, reaches iOS, Android, the web and the terminal; retained mode with fine-grained signals skips recomputing and redrawing unrelated parts when little changes, cutting CPU and unnecessary GPU work; tab focus, keyboard navigation and accessibility are left to the platform where possible; text input, selection and input methods are the platform's; TSX with hot updates and signed, sandboxed delivery are built in. NSH's GPUI backend embeds NSH apps in existing GPUI and GPUI Kit apps, so screens can move one at a time instead of in a rewrite ([GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md)). **The numbers, honestly.** In the [NSH performance benchmark](https://github.com/longbridge/nsh-perf-bench) (Linux, a 500-row quote table, NSH on GTK 4), everyday load costs the same: at 1,000 quotes a second NSH Rust uses 18% of one core and GPUI Fast 20%. Under sustained heavy updates GPUI Fast leads: at 20,000 quotes a second it uses 25% against NSH's 73–78%, and on an animation of 1,000 boxes computed every frame about a third of NSH's CPU. During development we have also observed the CPU use below in specific scenarios. They come from different scenarios and past experience, without a common device, workload or measurement method, and **are not a like-for-like comparison under one load**: | Scenario | CPU (development observation) | |---|---:| | Upstream GPUI, some continuously updating screens | 40%–60% | | GPUI Fast (after retained rendering and other work) | ~20% | | NSH, comparable updating screens | under 15% | | Upstream GPUI, some low-frequency updates | ~20%–40% | | NSH, some low-frequency updates | under ~5%–10% | GPU power has not been measured separately, and a drop in CPU should not be read as the same drop in GPU power. We built GPUI Fast precisely to reduce these costs in upstream GPUI; it is not what this comparison targets. For a desktop-only terminal dominated by thousands of views updated every frame, stay on GPUI Fast; for phones, the web, everyday screens or delivered UI, use NSH. GPUI Kit users already have advanced desktop components. The gain is carrying the same interaction model to additional hosts. Embed one NSH panel first and verify its document state and keyboard behavior before moving the surrounding workspace. **The challenge: Less CPU. Less GPU work. More Native. Desktop, Mobile, Web, and TUI.** ## Challenging Qt: can mature professional desktop reach phones and the web? **Qt offers two UI technologies, Widgets and Qt Quick.** Qt Widgets and Qt Quick draw their own controls styled to resemble each platform, with long-built tooling. NSH differs in foundation and model: platform controls rather than styled look-alikes, TSX on a Rust core, with Rust for the parts that need it, instead of C++ and QML, HTML on the web, one component model that adapts interaction across mobile, desktop and web, a toolchain designed for automated and AI-driven development, and an Apache-2.0 license for every use. Qt is one of the most mature and complete UI frameworks, with rich components, system integration and decades of engineering in professional desktop software, industrial applications and embedded devices. Where that hurts: - **Its center of gravity is not consumer mobile or the web.** Qt supports iOS, Android and WebAssembly, but on phones it has not become as common a choice as native development, React Native or Flutter, and its main UI paths are not built on UIKit and Android views. Qt's WebAssembly output draws into a canvas rather than producing HTML. - **Licensing needs case-by-case review.** Qt combines LGPL, GPL and commercial licenses; teams evaluate obligations per module, linking method and distribution, and some modules are GPL or commercial only ([Qt licensing](https://www.qt.io/licensing)). - **Shipping means shipping the runtime.** The common dynamically linked deployment bundles Qt libraries, platform plugins and resources, and on Windows that means managing DLLs, plugin directories and version compatibility. Static linking is possible, with its own build and license conditions. - **The toolchain is assembled by hand.** The Qt SDK, CMake, compilers, platform plugins, runtime libraries and per-platform deployment configuration all need maintaining. NSH's approach: on the desktop it provides multiple windows, Dock, DataTable, Editor, RichEditor and DiffView; on phones it builds on UIKit and Android views; on the web it outputs real HTML and CSS; and it also targets the terminal. The NSH core is Apache-2.0, usable in closed-source commercial apps with no framework license to buy and no LGPL relinking requirement — third-party nshm modules keep their own licenses. One `nsh` executable creates, runs, tests, packages and signs apps; TSX needs no Node or npm, and pure Rust apps carry no JavaScript VM. Platform tools such as Xcode and the Android SDK are still required. **The numbers, honestly.** Qt's desktop ecosystem is still ahead, and NSH does not replace every Qt component. NSH has Linux packages around 10 MB and a Rust app using about 19 MB on macOS, but the size, memory and CPU differences against Qt Widgets or Qt Quick can only be quantified by measuring the same features on the same platform. For a Qt Widgets workspace, map dock widgets to Dock and test saved layouts and panel state; existing Qt widget code still needs an integration or rewrite. **The challenge: Professional Desktop. Native Mobile. Real HTML Web. Apache 2.0.** ## Challenging Slint: beyond lightweight, who carries a complete cross-platform product? **Slint provides its own declarative language and renderer**, aimed at desktop and embedded devices and usable from Rust, C++, JavaScript or Python. Both value native performance; NSH's path is each platform's own UI and interaction, HTML on the web, TSX and Rust as app languages instead of a separate markup language, and phones as first-class targets. Slint's dedicated language is not a flaw: it makes the UI analyzable and optimizable, and for dashboards, device control panels and resource-constrained devices Slint is competitive. The difference shows when moving from building a screen to shipping a complete application: - **Depth of professional components.** Picture a cross-platform code-review tool: a draggable multi-column Dock, a diff of tens of thousands of lines, an editor with syntax highlighting and undo history, keyboard movement between tables and panels, multiple windows and system menus. NSH provides Dock, DiffView, Editor, RichEditor and DataTable directly; Slint has standard widgets, lists and models, and the fair comparison is how much editor, table, docking and desktop interaction work remains to be built. - **Native interaction on phones.** Slint's mobile UI is drawn by its own renderer, so input methods, text selection, touch gestures, system accessibility and platform conventions are the framework's to keep up with. NSH builds on UIKit and Android views on iOS and Android, which everyday apps such as chat, forms and document editing benefit from directly. - **The web is HTML, not a canvas.** Slint's web path is WebAssembly with its own rendering; NSH's web build outputs HTML elements and CSS, so the DOM, semantic structure, native input, text selection and web APIs all take part. - **Layout model.** NSH offers Flexbox, Grid, percentages, responsive state and Tailwind-style styling, so teams fluent in web layout can reuse their design and layout thinking. Slint's layouts and property bindings are mature too; they just do not aim at CSS layout. On embedded and very low-resource devices Slint keeps its edge; NSH's main ground is applications that need rich interaction and delivery to many platforms. For a table-heavy tool, compare the existing table with DataTable using the same model and check paging, column pinning and keyboard selection before porting custom cells. **The challenge: From lightweight UI to a complete application platform: professional desktop components, native mobile interaction, real HTML on the web, and one layout and development model.** ## Summary: one row per framework | Framework | Its structural limit | What NSH does instead | |---|---|---| | Electron | A browser and Node.js in every app; desktop only | Platform views, no browser; ~19 MB Rust app; phones and web from the same code | | Tauri | A different web engine per OS and version | Platform views, the same on every supported OS; TSX and Rust in one process | | React Native | JS thread and reconciliation on every update; desktop and web as separate projects | Rust core with fine-grained signals; six platforms in one framework and release | | Flutter | Self-drawn text and input; costly native views; canvas-like web | The system's text, input and accessibility; native views in the tree; HTML web | | GPUI | Desktop only, pre-1.0, editor-driven; text, focus and accessibility built by hand | Same Rust model on phones, the web and the terminal; embeds in GPUI apps | | Qt | Centered on desktop and embedded; licensing and runtime distribution need case-by-case review | Native phones and HTML web; Apache-2.0; one `nsh` toolchain | | Slint | Professional app components left to build; phones and web are drawn | Built-in professional components; native phone views; HTML on the web | ## One framework, more of the product Each mainstream framework proved something important: - **Electron**: a web developer experience can greatly lower the bar for desktop apps. - **Tauri**: Rust plus the system web view can cut Electron's runtime cost. - **React Native**: TSX/JavaScript and native UI can work together. - **Flutter**: one rendering system can give highly consistent visuals. - **GPUI**: Rust and the GPU can build complex, high-performance desktop apps. - **Qt**: professional desktop apps can have a deeply mature component and engineering system. - **Slint**: lightweight declarative UI can cover embedded and resource-constrained devices. But real product requirements do not arrive along framework boundaries. A typical product meeting produces a list like this: - macOS, Windows and Linux, and iOS and Android, and the web, and even the terminal. - One codebase, sharing as much of the components, layout, business logic and tooling as possible. - Native UI, not the whole app wrapped as a web page. - A TSX and CSS-style developer experience, and Rust's performance and system access. - Low CPU, low GPU work, low power, fast start-up and a small package. - Professional desktop Dock, tables, editors, complex layouts and multiple windows, and natural touch, input methods, focus and accessibility on phones. - Rust extensions for file indexing, audio and video processing, heavy computation and OS APIs. - Embedding into existing apps, and dynamic UI that is signed, authorized and revocable. NSH aims to stop these needs forcing a team to maintain several incompatible UI frameworks at once. It does not stitch existing frameworks together; on one Rust core it organizes native UI, a web-style developer experience, fine-grained retained mode, professional components, cross-platform backends and module extensions into one application system: | You want | How NSH does it | |---|---| | Professional desktop | macOS, Windows, Linux; multiple windows, Dock, editors, tables | | Native mobile | UIKit on iOS, Android views | | A real web build | HTML elements, CSS, the browser DOM and web APIs | | Terminal | A [TUI](https://nsh.dev/versions/v0.7.1/docs/tui.md) backend | | One codebase | Shared components, layout, reactive model and business logic | | A web-style developer experience | TSX, Flexbox, Grid, [Tailwind](https://nsh.dev/versions/v0.7.1/docs/tailwind.md)-style styling | | Rust performance | Rust core, pure Rust apps, [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md) modules | | Low resource use | Retained mode, fine-grained updates, no Chromium for native UI | | Full native interaction | System views, input, focus and accessibility reused where possible | | A simpler toolchain | One `nsh` CLI, an Apache-2.0 core | | UI delivered after release | Signed packages, capability grants, sandboxing and revocation (subject to platform and app store rules) | These are not independent wish-list items; a real product can face all of them at once. **Build once, native everywhere.** ## Evaluating it: start with a pilot No rewrite is needed to find out. An NSH app can ship on its own or embed as one view in an existing iOS, Android or desktop app ([Embedding](https://nsh.dev/versions/v0.7.1/docs/embedding.md)), so start with one screen: 1. **Pick the scenario that matters most to you**: live data and charts, a rich-text or AI chat screen, a module you need to deliver after release, or one module of a desktop client. 2. **Build it in NSH alongside the current one**: screens in TSX to begin with, key logic and computation in Rust. 3. **Compare with your own data**: start time and memory; CPU and frame rate under frequent updates; scrolling of long content and whether selection and input methods feel natural; whether menus, windows and text input are consistent across platforms; and, for delivered UI, signature checks, capability limits and rollback. `nsh`'s trace and the methods in the [performance report](https://nsh.dev/versions/v0.7.1/docs/performance-report.md) apply directly to these comparisons. ## UI delivered after release An app that wants UI it did not ship with — answers generated by a model, features from partners or other teams, screens that change without a release — has a handful of established options, on phones and desktops alike. They differ in what draws the UI, what the delivered code may do, and how much of the app has to change to host them. NSH is designed for custom UI. The app styles its components and can use system materials such as Liquid Glass on supported platforms. Text editing, input methods and selection follow platform conventions. | Capability | NSH | Web view | Server-driven UI | Mini-programs | OTA updates | |---|---|---|---|---|---| | Drawn by | Platform UI | Browser engine | The app's views | Web engine + layer | Framework renderer | | Native interaction behavior | | | | | | | Own state, logic and layout | | | | | | | Host's native components | | Bridge | | | | | Sandbox the host configures | | Same-origin | Schema | | | | Signed, revocable packages | | | | | | | Fit for AI-generated UI | | Web pages | | | | | Cost to the host app | One view and a library | A browser engine per view | A renderer per component | A container SDK | The whole app in the framework | - **Web view (H5).** A page in a browser engine: anything HTML can express, with the browser's look and a hand-written bridge to native code. - **Server-driven UI.** JSON that recombines the components and actions the app already ships: easy to generate, with no local state or logic beyond what the schema provides. - **Mini-program containers.** A platform-specific framework and API on a web engine, inside a large container SDK. - **Over-the-air updates** (React Native with a code-push service, for example). The whole framework, but updates are trusted app code, and the app has to be written in that framework. - **NSH.** A TSX module with its own state, logic, animation and layout, rendered with the platform's own UI, that can use the host's registered native views. It arrives as a signed package the app verifies, runs in its own VM with memory, call-time and node limits, and reaches only the network hosts, web pages and system settings the host grants ([Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). The host adds one view where the module appears ([Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md#embed-in-a-native-app)), and the same bundle runs on every platform. This is the reason NSH exists next to [GPUI Shell](https://nsh.dev/versions/v0.7.1/docs.md#native-shell-and-gpui-shell). ## When another option fits better - The screen is dominated by sustained, dense updates of thousands of views — a market-data terminal streaming tens of thousands of quotes a second, a custom visualization redrawn every frame: GPUI Fast's retained GPU rendering uses a fraction of the CPU (see the GPUI section above). - The app must look pixel-identical on every platform: a framework that draws everything itself, such as Flutter or Slint, gives that by design. - You need a large ecosystem of third-party packages today: React Native, Flutter and Qt have years of them. - The UI is a document or an existing web page: a web view shows it as it is. - The set of screens is fixed and small, and only content and order change: server-driven UI needs no runtime at all. ## See also - [Introduction](https://nsh.dev/versions/v0.7.1/docs.md): what NSH is, and what native means in it. - [Architecture](https://nsh.dev/versions/v0.7.1/docs/architecture.md): what runs where inside NSH. - [Performance](https://nsh.dev/versions/v0.7.1/docs/performance.md): the rules NSH follows, and how to measure an app. Source: https://nsh.dev/versions/v0.7.1/docs/comparison --- # Installation Everything NSH does goes through one command, `nsh`. It builds apps written in TSX or Rust, runs them on every platform, serves TSX to development hosts with hot updates, and packages installable apps. You can use it from a prebuilt distribution or build it from a checkout of the repository. TSX apps need `nsh` alone. Apps with Rust in them (their own crates in `ext/`, a Rust nshm, or an app written in Rust) also need a Rust toolchain ([below](#for-apps-written-in-rust)). On top of that, each platform needs its own tools: | Platform | Develop and package on | Needs | |---|---|---| | iOS | macOS | Xcode and an iOS simulator runtime | | Android | macOS, Windows or Linux | The Android SDK and a JDK; an emulator or a device | | macOS | macOS | Xcode's command line tools; apps run on macOS 14+ | | Windows | Windows | Windows 10 1809+; the WebView2 Runtime for web views | | Linux | Linux | GTK 4.14+ (and its development packages to build the runtime) | | [GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md) (embedding in GPUI apps) | macOS, Windows or Linux | A GPU (Metal, DirectX or Vulkan); on Linux, Wayland or X11 | The AppKit host is the default on macOS. Mac Catalyst (`--target catalyst`), a development tool for Catalyst-specific work, needs Xcode like iOS. Details are under [Platform tools](#platform-tools). ## Installing a release Each [GitHub release](https://github.com/longbridge/nsh/releases) carries the prebuilt distribution (below) for macOS (Apple silicon and Intel), Linux (x86_64 and arm64) and Windows (x86_64 and arm64). Every way of installing it puts the same `nsh` command on your `PATH`. **macOS and Linux**, with the install script: ```sh curl -fsSL https://nsh.dev/install.sh | sh ``` It installs the distribution to `~/.nsh` and links `~/.local/bin/nsh` to it; running it again updates it. `NSH_VERSION=v0.1.0` pins a release, `NSH_INSTALL_DIR` picks another directory. **Windows**, in PowerShell: ```powershell irm https://nsh.dev/install.ps1 | iex ``` It installs to `%LOCALAPPDATA%\nsh` and adds its `bin` to your user `PATH` (open a new terminal afterwards). `$env:NSH_VERSION` and `$env:NSH_INSTALL_DIR` work as above. **Homebrew** (Apple silicon Macs and x86_64 Linux): ```sh brew install longbridge/tap/nsh ``` **Scoop** (x86_64 Windows): ```powershell scoop install https://github.com/longbridge/nsh/releases/latest/download/nsh.json ``` **mise** (all three): ```sh mise use -g github:longbridge/nsh ``` The archives (`nsh-macos-arm64.tar.gz`, `nsh-macos-x86_64.tar.gz`, `nsh-linux-x86_64.tar.gz`, `nsh-linux-arm64.tar.gz`, `nsh-windows-x86_64.zip`, `nsh-windows-arm64.zip`, each with a `.sha256`) carry no version in their names, so `https://github.com/longbridge/nsh/releases/latest/download/` always fetches the latest. Each holds the CLI and the runtime of its own platform; the runtimes of the other platforms are [components](#components), added when they are first needed. The embedding SDKs are released alone, for native apps that embed NSH: `nsh-embed-ios.zip` and `nsh-embed-android.zip`. > [!NOTE] > The binaries are not signed yet. macOS quarantines files downloaded by a browser; the install script, Homebrew and mise download with `curl` and are not affected, otherwise run `xattr -dr com.apple.quarantine `. The Linux runtime needs glibc 2.39 and GTK 4.14 or newer (Ubuntu 24.04 and later). Homebrew and Scoop install the Apple silicon, x86_64 Linux and x86_64 Windows builds; use the install script on the others. ## Components The runtimes for platforms other than the one you develop on are components of the release, as `rustup component add` installs a toolchain's parts. The first command that needs one, such as `nsh run --target android` or `nsh package --target web`, downloads it from the release of your `nsh`, checks its SHA-256 and installs it next to the CLI. `nsh component` manages them ahead of time: `nsh component list` shows the components for this machine, installed or not; `nsh component add` installs them ahead of time, e.g. before going offline; `nsh component remove` frees the space again: ```sh nsh component list nsh component add android web nsh component remove gpui ``` | Component | Holds | Published for | |---|---|---| | `android` | The Android runtime (`--target android`) | Every platform | | `android-symbols` | The Android runtime's symbols, for crash reports and `ndk-stack` | Every platform | | `ios` | The iOS and Mac Catalyst runtimes (`--target ios`, `catalyst`) | macOS on Apple silicon | | `web` | The web runtimes (`--target web`) | Every platform | | `gpui` | The [GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md) development host (`--target gpui`) | Every platform, built for it | | `tui` | The terminal development host (`--target tui`) | Every platform, built for it | A component always comes from the same build as the CLI. `nsh update` adds the installed components again from the release it updates to. A nightly build's components are replaced every night, so a nightly `nsh` from an earlier night asks you to run `nsh update` first. ## For apps written in Rust Install Rust through [rustup](https://rustup.rs) when the app has Rust in it: a crate of its own in `ext/`, a Rust nshm, or a whole app in Rust. `nsh` builds the app's runner for each target with Cargo, from those crates and NSH's crates on crates.io at the CLI's version, so add the Rust targets of the platforms you run on. For the iOS simulator, iOS devices and Mac Catalyst: ```sh rustup target add aarch64-apple-ios-sim aarch64-apple-ios aarch64-apple-ios-macabi ``` For Android (with the SDK's NDK): ```sh rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android ``` For the web: ```sh rustup target add wasm32-unknown-unknown ``` We recommend building with [huacnlee/cargo](https://github.com/huacnlee/cargo), a fork of Cargo optimized by [huacnlee](https://github.com/huacnlee) so Rust build artifacts never fill the disk: every project and Git worktree shares one build directory that stays under a size limit on its own. With 50 worktrees it takes about 90% less disk space than stock Cargo, and a 512 GB disk is plenty. It is a drop-in replacement for `~/.cargo/bin/cargo` with nothing to configure: On macOS and Linux: ```sh curl -fsSL https://huacnlee.github.io/cargo/install.sh | sh ``` On Windows, in PowerShell: ```powershell irm https://huacnlee.github.io/cargo/install.ps1 | iex ``` The desktops build for the machine you are on. `cargo run` in a Rust app's directory starts it on the desktop backend directly, which builds with the backend's development libraries ([Platform tools](#platform-tools)). Android builds also use an **NDK** from the SDK, as [building the Android runtime](#building-the-android-runtime) does. ## The prebuilt distribution The distribution is a directory, `dist/nsh`, with the CLI and the prebuilt native runtimes it packages apps with: ```sh dist/nsh/bin/nsh # the CLI dist/nsh/runtime/ios/iphoneos/nsh-ios-app # runs packaged apps on iOS devices dist/nsh/runtime/ios/iphonesimulator/{nsh-ios-app,nsh-ios-host} dist/nsh/runtime/ios/maccatalyst/nsh-ios-host # the Mac Catalyst development host dist/nsh/runtime/android/{release,dev}/ # classes.dex, lib//libnsh.so, symbols//libnsh.so dist/nsh/runtime/macos/{nsh-macos-host,nsh-macos-app} # the macOS (AppKit) development host and release runner dist/nsh/runtime/linux/{nsh-linux-host,nsh-linux-app} # the Linux development host and release runner dist/nsh/runtime/windows/{nsh-windows-host,nsh-windows-app}.exe # the Windows development host and release runner dist/nsh/runtime/gpui/nsh-gpui-host[.exe] # the GPUI development host, for this OS dist/nsh/runtime/tui/nsh-tui-host[.exe] # the terminal development host (nsh run --target tui) dist/nsh/runtime/web/{nsh.wasm,nsh-dev.wasm,nsh.js} # the web runtimes (nsh package / run --target web) dist/nsh/embed/ios/{NativeShell,NativeShellDev}.xcframework # embedding in iOS apps dist/nsh/embed/android/{nsh,nsh-dev}.aar # embedding in Android apps ``` Put `dist/nsh/bin` on your `PATH` (or call `dist/nsh/bin/nsh` directly) and keep the directory together: `nsh` finds the runtimes next to itself, in `bin/../runtime` (through a symlink to it, as the installers make, too). The release archives are made from it: each platform's archive keeps `bin` and its own runtime, the other runtimes become [components](#components) and `embed` the SDK archives. ```sh export PATH="$PWD/dist/nsh/bin:$PATH" nsh --version ``` The distribution is made with `cargo xtask dist` in a checkout (below). The `nsh` binary it contains is built for that machine. On a Mac with Xcode it includes the iOS and macOS runtimes (Apple Silicon); on Linux it includes the Linux runtime instead, built for that machine; on Windows the Windows runtime, with `bin\nsh.exe`. Each also includes the [GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md) and terminal development hosts, built for that machine. All include the Android runtime (on Windows only when the Android SDK is found). ## Installing the nightly build Every night that `main` changes, it is built and published as the [nightly release](https://github.com/longbridge/nsh/releases/tag/nightly), with the same archives as a release. **macOS and Linux**: ```sh curl -fsSL https://nsh.dev/install.sh | sh -s -- --nightly ``` **Windows**, in PowerShell (`NSH_VERSION` names the release to install, here `nightly`): ```powershell $env:NSH_VERSION = 'nightly'; irm https://nsh.dev/install.ps1 | iex ``` `nsh -V` then shows the commit and the channel, such as `nsh 0.4.0 (abcdef0 nightly)`. Apps written in Rust build their runner with NSH's crates on crates.io at the CLI's version, the last release's; for those apps, use a release or the source. ## Updating `nsh update` updates an installed `nsh` to the latest build of its channel: the latest release, or the latest nightly for a nightly build. Naming a channel switches to it, as `rustup update nightly` does: `nsh update nightly` moves to the nightly build of `main`, `nsh update stable` goes back to the latest release. ```sh nsh update ``` It downloads the same archive as the install scripts, checks its SHA-256, replaces the whole distribution directory and adds the components that were installed again. Homebrew, Scoop and mise update the `nsh` they installed themselves (`brew upgrade nsh`, `scoop update nsh`, `mise upgrade`). ## Building from source With Git, Rust and the [platform tools](#platform-tools), on macOS and Linux: ```sh curl -fsSL https://nsh.dev/install.sh | sh -s -- --source ``` It keeps the checkout in `~/.nsh/source`, builds the CLI and links it into `~/.local/bin`; run it again to update. To work on NSH itself, clone the repository and build the CLI there; it builds the desktop and web runtimes it runs on when they are missing: The CLI is then `./target/debug/nsh`: ```sh git clone https://github.com/longbridge/nsh.git && cd nsh cargo build -p nsh-cli ``` The commands for the iOS and Android runtimes and the release runners are in the repository's [AGENTS.md](https://github.com/longbridge/nsh/blob/main/AGENTS.md#commands). ## Platform tools ### iOS and Mac Catalyst - **Xcode** (with its command line tools). `nsh run` uses `xcrun simctl` to boot simulators and install the development host; `nsh package` uses `actool` for app icons and `codesign` for signing. - An iOS simulator runtime. If none is installed, install one with `xcodebuild -downloadPlatform iOS`. - Apps target iOS 15.0 and later. ### Android - **The Android SDK**, found through `ANDROID_HOME`, `ANDROID_SDK_ROOT` or Android Studio's default place (`~/Library/Android/sdk`, `%LOCALAPPDATA%\Android\Sdk` on Windows), with: - `platforms;android-35` and a recent `build-tools` (NSH uses `aapt2`, `zipalign` and `apksigner` from it, no Gradle); - `platform-tools` (`adb`). - **A JDK** (`keytool` creates the debug keystore in `~/.android/debug.keystore` the first time you package, `apksigner` needs Java). - A running emulator or a device connected over `adb`. Apps need Android 8 (API 26) or later. ```sh sdkmanager "platforms;android-35" "build-tools;35.0.1" "platform-tools" ``` ### macOS - **Xcode's command line tools** (`xcode-select --install`): the SDK and clang to build the runtime, `codesign` and `sips` to package apps. - Apps need macOS 14 or later. See [macOS](https://nsh.dev/versions/v0.7.1/docs/macos.md). ### Linux - **GTK 4.14** or later, with their development packages and clang to build the runtime: `libgtk-4-dev clang` (Debian, Ubuntu 24.04 or later), `gtk4 clang` (Arch), `gtk4-devel clang` (Fedora). - **WebKitGTK 6.0** (2.42 or later) for web views and download decisions: `libwebkitgtk-6.0-dev` (Debian, Ubuntu), `webkitgtk-6.0` (Arch), `webkitgtk6.0-devel` (Fedora) to build the runtime; apps then need it where they run. Without it, `cargo xtask dist` builds the runtime with placeholders for web views. - **GStreamer** 1.14 or later, for video and sound, where apps run: its base plug-ins and the plug-ins for the video and audio formats apps play. Building needs nothing of it; without it an app still starts, and loading a sound fails naming the missing library. See [Linux](https://nsh.dev/versions/v0.7.1/docs/linux.md). ### Windows - **Windows 10 1809** or later, or Windows 11. The WebView2 Runtime (part of Windows 11, installed with Edge on Windows 10) for web views. - To build the runtime: **Visual Studio Build Tools** with the "Desktop development with C++" workload and the Windows SDK, and **LLVM** (libclang, for QuickJS' bindings; found in `C:\Program Files\LLVM`, else set `LIBCLANG_PATH`). See [Windows](https://nsh.dev/versions/v0.7.1/docs/windows.md). ### Building the Android runtime Building the Android runtime from a checkout (`cargo xtask android`) additionally needs an **NDK** from the SDK (`ndk;`; set `ANDROID_NDK_HOME` if the newest one installed is incomplete) and `javac`. The embedding libraries alone: `cargo xtask android-embed` (`dist/nsh/embed/android/{nsh,nsh-dev}.aar`). ## What works where | Command | macOS | Linux | Windows | |---|---|---|---| | `nsh init`, `nsh build`, `nsh test`, `nsh dev`, `nsh check` | Yes | Yes | Yes | | `nsh run --target macos`, `nsh package --target macos` | Yes | No | No | | `nsh run --target linux` (the default on Linux), `nsh package --target linux` | No | Yes | No | | `nsh run --target windows` (the default on Windows), `nsh package --target windows` | No | No | Yes | | `nsh run --target gpui` (the backend GPUI apps embed) | Yes | Yes | Yes | | `nsh run --target ios`, `nsh package --target ios` / `ios-simulator` | Yes, with Xcode | No | No | | `nsh run --target android`, `nsh package --target android` | Yes | Yes, from a checkout | Yes, with the Android runtime | | `nsh keygen`, `certify`, `publish`, `verify`, `revoke` | Yes | Yes | Yes | | `nsh run --target catalyst` (Mac Catalyst) | Yes | No | No | On Linux, build the CLI and the Android runtime from a checkout (`cargo build -p nsh-cli` and `cargo xtask android --dev`); the NDK's Linux toolchain is used automatically. On Windows the NDK's Windows toolchain is used the same way, and `cargo xtask dist` includes the Android runtime when it finds the Android SDK. ## Editor setup A Rust app is a Cargo project: rust-analyzer (VS Code, Zed, Neovim, RustRover) checks it and completes NSH's API, with its doc comments, as for any crate. For TSX, NSH needs no NPM. `nsh init` writes a `tsconfig.json` and the type declarations of everything NSH provides into `.nsh/types`, and every command that builds the app keeps them up to date. Any editor that uses the TypeScript language server (VS Code, Zed, Neovim, WebStorm) type-checks the app with them. See [Project structure](https://nsh.dev/versions/v0.7.1/docs/project-structure.md#tsconfigjson-and-nshtypes). ## Next steps Continue with [Getting started](https://nsh.dev/versions/v0.7.1/docs/getting-started.md) to create an app and run it. Source: https://nsh.dev/versions/v0.7.1/docs/installation --- # Getting started This guide creates an NSH app, runs it on the platforms you target, and ships it. NSH apps are written in TSX, with hot updates while you develop; the app's own code runs on QuickJS, and the engine, layout, rendering and modules under it are native. Where an app needs native speed, system access or a crate, it adds Rust through [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md), and an app can also be Rust from start to end, compiled with no JavaScript VM. The guide follows a TSX app, with the same app in Rust beside it. It assumes `nsh` is installed and on your `PATH` ([Installation](https://nsh.dev/versions/v0.7.1/docs/installation.md)); in a checkout, use `./target/debug/nsh` instead. > [!TIP] > No app project at hand? The first two sections need none: `nsh run` shows the app in a window on your computer, in > the iOS simulator, on an Android device or in the browser. You can stop there, or [package it as a standalone > app](#or-ship-it-as-a-standalone-app). ## Create an app On a terminal, `nsh init` asks what the app is written in: `ts` (the default), `rust` or `mixed` (TSX extended with Rust in `ext/`). `--template` chooses without asking. ### In TSX ```sh nsh init my-app --template ts ``` A TSX app is one or more `.tsx` files with an entry: what `nsh run` runs, and what a host app loads as a module. | File | What it is | |---|---| | `App.tsx` | The entry module: renders the app with `mount` | | `App.test.tsx` | Its test (`nsh test`) | | `nsh.json` | The app's name, id, version and build number ([Project structure](https://nsh.dev/versions/v0.7.1/docs/project-structure.md#nshjson)) | | `tsconfig.json` | Extends `.nsh/tsconfig.json`, NSH's TypeScript settings, which resolve `nsh` to the declarations in `.nsh/types` | | `.gitignore` | Ignores `.nsh/` and `target/` | | `.nsh/types/` | Generated declarations of every NSH module, for your editor | ### In Rust ```sh nsh init my-app --template rust ``` `nsh init` creates the directory and writes a Cargo project: | File | What it is | |---|---| | `src/lib.rs` | The app: its root component, state and handlers | | `src/main.rs` | Mounts the same root on macOS, Windows or Linux for `cargo run` | | `Cargo.toml` | The crate, depending on `nsh-core` and `nsh-base` at the CLI's version | | `nsh.json` | The app's name, id, version and build number, its crate (`"rust": "."`) and root component (`"root": "App"`) ([Project structure](https://nsh.dev/versions/v0.7.1/docs/project-structure.md#nshjson)) | | `App.test.tsx` | The root's test, in TypeScript (`nsh test`), with `tsconfig.json` and `.nsh/types` for your editor | | `README.md` | How to run, test and package the app, and how to add a TSX entry later | | `.gitignore` | Ignores `.nsh/` and `target/` | Rust development needs a Rust toolchain ([rustup](https://rustup.rs), and we recommend [huacnlee/cargo](https://github.com/huacnlee/cargo) for building); the `nsh` commands build the app's runners from NSH's crates on crates.io, at the CLI's version. For a TSX app, files that already exist are kept, so you can run it in a directory that has some of them; a Rust app is created in a new directory. For both, the display name defaults to the directory's name; pass `--name "My App"` to choose another. The id becomes `com.example.`: change it in `nsh.json` before you ship. ### TSX extended with Rust ```sh nsh init my-app --template mixed ``` The TSX app, plus an nshm crate of its own in `ext/-native/`, whose component, module and class `App.tsx` imports: the place for the parts of the app that are better in Rust ([An app's own Rust: ext/](https://nsh.dev/versions/v0.7.1/docs/nshm.md#an-apps-own-rust-ext)). A TSX app made with `--template ts` adds the same later with `nsh add`. ### The root component The two templates make the same app, a counter: ```tsx // App.tsx import { mount, signal, Text, View } from "nsh"; import { Window } from "nsh/desktop"; function App() { const count = signal(0); return ( {count()} count.update((c) => c + 1)} role="button" class="rounded-(--radius) bg-primary px-5 py-3 active:bg-primary/90" > Tap ); } // The desktops show the app in windows it declares; `App` is the content of // the first one. Off the desktops it is the app's screen. mount(() => {App}); ``` ```rust // src/lib.rs use nsh_base::theme; use nsh_core::{element::desktop::window as app_window, prelude::*}; /// The crate's UI set: what a TSX entry may import from `my-app/native`. #[native_module("my-app/native")] fn native(registry: &mut Registry) { registry.register::(); } /// The application's root component. #[component] pub fn App() -> impl IntoElement { let count = signal(0_u32); app_window().id("main").content(move || { view() .flex_1() .bg(move || theme().background) .text_color(move || theme().foreground) .child( view() .flex_1() .p_safe_area() .child( view() .flex_1() .items_center() .justify_center() .gap_4() .child(text(move || format!("Count: {}", count.get())).text_size(px(28.0))) .child( view() .px_5() .py_3() .rounded(px(10.0)) .bg(move || theme().primary) .active(|s| s.opacity(0.6)) .on_press(move || count.update(|value| *value += 1)) .child( text("Tap") .text_size(px(17.0)) .text_color(move || theme().primary_foreground), ), ), ), ) }) } ``` In TSX: - **`import { mount, signal, Text, View } from "nsh"`**: `nsh` is the core module: signals, `mount`, the other reactive primitives, and the host elements. It is served by the native runtime, not bundled. **`nsh/base`** has the base components. - **`function App()`** is a component that runs **once**. **`{count()}`** reads the signal inside JSX: the compiler sees a call and makes this text follow the signal. - **``** is a native view that reacts to presses; `active:` classes are its style while pressed. `View`, `Text`, `Image`, `Scroll` and the other [host elements](https://nsh.dev/versions/v0.7.1/elements.md) are imported from `nsh` (`Input` from `nsh/base`); only `If` and `Each` need no import. - **`class`** takes [Tailwind](https://nsh.dev/versions/v0.7.1/docs/tailwind.md) classes; `style={{ … }}` takes an object of camelCase style properties, with numbers in points. `bg-background`, `bg-primary`, `text-primary-foreground` and `rounded-(--radius)` name the tokens of the app's theme ([Theme tokens](https://nsh.dev/versions/v0.7.1/docs/tailwind.md#theme-tokens)): they follow dark mode by themselves, and `"theme"` in `nsh.json` restyles them. Layout is flexbox, and children stack in a column by default ([Layout](https://nsh.dev/versions/v0.7.1/docs/layout.md)). - **`mount(App)`** renders the app root; on the desktops the root declares its windows with ``. In Rust: - **`use nsh_core::prelude::*`** brings the primitives (`view()`, `text()`, `scroll()`, `input()`, `image()`, ...), [signals](https://nsh.dev/versions/v0.7.1/docs/reactivity.md) and the typed style methods (`.p_safe_area()` pads a view by the [safe area](https://nsh.dev/versions/v0.7.1/elements/safe-area.md)); **`nsh_base`** has the unstyled base components (`button()`, the keyboard, dialogs) and `theme()`, the colors and radii the app's components draw with ([Theme](https://nsh.dev/versions/v0.7.1/docs/rust.md#theme)). - **`#[component] pub fn App()`** is a component: a function that runs **once** and returns its elements. `nsh.json`'s `"root": "App"` names it, and `nsh run` mounts it. `signal(0_u32)` makes a value that changes over time. - **`text(move || format!(…, count.get()))`** binds the text to the signal: when `count` changes, NSH runs this closure again and updates this one text, nothing else. Styles take closures the same way: `.bg(move || theme().primary)` follows the theme into dark mode. - **`.on_press(..)`** makes the view answer presses; `.active(|s| s.opacity(0.6))` is its style while pressed, applied natively. The button is the app's own: NSH provides the primitives and the capabilities, and the app draws its UI from them. - **`.px_5()`, `.rounded(px(10.0))`, `.gap_4()`** are typed style methods named as Tailwind's utilities are, in points (`px`). - **`#[native_module("my-app/native")]`** names what a TSX entry may import from the crate, for when you add TSX screens on top ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md#extending-a-rust-app-with-tsx)). > [!IMPORTANT] > Text shows in a text element: `` in TSX, `text(..)` in Rust. In TSX, text written straight in a `` > (`Hello`) is a build error that points at it, and a string an expression puts there > (`{name}`) is reported in the log. ## Develop it ### Run it `nsh run` builds the app, launches it and rebuilds while you edit; the app's logs appear in the terminal. Give it the app's directory: it runs a TSX app's `App.tsx` (`nsh run my-app/App.tsx` names another entry), or a Rust app's root. For a TSX app, `nsh run` starts a dev server and a development host that loads the app from it, and patches the running app on every save; Rust in `ext/` is built into the host, and built again when it changes. For a Rust app, `nsh run` builds the app's own runner for the target, with your crate and the root mounted and no QuickJS, and starts it; a change to the Rust code builds it again and restarts the app. `cargo run` in the app's directory starts the same root straight on the desktop backend. Without `--target`, `nsh run` uses the machine you are on: an AppKit window on macOS, a Win32 window on Windows and a GTK window on Linux. Pick another platform with `--target`: | Target | Command | Runs from | |---|---|---| | iOS simulator | `nsh run my-app --target ios` | macOS with Xcode | | Android | `nsh run my-app --target android` | macOS, Windows, Linux | | macOS (AppKit) | `nsh run my-app` | macOS (the default) | | Windows | `nsh run my-app` | Windows (the default) | | Linux (GTK 4) | `nsh run my-app` | Linux (the default) | | Web | `nsh run my-app --target web` | macOS, Windows, Linux | #### iOS simulator ```sh nsh run my-app --target ios nsh run my-app --target ios --device "iPhone 16 Pro" ``` `nsh` uses a booted simulator, or boots the newest iPhone if none is running, and installs the app (a Rust app's runner, or the development host) into it. `--device` picks a simulator by name or UDID. #### Android ```sh nsh run my-app --target android ``` Start an emulator or connect a device first (`adb devices` lists them). NSH uses the one `--device ` or `ANDROID_SERIAL` names, else the first one, and names the one it uses when several are connected. `nsh` installs the app on it: a Rust app's own `libnsh.so`, or a development host APK (rebuilt only when the runtime changes) whose dev server port is forwarded to the device with `adb reverse`, so it works over USB without a shared network. #### macOS (AppKit) ```sh nsh run my-app --target macos ``` The app opens as a desktop Mac app (AppKit, in a resizable window), with mouse, trackpad and keyboard input instead of touches. It needs macOS 14 or later; see [macOS](https://nsh.dev/versions/v0.7.1/docs/macos.md). #### Windows (default on Windows) ```sh nsh run my-app ``` The app opens in a desktop window (1200×800 points), with mouse, touchpad, touch and keyboard input. It needs Windows 10 1809 or later; see [Windows](https://nsh.dev/versions/v0.7.1/docs/windows.md). #### Linux (default on Linux) ```sh nsh run my-app ``` The app opens in a GTK window (390×844 points). It needs GTK 4.14 or later; see [Linux](https://nsh.dev/versions/v0.7.1/docs/linux.md). #### Web ```sh nsh run my-app --target web ``` `nsh` prints the page's address; open it in a browser. A Rust app runs as WebAssembly with your crate, and the open page loads the new build by itself after a change; see [Web](https://nsh.dev/versions/v0.7.1/docs/web.md). ### Edit it Leave `nsh run` running and change the button's label: ```tsx Add one ``` ```rust text("Add one") .text_size(px(17.0)) .text_color(move || theme().primary_foreground) ``` Save. A TSX app gets a hot update: the CLI rebuilds and sends a patch, and the host runs the changed module again and renders again only the components whose code changed. Here that is `App`, which owns the `count` signal, so the count starts over. A Rust app is built again and restarts with the new label; the count starts over too. Pieces of UI move into components of their own, or plain functions that return elements: ```tsx function TapButton(props: { onPress: () => void }) { return ( Tap ); } // In App: count.update((c) => c + 1)} /> ``` ```rust /// The app's button: a view that answers presses. fn tap_button(on_press: impl Fn() + 'static) -> impl IntoElement { view() .p_3() .rounded(px(10.0)) .bg(move || theme().primary) .active(|s| s.opacity(0.6)) .on_press(on_press) .child(text("Tap").text_size(px(17.0)).text_color(move || theme().primary_foreground)) } // In App: .child(tap_button(move || count.update(|value| *value += 1))) ``` In TSX, state survives when you edit a component that does not own it: tap a few times, then change `TapButton`'s color, and the button updates while the count stays. Hot replacement works per top-level component: a function with a capitalized name whose body contains JSX. A component renders again when its own code changes, or when the module's code outside components changes (a constant it uses, a helper). If an edit cannot be applied in place (for example, it imports an NSH module the running app did not import yet, or changes `nsh.json`'s capabilities), the host reloads the whole app. #### Errors A Rust compile error is printed in the terminal with cargo's output, and `nsh run` builds again with the next save. A TSX build error is printed in the terminal and shown on the device as a red overlay with the file, line and column; the app keeps running the last good build. The overlay disappears with the next successful build (tap it to dismiss it earlier). An exception thrown at run time is shown the same way, with its stack mapped back to your `.tsx` source. ### Development tools #### Mac Catalyst ```sh nsh run my-app --target catalyst ``` The app opens with the iOS (UIKit) backend in an iPhone-sized window (390×844 points) on your Mac. Use it only when you need it: to check behavior specific to Catalyst, or an app that embeds NSH in a Mac Catalyst app. For the Mac app, use the default `macos`; to see an app as a phone shows it, use `--target ios`. ## Host it in your app A native app shows NSH in a view of its own: `NshAppView` (a `UIView`) on iOS, `NshView` (an Android `View`) on Android, `AppView` on macOS, Windows, Linux and in GPUI apps. Place it like any other view, on any screen, as many times as you need. A Rust root is part of the app's build: the app links your crate and mounts the root with `AppSource::Rust` on the `AppView` of macOS, Windows, Linux, GPUI and iOS ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md#an-app-written-in-rust)). A TSX app is a module the view loads: during development from the dev server, in a release from a built bundle or a downloaded, signed package. The sections below load TSX modules. ### iOS Link `NativeShellDev.xcframework` in Debug and `NativeShell.xcframework` in Release ([Embedding in iOS apps](https://nsh.dev/versions/v0.7.1/docs/ios.md)), then: ```swift import NativeShell let app = NshAppView() app.onError = { message in print("nsh error: \(message)") } view.addSubview(app) // and constrain it like any view #if DEBUG try app.connectDevServer(URL(string: "ws://127.0.0.1:8790/ws")!) // `nsh dev my-app` on your Mac #else try app.loadBundle(at: Bundle.main.url(forResource: "bundle", withExtension: "nshc", subdirectory: "nsh")!) #endif ``` `nsh dev my-app` serves the module to the app and pushes every save, as `nsh run` does with its own host. For the release build, `nsh build my-app --release --out MyApp/nsh` writes the bundle into a folder you add to the app's resources. ### Android Add `nsh-dev.aar` for debug builds and `nsh.aar` for release builds ([Embedding in Android apps](https://nsh.dev/versions/v0.7.1/docs/android.md)), then: ```kotlin val nsh = NshView(this) nsh.setErrorListener { message -> Log.e("nsh", message) } setContentView(nsh) // or add it to any layout if (BuildConfig.DEBUG) { nsh.connectDevServer("ws://127.0.0.1:8790/ws") // with `adb reverse tcp:8790 tcp:8790` } else { nsh.loadAssetBundle("nsh") // assets/nsh, from `nsh build my-app --release --out app/src/main/assets/nsh` } ``` ### macOS, Windows and Linux Desktop apps written in Rust embed NSH with `AppView`, from the `nsh-platform-macos`, `nsh-platform-windows`, `nsh-platform-linux` and `nsh-platform-gpui` crates: an `NSView`, a child window, a GTK widget or a GPUI view that mounts a Rust root or loads a built bundle. See [macOS](https://nsh.dev/versions/v0.7.1/docs/macos.md#embedding-in-a-mac-app), [Windows](https://nsh.dev/versions/v0.7.1/docs/windows.md#embedding-in-a-win32-app), [Linux](https://nsh.dev/versions/v0.7.1/docs/linux.md#embedding-in-a-gtk-app) and [GPUI](https://nsh.dev/versions/v0.7.1/docs/gpui.md), and [Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md#embed-in-a-native-app) for every host side by side. ### What the module may do On iOS and Android, the host decides before loading what a module may do: `grantCapabilities` sets the network hosts and other capabilities it may reach, and limits cap its memory, call time and node count ([Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). To give modules your own native views (a map, a chart, a design-system component), register them as [native components](https://nsh.dev/versions/v0.7.1/docs/native-components.md). ## Ship updates as signed packages A TSX module the app downloads after release comes as a signed package. Create a root key once and keep it offline, certify a release key with it, and publish: ```sh nsh keygen keys/root && nsh keygen keys/release nsh certify --root keys/root.secret --key keys/release.pub --apps 'com.example.*' -o keys/release.cert nsh publish my-app --key keys/release.secret --cert keys/release.cert --build 2 ``` The app trusts the root's public key and loads what it downloads; NSH verifies the signature, the certificate and the revocation list before running anything: ```swift let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] let trust = try NshTrust(stateDirectory: support.appendingPathComponent("nsh")) try trust.addRoot(rootPublicKey) // the contents of keys/root.pub let info = try await app.loadPackage(at: downloadedFile, trust: trust) ``` Android has the same flow with `NshTrust` and `NshPackage`. Hosting, delivery and revocation in detail: [Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md). ## Or ship it as a standalone app `nsh package` builds an installable app, TSX or Rust, with no Xcode project or Gradle build of your own: ```sh nsh package my-app --target ios-simulator --run nsh package my-app --target android nsh package my-app --target macos nsh package my-app --target linux nsh package my-app --target windows nsh package my-app --target web ``` A TSX app is packaged with the prebuilt runtime (or, with Rust in `ext/`, a runtime built with it); a Rust app with its own runner, built from your crate and NSH's crates, its root mounted. Options, signing and icons: [Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md). ## Try it in the terminal `nsh test` runs an app headless, with no device or window. Given a TSX app's entry or a Rust app's `nsh.json`, it opens the app, lets it run and prints what it mounts; with `--trace`, also the native view operations and the time of every commit ([Testing](https://nsh.dev/versions/v0.7.1/docs/testing-and-trace.md)): ```sh nsh test my-app/App.tsx --trace # a TSX app's entry nsh test my-app/nsh.json --trace # a Rust app's root ``` Given a directory, it runs the app's tests: each template's `App.test.tsx` opens the app, presses its button and checks what it shows (`nsh test my-app`). A Rust app's opens its root (`open(".")`); it can also be tested in `cargo test` with `nsh_testing::Headless` ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md#testing)). ## Next steps - [JSX and components](https://nsh.dev/versions/v0.7.1/docs/jsx-and-components.md) and [Reactivity](https://nsh.dev/versions/v0.7.1/docs/reactivity.md): components and signals, in TSX and Rust. - [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md): add Rust to a TSX app, in `ext/` or from crates.io, and use published nshm. - [Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md): apps written in Rust from start to end, their theme, and TSX on top of a Rust crate. - [Platforms](https://nsh.dev/versions/v0.7.1/docs/platforms.md): what each platform supports, and its own page ([iOS](https://nsh.dev/versions/v0.7.1/docs/ios.md), [Android](https://nsh.dev/versions/v0.7.1/docs/android.md), [macOS](https://nsh.dev/versions/v0.7.1/docs/macos.md), [Windows](https://nsh.dev/versions/v0.7.1/docs/windows.md), [Linux](https://nsh.dev/versions/v0.7.1/docs/linux.md), [Web](https://nsh.dev/versions/v0.7.1/docs/web.md), [TUI](https://nsh.dev/versions/v0.7.1/docs/tui.md)). - [Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md) and [Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md): delivery and what modules may do. - [Project structure](https://nsh.dev/versions/v0.7.1/docs/project-structure.md): what goes in `nsh.json`, assets, files. Source: https://nsh.dev/versions/v0.7.1/docs/getting-started --- # Project structure An NSH app is a directory with an `nsh.json` and its code: a TSX entry module, with Rust crates in `ext/` when it has any, or a Rust crate whose root component `nsh.json` names. Everything else (more modules, images, fonts, JSON files) is found from there: the files the TSX entry imports, or a crate's modules and its `assets/` directory, so there is no file list to maintain. A TSX app is an entry and the modules it imports: ```text my-app/ ├── App.tsx the entry module: calls mount() ├── App.test.tsx its tests (nsh test) ├── nsh.json name, id, version, icon, Tailwind theme, capabilities ├── tsconfig.json TypeScript settings for editors ├── .gitignore .nsh/ and target/ ├── src/ your own modules (any layout you like) │ └── Header.tsx ├── ext/ the app's Rust, when it has any: one nshm crate per directory (nshm) ├── assets/ │ ├── logo@2x.png imported images │ └── Inter.ttf imported fonts ├── locales/ translations, rust-i18n's files: t("hello") (I18n) └── .nsh/ generated: type declarations, development host builds, test entries, build output (.nsh/out) ``` An app written entirely in Rust is a Cargo project: ```text my-app/ ├── nsh.json name, id, version, icon, the crate ("rust") and its root component ("root"), theme ├── Cargo.toml the crate: nsh-core, nsh-base and your dependencies ├── src/ │ ├── lib.rs the root component and the crate's UI set (#[native_module]) │ ├── main.rs cargo run: the root on this machine's desktop backend │ └── screens/ your own modules (any layout you like) ├── assets/ files the crate ships: asset!("logo@2x.png"), fonts ├── locales/ translations, rust-i18n's files: t!("hello") (I18n) ├── .gitignore .nsh/ and target/ ├── .nsh/ generated: the runners' sources, test entries, build output (.nsh/out) └── target/ Cargo's build directory ``` A TSX app extends itself with Rust through nshm crates of its own in `ext/`, listed in `"dependencies"` by path ([An app's own Rust: ext/](https://nsh.dev/versions/v0.7.1/docs/nshm.md#an-apps-own-rust-ext)); `src/` holds its TSX, `ext/` its Rust. A Rust app can also list its crates in `"rust"` and add a TSX entry that imports them ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md#extending-a-rust-app-with-tsx)). Every command takes the app's directory or its entry as its argument (`nsh run my-app`, `nsh run my-app/App.tsx`). The directory of `nsh.json` is the app's root: `nsh.json` is read from there, the paths it names and asset paths are relative to it, and `.nsh/` is written there. The entry is `App.tsx` beside it, unless `nsh.json` names another with `"entry"`. In a Rust app (`nsh.json` `"root"`), the directory runs the root component; naming a TSX entry runs that instead. ### An app in a larger project A project that also has other code, a server or a website, can keep `nsh.json` at its root, beside `package.json` or `Cargo.toml`, and its app's code in a directory of its own, which `"entry"` names: ```text my-project/ ├── nsh.json { "name": "…", "entry": "app/App.tsx", "theme": "app/theme.json", … } ├── package.json the server's ├── server/ └── app/ ├── App.tsx the entry ├── App.test.tsx its tests ├── tsconfig.json TypeScript settings for the app's modules └── theme.json ``` `nsh run`, `nsh test` and the other commands then work from the project's root as from an app's directory: the root is the app's root (`.nsh/`, `locales/` and the paths `nsh.json` names, such as `theme`, `icon` and `web.host`, are relative to it), while `nsh test` looks for test files in the entry's directory (`app/`, not the server's tests), and `nsh check` and `.nsh/types` follow the entry's `tsconfig.json`. ## The root component A TSX entry is a normal module that ends by rendering the root component. A Rust app's root is a component of its crate, which `nsh.json`'s `"root"` names by its path in the crate (`App`, `shell::Gallery`): ```tsx // App.tsx import { mount } from "nsh"; import { Window } from "nsh/desktop"; import { Home } from "./components/Home"; function App() { return ; } mount(() => ); ``` ```rust // src/lib.rs; nsh.json: { "rust": ".", "root": "App" } mod screens; use nsh_core::{element::desktop::window as app_window, prelude::*}; /// What a TSX entry may import from the crate. #[native_module("my-app/native")] fn native(registry: &mut Registry) { registry.register::().assets(assets!()); } #[component] pub fn App() -> impl IntoElement { // On the desktops this is the app's window; off them it shows its content. app_window().id("main").content(screens::home) } ``` In TSX, `mount(component, props?)` renders the component into the app root and returns a function that removes it again; an app calls it once. On the desktops the root holds top-level `` scenes (an app that declares windows declares the first too; a plain root renders in the implicit first window); off the desktops `` shows its content in the one surface. Code at the top level of the entry runs when the bundle loads, before the first frame. `nsh run` and `nsh package` mount a Rust root on every platform, with no QuickJS. ## nsh.json `nsh.json` sits in the app's root. `nsh init` writes `name`, `id`, `version` and `build`, and for a Rust app the crate and its root component: ```json { "name": "Gallery", "id": "com.example.gallery", "version": "1.0.0", "build": 1, "rust": ".", "root": "App", "theme": "theme.json" } ``` Every other key is optional; a TSX app may also leave out the four. A TSX app's `nsh.json` might read: ```json { "name": "Gallery", "id": "com.example.gallery", "version": "1.0.0", "build": 1, "icon": "icon.png", "tailwind": { "colors": { "brand": { "500": "#7c3aed", "600": "#6d28d9" } }, "radius": { "card": 14 } }, "capabilities": { "network": { "hosts": ["api.example.com", "*.cdn.example.com"] } } } ``` | Key | Type | Used by | Description | |---|---|---|---| | `name` | string | `package` | The display name under the app icon. Default: the name of `nsh.json`'s directory. | | `entry` | string | every command | The TSX entry module, relative to `nsh.json` and inside its directory, e.g. `"app/App.tsx"` ([An app in a larger project](#an-app-in-a-larger-project)). Default: `App.tsx` beside `nsh.json`. An entry named on the command line (`nsh run app/Other.tsx`) takes precedence. | | `id` | string | `package`, `publish`, `Storage` | Bundle identifier / application id in reverse-DNS form, e.g. `com.yourcompany.app`; required by `package` and `publish`. `nsh run` uses `com.example.` without one. | | `version` | string | `package`, `publish` | The user-visible version, e.g. `1.2.0` (`CFBundleShortVersionString`, Android `versionName`). | | `build` | number | `package`, `publish` | The build number (`CFBundleVersion`, Android `versionCode`). Signed packages require it to grow with every release. | | `nsh` | string | every command | The NSH versions the app is written for, as a Cargo-style requirement, e.g. `">=0.5"` or `">=0.5, <0.7"`. Every command that takes the app checks the CLI against it first and stops with one message, `this app requires nsh >=0.5; this is nsh 0.4.0`, instead of type or build errors from the other version. A nightly counts as its release. | | `minRuntime` | string | `publish` | The lowest NSH runtime that runs the signed package, e.g. `0.2.0`. Default: the CLI's version ([Signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md#which-runtimes-run-a-package)). | | `schemes` | string[] | `package`, `run` | URL schemes that open the app, e.g. `["myapp"]` for `myapp://…` links, which reach [`UrlScheme`](https://nsh.dev/versions/v0.7.1/modules/nsh.md#urlscheme). Lowercase letters, digits, `+`, `-` and `.`; not one the system or browser owns (`https`, `file`, …). | | `links` | object[] | `package`, `run` | Web links that open the app (Universal Links, App Links): `[{ "host": "example.com", "paths": ["/orders/*"] }]`, `host` a domain name or `*.` and one for its subdomains, `paths` whole paths or starts ending in `*` (none: every path). Their `https` links reach [`UrlScheme`](https://nsh.dev/versions/v0.7.1/modules/nsh.md#web-links) as a scheme's do. iOS packages claim the hosts in their associated domains entitlement, Android packages in a verified intent filter per link. | | `fileTypes` | object[] | `package`, `run` | The file types the app opens, `[{ "name": "Video", "extensions": ["mp4"], "mimeTypes": ["video/mp4"] }]`, which packages declare to the system (on Android, through `mimeTypes`, in the share sheet); the files reach [`Application.on("openFiles")`](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md#opening-files). | | `handoff` | boolean | `package` | `true`: on iOS and macOS the address the app sets with [`UrlScheme.setUrl`](https://nsh.dev/versions/v0.7.1/modules/nsh.md#handoff) goes to the system, so Handoff continues it on the user's other devices; packages declare its activity type, `.url`, in `NSUserActivityTypes`. | | `singleInstance` | boolean | `package` | `true`: the app runs once on Windows and Linux; a second launch hands its arguments and working directory to the running app and exits ([Single instance](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md#single-instance)). | | `logDir` | string | `package` | The directory a packaged desktop app (macOS, Windows, Linux) writes its log files (`app.log`, `app.1.log`, ...) in, and the directory `log_file()` and `process.logFile` point into. Spelled like `dataDir`: an absolute path or `"${homeDir}/.myapp/logs/ui"` (no `..`, no other `${...}`); NSH warns about and ignores any other value. Unset, the logs are in `logs` in the data directory (`dataDir`, or the app's id in the system's directory for apps' data); with `logDir` set, that `logs` directory is not created. iOS, Android, the web and embedded apps have no log file and ignore it. | | `dataDir` | string | `package` | The app's data directory on the desktop (macOS, Windows, Linux): its storage (`nsh/storage`), logs, `process.dataDir` and the files of `${dataDir}` live there. An absolute path or `"${homeDir}/.myapp"` (no `..`, no other `${...}`); NSH warns about and ignores any other value. Unset, it is the app's id in the system's directory for apps' data: `~/Library/Application Support/` on macOS, `%APPDATA%\` on Windows, `$XDG_DATA_HOME/` (`~/.local/share/`) on Linux. A directory set here stays the same when the app's id changes. Caches and downloaded updates keep their own places; iOS, Android, the web and embedded apps use the platform's directory. | | `features` | string[] | `package` | Native features the release runner always keeps (built locally when the app has Rust crates, or packages for this machine's OS with `cargo` installed), e.g. `["plot"]`: those only its Rust code or a computed import needs. `package` otherwise leaves out the ones its bundle never reaches (`shader`, `editor`, `plot`, …) and prints why. | | `icon` | string \| object | `package`, `run` | A square PNG, ideally 1024×1024, relative to `nsh.json`, or one per platform (`{ "macos": "…", "windows": "…" }`, [Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#icons)). Android's may be an adaptive icon (`{ "foreground": "…", "background": "…", "monochrome": "…" }`, [Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#icons)). | | `tailwind` | object | every build | Extends the Tailwind theme your `class` strings resolve against ([Tailwind](https://nsh.dev/versions/v0.7.1/docs/tailwind.md#theme)). | | `appearance` | string | every build, `package` | `"light"`, `"dark"` or `"system"` (the default): an app that is always light or dark says so here. `colorScheme()`, `dark:` classes, the components' theme and the platform's controls follow it from the start ([Device and environment](https://nsh.dev/versions/v0.7.1/docs/device-and-environment.md#dark-mode)). | | `locales` | string[] | every build | The languages the app formats numbers and dates in besides English (`["de", "zh-CN"]`), whose data its bundle carries. Default: the languages of its translations in `locales/` ([I18n](https://nsh.dev/versions/v0.7.1/docs/i18n.md#numbers-and-dates)). | | `timeZones` | string[] | every build | The named time zones `Intl` formats in besides the device's, `UTC` and offsets (`["America/New_York"]`), whose rules its bundle carries. Default: none ([Time zones](https://nsh.dev/versions/v0.7.1/docs/i18n.md#time-zones)). | | `theme` | string or object | every build | The app's design tokens (shadcn/ui's `cssVars`, over the default `neutral` theme), which token classes, `token()` and Rust components draw with: a theme file's path relative to `nsh.json`, or the theme inline ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md#theme), [Theme tokens](https://nsh.dev/versions/v0.7.1/docs/tailwind.md#theme-tokens)). | | `statusBar` | object | every build, `package` | The status bar's default under every page and dialog (iOS and Android): `{ "foreground": "auto" \| "light" \| "dark", "hidden": boolean }`, both optional. Packaged iOS apps show it from the launch screen on ([Status bar](https://nsh.dev/versions/v0.7.1/modules/nsh-base.md#status-bar)). | | `capabilities` | object | every build | What the app may reach outside its VM: network hosts, web view hosts, the status bar, windows of its own ([Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md)). | | `window` | object | every build, `package` | Launch settings for the first window the app declares on the desktops, which it has from its first frame: `title`, `defaultSize`, `minSize`, `titleBar`, `backdrop` and the other options and attributes of a window, as `nsh/desktop`'s `WindowOptions` spells them (`{ "defaultSize": { "width": 1100, "height": 720 }, "titleBar": { "style": "hidden" } }`) ([The app host and the first window](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md#the-app-host-and-the-first-window)). `defaultVisible` no longer applies: the app host never shows; an app that starts without a window opens none. | | `application` | object | every build, `package` | The app's lifecycle: `"quitMode": "platform" \| "lastWindowClosed" \| "explicit"`. `"platform"` (the default) keeps a macOS app running with no windows and quits Windows and Linux apps when the last window closes; `"lastWindowClosed"` quits on every platform; `"explicit"` leaves the app running with no windows. The app can change it at run time with `Application.setQuitMode` ([Quitting](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md#quitting)). | | `resolve` | object | every build | How bare imports resolve: the export conditions of npm packages and aliases ([npm packages](#npm-packages)). | | `rust` | string or string[] | every command | The app's Rust crate, or a list of them, relative to `nsh.json`: their components and modules, which TSX imports by each crate's `#[native_module]` specifier ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md#several-crates)). | | `dependencies` | object | every command | The [nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md) the app uses, by package name, which `nsh add` lists here and NSH pins in `nsh.lock`: a version requirement from crates.io (`"acme-gauge": "^1.0"`), or an object with `"github"`, `"git"` or `"path"`, optional `"version"`, `"tag"` or `"rev"`, and `"features"`, the Cargo features of a Rust nshm to turn on (`"nsh-extra": { "version": "^0.6", "features": ["camera"] }`) ([CLI: nsh add](https://nsh.dev/versions/v0.7.1/docs/cli.md#nsh-add)). | | `web` | object | `package` | What a web package adds to its page. `web.host`: a JS module relative to `nsh.json` exporting `createHost(player)`, which answers the app's [`host`](https://nsh.dev/versions/v0.7.1/modules/nsh.md#host) calls; `web.connect`: the hosts that module's own requests reach, as patterns of `capabilities.network.hosts`, which the page's Content-Security-Policy allows ([Web](https://nsh.dev/versions/v0.7.1/docs/web.md#the-hosts-functions)); `web.base`: the path the site is served under (`"/apps/counter/"`), the page's ``, so that it loads at the app's own paths ([Web](https://nsh.dev/versions/v0.7.1/docs/web.md#deploy-it)); `web.history`: whether pushed pages and open dialogs are browser history entries (by default when the app is the whole page, not in an iframe). | | `updater` | object | `package` | Where the packaged app gets its updates: `{ "github": "owner/repo" }` or `{ "url": "https://…/latest.json", "publicKey": "…" }`, `publicKey` optional with `github`, and `"packages": { "roots": [...] }` for [OTA updates](https://nsh.dev/versions/v0.7.1/docs/ota-updates.md) ([App Updates](https://nsh.dev/versions/v0.7.1/docs/app-updates.md), [nsh/updater](https://nsh.dev/versions/v0.7.1/modules/nsh-updater.md#nshjson)). | | `ios` | object | `package` | What iOS packages add: `infoPlist`, keys of the app's `Info.plist`, `infoPlistStrings`, their text in other languages, by language (`{ "zh-Hans": { "NSCameraUsageDescription": "…" } }`), which `nsh run`'s simulator host also takes ([Info.plist text in other languages](https://nsh.dev/versions/v0.7.1/docs/packaging.md#infoplist-text-in-other-languages)), `entitlements`, which device builds check against the provisioning profile, `launchScreen`, the color and image the system shows while the app starts ([Launch screen](https://nsh.dev/versions/v0.7.1/docs/packaging.md#launch-screen)), `extensions`, the app extensions (`.appex`) the app builds itself, which packages carry and sign ([App extensions](https://nsh.dev/versions/v0.7.1/docs/packaging.md#app-extensions)), and `privacyManifest`, what the app adds to its `PrivacyInfo.xcprivacy`, which packages join with NSH's own entries ([Privacy manifest](https://nsh.dev/versions/v0.7.1/docs/packaging.md#privacy-manifest)). NSH's own keys are refused ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#infoplist-keys-and-entitlements)); `infoPlist`'s `MinimumOSVersion` raises the iOS version the app needs ([Minimum system version](https://nsh.dev/versions/v0.7.1/docs/packaging.md#minimum-system-version)). | | `android` | object | `package` | What Android packages set: `targetSdk`, the API level the app targets and compiles against (default 35) ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#target-api-level)); `usesCleartextTraffic`, plain `http://` requests allowed (default `false`) ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#plain-http)); `permissions`, the permissions the manifest declares besides NSH's own (default none) ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#permissions)); `launchScreen`, the window's color and the splash screen's image while the app starts, the same keys as `ios.launchScreen` ([Launch screen](https://nsh.dev/versions/v0.7.1/docs/packaging.md#launch-screen)); `libraries`, jar, Android library (`.aar`) and dex files of the Java libraries the app ships, relative to `nsh.json`, before the ones its crates list (default none) ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#java-code)); `manifestPlaceholders`, the values of the `${name}` placeholders in the libraries' manifests and the app's and crates' manifest entries, which only the app sets (default none) ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#java-code)); `queries` and `application`, elements the manifest's `` and `` declare besides NSH's own (default none) ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#components-and-queries)). | | `macos` | object | `package`, `run`, `test` | What macOS packages add: `infoPlist`, `infoPlistStrings` and `entitlements`, as `ios`'s ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#infoplist-keys-and-entitlements)), `infoPlist`'s `LSMinimumSystemVersion` raising the macOS version the app needs ([Minimum system version](https://nsh.dev/versions/v0.7.1/docs/packaging.md#minimum-system-version)); `extensions`, the app extensions (`.appex`) the app builds itself, which packages carry in `Contents/PlugIns/` and sign ([macOS app extensions](https://nsh.dev/versions/v0.7.1/docs/packaging.md#macos-app-extensions)); and `activationPolicy`, how the app takes part in the system's UI whichever way NSH starts it: `"regular"` (the default), with a Dock icon and the menu bar, or `"accessory"`, a menu bar app ([macOS](https://nsh.dev/versions/v0.7.1/docs/macos.md#menu-bar-apps)). | | `root` | string | `run`, `package` | A Rust app's root component, its path in the `rust` crate, the first one of a list (`App`, `shell::Gallery`): `nsh run` and `nsh package` of the app's directory mount it with no QuickJS, on every platform; `nsh run App.tsx` still runs the TSX entry ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md)). | | `watch` | object | `run`, `dev` | What the development watcher skips: `"ignore"`, directories whose file changes do not rebuild or restart the app — paths relative to `nsh.json` (`"vendor"`, `"third/jpeg-turbo"`) or absolute, for generated code and other checkouts kept inside the app's directory (the watcher already skips `.nsh`, `node_modules` and nested Git checkouts). | The flags of `nsh package` and `nsh publish` (`--name`, `--id`, `--app-version`, `--build`, `--icon`, `--min-runtime`) override the file's values ([CLI](https://nsh.dev/versions/v0.7.1/docs/cli.md)). Every key is checked when the app is built. What NSH cannot read, a key it does not know or a value of a form it does not know, is reported as a warning and left out, entry by entry, and the rest of the file applies. So an app written for a newer NSH builds and runs with an older one, and a typo shows up in the build's output: ```text warn nsh.json: tailwind: unknown key `colours`, ignored (one of a newer NSH, or a typo) ``` A capability NSH cannot read is not granted, so nothing left out ever widens what the app may do. ### capabilities Without a `capabilities` key, an app may use the network, web views and the status bar freely: a standalone app is its developer's own. With the key, everything not listed is denied, both in development and in packaged apps: ```json "capabilities": { "network": { "hosts": ["api.example.com", "*.cdn.example.com"], "http": [{ "host": "quotes.example.com", "methods": ["GET"], "pathPrefix": "/v1/" }] }, "webview": { "hosts": ["*.example.com"] }, "statusBar": true } ``` `network` covers `fetch`, remote images and video sources; local assets are always allowed. An app that embeds NSH may grant less than an app declares. The details are in [Sandbox and capabilities](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md). ## tsconfig.json and .nsh/types NSH does not need `node_modules`. Instead, every command that builds the app (`init`, `build`, `test`, `dev`, `run`, `package`, `publish`, `check`) writes the TypeScript declarations of everything NSH provides into `.nsh/types`, and NSH's TypeScript settings into `.nsh/tsconfig.json`. The app's `tsconfig.json` extends them: ```json { "extends": "./.nsh/tsconfig.json", "include": ["**/*.ts", "**/*.tsx"] } ``` `.nsh/tsconfig.json` points the `nsh` imports and your app's crates to `.nsh/types`, includes the globals, asset and token declarations, and sets the compiler options NSH apps use (`lib`, `jsx`, `strict`, ...). NSH keeps it current: when a new version adds a library or a path, your app has it with the next build, and your `tsconfig.json` stays as you wrote it. Options you add to `tsconfig.json` apply over NSH's. | File in `.nsh/types/nsh/` | Declares | |---|---| | `index.d.ts` | `nsh`: `signal`, `computed`, `effect`, `mount`, `View`, `Text`, ... and re-exports the types below | | `types.d.ts` | Styles (`ViewStyle`, `TextStyle`, ...), every element's props and events, the refs (`ViewRef`, `InputRef`, ...: what a `ref` receives) | | `jsx-runtime.d.ts` | The JSX runtime TypeScript resolves through `jsxImportSource` (the `JSX` namespace) | | `globals.d.ts` | `If` and `Each`; `console`, timers, `requestAnimationFrame`, `fetch` and the other [global APIs](https://nsh.dev/versions/v0.7.1/modules/globals.md) | | `assets.d.ts` | What importing an image or font gives | | `tokens.d.ts` | `Tokens`: the app's design tokens, from its `"theme"`, which type [`token()`](https://nsh.dev/versions/v0.7.1/modules/nsh.md#token) | | `mobile.d.ts`, `desktop.d.ts` | One file per module (`nsh/mobile`, `nsh/desktop`) | | `base.d.ts` | `nsh/base` | `lib` is `ES2023` without `DOM`: there is no `document` or `window`. The files in `.nsh` are regenerated (only when their contents change), so do not edit them and do not commit them; `.gitignore` already excludes `.nsh/`. If your editor shows `nsh` as missing after cloning a project, run any build command once, e.g. `nsh check`. `.nsh/tsconfig.json` adds `"ESNext.Disposable"`, which declares `using` declarations and `Symbol.dispose`, which the runtime has: `using account = new Account()` frees a [Rust class](https://nsh.dev/versions/v0.7.1/docs/rust.md)'s value at the end of the block. Its `jsxImportSource: "nsh"` and `jsx: "preserve"` only matter to the editor: NSH compiles JSX with its own compiler, whatever the `tsconfig.json` says. TypeScript is checked by your editor or by `nsh check`; the other commands strip types without checking them. An app made by an earlier `nsh init` gets the new `tsconfig.json` with its next build when its own is NSH's template, unchanged; NSH prints a line saying so. A `tsconfig.json` you changed is yours: `nsh check` points out when it does not extend `./.nsh/tsconfig.json`, and you add the `extends` line and remove the options it sets. ## Modules A Rust app's code is its crate's modules (`mod screens;`), and its dependencies come from crates.io like any crate's; NSH's own crates are `nsh-core` (the primitives, signals and typed styles, `use nsh_core::prelude::*`) and `nsh-base` (the base components and the theme). In TSX, split the app into as many `.ts` and `.tsx` modules as you like and import them with relative paths; the extension may be left out: ```tsx import { Header } from "./components/Header"; import { formatPrice } from "./lib/format"; import strings from "./strings.json"; ``` All of them are bundled into one script. JSON files import as their parsed value. ### Leaving parts out of the binary The platform crates turn every optional part on by default: `js`, `shader`, `editor` (with `DiffView`), `rich-editor`, `plot`, `term`, `highlight`, `math`, `emoji-picker` (`EmojiPicker`), `zlib`, `crypto`, `websocket` and `updater`, and the platform's own: `net` and `sound` on Linux, `net`, `webview` and `media` on Windows. SVG images are always included. `nsh run` and the development hosts have every part. `nsh package` builds the release runner with only the parts the app's bundle reaches, when it builds the runner on this machine (the app has Rust crates, or it packages for this machine's OS, or for Android, with `cargo` installed), and prints why it keeps or leaves out each one. A `TextView` keeps `highlight` and `math`, since the text it shows may hold code and formulas. Linux's runner keeps sounds (`sound`, which loads GStreamer) only when the app imports `Sound`, and Windows' links Media Foundation (`media`) only when it imports `Sound` or `AudioPlayer` or shows a `Video`, so an app that plays nothing carries no media code. It cannot see what the app's Rust code uses, or what a computed `import()` loads: name those parts in [`nsh.json`'s `features`](#nshjson), e.g. `"features": ["shader"]`. A Rust crate that depends on `nsh-base` with its default features keeps `editor`, `rich-editor`, `plot`, `term` and `highlight` through Cargo; Rust code drawing a `Shader` still needs `"shader"` named, or its views draw nothing. A part `nsh-base` does not turn on by default (`math`, `emoji-picker`) goes in the crate's own dependency: `nsh-base = { version = "0.6", features = ["emoji-picker"] }`. If you build your own executable with Cargo (embedding NSH, or your own `main`), you choose the parts yourself: set `default-features = false` on the platform crate and on `nsh-base`, since either one left at its defaults turns them back on, and name what you keep: ```toml nsh-base = { version = "0.6", default-features = false, features = ["editor"] } nsh-platform-macos = { version = "0.6", default-features = false, features = ["js", "editor", "highlight", "shader"] } ``` Rust that uses a part its build left out does not compile; TSX that imports one fails when it loads (`Could not find export 'Editor' in module 'nsh/base'`). Without `shader`, shader views draw nothing; without `highlight` and `math`, code and formulas show as plain text. ### Loading code on demand `import()` of one of the app's modules returns a promise of its exports, as in a browser: ```tsx const open = async () => { const { Settings } = await import("./screens/Settings"); screen.set(() => Settings); }; ``` Apps on devices ship one bundle, so the module is already there and the promise resolves at once. A web app published split (`nsh build --split`) gets the module, and what only it uses, as a separate file that is downloaded the first time `import()` asks for it ([Web](https://nsh.dev/versions/v0.7.1/docs/web.md#split-bundles)). The specifier must be a literal relative path: the bundler has to see which module is meant. ### NSH's modules Imports of `nsh` and `nsh/...` are not bundled: the runtime provides them natively. | Module | What it has | |---|---| | `nsh` | Reactivity (`signal`, `computed`, `effect`, ...), `mount`, `split`, `context`; the primitives `View`, `Text`, `Scroll`, `Image`, `List`, `Canvas`, `WebView`, `Video` (`View`'s `selectable` for text selection); safe area insets (`safeArea`, `safeAreaInsets`) and the software keyboard (`Keyboard`, `keyboardFrame`); native animations; `PanResponder`; the environment (`platform`, `windowSize`, `colorScheme`, `fontScale`, `pixelRatio`, `locale`); screen reader and reduce motion state, announcements; the clipboard, the photo picker, storage, the host channel, keyboard shortcuts; components and functions the embedding app registers ([reference](https://nsh.dev/versions/v0.7.1/modules/nsh.md)) | | `nsh/base` | The unstyled foundation of an app's UI: navigation stacks and their pages (`NavStack`, `NavPage`, `createNavStack`), dialogs (`Dialog`), a press target (`Button`), a text input (`Input`) and the system's alert dialog (`AlertDialog`); pages and dialogs set the status bar (`statusBar`) ([reference](https://nsh.dev/versions/v0.7.1/modules/nsh-base.md)) | | `nsh/mobile` | What iOS and Android have: `TabBar`, `InputAccessoryView` (iOS), `BackHandler` (Android) ([reference](https://nsh.dev/versions/v0.7.1/modules/nsh-mobile.md)) | | `nsh/desktop` | What macOS, Windows and Linux have: windows (`Window`, `currentWindow`, `windows`), `titleBar`, `displays`, `Menu`, `Tray`, `GlobalShortcut` ([reference](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md)) | | `nsh/i18n` | The app's translations (its `locales/` files or loaded at run time) and the language it shows: `t`, `setLocale`, `availableLocales`, `addTranslations` ([I18n](https://nsh.dev/versions/v0.7.1/docs/i18n.md), [reference](https://nsh.dev/versions/v0.7.1/modules/nsh-i18n.md)) | | `nsh/updater` | A packaged app updates itself: `checkForUpdate`, `downloadUpdate`, `installAndRestart`, `installOnQuit` ([reference](https://nsh.dev/versions/v0.7.1/modules/nsh-updater.md)) | The [modules reference](https://nsh.dev/versions/v0.7.1/modules.md) documents each one. Importing a module NSH does not have (`nsh/foo`) is a build error. So is a name your code uses that the module does not export (`import { Buton } from "nsh/base"`): the error points at the import and names the closest export (``did you mean `Button`?``). Names used only as types are checked by `nsh check`. ### npm packages NSH needs nothing from npm, but the bundler resolves bare imports from a `node_modules` directory if you install packages with a package manager. Packages resolve their browser builds, because the runtime provides web APIs (`fetch`, streams, `URL`, `TextEncoder`, ...) and not Node's (`fs`, `Buffer`, `process`). Packages that touch the DOM do not work: there is none. A package whose browser build uses the DOM often has another build for workers or React Native. `resolve.conditions` picks the export conditions packages resolve with, in place of the default `["browser"]`: `import`, `require`, `module` and `default` always apply, and without `browser` packages resolve through their `module` and `main` fields. `resolve.alias` replaces an import: by a path relative to `nsh.json` (`./` or `../`), another package, or `false` for an empty module. TypeScript (`nsh check`, editors) types the import as written: a name that is not an installed package gets its types from a `.d.ts` file of the app. ```json "resolve": { "conditions": ["worker"], "alias": { "dom-only-helper": "./shims/helper.ts", "node-polyfill": false } } ``` ```ts // shims/aliases.d.ts declare module "node-polyfill"; ``` `solid-js` cannot be imported: the bundler refuses it and points to `nsh`'s own `signal`, `computed` and `effect`, which replace it. ## Assets Images and fonts ship with the app. A Rust crate reads each file of its `assets/` directory at compile time with `asset!`, and ships them all with `registry.assets(assets!())` in its `#[native_module]` function; TSX imports them like modules, and the bundler records each imported file (and an image's pixel-density variants). `nsh build` copies them to `.nsh/out/assets/`, `nsh package` puts them in the app, and during development they are served to the app. ```tsx import { Image, Text } from "nsh"; import logo from "./assets/logo@2x.png"; // { url: "asset:/assets/logo@2x.png", size: { width: 64, height: 64 } } import Inter from "./assets/Inter.ttf"; // "Inter" Hello ``` ```rust use nsh_core::element::{FontAsset, ImageAsset, asset}; const LOGO: ImageAsset = asset!("logo@2x.png"); // its url, and its size: 64×64 points const INTER: FontAsset = asset!("Inter.ttf"); // its uri, and its family: "Inter" image(LOGO) text("Hello").font_family(INTER.family) ``` | Extension | Import gives | |---|---| | `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.heic` | An `ImageAsset`: `{ url, size, scales? }`, sized in points. An `@2x` / `@3x` suffix divides the pixel size by 2 / 3. A file without a suffix also ships its `@1.5x`–`@4x` siblings, listed in `scales`, and the screen's variant is loaded ([pixel densities](https://nsh.dev/versions/v0.7.1/docs/images-and-assets.md#pixel-densities)). | | `.svg` | An `ImageAsset` sized in points by the SVG's `width` and `height` (or `viewBox`). | | `.ttf`, `.otf`, `.woff`, `.woff2` | The font's family name, a string. The font is registered before the first frame. | | `.json` | The parsed JSON | See [Images and assets](https://nsh.dev/versions/v0.7.1/docs/images-and-assets.md) and [Fonts](https://nsh.dev/versions/v0.7.1/docs/fonts.md). ## Generated directories - **`.nsh/`**: everything NSH generates: the type declarations (`.nsh/types`), the sources of a Rust app's runners (`.nsh/rust`), what `nsh run` installs on simulators and devices (the Catalyst host app, the Android development APK), and `.nsh/out`, the default output of `nsh build` (`bundle.js`, `bundle.js.map`, `bundle.nshc`, `capabilities.json`, `assets/`; for a Rust app, `app.json` and `assets/`) and `nsh package` (`.app`, `.ipa`, `.apk`, a site); `-o` writes elsewhere. Safe to delete; it is recreated. - **`target/`**: Cargo's build directory for an app's crates and runners (or `CARGO_TARGET_DIR`). With [huacnlee/cargo](https://github.com/huacnlee/cargo), which we recommend, it holds only the binaries, and the builds live under `~/.cargo/targets/`. Source: https://nsh.dev/versions/v0.7.1/docs/project-structure --- # nshm An **nshm** (NSH module) is a package that gives Native Shell apps components, modules and classes, as a crate gives Rust programs code. It comes in two kinds: - A **Rust nshm** is a Rust crate, published on crates.io or Git. An app uses it from Rust and from TSX: the same implementation, native on every platform. - A **TSX nshm** is TSX published as a Git repository with version tags. The app's bundle includes it, so an app that uses only TSX nshm needs no Rust, and the nshm ships with the app's packages and over-the-air updates. [nsh-omarchy](https://github.com/huacnlee/nsh-omarchy), for example, gives an app [Omarchy](https://omarchy.org)'s look: buttons, fields, menus, dialogs, tables and charts that follow the system's Omarchy theme as it changes. ```sh nsh add nsh-omarchy # from crates.io nsh add github:huacnlee/nsh-omarchy # or from GitHub ``` Then use it from the language the app is written in. **In a TSX app**, an nshm that exports components, modules or classes to TSX is ready to use once `nsh add` installs it: import them by its specifier, here `nsh-omarchy`. The app needs no newer NSH and no Rust code of its own, since `nsh` builds the app's hosts with the crate. ```tsx // App.tsx import { mount, signal, View } from "nsh"; import { Body, Button, Omarchy, Panel, Switch, Toaster, toast } from "nsh-omarchy"; function App() { // Draw with the system's Omarchy theme, and follow it as it changes. Omarchy.followSystem(); const notify = signal(true); const saved = signal(0); const save = () => { saved.set(saved() + 1); toast({ title: "Settings saved" }); }; return ( notify.set(checked)} /> )} // When the message is sent: each photo, prepared as a picked one. const photos = await Promise.all(selected().map((id) => Photos.loadPicked(id, { maxDimension: 2048 }))); // The attachment's remove button deselects it in the picker too. picker?.deselect(id); ``` - `onChange` hands over the ids of every photo selected now, each time the user selects or deselects one, in the order the user selected them; the picker shows each photo's number in that order. The ids are opaque; the photos' bytes stay native until `loadPicked(id, options)` reads one, with `load`'s options. An id reads while its photo is selected and its picker shown; after that it rejects with `ENOENT`. - `selectionLimit` caps the selection (100 by default, as `Picker.pickImages`; 0 lets the user select as many as the system allows), and `filter` shows `"images"` (default), `"livePhotos"` or `"screenshots"`. - The style sizes it: give it a height, and round it with `borderRadius` and `overflow: "hidden"`. - Where `pickerViewAvailable()` is `false` (iOS 16 and earlier, Android, the desktops, the web) it takes no room and shows nothing; the app lets the user choose with `Picker.pickImages`. Android's photo picker embeds only with a system extension recent devices have, which Native Shell does not use yet. - `loadPicked` needs the `picker` capability, as the rest of `Photos` does. Rust code makes it with `photos_picker()` (`.selection_limit(10).on_change(..)`), deselects through a `component_ref::()`'s `PhotosPickerApi`, and reads with `nsh_extra::photos::load_picked`. ### Push `Push` registers the device with a push service and hands the app its token, which the app sends to its server. Notifications then arrive as events. On iOS the service is the system's; Android has none that every device has, so there the app links a push service's binding, a crate built on `nsh_extra::push` that wraps the service's SDK: ```sh nsh add nsh-extra --features push ``` ```tsx import { Notifications } from "nsh"; import { Push } from "nsh-extra"; if (await Push.available()) { // Showing notifications needs the user's permission; background deliveries do not. await Notifications.requestPermission(); // The token can come later than this call (offline): hear it as an event, don't wait on it. Push.on("token", ({ token }) => sendTokenToServer(token)); Push.register().catch((error) => console.warn("not registered", error)); } Push.on("press", ({ payload }) => openChat(payload)); Push.on("notification", ({ threadId }) => refreshInbox(threadId)); Push.on("background", async ({ payload }) => { const changed = await syncInbox(payload); return changed ? "newData" : "noData"; }); // While a conversation is open, its notifications show no banner and play no sound. function openConversation(threadId: string) { Push.setForegroundPresentation({ banner: false, sound: false }, { threadId }); } function closeConversation(threadId: string) { Push.setForegroundPresentation(null, { threadId }); } ``` - `register()` resolves with `{ token }`, the string the push service takes (hexadecimal on iOS), and rejects with the service's reason when the device is not registered. The service answers once it can be reached, so offline the promise stays pending: `on("token")` is the dependable path, and it reports a token that changed. Register at every launch. `token()` reads the last one. - `press` reports the notification the user pressed, including the one that launched the app, which waits for the first listener. `notification` reports one that arrived while the app is in front. Both carry its `id`, its `threadId` and the `payload` the push service sent. A payload is untrusted input. - `background` reports a delivery that woke the app or reached it in front (on iOS one with `content-available`; a visible one with `content-available` arriving in front is reported to `notification` too; on Android one the binding hands over). The system waits for its listeners: return a promise for the work and what it gave, within 25 seconds of the delivery. One that came while nothing listened waits for a listener until 5 seconds after it came. - `setForegroundPresentation(presentation)` decides how notifications show while the app is in front, and `setForegroundPresentation(presentation, { threadId })` how one thread's show; `null` takes either back. They are decided ahead of the arrival, as the system asks at once, and hold for every surface of the app. On Android the binding posts a notification as they say. - `closeThread(threadId)` removes the delivered notifications of a thread (on Android a notification group), but those `Notifications.show` showed; `Notifications.close(id)` removes one. - `available()` is `true` in a standalone iOS app and wherever the app links a push service's binding. Elsewhere it is `false`, and `register` rejects with `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`; so does `closeThread`, except on Android. - An app that declares `"capabilities"` grants `Push` with [`"notifications": true`](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md#notifications), the capability `Notifications` uses. The token, the deliveries and how they show belong to the whole app, so every function but `available()` asks for it first. The feature adds the `remote-notification` background mode to the packaged iOS app. The `aps-environment` entitlement comes from the provisioning profile the app is signed with ([iOS devices](https://nsh.dev/versions/v0.7.1/docs/packaging.md#ios-devices)). On Android it adds nothing: the push service's SDK brings what its manifest needs. Rust code, such as a push service's SDK binding, uses `nsh_extra::push`: `on_event` hears the same events with the token's raw bytes, `set_foreground_presentation_decider` decides each notification's presentation natively, and the launch options on iOS come from `nsh_platform_ios::on_application_event` ([Application events](https://nsh.dev/versions/v0.7.1/docs/ios.md#application-events)). A binding implements `PushProvider` (it registers the device with its service), sets it with `set_provider` from its `#[native_module]` entry, and reports what the service delivers with `provide_token`, `provide_registration_failure`, `provide_notification` and `provide_background`. A press of a notification the binding posted opens the app with the payload as the intent's extras, and reaches `press` with them as its `payload` (Android does not say which notification it was, so it has no `id` or `threadId`). ### Speech `Speech` turns what the user says into text (dictation): the app starts a session, the system listens to the microphone, and the transcript arrives as it grows. macOS and iOS recognize with the system's Speech framework, Android with the device's recognition service (`SpeechRecognizer`), Windows with its dictation (`Windows.Media.SpeechRecognition`), the web with the browser's Web Speech API; the system or the browser asks the user for the microphone (and on Apple platforms for speech recognition) once. Windows dictates with the user's online speech recognition, which they turn on in Settings > Privacy & security > Speech; while it is off, a session ends with `"not-allowed"`. Linux has no recognizer, nor have terminal apps (the TUI host, on every OS); an app embedded with GPUI recognizes with the platform's recognizer on macOS and Windows. Check `Speech.available()` before showing a microphone button: where nothing recognizes speech, a session ends at once with `"unavailable"`. ```sh nsh add nsh-extra --features speech ``` ```ts const Speech: { available(): Promise; start(options?: SpeechOptions): SpeechSession; }; interface SpeechOptions { /** The language spoken, a BCP 47 tag ("en-US", "zh-CN"); the user's when left out. */ lang?: string; /** Results while the user speaks (true, the default), or only the final one. */ interim?: boolean; } interface SpeechSession { on(event: "start", listener: () => void): () => void; on(event: "result", listener: (result: SpeechResult) => void): () => void; on(event: "end", listener: (end: SpeechEnd) => void): () => void; /** The whole transcript so far. */ readonly text: string; readonly ended: boolean; stop(): void; abort(): void; } interface SpeechResult { text: string; isFinal: boolean } interface SpeechEnd { text: string; error?: SpeechErrorCode } type SpeechErrorCode = | "not-allowed" | "no-speech" | "audio-capture" | "network" | "language-not-supported" | "unavailable" | "failed"; ``` ```tsx import { signal } from "nsh"; import { Speech, type SpeechSession } from "nsh-extra"; const transcript = signal(""); let session: SpeechSession | null = null; function toggle() { if (session && !session.ended) { session.stop(); return; } session = Speech.start({ lang: "en-US" }); session.on("result", ({ text }) => transcript.set(text)); session.on("end", ({ text, error }) => { if (error) console.warn("dictation ended:", error); else transcript.set(text); }); } ``` - `start` returns the session at once. It reports, in this order: `start` when the microphone is on and the recognizer listens, `result` each time the transcript changes (`text` is always the whole transcript so far, so the app shows it as it is), and one `end`, after which nothing comes. `stop()` stops listening and lets the recognizer finish what it heard: a last result with `isFinal: true`, then `end`. `abort()` ends the session at once, without an error. One session runs at a time, as there is one microphone: starting another ends the one running. A new session of the same app in the same view ends it as `abort()` does, without an error; one that another app or view of the process starts (an embedding app's other `AppView`) ends it with `"audio-capture"`, as the microphone was taken from it. - `end` carries the last transcript and, when the session failed, `error`, named as in the Web Speech API: `"not-allowed"` (the user or the system does not allow the microphone or speech recognition, or the app is in the background), `"no-speech"` (nothing was said), `"audio-capture"` (the microphone could not be used), `"network"` (the recognizer needs the network), `"language-not-supported"` (the recognizer does not know `lang`), `"unavailable"` (nothing recognizes speech here, or not now) and `"failed"`. - `start` throws a `TypeError` for options of the wrong types and a `RangeError` for a `lang` that is no language tag. - `available()` is `true` on macOS and iOS, on Android devices with a recognition service, on Windows with a dictation language and a microphone, in browsers with the Web Speech API (Chromium-based browsers such as Chrome and Edge, and Safari), and wherever the app gave the module a recognizer of its own. It is `false` on Linux and in terminal apps. - On the web the page needs a secure context (HTTPS, or `localhost` while developing) for the microphone, and a page that embeds the app in an iframe allows it (`allow="microphone"`). Chrome recognizes with its online service, so `"network"` reports a lost connection. - An app that declares `"capabilities"` grants `Speech` with [`"speech": true`](https://nsh.dev/versions/v0.7.1/docs/sandbox-and-capabilities.md#speech). Without it `start` throws an `Error` whose `code` is `"ERR_ACCESS_DENIED"`, `permission` `"speech"`. The feature adds what the packaged app needs: the microphone's and speech recognition's usage descriptions on iOS and macOS (an app sets its own wording with `ios.infoPlist` / `macos.infoPlist`), the audio input entitlement on macOS, and on Android the `RECORD_AUDIO` permission and the query of recognition services. On the web the module calls the browser through wasm-bindgen, so `nsh` builds the app's web runtime with the `wasm-bindgen` CLI ([browser APIs from Rust](https://nsh.dev/versions/v0.7.1/docs/web.md#browser-apis-from-rust)); the site itself needs no declaration. Rust code uses `nsh_extra::speech`: `available().await`, and `recognize(SpeechRequest)`, a session whose `next().await` gives each `SpeechEvent` (`stop()`, `abort()`; dropping it aborts). An app that recognizes speech its own way (its own engine or service, an embedding app's) gives the module a `SpeechBackend` with `set_backend`: every session then reaches it instead of the system's recognizer. ```rust use nsh_extra::speech::{self, SpeechEvent, SpeechRequest}; async fn dictate() -> String { let mut recognition = speech::recognize(SpeechRequest::default()); let mut text = String::new(); while let Some(event) = recognition.next().await { match event { SpeechEvent::Result { text: heard, .. } => text = heard, SpeechEvent::End { .. } => break, _ => {} } } text } ``` In `nsh test` (and `nsh_testing::Headless`), sessions run on the module's fake recognizer, named `"nsh-extra/speech"`: a session starts listening at once, as if the user allowed the microphone, and the test speaks for the user through the fake with [`app.fake`](https://nsh.dev/versions/v0.7.1/docs/testing-and-trace.md) (`Headless::call_fake` in Rust): | Method | `args` | What it does, and its answer | |---|---|---| | `hear` | `[text]` | The user says `text`, the whole transcript so far: the running session reports it as a `result` that is not final (with `interim: false`, it keeps it for the end). Resolves with `null`; rejects with `no speech session listens` when none runs. | | `end` | `[]` or `[error]` | Ends the running session: with `error` (one of the codes above), or as when the user stops: the transcript as the final `result`, then `end` (`"no-speech"` when nothing was heard). Resolves with `null`; rejects when no session runs or `error` is no code. | | `requests` | `[]` | Resolves with the sessions the app started, in order: `[{ lang, interim }]`, `lang` `null` for the user's language. | ```tsx await app.press("label:Dictate"); await app.fake("nsh-extra/speech", "hear", ["hello"]); await app.waitFor("text:hello"); await app.fake("nsh-extra/speech", "end"); ``` ## An app's own Rust: `ext/` A TSX app that needs Rust of its own (a scanner, a parser, a database, a native view) keeps it in `ext/`, beside `src/`: `src/` holds the app's TSX, `ext/` its Rust, one nshm crate per directory. The app lists each in `nsh.json` `"dependencies"` by path and imports it from TSX like any other nshm. `nsh init --template mixed` starts an app this way. ```text my-app/ ├── App.tsx the entry ├── src/ the app's TSX modules ├── ext/ the app's Rust │ └── my-app-native/ │ ├── Cargo.toml nsh-core and the crate's own dependencies │ └── src/lib.rs #[native_module("my-app-native")] ├── nsh.json "dependencies": { "my-app-native": { "path": "ext/my-app-native" } } └── nsh.lock ``` [Disktree](https://github.com/huacnlee/disktree), a disk usage analyzer, is built this way: its UI is TSX in `App.tsx` and `src/`, and its file system scanner, an SQLite index and file removal are Rust in `ext/disktree-native`: ```json // nsh.json { "name": "disktree", "dependencies": { "disktree-native": { "path": "ext/disktree-native" } } } ``` ```rust // ext/disktree-native/src/lib.rs (abridged) mod scanner; use nsh_core::prelude::*; /// Scans, browses and removes entries using the native disk index. #[module] pub struct DiskTree; #[module] impl DiskTree { /// Runs a filesystem operation with a JSON payload and returns its JSON result. pub async fn request(route: String, body: String) -> Result { // An `async fn` returns a Promise to TSX; `blocking` keeps the // file system work off the UI thread. blocking(move || scanner::dispatch(&route, &body)).await } } #[native_module("disktree-native")] fn native(registry: &mut Registry) { registry.module::(); } ``` ```ts // src/runtime.ts import { DiskTree } from "disktree-native"; const result = JSON.parse(await DiskTree.request("/scan", JSON.stringify({ path }))); ``` Why `ext/` rather than a crate at the app's root (`"rust": "."`): - **The same way as every other nshm.** The app's own Rust and the nshm it installs are listed, locked and built the same way, and moving a crate from `ext/` to crates.io or its own repository later only changes its `nsh.json` entry. - **Each crate on its own.** It has its own `Cargo.toml`, dependencies and tests (`cargo test` in its directory), and builds once, optimized, in `~/.nsh/builds` until it changes. The app's root stays a TSX project. - **Small interfaces.** TSX reaches the Rust only through what `#[native_module]` registers, with declarations generated from the Rust signatures (`.nsh/types/.d.ts`), so the boundary is typed and easy to see in review. Add another crate with `cargo new --lib ext/`, give it a `#[native_module("")]`, and run `nsh add --path ext/`. Keep UI in TSX and put in Rust what needs native speed, the platform, or the crates.io ecosystem; a crate exports components too when a view must be native ([A Rust nshm](#a-rust-nshm)). ## Writing an nshm ### A Rust nshm A Rust nshm is an ordinary Cargo library with a `#[native_module("")]` entry at its root, the same as an app's own crate: the specifier is what TSX imports, and the function registers what it exports ([Extending a Rust app with TSX](https://nsh.dev/versions/v0.7.1/docs/rust.md#extending-a-rust-app-with-tsx)). A small one: ```toml # Cargo.toml [package] name = "my-gauge" version = "0.1.0" edition = "2024" keywords = ["nshm"] [dependencies] nsh-core = "0.6" ``` ```rust // src/lib.rs use nsh_core::prelude::*; #[native_module("my-gauge")] fn native(registry: &mut Registry) { registry.register::(); } #[derive(Clone, PartialEq, Props)] pub struct GaugeProps { /// The value shown, from 0 to 1. pub value: Prop, } /// A horizontal gauge. #[component] pub fn Gauge(props: GaugeProps) -> impl IntoElement { view() .h(px(8.0)) .rounded_full() .bg(rgb(0xe5e7eb)) .child( view() .h_full() .rounded_full() .bg(rgb(0x2563eb)) .w(move || relative(props.value.get())), ) } ``` The NSH versions an nshm builds with are its own `nsh-core` requirement (`nsh-core = "0.6"`, or its workspace's with `nsh-core.workspace = true`), which `nsh add` checks against the running `nsh` before anything compiles. An nshm developed in a Cargo workspace takes its version and this requirement from the workspace as Cargo does, its own manifest's when it is the workspace's root package. Its TypeScript declarations are generated from its Rust types, so apps check their TSX against it as they do against their own crate. [nsh-omarchy's `src/lib.rs`](https://github.com/huacnlee/nsh-omarchy/blob/main/src/lib.rs) is a complete one: its components, exported to TSX by `#[native_module("nsh-omarchy")]`, with the `Omarchy` theme module. ### What the packaged app needs An nshm that uses a system feature declares what the packaged app needs in its `Cargo.toml`, under `[package.metadata.nsh]`, or under a feature's `[package.metadata.nsh.features.]` when only that feature needs it. `nsh` adds the entries of every crate the app links, with the features Cargo turns on, to the packages it builds, and the iOS `Info.plist` keys and Android entries to its development hosts: ```toml [package.metadata.nsh.features.scanner.ios.infoPlist] NSCameraUsageDescription = "Scans the codes you point the camera at." [package.metadata.nsh.features.scanner.android] permissions = ["CAMERA"] queries = [''] application = [''] libraries = ["android/libs/scanner-glue.jar"] ``` | Key | Adds | |---|---| | `ios.infoPlist` | Keys of the iOS app's `Info.plist`, as `nsh.json`'s `ios.infoPlist` | | `ios.infoPlistStrings` | The text of those keys in other languages, by language, as `nsh.json`'s `ios.infoPlistStrings` ([Packaging](https://nsh.dev/versions/v0.7.1/docs/packaging.md#infoplist-text-in-other-languages)) | | `ios.entitlements` | The iOS app's entitlements | | `macos.infoPlist` | Keys of the macOS app's `Info.plist`, as `nsh.json`'s `macos.infoPlist` | | `macos.infoPlistStrings` | The text of those keys in other languages, as `ios.infoPlistStrings` | | `macos.entitlements` | The macOS app's entitlements | | `android.permissions` | `` elements, named as in `nsh.json` (`CAMERA` is `android.permission.CAMERA`) | | `android.queries` | ``, `` and `` elements of the manifest's `` | | `android.application` | ``, ``, ``, `` and `` elements of ``; `${applicationId}` is the app's package, other placeholders the app's `android.manifestPlaceholders` | | `android.libraries` | Java libraries, jar, Android library (`.aar`) and dex files relative to the crate's `Cargo.toml`, packaged as `nsh.json`'s `android.libraries` are ([Java code](https://nsh.dev/versions/v0.7.1/docs/packaging.md#java-code)) | A crate does not set `android.manifestPlaceholders`, which is an error: the values of placeholders (a service's key) are the app's, set in its `nsh.json`. The version of an Android library two crates carry in different versions is the one the app lists in its own `android.libraries`. When two libraries define a resource of one name, a library the app lists wins, then the crate whose name sorts first ([Java code](https://nsh.dev/versions/v0.7.1/docs/packaging.md#java-code)). The app's own `nsh.json` wins: a key it sets keeps its value, and arrays (such as `UIBackgroundModes`) are joined. When two crates set one key to different values (two usage descriptions of the camera), the app chooses by setting the key in `ios.infoPlist`, `ios.entitlements`, `macos.infoPlist` or `macos.entitlements`; until it does, packaging for that platform stops with an error naming both crates. Keys NSH sets itself (the bundle's identifier, version and the like) are not the crates'. A crate translates the keys the crates set in `ios.infoPlist` (`macos.infoPlist` in `macos.infoPlistStrings`), as they word them; a translation of a key no crate sets with the app's features (one of a feature that is off) is left out with a warning. The app takes the crates' translations for the languages it has only, those of its `locales` or its own `ios.infoPlistStrings` (`macos.infoPlistStrings`; an empty `{}` names a language without text of its own), so a crate may carry many languages without adding any to the app. A key the app sets itself takes none of the crates' translations, which would say something else than the app's text. Two crates translating a key differently are settled by the app as above, in `ios.infoPlistStrings` (`macos.infoPlistStrings`). Develop it beside an app with `nsh add --path ../my-gauge`, which reads the directory as it is. Publish it as any crate (`cargo publish`), with the keyword `nshm` so that it can be found on [crates.io](https://crates.io/keywords/nshm), or push it to Git and tag its versions. ### Wrapping a native SDK An nshm that wraps an Apple SDK calls it from Rust under `#[cfg(target_os = "ios")]` or `#[cfg(target_os = "macos")]`. System frameworks used through the `objc2` crates need nothing more. A vendor's prebuilt library (an `.xcframework` or `.a`) is linked from the nshm's own `build.rs`: Cargo passes the `rustc-link-lib` and `rustc-link-search` of every dependency to the app's executable, so the app lists nothing and NSH has no per-platform SDK settings. ```rust // build.rs fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("ios") { return; } // The simulator's and Mac Catalyst's (`nsh run --target catalyst`) are iOS too. let slice = match std::env::var("CARGO_CFG_TARGET_ABI").as_deref() { Ok("sim") => "ios-arm64_x86_64-simulator", Ok("macabi") => "ios-arm64_x86_64-maccatalyst", _ => "ios-arm64", }; let root = std::env::var("CARGO_MANIFEST_DIR").unwrap(); println!("cargo:rustc-link-search=native={root}/vendor/Sdk.xcframework/{slice}"); // +whole-archive is -force_load: it keeps Objective-C categories, like -ObjC. println!("cargo:rustc-link-lib=static:+whole-archive=Sdk"); println!("cargo:rustc-link-lib=framework=AdSupport"); } ``` - Use `rustc-link-lib`, not `rustc-link-arg`: link arguments only apply to the crate's own targets. - Put a static library's privacy manifest entries in the app's `ios.privacyManifest`. - NSH does not embed dynamic frameworks; prefer the SDK's static build. - A library whose licence asks that users can replace it (LGPL, such as libmpv) stays dynamic, and the app carries it itself; NSH's packages have no setting for it. Link it from the nshm's `build.rs` as above (`rustc-link-lib=framework=…`, `rustc-link-search=framework=…`). Give the executables their run path in the app's `.cargo/config.toml` (`rustflags = ["-C", "link-arg=-Wl,-rpath,@executable_path/../Frameworks", "-C", "link-arg=-Wl,-rpath,"]` under `[target.aarch64-apple-darwin]`), since a crate's `rustc-link-arg` does not reach `nsh run`, `nsh check` or `nsh test`. After `nsh package --target macos`, copy the framework into the app's `Contents/Frameworks/`, remove the development run path with `install_name_tool -delete_rpath`, then sign again, the framework first and the app last, with the identity the package used (`codesign --force --sign --options runtime --entitlements `, or `--sign -` for an ad hoc package), and check it with `codesign --verify --deep --strict`. - On Linux and Windows the same `build.rs` links the SDK (`.a` and `.so` on Linux, `.lib` on Windows). NSH does not carry shared libraries (`.so`, `.dll`) into the package either; prefer the SDK's static build. ### A TSX nshm A TSX nshm is a Git repository whose `nsh.json` describes it: its package name and version, the NSH versions it works with, and what it exports, each specifier with its TSX entry file: ```json { "name": "acme-badge", "version": "0.1.0", "nsh": ">=0.6", "exports": { "acme-badge": "src/index.tsx" }, "dependencies": { "acme-icons": { "github": "acme/icons", "version": "^1" } } } ``` ```tsx // src/index.tsx import { Text, View } from "nsh"; /** A rounded label. */ export function Badge(props: { label: string }) { return ( {props.label} ); } ``` Its exports are its specifier or start with it (`acme-badge`, `acme-badge/icons`), and its files stay inside it. Apps import it as they import their own modules, and `nsh check` checks their TSX against its source. Publish a version by tagging it (`git tag v0.1.0 && git push --tags`); the tag's version must be the one its `nsh.json` says. A Rust nshm can export TSX as well, by the same `"exports"` in an `nsh.json` beside its `Cargo.toml`: TSX helpers written on top of its native module. Its name and version are then its crate's. ### Dependencies An nshm lists the nshm it needs in its `nsh.json` `"dependencies"`, in the app's form: from crates.io or Git, with a version requirement as wide as it works with, so that apps and the other nshm they use can agree on one version. A published nshm cannot depend on a directory. The app's own entry for a package decides where it comes from: an app can take an nshm its nshm depend on from a fork or a local directory while their version requirements still apply. ## Platform nshm An nshm can provide a target of its own, such as a platform NSH does not build for, with `"platform"` in its `nsh.json` and a binary named `nsh-platform-` in its crate. The crate needs no `#[native_module]` when it gives the app nothing but the target; without one, the app is not linked with it and does not become a Rust app: ```json { "name": "nsh-harmony", "version": "0.1.0", "platform": "harmony" } ``` After `nsh add nsh-harmony`, the app's `nsh run`, `nsh dev`, `nsh test` and `nsh package` with `--target harmony` build that binary (in the app's `.nsh/platforms/harmony`, leaving the shared installation as it is) and run it as an [external target](https://nsh.dev/versions/v0.7.1/docs/cli.md#external-targets). A platform installed on `PATH` as `nsh-platform-` serves every app without being an nshm; the app's nshm comes first. [Building a platform](https://nsh.dev/versions/v0.7.1/docs/platform-extensions.md) covers what a platform implements. ## Security An nshm's build scripts and procedural macros run when the app builds, and its code, TSX or Rust, runs with the app's permissions. Any crate in the app's dependency graph can also add system permissions, manifest components, Java and Android libraries (with their native code) and entitlements to the packaged app through `[package.metadata.nsh]`. Review its source and the changes to `nsh.lock` as you review the app's own code. Source: https://nsh.dev/versions/v0.7.1/docs/nshm --- # Building with Rust Native Shell apps are written in TSX, with Rust where it pays off, or entirely in Rust. All of them run on the same engine: the reactive graph, the renderer, Taffy layout and the native modules (navigation, dialogs, the keyboard, the status bar) are Rust in every case, and every platform renders with its own UI. What differs is the language of your own code, and with it whether the app carries a JavaScript VM. | | TSX | TSX with Rust | Rust | |---|---|---|---| | Your UI, state and handlers | TSX on QuickJS | TSX screens, with Rust components, modules and classes from nshm (`ext/` or published) | Rust | | The app runs | QuickJS and the engine (in the browser, its JavaScript engine) | QuickJS and the engine, with your crates (in the browser, its JavaScript engine) | the engine and your crate only, on every platform and in the browser | | Suits | Most apps, and modules delivered at run time | Apps with parts that need native speed, the platform or crates.io | Apps whose core is large, demanding business logic | | Edits | Hot updates | Hot updates for TSX, rebuild for Rust | Rebuild and restart | | Start | `nsh init my-app --template ts` | `nsh init my-app --template mixed` | `nsh init my-app --template rust` | ## Choosing **TSX** suits most apps: screens, state and business logic written with hot updates while you develop, built with `nsh` alone. The same code also makes UI that arrives after the app ships: modules a native app loads at run time, generated by a model or written by another team, delivered as [signed packages](https://nsh.dev/versions/v0.7.1/docs/signed-packages.md) and run in a sandbox the host configures. **TSX with Rust** keeps the app in TSX and puts in Rust what needs native speed, the platform or the crates.io ecosystem: parsing, large data, file system and system APIs, a view that must be native. The Rust lives in nshm crates, the app's own in `ext/` or published ones, and TSX imports their components, modules and classes like any NSH module, so the two halves meet at typed interfaces ([nshm](https://nsh.dev/versions/v0.7.1/docs/nshm.md), [An app's own Rust: ext/](https://nsh.dev/versions/v0.7.1/docs/nshm.md#an-apps-own-rust-ext)). **Rust** suits apps whose business logic is large and demanding: trading, editors, data-heavy tools. You get Rust's type system and compile-time checks across the whole app, the crates.io ecosystem, native performance for your own code (not only for NSH's), and headless tests of the real UI with `cargo test`. The app is Rust and native code from start to end: no JavaScript VM ships with it or runs in it, on iOS, Android, macOS, Windows, Linux, GPUI and the web. Components are functions that run once and bind signals to what they show, as in TSX ([Reactivity](https://nsh.dev/versions/v0.7.1/docs/reactivity.md)), written with typed styles instead of class strings. A Rust app can still take TSX screens on top, for parts that change often or arrive at run time ([Extending a Rust app with TSX](#extending-a-rust-app-with-tsx)); the TSX runs on QuickJS, which the app then carries. The rest of this page covers apps written in Rust: their structure, theme, tests and how TSX extends them. ## An app written in Rust ```sh nsh init my-app --template rust cd my-app nsh run # this machine's backend; --target ios, android, web, macos, linux or windows nsh package --target web # or ios, ios-simulator, android, macos, linux, windows ``` Build with [huacnlee/cargo](https://github.com/huacnlee/cargo), the Cargo NSH is developed with: a drop-in fork that builds each dependency once for all your projects and Git worktrees and keeps its build directory under a size limit on its own, with nothing to configure ([Installation](https://nsh.dev/versions/v0.7.1/docs/installation.md#for-apps-written-in-rust)). `src/lib.rs` holds the app: components, state, handlers, tasks. ```rust use nsh_base::{button, theme}; use nsh_core::prelude::*; /// The components available to TSX through `app/native`. #[native_module("app/native")] fn native(registry: &mut Registry) { registry.register::(); } #[component] pub fn App() -> impl IntoElement { let count = signal(0_u32); let quote = signal(SharedString::from("…")); // Async work runs in tasks; requests go through NSH's network stack. spawn(async move { if let Ok(response) = fetch("https://api.example.com/quote").await { quote.set(response.text().into()); } }); view() .flex_1() .items_center() .justify_center() .gap_4() .child(text(move || format!("Count: {}", count.get()))) .child(text(quote)) .child( // nsh_base's unstyled button, drawn with the theme's colors. button() .px(px(20.0)) .py(px(12.0)) .rounded(move || theme().radius) .bg(move || theme().primary) .active(|s| s.bg(move || theme().primary.opacity(0.9))) .on_press(move || count.update(|c| *c += 1)) .child(text("Tap").text_color(move || theme().primary_foreground)), ) } ``` Elements and components are made the same way: a function makes one (`view()`, `text(..)`, `nsh_base`'s `button()`, your `#[component] fn Chart`'s `chart()`), and its methods set its props, one setter per prop (a value, a signal or a closure), and its listeners, one method per event. Listeners are closures of their event (`move |text: &str| ..`), and `move || ..` for an event without data; `.child(..)` takes an element, or an `Option`, a `Vec`, an array or an iterator of elements (`.child(rows.iter().map(|r| row(r)))`). `nsh.json` names the root, and `nsh` mounts it: ```json { "name": "My App", "rust": ".", "root": "App", "theme": "theme.json", "appearance": "system" } ``` `"root"` is the component's path in the crate (`App`, `shell::Gallery`; in the first one with [several crates](#several-crates)); `"theme"` is the [theme](#theme) its components draw with, and `"appearance"` applies to it as it does to a TSX app. With it, `nsh run` and `nsh package` of the app's directory build the app's own runner for the target, with the root mounted and no QuickJS linked in: | Target | What runs | |---|---| | macOS, Windows, Linux | The release runner with your crate, in a window; `nsh run` runs a debug build and shows the app's logs in the terminal | | iOS, the iOS simulator, Mac Catalyst | The iOS runner with your crate, in an app | | Android | The app's `libnsh.so` with your crate, started by the runtime's activity | | Web | `nsh.wasm` with the engine and your crate (3.3 MB for the whole Rust gallery, 0.75 MB with brotli); the page mounts the root | `nsh` builds what your crate needs and nothing more: a small program of your crate and NSH's core that describes its components and modules to the CLI, which then does the rest itself, and the runner of each target you run or package. The first build of a new Rust app compiles your crate and NSH's core, about 60 crates. `nsh test` runs the app's tests headless in a runner of your crate built the same way. On Linux, your crate selects optional platform features. Enable `webview` on your `nsh-platform-linux` dependency to use web views; this links WebKitGTK 6.0, which must be installed to build and run the app. The generated runner inherits that choice through Cargo feature unification. During `nsh run`, a change to the crate's Rust code builds the runner again and restarts the app; in the browser, the open page loads the new runtime by itself. `cargo run` starts the same root directly on the desktop backend (`src/main.rs`), and native apps that embed NSH mount a Rust root with `AppSource::Rust` on the `AppView` of macOS, Windows, Linux, GPUI and iOS. Code for every platform, the web included, uses NSH's services: `fetch` for HTTP ([Networking](https://nsh.dev/versions/v0.7.1/docs/networking.md#from-rust-components)), `timer`, `set_timeout` and `set_interval` for waiting, `nsh_core::time::Instant` and `nsh_core::time::unix_ms()` for the clock. `background` and `blocking` run work on the native targets' threads. `run_on_main_thread(f)` runs `f` on the platform's main thread, for APIs that only work there (AppKit's status items, UIKit): after the views of the current turn are mounted, and its result is a future to await on the engine thread. A module function that is not `async` calls `cx.run_on_main_thread(f)`. On the web and in headless tests `f` runs on the engine thread at the end of the commit, and on the native platforms later, while the engine goes on: await the result to know that `f` ran. `f` returns a value, and the code that awaits it writes signals and calls NSH's functions with it. ## Desktop title bars Rust apps draw their own title bars with `nsh_core::element::desktop`. Set the window's `title_bar` attribute to `TitleBarStyle::Hidden` with `current_window().set(..)`, mark the bar's background with `.window_drag(true)`, and reserve the native window controls' space with `title_bar()`. Its `top` is the bar's height, and `left` and `right` are the widths occupied by the system controls. Reading it subscribes to changes, including full screen. The platform handles window dragging and the user's title-bar double-click behavior; `.window_drag(false)` keeps a child out of its parent's drag region. ```rust use nsh_core::{ desktop::{TitleBarOptions, TitleBarStyle, WindowAttributes, WindowControl}, element::desktop::{current_window, title_bar}, prelude::*, }; fn window_bar() -> impl IntoElement { let mut bar = TitleBarOptions::default(); bar.style = TitleBarStyle::Hidden; bar.height = Some(px(42.0)); let mut attributes = WindowAttributes::default(); attributes.title_bar = Some(bar); current_window().set(attributes); view() .h(px(42.0)) .flex_row() .items_center() .window_drag(true) .pl(move || title_bar().left + px(12.0)) .pr(move || title_bar().right + px(12.0)) .child(text("My app").flex_1()) .child(text("Close").window_control(WindowControl::Close)) } ``` A title bar with `TitleBarStyle::Default` restores the system's. A view with `.window_control(..)` is the window's minimize, maximize or close button: the platform carries out its press, and a close goes through the window's `close_on_press`. The `WindowRef` has the window's other requests (`set_mode`, `minimize`, `set_bounds`, `close`, ...), `window()` opens windows of the app's own, and the module has the menus (`set_application_menu`, `popup_menu`) too: [nsh/desktop](https://nsh.dev/versions/v0.7.1/modules/nsh-desktop.md). ## Files and folders On the desktops, Rust code shows the system's file dialogs and hands local paths to the system, each answer awaited in a task: `pick_paths` with an `OpenDialog` (`OpenDialog::files()`, `::folders()` or `::files_and_folders()`), `pick_save_path` with a `SaveDialog`, `open_path` (the file's default app), `reveal_path` (the item selected in Finder, File Explorer or the file manager) and `move_to_trash` (where the item went, when macOS says). The dialogs answer `Ok(None)` when the user cancels and an error when they cannot show (on Linux without a file chooser portal, and on iOS, Android and the web, where `open_path`, `reveal_path` and `move_to_trash` answer an error too). Every request that fails answers its error, never `false`. ```rust use nsh_core::{ file_dialog::{FileFilter, OpenDialog}, prelude::*, }; fn open_notes() { let picked = pick_paths( OpenDialog::files() .multiple(true) .filter(FileFilter::new("Markdown", ["md", "markdown"])) .button_label("Open"), ); spawn(async move { match picked.await { Ok(Some(paths)) => { for path in paths { let _ = reveal_path(path).await; } } Ok(None) => {} // Cancelled. Err(error) => log::warn!("no file dialog: {error}"), } }); } ``` ## Signing in on the web `open_auth_session` opens a provider's sign-in page (an OAuth authorization URL) and answers with the callback URL it redirects to: iOS shows it in an `ASWebAuthenticationSession` sheet (`.ephemeral(true)` keeps it apart from the user's Safari data), Android in a Custom Tab, the macOS, Windows and Linux backends in the system browser. Outside iOS the callback comes back as a link of a scheme the app claims (`nsh.json` `schemes`); the session takes it, so `next_url_scheme_open` never hears it. The answer is `Completed(url)` or `Cancelled` (the user closed the page or came back to the app without signing in). A session with nothing to bring its callback back fails at once with `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`: one whose scheme the app does not claim, and every one on the web and the GPUI and terminal backends, where no link of the app's schemes reaches the app. The page's URL needs the `openUrl` capability, as `open_url` does. When the app learns the user signed in some other way while the page still shows (a device code approved on a page that never redirects back), `close_auth_session()` closes it: the session answers `Cancelled`, and iOS and Android take the page away and bring the app back. A page in a desktop browser stays open. With no session waiting, it does nothing. ```rust use nsh_core::{ auth_session::{AuthSessionOutcome, AuthSessionRequest}, prelude::*, }; fn sign_in(authorize_url: String) { let session = open_auth_session(AuthSessionRequest::new(authorize_url, "myapp")); spawn(async move { match session.await { Ok(AuthSessionOutcome::Completed(callback)) => log::info!("signed in: {callback}"), Ok(_) => {} // Cancelled. Err(error) => log::warn!("no sign-in page: {error}"), } }); } ``` In tests, `Headless::on_auth_session` gives the platform an in-app session and ends each one with the outcome given, and `keep_auth_sessions_open` leaves each one open until the app closes it (`screen().auth_session_showing()`); without either the page is in `opened_urls()` and `open_with_url` delivers the callback (not in a test run as the web, where the session fails at once). ## Extending a Rust app with TSX The crate's `#[native_module("app/native")]` function names what TSX may import: components (`registry.register::()`), modules of functions (`registry.module::()`, `#[module]` on a unit struct and its `impl`), classes (`registry.class::()`, `#[class]` on a struct and its `impl`) and assets; the attribute also makes `pub fn registry()` at the crate's root, the same set for your tests and other Rust code (`my_app_native::registry()`, next to `nsh_base::registry()`). In a `#[module]` or `#[class]` `impl`, the `pub fn`s are exported (`pub(crate)` too); functions without a visibility are helpers that stay in Rust. Their TypeScript declarations, doc comments included, are generated from the Rust types into `.nsh/types`, so TSX is checked against them by `nsh check` and your editor: ```rust /// A price chart. #[derive(Clone, PartialEq, Props)] pub struct ChartProps { /// The symbol to chart. pub symbol: Prop, /// The range shown. #[prop(default = SharedString::from("1D"))] pub range: Prop, } #[derive(Event)] pub enum ChartEvent { /// A price was selected. #[args(price)] Select(f64), } /// A price chart; a press selects the last price. #[component] pub fn Chart(props: ChartProps, cx: Scope) -> impl IntoElement { view() .h(px(160.0)) .bg(move || theme().muted) .on_press(move || cx.emit(ChartEvent::Select(101.5))) .child(text(move || format!("{} · {}", props.symbol.get(), props.range.get()))) } /// A ledger kept in Rust. #[class] pub struct Ledger { entries: Vec, } #[class] impl Ledger { /// An empty ledger. pub fn new() -> Self { Ledger { entries: Vec::new() } } /// Adds `amount`; the new balance. pub fn add(&mut self, amount: f64) -> f64 { self.entries.push(amount); self.balance() } /// The balance. #[getter] pub fn balance(&self) -> f64 { self.entries.iter().sum() } /// Uploads the entries; resolves when the server has them. pub async fn upload(this: Instance, url: String) -> Result<(), String> { let body = this.with(|l| format!("{:?}", l.entries)); fetch(HttpRequest::post(url, body)).await.map(|_| ()) } } /// The app's holdings. #[module] pub struct Portfolio; #[module] impl Portfolio { /// The value of the holdings. pub fn total() -> f64 { 1250.0 } } ``` ```tsx import { mount, signal, View, Text } from "nsh"; import { Window } from "nsh/desktop"; import { Chart, Ledger, Portfolio } from "app/native"; // Rust const ledger = new Ledger(); // its state lives in Rust function Overview() { const balance = signal(ledger.add(Portfolio.total())); // Rust, called at once return ( Balance: {balance()} balance.set(ledger.add(e.price))} /> ledger.upload("https://example.com/ledger")} role="button" class="rounded-lg bg-blue-600 px-4 py-2 active:bg-blue-700"> Upload ); } mount(() => ( )); ``` Each export is documented in TypeScript by the doc comment of the Rust item that names it: a component by its `#[component] fn` (`Chart`), a module and a class by their struct (`Portfolio`, `Ledger`), and props, events, functions and members by their own (a setter needs none beside its getter). The `Props` struct's and the event enum's own doc comments, and those of `impl` blocks, stay in Rust; a doc comment on a `#[module]` or `#[class]` `impl` block is a compile error, since TypeScript would not show it. Each command that writes `.nsh/types` warns about an export TSX sees without a doc comment, naming it (`Ledger.add`, `Chart.range`). TypeScript shows a doc comment up to its first heading. Notes for Rust callers, such as what `&self` borrows or why a function takes `cx`, go under a heading, `# Rust` (or rustdoc's `# Panics`, `# Examples`), and stay in the Rust docs: ```rust /// Puts `text` on the clipboard; resolves with the number of characters copied. /// /// # Rust /// /// Taking `cx` makes it an op, run in order with the UI changes TS made before it. pub fn copy(text: String, cx: &mut ModuleCx) -> u32 { let count = text.chars().count() as u32; cx.set_clipboard(text); count } ``` Props are the fields of the component's `Props` struct and events the variants of its `Event` enum (`onSelect`), both in camel case. Rust code places the same component with its constructor, a setter per prop and a listener method per event: `chart().symbol("NSH").range("1M").on_select(move |price: &f64| last.set(*price))`. A Rust component's own content, events and state stay in Rust; TSX passes props in and hears events. A prop of the wrong type (`level={1.5}` for a `u32` prop) is a warning, as on a built-in element: the prop keeps its value and the rest of the component renders. A function or a member runs the way its Rust signature says. One that is not `async` runs inside the TSX call and returns its value (`Portfolio.total()` is a number, `ledger.balance` a property): it computes and keeps state. An `async fn` returns a Promise and runs as a task with NSH's services (`fetch`, `timer`, dialogs). A module function taking `cx: &mut ModuleCx` reaches the platform in order with the UI (a toast, the status bar) and may `spawn` a task, which runs to its end. A component's ref method also reaches the platform in order with the UI; their return type decides what TSX gets: one returning `()` gives `void`, with no reply (TSX calls it and moves on); one returning `Result<(), E>` gives `Promise`, which rejects with the `Err`'s message (the call runs with the UI's changes, after the TSX call returned, so the Promise carries its error; one nobody awaits or catches is logged as an [unhandled rejection](https://nsh.dev/versions/v0.7.1/docs/dev-server-and-debugging.md#logs)); one returning a value gives `Promise`. Arguments and results are typed from the signature: numbers, strings, `Option`, `Vec`, your `#[derive(JsObject)]` structs and `#[derive(PropEnum)]` enums, instances of your classes, and TSX functions (`Callback`, which Rust calls at once inside a call, or later with `post` and `call_async`; TS sees `(value: number) => void` for a `Callback`, and `#[args(balance)] listener: Callback` names the argument, `(balance: number) => void`). A function that starts listening is named `on(event, listener)` and returns `Stop` (`Stop::new(|| …)`), which TSX gets as a function that stops it (`() => void`); it runs once, when TSX calls it or when what called `on` goes (a component, or the module's run under hot reload). An event's handler gets one object: a variant's value is its field `value`, which `#[args(price)]` on the variant names (`onSelect({ price })`), and `#[args(open, reason)]` names the fields of a variant of several. An argument of the wrong type throws a `TypeError` in the call, or rejects the Promise of one that returns a Promise; an `Err` throws (or rejects) with its message. A class's object owns its Rust value: it is freed when the object is collected, or at once with `ledger.dispose()` (also `using ledger = new Ledger()`). Name the TSX entry to run it, `nsh run App.tsx` or `nsh package App.tsx --target …`: TSX edits are hot updates, Rust edits rebuild and restart the app. The CLI bundles and compiles the TSX itself, knowing your crate's exports from its description; the development hosts and `nsh test`'s headless runner are built with your crate and QuickJS. `examples/rust-exports` in the repository is the reference for exporting: a small TSX app whose crate exports one component (props required, defaulted and optional, an event, children), one module (a function of each kind) and one class (a constructor, methods, a getter and a setter, a static, an `async` member, another instance as an argument, a callback Rust posts to, `dispose()` and `using`), each with a short doc comment, and tests, in Rust and in TypeScript (`App.test.tsx`), that press through the app and check what each one shows. `examples/gallery-rs` in the repository is a complete Rust app: every demo is Rust, `nsh run examples/gallery-rs --target web` (or `ios`, `android`, …) runs its root, `nsh test examples/gallery-rs` runs its tests headless, and `cargo run -p gallery-native` starts it on the desktop backend. ### Render functions and the app's classes A component draws content of the app's for values it has (a row of its data, a code block of a document) with a render function: a prop `Option>`, in TypeScript `(value: T) => JSX.Element`. The component calls `render(key, value)` where the content goes and gets a view it styles and places as any other (inside a `text(..)`, an inline view). The content is kept per key while the value stays equal, and rendered again when it changes. A Rust parent passes a closure to the prop's setter (`quote().render_badge(|symbol| ..)`), which makes the `Renderer` of it. Styles in a component are typed; the app's Tailwind classes reach one of its parts through a prop of classes and `.app_class(..)` on that part's element. They apply after the element's own styles, with the app's theme, `dark:` and the states, as `class` on an element does. ```rust /// A quote: its symbol, then content of the app's. #[derive(Clone, Copy, PartialEq, Props)] pub struct QuoteProps { /// The symbol. pub symbol: Prop, /// Tailwind classes of the symbol's text. pub symbol_class: Prop>, /// Content of the app's after the symbol (a change, a badge). pub render_badge: Prop>>, } /// A quote of a symbol. #[component] pub fn Quote(props: QuoteProps) -> impl IntoElement { view() .flex_row() .items_center() .gap_2() .child(text(props.symbol).app_class(props.symbol_class)) .child(dynamic(move || { props.render_badge.get().map(|r| r.render("badge", props.symbol.get()).flex_1()) })) } ``` ```tsx {`${symbol} ▲ 2.4%`}} /> ``` `TextView` in `nsh/base` is built this way: its `renderCodeBlock`, `renderMath`, ... are render functions, and its `classes` are the app's classes by part ([TextView](https://nsh.dev/versions/v0.7.1/elements/text-view.md)). ## Testing A Rust app's tests run it headless, in `cargo test` or in `nsh test`, with the same driver: on the real engine, without a window, with display frames at 60 Hz, so timers, tasks and animations run as on screen. The driver starts the app, keeps a model of the views it shows and takes steps (`press`, `type_text`, `submit`, `scroll`, `wait_for`) on views named by selectors (a text, an accessibility label or a test id; `text:`, `label:`, `id:`); a step that cannot be taken fails with the texts on screen. In `cargo test`, `nsh_testing::Headless` (nsh-testing's default features, without QuickJS) runs the root (`app.screen()`: the texts on screen, the commands it sent); `EngineConfig::new` is a phone-sized engine with nothing else set. `nsh test` runs TypeScript tests ([Testing](https://nsh.dev/versions/v0.7.1/docs/testing-and-trace.md)) in a headless runner built with your crates, where `open(".")` starts a Rust app's root: ```toml [dev-dependencies] nsh-engine = "0.1" nsh-testing = "0.1" ``` ```tsx // App.test.tsx, next to nsh.json: nsh test import { expect, open, test } from "nsh/test"; test("a tap counts", async () => { const app = await open("."); await app.press("Tap"); expect(app.texts()).toContain("Count: 1"); }); ``` ```rust // tests/app.rs: cargo test use nsh_engine::{EngineConfig, Root}; use nsh_testing::Headless; #[test] fn a_tap_counts() { let mut app = Headless::start(EngineConfig::new(Root::of::())).unwrap(); app.wait_for("Count: 0").unwrap(); app.press("Tap").unwrap(); app.wait_for("Count: 1").unwrap(); } ``` Text is laid out with an estimate of its width (every character `0.55 ×` the font size) unless the test starts the app with `Headless::start_with_text_engine`, which takes a function making the platform's text engine on the engine's thread (`nsh_platform_macos::CoreTextEngine`, `nsh_platform_windows::DWriteTextEngine`), so text measures as it does on screen. `app.screen().layout_nodes()` returns the views on screen in tree order as layout placed them (`LayoutNode`: kind, test id, parent, bounds in the root's points before transforms, whether it is hidden or clips, a scroll view's axis and content size in `scroll`, a text view's text and the box it was laid out in in `text`), so a test can check that nothing passes its parent, is cut by a view that clips, or is too wide for its text. Both are Rust API of `nsh_testing`, for `cargo test`. A web app's routing is tested on its page: `Headless::start_at_page(config, "https://example.test/app/")` starts the app on the web at that address, and `app.browser()` is the browser around it, with the history the web keeps (an entry per page a stack pushes and per open dialog, the app's `set_app_url_with(url, HistoryBehavior::Push)` addresses) and the user's moves through it: `back()`, `forward()`, `go(delta)` and `type_address("#inbox")`, which the app hears as on the web (`next_app_url_change`, `next_url_scheme_open`); `entries()`, `index()` and `url()` read the history. ```rust let mut app = Headless::start_at_page(config, "https://example.test/app/").unwrap(); app.press("Message").unwrap(); // pushes a page and sets `?m=1` assert_eq!(app.browser().url(), Some("https://example.test/app/?m=1")); app.browser().back().unwrap(); // pops the page app.browser().type_address("#inbox").unwrap(); // an `Address` change ``` A TSX entry is built with `nsh-testing`'s feature `bundle` as `nsh run` builds it, against the UI sets its hosts serve: NSH's, and each crate's `registry()`, which `#[native_module]` makes: ```toml [dev-dependencies] nsh-testing = { version = "0.1", features = ["bundle"] } nsh-base = "0.1" ``` ```rust #[test] fn the_module_formats_money() { let sets = vec![nsh_base::registry(), my_app_native::registry()]; let mut app = nsh_testing::tsx("../App.tsx", sets).unwrap(); app.wait_for("Formatted at once: $1,234.50").unwrap(); } ``` `nsh_testing::compile_tsx` builds the entry once for several tests, and `nsh_testing::start` hands the batches to a test that keeps its own model of the screen. `examples/rust-exports` tests its TSX entry this way; `examples/gallery-rs` tests its Rust root in TypeScript, a test file for about each demo. ## Theme The look of an app is the app's own: NSH provides the primitives and the unstyled base components of `nsh_base`, and your crate is the styled layer on top, the app's own component library ([Three layers](https://nsh.dev/versions/v0.7.1/docs/architecture.md#three-layers)). Rust components take their colors, corner radius and fonts from a theme, `theme()` from `nsh_base`, so one file restyles every component of the app. Each color has a light and a dark value; when the system switches appearance, a binding such as `.bg(move || theme().primary)` changes color natively, with no render. The theme has the design tokens of [shadcn/ui](https://ui.shadcn.com/docs/theming), and its default is shadcn's `neutral` theme, a black-and-white palette with a 10 pt corner radius. To use your own, set `"theme"` in `nsh.json` to the path of a theme file, relative to `nsh.json`, or to the theme's content inline: ```json { "name": "My App", "rust": ".", "theme": "brand-theme.json" } ``` A theme file is shadcn's `cssVars`, the format of shadcn's themes and registry items, so a theme exported from [shadcn's themes](https://ui.shadcn.com/themes) or [tweakcn](https://tweakcn.com) works as it is. `light` sets the values of the light appearance, `dark` those of the dark one, and `theme` those of both: ```json { "cssVars": { "theme": { "radius": "0.5rem", "font-sans": "Inter, sans-serif" }, "light": { "primary": "oklch(0.541 0.281 293.009)", "primary-foreground": "oklch(0.969 0.016 293.756)", "ring": "var(--primary)", "up": "#16a34a" }, "dark": { "primary": "oklch(0.702 0.183 293.541)", "primary-foreground": "oklch(0.283 0.141 291.089)", "up": "#4ade80" } } } ``` - Your theme is applied over the default theme, so you list only what you change. A value `light` sets and `dark` leaves out is used in both appearances. - Values are written as in CSS. Colors are any CSS color (`#7c3aed`, `rgb(…)`, `hsl(…)`, `oklch(…)`, `white`), `color-mix(in oklab, var(--primary) 80%, white)`, or another token of the same appearance, `var(--primary)` (with a fallback: `var(--brand, #7c3aed)`). Lengths are `rem` (16 points) or `px` (points). Fonts are font family lists: the first family that is not a generic one is used, and a generic first family (`system-ui`, `sans-serif`) is the system font. - **Your own tokens.** Any other name is a token of the app, as a variable in Tailwind's `@theme` is: `"up"` above is `theme().color("up")` in Rust, `bg-up` / `text-up/70` in classes and `token("up")` in TSX ([Theme tokens](https://nsh.dev/versions/v0.7.1/docs/tailwind.md#theme-tokens)). A number such as `"radius-card": "14px"` is `theme().number("radius-card")` and `rounded-(--radius-card)`. - The bundler checks the theme when it builds: a missing file, invalid JSON or a theme other than `cssVars` fails the build with an `nsh.json: theme: …` error. The tokens, with their default light and dark values (shadcn's `neutral`): | Token | `theme()` | Light | Dark | Role | |---|---|---|---|---| | `background` / `foreground` | `background` / `foreground` | `oklch(1 0 0)` / `oklch(0.145 0 0)` | `oklch(0.145 0 0)` / `oklch(0.985 0 0)` | The app's background, and the text on it | | `card` / `card-foreground` | `card` / `card_foreground` | `oklch(1 0 0)` / `oklch(0.145 0 0)` | `oklch(0.205 0 0)` / `oklch(0.985 0 0)` | Cards and grouped surfaces, and the text on them | | `popover` / `popover-foreground` | `popover` / `popover_foreground` | `oklch(1 0 0)` / `oklch(0.145 0 0)` | `oklch(0.205 0 0)` / `oklch(0.985 0 0)` | Popovers, menus and tooltips, and the text on them | | `primary` / `primary-foreground` | `primary` / `primary_foreground` | `oklch(0.205 0 0)` / `oklch(0.985 0 0)` | `oklch(0.922 0 0)` / `oklch(0.205 0 0)` | The main action (a primary button), and the text on it | | `secondary` / `secondary-foreground` | `secondary` / `secondary_foreground` | `oklch(0.97 0 0)` / `oklch(0.205 0 0)` | `oklch(0.269 0 0)` / `oklch(0.985 0 0)` | Secondary actions, and the text on them | | `muted` / `muted-foreground` | `muted` / `muted_foreground` | `oklch(0.97 0 0)` / `oklch(0.556 0 0)` | `oklch(0.269 0 0)` / `oklch(0.708 0 0)` | Quiet surfaces; secondary text: captions, labels, placeholders | | `accent` / `accent-foreground` | `accent` / `accent_foreground` | `oklch(0.97 0 0)` / `oklch(0.205 0 0)` | `oklch(0.269 0 0)` / `oklch(0.985 0 0)` | A hovered or highlighted item, such as a menu item or list row, and its text | | `destructive` | `destructive` | `oklch(0.577 0.245 27.325)` | `oklch(0.704 0.191 22.216)` | Destructive actions and errors | | `border` | `border` | `oklch(0.922 0 0)` | `oklch(1 0 0 / 10%)` | Dividers and borders | | `input` | `input` | `oklch(0.922 0 0)` | `oklch(1 0 0 / 15%)` | The border of inputs | | `ring` | `ring` | `oklch(0.708 0 0)` | `oklch(0.556 0 0)` | Focus rings | | `chart-1` … `chart-5` | `chart_1` … `chart_5` | `oklch(0.87 0 0)` … `oklch(0.269 0 0)` | the same | The series of a chart | | `sidebar`, `sidebar-foreground`, `sidebar-primary`, `sidebar-primary-foreground`, `sidebar-accent`, `sidebar-accent-foreground`, `sidebar-border`, `sidebar-ring` | `sidebar`, `sidebar_foreground`, ... | `sidebar` `oklch(0.985 0 0)`, `sidebar-primary` `oklch(0.205 0 0)` | `sidebar` `oklch(0.205 0 0)`, `sidebar-primary` `oklch(0.488 0.243 264.376)` | A sidebar's surface, its main action, its highlighted item, borders and focus ring | | `radius` | `radius` | `0.625rem` (10 pt) | | The corner radius | | `font-sans` | `font_sans` | the system font | | The app's font: every text that sets no family of its own | | `font-mono` | `font_mono` | the system monospace font | | The monospaced font: `font-mono`, code in `TextView` | ## Several crates An app's Rust code can be split into crates, each imported by its own specifier: `"rust"` takes a list of crate paths, and each crate in it has its own `#[native_module]` function. ```json { "rust": ["native/charts", "native/storage"], "root": "App" } ``` ```tsx import { Chart } from "app/charts"; // native/charts: #[native_module("app/charts")] import { Store } from "app/storage"; // native/storage: #[native_module("app/storage")] ``` Every runner and host links all of them, and `.nsh/types` declares each specifier. Crates share code through Cargo path dependencies (`shared = { path = "../shared" }`): a crate of company components can be used by several crates and listed by several apps, and only the crates listed in `"rust"` export to TSX. Each listed crate has a package name and a specifier of its own; `nsh` reports a repeated one with the two paths that share it. A Rust app's `"root"` is a component of the first crate listed. During `nsh run` and `nsh dev`, a change to any of them, or to a crate they depend on by path, rebuilds the app and restarts it. ## Browser APIs on the web On the web, a crate can call the browser's APIs (a WebSocket, `IndexedDB`, …) through wasm-bindgen and `web-sys`; `nsh` builds the glue they need with the runtime. See [Web](https://nsh.dev/versions/v0.7.1/docs/web.md#browser-apis-from-rust). ## See also - [Project structure](https://nsh.dev/versions/v0.7.1/docs/project-structure.md): every key of `nsh.json`. - [Web](https://nsh.dev/versions/v0.7.1/docs/web.md#apps-with-rust-components): Rust apps in the browser. - [Networking](https://nsh.dev/versions/v0.7.1/docs/networking.md#from-rust-components): `fetch` from Rust. - [CLI](https://nsh.dev/versions/v0.7.1/docs/cli.md#nsh-init): `nsh init --template rust` and `--template mixed`. Source: https://nsh.dev/versions/v0.7.1/docs/rust --- # CLI `nsh` is the tool an NSH app is built with, in TSX or Rust. Every subcommand that builds an app takes `[ENTRY]`: the app's directory (default: the current one, so `cd my-app && nsh run` works), which runs a Rust app's root component (`nsh.json` `"root"`) or a TSX app's `App.tsx`, or a TSX entry module. It reads `nsh.json` in the app's root and refreshes the type declarations in `.nsh/types`. ```text nsh init Create an app in Rust or TSX build Build an app: describe a Rust app's crates, or bundle a TSX app and compile it to QuickJS bytecode test Run an app's tests headless, and its Rust crates' with cargo test check Type check an app with TypeScript's native compiler, and its Rust crates with cargo check dev Serve an app to dev hosts (simulators, devices) and push rebuilds run Like dev, and also run the app in a development host package Package an installable app from the prebuilt runtime keygen Create a signing key certify Certify a release key with a root key publish Build an app in release mode and sign it into a package (.nshpkg) verify Verify a package symbolicate Map the positions in a reported error stack to the app's sources revoke Sign a revocation list ``` `nsh --help` prints the flags of a command; `nsh -V` (`--version`) prints the version and the Git revision it was built from. ## Output Every command prints one line per step, and the details only when something fails: ```text ✓ built the Rust crate gallery-native (5.0s) ✓ built App.tsx (500 B js, 809 B bytecode, 21ms) ✓ built the development host for the iOS simulator (12.7s) • iOS Simulator (iPhone 16 Plus) connected, build 1 warn iOS Simulator: image failed: An SSL error has occurred and a secure connection to the server cannot be made. ✓ rebuilt App.tsx (18ms), 1 device ``` `✓` is a finished step, `→` where to connect, `•` what a device did; `warn` and `error` lines are problems, and plain lines are your app's own output (`console.log`). On a terminal a spinner shows the step that is running, and lines are colored (unless `NO_COLOR` is set); redirected to a file, only the result lines are written, without colors. The output of the tools NSH runs (cargo for an app's Rust crate, the development hosts) is printed below an `error` line when one of them fails. `-v, --verbose` (any command; also `NSH_VERBOSE=1`) prints everything as it comes: every log line with its level and source, cargo's output and the hosts' own. ## nsh init ```sh nsh init [DIR] [--name ] [--template ] [--nsh-source ] ``` Creates an app in `DIR` (default: the current directory, created if missing) from a template. Without `--template`, `nsh init` asks which one on a terminal (Enter picks `ts`) and takes `ts` elsewhere (a script, CI). | Template | What it creates | |---|---| | `rust` | An app written in Rust: a Cargo project (`Cargo.toml`, `src/lib.rs` with the root component, `src/main.rs` for `cargo run`), `nsh.json` with `"rust": "."` and `"root": "App"`, the root's test `App.test.tsx` with `tsconfig.json` and `.nsh/types`, `.gitignore` and a README, which also says how to add a TSX entry later. `nsh run` and `nsh package` mount the root with no QuickJS on every target (`nsh test` opens it for TypeScript tests), the browser included ([Building with Rust](https://nsh.dev/versions/v0.7.1/docs/rust.md)); `cargo run` starts it on macOS, Windows or Linux directly. | | `ts` | A TSX app: `App.tsx`, its test `App.test.tsx` (`nsh test`), `nsh.json`, `tsconfig.json`, `.gitignore` and `.nsh/types`. Files that exist are kept; it fails only if all of them exist already. | | `mixed` | A TSX app extended with Rust in `ext/`: `App.tsx`, its test `App.test.tsx`, `tsconfig.json`, `.gitignore`, `.nsh/types`, a README, and an nshm crate of the app's own in `ext/-native/` (`Cargo.toml`, `src/lib.rs`), which `nsh.json` lists in `"dependencies"` by path and whose `#[native_module("-native")]` exports a component, a module and a class that `App.tsx` uses ([An app's own Rust: ext/](https://nsh.dev/versions/v0.7.1/docs/nshm.md#an-apps-own-rust-ext)). | | Flag | Description | |---|---| | `--name ` | Display name written to `nsh.json`. Default: the directory's name. The id becomes `com.example.` (letters and digits only, lower case), and the crates' import specifier `/native` (lower case, words joined by `-`). | | `--template