@bastani/atomic 0.10.14 → 0.10.15-alpha.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 (341) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +3 -3
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +3 -3
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +3 -3
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  10. package/dist/_shared/{sdk-B5LEWGGI.js → sdk-OHKMDJ74.js} +27 -5
  11. package/dist/_shared/{sdk-B5LEWGGI.js.map → sdk-OHKMDJ74.js.map} +1 -1
  12. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  13. package/dist/_shared/startup-0-0-Q3MWKUK4.js +2 -2
  14. package/dist/_shared/startup-0-1-M6OWAYHH.js +2 -2
  15. package/dist/_shared/{startup-0-2-5QHPCEON.js → startup-0-2-2HUMCPKX.js} +14 -16
  16. package/dist/_shared/startup-0-2-2HUMCPKX.js.map +1 -0
  17. package/dist/_shared/startup-0-3-4ZYBYQNM.js +3 -3
  18. package/dist/_shared/startup-0-4-ZMJV547D.js +3 -3
  19. package/dist/_shared/startup-0-5-YDW47QX6.js +3 -3
  20. package/dist/_shared/startup-10-0-TDQNBDDL.js +3 -3
  21. package/dist/_shared/startup-14-0-MLX36RBG.js +1 -1
  22. package/dist/_shared/startup-15-0-YUKGAC63.js +1 -1
  23. package/dist/_shared/startup-15-1-4S7FLMNG.js +6 -30
  24. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  25. package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
  26. package/dist/_shared/startup-8-1-LZFXSD3Z.js +3 -3
  27. package/dist/_shared/storage-command-7MGXLJGZ.js +2 -2
  28. package/dist/_shared/storage-status-K7PX2RXA.js +3 -3
  29. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  30. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  31. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  32. package/dist/builtin/intercom/package.json +1 -1
  33. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  34. package/dist/builtin/mcp/package.json +1 -1
  35. package/dist/builtin/subagents/package.json +1 -1
  36. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  37. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  38. package/dist/builtin/web-access/package.json +1 -1
  39. package/dist/cli/auth-cli.code.js +1 -1
  40. package/dist/cli/auth-cli.impl.js +3 -3
  41. package/dist/cli/auth-cli.js +3 -3
  42. package/dist/cli/blueprint-command.impl.js +3 -3
  43. package/dist/cli/blueprint-command.js +3 -3
  44. package/dist/cli/intercom-command.code.js +3 -3
  45. package/dist/cli/intercom-command.impl.js +3 -3
  46. package/dist/cli/intercom-command.js +3 -3
  47. package/dist/cli/list-models.impl.js +3 -3
  48. package/dist/cli/list-models.js +3 -3
  49. package/dist/cli/session-picker.code.js +1 -1
  50. package/dist/cli/session-picker.impl.js +3 -3
  51. package/dist/cli/session-picker.js +3 -3
  52. package/dist/cli/startup-ui.code.js +1 -1
  53. package/dist/cli/startup-ui.impl.js +3 -3
  54. package/dist/cli/startup-ui.js +3 -3
  55. package/dist/cli/storage-command.impl.js +3 -3
  56. package/dist/cli/storage-command.js +3 -3
  57. package/dist/cli/storage-search-session.code.js +1 -1
  58. package/dist/cli/storage-search-session.impl.js +3 -3
  59. package/dist/cli/storage-search-session.js +3 -3
  60. package/dist/cli/team-command.code.js +1 -1
  61. package/dist/cli/team-command.impl.js +3 -3
  62. package/dist/cli/team-command.js +3 -3
  63. package/dist/cli.js +2 -2
  64. package/dist/core/compaction/compactor.d.ts +0 -8
  65. package/dist/core/debug.impl.js +3 -3
  66. package/dist/core/debug.js +3 -3
  67. package/dist/core/export-html/card-projection.impl.js +3 -3
  68. package/dist/core/export-html/card-projection.js +3 -3
  69. package/dist/core/export-html/index.code.js +2 -2
  70. package/dist/core/export-html/index.impl.js +3 -3
  71. package/dist/core/export-html/index.js +3 -3
  72. package/dist/core/export-html/json-spans.impl.js +3 -3
  73. package/dist/core/export-html/json-spans.js +3 -3
  74. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  75. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  76. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  77. package/dist/core/export-html/tool-renderer.js +3 -3
  78. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  79. package/dist/core/extensions/jiti-loader.js +3 -3
  80. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  81. package/dist/core/extensions/jiti-static-loader.js +3 -3
  82. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  83. package/dist/core/extensions/loader-host-modules.js +3 -3
  84. package/dist/core/intercom-broker-control-host.code.js +1 -1
  85. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  86. package/dist/core/intercom-broker-control-host.js +3 -3
  87. package/dist/core/intercom-broker-control.code.js +2 -2
  88. package/dist/core/intercom-broker-control.impl.js +3 -3
  89. package/dist/core/intercom-broker-control.js +3 -3
  90. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  91. package/dist/core/package-manager-storage-adapters.js +3 -3
  92. package/dist/core/sdk.code.js +1 -1
  93. package/dist/core/sdk.impl.js +3 -3
  94. package/dist/core/sdk.js +3 -3
  95. package/dist/core/session-manager-core.js +3 -3
  96. package/dist/core/session-manager-list.impl.js +3 -3
  97. package/dist/core/session-manager-list.js +3 -3
  98. package/dist/core/session-manager.impl.js +3 -3
  99. package/dist/core/session-manager.js +3 -3
  100. package/dist/core/session-storage.impl.js +3 -3
  101. package/dist/core/session-storage.js +3 -3
  102. package/dist/core/storage/index.js +2 -2
  103. package/dist/core/storage/node-sqlite-thread.js +2 -2
  104. package/dist/core/storage/node-sqlite.js +2 -2
  105. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  106. package/dist/core/storage/offline-snapshot-file.js +3 -3
  107. package/dist/core/storage/provider.js +2 -2
  108. package/dist/core/storage/selection.js +2 -2
  109. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  110. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  111. package/dist/core/storage/session/branch-fork-source.js +3 -3
  112. package/dist/core/storage/session/card-view.impl.js +3 -3
  113. package/dist/core/storage/session/card-view.js +3 -3
  114. package/dist/core/storage/session/child-reader.code.js +2 -2
  115. package/dist/core/storage/session/child-reader.impl.js +3 -3
  116. package/dist/core/storage/session/child-reader.js +3 -3
  117. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  118. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  119. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  120. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  121. package/dist/core/storage/session/expanded-child-details.js +3 -3
  122. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  123. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  124. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  125. package/dist/core/storage/session/fork-row-index.js +3 -3
  126. package/dist/core/storage/session/fork-staging.code.js +1 -1
  127. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  128. package/dist/core/storage/session/fork-staging.js +3 -3
  129. package/dist/core/storage/session/fork-window.code.js +2 -2
  130. package/dist/core/storage/session/fork-window.impl.js +3 -3
  131. package/dist/core/storage/session/fork-window.js +3 -3
  132. package/dist/core/storage/session/history-pages.impl.js +3 -3
  133. package/dist/core/storage/session/history-pages.js +3 -3
  134. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  135. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  136. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  137. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  138. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  139. package/dist/core/storage/session/memory-session-store.js +3 -3
  140. package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
  141. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  142. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  143. package/dist/core/storage/session/released-history-files.code.js +1 -1
  144. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  145. package/dist/core/storage/session/released-history-files.js +3 -3
  146. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  147. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  148. package/dist/core/storage/session/session-resume.impl.js +3 -3
  149. package/dist/core/storage/session/session-resume.js +3 -3
  150. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  151. package/dist/core/storage/session/snapshot-cut.js +3 -3
  152. package/dist/core/storage/session/snapshot-history.code.js +2 -2
  153. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  154. package/dist/core/storage/session/snapshot-history.js +3 -3
  155. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  156. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  157. package/dist/core/storage/session/sql-session-store.js +3 -3
  158. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  159. package/dist/core/storage/session/tree-outline.js +3 -3
  160. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  161. package/dist/core/storage/session/tree-presentation.js +3 -3
  162. package/dist/core/storage/storage-status.impl.js +3 -3
  163. package/dist/core/storage/storage-status.js +3 -3
  164. package/dist/core/storage/team.impl.js +3 -3
  165. package/dist/core/storage/team.js +3 -3
  166. package/dist/core/structured-output/index.code.js +1 -1
  167. package/dist/core/structured-output/index.impl.js +3 -3
  168. package/dist/core/structured-output/index.js +3 -3
  169. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  170. package/dist/core/tasks/task-completion-entry.js +3 -3
  171. package/dist/core/tasks/task-file-history.code.js +2 -2
  172. package/dist/core/tasks/task-file-history.impl.js +3 -3
  173. package/dist/core/tasks/task-file-history.js +3 -3
  174. package/dist/core/tasks/task-reference-archive.code.js +2 -2
  175. package/dist/core/tasks/task-reference-archive.js +3 -3
  176. package/dist/core/tasks/task-reference-identity.js +3 -3
  177. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  178. package/dist/core/tasks/task-reference-stream.js +3 -3
  179. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  180. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  181. package/dist/core/tasks/task-view-source.impl.js +3 -3
  182. package/dist/core/tasks/task-view-source.js +3 -3
  183. package/dist/core/tools/read-url.impl.js +3 -3
  184. package/dist/core/tools/read-url.js +3 -3
  185. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  186. package/dist/core/worktree-snapshot/errors.code.js +1 -1
  187. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  188. package/dist/core/worktree-snapshot/errors.js +3 -3
  189. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  190. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  191. package/dist/extensions/codemode/execute.impl.js +3 -3
  192. package/dist/extensions/codemode/execute.js +3 -3
  193. package/dist/extensions/codemode/renderer.impl.js +3 -3
  194. package/dist/extensions/codemode/renderer.js +3 -3
  195. package/dist/extensions/mcp/cli.code.js +1 -1
  196. package/dist/extensions/mcp/cli.impl.js +3 -3
  197. package/dist/extensions/mcp/cli.js +3 -3
  198. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  199. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  200. package/dist/extensions/mcp/cli.lazy.js +3 -3
  201. package/dist/extensions/mcp/runtime.code.js +1 -1
  202. package/dist/extensions/mcp/runtime.impl.js +3 -3
  203. package/dist/extensions/mcp/runtime.js +3 -3
  204. package/dist/index.d.ts +21 -1
  205. package/dist/index.js +2 -2
  206. package/dist/main-first-time-setup.code.js +1 -1
  207. package/dist/main-first-time-setup.impl.js +3 -3
  208. package/dist/main-first-time-setup.js +3 -3
  209. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  210. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  211. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  212. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  213. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  214. package/dist/modes/print-mode.js +1 -1
  215. package/dist/package-manager-cli.code.js +2 -2
  216. package/dist/package-manager-cli.impl.js +3 -3
  217. package/dist/package-manager-cli.js +3 -3
  218. package/dist/startup-files.json +1 -1
  219. package/dist/startup-stages/6.js +1 -1
  220. package/dist/utils/startup-database-spare.code.js +1 -1
  221. package/dist/utils/startup-database-spare.impl.js +3 -3
  222. package/dist/utils/startup-database-spare.js +3 -3
  223. package/dist/utils/tools-manager.impl.js +3 -3
  224. package/dist/utils/tools-manager.js +3 -3
  225. package/docs/background-tasks/reference.md +182 -0
  226. package/docs/background-tasks.md +98 -405
  227. package/docs/build.md +67 -27
  228. package/docs/changelog.mdx +1 -1
  229. package/docs/codemode.md +108 -39
  230. package/docs/compaction/branch-summaries.md +54 -0
  231. package/docs/compaction/custom-compactors.md +161 -0
  232. package/docs/compaction/memory-compaction.md +77 -0
  233. package/docs/compaction/reference.md +86 -38
  234. package/docs/compaction.md +51 -252
  235. package/docs/computer-use.md +169 -321
  236. package/docs/containerization.md +71 -57
  237. package/docs/custom-provider/api-reference.md +119 -25
  238. package/docs/custom-provider/oauth.md +114 -132
  239. package/docs/custom-provider/override.md +37 -27
  240. package/docs/custom-provider/registration.md +107 -83
  241. package/docs/custom-provider/streaming.md +85 -71
  242. package/docs/custom-provider.md +85 -52
  243. package/docs/development.md +39 -29
  244. package/docs/docs.json +76 -63
  245. package/docs/environment-variables.md +94 -44
  246. package/docs/extensions/api-reference.md +86 -43
  247. package/docs/extensions/authoring.md +162 -154
  248. package/docs/extensions/events.md +80 -25
  249. package/docs/extensions/examples.md +90 -85
  250. package/docs/extensions/ui.md +206 -82
  251. package/docs/extensions.md +79 -108
  252. package/docs/getting-started/authentication.md +67 -36
  253. package/docs/getting-started/first-session.md +53 -43
  254. package/docs/getting-started/installation.md +116 -89
  255. package/docs/getting-started/project-instructions.md +48 -34
  256. package/docs/guides/configuration.md +82 -20
  257. package/docs/guides/non-interactive.md +66 -24
  258. package/docs/guides/resume-on-any-machine.md +135 -82
  259. package/docs/guides/team-setup.md +114 -105
  260. package/docs/guides.md +76 -32
  261. package/docs/herdr.md +15 -16
  262. package/docs/how-atomic-works.md +140 -0
  263. package/docs/index.md +58 -44
  264. package/docs/intercom/operations.md +141 -151
  265. package/docs/intercom/reference.md +85 -108
  266. package/docs/intercom.md +84 -145
  267. package/docs/json.md +120 -67
  268. package/docs/keybindings.md +85 -49
  269. package/docs/libraries/agent-core.md +137 -275
  270. package/docs/libraries/ai.md +100 -84
  271. package/docs/libraries/codemode.md +210 -300
  272. package/docs/libraries/schema.md +59 -53
  273. package/docs/libraries/storage-postgres.md +49 -35
  274. package/docs/libraries/telemetry.md +153 -354
  275. package/docs/libraries/tui.md +265 -393
  276. package/docs/libraries.md +42 -26
  277. package/docs/llama-cpp.md +171 -161
  278. package/docs/mcp-servers.md +90 -51
  279. package/docs/models/choose-a-model.md +188 -0
  280. package/docs/models/reference.md +74 -30
  281. package/docs/models.md +153 -88
  282. package/docs/orchestration/migrating-workflows.md +23 -16
  283. package/docs/orchestration/patterns.md +39 -44
  284. package/docs/orchestration.md +65 -26
  285. package/docs/packages/authoring.md +51 -29
  286. package/docs/packages/reference.md +42 -21
  287. package/docs/packages.md +69 -58
  288. package/docs/programmatic.md +118 -24
  289. package/docs/prompt-templates.md +84 -83
  290. package/docs/providers/reference.md +43 -48
  291. package/docs/providers.md +219 -451
  292. package/docs/quickstart.md +140 -120
  293. package/docs/reference/cli.md +135 -97
  294. package/docs/reference.md +20 -18
  295. package/docs/rpc/examples.md +76 -20
  296. package/docs/rpc/extension-ui.md +64 -38
  297. package/docs/rpc/protocol.md +361 -110
  298. package/docs/rpc.md +57 -17
  299. package/docs/sdk/reference.md +409 -534
  300. package/docs/sdk/storage.md +53 -13
  301. package/docs/sdk/structured-decisions.md +82 -56
  302. package/docs/sdk/web-server.md +57 -43
  303. package/docs/sdk.md +106 -84
  304. package/docs/security.md +42 -64
  305. package/docs/session-format.md +62 -38
  306. package/docs/sessions.md +99 -214
  307. package/docs/settings.md +165 -195
  308. package/docs/shell-aliases.md +9 -6
  309. package/docs/skills/authoring.md +69 -48
  310. package/docs/skills/reference.md +51 -20
  311. package/docs/skills.md +99 -148
  312. package/docs/slash-commands.md +129 -0
  313. package/docs/storage/custom-adapters.md +160 -85
  314. package/docs/storage/jsonl.md +81 -66
  315. package/docs/storage/postgres/pgbouncer.md +120 -126
  316. package/docs/storage/postgres/tuning.md +120 -143
  317. package/docs/storage/postgres.md +314 -330
  318. package/docs/storage/sqlite.md +71 -42
  319. package/docs/storage.md +298 -302
  320. package/docs/subagents/authoring.md +55 -38
  321. package/docs/subagents/reference.md +73 -33
  322. package/docs/subagents.md +119 -187
  323. package/docs/terminal-setup.md +50 -38
  324. package/docs/termux.md +67 -41
  325. package/docs/themes/reference.md +23 -19
  326. package/docs/themes.md +142 -127
  327. package/docs/tmux.md +47 -55
  328. package/docs/tools.md +147 -109
  329. package/docs/tui/reference.md +166 -214
  330. package/docs/tui.md +196 -341
  331. package/docs/usage.md +118 -138
  332. package/docs/verification.md +79 -51
  333. package/docs/web-access.md +121 -101
  334. package/docs/windows.md +26 -27
  335. package/docs/worktree-snapshots/reference.md +245 -0
  336. package/docs/worktree-snapshots.md +71 -259
  337. package/package.json +8 -8
  338. package/dist/_shared/startup-0-2-5QHPCEON.js.map +0 -1
  339. package/docs/guides/intercom.md +0 -32
  340. package/docs/guides/orchestration.md +0 -28
  341. package/docs/guides/subagents.md +0 -37
