### Install OpenTUI Examples (macOS, Linux, WSL, Git Bash) Source: https://github.com/anomalyco/opentui/blob/main/README.md Download and install the OpenTUI examples script for Unix-like systems. This allows you to quickly try out OpenTUI examples without cloning the repository. ```bash curl -fsSL https://raw.githubusercontent.com/anomalyco/opentui/main/packages/examples/install.sh | sh ``` -------------------------------- ### Run Development Example Source: https://github.com/anomalyco/opentui/blob/main/packages/core/README.md Install dependencies, navigate to the examples directory, and run the development server. ```bash bun install cd ../examples bun run dev ``` -------------------------------- ### Running TypeScript Examples Source: https://github.com/anomalyco/opentui/blob/main/README.md Install dependencies, navigate to the examples directory, and run the development server for TypeScript examples. ```bash bun install cd packages/examples bun run dev ``` -------------------------------- ### Run OpenTUI Examples Source: https://github.com/anomalyco/opentui/blob/main/packages/core/docs/development.md Navigate to the examples directory and run the development server using Bun. This is useful for previewing example applications. ```bash cd packages/examples bun run dev ``` -------------------------------- ### Install OpenTUI Dependencies Source: https://github.com/anomalyco/opentui/blob/main/packages/core/docs/development.md Clone the repository and install project dependencies using Bun. This is a standard setup step for new local development. ```bash git clone https://github.com/anomalyco/opentui.git cd opentui bun install ``` -------------------------------- ### Install @opentui/react with bun Source: https://github.com/anomalyco/opentui/blob/main/packages/react/README.md Quickly start a new TUI project using bun and the create-tui tool with the React template. ```bash bun create tui --template react ``` -------------------------------- ### Load and Play Sound File Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/audio.mdx Demonstrates basic audio setup, error handling, loading a sound file, and playing it. Ensure the audio engine is started before playing sounds. The engine will be disposed of after use. ```typescript import { Audio } from "@opentui/core" const audio = Audio.create({ autoStart: false }) audio.on("error", (error, context) => { console.error(`${context.action}: ${error.message}`) }) const sound = await audio.loadSoundFile("click.wav") if (sound != null && audio.start()) { audio.play(sound, { volume: 0.8, pan: 0, loop: false }) } audio.dispose() ``` -------------------------------- ### Install OpenTUI Core Source: https://github.com/anomalyco/opentui/blob/main/packages/core/README.md Install the OpenTUI Core package using Bun. ```bash bun install @opentui/core ``` -------------------------------- ### ASCIIFont Example: Welcome Screen Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/ascii-font.mdx An example demonstrating how to use ASCIIFont within a Box component to create a welcome screen with decorative titles. ```APIDOC ## Example: Welcome Screen ```typescript import { Box, ASCIIFont, Text, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() const welcomeScreen = Box( { width: "100%", height: "100%", flexDirection: "column", alignItems: "center", justifyContent: "center", }, ASCIIFont({ text: "OPENTUI", font: "huge", color: "#00FFFF", }), Text({ content: "Terminal UI Framework", fg: "#888888", }), Text({ content: "Press any key to continue...", fg: "#444444", }), ) renderer.root.add(welcomeScreen) ``` ``` -------------------------------- ### Welcome Screen Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/ascii-font.mdx A comprehensive example demonstrating how to create a welcome screen using Box, ASCIIFont, and Text components. This snippet shows centering content and applying different styles. ```typescript import { Box, ASCIIFont, Text, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() const welcomeScreen = Box( { width: "100%", height: "100%", flexDirection: "column", alignItems: "center", justifyContent: "center", }, ASCIIFont({ text: "OPENTUI", font: "huge", color: "#00FFFF", }), Text({ content: "Terminal UI Framework", fg: "#888888", }), Text({ content: "Press any key to continue...", fg: "#444444", }), ) renderer.root.add(welcomeScreen) ``` -------------------------------- ### Install QR Code Package Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/qr-code.mdx Install the QR code package separately using bun. ```bash bun install @opentui/qrcode ``` -------------------------------- ### Quick Start with create-tui Source: https://github.com/anomalyco/opentui/blob/main/README.md Use this command to quickly set up a new OpenTUI project with bun. ```bash bun create tui ``` -------------------------------- ### Install Native Packages for Multi-Platform Builds Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/reference/standalone-executables.mdx Before compiling multi-platform release builds, install optional native packages for all target operating systems and CPU architectures using `bun install`. ```shell bun install --os="*" --cpu="*" @opentui/core@ ``` -------------------------------- ### Basic Usage Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/keymap/solid.mdx Demonstrates how to set up the KeymapProvider, use the useBindings hook to define commands and keybindings, and render a simple Solid component. ```APIDOC ## Basic Usage ```tsx import { createCliRenderer } from "@opentui/core" import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import { KeymapProvider, useBindings } from "@opentui/keymap/solid" import { render } from "@opentui/solid" const renderer = await createCliRenderer() const keymap = createDefaultOpenTuiKeymap(renderer) function App() { useBindings(() => ({ commands: [ { name: "quit", run() { renderer.destroy() }, }, ], bindings: [{ key: "q", cmd: "quit" }], })) return Press q to quit } await render( () => ( ), renderer, ) ``` ``` -------------------------------- ### Install OpenTUI Solid.js Source: https://github.com/anomalyco/opentui/blob/main/packages/solid/README.md Install the necessary packages for Solid.js support. This includes solid-js and the OpenTUI Solid.js library. ```bash bun install solid-js @opentui/solid ``` -------------------------------- ### Example: Login Form with Input Components Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/input.mdx A comprehensive example showcasing the use of Input components within a login form, including tab navigation. ```APIDOC ## Example: Login Form with Input Components ### Usage ```typescript import { Box, Text, Input, delegate, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() function LabeledInput(props: { id: string; label: string; placeholder: string }) { return delegate( { focus: `${props.id}-input` }, Box( { flexDirection: "row", marginBottom: 1 }, Text({ content: props.label.padEnd(12), fg: "#888888" }), Input({ id: `${props.id}-input`, placeholder: props.placeholder, width: 20, backgroundColor: "#222", focusedBackgroundColor: "#333", textColor: "#FFF", cursorColor: "#0F0", }), ), ) } const usernameInput = LabeledInput({ id: "username", label: "Username:", placeholder: "Enter username", }) const passwordInput = LabeledInput({ id: "password", label: "Password:", placeholder: "Enter password", }) const form = Box( { width: 40, borderStyle: "rounded", title: "Login", padding: 1, }, usernameInput, passwordInput, ) // Focus the username input usernameInput.focus() renderer.root.add(form) ``` ### Tab Navigation Add tab navigation between inputs: ```typescript const inputs = [usernameInput, passwordInput] let focusIndex = 0 renderer.keyInput.on("keypress", (key) => { if (key.name === "tab") { focusIndex = (focusIndex + 1) % inputs.length inputs[focusIndex].focus() } }) ``` ``` -------------------------------- ### Register External Plugin with Bun Runtime Support Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/plugins/react.mdx Example of loading a plugin from a file path and registering it after ensuring Bun runtime support is installed. ```typescript import "@opentui/react/runtime-plugin-support" const mod = await import(pathToFileURL(pluginPath).href) registry.register(mod.loadExternalPlugin()) ``` -------------------------------- ### Install OpenTUI Keymap Package Source: https://github.com/anomalyco/opentui/blob/main/packages/keymap/README.md Install the OpenTUI keymap package using Bun. This command fetches and installs the necessary dependencies for the keymap functionality. ```bash bun install @opentui/keymap ``` -------------------------------- ### Install OpenTUI React Bindings Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/bindings/react.mdx Install the necessary OpenTUI packages for React development using Bun. ```bash bun install @opentui/react @opentui/core react ``` -------------------------------- ### Install OpenTUI with Bun Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/getting-started.mdx Use these commands to set up a new project and install the OpenTUI core package. Currently, Bun is the exclusive package manager. ```bash mkdir my-tui && cd my-tui bun init -y bun add @opentui/core ``` -------------------------------- ### Install Bun Runtime Support Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/plugins/core.mdx Import this once in your app entry to install Bun runtime support for @opentui/core and default entrypoints. ```ts import "@opentui/core/runtime-plugin-support" ``` -------------------------------- ### Styling Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/select.mdx Provides an example of how to apply custom styles to the Select component, including background colors and text colors for different states. ```APIDOC ## Styling ### Description Custom styles can be applied to the `SelectRenderable` component during initialization to control its appearance, including colors for backgrounds, text, and descriptions in various states (normal, focused, selected). ### Example ```typescript const styledMenu = new SelectRenderable(renderer, { id: "styled-menu", width: 40, height: 10, options: [...], backgroundColor: "#1a1a1a", selectedBackgroundColor: "#333366", selectedTextColor: "#FFFFFF", textColor: "#AAAAAA", descriptionColor: "#666666", }) ``` ``` -------------------------------- ### Status Bar Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/text.mdx A comprehensive example demonstrating the use of Text, Box, and styling utilities to create a status bar. ```APIDOC ## Example: Status Bar ### Description This example showcases how to combine `Text` components with `Box` and styling utilities like `t`, `bold`, and `fg` to create a functional status bar at the bottom of the screen. ### Request Example ```typescript import { Text, Box, t, bold, fg } from "@opentui/core" const statusBar = Box( { position: "absolute", bottom: 0, width: "100%", height: 1, backgroundColor: "#333333", flexDirection: "row", justifyContent: "space-between", paddingLeft: 1, paddingRight: 1, }, Text({ content: t`${bold("myfile.ts")} - ${fg("#888888")("TypeScript")}`, }), Text({ content: t`Ln ${fg("#00FF00")("42")}, Col ${fg("#00FF00")("15")}`, }), ) renderer.root.add(statusBar) ``` ``` -------------------------------- ### Interactive Counter Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/bindings/solid.mdx A basic counter example demonstrating state management with `createSignal` and handling keyboard input with `useKeyboard`. The counter can be incremented/decremented with Up/Down keys, and the app can be closed with the ESC key. Requires importing `render`, `useKeyboard`, and `useRenderer` from '@opentui/solid' and `createSignal` from 'solid-js'. ```tsx import { render, useKeyboard, useRenderer } from "@opentui/solid" import { createSignal } from "solid-js" const App = () => { const [count, setCount] = createSignal(0) const renderer = useRenderer() useKeyboard((key) => { if (key.name === "up") setCount((c) => c + 1) if (key.name === "down") setCount((c) => c - 1) if (key.name === "escape") renderer.destroy() }) return ( Count: {count()} Up/Down to change, ESC to close ) } render(App) ``` -------------------------------- ### Create a Basic Solid.js App Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/bindings/solid.mdx A minimal example of a Solid.js application using OpenTUI's render function. ```tsx import { render } from "@opentui/solid" const App = () => Hello, World! render(App) ``` -------------------------------- ### Basic Console Overlay Usage Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/console.mdx Demonstrates how to initialize the CLI renderer with the console overlay enabled and shows examples of logging different message types. ```typescript import { createCliRenderer, ConsolePosition } from "@opentui/core" const renderer = await createCliRenderer({ consoleOptions: { position: ConsolePosition.BOTTOM, sizePercent: 30, }, }) // These appear in the overlay instead of stdout console.log("This appears in the overlay") console.error("Errors are color-coded red") console.warn("Warnings appear in yellow") ``` -------------------------------- ### Login Form Example with Inputs Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/input.mdx Constructs a simple login form with username and password inputs using the LabeledInput helper component. It demonstrates delegation for focus management. ```typescript import { Box, Text, Input, delegate, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() function LabeledInput(props: { id: string; label: string; placeholder: string }) { return delegate( { focus: `${props.id}-input` }, Box( { flexDirection: "row", marginBottom: 1 }, Text({ content: props.label.padEnd(12), fg: "#888888" }), Input({ id: `${props.id}-input`, placeholder: props.placeholder, width: 20, backgroundColor: "#222", focusedBackgroundColor: "#333", textColor: "#FFF", cursorColor: "#0F0", }), ), ) } const usernameInput = LabeledInput({ id: "username", label: "Username:", placeholder: "Enter username", }) const passwordInput = LabeledInput({ id: "password", label: "Password:", placeholder: "Enter password", }) const form = Box( { width: 40, borderStyle: "rounded", title: "Login", padding: 1, }, usernameInput, passwordInput, ) // Focus the username input usernameInput.focus() renderer.root.add(form) ``` -------------------------------- ### Quick Start React App Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/bindings/react.mdx A basic React component rendered into the terminal using OpenTUI's core and React bindings. ```tsx import { createCliRenderer } from "@opentui/core" import { createRoot } from "@opentui/react" function App() { return Hello, world! } const renderer = await createCliRenderer() createRoot(renderer).render() ``` -------------------------------- ### Building a Login Form with React and OpenTUI Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/bindings/react.mdx This example demonstrates creating an interactive login form using React hooks like `useState` and `useKeyboard`, along with OpenTUI components. ```tsx import { createCliRenderer } from "@opentui/core" import { createRoot, useKeyboard } from "@opentui/react" import { useCallback, useState } from "react" function App() { const [username, setUsername] = useState("") const [password, setPassword] = useState("") const [focused, setFocused] = useState<"username" | "password">("username") const [status, setStatus] = useState("idle") useKeyboard((key) => { if (key.name === "tab") { setFocused((prev) => (prev === "username" ? "password" : "username") } }) const handleSubmit = useCallback(() => { if (username === "admin" && password === "secret") { setStatus("success") } else { setStatus("error") } }, [username, password]) return ( Login Form {status.toUpperCase()} ) } const renderer = await createCliRenderer() createRoot(renderer).render() ``` -------------------------------- ### Tree-sitter Parser Configuration Example Source: https://github.com/anomalyco/opentui/blob/main/packages/core/src/lib/tree-sitter/assets/README.md Defines the structure for a Tree-sitter parser configuration file, specifying filetype, WASM URL, and query file URLs. ```json { "parsers": [ { "filetype": "python", "wasm": "https://github.com/tree-sitter/tree-sitter-python/releases/download/v0.20.4/tree-sitter-python.wasm", "queries": { "highlights": [ "https://raw.githubusercontent.com/tree-sitter/tree-sitter-python/refs/heads/master/queries/highlights.scm" ] } } ] } ``` -------------------------------- ### Install AI Agent Skill for OpenTUI Source: https://github.com/anomalyco/opentui/blob/main/README.md Add the OpenTUI skill to your AI coding assistant using npx skills. This command can be used for universal installation or global installation. ```bash npx skills add anomalyco/opentui --skill opentui ``` ```bash npx skills add anomalyco/opentui --skill opentui -g ``` -------------------------------- ### Basic Solid Keymap Integration Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/keymap/solid.mdx Demonstrates setting up the `KeymapProvider` and using `useBindings` to register commands and key bindings within a Solid application. Ensure the OpenTUI renderer and keymap are initialized before rendering. ```tsx import { createCliRenderer } from "@opentui/core" import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import { KeymapProvider, useBindings } from "@opentui/keymap/solid" import { render } from "@opentui/solid" const renderer = await createCliRenderer() const keymap = createDefaultOpenTuiKeymap(renderer) function App() { useBindings(() => ({ commands: [ { name: "quit", run() { renderer.destroy() }, }, ], bindings: [{ key: "q", cmd: "quit" }], })) return Press q to quit } await render( () => ( ), renderer, ) ``` -------------------------------- ### HTML Host - Basic Usage Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/keymap/hosts.mdx Demonstrates the basic usage of the HTML host package by creating a default keymap host and registering a simple command binding for toggling help. ```APIDOC ## HTML Host - Basic Usage ### Description This example shows how to initialize the HTML keymap host and register a custom key binding. ### Method ```ts import { createDefaultHtmlKeymap } from "@opentui/keymap/html" const root = document.getElementById("app")! const keymap = createDefaultHtmlKeymap(root) keymap.registerLayer({ commands: [ { name: "toggle-help", run() { document.body.classList.toggle("help-open") }, }, ], bindings: [{ key: "?", cmd: "toggle-help" }], }) ``` ### Notes - `createDefaultHtmlKeymap(root)` initializes a keymap host attached to the specified root element. - `registerLayer` is used to define custom commands and their key bindings. - The example registers a `toggle-help` command that adds or removes the `help-open` class from the document body when the `?` key is pressed. ``` -------------------------------- ### Link OpenTUI with Options Source: https://github.com/anomalyco/opentui/blob/main/packages/core/docs/development.md Demonstrates linking OpenTUI with various options like including React or SolidJS dependencies, linking built distributions, or copying files instead of symlinking. ```bash # Link core only ./scripts/link-opentui-dev.sh /path/to/your/project # Link core and solid with subdependency discovery ./scripts/link-opentui-dev.sh /path/to/your/project --solid --subdeps # Link built artifacts ./scripts/link-opentui-dev.sh /path/to/your/project --react --dist # Copy for Docker/Windows ./scripts/link-opentui-dev.sh /path/to/your/project --dist --copy ``` -------------------------------- ### Compile and Run Zig Benchmarks Source: https://github.com/anomalyco/opentui/blob/main/packages/core/src/zig/bench/README.md Alternatively, compile and run benchmarks directly from the Zig build system in the packages/core/src/zig directory. Use the -Doptimize=ReleaseFast flag for optimized builds and -- --mem to include memory statistics. ```bash zig build bench -Doptimize=ReleaseFast ``` ```bash zig build bench -Doptimize=ReleaseFast -- --mem ``` -------------------------------- ### Select Component Usage Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/select.mdx Demonstrates how to create and render a basic Select component with options and descriptions. ```APIDOC ## Select Component Usage ### Description This example shows how to initialize and display a `Select` component within a `Box` container, setting its dimensions and defining a list of options with associated descriptions. ### Usage ```typescript import { Box, Select, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() const fileMenu = Select({ width: 25, height: 12, options: [ { name: "New", description: "Create new file (Ctrl+N)" }, { name: "Open...", description: "Open file (Ctrl+O)" }, { name: "Save", description: "Save file (Ctrl+S)" }, { name: "Save As...", description: "Save with new name" }, { name: "---", description: "" }, // Separator (visual only) { name: "Exit", description: "Quit application (Ctrl+Q)" }, ], }) const menuPanel = Box( { borderStyle: "single", borderColor: "#666", }, fileMenu, ) fileMenu.focus() renderer.root.add(menuPanel) ``` ``` -------------------------------- ### Instantiate Keymap with Custom Host Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/keymap/hosts.mdx Import Keymap and KeymapHost, then construct the Keymap engine with your custom host implementation. Ensure your host provides conservative metadata, using 'unknown' for unproven capabilities. ```typescript import { Keymap, type KeymapHost } from "@opentui/keymap" const keymap = new Keymap(host as KeymapHost) ``` -------------------------------- ### Install C++ Runtime Libraries on Alpine Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/reference/standalone-executables.mdx For Bun's Linux musl standalone runtime on Alpine, install the standard C++ runtime libraries using `apk add`. ```shell apk add --no-cache libstdc++ libgcc ``` -------------------------------- ### Start and stop continuous rendering Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/renderer.mdx Call `start()` to enable continuous rendering at the target FPS and `stop()` to halt the render loop. This mode is useful for animations or dynamic UIs. ```typescript renderer.start() // Start continuous rendering renderer.stop() // Stop the render loop ``` -------------------------------- ### Basic OpenTUI Keymap Usage in React Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/keymap/react.mdx Demonstrates the basic setup for using OpenTUI keymaps in a React application. It includes setting up the renderer, keymap, and defining a simple command with a key binding using the `useBindings` hook within a `KeymapProvider`. ```tsx /** @jsxImportSource @opentui/react */ import { createCliRenderer } from "@opentui/core" import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import { KeymapProvider, useBindings } from "@opentui/keymap/react" import { createRoot } from "@opentui/react" const renderer = await createCliRenderer() const keymap = createDefaultOpenTuiKeymap(renderer) function App() { useBindings( () => ({ commands: [ { name: "quit", run() { renderer.destroy() }, }, ], bindings: [{ key: "q", cmd: "quit" }], }), [], ) return Press q to quit } createRoot(renderer).render( , ) ``` -------------------------------- ### useTerminalDimensions() Source: https://github.com/anomalyco/opentui/blob/main/packages/react/README.md Get current terminal dimensions and automatically update when the terminal is resized. ```APIDOC ## useTerminalDimensions() ### Description Get current terminal dimensions and automatically update when the terminal is resized. ### Returns An object with `width` and `height` properties representing the current terminal dimensions. ### Usage ```tsx import { useTerminalDimensions } from "@opentui/react" function App() { const { width, height } = useTerminalDimensions() return ( Terminal dimensions: {width}x{height} Half-width, third-height box ) } ``` ``` -------------------------------- ### Getting Input Value Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/input.mdx Retrieves the current text value of the input field. ```typescript const currentValue = input.value ``` -------------------------------- ### Register and Use a Core Plugin with SlotRenderable Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/plugins/core.mdx Demonstrates registering a 'clock-plugin' to the 'statusbar' slot and rendering it. It shows how to initialize the renderer, create a registry, register the plugin, and add a SlotRenderable to the root. The example also illustrates updating the slot's data, refreshing, and destroying the slot. ```typescript import { BoxRenderable, createCliRenderer, createCoreSlotRegistry, registerCorePlugin, SlotRenderable, TextRenderable, } from "@opentui/core" type Slots = "statusbar" type SlotData = { label: string } const context = { appName: "core-app", version: "1.0.0" } const renderer = await createCliRenderer() const registry = createCoreSlotRegistry(renderer, context) const unregister = registerCorePlugin(registry, { id: "clock-plugin", order: 0, slots: { statusbar(_ctx, data) { return new TextRenderable(renderer, { id: "clock-status", content: `clock: ${data.label}`, }) }, }, }) const slot = new SlotRenderable(renderer, { id: "statusbar-slot", registry, name: "statusbar", data: { label: "ok" }, mode: "append", width: "100%", height: 3, flexDirection: "row", fallback: () => new TextRenderable(renderer, { id: "statusbar-fallback", content: "fallback", }), }) renderer.root.add(slot) // later slot.mode = "replace" slot.data = { label: "updated" } slot.refresh() slot.destroy() ``` -------------------------------- ### Input Component Value Management Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/input.mdx Explains how to get and set the value of the Input component. ```APIDOC ## Input Component Value Management ### Getting the current value ```typescript const currentValue = input.value ``` ### Setting the value ```typescript input.value = "New value" ``` ``` -------------------------------- ### Handling Function Keys Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/keyboard.mdx Example of how to detect presses of function keys (F1-F12) and trigger corresponding actions. ```typescript keyHandler.on("keypress", (key: KeyEvent) => { // F1-F12 if (key.name === "f1") { showHelp() } if (key.name === "f5") { refresh() } }) ``` -------------------------------- ### Run OpenTUI Benchmarks with npm Source: https://github.com/anomalyco/opentui/blob/main/packages/core/src/zig/bench/README.md Execute the native benchmarks using the recommended npm script. Include memory statistics by adding the --mem flag. ```bash bun bench:native ``` ```bash bun bench:native --mem ``` -------------------------------- ### Build NativeSpanFeed Benchmark Library with Zig Source: https://github.com/anomalyco/opentui/blob/main/packages/core/src/benchmark/native-span-feed-benchmark.md Builds the benchmark library using the Zig build system. Ensure you are in the correct directory before running. ```bash cd packages/core/src/zig zig build bench-ffi ``` -------------------------------- ### drawText Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/frame-buffer.mdx Draws a string of text starting at a specified position with customizable foreground and background colors, and attributes. ```APIDOC ## drawText ### Description Draw a string of text at a position. ### Signature ```typescript drawText( text: string, // String to draw x: number, // Starting X position y: number, // Y position fg: RGBA, // Text color (RGBA) bg?: RGBA, // Background color (RGBA, optional) attributes?: number // Text attributes (optional, default: 0) ): void ``` ### Example ```typescript cvas.frameBuffer.drawText("Score: 100", 2, 1, RGBA.fromHex("#00FF00")) ``` ``` -------------------------------- ### Run a test with Bun Source: https://github.com/anomalyco/opentui/blob/main/AGENTS.md Use `bun test` to execute tests. This example shows a basic passing test case. ```typescript import { test, expect } from "bun:test"; test("hello world", () => { expect(1).toBe(1); }); ``` -------------------------------- ### Creating a Root Renderer with Options Source: https://github.com/anomalyco/opentui/blob/main/packages/react/README.md Instantiate a CLI renderer with custom options, such as disabling exit on Ctrl+C, and then create a React root for rendering. ```tsx import { createCliRenderer } from "@opentui/core" import { createRoot } from "@opentui/react" const renderer = await createCliRenderer({ // Optional renderer configuration exitOnCtrlC: false, }) createRoot(renderer).render() ``` -------------------------------- ### Listen for Focus and Blur Events Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/renderables.mdx Example of attaching event listeners to a renderable to react to focus and blur events using RenderableEvents. ```typescript import { RenderableEvents } from "@opentui/core" input.on(RenderableEvents.FOCUSED, () => { console.log("Input focused") }) input.on(RenderableEvents.BLURRED, () => { console.log("Input blurred") }) ``` -------------------------------- ### ScrollBox scrollTo Method Examples Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/scrollbox.mdx Illustrates using the scrollTo method to scroll content to an absolute position, such as the top or a specific coordinate. ```typescript // Scroll to top scrollbox.scrollTo(0) // Scroll to specific position scrollbox.scrollTo({ x: 0, y: 100 }) ``` -------------------------------- ### Import New Benchmark in Zig Source: https://github.com/anomalyco/opentui/blob/main/packages/core/src/zig/bench/README.md After creating a new benchmark file (e.g., `my_new_bench.zig`) in the `bench/` directory, import it into the main `bench.zig` file. ```zig const my_new_bench = @import("bench/my_new_bench.zig"); ``` -------------------------------- ### Toggling Console Overlay Programmatically Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/console.mdx Provides code examples for toggling the visibility and focus of the console overlay using the renderer instance. ```typescript // Toggle visibility and focus renderer.console.toggle() // When open but not focused, toggle() focuses the console // When focused, toggle() closes the console ``` -------------------------------- ### Create a Vertical Slider Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/slider.mdx Instantiate a SliderRenderable with the 'vertical' orientation. This example demonstrates setting a different value range and initial value. ```typescript const slider = new SliderRenderable(renderer, { orientation: "vertical", width: 2, height: 10, min: 0, max: 1, value: 0.5, }) ``` -------------------------------- ### useTerminalDimensions() Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/bindings/react.mdx Get reactive terminal dimensions. This hook returns the current width and height of the terminal, updating automatically when the terminal is resized. ```APIDOC ## useTerminalDimensions() ### Description Get reactive terminal dimensions. ### Parameters None ### Request Example ```tsx import { useTerminalDimensions } from "@opentui/react" function App() { const { width, height } = useTerminalDimensions() return ( Terminal: {width}x{height} ) } ``` ### Response #### Success Response (200) An object containing the current terminal dimensions. #### Response Example ```json { "width": 80, "height": 24 } ``` ``` -------------------------------- ### Run Native Benchmarks Source: https://github.com/anomalyco/opentui/blob/main/packages/core/README.md Execute native performance benchmarks for OpenTUI Core using Bun. ```bash bun run bench:native ``` -------------------------------- ### Configure Renderer with Disabled Console Overlay Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/renderer.mdx Example of creating a CLI renderer with the console overlay disabled. This requires `screenMode` and `externalOutputMode` to be set. ```typescript const renderer = await createCliRenderer({ screenMode: "split-footer", externalOutputMode: "capture-stdout", consoleMode: "disabled", }) ``` -------------------------------- ### Basic React Slot Registry and Plugin Usage Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/plugins/react.mdx Demonstrates creating a React slot registry, registering a plugin that contributes to a 'statusbar' slot, and rendering the slot with fallback content. ```tsx import { createCliRenderer } from "@opentui/core" import { createReactSlotRegistry, createRoot, Slot } from "@opentui/react" type Slots = { statusbar: { user: string } } const context = { appName: "react-app", version: "1.0.0" } const renderer = await createCliRenderer() const registry = createReactSlotRegistry(renderer, context) const unregister = registry.register({ id: "clock-plugin", slots: { statusbar(ctx, props) { return {`${ctx.appName}:${props.user}`} }, }, }) const AppSlot = Slot function App() { return ( fallback-statusbar ) } createRoot(renderer).render() ``` -------------------------------- ### Initialize Core Constructs Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/constructs.mdx Import and instantiate various core UI components as VNodes. ```typescript import { ASCIIFont, Box, Code, FrameBuffer, Input, ScrollBox, Select, SyntaxStyle, TabSelect, Text, RGBA, } from "@opentui/core" // These create VNodes, not actual Renderables const syntaxStyle = SyntaxStyle.fromStyles({ default: { fg: RGBA.fromHex("#FFFFFF") }, }) const box = Box({ border: true }) const text = Text({ content: "Hello" }) const input = Input({ placeholder: "Type here..." }) const code = Code({ content: "const x = 1", filetype: "typescript", syntaxStyle }) const scrollBox = ScrollBox({ width: 40, height: 10 }) const frameBuffer = FrameBuffer({ width: 20, height: 10 }) const ascii = ASCIIFont({ text: "OPEN", font: "tiny" }) ``` -------------------------------- ### ScrollBox Construct API Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/scrollbox.mdx Shows how to create a ScrollBox using the Construct API, including adding child components with specific styling. ```typescript import { ScrollBox, Box, Text, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() renderer.root.add( ScrollBox( { width: 40, height: 20, }, ...Array.from({ length: 100 }, (_, i) => Box( { width: "100%", padding: 1, backgroundColor: i % 2 === 0 ? "#292e42" : "#2f3449" }, Text({ content: `Item ${i}` }), ), ), ), ) ``` -------------------------------- ### ScrollBox Renderable API Example Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/scrollbox.mdx Demonstrates how to create and populate a ScrollBox using the Renderable API. Add multiple child renderables to the scrollbox. ```typescript import { ScrollBoxRenderable, TextRenderable, BoxRenderable, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() const scrollbox = new ScrollBoxRenderable(renderer, { id: "scrollbox", width: 40, height: 20, }) // Add content to the scrollbox for (let i = 0; i < 100; i++) { scrollbox.add( new BoxRenderable(renderer, { id: `item-${i}`, width: "100%", height: 2, backgroundColor: i % 2 === 0 ? "#292e42" : "#2f3449", }), ) } renderer.root.add(scrollbox) ``` -------------------------------- ### Initialize xterm.js Terminal and FitAddon Source: https://github.com/anomalyco/opentui/blob/main/packages/examples/src/xterm-web-demo/index.html Sets up a new xterm.js terminal instance with custom options and loads the FitAddon for automatic resizing. The terminal is then opened in a specified host element. ```javascript const status = document.getElementById("status") const terminalSize = document.getElementById("terminal-size") const terminalHost = document.getElementById("terminal-host") const fontFamily = "Menlo, Monaco, 'Courier New', monospace" const lineHeight = 1 const fontSizes = [8, 10, 12, 14, 16, 20, 24, 30, 38, 48] const defaultFontSizeIndex = 6 let fontSizeIndex = defaultFontSizeIndex let currentCols = 80 let currentRows = 24 let currentFontSize = fontSizes[fontSizeIndex] let lastSentCols = 0 let lastSentRows = 0 let pendingLayoutFrame = 0 let ws = null const term = new Terminal({ cursorBlink: false, fontFamily, fontSize: currentFontSize, lineHeight, letterSpacing: 0, scrollback: 0, theme: { background: "#000000" }, }) const fitAddon = new FitAddon.FitAddon() term.loadAddon(fitAddon) term.open(terminalHost) ``` -------------------------------- ### Common Color Constants Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/colors.mdx Provides examples of commonly used RGBA color constants for white, black, red, green, blue, and transparent. ```typescript // Some examples of commonly used colors const white = RGBA.fromInts(255, 255, 255, 255) const black = RGBA.fromInts(0, 0, 0, 255) const red = RGBA.fromInts(255, 0, 0, 255) const green = RGBA.fromInts(0, 255, 0, 255) const blue = RGBA.fromInts(0, 0, 255, 255) const transparent = RGBA.fromInts(0, 0, 0, 0) ``` -------------------------------- ### Add Preload Script for OpenTUI Source: https://github.com/anomalyco/opentui/blob/main/packages/solid/README.md Configure your bunfig.toml to include the OpenTUI Solid.js preload script for proper initialization. ```toml preload = ["@opentui/solid/preload"] ``` -------------------------------- ### Test Recorder API Source: https://github.com/anomalyco/opentui/blob/main/packages/core/src/testing/README.md Record terminal frames during rendering for testing or analysis. Allows starting, stopping, clearing, and accessing recorded frames. ```typescript import { TestRecorder } from "@opentui/core/testing" const { renderer, renderOnce } = await createTestRenderer({ width: 80, height: 24 }) const recorder = new TestRecorder(renderer) // Start recording recorder.rec() // Add content and trigger renders const text = new TextRenderable(renderer, { content: "Hello" }) renderer.root.add(text) await Bun.sleep(1) // Wait for automatic render from add() text.content = "World" await Bun.sleep(1) // Wait for automatic render from content change // Stop recording recorder.stop() // Access recorded frames const frames = recorder.recordedFrames console.log(`Recorded ${frames.length} frames`) frames.forEach((frame) => { console.log(`Frame ${frame.frameNumber} at ${frame.timestamp}ms:`) console.log(frame.frame) }) // Clear and start new recording recorder.clear() recorder.rec() ``` -------------------------------- ### Build OpenTUI Core Source: https://github.com/anomalyco/opentui/blob/main/packages/core/README.md Build the platform-specific libraries for OpenTUI Core using Bun. ```bash bun run build ``` -------------------------------- ### ASCIIFont Basic Usage (Construct API) Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/ascii-font.mdx Shows how to use the `ASCIIFont` construct function to quickly add ASCII text elements to the renderer's root. ```APIDOC ## ASCIIFont Construct API ### Description The `ASCIIFont` construct provides a concise way to create and add ASCII text elements directly to the renderer's root. ### Usage ```typescript import { ASCIIFont, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() renderer.root.add( ASCIIFont({ text: "HELLO", font: "block", color: "#00FF00", }) ) ``` ### Parameters - `text` (string): Text to display. - `font` (ASCIIFontName): Font style to use. - `color` (ColorInput): Text color. ``` -------------------------------- ### Find Renderables in the Tree Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/core-concepts/renderables.mdx Demonstrates methods for retrieving renderables from the tree, including getting a direct child by ID and recursively searching for a descendant. ```typescript // Get a direct child by ID const title = container.getRenderable("title") // Recursively search all descendants const deepChild = container.findDescendantById("nested-input") // Get all children const children = container.getChildren() ``` -------------------------------- ### Programmatic Control Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/select.mdx Illustrates how to control the Select component programmatically after initialization, including getting selections, setting selections, navigation, and updating options. ```APIDOC ## Programmatic Control ### Description This section details how to interact with the `Select` component programmatically. You can retrieve the current selection, set it programmatically, navigate through options, and dynamically update the component's options and display properties. ### Methods - **`getSelectedIndex()`**: Returns the index of the currently selected option. - **`getSelectedOption()`**: Returns the currently selected option object. - **`setSelectedIndex(index)`**: Sets the selected option to the item at the specified `index`. - **`moveUp(count)`**: Moves the selection up by `count` items (defaults to 1). - **`moveDown(count)`**: Moves the selection down by `count` items (defaults to 1). - **`selectCurrent()`**: Triggers the selection of the currently highlighted option. ### Properties - **`options`**: Allows dynamic updating of the select options. Assign a new array of option objects to this property. - **`showDescription`**: (boolean) Controls whether option descriptions are displayed. Set to `false` to hide descriptions. - **`showScrollIndicator`**: (boolean) Controls the visibility of the scroll indicator. Set to `true` to show it. - **`wrapSelection`**: (boolean) Determines if selection wraps around when navigating past the first or last item. Set to `true` to enable wrapping. ### Usage Examples ```typescript // Get current selection index const currentIndex = menu.getSelectedIndex() // Get currently selected option const option = menu.getSelectedOption() // Set selection programmatically menu.setSelectedIndex(2) // Navigate programmatically menu.moveUp() // Move up one item menu.moveDown() // Move down one item menu.moveUp(3) // Move up multiple items menu.selectCurrent() // Trigger selection of current item // Update options dynamically menu.options = [ { name: "New Option 1", description: "First" }, { name: "New Option 2", description: "Second" }, ] // Toggle display options menu.showDescription = false menu.showScrollIndicator = true menu.wrapSelection = true ``` ``` -------------------------------- ### ASCIIFont Basic Usage (Renderable API) Source: https://github.com/anomalyco/opentui/blob/main/packages/web/src/content/docs/components/ascii-font.mdx Demonstrates how to create and render ASCII text using the ASCIIFontRenderable class, allowing for dynamic updates and control over properties like font, color, and position. ```APIDOC ## ASCIIFontRenderable API ### Description Use `ASCIIFontRenderable` to create and manage ASCII text elements that can be dynamically updated and positioned within the renderer. ### Usage ```typescript import { ASCIIFontRenderable, RGBA, createCliRenderer } from "@opentui/core" const renderer = await createCliRenderer() const title = new ASCIIFontRenderable(renderer, { id: "title", text: "OPENTUI", font: "tiny", color: RGBA.fromInts(255, 255, 255, 255), x: 10, // Optional: X position offset y: 2, // Optional: Y position offset }) renderer.root.add(title) ``` ### Properties - `id` (string): Unique identifier for the renderable. - `text` (string): The text content to display. - `font` (ASCIIFontName): The font style to use (e.g., 'tiny', 'block', 'huge'). - `color` (ColorInput | ColorInput[]): The color of the text. - `backgroundColor` (ColorInput): The background color of the text. - `x` (number): The horizontal position offset. - `y` (number): The vertical position offset. ```