silvery 0.3.0 → 0.4.1

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.
Files changed (120) hide show
  1. package/README.md +41 -145
  2. package/dist/chalk.js +3 -0
  3. package/dist/chalk.js.map +11 -0
  4. package/dist/index.js +340 -0
  5. package/dist/index.js.map +282 -0
  6. package/dist/ink.js +129 -0
  7. package/dist/ink.js.map +140 -0
  8. package/dist/runtime.js +394 -0
  9. package/dist/runtime.js.map +286 -0
  10. package/dist/theme.js +343 -0
  11. package/dist/theme.js.map +286 -0
  12. package/dist/ui/animation.js +3 -0
  13. package/dist/ui/animation.js.map +15 -0
  14. package/dist/ui/ansi.js +3 -0
  15. package/dist/ui/ansi.js.map +10 -0
  16. package/dist/ui/cli.js +8 -0
  17. package/dist/ui/cli.js.map +14 -0
  18. package/dist/ui/display.js +4 -0
  19. package/dist/ui/display.js.map +10 -0
  20. package/dist/ui/image.js +4 -0
  21. package/dist/ui/image.js.map +15 -0
  22. package/dist/ui/input.js +3 -0
  23. package/dist/ui/input.js.map +11 -0
  24. package/dist/ui/progress.js +8 -0
  25. package/dist/ui/progress.js.map +20 -0
  26. package/dist/ui/react.js +3 -0
  27. package/dist/ui/react.js.map +15 -0
  28. package/dist/ui/utils.js +3 -0
  29. package/dist/ui/utils.js.map +10 -0
  30. package/dist/ui/wrappers.js +14 -0
  31. package/dist/ui/wrappers.js.map +19 -0
  32. package/dist/ui.js +17 -0
  33. package/dist/ui.js.map +20 -0
  34. package/package.json +67 -15
  35. package/src/index.ts +67 -1
  36. package/src/runtime.ts +4 -0
  37. package/src/theme.ts +4 -0
  38. package/src/ui/animation.ts +2 -0
  39. package/src/ui/ansi.ts +2 -0
  40. package/src/ui/cli.ts +2 -0
  41. package/src/ui/display.ts +2 -0
  42. package/src/ui/image.ts +2 -0
  43. package/src/ui/input.ts +2 -0
  44. package/src/ui/progress.ts +2 -0
  45. package/src/ui/react.ts +2 -0
  46. package/src/ui/utils.ts +2 -0
  47. package/src/ui/wrappers.ts +2 -0
  48. package/src/ui.ts +4 -0
  49. package/examples/CLAUDE.md +0 -75
  50. package/examples/_banner.tsx +0 -60
  51. package/examples/cli.ts +0 -228
  52. package/examples/index.md +0 -101
  53. package/examples/inline/inline-nontty.tsx +0 -98
  54. package/examples/inline/inline-progress.tsx +0 -79
  55. package/examples/inline/inline-simple.tsx +0 -63
  56. package/examples/inline/scrollback.tsx +0 -185
  57. package/examples/interactive/_input-debug.tsx +0 -110
  58. package/examples/interactive/_stdin-test.ts +0 -71
  59. package/examples/interactive/_textarea-bare.tsx +0 -45
  60. package/examples/interactive/aichat/components.tsx +0 -468
  61. package/examples/interactive/aichat/index.tsx +0 -207
  62. package/examples/interactive/aichat/script.ts +0 -460
  63. package/examples/interactive/aichat/state.ts +0 -326
  64. package/examples/interactive/aichat/types.ts +0 -19
  65. package/examples/interactive/app-todo.tsx +0 -198
  66. package/examples/interactive/async-data.tsx +0 -208
  67. package/examples/interactive/cli-wizard.tsx +0 -332
  68. package/examples/interactive/clipboard.tsx +0 -183
  69. package/examples/interactive/components.tsx +0 -463
  70. package/examples/interactive/data-explorer.tsx +0 -506
  71. package/examples/interactive/dev-tools.tsx +0 -379
  72. package/examples/interactive/explorer.tsx +0 -747
  73. package/examples/interactive/gallery.tsx +0 -652
  74. package/examples/interactive/inline-bench.tsx +0 -136
  75. package/examples/interactive/kanban.tsx +0 -267
  76. package/examples/interactive/layout-ref.tsx +0 -185
  77. package/examples/interactive/outline.tsx +0 -171
  78. package/examples/interactive/paste-demo.tsx +0 -198
  79. package/examples/interactive/scroll.tsx +0 -77
  80. package/examples/interactive/search-filter.tsx +0 -240
  81. package/examples/interactive/task-list.tsx +0 -279
  82. package/examples/interactive/terminal.tsx +0 -798
  83. package/examples/interactive/textarea.tsx +0 -103
  84. package/examples/interactive/theme.tsx +0 -336
  85. package/examples/interactive/transform.tsx +0 -256
  86. package/examples/interactive/virtual-10k.tsx +0 -413
  87. package/examples/kitty/canvas.tsx +0 -519
  88. package/examples/kitty/generate-samples.ts +0 -236
  89. package/examples/kitty/image-component.tsx +0 -273
  90. package/examples/kitty/images.tsx +0 -604
  91. package/examples/kitty/input.tsx +0 -371
  92. package/examples/kitty/keys.tsx +0 -378
  93. package/examples/kitty/paint.tsx +0 -1017
  94. package/examples/layout/dashboard.tsx +0 -551
  95. package/examples/layout/live-resize.tsx +0 -290
  96. package/examples/layout/overflow.tsx +0 -51
  97. package/examples/playground/README.md +0 -69
  98. package/examples/playground/build.ts +0 -61
  99. package/examples/playground/index.html +0 -420
  100. package/examples/playground/playground-app.tsx +0 -416
  101. package/examples/runtime/elm-counter.tsx +0 -206
  102. package/examples/runtime/hello-runtime.tsx +0 -73
  103. package/examples/runtime/pipe-composition.tsx +0 -184
  104. package/examples/runtime/run-counter.tsx +0 -78
  105. package/examples/runtime/runtime-counter.tsx +0 -197
  106. package/examples/screenshots/generate.tsx +0 -563
  107. package/examples/scrollback-perf.tsx +0 -230
  108. package/examples/viewer.tsx +0 -654
  109. package/examples/web/build.ts +0 -365
  110. package/examples/web/canvas-app.tsx +0 -80
  111. package/examples/web/canvas.html +0 -89
  112. package/examples/web/dom-app.tsx +0 -81
  113. package/examples/web/dom.html +0 -113
  114. package/examples/web/showcase-app.tsx +0 -107
  115. package/examples/web/showcase.html +0 -34
  116. package/examples/web/showcases/index.tsx +0 -56
  117. package/examples/web/viewer-app.tsx +0 -555
  118. package/examples/web/viewer.html +0 -30
  119. package/examples/web/xterm-app.tsx +0 -105
  120. package/examples/web/xterm.html +0 -118
