@opentui/react 0.0.0-20250908-4906ddad

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 opentui
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,531 @@
1
+ # @opentui/react
2
+
3
+ A React renderer for building terminal user interfaces using [OpenTUI core](https://github.com/sst/opentui). Create rich, interactive console applications with familiar React patterns and components.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun install @opentui/react @opentui/core react
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```tsx
14
+ import { render } from "@opentui/react"
15
+
16
+ function App() {
17
+ return (
18
+ <box>
19
+ <text fg="#00FF00">Hello, Terminal!</text>
20
+ <box title="Welcome" padding={2}>
21
+ <text>Welcome to OpenTUI with React!</text>
22
+ </box>
23
+ </box>
24
+ )
25
+ }
26
+
27
+ render(<App />)
28
+ ```
29
+
30
+ ## TypeScript Configuration
31
+
32
+ For optimal TypeScript support, configure your `tsconfig.json`:
33
+
34
+ ```json
35
+ {
36
+ "compilerOptions": {
37
+ "lib": ["ESNext", "DOM"],
38
+ "target": "ESNext",
39
+ "module": "ESNext",
40
+ "moduleResolution": "bundler",
41
+ "jsx": "react-jsx",
42
+ "jsxImportSource": "@opentui/react",
43
+ "strict": true,
44
+ "skipLibCheck": true
45
+ }
46
+ }
47
+ ```
48
+
49
+ ## Core Concepts
50
+
51
+ ### Components
52
+
53
+ OpenTUI React provides several built-in components that map to OpenTUI core renderables:
54
+
55
+ - **`<text>`** - Display text with styling
56
+ - **`<box>`** - Container with borders and layout
57
+ - **`<input>`** - Text input field
58
+ - **`<select>`** - Selection dropdown
59
+ - **`<tab-select>`** - Tab-based selection
60
+ - **`<ascii-font>`** - Display ASCII art text with different font styles
61
+
62
+ ### Styling
63
+
64
+ Components can be styled using props or the `style` prop:
65
+
66
+ ```tsx
67
+ // Direct props
68
+ <text fg="#FF0000">Hello</text>
69
+
70
+ // Style prop
71
+ <box style={{ backgroundColor: "blue", padding: 2 }}>
72
+ <text>Styled content</text>
73
+ </box>
74
+ ```
75
+
76
+ ## API Reference
77
+
78
+ ### `render(element, config?)`
79
+
80
+ Renders a React element to the terminal.
81
+
82
+ ```tsx
83
+ import { render } from "@opentui/react"
84
+
85
+ await render(<App />, {
86
+ // Optional renderer configuration
87
+ exitOnCtrlC: false,
88
+ })
89
+ ```
90
+
91
+ **Parameters:**
92
+
93
+ - `element`: React element to render
94
+ - `config?`: Optional `CliRendererConfig` object
95
+
96
+ ### Hooks
97
+
98
+ #### `useRenderer()`
99
+
100
+ Access the OpenTUI renderer instance.
101
+
102
+ ```tsx
103
+ import { useRenderer } from "@opentui/react"
104
+
105
+ function MyComponent() {
106
+ const renderer = useRenderer()
107
+
108
+ useEffect(() => {
109
+ renderer.toggleDebugOverlay()
110
+ }, [])
111
+
112
+ return <text>Debug available</text>
113
+ }
114
+ ```
115
+
116
+ #### `useKeyboard(handler)`
117
+
118
+ Handle keyboard events.
119
+
120
+ ```tsx
121
+ import { useKeyboard } from "@opentui/react"
122
+
123
+ function MyComponent() {
124
+ useKeyboard((key) => {
125
+ if (key.name === "escape") {
126
+ process.exit(0)
127
+ }
128
+ })
129
+
130
+ return <text>Press ESC to exit</text>
131
+ }
132
+ ```
133
+
134
+ #### `useOnResize(callback)`
135
+
136
+ Handle terminal resize events.
137
+
138
+ ```tsx
139
+ import { useOnResize, useRenderer } from "@opentui/react"
140
+ import { useEffect } from "react"
141
+
142
+ function MyComponent() {
143
+ const renderer = useRenderer()
144
+
145
+ useEffect(() => {
146
+ renderer.console.show()
147
+ }, [renderer])
148
+
149
+ useOnResize((width, height) => {
150
+ console.log(`Terminal resized to ${width}x${height}`)
151
+ })
152
+
153
+ return <text>Resize-aware component</text>
154
+ }
155
+ ```
156
+
157
+ #### `useTerminalDimensions()`
158
+
159
+ Get current terminal dimensions and automatically update when the terminal is resized.
160
+
161
+ ```tsx
162
+ import { useTerminalDimensions } from "@opentui/react"
163
+
164
+ function MyComponent() {
165
+ const { width, height } = useTerminalDimensions()
166
+
167
+ return (
168
+ <box>
169
+ <text>
170
+ Terminal dimensions: {width}x{height}
171
+ </text>
172
+ <box style={{ width: Math.floor(width / 2), height: Math.floor(height / 3) }}>
173
+ <text>Half-width, third-height box</text>
174
+ </box>
175
+ </box>
176
+ )
177
+ }
178
+ ```
179
+
180
+ **Returns:** An object with `width` and `height` properties representing the current terminal dimensions.
181
+
182
+ ## Components
183
+
184
+ ### Text Component
185
+
186
+ Display text with rich formatting.
187
+
188
+ ```tsx
189
+ import { bold, fg, t } from "@opentui/core"
190
+
191
+ function TextExample() {
192
+ return (
193
+ <box>
194
+ {/* Simple text */}
195
+ <text>Hello World</text>
196
+
197
+ {/* Rich text with children */}
198
+ <text>{bold(fg("red")("Bold Red Text"))}</text>
199
+
200
+ {/* Template literals */}
201
+ <text>{t`${bold("Bold")} and ${fg("blue")("Blue")}`}</text>
202
+ </box>
203
+ )
204
+ }
205
+ ```
206
+
207
+ ### Box Component
208
+
209
+ Container with borders and layout capabilities.
210
+
211
+ ```tsx
212
+ function BoxExample() {
213
+ return (
214
+ <box flexDirection="column">
215
+ {/* Basic box */}
216
+ <box>
217
+ <text>Simple box</text>
218
+ </box>
219
+
220
+ {/* Box with title and styling */}
221
+ <box title="Settings" borderStyle="double" padding={2} backgroundColor="blue">
222
+ <text>Box content</text>
223
+ </box>
224
+
225
+ {/* Styled box */}
226
+ <box
227
+ style={{
228
+ width: 40,
229
+ height: 10,
230
+ margin: 1,
231
+ alignItems: "center",
232
+ justifyContent: "center",
233
+ }}
234
+ >
235
+ <text>Centered content</text>
236
+ </box>
237
+ </box>
238
+ )
239
+ }
240
+ ```
241
+
242
+ ### Input Component
243
+
244
+ Text input field with event handling.
245
+
246
+ ```tsx
247
+ import { useState } from "react"
248
+
249
+ function InputExample() {
250
+ const [value, setValue] = useState("")
251
+ const [focused, setFocused] = useState(true)
252
+
253
+ return (
254
+ <box title="Enter your name" style={{ height: 3 }}>
255
+ <input
256
+ placeholder="Type here..."
257
+ focused={focused}
258
+ onInput={setValue}
259
+ onSubmit={(value) => console.log("Submitted:", value)}
260
+ style={{
261
+ focusedBackgroundColor: "#333333",
262
+ }}
263
+ />
264
+ </box>
265
+ )
266
+ }
267
+ ```
268
+
269
+ ### Select Component
270
+
271
+ Dropdown selection component.
272
+
273
+ ```tsx
274
+ import type { SelectOption } from "@opentui/core"
275
+ import { useState } from "react"
276
+
277
+ function SelectExample() {
278
+ const [selectedIndex, setSelectedIndex] = useState(0)
279
+
280
+ const options: SelectOption[] = [
281
+ { name: "Option 1", description: "Option 1 description", value: "opt1" },
282
+ { name: "Option 2", description: "Option 2 description", value: "opt2" },
283
+ { name: "Option 3", description: "Option 3 description", value: "opt3" },
284
+ ]
285
+
286
+ return (
287
+ <box style={{ height: 24 }}>
288
+ <select
289
+ style={{ height: 22 }}
290
+ options={options}
291
+ focused={true}
292
+ onChange={(index, option) => {
293
+ setSelectedIndex(index)
294
+ console.log("Selected:", option)
295
+ }}
296
+ />
297
+ </box>
298
+ )
299
+ }
300
+ ```
301
+
302
+ ### ASCII Font Component
303
+
304
+ Display ASCII art text with different font styles.
305
+
306
+ ```tsx
307
+ import { measureText } from "@opentui/core"
308
+ import { useState } from "react"
309
+
310
+ function ASCIIFontExample() {
311
+ const text = "ASCII"
312
+ const [font, setFont] = useState<"block" | "shade" | "slick" | "tiny">("tiny")
313
+
314
+ const { width, height } = measureText({
315
+ text,
316
+ font,
317
+ })
318
+
319
+ return (
320
+ <box style={{ paddingLeft: 1, paddingRight: 1 }}>
321
+ <box
322
+ style={{
323
+ height: 8,
324
+ marginBottom: 1,
325
+ }}
326
+ >
327
+ <select
328
+ focused
329
+ onChange={(_, option) => setFont(option?.value)}
330
+ showScrollIndicator
331
+ options={[
332
+ {
333
+ name: "Tiny",
334
+ description: "Tiny font",
335
+ value: "tiny",
336
+ },
337
+ {
338
+ name: "Block",
339
+ description: "Block font",
340
+ value: "block",
341
+ },
342
+ {
343
+ name: "Slick",
344
+ description: "Slick font",
345
+ value: "slick",
346
+ },
347
+ {
348
+ name: "Shade",
349
+ description: "Shade font",
350
+ value: "shade",
351
+ },
352
+ ]}
353
+ style={{ flexGrow: 1 }}
354
+ />
355
+ </box>
356
+
357
+ <ascii-font style={{ width, height }} text={text} font={font} />
358
+ </box>
359
+ )
360
+ }
361
+ ```
362
+
363
+ ## Examples
364
+
365
+ ### Login Form
366
+
367
+ ```tsx
368
+ import { useState, useCallback } from "react"
369
+ import { render, useKeyboard } from "@opentui/react"
370
+
371
+ function LoginForm() {
372
+ const [username, setUsername] = useState("")
373
+ const [password, setPassword] = useState("")
374
+ const [focused, setFocused] = useState<"username" | "password">("username")
375
+ const [status, setStatus] = useState("idle")
376
+
377
+ useKeyboard((key) => {
378
+ if (key.name === "tab") {
379
+ setFocused((prev) => (prev === "username" ? "password" : "username"))
380
+ }
381
+ })
382
+
383
+ const handleSubmit = useCallback(() => {
384
+ if (username === "admin" && password === "secret") {
385
+ setStatus("success")
386
+ } else {
387
+ setStatus("error")
388
+ }
389
+ }, [username, password])
390
+
391
+ return (
392
+ <box style={{ padding: 2, flexDirection: "column" }}>
393
+ <text fg="#FFFF00">Login Form</text>
394
+
395
+ <box title="Username" style={{ width: 40, height: 3, marginTop: 1 }}>
396
+ <input
397
+ placeholder="Enter username..."
398
+ onInput={setUsername}
399
+ onSubmit={handleSubmit}
400
+ focused={focused === "username"}
401
+ />
402
+ </box>
403
+
404
+ <box title="Password" style={{ width: 40, height: 3, marginTop: 1 }}>
405
+ <input
406
+ placeholder="Enter password..."
407
+ onInput={setPassword}
408
+ onSubmit={handleSubmit}
409
+ focused={focused === "password"}
410
+ />
411
+ </box>
412
+
413
+ <text
414
+ style={{
415
+ fg: status === "success" ? "green" : status === "error" ? "red" : "#999",
416
+ }}
417
+ >
418
+ {status.toUpperCase()}
419
+ </text>
420
+ </box>
421
+ )
422
+ }
423
+
424
+ render(<LoginForm />)
425
+ ```
426
+
427
+ ### Counter with Timer
428
+
429
+ ```tsx
430
+ import { useState, useEffect } from "react"
431
+ import { render } from "@opentui/react"
432
+
433
+ function Counter() {
434
+ const [count, setCount] = useState(0)
435
+
436
+ useEffect(() => {
437
+ const interval = setInterval(() => {
438
+ setCount((prev) => prev + 1)
439
+ }, 1000)
440
+
441
+ return () => clearInterval(interval)
442
+ }, [])
443
+
444
+ return (
445
+ <box title="Counter" style={{ padding: 2 }}>
446
+ <text fg="#00FF00">{`Count: ${count}`}</text>
447
+ </box>
448
+ )
449
+ }
450
+
451
+ render(<Counter />)
452
+ ```
453
+
454
+ ### Styled Text Showcase
455
+
456
+ ```tsx
457
+ import { blue, bold, red, t, underline } from "@opentui/core"
458
+ import { render } from "@opentui/react"
459
+
460
+ function StyledTextShowcase() {
461
+ return (
462
+ <box style={{ flexDirection: "column" }}>
463
+ <text>Simple text</text>
464
+ <text>{bold("Bold text")}</text>
465
+ <text>{underline("Underlined text")}</text>
466
+ <text>{red("Red text")}</text>
467
+ <text>{blue("Blue text")}</text>
468
+ <text>{bold(red("Bold red text"))}</text>
469
+ <text>{t`${bold("Bold")} and ${blue("blue")} combined`}</text>
470
+ </box>
471
+ )
472
+ }
473
+
474
+ render(<StyledTextShowcase />)
475
+ ```
476
+
477
+ ## Component Extension
478
+
479
+ You can create custom components by extending OpenTUI's base renderables:
480
+
481
+ ```tsx
482
+ import { BoxRenderable, OptimizedBuffer, RGBA } from "@opentui/core"
483
+ import { extend, render } from "@opentui/react"
484
+
485
+ // Create custom component class
486
+ class ButtonRenderable extends BoxRenderable {
487
+ private _label: string = "Button"
488
+
489
+ constructor(id: string, options: any) {
490
+ super(id, options)
491
+ this.borderStyle = "single"
492
+ this.padding = 1
493
+ }
494
+
495
+ protected renderSelf(buffer: OptimizedBuffer): void {
496
+ super.renderSelf(buffer)
497
+
498
+ const centerX = this.x + Math.floor(this.width / 2 - this._label.length / 2)
499
+ const centerY = this.y + Math.floor(this.height / 2)
500
+
501
+ buffer.drawText(this._label, centerX, centerY, RGBA.fromInts(255, 255, 255, 255))
502
+ }
503
+
504
+ set label(value: string) {
505
+ this._label = value
506
+ this.requestRender()
507
+ }
508
+ }
509
+
510
+ // Add TypeScript support
511
+ declare module "@opentui/react" {
512
+ interface OpenTUIComponents {
513
+ button: typeof ButtonRenderable
514
+ }
515
+ }
516
+
517
+ // Register the component
518
+ extend({ button: ButtonRenderable })
519
+
520
+ // Use in JSX
521
+ function App() {
522
+ return (
523
+ <box>
524
+ <button label="Click me!" style={{ backgroundColor: "blue" }} />
525
+ <button label="Another button" style={{ backgroundColor: "green" }} />
526
+ </box>
527
+ )
528
+ }
529
+
530
+ render(<App />)
531
+ ```