@m4ike1/ion-tui 0.1.0

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 (196) hide show
  1. package/README.md +114 -0
  2. package/dist/alt-screen-search.d.ts +46 -0
  3. package/dist/alt-screen-search.d.ts.map +1 -0
  4. package/dist/alt-screen-search.js +282 -0
  5. package/dist/alt-screen-search.js.map +1 -0
  6. package/dist/autocomplete.d.ts +75 -0
  7. package/dist/autocomplete.d.ts.map +1 -0
  8. package/dist/autocomplete.js +749 -0
  9. package/dist/autocomplete.js.map +1 -0
  10. package/dist/components/alt-screen-flash.d.ts +13 -0
  11. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  12. package/dist/components/alt-screen-flash.js +37 -0
  13. package/dist/components/alt-screen-flash.js.map +1 -0
  14. package/dist/components/box.d.ts +24 -0
  15. package/dist/components/box.d.ts.map +1 -0
  16. package/dist/components/box.js +133 -0
  17. package/dist/components/box.js.map +1 -0
  18. package/dist/components/cancellable-loader.d.ts +22 -0
  19. package/dist/components/cancellable-loader.d.ts.map +1 -0
  20. package/dist/components/cancellable-loader.js +35 -0
  21. package/dist/components/cancellable-loader.js.map +1 -0
  22. package/dist/components/editor.d.ts +266 -0
  23. package/dist/components/editor.d.ts.map +1 -0
  24. package/dist/components/editor.js +2087 -0
  25. package/dist/components/editor.js.map +1 -0
  26. package/dist/components/h-stack.d.ts +7 -0
  27. package/dist/components/h-stack.d.ts.map +1 -0
  28. package/dist/components/h-stack.js +43 -0
  29. package/dist/components/h-stack.js.map +1 -0
  30. package/dist/components/image.d.ts +28 -0
  31. package/dist/components/image.d.ts.map +1 -0
  32. package/dist/components/image.js +90 -0
  33. package/dist/components/image.js.map +1 -0
  34. package/dist/components/input.d.ts +48 -0
  35. package/dist/components/input.d.ts.map +1 -0
  36. package/dist/components/input.js +417 -0
  37. package/dist/components/input.js.map +1 -0
  38. package/dist/components/loader.d.ts +33 -0
  39. package/dist/components/loader.d.ts.map +1 -0
  40. package/dist/components/loader.js +76 -0
  41. package/dist/components/loader.js.map +1 -0
  42. package/dist/components/markdown.d.ts +103 -0
  43. package/dist/components/markdown.d.ts.map +1 -0
  44. package/dist/components/markdown.js +858 -0
  45. package/dist/components/markdown.js.map +1 -0
  46. package/dist/components/mouse-region.d.ts +12 -0
  47. package/dist/components/mouse-region.d.ts.map +1 -0
  48. package/dist/components/mouse-region.js +21 -0
  49. package/dist/components/mouse-region.js.map +1 -0
  50. package/dist/components/scroll-view.d.ts +68 -0
  51. package/dist/components/scroll-view.d.ts.map +1 -0
  52. package/dist/components/scroll-view.js +199 -0
  53. package/dist/components/scroll-view.js.map +1 -0
  54. package/dist/components/select-list.d.ts +53 -0
  55. package/dist/components/select-list.d.ts.map +1 -0
  56. package/dist/components/select-list.js +206 -0
  57. package/dist/components/select-list.js.map +1 -0
  58. package/dist/components/settings-list.d.ts +60 -0
  59. package/dist/components/settings-list.d.ts.map +1 -0
  60. package/dist/components/settings-list.js +252 -0
  61. package/dist/components/settings-list.js.map +1 -0
  62. package/dist/components/spacer.d.ts +12 -0
  63. package/dist/components/spacer.d.ts.map +1 -0
  64. package/dist/components/spacer.js +23 -0
  65. package/dist/components/spacer.js.map +1 -0
  66. package/dist/components/stack.d.ts +32 -0
  67. package/dist/components/stack.d.ts.map +1 -0
  68. package/dist/components/stack.js +111 -0
  69. package/dist/components/stack.js.map +1 -0
  70. package/dist/components/text.d.ts +19 -0
  71. package/dist/components/text.d.ts.map +1 -0
  72. package/dist/components/text.js +90 -0
  73. package/dist/components/text.js.map +1 -0
  74. package/dist/components/truncated-text.d.ts +13 -0
  75. package/dist/components/truncated-text.d.ts.map +1 -0
  76. package/dist/components/truncated-text.js +51 -0
  77. package/dist/components/truncated-text.js.map +1 -0
  78. package/dist/components/v-stack.d.ts +8 -0
  79. package/dist/components/v-stack.d.ts.map +1 -0
  80. package/dist/components/v-stack.js +26 -0
  81. package/dist/components/v-stack.js.map +1 -0
  82. package/dist/components/virtual-list.d.ts +51 -0
  83. package/dist/components/virtual-list.d.ts.map +1 -0
  84. package/dist/components/virtual-list.js +170 -0
  85. package/dist/components/virtual-list.js.map +1 -0
  86. package/dist/editor-component.d.ts +39 -0
  87. package/dist/editor-component.d.ts.map +1 -0
  88. package/dist/editor-component.js +2 -0
  89. package/dist/editor-component.js.map +1 -0
  90. package/dist/fuzzy.d.ts +16 -0
  91. package/dist/fuzzy.d.ts.map +1 -0
  92. package/dist/fuzzy.js +110 -0
  93. package/dist/fuzzy.js.map +1 -0
  94. package/dist/index.d.ts +34 -0
  95. package/dist/index.d.ts.map +1 -0
  96. package/dist/index.js +46 -0
  97. package/dist/index.js.map +1 -0
  98. package/dist/keybindings.d.ts +366 -0
  99. package/dist/keybindings.d.ts.map +1 -0
  100. package/dist/keybindings.js +331 -0
  101. package/dist/keybindings.js.map +1 -0
  102. package/dist/keys.d.ts +184 -0
  103. package/dist/keys.d.ts.map +1 -0
  104. package/dist/keys.js +1174 -0
  105. package/dist/keys.js.map +1 -0
  106. package/dist/kill-ring.d.ts +28 -0
  107. package/dist/kill-ring.d.ts.map +1 -0
  108. package/dist/kill-ring.js +44 -0
  109. package/dist/kill-ring.js.map +1 -0
  110. package/dist/latex.d.ts +10 -0
  111. package/dist/latex.d.ts.map +1 -0
  112. package/dist/latex.js +1285 -0
  113. package/dist/latex.js.map +1 -0
  114. package/dist/layout-node.d.ts +59 -0
  115. package/dist/layout-node.d.ts.map +1 -0
  116. package/dist/layout-node.js +12 -0
  117. package/dist/layout-node.js.map +1 -0
  118. package/dist/layout.d.ts +42 -0
  119. package/dist/layout.d.ts.map +1 -0
  120. package/dist/layout.js +404 -0
  121. package/dist/layout.js.map +1 -0
  122. package/dist/native-modifiers.d.ts +4 -0
  123. package/dist/native-modifiers.d.ts.map +1 -0
  124. package/dist/native-modifiers.js +13 -0
  125. package/dist/native-modifiers.js.map +1 -0
  126. package/dist/native-module-path.d.ts +7 -0
  127. package/dist/native-module-path.d.ts.map +1 -0
  128. package/dist/native-module-path.js +19 -0
  129. package/dist/native-module-path.js.map +1 -0
  130. package/dist/native-platform.d.ts +18 -0
  131. package/dist/native-platform.d.ts.map +1 -0
  132. package/dist/native-platform.js +42 -0
  133. package/dist/native-platform.js.map +1 -0
  134. package/dist/pty-host.d.ts +224 -0
  135. package/dist/pty-host.d.ts.map +1 -0
  136. package/dist/pty-host.js +347 -0
  137. package/dist/pty-host.js.map +1 -0
  138. package/dist/stdin-buffer.d.ts +56 -0
  139. package/dist/stdin-buffer.d.ts.map +1 -0
  140. package/dist/stdin-buffer.js +366 -0
  141. package/dist/stdin-buffer.js.map +1 -0
  142. package/dist/terminal-colors.d.ts +10 -0
  143. package/dist/terminal-colors.d.ts.map +1 -0
  144. package/dist/terminal-colors.js +59 -0
  145. package/dist/terminal-colors.js.map +1 -0
  146. package/dist/terminal-image.d.ts +118 -0
  147. package/dist/terminal-image.d.ts.map +1 -0
  148. package/dist/terminal-image.js +550 -0
  149. package/dist/terminal-image.js.map +1 -0
  150. package/dist/terminal.d.ts +123 -0
  151. package/dist/terminal.d.ts.map +1 -0
  152. package/dist/terminal.js +442 -0
  153. package/dist/terminal.js.map +1 -0
  154. package/dist/tui-alt-screen.d.ts +165 -0
  155. package/dist/tui-alt-screen.d.ts.map +1 -0
  156. package/dist/tui-alt-screen.js +1515 -0
  157. package/dist/tui-alt-screen.js.map +1 -0
  158. package/dist/tui-main-screen.d.ts +39 -0
  159. package/dist/tui-main-screen.d.ts.map +1 -0
  160. package/dist/tui-main-screen.js +594 -0
  161. package/dist/tui-main-screen.js.map +1 -0
  162. package/dist/tui.d.ts +431 -0
  163. package/dist/tui.d.ts.map +1 -0
  164. package/dist/tui.js +1142 -0
  165. package/dist/tui.js.map +1 -0
  166. package/dist/undo-stack.d.ts +17 -0
  167. package/dist/undo-stack.d.ts.map +1 -0
  168. package/dist/undo-stack.js +25 -0
  169. package/dist/undo-stack.js.map +1 -0
  170. package/dist/utils.d.ts +98 -0
  171. package/dist/utils.d.ts.map +1 -0
  172. package/dist/utils.js +1200 -0
  173. package/dist/utils.js.map +1 -0
  174. package/dist/word-navigation.d.ts +25 -0
  175. package/dist/word-navigation.d.ts.map +1 -0
  176. package/dist/word-navigation.js +96 -0
  177. package/dist/word-navigation.js.map +1 -0
  178. package/native/clipboard.h +170 -0
  179. package/native/darwin/README.md +22 -0
  180. package/native/darwin/build.sh +69 -0
  181. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  182. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  183. package/native/darwin/src/darwin-platform.m +93 -0
  184. package/native/linux/README.md +23 -0
  185. package/native/linux/build.sh +65 -0
  186. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  187. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  188. package/native/linux/src/clipboard-worker.h +70 -0
  189. package/native/linux/src/linux-platform-x11.c +274 -0
  190. package/native/napi.h +89 -0
  191. package/native/win32/README.md +31 -0
  192. package/native/win32/build.mjs +232 -0
  193. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  194. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  195. package/native/win32/src/win32-platform.c +241 -0
  196. package/package.json +62 -0