@@ -4,7 +4,7 @@ sidebarTitle: "@bastani/atomic-tui"
4
4
  description: "Terminal UI framework with differential rendering, alternate-screen viewports, components, overlays, key handling, and images."
5
5
  ---
6
6
 
7
- Minimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLI applications (requires Node.js 24.20+).
7
+ Minimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLI applications (requires Node.js 24.20+). See [Standalone libraries](/libraries) for all standalone packages, or [Build TUI components](/tui) when writing Atomic extensions.
8
8
 
9
9
  ## Installation
10
10
 
@@ -14,16 +14,12 @@ npm install @bastani/atomic-tui
14
14
 
15
15
  ## Features
16
16
 
17
- - **Interchangeable renderers.** Shared `TUI` interface with main-screen and alternate-screen implementations.
18
- - **Differential rendering.** Updates only changed lines or viewport rows.
19
- - **Application-owned scrolling.** Alternate-screen viewport supports mouse, trackpad, and keyboard navigation.
20
- - **Synchronized output.** Uses CSI 2026 for atomic, flicker-free screen updates.
21
- - **Bracketed paste mode.** Handles large pastes with compact markers for pastes over 10 lines.
22
- - **Component-based.** Simple `Component` interface with `render(width)` and optional `renderSized(width, height)`.
23
- - **Theme support.** Components accept theme interfaces for styling.
24
- - **Built-in components.** `Text`, `TruncatedText`, `Input`, `Editor`, `Markdown`, `Loader`, `CancellableLoader`, `SelectList`, `SettingsList`, `MouseRegion`, `Spacer`, `Image`, `Box`, `Container`, `WindowedContainer`, `VStack`, `HStack`, and `ScrollView`.
25
- - **Inline images.** Renders images in terminals supporting Kitty or iTerm2 graphics protocols.
26
- - **Autocomplete support.** File paths and slash commands.
17
+ - **Interchangeable renderers:** Shared `TUI` interface with main-screen (`TuiMainScreen`) and alternate-screen (`TuiAltScreen`) implementations.
18
+ - **Differential rendering & synchronized output:** Updates only changed lines or viewport rows inside CSI 2026 synchronized frames.
19
+ - **Application-owned scrolling:** Alternate-screen viewports support mouse, trackpad, scrollbar dragging, and keyboard navigation.
20
+ - **Bracketed paste & autocomplete:** Compact paste markers for pastes over 10 lines plus slash-command and file-path completion.
21
+ - **Built-in components:** `Text`, `TruncatedText`, `Input`, `Editor`, `Markdown`, `Loader`, `CancellableLoader`, `SelectList`, `SettingsList`, `MouseRegion`, `Spacer`, `Image`, `Box`, `Container`, `WindowedContainer`, `VStack`, `HStack`, and `ScrollView`.
22
+ - **Inline images:** Renders PNG, JPEG, GIF, and WebP images in terminals supporting Kitty or iTerm2 graphics protocols.
27
23
 
28
24
  ## Quick start
29
25
 
@@ -39,11 +35,9 @@ import {
39
35
  TuiMainScreen,
40
36
  } from "@bastani/atomic-tui";
41
37
 
42
- // Create terminal and main-screen renderer
43
38
  const terminal = new ProcessTerminal();
44
39
  const tui: TUI = new TuiMainScreen(terminal);
45
40
 
46
- // Add header text
47
41
  tui.addChild(new Text("Welcome to my app!"));
48
42
 