@@ -1,326 +0,0 @@
1
- /**
2
- * TEA state machine for the AI coding agent demo.
3
- *
4
- * Pure (state, msg) → [state, effects] — all side effects are timer-based.
5
- * The update function is created via factory to close over script/mode config.
6
- */
7
-
8
- import { fx } from "silvery"
9
- import type { TeaResult, TimerEffect } from "silvery"
10
- import type { Exchange, ScriptEntry } from "./types.js"
11
- import { RANDOM_AGENT_RESPONSES, INPUT_COST_PER_M, OUTPUT_COST_PER_M, CONTEXT_WINDOW } from "./script.js"
12
-
13
- // ============================================================================
14
- // Types
15
- // ============================================================================
16
-
17
- /** Streaming phases: thinking -> streaming text -> tool calls -> done */
18
- export type StreamPhase = "thinking" | "streaming" | "tools" | "done"
19
-
20
- export type DemoState = {
21
- exchanges: Exchange[]
22
- scriptIdx: number
23
- streamPhase: StreamPhase
24
- revealFraction: number
25
- done: boolean
26
- compacting: boolean
27
- pulse: boolean
28
- ctrlDPending: boolean
29
- contextBaseline: number
30
- offScript: boolean
31
- nextId: number
32
- autoTyping: { full: string; revealed: number } | null
33
- }
34
-
35
- export type DemoMsg =
36
- | { type: "mount" }
37
- | { type: "advance" }
38
- | { type: "endThinking" }
39
- | { type: "streamTick" }
40
- | { type: "endTools" }
41
- | { type: "submit"; text: string }
42
- | { type: "compact" }
43
- | { type: "compactDone" }
44
- | { type: "pulse" }
45
- | { type: "autoAdvance" }
46
- | { type: "typingTick" }
47
- | { type: "autoTypingDone" }
48
- | { type: "respondRandom" }
49
- | { type: "setCtrlDPending"; pending: boolean }
50
-
51
- export type DemoEffect = TimerEffect<DemoMsg>
52
- export type DemoResult = TeaResult<DemoState, DemoEffect>
53
-
54
- // ============================================================================
55
- // Constants
56
- // ============================================================================
57
-
58
- const INTRO_TEXT = [
59
- "Coding agent simulation showcasing ScrollbackList:",
60
- " • ScrollbackList — declarative list with automatic scrollback",
61
- " • Auto-freeze — items freeze when they scroll off-screen",
62
- " • OSC 8 hyperlinks — clickable file paths and URLs",
63
- " • OSC 133 markers — Cmd+↑/↓ to jump between exchanges",
64
- " • $token theme colors — semantic color tokens",
65
- ].join("\n")
66
-
67
- export const INIT_STATE: DemoState = {
68
- exchanges: [{ id: 0, role: "system", content: INTRO_TEXT }],
69
- scriptIdx: 0,
70
- streamPhase: "done",
71
- revealFraction: 1,
72
- done: false,
73
- compacting: false,
74
- pulse: false,
75
- ctrlDPending: false,
76
- contextBaseline: 0,
77
- offScript: false,
78
- nextId: 1,
79
- autoTyping: null,
80
- }
81
-
82
- // ============================================================================
83
- // Token & Cost Utilities
84
- // ============================================================================
85
-
86
- export function formatTokens(n: number): string {
87
- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
88
- if (n >= 1000) return `${(n / 1000).toFixed(1)}K`
89
- return String(n)
90
- }
91
-
92
- export function formatCost(inputTokens: number, outputTokens: number): string {
93
- const cost = (inputTokens * INPUT_COST_PER_M + outputTokens * OUTPUT_COST_PER_M) / 1_000_000
94
- if (cost < 0.01) return `$${cost.toFixed(4)}`
95
- return `$${cost.toFixed(2)}`
96
- }
97
-
98
- /**
99
- * Compute token stats for display and compaction.
100
- *
101
- * Token values in the script are CUMULATIVE — each exchange's `input` represents
102
- * the total context consumed at that point. So:
103
- * - `currentContext`: the LAST exchange's input tokens (= current context window usage)
104
- * - `totalCost`: sum of all (input + output) for cost calculation (each API call costs)
105
- */
106
- export function computeCumulativeTokens(exchanges: Exchange[]): {
107
- input: number
108
- output: number
109
- currentContext: number
110
- } {
111
- let input = 0
112
- let output = 0
113
- let currentContext = 0
114
- for (const ex of exchanges) {
115
- if (ex.tokens) {
116
- input += ex.tokens.input
117
- output += ex.tokens.output
118
- if (ex.tokens.input > currentContext) currentContext = ex.tokens.input
119
- }
120
- }
121
- return { input, output, currentContext }
122
- }
123
-
124
- /** Next scripted user message for footer placeholder. */
125
- export function getNextMessage(state: DemoState, script: ScriptEntry[], autoMode: boolean): string {
126
- if (autoMode || state.done || state.offScript || state.streamPhase !== "done" || state.exchanges.length === 0)
127
- return ""
128
- const entry = script[state.scriptIdx]
129
- return entry?.role === "user" ? entry.content : ""
130
- }
131
-
132
- // ============================================================================
133
- // Update Factory
134
- // ============================================================================
135
-
136
- export function createDemoUpdate(script: ScriptEntry[], fastMode: boolean, autoMode: boolean) {
137
- function addExchange(state: DemoState, entry: ScriptEntry): DemoState {
138
- const exchange: Exchange = { ...entry, id: state.nextId }
139
- return { ...state, exchanges: [...state.exchanges, exchange], nextId: state.nextId + 1 }
140
- }
141
-
142
- function startStreaming(state: DemoState, entry: ScriptEntry): [DemoState, DemoEffect[]] {
143
- const s = addExchange(state, entry)
144
- if (entry.role !== "agent" || fastMode) {
145
- return [{ ...s, streamPhase: "done", revealFraction: 1 }, []]
146
- }
147
- if (entry.thinking) {
148
- return [{ ...s, streamPhase: "thinking", revealFraction: 0 }, [fx.delay(1200, { type: "endThinking" })]]
149
- }
150
- return [{ ...s, streamPhase: "streaming", revealFraction: 0 }, [fx.interval(50, { type: "streamTick" }, "reveal")]]
151
- }
152
-
153
- function autoAdvanceEffects(state: DemoState): DemoEffect[] {
154
- if (state.done || state.compacting || state.streamPhase !== "done") return []
155
- const next = script[state.scriptIdx]
156
- if (!next) return autoMode ? [fx.delay(0, { type: "autoAdvance" })] : []
157
- if (autoMode || next.role !== "user") return [fx.delay(fastMode ? 100 : 400, { type: "autoAdvance" })]
158
- return []
159
- }
160
-
161
- function doAdvance(state: DemoState, extraEffects: DemoEffect[] = []): DemoResult {
162
- if (state.done || state.compacting || state.streamPhase !== "done") return state
163
- if (state.scriptIdx >= script.length) {
164
- return autoMode ? { ...state, done: true } : state
165
- }
166
-
167
- const entry = script[state.scriptIdx]!
168
- let s: DemoState = {
169
- ...state,
170
- scriptIdx: state.scriptIdx + 1,
171
- }
172
- let effects = [...extraEffects]
173
- let streamFx: DemoEffect[]
174
-
175
- ;[s, streamFx] = startStreaming(s, entry)
176
- effects.push(...streamFx)
177
-
178
- if (fastMode) {
179
- while (s.scriptIdx < script.length && script[s.scriptIdx]!.role !== "user") {
180
- ;[s, streamFx] = startStreaming({ ...s, scriptIdx: s.scriptIdx + 1 }, script[s.scriptIdx]!)
181
- effects.push(...streamFx)
182
- }
183
- effects.push(...autoAdvanceEffects(s))
184
- } else if (entry.role === "user") {
185
- if (s.scriptIdx < script.length && script[s.scriptIdx]!.role === "agent") {
186
- ;[s, streamFx] = startStreaming({ ...s, scriptIdx: s.scriptIdx + 1 }, script[s.scriptIdx]!)
187
- effects.push(...streamFx)
188
- }
189
- }
190
-
191
- return [s, effects]
192
- }
193
-
194
- return function update(state: DemoState, msg: DemoMsg): DemoResult {
195
- switch (msg.type) {
196
- case "mount":
197
- return doAdvance(state, [fx.interval(400, { type: "pulse" }, "pulse")])
198
-
199
- case "advance":
200
- case "autoAdvance": {
201
- if (autoMode && !fastMode && state.streamPhase === "done" && !state.done && !state.compacting) {
202
- const next = script[state.scriptIdx]
203
- if (next?.role === "user") {
204
- return [
205
- { ...state, autoTyping: { full: next.content, revealed: 0 } },
206
- [fx.interval(30, { type: "typingTick" }, "typing")],
207
- ]
208
- }
209
- }
210
- if (autoMode && state.scriptIdx >= script.length && state.streamPhase === "done") {
211
- return { ...state, done: true }
212
- }
213
- return doAdvance(state)
214
- }
215
-
216
- case "typingTick": {
217
- if (!state.autoTyping) return state
218
- const next = state.autoTyping.revealed + 1
219
- if (next >= state.autoTyping.full.length) {
220
- return [
221
- {
222
- ...state,
223
- autoTyping: { ...state.autoTyping, revealed: state.autoTyping.full.length },
224
- },
225
- [fx.cancel("typing"), fx.delay(300, { type: "autoTypingDone" })],
226
- ]
227
- }
228
- return { ...state, autoTyping: { ...state.autoTyping, revealed: next } }
229
- }
230
-
231
- case "autoTypingDone":
232
- return doAdvance({ ...state, autoTyping: null })
233
-
234
- case "endThinking":
235
- return [
236
- { ...state, streamPhase: "streaming", revealFraction: 0 },
237
- [fx.interval(50, { type: "streamTick" }, "reveal")],
238
- ]
239
-
240
- case "streamTick": {
241
- const last = state.exchanges[state.exchanges.length - 1]
242
- const rate = last?.thinking ? 0.08 : 0.12
243
- const frac = Math.min(state.revealFraction + rate, 1)
244
- if (frac < 1) return { ...state, revealFraction: frac }
245
-
246
- const tools = last?.toolCalls ?? []
247
- if (tools.length > 0) {
248
- const s = { ...state, streamPhase: "tools" as StreamPhase, revealFraction: 1 }
249
- return [s, [fx.cancel("reveal"), fx.delay(600 * tools.length, { type: "endTools" })]]
250
- }
251
- const s = { ...state, streamPhase: "done" as StreamPhase, revealFraction: 1 }
252
- return [s, [fx.cancel("reveal"), ...autoAdvanceEffects(s)]]
253
- }
254
-
255
- case "endTools": {
256
- const s = { ...state, streamPhase: "done" as StreamPhase }
257
- return [s, autoAdvanceEffects(s)]
258
- }
259
-
260
- case "submit": {
261
- // Fast-forward streaming if still animating
262
- const base =
263
- state.streamPhase !== "done"
264
- ? { ...state, streamPhase: "done" as StreamPhase, revealFraction: 1, autoTyping: null }
265
- : state.autoTyping
266
- ? { ...state, autoTyping: null }
267
- : state
268
- const cancelEffects: DemoEffect[] =
269
- state.streamPhase !== "done" ? [fx.cancel("reveal"), fx.cancel("typing")] : [fx.cancel("typing")]
270
-
271
- // Empty submit just fast-forwards (no text to queue)
272
- if (!msg.text.trim()) return [base, cancelEffects]
273
- if (base.done) return base
274
-
275
- const s = addExchange(base, {
276
- role: "user",
277
- content: msg.text,
278
- tokens: { input: msg.text.length * 4, output: 0 },
279
- })
280
-
281
- if (s.scriptIdx < script.length) {
282
- let nextIdx = s.scriptIdx
283
- while (nextIdx < script.length && script[nextIdx]!.role === "user") nextIdx++
284
- return [{ ...s, scriptIdx: nextIdx }, [...cancelEffects, fx.delay(150, { type: "autoAdvance" })]]
285
- }
286
-
287
- return [{ ...s, offScript: true }, [...cancelEffects, fx.delay(150, { type: "respondRandom" })]]
288
- }
289
-
290
- case "respondRandom": {
291
- const resp = RANDOM_AGENT_RESPONSES[Math.floor(Math.random() * RANDOM_AGENT_RESPONSES.length)]!
292
- const [s, effects] = startStreaming(state, resp)
293
- return [{ ...s, offScript: true }, effects]
294
- }
295
-
296
- case "compact": {
297
- if (state.done || state.compacting) return state
298
- const cumulative = computeCumulativeTokens(state.exchanges)
299
- return [
300
- {
301
- ...state,
302
- streamPhase: "done",
303
- revealFraction: 1,
304
- compacting: true,
305
- contextBaseline: cumulative.currentContext,
306
- exchanges: state.exchanges,
307
- autoTyping: null,
308
- },
309
- [fx.cancel("reveal"), fx.cancel("typing"), fx.delay(fastMode ? 300 : 3000, { type: "compactDone" })],
310
- ]
311
- }
312
-
313
- case "compactDone":
314
- return doAdvance({ ...state, compacting: false })
315
-
316
- case "pulse":
317
- return { ...state, pulse: !state.pulse }
318
-
319
- case "setCtrlDPending":
320
- return { ...state, ctrlDPending: msg.pending }
321
-
322
- default:
323
- return state
324
- }
325
- }
326
- }
@@ -1,19 +0,0 @@
1
- /** Tool call in an exchange (Read, Edit, Bash, etc.). */
2
- export interface ToolCall {
3
- tool: string
4
- args: string
5
- output: string[]
6
- }
7
-
8
- /** A single exchange in the conversation. */
9
- export interface Exchange {
10
- id: number
11
- role: "user" | "agent" | "system"
12
- content: string
13
- thinking?: string
14
- toolCalls?: ToolCall[]
15
- tokens?: { input: number; output: number }
16
- }
17
-
18
- /** Script entry — exchange data before id is assigned. */
19
- export type ScriptEntry = Omit<Exchange, "id">
@@ -1,198 +0,0 @@
1
- /**
2
- * App Todo - Layer 3 Example
3
- *
4
- * Demonstrates pipe() composition with createApp(), withReact(), and
5
- * withTerminal() — the canonical pattern for building full apps.
6
- *
7
- * The plugin system separates concerns:
8
- * - createApp() — store + event handlers (what the app does)
9
- * - withReact() — element binding (what the app renders)
10
- * - withTerminal() — I/O binding (where the app runs)
11
- *
12
- * pipe() composes them left-to-right: each plugin enhances the
13
- * app object, wrapping run() so the final call needs no arguments.
14
- *
15
- * Usage: bun examples/interactive/app-todo.tsx
16
- *
17
- * Controls:
18
- * j/k - Move cursor down/up
19
- * a - Add new todo
20
- * x - Toggle completed
21
- * d - Delete todo
22
- * Esc/q - Quit
23
- */
24
-
25
- import React from "react"
26
- import { Box, Text, Muted, Kbd } from "../../src/index.js"
27
- import { createApp, useApp } from "@silvery/term/runtime"
28
- import { pipe, withReact, withTerminal } from "@silvery/tea/plugins"
29
- import { ExampleBanner, type ExampleMeta } from "../_banner.js"
30
-
31
- export const meta: ExampleMeta = {
32
- name: "Todo App",
33
- description: "Layer 3: pipe() + createApp() + withReact() + withTerminal()",
34
- features: ["pipe()", "createApp()", "withReact()", "withTerminal()"],
35
- }
36
-
37
- // ============================================================================
38
- // Types
39
- // ============================================================================
40
-
41
- interface Todo {
42
- id: number
43
- text: string
44
- completed: boolean
45
- }
46
-
47
- interface State {
48
- todos: Todo[]
49
- cursor: number
50
- nextId: number
51
- addTodo: (text: string) => void
52
- toggleTodo: () => void
53
- deleteTodo: () => void
54
- moveCursor: (delta: number) => void
55
- }
56
-
57
- // ============================================================================
58
- // Components
59
- // ============================================================================
60
-
61
- function TodoItem({ todo, isCursor }: { todo: Todo; isCursor: boolean }) {
62
- return (
63
- <Box>
64
- <Text color={isCursor ? "$primary" : undefined}>{isCursor ? "› " : " "}</Text>
65
- <Text color={todo.completed ? "$success" : undefined} strikethrough={todo.completed}>
66
- {todo.completed ? "✓" : "○"} {todo.text}
67
- </Text>
68
- </Box>
69
- )
70
- }
71
-
72
- function TodoList() {
73
- const todos = useApp((s: State) => s.todos)
74
- const cursor = useApp((s: State) => s.cursor)
75
-
76
- return (
77
- <Box flexDirection="column">
78
- {todos.map((todo, i) => (
79
- <TodoItem key={todo.id} todo={todo} isCursor={i === cursor} />
80
- ))}
81
- {todos.length === 0 && <Muted>No todos. Press 'a' to add one.</Muted>}
82
- </Box>
83
- )
84
- }
85
-
86
- function TodoApp() {
87
- return (
88
- <Box flexDirection="column" padding={1}>
89
- <TodoList />
90
- <Text> </Text>
91
- <Muted>
92
- <Kbd>j/k</Kbd> move <Kbd>x</Kbd> toggle <Kbd>a</Kbd> add <Kbd>d</Kbd> delete <Kbd>Esc/q</Kbd> quit
93
- </Muted>
94
- </Box>
95
- )
96
- }
97
-
98
- // ============================================================================
99
- // App — pipe() composition
100
- // ============================================================================
101
-
102
- // 1. createApp() defines the store and event handlers
103
- const baseApp = createApp<Record<string, unknown>, State>(
104
- () => (set, get) => ({
105
- todos: [
106
- { id: 1, text: "Learn silvery plugin composition", completed: true },
107
- { id: 2, text: "Build an app with pipe()", completed: false },
108
- { id: 3, text: "Ship to production", completed: false },
109
- ],
110
- cursor: 0,
111
- nextId: 4,
112
-
113
- addTodo: (text: string) =>
114
- set((s) => ({
115
- todos: [...s.todos, { id: s.nextId, text, completed: false }],
116
- nextId: s.nextId + 1,
117
- })),
118
-
119
- toggleTodo: () =>
120
- set((s) => ({
121
- todos: s.todos.map((t, i) => (i === s.cursor ? { ...t, completed: !t.completed } : t)),
122
- })),
123
-
124
- deleteTodo: () =>
125
- set((s) => {
126
- const newTodos = s.todos.filter((_, i) => i !== s.cursor)
127
- return {
128
- todos: newTodos,
129
- cursor: Math.min(s.cursor, newTodos.length - 1),
130
- }
131
- }),
132
-
133
- moveCursor: (delta: number) =>
134
- set((s) => ({
135
- cursor: Math.max(0, Math.min(s.cursor + delta, s.todos.length - 1)),
136
- })),
137
- }),
138
-
139
- {
140
- "term:key": (data: unknown, { get }: { get: () => State }) => {
141
- const { input: k, key } = data as {
142
- input: string
143
- key: { escape: boolean }
144
- }
145
- const state = get()
146
- if (key.escape) return "exit"
147
- switch (k) {
148
- case "j":
149
- state.moveCursor(1)
150
- break
151
- case "k":
152
- state.moveCursor(-1)
153
- break
154
- case "x":
155
- state.toggleTodo()
156
- break
157
- case "d":
158
- if (state.todos.length > 0) state.deleteTodo()
159
- break
160
- case "a":
161
- state.addTodo(`New todo ${state.nextId}`)
162
- break
163
- case "q":
164
- return "exit"
165
- }
166
- },
167
- },
168
- )
169
-
170
- // 2. pipe() composes plugins left-to-right:
171
- // - withReact() binds the element, so run() needs no JSX argument
172
- // - withTerminal() binds stdin/stdout, so run() needs no options
173
- const app = pipe(
174
- baseApp,
175
- withReact(
176
- <ExampleBanner meta={meta} controls="j/k move x toggle a add d delete Esc/q quit">
177
- <TodoApp />
178
- </ExampleBanner>,
179
- ),
180
- withTerminal(process),
181
- )
182
-
183
- // ============================================================================
184
- // Main
185
- // ============================================================================
186
-
187
- async function main() {
188
- // 3. run() needs no arguments — element and terminal are already bound
189
- const handle = await app.run()
190
-
191
- await handle.waitUntilExit()
192
-
193
- console.log("\nFinal state:", handle.store.getState().todos.length, "todos")
194
- }
195
-
196
- if (import.meta.main) {
197
- main().catch(console.error)
198
- }