@@ -0,0 +1,594 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { deleteKittyImage, isImageLine } from "./terminal-image.js";
5
+ import { TuiBase } from "./tui.js";
6
+ import { visibleWidth } from "./utils.js";
7
+ const KITTY_SEQUENCE_PREFIX = "\x1b_G";
8
+ const MAX_RENDER_WRITE_CHARS = 1024 * 1024;
9
+ /**
10
+ * Streams terminal output in 1 MiB chunks so a full render never forms one string large enough to exceed V8's limit.
11
+ *
12
+ * `append()` fills the current chunk and flushes it when full. Oversized input is split at chunk boundaries, preserving
13
+ * surrogate pairs so each write remains valid UTF-16. Callers append synchronized-output begin/end sequences themselves;
14
+ * the final `flush()` writes any remainder, including the end sequence.
15
+ */
16
+ class BoundedTerminalWriter {
17
+ buffer = "";
18
+ writtenChars = 0;
19
+ write;
20
+ constructor(write) {
21
+ this.write = write;
22
+ }
23
+ /**
24
+ * Append terminal data, flushing full chunks as needed. Callers must call `flush()` after the final append.
25
+ * @param value Terminal data to write in order; oversized values are split without splitting surrogate pairs.
26
+ */
27
+ append(value) {
28
+ let offset = 0;
29
+ while (offset < value.length) {
30
+ const capacity = MAX_RENDER_WRITE_CHARS - this.buffer.length;
31
+ if (capacity === 0) {
32
+ this.flush();
33
+ continue;
34
+ }
35
+ let end = Math.min(value.length, offset + capacity);
36
+ if (end < value.length &&
37
+ value.charCodeAt(end - 1) >= 0xd800 &&
38
+ value.charCodeAt(end - 1) <= 0xdbff &&
39
+ value.charCodeAt(end) >= 0xdc00 &&
40
+ value.charCodeAt(end) <= 0xdfff) {
41
+ end--;
42
+ }
43
+ if (end === offset) {
44
+ this.flush();
45
+ continue;
46
+ }
47
+ this.buffer += value.slice(offset, end);
48
+ offset = end;
49
+ if (this.buffer.length === MAX_RENDER_WRITE_CHARS) {
50
+ this.flush();
51
+ }
52
+ }
53
+ }
54
+ /** Write the current chunk, if any, and retain only its character count for debug output. */
55
+ flush() {
56
+ if (!this.buffer)
57
+ return;
58
+ this.write(this.buffer);
59
+ this.writtenChars += this.buffer.length;
60
+ this.buffer = "";
61
+ }
62
+ get length() {
63
+ return this.writtenChars + this.buffer.length;
64
+ }
65
+ }
66
+ function parseKittyImageHeader(line) {
67
+ const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
68
+ if (sequenceStart === -1)
69
+ return undefined;
70
+ const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
71
+ const paramsEnd = line.indexOf(";", paramsStart);
72
+ if (paramsEnd === -1)
73
+ return undefined;
74
+ const ids = [];
75
+ let rows = 1;
76
+ for (const param of line.slice(paramsStart, paramsEnd).split(",")) {
77
+ const [key, value] = param.split("=", 2);
78
+ if (value === undefined)
79
+ continue;
80
+ const numberValue = Number(value);
81
+ if (!Number.isInteger(numberValue) || numberValue <= 0 || numberValue > 0xffffffff)
82
+ continue;
83
+ if (key === "i")
84
+ ids.push(numberValue);
85
+ else if (key === "r")
86
+ rows = numberValue;
87
+ }
88
+ return { ids, rows };
89
+ }
90
+ function extractKittyImageIds(line) {
91
+ return parseKittyImageHeader(line)?.ids ?? [];
92
+ }
93
+ function extractKittyImageRows(line) {
94
+ return parseKittyImageHeader(line)?.rows ?? 1;
95
+ }
96
+ function isTermuxSession() {
97
+ return Boolean(process.env.TERMUX_VERSION);
98
+ }
99
+ /** TUI implementation that renders into the terminal's main screen and scrollback. */
100
+ export class TuiMainScreen extends TuiBase {
101
+ mode = "regular";
102
+ previousLines = [];
103
+ previousKittyImageIds = new Set();
104
+ previousWidth = 0;
105
+ previousHeight = 0;
106
+ cursorRow = 0;
107
+ hardwareCursorRow = 0;
108
+ maxLinesRendered = 0;
109
+ previousViewportTop = 0;
110
+ captureRenderState() {
111
+ return {
112
+ previousLines: [...this.previousLines],
113
+ previousWidth: this.previousWidth,
114
+ previousHeight: this.previousHeight,
115
+ cursorRow: this.cursorRow,
116
+ hardwareCursorRow: this.hardwareCursorRow,
117
+ maxLinesRendered: this.maxLinesRendered,
118
+ previousViewportTop: this.previousViewportTop,
119
+ };
120
+ }
121
+ restoreRenderState(state) {
122
+ this.previousLines = state.previousLines.map((line) => (isImageLine(line) ? "" : line));
123
+ this.previousKittyImageIds = new Set();
124
+ this.previousWidth = state.previousWidth;
125
+ this.previousHeight = state.previousHeight;
126
+ this.cursorRow = state.cursorRow;
127
+ this.hardwareCursorRow = state.hardwareCursorRow;
128
+ this.maxLinesRendered = state.maxLinesRendered;
129
+ this.previousViewportTop = state.previousViewportTop;
130
+ }
131
+ resetRenderState() {
132
+ this.previousLines = [];
133
+ this.previousWidth = -1;
134
+ this.previousHeight = -1;
135
+ this.cursorRow = 0;
136
+ this.hardwareCursorRow = 0;
137
+ this.maxLinesRendered = 0;
138
+ this.previousViewportTop = 0;
139
+ }
140
+ beforeTerminalStop(options) {
141
+ if (options.preserveScreen || this.previousLines.length === 0)
142
+ return;
143
+ this.terminal.write(" ");
144
+ const targetRow = this.previousLines.length;
145
+ const lineDiff = targetRow - this.hardwareCursorRow;
146
+ if (lineDiff > 0)
147
+ this.terminal.write(`\x1b[${lineDiff}B`);
148
+ else if (lineDiff < 0)
149
+ this.terminal.write(`\x1b[${-lineDiff}A`);
150
+ this.terminal.write("\r\n");
151
+ }
152
+ collectKittyImageIds(lines) {
153
+ const ids = new Set();
154
+ for (const line of lines) {
155
+ for (const id of extractKittyImageIds(line)) {
156
+ ids.add(id);
157
+ }
158
+ }
159
+ return ids;
160
+ }
161
+ deleteKittyImages(ids) {
162
+ let buffer = "";
163
+ for (const id of ids) {
164
+ buffer += deleteKittyImage(id);
165
+ }
166
+ return buffer;
167
+ }
168
+ getKittyImageReservedRows(lines, index, maxIndex = lines.length - 1) {
169
+ const rows = extractKittyImageRows(lines[index] ?? "");
170
+ if (rows <= 1)
171
+ return 1;
172
+ const maxRows = Math.min(rows, maxIndex - index + 1, lines.length - index);
173
+ let reservedRows = 1;
174
+ while (reservedRows < maxRows) {
175
+ const line = lines[index + reservedRows] ?? "";
176
+ if (isImageLine(line) || visibleWidth(line) > 0)
177
+ break;
178
+ reservedRows++;
179
+ }
180
+ return reservedRows;
181
+ }
182
+ expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines) {
183
+ let expandedFirstChanged = firstChanged;
184
+ let expandedLastChanged = lastChanged;
185
+ const expandForLines = (lines) => {
186
+ for (let i = 0; i < lines.length; i++) {
187
+ if (extractKittyImageIds(lines[i]).length === 0)
188
+ continue;
189
+ const blockEnd = i + this.getKittyImageReservedRows(lines, i) - 1;
190
+ if (i >= firstChanged || (i <= lastChanged && blockEnd >= firstChanged)) {
191
+ expandedFirstChanged = Math.min(expandedFirstChanged, i);
192
+ expandedLastChanged = Math.max(expandedLastChanged, blockEnd);
193
+ }
194
+ }
195
+ };
196
+ expandForLines(this.previousLines);
197
+ expandForLines(newLines);
198
+ return { firstChanged: expandedFirstChanged, lastChanged: expandedLastChanged };
199
+ }
200
+ deleteChangedKittyImages(firstChanged, lastChanged) {
201
+ if (firstChanged < 0 || lastChanged < firstChanged)
202
+ return "";
203
+ const ids = new Set();
204
+ const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
205
+ for (let i = firstChanged; i <= maxLine; i++) {
206
+ for (const id of extractKittyImageIds(this.previousLines[i] ?? "")) {
207
+ ids.add(id);
208
+ }
209
+ }
210
+ return this.deleteKittyImages(ids);
211
+ }
212
+ doRender() {
213
+ if (this.stopped)
214
+ return;
215
+ const width = this.terminal.columns;
216
+ const height = this.terminal.rows;
217
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
218
+ const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
219
+ const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
220
+ let prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;
221
+ let viewportTop = prevViewportTop;
222
+ let hardwareCursorRow = this.hardwareCursorRow;
223
+ const computeLineDiff = (targetRow) => {
224
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
225
+ const targetScreenRow = targetRow - viewportTop;
226
+ return targetScreenRow - currentScreenRow;
227
+ };
228
+ // Render all components to get new lines
229
+ let newLines = this.render(width);
230
+ // Composite overlays into the rendered lines (before differential compare)
231
+ if (this.hasOverlayEntries) {
232
+ newLines = this.compositeOverlays(newLines, width, height);
233
+ }
234
+ // Extract cursor position before applying line resets (marker must be found first)
235
+ const cursorPos = this.extractCursorPosition(newLines, height);
236
+ newLines = this.applyLineResets(newLines);
237
+ // Helper to clear scrollback and viewport and render all new lines
238
+ const fullRender = (clear) => {
239
+ this.fullRedrawCount += 1;
240
+ const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
241
+ output.append("\x1b[?2026h"); // Begin synchronized output
242
+ if (clear) {
243
+ output.append(this.deleteKittyImages(this.previousKittyImageIds));
244
+ output.append("\x1b[2J\x1b[H\x1b[3J"); // Clear screen, home, then clear scrollback
245
+ }
246
+ for (let i = 0; i < newLines.length; i++) {
247
+ if (i > 0)
248
+ output.append("\r\n");
249
+ const line = newLines[i];
250
+ const isImage = isImageLine(line);
251
+ const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i) : 1;
252
+ if (imageReservedRows > 1 && imageReservedRows <= height) {
253
+ for (let row = 1; row < imageReservedRows; row++) {
254
+ output.append("\r\n");
255
+ }
256
+ output.append(`\x1b[${imageReservedRows - 1}A`);
257
+ output.append(line);
258
+ output.append(`\x1b[${imageReservedRows - 1}B`);
259
+ i += imageReservedRows - 1;
260
+ continue;
261
+ }
262
+ output.append(line);
263
+ }
264
+ output.append("\x1b[?2026l"); // End synchronized output
265
+ output.flush();
266
+ this.cursorRow = Math.max(0, newLines.length - 1);
267
+ this.hardwareCursorRow = this.cursorRow;
268
+ // Reset max lines when clearing, otherwise track growth
269
+ if (clear) {
270
+ this.maxLinesRendered = newLines.length;
271
+ }
272
+ else {
273
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
274
+ }
275
+ const bufferLength = Math.max(height, newLines.length);
276
+ this.previousViewportTop = Math.max(0, bufferLength - height);
277
+ this.positionHardwareCursor(cursorPos, newLines.length);
278
+ this.previousLines = newLines;
279
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
280
+ this.previousWidth = width;
281
+ this.previousHeight = height;
282
+ };
283
+ const redrawLogDirectory = process.env.ION_TUI_DEBUG_REDRAW === "1" ? this.logDirectory : undefined;
284
+ const logRedraw = (reason) => {
285
+ if (redrawLogDirectory === undefined)
286
+ return;
287
+ const logPath = path.join(redrawLogDirectory, "ion-tui-debug.log");
288
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
289
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
290
+ fs.appendFileSync(logPath, msg);
291
+ };
292
+ // First render - just output everything without clearing (assumes clean screen)
293
+ if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
294
+ logRedraw("first render");
295
+ fullRender(false);
296
+ return;
297
+ }
298
+ // Width changes always need a full re-render because wrapping changes.
299
+ if (widthChanged) {
300
+ logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
301
+ fullRender(true);
302
+ return;
303
+ }
304
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
305
+ // but Termux changes height when the software keyboard shows or hides.
306
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
307
+ if (heightChanged && !isTermuxSession()) {
308
+ logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
309
+ fullRender(true);
310
+ return;
311
+ }
312
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
313
+ // (overlays need the padding, so only do this when no overlays are active)
314
+ // Configurable via setClearOnShrink()
315
+ if (this.getClearOnShrink() && newLines.length < this.maxLinesRendered && !this.hasOverlayEntries) {
316
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
317
+ fullRender(true);
318
+ return;
319
+ }
320
+ // Find first and last changed lines
321
+ let firstChanged = -1;
322
+ let lastChanged = -1;
323
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
324
+ for (let i = 0; i < maxLines; i++) {
325
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
326
+ const newLine = i < newLines.length ? newLines[i] : "";
327
+ if (oldLine !== newLine) {
328
+ if (firstChanged === -1) {
329
+ firstChanged = i;
330
+ }
331
+ lastChanged = i;
332
+ }
333
+ }
334
+ const appendedLines = newLines.length > this.previousLines.length;
335
+ if (appendedLines) {
336
+ if (firstChanged === -1) {
337
+ firstChanged = this.previousLines.length;
338
+ }
339
+ lastChanged = newLines.length - 1;
340
+ }
341
+ if (firstChanged !== -1) {
342
+ const expandedRange = this.expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines);
343
+ firstChanged = expandedRange.firstChanged;
344
+ lastChanged = expandedRange.lastChanged;
345
+ }
346
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
347
+ // No changes - but still need to update hardware cursor position if it moved
348
+ if (firstChanged === -1) {
349
+ this.positionHardwareCursor(cursorPos, newLines.length);
350
+ this.previousViewportTop = prevViewportTop;
351
+ this.previousHeight = height;
352
+ return;
353
+ }
354
+ // All changes are in deleted lines (nothing to render, just clear)
355
+ if (firstChanged >= newLines.length) {
356
+ if (this.previousLines.length > newLines.length) {
357
+ const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
358
+ output.append("\x1b[?2026h");
359
+ output.append(this.deleteChangedKittyImages(firstChanged, lastChanged));
360
+ // Move to end of new content (clamp to 0 for empty content)
361
+ const targetRow = Math.max(0, newLines.length - 1);
362
+ if (targetRow < prevViewportTop) {
363
+ logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
364
+ fullRender(true);
365
+ return;
366
+ }
367
+ const lineDiff = computeLineDiff(targetRow);
368
+ if (lineDiff > 0)
369
+ output.append(`\x1b[${lineDiff}B`);
370
+ else if (lineDiff < 0)
371
+ output.append(`\x1b[${-lineDiff}A`);
372
+ output.append("\r");
373
+ // Clear extra lines without scrolling
374
+ const extraLines = this.previousLines.length - newLines.length;
375
+ if (extraLines > height) {
376
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
377
+ fullRender(true);
378
+ return;
379
+ }
380
+ const clearStartOffset = newLines.length === 0 ? 0 : 1;
381
+ if (extraLines > 0 && clearStartOffset > 0) {
382
+ output.append(`\x1b[${clearStartOffset}B`);
383
+ }
384
+ for (let i = 0; i < extraLines; i++) {
385
+ output.append("\r\x1b[2K");
386
+ if (i < extraLines - 1)
387
+ output.append("\x1b[1B");
388
+ }
389
+ const moveBack = Math.max(0, extraLines - 1 + clearStartOffset);
390
+ if (moveBack > 0) {
391
+ output.append(`\x1b[${moveBack}A`);
392
+ }
393
+ output.append("\x1b[?2026l");
394
+ output.flush();
395
+ this.cursorRow = targetRow;
396
+ this.hardwareCursorRow = targetRow;
397
+ }
398
+ this.positionHardwareCursor(cursorPos, newLines.length);
399
+ this.previousLines = newLines;
400
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
401
+ this.previousWidth = width;
402
+ this.previousHeight = height;
403
+ this.previousViewportTop = prevViewportTop;
404
+ return;
405
+ }
406
+ // Differential rendering can only touch what was actually visible.
407
+ // If the first changed line is above the previous viewport, we need a full redraw.
408
+ if (firstChanged < prevViewportTop) {
409
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
410
+ fullRender(true);
411
+ return;
412
+ }
413
+ // Render from first changed line to end
414
+ // Keep updates wrapped in synchronized output while writing bounded chunks.
415
+ const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
416
+ output.append("\x1b[?2026h"); // Begin synchronized output
417
+ output.append(this.deleteChangedKittyImages(firstChanged, lastChanged));
418
+ const prevViewportBottom = prevViewportTop + height - 1;
419
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
420
+ if (moveTargetRow > prevViewportBottom) {
421
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
422
+ const moveToBottom = height - 1 - currentScreenRow;
423
+ if (moveToBottom > 0) {
424
+ output.append(`\x1b[${moveToBottom}B`);
425
+ }
426
+ const scroll = moveTargetRow - prevViewportBottom;
427
+ output.append("\r\n".repeat(scroll));
428
+ prevViewportTop += scroll;
429
+ viewportTop += scroll;
430
+ hardwareCursorRow = moveTargetRow;
431
+ }
432
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
433
+ const lineDiff = computeLineDiff(moveTargetRow);
434
+ if (lineDiff > 0) {
435
+ output.append(`\x1b[${lineDiff}B`); // Move down
436
+ }
437
+ else if (lineDiff < 0) {
438
+ output.append(`\x1b[${-lineDiff}A`); // Move up
439
+ }
440
+ output.append(appendStart ? "\r\n" : "\r"); // Move to column 0
441
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
442
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
443
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
444
+ for (let i = firstChanged; i <= renderEnd; i++) {
445
+ if (i > firstChanged)
446
+ output.append("\r\n");
447
+ const line = newLines[i];
448
+ const isImage = isImageLine(line);
449
+ const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i, renderEnd) : 1;
450
+ if (imageReservedRows > 1) {
451
+ const imageStartScreenRow = i - viewportTop;
452
+ if (imageStartScreenRow < 0 || imageStartScreenRow + imageReservedRows > height) {
453
+ logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`);
454
+ fullRender(true);
455
+ return;
456
+ }
457
+ output.append("\x1b[2K");
458
+ for (let row = 1; row < imageReservedRows; row++) {
459
+ output.append("\r\n\x1b[2K");
460
+ }
461
+ output.append(`\x1b[${imageReservedRows - 1}A`);
462
+ output.append(line);
463
+ output.append(`\x1b[${imageReservedRows - 1}B`);
464
+ i += imageReservedRows - 1;
465
+ continue;
466
+ }
467
+ output.append("\x1b[2K"); // Clear current line
468
+ if (!isImage && visibleWidth(line) > width) {
469
+ // Log all lines to crash file for debugging
470
+ const crashLogPath = path.join(this.logDirectory ?? os.tmpdir(), "ion-tui-crash.log");
471
+ const crashData = [
472
+ `Crash at ${new Date().toISOString()}`,
473
+ `Terminal width: ${width}`,
474
+ `Line ${i} visible width: ${visibleWidth(line)}`,
475
+ "",
476
+ "=== All rendered lines ===",
477
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
478
+ "",
479
+ ].join("\n");
480
+ fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
481
+ fs.writeFileSync(crashLogPath, crashData);
482
+ // Clean up terminal state before throwing
483
+ this.stop();
484
+ const errorMsg = [
485
+ `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
486
+ "",
487
+ "This is likely caused by a custom TUI component not truncating its output.",
488
+ "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
489
+ "",
490
+ `Debug log written to: ${crashLogPath}`,
491
+ ].join("\n");
492
+ throw new Error(errorMsg);
493
+ }
494
+ output.append(line);
495
+ }
496
+ // Track where cursor ended up after rendering
497
+ let finalCursorRow = renderEnd;
498
+ // If we had more lines before, clear them and move cursor back
499
+ if (this.previousLines.length > newLines.length) {
500
+ // Move to end of new content first if we stopped before it
501
+ if (renderEnd < newLines.length - 1) {
502
+ const moveDown = newLines.length - 1 - renderEnd;
503
+ output.append(`\x1b[${moveDown}B`);
504
+ finalCursorRow = newLines.length - 1;
505
+ }
506
+ const extraLines = this.previousLines.length - newLines.length;
507
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
508
+ output.append("\r\n\x1b[2K");
509
+ }
510
+ // Move cursor back to end of new content
511
+ output.append(`\x1b[${extraLines}A`);
512
+ }
513
+ output.append("\x1b[?2026l"); // End synchronized output
514
+ if (process.env.ION_TUI_DEBUG === "1") {
515
+ const debugDir = "/tmp/tui";
516
+ fs.mkdirSync(debugDir, { recursive: true });
517
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
518
+ const debugData = [
519
+ `firstChanged: ${firstChanged}`,
520
+ `viewportTop: ${viewportTop}`,
521
+ `cursorRow: ${this.cursorRow}`,
522
+ `height: ${height}`,
523
+ `lineDiff: ${lineDiff}`,
524
+ `hardwareCursorRow: ${hardwareCursorRow}`,
525
+ `renderEnd: ${renderEnd}`,
526
+ `finalCursorRow: ${finalCursorRow}`,
527
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
528
+ `newLines.length: ${newLines.length}`,
529
+ `previousLines.length: ${this.previousLines.length}`,
530
+ "",
531
+ "=== newLines ===",
532
+ JSON.stringify(newLines, null, 2),
533
+ "",
534
+ "=== previousLines ===",
535
+ JSON.stringify(this.previousLines, null, 2),
536
+ "",
537
+ "=== buffer ===",
538
+ `[${output.length} chars written in bounded chunks]`,
539
+ ].join("\n");
540
+ fs.writeFileSync(debugPath, debugData);
541
+ }
542
+ output.flush();
543
+ // Track cursor position for next render
544
+ // cursorRow tracks end of content (for viewport calculation)
545
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
546
+ this.cursorRow = Math.max(0, newLines.length - 1);
547
+ this.hardwareCursorRow = finalCursorRow;
548
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
549
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
550
+ this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
551
+ // Position hardware cursor for IME
552
+ this.positionHardwareCursor(cursorPos, newLines.length);
553
+ this.previousLines = newLines;
554
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
555
+ this.previousWidth = width;
556
+ this.previousHeight = height;
557
+ }
558
+ /**
559
+ * Position the hardware cursor for IME candidate window.
560
+ * @param cursorPos The cursor position extracted from rendered output, or null
561
+ * @param totalLines Total number of rendered lines
562
+ */
563
+ positionHardwareCursor(cursorPos, totalLines) {
564
+ if (!cursorPos || totalLines <= 0) {
565
+ this.terminal.hideCursor();
566
+ return;
567
+ }
568
+ // Clamp cursor position to valid range
569
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
570
+ const targetCol = Math.max(0, cursorPos.col);
571
+ // Move cursor from current position to target
572
+ const rowDelta = targetRow - this.hardwareCursorRow;
573
+ let buffer = "";
574
+ if (rowDelta > 0) {
575
+ buffer += `\x1b[${rowDelta}B`; // Move down
576
+ }
577
+ else if (rowDelta < 0) {
578
+ buffer += `\x1b[${-rowDelta}A`; // Move up
579
+ }
580
+ // Move to absolute column (1-indexed)
581
+ buffer += `\x1b[${targetCol + 1}G`;
582
+ if (buffer) {
583
+ this.terminal.write(buffer);
584
+ }
585
+ this.hardwareCursorRow = targetRow;
586
+ if (this.getShowHardwareCursor()) {
587
+ this.terminal.showCursor();
588
+ }
589
+ else {
590
+ this.terminal.hideCursor();
591
+ }
592
+ }
593
+ }
594
+ //# sourceMappingURL=tui-main-screen.js.map