49
43
  const editorTheme: EditorTheme = {
@@ -66,7 +60,7 @@ tui.addChild(editor);
66
60
  // Focus the editor so it receives keyboard input
67
61
  tui.setFocus(editor);
68
62
 
69
- // In raw mode Ctrl+C does not send SIGINT, so intercept it here to exit
63
+ // In raw mode Ctrl+C does not send SIGINT, so intercept it to exit
70
64
  tui.addInputListener((data) => {
71
65
  if (matchesKey(data, Key.ctrl("c"))) {
72
66
  tui.stop();
@@ -74,7 +68,6 @@ tui.addInputListener((data) => {
74
68
  }
75
69
  });
76
70
 
77
- // Start rendering
78
71
  tui.start();
79
72
  ```
80
73
 
@@ -82,31 +75,50 @@ tui.start();
82
75
 
83
76
  ### TUI interface and renderers
84
77
 
85
- `TUI` is the shared interface for component management, focus, overlays, input, lifecycle, terminal queries, and rendering. Choose a concrete renderer only when constructing the application:
78
+ `TUI` is the shared interface for component management, focus, overlays, input, lifecycle, terminal queries, and rendering. Choose a concrete renderer when constructing the app:
86
79
 
87
- - `TuiMainScreen` renders into the main terminal buffer and preserves terminal scrollback.
88
- - `TuiAltScreen` renders a fixed-height viewport in the alternate terminal buffer with application-owned scrolling. When stopped, it restores the main buffer and prints the complete final document.
80
+ - `new TuiMainScreen(terminal, showHardwareCursor?, logDirectory?)` renders into the main terminal buffer and preserves terminal scrollback.
81
+ - `new TuiAltScreen(terminal, showHardwareCursor?, logDirectory?, options?)` renders a fixed-height viewport in the alternate terminal buffer with application-owned scrolling. When stopped, it restores the main buffer and prints the complete final document.
82
+
83
+ <Note>
84
+ In `new TuiAltScreen(terminal, showHardwareCursor?, logDirectory?, options?)`, `options` (`TuiAltScreenOptions`) is the **fourth** positional argument—pass `undefined` for `showHardwareCursor` and `logDirectory` when you want defaults:
85
+
86
+ ```typescript
87
+ const tui = new TuiAltScreen(terminal, undefined, undefined, { mouse: true, wheelScrollLines: "auto" });
88
+ ```
89
+ </Note>
89
90
 
90
91
  ```typescript
91
92
  import { type TUI, TuiAltScreen, TuiMainScreen } from "@bastani/atomic-tui";
92
93
 
93
94
  const tui: TUI = new TuiMainScreen(terminal);
94
- // To use an application-owned viewport in the alternate terminal buffer instead:
95
- // const tui: TUI = new TuiAltScreen(terminal);
95
+ // Or alternate screen with options:
96
+ // const tui: TUI = new TuiAltScreen(terminal, false, undefined, { copyOnSelect: true });
96
97
 
97
98
  tui.addChild(component);
98
99
  tui.removeChild(component);
99
100
  tui.start();
100
101
  tui.stop();
101
- tui.requestRender(); // Request a re-render
102
+ tui.requestRender();
102
103
 
103
104
  // Global debug key handler (Shift+Ctrl+D)
104
105
  tui.onDebug = () => console.log("Debug triggered");
105
106
  ```
106
107
 
108
+ ### Debug logging and escape timing
109
+
110
+ Four environment variables control standalone TUI diagnostics and escape-key timing (legacy `PI_*` aliases work when `ATOMIC_*` is unset):
111
+
112
+ | Variable | Behavior |
113
+ | --- | --- |
114
+ | `ATOMIC_TUI_WRITE_LOG` | Captures raw ANSI bytes written to stdout (file path, or a directory path for one `tui-<timestamp>-<pid>.log` per process). |
115
+ | `ATOMIC_TUI_DEBUG=1` | Writes main-screen render snapshots to `/tmp/tui/render-<timestamp>-<random>.log` (`TuiMainScreen` only, not `TuiAltScreen`). |
116
+ | `ATOMIC_TUI_DEBUG_REDRAW=1` | Logs main-screen full-redraw triggers to `<logDirectory>/pi-tui-debug.log` (`TuiMainScreen` only; requires `logDirectory` in the constructor; the `pi-` filename prefix is intentional). |
117
+ | `ATOMIC_TUI_ESC_TIMEOUT` | Wait in milliseconds after a lone `ESC` byte before dispatching `Escape` instead of a legacy `Alt`/escape sequence. Defaults to `10` ms locally, `100` ms when `SSH_CONNECTION` or `SSH_TTY` is set. |
118
+
107
119
  ### Colors and terminal styles
108
120
 
109
- Colors are values that can be converted or mixed before terminal rendering:
121
+ Colors are values that can be parsed, converted, or mixed before rendering:
110
122
 
111
123
  ```typescript
112
124
  import {
@@ -130,21 +142,21 @@ const text = styleText(
130
142
  );
131
143
  ```
132
144
 
133
- `Color` is an indexed ANSI color, an sRGB color, or an OKLCH color. Every color converts to sRGB, so color math such as `mixColors()` always works. Indices 0-15 follow the user's terminal palette, so their sRGB values are approximations. `styleText()` converts colors to truecolor or 256-color output based on the requested terminal mode.
145
+ `Color` represents an indexed ANSI color, an sRGB color, or an OKLCH color. Every color converts to sRGB so `mixColors()` always works (ANSI indices `0`–`15` approximate the user's terminal palette). `styleText()` emits truecolor or 256-color ANSI codes based on the requested terminal mode.
134
146
 
135
- `parseColor()` also accepts OKHSL strings using either percentages (`okhsl(250 60% 55%)`) or 0 to 1 decimals (`okhsl(250 0.6 0.55)`), with an optional `deg` unit on the hue. Use `okhslColor(h, s, l)` to construct an OKHSL color in code and `colorToOkhsl()` to read any color's OKHSL channels. OKHSL saturation is relative to the sRGB gamut at that hue and lightness, so every value stays in gamut and equal saturation looks evenly colorful across hues. OKHSL colors convert to sRGB on creation.
147
+ `parseColor()` also accepts OKHSL strings (`okhsl(250 60% 55%)` or `okhsl(250 0.6 0.55)`, with an optional `deg` unit on hue). Use `okhslColor(h, s, l)` and `colorToOkhsl()` in code; OKHSL colors stay inside the sRGB gamut and convert to sRGB on creation.
136
148
 
137
- Conversions are not cached. OKLCH colors, especially ones outside the sRGB gamut, are more expensive to convert than sRGB or indexed colors. For colors used on every render, convert once and reuse the result:
149
+ Because OKLCH conversions are not cached, convert repeated colors once and reuse the resulting sRGB or ANSI sequence:
138
150
 
139
151
  ```typescript
140
152
  const { r, g, b } = colorToRgb(mixColors(accent, background, 0.2));
141
- const foreground = rgbColor(r, g, b); // cheap to render repeatedly
153
+ const foreground = rgbColor(r, g, b);
142
154
  const foregroundCode = foregroundAnsi(foreground, getTerminalColorMode());
143
155
  ```
144
156
 
145
157
  ### Alternate-screen viewport layouts
146
158
 
147
- `TuiAltScreen` can render an explicit terminal-height layout. `VStack` and `HStack` allocate constrained regions, while `ScrollView` owns scrolling for one region. These semantics are intentionally unavailable on `TuiMainScreen`, where the terminal owns scrollback.
159
+ `TuiAltScreen` supports explicit terminal-height layouts built with `VStack`, `HStack`, and `ScrollView` (unavailable on `TuiMainScreen`, where the terminal owns scrollback):
148
160
 
149
161
  ```typescript
150
162
  import {
@@ -158,136 +170,91 @@ import {
158
170
  const transcript = new Container();
159
171
  transcript.addChild(new Text("History"));
160
172
 
161
- const editorAndFooter = new VStack([
162
- editor,
163
- new Text("status"),
164
- ]);
173
+ const editorAndFooter = new VStack([editor, new Text("status")]);
165
174
 
166
175
  if (isViewportTUI(tui)) {
167
- tui.setLayoutRoot(new VStack([
168
- {
169
- component: new ScrollView(transcript, {
170
- follow: "end",
171
- primary: true,
172
- overscroll: "chain",
173
- }),
174
- basis: 0,
175
- grow: 1,
176
- minSize: 1,
177
- },
178
- {
179
- component: editorAndFooter,
180
- basis: "auto",
181
- shrink: 1,
182
- minSize: 1,
183
- },
184
- ]));
176
+ tui.setLayoutRoot(
177
+ new VStack([
178
+ {
179
+ component: new ScrollView(transcript, {
180
+ follow: "end",
181
+ primary: true,
182
+ overscroll: "chain",
183
+ }),
184
+ basis: 0,
185
+ grow: 1,
186
+ minSize: 1,
187
+ },
188
+ {
189
+ component: editorAndFooter,
190
+ basis: "auto",
191
+ shrink: 1,
192
+ minSize: 1,
193
+ },
194
+ ]),
195
+ );
185
196
  }
186
197
  ```
187
198
 
188
- Stack entries support `basis`, `grow`, `shrink`, `minSize`, `maxSize`, and responsive `visible` callbacks. Mouse-wheel input targets the scroll view under the pointer, and unused delta chains to outer scroll views by default.
189
-
190
- The primary scroll view receives alternate-screen keyboard navigation actions and wheel input over non-scrollable regions. It can also jump between OSC 133 semantic prompt markers.
191
-
192
- Press `Ctrl+Shift+F` to open or close the primary scroll view's bordered search panel. The panel displays the configured previous and next shortcuts with clickable arrow controls. By default, `Enter` or `Ctrl+G` moves to the next match, `Shift+Enter` or `Ctrl+Shift+G` moves to the previous match, and `Escape` closes search. Customize match highlighting through `TuiAltScreenOptions.searchMatchStyle` and `searchCurrentMatchStyle`, and arrow button styling through `searchNavigationButtonStyle` (which receives hover state).
193
-
194
- `TuiAltScreenOptions.scrollToEndIndicator` renders a clickable label centered on the last row of a `follow: "end"` primary scroll view while scrolled away from the end. Clicking it resumes end-following.
199
+ Stack entries accept `basis`, `grow`, `shrink`, `minSize`, `maxSize`, and responsive `visible` callbacks. Mouse-wheel input targets the scroll view under the pointer and chains unused delta to outer scroll views by default. The primary scroll view handles alternate-screen keyboard scrolling, OSC 133 prompt jumps, and built-in transcript search (`Ctrl+Shift+F`, with `Enter`/`Ctrl+G` next, `Shift+Enter`/`Ctrl+Shift+G` previous, `Escape` close).
195
200
 
196
201
  **`TuiAltScreenOptions` summary:**
197
202
 
198
203
  | Option | Type | Description |
199
204
  | --- | --- | --- |
200
205
  | `wheelScrollLines` | `number \| "auto"` | Logical lines moved per wheel event (default `1`; `"auto"` accelerates fast spins; Alt+wheel moves 5x). |
201
- | `mouse` | `boolean` | Capture mouse events for scrolling and application-owned text selection. |
206
+ | `mouse` | `boolean` | Capture mouse events for scrolling and application-owned text selection (default `true`). |
202
207
  | `copyOnSelect` | `boolean` | Automatically copy dragged selections on mouse release (default `true`). |
203
208
  | `copySelection` | `(text: string) => Promise<boolean \| string>` | Custom system clipboard writer; falls back to OSC 52 when omitted. |
204
209
  | `openUrl` | `(url: string) => void` | Handler invoked when clicking an OSC 8 hyperlink. |
205
- | `onRightClickPaste` | `() => void` | Secondary-button paste handler (currently Windows only). |
210
+ | `onRightClickPaste` | `() => void` | Secondary-button paste handler (Windows). |
206
211
  | `searchMatchStyle` / `searchCurrentMatchStyle` | `(text: string) => string` | Highlighters for transcript search matches and the active match. |
207
212
  | `searchNavigationButtonStyle` | `(text: string, hovered: boolean) => string` | Styling callback for the search panel's previous/next buttons. |
208
- | `scrollToEndIndicator` | `() => string` | Clickable jump-to-end indicator shown when scrolled away from the bottom. |
213
+ | `scrollToEndIndicator` | `() => string` | Clickable jump-to-end indicator shown when scrolled away from the bottom of a `follow: "end"` primary scroll view. |
209
214
  | `scrollPinnedPrompt` | `{ isPrompt, render }` | Pins matching prompt rows at the top of the scroll viewport. |
210
215
 
211
- Layout geometry is rebuilt for each requested frame. Stateful components are retained, and their existing rendered-line caches remain effective. Calling `render(width)` directly on these layout components produces an unbounded document, which is also used when alt mode restores the main screen.
216
+ Layout geometry rebuilds per frame while retaining stateful components and their rendered-line caches. Calling `render(width)` directly on layout components produces an unbounded document (also used when `TuiAltScreen` stops and prints to the main buffer).
212
217
 
213
218
  ### Overlays
214
219
 
215
- Overlays render components on top of existing content without replacing it. Useful for dialogs, menus, and modal UI.
220
+ Overlays render floating components on top of existing content:
216
221
 
217
222
  ```typescript
218
- // Show overlay with default options (centered, max 80 cols)
219
- const handle = tui.showOverlay(component);
220
-
221
- // Show overlay with custom positioning and sizing
222
- // Values can be numbers (absolute) or percentage strings (e.g., "50%")
223
223
  const handle = tui.showOverlay(component, {
224
- // Sizing
225
- width: 60, // Fixed width in columns
226
- width: "80%", // Width as percentage of terminal
227
- minWidth: 40, // Minimum width floor
228
- maxHeight: 20, // Maximum height in rows
229
- maxHeight: "50%", // Maximum height as percentage of terminal
230
-
231
- // Anchor-based positioning (default: 'center')
232
- anchor: 'bottom-right', // Position relative to anchor point
233
- offsetX: 2, // Horizontal offset from anchor
234
- offsetY: -1, // Vertical offset from anchor
235
-
236
- // Percentage-based positioning (alternative to anchor)
237
- row: "25%", // Vertical position (0%=top, 100%=bottom)
238
- col: "50%", // Horizontal position (0%=left, 100%=right)
239
-
240
- // Absolute positioning (overrides anchor/percent)
241
- row: 5, // Exact row position
242
- col: 10, // Exact column position
243
-
244
- // Margin from terminal edges
245
- margin: 2, // All sides
224
+ // Sizing: number or percentage string
225
+ width: "80%",
226
+ minWidth: 40,
227
+ maxHeight: "50%",
228
+
229
+ // Positioning: absolute row/col > percentage row/col > anchor (default "center")
230
+ anchor: "bottom-right", // center, top-left, top-right, bottom-left, bottom-right, top-center, bottom-center, left-center, right-center
231
+ offsetX: 2,
232
+ offsetY: -1,
233
+
234
+ // Margin clamping from terminal edges
246
235
  margin: { top: 1, right: 2, bottom: 1, left: 2 },
247
236
 
248
- // Responsive visibility
249
- visible: (termWidth, termHeight) => termWidth >= 100 // Hide on narrow terminals
237
+ // Responsive visibility evaluated each frame
238
+ visible: (termWidth, _termHeight) => termWidth >= 100,
250
239
 
251
- // Focus behavior
252
- nonCapturing: true // Don't auto-focus when shown
240
+ // Set true to avoid auto-focusing when shown
241
+ nonCapturing: false,
253
242
  });
254
243
 
255
- // OverlayHandle methods
256
- handle.hide(); // Permanently remove the overlay
257
- handle.setHidden(true); // Temporarily hide (can show again)
258
- handle.setHidden(false); // Show again after hiding
259
- handle.isHidden(); // Check if temporarily hidden
260
- handle.focus(); // Focus and bring to visual front
261
- handle.unfocus(); // Release focus to normal fallback
262
- handle.unfocus({ target: baseComponent }); // Release this overlay to a specific component
263
- handle.unfocus({ target: null }); // Release this overlay and leave focus empty
264
- handle.isFocused(); // Check if overlay has focus
265
- handle.getBounds(); // Get last rendered terminal-relative bounds
266
-
267
- handle.unfocus();
268
- // Overlay loses focus; TUI falls back to another visible capturing overlay or the previous focus target.
269
-
270
- handle.unfocus({ target: null });
271
- // Overlay loses focus; no component receives input until focus is set again.
272
-
273
- // A focused visible overlay reclaims keyboard input after temporary replacement UI
274
- // releases focus. If you want a specific component to receive input while overlays remain
275
- // visible, call handle.unfocus({ target: component }).
276
-
277
- // Hide topmost overlay
278
- tui.hideOverlay();
279
-
280
- // Check if any visible overlay is active
281
- tui.hasOverlay();
244
+ handle.hide(); // Permanently remove
245
+ handle.setHidden(true); // Temporarily hide
246
+ handle.isHidden();
247
+ handle.focus(); // Focus and bring to front
248
+ handle.unfocus(); // Release focus to fallback target
249
+ handle.unfocus({ target: baseComponent }); // Release focus to a specific component (or null)
250
+ handle.isFocused();
251
+ handle.getBounds(); // Last rendered terminal-relative bounds
252
+
253
+ tui.hideOverlay(); // Hide topmost overlay
254
+ tui.hasOverlay(); // Check if any visible overlay is active
282
255
  ```
283
256
 
284
- **Anchor values**: `'center'`, `'top-left'`, `'top-right'`, `'bottom-left'`, `'bottom-right'`, `'top-center'`, `'bottom-center'`, `'left-center'`, `'right-center'`
285
-
286
- **Resolution order**:
287
- 1. `minWidth` is applied as a floor after width calculation
288
- 2. For position: absolute `row`/`col` > percentage `row`/`col` > `anchor`
289
- 3. `margin` clamps final position to stay within terminal bounds
290
- 4. `visible` callback controls whether overlay renders (called each frame)
257
+ A focused visible overlay reclaims input after temporary non-overlay replacement UI closes; use `handle.unfocus({ target })` to send input elsewhere while keeping the overlay visible.
291
258
 
292
259
  ### Component interface
293
260
 
@@ -310,24 +277,37 @@ interface Component {
310
277
 
311
278
  | Member | Description |
312
279
  | --- | --- |
313
- | `render(width)` | Returns an array of strings, one per line. Each line **must not exceed `width`** or the TUI throws an error. Use `truncateToWidth()` or manual wrapping. |
280
+ | `render(width)` | Returns one string per line. Each line **must not exceed `width`** or the TUI throws an error; use `truncateToWidth()` or `wrapTextWithAnsi()`. |
314
281
  | `renderSized?(width, height)` | Optional sized renderer invoked instead of `render()` when a layout slot allocates a fixed row height. |
315
- | `handleInput?(data)` | Called when the component has focus and receives keyboard input. The `data` string contains raw terminal input, which may include ANSI escape sequences. |
316
- | `handleMouse?(event)` | Called by `TuiAltScreen` for normalized pointer input targeted at the component. |
317
- | `paintedRowKey?(row)` | Optional stable identity for what the last render drew on `row`, so press and release become a click only when both target the same item across repaints. |
318
- | `selectionTextMayChangeOnReplay` | Set to `true` on a `WindowedContainer` component whose text cannot be recreated from saved input. Fullscreen selection then keeps the selected fragments in memory until dismissed or replaced. Leave unset for deterministic rows. |
319
- | `historyReplayable` | Set to `true` on a chat-rendered component that can be discarded offscreen and recreated from saved input without losing state. |
282
+ | `handleInput?(data)` | Receives raw keyboard input (including ANSI/Kitty escape sequences) while focused. |
283
+ | `handleMouse?(event)` | Receives normalized pointer input targeted at the component in `TuiAltScreen`. |
284
+ | `paintedRowKey?(row)` | Optional stable identity for what the last render drew on `row`, so press and release become a click only when both hit the same item across repaints. |
285
+ | `selectionTextMayChangeOnReplay` | Set `true` on a `WindowedContainer` child whose text cannot be recreated from saved input, keeping selected fragments in memory until dismissed. |
286
+ | `historyReplayable` | Set `true` on a component that can be evicted offscreen and recreated from saved input without losing state. |
320
287
  | `wantsKeyRelease` | When `true`, receives Kitty key release events in `handleInput()`. Default: `false`. |
321
- | `capturesViewportInput` | When `true` on the focused component, `TuiAltScreen` forwards viewport scrolling and prompt-jump keys (`tui.altScreen.*` except search) to the component instead of scrolling the viewport, matching focused overlays. `SelectList`, `SettingsList`, and `Editor` (while autocomplete is open) set this so PageUp and PageDown move selection. Use `getSelectPageIndex(keybindings, data, selectedIndex, itemCount, pageSize)` to compute page movement. |
322
- | `invalidate()` | Required. Clears cached render state so the next `render()` rebuilds from scratch. Stateless components can leave the body empty. |
288
+ | `capturesViewportInput` | When `true` on the focused component, `TuiAltScreen` forwards viewport navigation keys (`tui.altScreen.pageUp`, `pageDown`, `halfPageUp`, `halfPageDown`, `lineUp`, `lineDown`, `previousPrompt`, `nextPrompt`, `top`, `bottom`) to the component instead of scrolling the viewport (search keys `tui.altScreen.search*` remain handled by `TuiAltScreen`). `SelectList`, `SettingsList`, and `Editor` (while autocomplete is open) set this flag. |
289
+ | `invalidate()` | Required. Clears cached render state so the next `render()` rebuilds cleanly. |
323
290
 
324
- The TUI appends a full SGR reset and OSC 8 reset at the end of each rendered line, so styles do not carry across lines. Reapply styles per line or use `wrapTextWithAnsi()` to preserve styling across wrapped lines.
291
+ For selectable lists that set `capturesViewportInput = true`, use `getSelectPageIndex()` to compute page jumps cleanly:
292
+
293
+ ```typescript
294
+ import { getKeybindings, getSelectPageIndex } from "@bastani/atomic-tui";
295
+
296
+ // Returns the next clamped index on tui.select.pageUp / tui.select.pageDown,
297
+ // or undefined for any other key (returns 0 on an empty list, so guard itemCount > 0).
298
+ const nextIndex = getSelectPageIndex(getKeybindings(), data, selectedIndex, items.length, maxVisible);
299
+ if (nextIndex !== undefined && items.length > 0) {
300
+ selectedIndex = nextIndex;
301
+ }
302
+ ```
303
+
304
+ The TUI appends a full SGR reset and OSC 8 reset at the end of every rendered line, so styles never leak across lines; reapply styles per line or use `wrapTextWithAnsi()`.
325
305
 
326
306
  ### Mouse input
327
307
 
328
- `TuiAltScreen` normalizes SGR mouse input and hit-tests components and overlays. Events contain component-local `x` and `y`, absolute `screenX` and `screenY`, bounds, button, modifiers, click count, and wheel delta. `TuiMainScreen` does not capture mouse input because the terminal owns its scrollback.
308
+ `TuiAltScreen` normalizes SGR mouse input and hit-tests components and overlays (`TuiMainScreen` does not capture mouse input). Events include component-local `x`/`y`, absolute `screenX`/`screenY`, bounds, button, modifiers, `clickCount` (`1`, `2`, or `3`), and wheel delta.
329
309
 
330
- `isPointerIdle()` returns `true` while no text selection, press, drag, pending single click, or search depends on row positions. To observe changes without polling, `onViewportChange(listener)` invokes the listener at most once per event-loop turn after each input, deferred single click, or painted frame, and returns an unsubscribe function.
310
+ `isPointerIdle()` returns `true` when no selection, press, drag, pending single click, or search depends on row positions. `onViewportChange(listener)` fires at most once per event-loop turn after input, deferred clicks, or painted frames, and returns an unsubscribe function.
331
311
 
332
312
  ```typescript
333
313
  import type { TuiMouseEvent, TuiMouseEventResult } from "@bastani/atomic-tui";
@@ -348,43 +328,26 @@ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
348
328
  }
349
329
  ```
350
330
 
351
- Returning `handled` suppresses renderer fallback behavior. `capture` routes subsequent drag and release events to the same component, and `focus` requests keyboard focus. The optional `render` flag controls repainting: press, click, drag, and wheel repaint by default, while move and release do not. Set `render: true` when hover state changes visibly, or `render: false` for a handled no-op. Render requests coalesce and output remains differential.
352
-
353
- Each click carries `clickCount` (`1`, `2`, or `3`). When a single click should perform an action that a double-click must not (such as expanding a block whose text a double-click would select), return `{ handled: true, whenSingleClick: () => toggle() }` instead of running it immediately. `TuiAltScreen` invokes `whenSingleClick` once `MULTI_CLICK_INTERVAL_MS` (500 ms) passes after the press with no second press on the same spot, then repaints.
354
-
355
- A second press at that location cancels the deferred action even if the button stays held past the deadline, and the same timing applies when the component handles the press itself. Pass `onSingleClickCancel` alongside `whenSingleClick` to release any reserved resources on cancellation. Hiding or removing an overlay cancels its pending single-click action even if you show it again before a repaint.
331
+ - `handled`: suppresses renderer fallback behavior.
332
+ - `capture`: routes subsequent drag and release events to the same component.
333
+ - `focus`: requests keyboard focus.
334
+ - `render`: overrides default repainting (press, click, drag, and wheel repaint by default; move and release do not).
335
+ - `whenSingleClick` / `onSingleClickCancel`: defers a single-click action until `MULTI_CLICK_INTERVAL_MS` (`500` ms) elapses without a second press at the same spot (so double-clicks can select text without triggering single-click toggles). Capture item identity rather than screen coordinates and read mutable state inside the callback; hiding or removing an overlay cancels its pending single click.
356
336
 
357
- A held single click does not trigger `whenSingleClick` on release, though a control that claimed the press still receives button-up. When a double- or triple-click also selects text, a row that did not take the press still decides whether to handle the click or let the terminal copy the selection.
358
-
359
- Capture the clicked item's identity rather than its screen coordinates because items can move before the callback runs. Read mutable state when the action executes rather than when the click arrives: two fast clicks on different rows are both single clicks, so the first may run right before the second.
360
-
361
- Unhandled gestures retain alternate-screen defaults: wheel input scrolls the nearest `ScrollView` and chains unused delta, primary-button drags select text, OSC 8 links open before parent click handlers, and unhandled right-click runs configured paste behavior. Click events fire only when press and release complete without a drag.
362
-
363
- Use `MouseRegion` to attach mouse handling without changing a component's rendering:
364
-
365
- ```typescript
366
- const collapsible = new MouseRegion(content, (event) => {
367
- if (event.type !== "click" || event.button !== "left") return undefined;
368
- expanded = !expanded;
369
- return { handled: true };
370
- });
371
- ```
372
-
373
- `Container` and `Box` route events to nested children using geometry recorded during the last frame, so pointer motion does not rerender children just to hit-test them. Explicit `VStack`, `HStack`, and `ScrollView` layouts use the alternate-screen layout frame directly.
337
+ Unhandled gestures keep alternate-screen defaults: wheel scrolls the nearest `ScrollView` (chaining unused delta), primary drags select text, OSC 8 links open before parent click handlers, and right-click runs `onRightClickPaste`. Wrap any component with `new MouseRegion(content, handler)` to add mouse handling without changing its rendering.
374
338
 
375
339
  ### Focusable interface (IME support)
376
340
 
377
- Components that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface:
341
+ Components displaying a text cursor that need IME (Input Method Editor) candidate-window positioning should implement `Focusable`:
378
342
 
379
343
  ```typescript
380
344
  import { CURSOR_MARKER, type Component, type Focusable, renderFakeCursor } from "@bastani/atomic-tui";
381
345
 
382
346
  class MyInput implements Component, Focusable {
383
- focused: boolean = false; // Set by TUI when focus changes
384
-
385
- render(width: number): string[] {
347
+ focused = false; // Set by TUI when focus changes
348
+
349
+ render(_width: number): string[] {
386
350
  const marker = this.focused ? CURSOR_MARKER : "";
387
- // Emit marker right before the fake cursor
388
351
  return [`> ${beforeCursor}${marker}${renderFakeCursor(atCursor)}${afterCursor}`];
389
352
  }
390
353
 
@@ -392,27 +355,20 @@ class MyInput implements Component, Focusable {
392
355
  }
393
356
  ```
394
357
 
395
- When a `Focusable` component has focus, TUI:
396
- 1. Sets `focused = true` on the component
397
- 2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence)
398
- 3. Positions the hardware terminal cursor at that location
399
- 4. Shows the hardware cursor only when `showHardwareCursor` is enabled
400
-
401
- `renderFakeCursor()` wraps the cursor cell in zero-width markers. TUI renders them as reverse video. When `showHardwareCursor` is enabled, TUI removes the fake cursor that directly follows `CURSOR_MARKER`, so the focused component shows only the terminal cursor. Fake cursors without a preceding `CURSOR_MARKER` stay visible.
402
-
403
- The hardware cursor remains hidden by default. This keeps the fake cursor rendering, while still positioning the hardware cursor for terminals that track IME candidate windows with hidden cursors. Some terminals require a visible hardware cursor for IME positioning; enable it with the renderer constructor's `showHardwareCursor` argument or `setShowHardwareCursor(true)`. The `Editor` and `Input` built-in components already implement this interface.
358
+ When a `Focusable` component has focus, TUI locates `CURSOR_MARKER`, positions the hardware terminal cursor there, and shows the hardware cursor only when `showHardwareCursor` is enabled (hiding the directly following `renderFakeCursor()` reverse-video cell so only the real cursor renders). Built-in `Editor` and `Input` implement `Focusable` automatically.
404
359
 
405
- **Container components with embedded inputs:** When a container component (dialog, selector, etc.) contains an `Input` or `Editor` child, the container must implement `Focusable` and propagate the focus state to the child:
360
+ Container components wrapping an `Input` or `Editor` must also implement `Focusable` and propagate `focused` to their child input so IME candidate windows position accurately:
406
361
 
407
362
  ```typescript
408
363
  import { Container, type Focusable, Input } from "@bastani/atomic-tui";
409
364
 
410
365
  class SearchDialog extends Container implements Focusable {
411
- private searchInput: Input;
412
-
413
- // Propagate focus to child input for IME cursor positioning
366
+ private searchInput = new Input();
414
367
  private _focused = false;
415
- get focused(): boolean { return this._focused; }
368
+
369
+ get focused(): boolean {
370
+ return this._focused;
371
+ }
416
372
  set focused(value: boolean) {
417
373
  this._focused = value;
418
374
  this.searchInput.focused = value;
@@ -420,19 +376,16 @@ class SearchDialog extends Container implements Focusable {
420
376
 
421
377
  constructor() {
422
378
  super();
423
- this.searchInput = new Input();
424
379
  this.addChild(this.searchInput);
425
380
  }
426
381
  }
427
382
  ```
428
383
 
429
- Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position.
430
-
431
384
  ## Built-in components
432
385
 
433
386
  ### Container
434
387
 
435
- Groups child components vertically.
388
+ Groups child components vertically:
436
389
 
437
390
  ```typescript
438
391
  const container = new Container();
@@ -442,52 +395,68 @@ container.removeChild(component);
442
395
 
443
396
  ### WindowedContainer
444
397
 
445
- Virtualized vertical container for large transcripts inside `ScrollView`. Keeps only visible children mounted in memory and materializes or evicts off-screen rows on demand (respecting `historyReplayable` and `selectionTextMayChangeOnReplay` for fullscreen text selection).
398
+ Virtualized vertical container for large transcripts inside `ScrollView`. Keeps only visible children mounted in memory and materializes or evicts off-screen rows on demand while respecting `historyReplayable` and `selectionTextMayChangeOnReplay`.
399
+
400
+ Key supporting contracts exported alongside `WindowedContainer`:
401
+
402
+ | Type | Purpose |
403
+ | --- | --- |
404
+ | `HistorySource` | `{ readonly last: number; read(from, to, width): Promise<readonly HistoryRowsBlock[]> }` — supplies unmounted saved rows on demand (for scrolling and fullscreen copy across evicted history). |
405
+ | `WindowRequest` | `{ width, top, moved?, exact?, height, followEnd, requestRender }` — viewport request passed by `ScrollView` to compute a visible row window. |
406
+ | `WindowRows` | Virtualized row accessor (`length`, `at(index)`, plus optional row tracking and history inspection hooks) returned for a layout frame. |
407
+ | `WindowLayout` | Extends `WindowRows` with the resolved `top` offset for the frame. |
446
408
 
447
409
  ### Box
448
410
 
449
- Container that applies padding and background color to all children.
411
+ Container applying padding and optional background styling to all children:
450
412
 
451
413
  ```typescript
414
+ import { Box, getTerminalColorMode, parseColor, styleText, Text } from "@bastani/atomic-tui";
415
+
416
+ const mode = getTerminalColorMode();
417
+ const bgGray = (s: string) => styleText(s, { bg: parseColor("#30343c") }, mode);
418
+ const bgBlue = (s: string) => styleText(s, { bg: parseColor("#1e3a5f") }, mode);
419
+
452
420
  const box = new Box(
453
- 1, // paddingX (default: 1)
454
- 1, // paddingY (default: 1)
455
- (text) => chalk.bgGray(text) // optional background function
421
+ 1, // paddingX (default: 1)
422
+ 1, // paddingY (default: 1)
423
+ bgGray, // optional background function
456
424
  );
457
425
  box.addChild(new Text("Content"));
458
- box.setBgFn((text) => chalk.bgBlue(text)); // Change background dynamically
426
+ box.setBgFn(bgBlue); // update background dynamically
459
427
  ```
460
428
 
461
429
  ### Text
462
430
 
463
- Displays multi-line text with word wrapping and padding.
431
+ Multi-line text with word wrapping, padding, and optional background function:
464
432
 
465
433
  ```typescript
466
- const text = new Text(
467
- "Hello World", // text content
468
- 1, // paddingX (default: 1)
469
- 1, // paddingY (default: 1)
470
- (text) => chalk.bgGray(text) // optional background function
471
- );
434
+ import { getTerminalColorMode, parseColor, styleText, Text } from "@bastani/atomic-tui";
435
+
436
+ const mode = getTerminalColorMode();
437
+ const bgGray = (s: string) => styleText(s, { bg: parseColor("#30343c") }, mode);
438
+ const bgBlue = (s: string) => styleText(s, { bg: parseColor("#1e3a5f") }, mode);
439
+
440
+ const text = new Text("Hello World", 1, 1, bgGray);
472
441
  text.setText("Updated text");
473
- text.setCustomBgFn((text) => chalk.bgBlue(text));
442
+ text.setCustomBgFn(bgBlue);
474
443
  ```
475
444
 
476
445
  ### TruncatedText
477
446
 
478
- Single-line text that truncates to fit viewport width. Useful for status lines and headers.
447
+ Single-line text that truncates to viewport width (useful for headers and status bars):
479
448
 
480
449
  ```typescript
481
450
  const truncated = new TruncatedText(
482
451
  "This is a very long line that will be truncated...",
483
- 0, // paddingX (default: 0)
484
- 0 // paddingY (default: 0)
452
+ 0, // paddingX (default: 0)
453
+ 0, // paddingY (default: 0)
485
454
  );
486
455
  ```
487
456
 
488
457
  ### Input
489
458
 
490
- Single-line text input with horizontal scrolling.
459
+ Single-line text input with horizontal scrolling (click to position cursor and focus in `TuiAltScreen`):
491
460
 
492
461
  ```typescript
493
462
  const input = new Input();
@@ -496,21 +465,11 @@ input.setValue("initial");
496
465
  input.getValue();
497
466
  ```
498
467
 
499
- Clicking positions the cursor and gives the input keyboard focus in alternate-screen mode.
500
-
501
- **Key bindings:**
502
-
503
- - `Enter`: Submit
504
- - `Ctrl+A` / `Ctrl+E`: Line start or end
505
- - `Ctrl+W` or `Alt+Backspace`: Delete word backwards
506
- - `Ctrl+U`: Delete to start of line
507
- - `Ctrl+K`: Delete to end of line
508
- - `Ctrl+Left` / `Ctrl+Right` or `Alt+Left` / `Alt+Right`: Word navigation
509
- - Arrow keys, `Backspace`, and `Delete`: Standard cursor and character editing
468
+ Supports `Enter` (submit), `Ctrl+A`/`Ctrl+E` (line start/end), `Ctrl+W`/`Alt+Backspace` (delete word back), `Ctrl+U`/`Ctrl+K` (delete to start/end), `Ctrl+Left`/`Right` or `Alt+Left`/`Right` (word jump), and standard cursor editing.
510
469
 
511
470
  ### Editor
512
471
 
513
- Multi-line text editor with autocomplete, file completion, paste handling, and vertical scrolling when content exceeds terminal height.
472
+ Multi-line text editor with autocomplete, paste markers (over 10 lines), history, click-to-position cursor, and height-aware scrolling:
514
473
 
515
474
  ```typescript
516
475
  interface EditorTheme {
@@ -520,50 +479,28 @@ interface EditorTheme {
520
479
  }
521
480
 
522
481
  interface EditorOptions {
523
- paddingX?: number; // Horizontal padding (default: 0)
524
- autocompleteMaxVisible?: number; // Maximum visible autocomplete rows
482
+ paddingX?: number; // Horizontal padding (default: 0)
483
+ autocompleteMaxVisible?: number; // Maximum visible autocomplete rows
525
484
  }
526
485
 
527
- const editor = new Editor(tui, theme, options?); // tui is required for height-aware scrolling
486
+ const editor = new Editor(tui, theme, options?);
528
487
  editor.onSubmit = (text) => console.log(text);
529
488
  editor.onChange = (text) => console.log("Changed:", text);
530
- editor.disableSubmit = true; // Disable submit temporarily
489
+ editor.disableSubmit = true;
531
490
  editor.setAutocompleteProvider(provider);
532
- editor.borderColor = (s) => chalk.blue(s); // Change border dynamically
533
- editor.setPaddingX(1); // Update horizontal padding dynamically
534
- editor.getPaddingX(); // Get current padding
535
- editor.getHistory();
491
+ editor.borderColor = (s) => `\x1b[34m${s}\x1b[0m`; // update border color dynamically
492
+ editor.setPaddingX(1);
493
+ editor.getPaddingX();
494
+ editor.getHistory(); // past prompts, newest first
536
495
  ```
537
496
 
538
- `getHistory()` returns past prompts, newest first. `autocompleteHint` draws one line below an open completion menu. Its entries name the available actions and labels, with `essential` marking actions to keep on narrow terminals. Resolve `actions` through the active keybindings; when `resolvedKeys` is present, use those keys instead (including an empty array, because `CustomEditor` supplies only keys that reach the menu after app shortcuts). Without `autocompleteHint`, the editor draws no menu hint.
539
-
540
- **Features:**
541
-
542
- - Click-to-position cursor and clickable autocomplete rows in alternate-screen mode
543
- - Multi-line editing with word wrap
544
- - Slash command autocomplete (type `/`)
545
- - File path autocomplete (press `Tab`)
546
- - Large paste handling (more than 10 lines creates a `[paste #1 +50 lines]` marker)
547
- - Horizontal lines above and below the editor
548
- - Fake cursor rendering (hidden real cursor)
549
-
550
- **Key bindings:**
497
+ `autocompleteHint` draws one line below an open completion menu, using `resolvedKeys` when provided (including an empty array when outer shortcuts shadow keys) and keeping `essential` entries on narrow terminals.
551
498
 
552
- - `Enter`: Submit
553
- - `Shift+Enter`, `Ctrl+Enter`, or `Alt+Enter`: New line (terminal-dependent; `Alt+Enter` is the most reliable)
554
- - `Tab`: Autocomplete
555
- - `Ctrl+K`: Delete to end of line
556
- - `Ctrl+U`: Delete to start of line
557
- - `Ctrl+W` or `Alt+Backspace`: Delete word backwards
558
- - `Alt+D` or `Alt+Delete`: Delete word forwards
559
- - `Ctrl+A` / `Ctrl+E`: Line start or end
560
- - `Ctrl+]`: Jump forward to character (awaits next keypress, then moves cursor to first occurrence)
561
- - `Ctrl+Alt+]`: Jump backward to character
562
- - Arrow keys, `Backspace`, and `Delete`: Standard cursor and character editing
499
+ Supports `Enter` (submit), `Shift+Enter`/`Ctrl+Enter`/`Alt+Enter` (newline), `Tab` (autocomplete), `Ctrl+A`/`Ctrl+E`, `Ctrl+U`/`Ctrl+K`, `Ctrl+W`/`Alt+Backspace`, `Alt+D`/`Alt+Delete`, and `Ctrl+]`/`Ctrl+Alt+]` (jump forward/backward to next typed character).
563
500
 
564
501
  ### Markdown
565
502
 
566
- Renders markdown with syntax highlighting and theming support.
503
+ Renders Markdown with optional syntax highlighting, LaTeX math rendering, caching, and per-instance options:
567
504
 
568
505
  ```typescript
569
506
  interface MarkdownTheme {
@@ -582,6 +519,7 @@ interface MarkdownTheme {
582
519
  strikethrough: (text: string) => string;
583
520
  underline: (text: string) => string;
584
521
  highlightCode?: (code: string, lang?: string) => string[];
522
+ codeBlockIndent?: string; // Prefix per rendered code block line (default: " ")
585
523
  }
586
524
 
587
525
  interface DefaultTextStyle {
@@ -593,63 +531,52 @@ interface DefaultTextStyle {
593
531
  underline?: boolean;
594
532
  }
595
533
 
534
+ interface MarkdownOptions {
535
+ hyperlinks?: boolean; // Override OSC 8 hyperlink emission for this instance
536
+ images?: boolean; // Override inline image rendering for this instance
537
+ preserveOrderedListMarkers?: boolean; // Keep original ordered list numbering
538
+ preserveBackslashEscapes?: boolean; // Keep backslash-escaped punctuation verbatim
539
+ transform?: (markdown: string, availableWidth: number) => string; // Pre-parse transform
540
+ renderLatex?: boolean; // Render supported LaTeX math as Unicode (default: true)
541
+ }
542
+
596
543
  const md = new Markdown(
597
544
  "# Hello\n\nSome **bold** text",
598
- 1, // paddingX
599
- 1, // paddingY
600
- theme, // MarkdownTheme
601
- defaultStyle // optional DefaultTextStyle
545
+ 1, // paddingX
546
+ 1, // paddingY
547
+ theme, // MarkdownTheme
548
+ defaultStyle, // optional DefaultTextStyle
549
+ options, // optional MarkdownOptions
602
550
  );
603
551
  md.setText("Updated markdown");
604
552
  ```
605
553
 
606
- **Features:**
607
- - Headings, bold, italic, code blocks, lists, links, blockquotes
608
- - HTML tags rendered as plain text
609
- - Optional syntax highlighting via `highlightCode`
610
- - Padding support
611
- - Render caching for performance
554
+ HTML tags render as plain text, and top-level blocks cache syntax-highlighted lines across resizes until `invalidate()`.
612
555
 
613
- ### Loader
556
+ ### Loader and CancellableLoader
614
557
 
615
- Animated loading spinner.
558
+ Animated spinners (`CancellableLoader` adds `Escape` cancellation and an `AbortSignal`):
616
559
 
617
560
  ```typescript
618
- const loader = new Loader(
619
- tui, // TUI instance for render updates
620
- (s) => chalk.cyan(s), // spinner color function
621
- (s) => chalk.gray(s), // message color function
622
- "Loading..." // message (default: "Loading...")
623
- );
561
+ import { CancellableLoader, Loader } from "@bastani/atomic-tui";
562
+
563
+ const cyan = (s: string) => `\x1b[36m${s}\x1b[0m`;
564
+ const gray = (s: string) => `\x1b[90m${s}\x1b[0m`;
565
+
566
+ const loader = new Loader(tui, cyan, gray, "Loading...");
624
567
  loader.start();
625
568
  loader.setMessage("Still loading...");
626
569
  loader.stop();
627
- ```
628
-
629
- ### CancellableLoader
630
-
631
- Extends Loader with Escape key handling and an AbortSignal for cancelling async operations.
632
570
 
633
- ```typescript
634
- const loader = new CancellableLoader(
635
- tui, // TUI instance for render updates
636
- (s) => chalk.cyan(s), // spinner color function
637
- (s) => chalk.gray(s), // message color function
638
- "Working..." // message
639
- );
640
- loader.onAbort = () => done(null); // Called when user presses Escape
641
- doAsyncWork(loader.signal).then(done);
571
+ const cancellable = new CancellableLoader(tui, cyan, gray, "Working...");
572
+ cancellable.onAbort = () => done(null); // triggered on Escape
573
+ // cancellable.signal: AbortSignal, cancellable.aborted: boolean
574
+ doAsyncWork(cancellable.signal).then(done);
642
575
  ```
643
576
 
644
- **Properties:**
645
-
646
- - `signal: AbortSignal`: Aborted when the user presses `Escape`.
647
- - `aborted: boolean`: Whether the loader was aborted.
648
- - `onAbort?: () => void`: Callback invoked when the user presses `Escape`.
649
-
650
577
  ### SelectList
651
578
 
652
- Interactive selection list with keyboard navigation.
579
+ Interactive selection list with keyboard and mouse navigation:
653
580
 
654
581
  ```typescript
655
582
  interface SelectItem {
@@ -671,26 +598,19 @@ const list = new SelectList(
671
598
  { value: "opt1", label: "Option 1", description: "First option" },
672
599
  { value: "opt2", label: "Option 2", description: "Second option" },
673
600
  ],
674
- 5, // maxVisible
675
- theme // SelectListTheme
601
+ 5, // maxVisible
602
+ theme, // SelectListTheme
676
603
  );
677
604
 
678
605
  list.onSelect = (item) => console.log("Selected:", item);
679
606
  list.onCancel = () => console.log("Cancelled");
680
607
  list.onSelectionChange = (item) => console.log("Highlighted:", item);
681
- list.setFilter("opt"); // Filter items
608
+ list.setFilter("opt");
682
609
  ```
683
610
 
684
- **Controls:**
685
- - Mouse move/wheel: Highlight rows in alternate-screen mode
686
- - Click: Select a row
687
- - Arrow keys: Navigate
688
- - Enter: Select
689
- - Escape: Cancel
690
-
691
611
  ### SettingsList
692
612
 
693
- Settings panel with value cycling and submenus.
613
+ Settings panel with value cycling and submenus:
694
614
 
695
615
  ```typescript
696
616
  interface SettingItem {
@@ -698,7 +618,7 @@ interface SettingItem {
698
618
  label: string;
699
619
  description?: string;
700
620
  currentValue: string;
701
- values?: string[]; // If provided, Enter/Space cycles through these
621
+ values?: string[];
702
622
  submenu?: (currentValue: string, done: (selectedValue?: string) => void) => Component;
703
623
  }
704
624
 
@@ -713,26 +633,19 @@ interface SettingsListTheme {
713
633
  const settings = new SettingsList(
714
634
  [
715
635
  { id: "theme", label: "Theme", currentValue: "dark", values: ["dark", "light"] },
716
- { id: "model", label: "Model", currentValue: "gpt-4", submenu: (val, done) => modelSelector },
636
+ { id: "model", label: "Model", currentValue: "gpt-4", submenu: (_val, _done) => modelSelector },
717
637
  ],
718
- 10, // maxVisible
719
- theme, // SettingsListTheme
638
+ 10,
639
+ theme,
720
640
  (id, newValue) => console.log(`${id} changed to ${newValue}`),
721
- () => console.log("Cancelled")
641
+ () => console.log("Cancelled"),
722
642
  );
723
643
  settings.updateValue("theme", "light");
724
644
  ```
725
645
 
726
- **Controls:**
727
- - Mouse move/wheel: Highlight rows in alternate-screen mode
728
- - Click: Activate a row
729
- - Arrow keys: Navigate
730
- - Enter/Space: Activate (cycle value or open submenu)
731
- - Escape: Cancel
732
-
733
646
  ### Spacer
734
647
 
735
- Empty lines for vertical spacing.
648
+ Empty lines for vertical spacing:
736
649
 
737
650
  ```typescript
738
651
  const spacer = new Spacer(2); // 2 empty lines (default: 1)
@@ -740,7 +653,7 @@ const spacer = new Spacer(2); // 2 empty lines (default: 1)
740
653
 
741
654
  ### Image
742
655
 
743
- Renders images inline for terminals that support the Kitty graphics protocol (Kitty, Ghostty, WezTerm) or iTerm2 inline images. Falls back to a text placeholder on unsupported terminals.
656
+ Renders PNG, JPEG, GIF, and WebP images inline in Kitty or iTerm2-capable terminals (automatically parsing header dimensions), falling back to a text placeholder elsewhere:
744
657
 
745
658
  ```typescript
746
659
  interface ImageTheme {
@@ -753,26 +666,17 @@ interface ImageOptions {
753
666
  filename?: string;
754
667
  }
755
668
 
756
- const image = new Image(
757
- base64Data, // base64-encoded image data
758
- "image/png", // MIME type
759
- theme, // ImageTheme
760
- options // optional ImageOptions
761
- );
669
+ const image = new Image(base64Data, "image/png", theme, options);
762
670
  tui.addChild(image);
763
671
  ```
764
672
 
765
- Supported formats: PNG, JPEG, GIF, WebP. Dimensions are parsed from the image headers automatically.
766
-
767
- #### Alternate-screen image compatibility
768
-
769
- `TuiAltScreen` supports inline images and partial viewport cropping in terminals that implement the Kitty graphics protocol, including Kitty and Ghostty. iTerm2's inline-image protocol does not provide operations to delete an existing placement or crop its source while scrolling. To prevent stale images from remaining over repainted content, `TuiAltScreen` renders image components as text placeholders in iTerm2. `TuiMainScreen` continues to render iTerm2 inline images normally.
673
+ <Note>
674
+ **Alternate-screen image compatibility:** `TuiAltScreen` renders inline Kitty images with partial viewport cropping (Kitty, Ghostty). Because the iTerm2 inline-image protocol cannot delete or crop placements during scrolling, `TuiAltScreen` renders text placeholders in iTerm2, while `TuiMainScreen` renders iTerm2 inline images normally.
675
+ </Note>
770
676
 
771
677
  ## Autocomplete
772
678
 
773
- ### CombinedAutocompleteProvider
774
-
775
- Supports both slash commands and file paths.
679
+ `CombinedAutocompleteProvider` provides slash-command (`/`) and file-path (`Tab`, `~/`, `./`, `../`, `@`) completion:
776
680
 
777
681
  ```typescript
778
682
  import { CombinedAutocompleteProvider } from "@bastani/atomic-tui";
@@ -783,77 +687,51 @@ const provider = new CombinedAutocompleteProvider(
783
687
  { name: "clear", description: "Clear screen" },
784
688
  { name: "delete", description: "Delete last message" },
785
689
  ],
786
- process.cwd() // base path for file completion
690
+ process.cwd(), // base path for file completion
787
691
  );
788
692
 
789
693
  editor.setAutocompleteProvider(provider);
790
694
  ```
791
695
 
792
- A lookup triggered before the editor received a provider (typing `/`, an `@` token, a trigger character, or pressing `Tab`) starts once `setAutocompleteProvider()` attaches a provider, provided the prompt text and cursor have not moved. Any intervening edit, cursor move, undo, history step, `Escape`, or cursor-placing click cancels that pending lookup.
793
-
794
- `snapshotDraft()` captures any pending lookup, and `restoreDraft()` resumes it immediately or when the target editor receives a provider. `setTextAsTyped(text)` sets the prompt text like `setText(text)` and starts whatever lookup typing its last character would trigger.
795
-
796
- Replacing the built-in editor's provider normally closes any open menu. Call `editor.setAutocompleteProvider(provider, { preserveSelection: true })` to keep the current menu while switching providers for future lookups. An open menu keeps the provider that produced its rows. Any in-flight lookup or empty lookup for the current text retries against the new provider (preserving whether the user pressed `Tab`), and a failed lookup leaves the prompt intact so later lookups still run.
797
-
798
- Add `refreshMenu: true` to query the new provider for any open menu (commands, arguments, `@` files, or a `Tab` file menu) where the user has not chosen a row. A non-empty answer for the same text replaces the rows and selects an exact match. User selection, thrown or rejected lookups, empty answers, or answers arriving after the text changed leave the menu unchanged, and background refreshes never delay the editor's own lookups. Atomic forwards the same options to extension-provided editors' `setAutocompleteProvider()`, which may ignore them.
799
-
800
- Lookup results appear on the next render. Until then, menu keys (`Up`, `Down`, `Page Up`, `Page Down`, `Tab`, `Enter`, `Escape`) and pointer clicks act on the drawn menu while it matches the prompt text; once the user types further, keys act on the answer for the new text. Clicks on rows that changed since they were drawn select nothing. A provider that throws or rejects returns no suggestions, and a provider that ignores its abort signal holds the next lookup for at most 100 ms.
801
-
802
- **Features:**
803
-
804
- - Type `/` to see slash commands
805
- - Press `Tab` for file path completion
806
- - Works with `~/`, `./`, `../`, and `@` prefixes
807
- - Filters to attachable files for the `@` prefix
696
+ - **Pending lookups & drafts:** A lookup triggered before a provider attaches runs automatically once `setAutocompleteProvider()` is called (unless canceled by edits, cursor moves, undo, history, or `Escape`). `snapshotDraft()` / `restoreDraft()` preserve pending lookups across editor swaps, and `setTextAsTyped(text)` inserts text while triggering any completion its last character would start.
697
+ - **Swapping providers cleanly:** Pass `{ preserveSelection: true }` to `setAutocompleteProvider()` to keep an open menu active while updating the provider for future lookups, and add `refreshMenu: true` to silently re-query open menus where the user has not chosen a row yet.
698
+ - **Error isolation:** Lookups that throw or reject yield no suggestions; providers that ignore their abort signal hold the next lookup for at most 100 ms.
808
699
 
809
700
  ## Key detection
810
701
 
811
- Use `matchesKey()` with the `Key` helper for detecting keyboard input (supports Kitty keyboard protocol):
702
+ Use `matchesKey()` with `Key` helpers (or string literals) to detect keyboard input across legacy terminals, xterm `modifyOtherKeys`, and the Kitty keyboard protocol:
812
703
 
813
704
  ```typescript
814
- import { matchesKey, Key } from "@bastani/atomic-tui";
815
-
816
- if (matchesKey(data, Key.ctrl("c"))) {
817
- process.exit(0);
818
- }
705
+ import { Key, matchesKey } from "@bastani/atomic-tui";
819
706
 
820
- if (matchesKey(data, Key.enter)) {
821
- submit();
822
- } else if (matchesKey(data, Key.escape)) {
823
- cancel();
824
- } else if (matchesKey(data, Key.up)) {
825
- moveUp();
826
- }
707
+ if (matchesKey(data, Key.ctrl("c"))) process.exit(0);
708
+ if (matchesKey(data, Key.enter)) submit();
709
+ else if (matchesKey(data, Key.escape)) cancel();
710
+ else if (matchesKey(data, Key.up)) moveUp();
827
711
  ```
828
712
 
829
- **Key identifiers** (use `Key.*` for autocomplete, or string literals):
830
-
831
- - Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`
832
- - Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right`
833
- - With modifiers: `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")`
834
- - String format also works: `"enter"`, `"ctrl+c"`, `"shift+tab"`, `"ctrl+shift+p"`
713
+ - **Basic keys:** `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`, `Key.up`, `Key.down`, `Key.left`, `Key.right`
714
+ - **Modified keys:** `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")` (string literals like `"ctrl+shift+p"` also work)
835
715
 
836
716
  ## Rendering modes
837
717
 
838
- `TuiMainScreen` uses three rendering strategies:
718
+ - **`TuiMainScreen`:** Outputs all lines on first render without clearing scrollback; clears and fully re-renders on width changes or changes above the viewport; otherwise moves to the first changed line, clears to end, and writes changed lines.
719
+ - **`TuiAltScreen`:** Owns a fixed terminal-height viewport with differential in-place updates, bottom-following streaming, hover-expanding draggable scrollbars, OSC 133 prompt jumps, OSC 8 clickable links, drag-to-select with auto-scroll and OSC 52 copy, and Kitty image cropping.
839
720
 
840
- 1. **First render.** Output all lines without clearing scrollback.
841
- 2. **Width changed or change above viewport.** Clear screen and fully re-render.
842
- 3. **Normal update.** Move the cursor to the first changed line, clear to the end, and render changed lines.
843
-
844
- `TuiAltScreen` owns a terminal-height viewport. Without an explicit layout root it keeps single-document scrolling; with `setLayoutRoot()`, `VStack`, `HStack`, and nested `ScrollView` components allocate fixed regions and scroll constrained regions independently. It updates changed rows in place, follows streaming output at the bottom, and holds a manual scroll position while content grows.
845
-
846
- Mouse-wheel and keyboard navigation scroll without altering terminal scrollback, including jumps between OSC 133 semantic prompt markers. Scrollbars support hover expansion, thumb dragging, and track-click jumping. Clicking an OSC 8 hyperlink invokes the configured `openUrl` handler.
847
-
848
- Dragging with the primary mouse button selects text and, unless `TuiAltScreenOptions.copyOnSelect` is `false`, copies it with OSC 52. Holding a drag at a scroll view's top or bottom edge auto-scrolls and extends the selection into off-screen content. Kitty images support vertical viewport cropping, while iTerm2 inline images render as text placeholders because the iTerm2 protocol cannot delete or crop placements during viewport repainting.
849
-
850
- Both renderers wrap updates in **synchronized output** (`\x1b[?2026h` ... `\x1b[?2026l`) for atomic, flicker-free rendering.
721
+ Both renderers wrap frames in **synchronized output** (`\x1b[?2026h` ... `\x1b[?2026l`) for flicker-free updates.
851
722
 
852
723
  ## Terminal interface
853
724
 
854
- The TUI works with any object implementing the `Terminal` interface:
725
+ The TUI runs against any implementation of `Terminal` (`ProcessTerminal` wraps `process.stdin`/`process.stdout`; pass a mock implementation for headless tests):
855
726
 
856
727
  ```typescript
728
+ interface ProgramStatus {
729
+ state: "idle" | "working" | "blocked" | "done" | "error" | "clear";
730
+ app?: string; // Stable app name ([A-Za-z0-9_.+-]{1,32})
731
+ kind?: "permission" | "question" | "auth";// Only used when state === "blocked"
732
+ message?: string; // Single line, capped at 2,048 UTF-8 bytes
733
+ }
734
+
857
735
  interface Terminal {
858
736
  start(onInput: (data: string) => void, onResize: () => void): void;
859
737
  stop(): void;
@@ -879,25 +757,21 @@ interface Terminal {
879
757
  }
880
758
  ```
881
759
 
882
- **Built-in implementation:** `ProcessTerminal`, which reads from `process.stdin` and writes to `process.stdout`. For automated tests, provide a mock or headless implementation of `Terminal`.
760
+ Key lifecycle and protocol hooks on `Terminal`:
761
+
762
+ - **`handOff?(held?)` and `continuedFromHandOff`:** Allows switching from one renderer (such as a fast startup screen) to another without resetting terminal modes or clearing the screen; input arriving during the hand-off is buffered and replayed in order after `held` once the next renderer calls `start()`.
763
+ - **`restoreOnExit?(before, after)`:** Synchronously writes terminal mode resets (`before`, the terminal's own resets, then `after`) from a process `exit` handler if `stop()` did not run.
764
+ - **`setProgramStatus(status)`:** Emits an [OSC 7501 Program Status](https://www.superlogical.com/rex/docs/build/program-status) update once the terminal confirms support, re-sending the latest state when support is confirmed or the terminal restarts.
883
765
 
884
766
  ## Utilities
885
767
 
886
768
  ```typescript
887
- import { visibleWidth, truncateToWidth, wrapTextWithAnsi } from "@bastani/atomic-tui";
888
-
889
- // Get visible width of string (ignoring ANSI codes)
890
- const width = visibleWidth("\x1b[31mHello\x1b[0m"); // 5
891
-
892
- // Truncate string to width (preserving ANSI codes and closing active styles)
893
- const truncated = truncateToWidth("Hello World", 8); // "Hello..."
769
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@bastani/atomic-tui";
894
770
 
895
- // Truncate without ellipsis
896
- const truncatedNoEllipsis = truncateToWidth("Hello World", 8, ""); // "Hello Wo"
897
-
898
- // Wrap text to width (preserving ANSI codes across line breaks)
899
- const lines = wrapTextWithAnsi("This is a long line that needs wrapping", 20);
900
- // ["This is a long line", "that needs wrapping"]
771
+ const width = visibleWidth("\x1b[31mHello\x1b[0m"); // 5
772
+ const truncated = truncateToWidth("Hello World", 8); // "Hello..."
773
+ const noEllipsis = truncateToWidth("Hello World", 8, ""); // "Hello Wo"
774
+ const wrapped = wrapTextWithAnsi("A long line to wrap nicely", 14);
901
775
  ```
902
776
 
903
777
  Additional exported helpers:
@@ -905,7 +779,7 @@ Additional exported helpers:
905
779
  | Export | Purpose |
906
780
  | --- | --- |
907
781
  | `fuzzyFilter` / `fuzzyMatch` | Fuzzy matching and ranked filtering for pickers and search inputs. |
908
- | `KeybindingsManager` / `TUI_KEYBINDINGS` | Configurable TUI keybinding definitions and lookup. |
782
+ | `KeybindingsManager` / `TUI_KEYBINDINGS` / `getSelectPageIndex` | Configurable TUI keybinding definitions, matching, and list paging helper. |
909
783
  | `decodePrintableKey` | Decode printable Kitty CSI-u and `modifyOtherKeys` sequences. |
910
784
  | `normalizePastedText` | Normalize bracketed paste text (CRLF/CR, tmux control bytes, tabs, C0 control filtering). |
911
785
  | `stripTerminalSequences` / `sliceByColumn` | Strip ANSI/OSC sequences or slice styled strings by display column range. |
@@ -916,10 +790,10 @@ Additional exported helpers:
916
790
 
917
791
  ## Creating custom components
918
792
 
919
- When building a custom `Component`, keep every line returned by `render(width)` within `width` columns using `truncateToWidth()`, `wrapTextWithAnsi()`, or `visibleWidth()`, handle keys via `matchesKey()` (see [Key detection](#key-detection)), and cache rendered output by width until `invalidate()` runs:
793
+ Keep every line returned by `render(width)` within `width` columns, match keys via `matchesKey()`, and cache lines by width until `invalidate()` runs:
920
794
 
921
795
  ```typescript
922
- import { Key, matchesKey, truncateToWidth, type Component } from "@bastani/atomic-tui";
796
+ import { type Component, Key, matchesKey, truncateToWidth } from "@bastani/atomic-tui";
923
797
 
924
798
  class CachedList implements Component {
925
799
  private selectedIndex = 0;
@@ -944,9 +818,7 @@ class CachedList implements Component {
944
818
  }
945
819
 
946
820
  render(width: number): string[] {
947
- if (this.cachedLines && this.cachedWidth === width) {
948
- return this.cachedLines;
949
- }
821
+ if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
950
822
  this.cachedWidth = width;
951
823
  this.cachedLines = this.items.map((item, i) =>
952
824
  truncateToWidth(`${i === this.selectedIndex ? "> " : " "}${item}`, width),
@@ -963,7 +835,7 @@ class CachedList implements Component {
963
835
 
964
836
  ## Example
965
837
 
966
- A self-contained alternate-screen chat interface combining `ScrollView`, `Markdown`, `Loader`, `Spacer`, `Editor`, and `CombinedAutocompleteProvider`:
838
+ A self-contained alternate-screen chat app combining `ScrollView`, `Markdown`, `Loader`, `Spacer`, `Editor`, and `CombinedAutocompleteProvider`:
967
839
 
968
840
  ```typescript
969
841
  import {