# `@effect/ui-opentui` OpenTUI vocabulary, terminal host, global Subscriptions, imperative Commands, and test harnesses for building terminal applications with `effect/ui`. ## Requirements - Peer dependencies: `effect`, `@opentui/core` (`^0.9.9`) - Runtime: **Node 26.4+** with `--experimental-ffi`, or **Bun 1.3.14+** (no flag required) ## Modules - `OpenTui`: `OpenTui.component`, `OpenTui.H`, element vocabulary (`box`, `scrollbox`, `lineNumber`, `text`, `span`, `b`, `i`, `u`, `a`, `br`, `input`, `textarea`, `select`, `tabSelect`, `slider`, `code`, `diff`, `markdown`, `asciiFont`), plain-data event payloads, `OpenTui.Host`, and `OpenTui.ref` - `OpenTuiHost`: `makeHost`, `layer`, `layerFromRenderer`, `mount`, `mountEffect`, and `run` - `OpenTuiSubscription`: global `onKeyPress`, `onKeyRelease`, `shortcuts`, `onPaste`, and `onResize` - `OpenTuiKeyboard`: pure shortcut table matcher over `OpenTui.KeyPayload` - `OpenTuiCommand`: ref commands (`focus`, `blur`, `scrollTo`, `scrollBy`, `measure`), `quit`, and clipboard commands (`writeClipboardText`, `readClipboardText`, `clearClipboard`) - `@effect/ui-opentui/testing`: `OpenTuiPlay` (FFI-free interaction tests with focus tracking and global key routing), `TestOpenTuiEvents` (FFI-free `TestHost` fakes) and `OpenTuiTest` (native frame-rendering harness over `@opentui/core/testing`) ## A terminal app `OpenTui.component` puts the OpenTUI tags on `h`. Everything else, such as Models, `update`, Commands and queries, works as it does in the browser. ```ts const Message = UiSchema.TaggedEnum({ UpdatedDraft: { value: Schema.String }, SubmittedDraft: {}, ChangedSelection: { index: Schema.Number }, SwitchedFocus: {}, RequestedCopy: {}, CompletedCopy: { status: Schema.Literals(["written", "sent", "unsupported", "failed"]) }, RequestedQuit: {} }) export const TaskBoard = OpenTui.component({ name: "TaskBoard", model: Schema.Struct({ draft: Schema.String, items: Schema.Array(Schema.String), selected: Schema.Number, focus: Schema.Literals(["input", "list"]) }), message: Message }).make({ init: () => ({ draft: "", items: [], selected: 0, focus: "input" as const }), update: { UpdatedDraft: ($, { value }) => $.evolve({ draft: value }), SubmittedDraft: ($) => $.model.draft.trim() === "" ? $.model : $.evolve({ draft: "", items: (items) => [...items, $.model.draft.trim()] }), ChangedSelection: ($, { index }) => $.evolve({ selected: index }), SwitchedFocus: ($) => $.evolve({ focus: (f) => (f === "input" ? "list" : "input") }), RequestedCopy: ($) => $.run(OpenTuiCommand.writeClipboardText( $.model.items[$.model.selected] ?? "", ({ status }) => Message.CompletedCopy({ status }) )), CompletedCopy: ($) => $.model, RequestedQuit: ($) => $.run(OpenTuiCommand.quit()) }, subscriptions: () => [ OpenTuiSubscription.shortcuts([ { key: "tab", message: Message.SwitchedFocus(), whileTyping: true }, { key: "c", message: Message.RequestedCopy() }, { key: "q", message: Message.RequestedQuit() } ]) ], head: ({ model }) => [Head.title(`Tasks (${model.items.length})`)], view: (h, model) => h.box.style({ border: true, flexDirection: "column", padding: 1 }).title("Tasks").children( h.input.placeholder("New task...").value(model.draft) .focused(model.focus === "input") .on("input", ({ value }) => Message.UpdatedDraft({ value })) .on("enter", Message.SubmittedDraft()), h.select.style({ height: 6 }) .options(model.items.map((name) => ({ name, description: "" }))) .selectedIndex(model.selected) .focused(model.focus === "list") .on("selectionChanged", ({ index }) => Message.ChangedSelection({ index })), h.text(h.b("Tab"), " focus ", h.b("c"), " copy ", h.b("q"), " quit") ) }) OpenTuiHost.run(TaskBoard, {}).pipe(NodeRuntime.runMain) ``` - Text goes in `h.text(...)` or an inline modifier (`h.span`, `h.b`, `h.i`, `h.u`, `h.a`). Layout containers such as `h.box` and `h.scrollbox` reject raw strings, at compile time and at runtime. - `value`, `selectedIndex` and `focused` are controlled. Keep focus in the Model: the host blurs before it focuses, so exactly one element ends up focused. - `options` arrays are compared by value, so a fresh array on each render doesn't reset the `select`. - `OpenTuiSubscription.shortcuts` runs before the focused element sees a key and cancels the keys it matches. Shortcuts are skipped while an editor such as `input` is focused, so typing `q` there types a `q`. Set `whileTyping: true` for keys like Tab that should work anyway. - `OpenTuiHost.run` owns the `CliRenderer` and completes once it is destroyed: Ctrl+C, an exit signal, or `OpenTuiCommand.quit()`. That closes the application Scope. - `Head.title` sets the terminal window title. `writeClipboardText` never fails; its `status` says whether the host clipboard confirmed the write (`written`) or it went over OSC 52 unconfirmed (`sent`). - Ref Commands (`OpenTuiCommand.focus`, `scrollTo`, `measure`, ...) take an `OpenTui.ref` for what the Model can't express. ## Screens with Back A terminal app drills down: Enter opens a row, Esc goes back. Routes and `Router` Commands work as on the web, and `RouterStack` keeps each history entry as a screen. ```ts const IssueRoute = Route.union({ Issues: Route.make("/"), Issue: Route.make("/issues/:id", { params: { id: Schema.Number } }) }) // IssueList and IssuePage are ordinary OpenTui components. const TrackerMessage = UiSchema.TaggedEnum({ Navigated: { navigation: RouterStack.Navigation(IssueRoute) }, PressedEscape: {} }) export const IssueTracker = OpenTui.component({ name: "IssueTracker", props: Schema.Struct({ stack: RouterStack.Stack(IssueRoute) }), model: RouterStack.Stack(IssueRoute), message: TrackerMessage }).make({ init: ($) => $.props.stack, update: { Navigated: ($, { navigation }) => $.set(RouterStack.follow(IssueRoute, $.model, navigation)), PressedEscape: ($) => $.run($.model.length > 1 ? Router.Back.make().pipe(Command.asNoop) : OpenTuiCommand.quit()) }, subscriptions: ({ model }) => [ RouterStack.subscription(IssueRoute, model, (navigation) => TrackerMessage.Navigated({ navigation })), OpenTuiSubscription.shortcuts([{ key: "escape", message: TrackerMessage.PressedEscape() }]) ], view: (h, stack) => h.box.children(RouterStack.Screens(h, { entries: stack, screen: (s, { route }, covered) => s.el("box").prop("visible", !covered).children( IssueRoute.match(route, { Issues: () => IssueList(s, { key: "issues" }), Issue: ({ params }) => IssuePage(s, { key: "issue", props: params }) }) ) })) }) OpenTuiHost.run(IssueTracker, RouterStack.props(IssueRoute)).pipe( Effect.provide(RouterStack.layer({ routes: IssueRoute, url: process.argv[2] })), NodeRuntime.runMain ) ``` `RouterStack.Screens` draws a screen for every entry and passes `covered` to all but the top one. Hiding a covered screen with `.prop("visible", !covered)` keeps it mounted, so Back shows the list with its focus, selection and scroll offset intact. A covered screen's Subscriptions keep running, but it gets no keys or pastes while hidden. There is no address bar: the first URL comes from the command line (`issues /issues/2`), and one the routes don't parse starts at `/`. ## Testing `TestHost` with `TestOpenTuiEvents.layer` runs a component without loading OpenTUI's native library. `TestOpenTuiEvents.pressKey` fires a key press at the global listeners, so shortcuts run: ```ts export const unit = Effect.gen(function*() { const root = yield* TestHost.mount(TaskBoard, {}) yield* TestHost.settle yield* TestOpenTuiEvents.pressKey("tab", { editable: true }) yield* TestHost.settle return root.model()?.focus // "list" }).pipe(Effect.provide(Layer.merge(TestHost.layer(), TestOpenTuiEvents.layer)), Effect.scoped) ``` `OpenTuiPlay` drives interactions on the same FFI-free host and tracks focus. Keys reach global listeners before the focused element, and a cancelled key never reaches it. Widget key handling isn't simulated: use `fire` for an input's `enter` and `select` to choose an option. ```ts export const play = Effect.gen(function*() { const play = yield* OpenTuiPlay.make(TaskBoard, {}) yield* play.type("Ship it") yield* play.fire(Locator.tag("input"), "enter", { value: "Ship it" }) yield* play.pressKey("tab") yield* play.expect(Locator.tag("select")).toBeFocused() }).pipe(Effect.provide(TestHost.layer()), Effect.scoped) ``` `OpenTuiTest.mount` renders on `@opentui/core/testing` and returns character frames, so it needs FFI (Node with `--experimental-ffi`, or Bun). Clipboard Commands write to an in-memory clipboard, `app.clipboard`. ```ts export const frame = Effect.gen(function*() { const app = yield* OpenTuiTest.mount(TaskBoard, {}, { width: 54, height: 14 }) yield* app.typeText("Ship it") yield* app.pressEnter yield* app.pressKey("\t") yield* app.pressKey("c") return { frame: app.captureFrame(), copied: app.clipboard.get("clipboard") } }).pipe(Effect.scoped) ``` ## Examples The Effect-TS/ui repository has two runnable terminal apps, written before the package moved here (they import `@effect/ui` rather than `effect/ui`): [`snake-tui`](https://github.com/Effect-TS/ui/tree/main/examples/snake-tui), a port of the browser Snake game that shares its logic, and [`routing-tui`](https://github.com/Effect-TS/ui/tree/main/examples/routing-tui), an issue tracker with screens and Back.