@chengchenccc/tui 0.1.1-rc.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 (226) hide show
  1. package/dist/autocomplete.d.ts +56 -0
  2. package/dist/autocomplete.d.ts.map +1 -0
  3. package/dist/autocomplete.js +647 -0
  4. package/dist/components/box.d.ts +22 -0
  5. package/dist/components/box.d.ts.map +1 -0
  6. package/dist/components/box.js +103 -0
  7. package/dist/components/card.d.ts +33 -0
  8. package/dist/components/card.d.ts.map +1 -0
  9. package/dist/components/card.js +49 -0
  10. package/dist/components/editor.d.ts +257 -0
  11. package/dist/components/editor.d.ts.map +1 -0
  12. package/dist/components/editor.js +1980 -0
  13. package/dist/components/input.d.ts +37 -0
  14. package/dist/components/input.d.ts.map +1 -0
  15. package/dist/components/input.js +389 -0
  16. package/dist/components/loader.d.ts +33 -0
  17. package/dist/components/loader.d.ts.map +1 -0
  18. package/dist/components/loader.js +100 -0
  19. package/dist/components/markdown.d.ts +108 -0
  20. package/dist/components/markdown.d.ts.map +1 -0
  21. package/dist/components/markdown.js +847 -0
  22. package/dist/components/markdown.test.d.ts +2 -0
  23. package/dist/components/markdown.test.d.ts.map +1 -0
  24. package/dist/components/markdown.test.js +81 -0
  25. package/dist/components/output-block.d.ts +44 -0
  26. package/dist/components/output-block.d.ts.map +1 -0
  27. package/dist/components/output-block.js +131 -0
  28. package/dist/components/select-list.d.ts +50 -0
  29. package/dist/components/select-list.d.ts.map +1 -0
  30. package/dist/components/select-list.js +166 -0
  31. package/dist/components/spacer.d.ts +12 -0
  32. package/dist/components/spacer.d.ts.map +1 -0
  33. package/dist/components/spacer.js +22 -0
  34. package/dist/components/statusline.d.ts +30 -0
  35. package/dist/components/statusline.d.ts.map +1 -0
  36. package/dist/components/statusline.js +46 -0
  37. package/dist/components/text.d.ts +19 -0
  38. package/dist/components/text.d.ts.map +1 -0
  39. package/dist/components/text.js +90 -0
  40. package/dist/components/truncated-text.d.ts +13 -0
  41. package/dist/components/truncated-text.d.ts.map +1 -0
  42. package/dist/components/truncated-text.js +50 -0
  43. package/dist/editor-component.d.ts +39 -0
  44. package/dist/editor-component.d.ts.map +1 -0
  45. package/dist/editor-component.js +1 -0
  46. package/dist/fuzzy.d.ts +16 -0
  47. package/dist/fuzzy.d.ts.map +1 -0
  48. package/dist/fuzzy.js +109 -0
  49. package/dist/index.d.ts +25 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +36 -0
  52. package/dist/keybindings.d.ts +193 -0
  53. package/dist/keybindings.d.ts.map +1 -0
  54. package/dist/keybindings.js +191 -0
  55. package/dist/keys.d.ts +184 -0
  56. package/dist/keys.d.ts.map +1 -0
  57. package/dist/keys.js +1191 -0
  58. package/dist/kill-ring.d.ts +28 -0
  59. package/dist/kill-ring.d.ts.map +1 -0
  60. package/dist/kill-ring.js +43 -0
  61. package/dist/mermaid.d.ts +23 -0
  62. package/dist/mermaid.d.ts.map +1 -0
  63. package/dist/mermaid.js +77 -0
  64. package/dist/mouse.d.ts +40 -0
  65. package/dist/mouse.d.ts.map +1 -0
  66. package/dist/mouse.js +39 -0
  67. package/dist/mouse.test.d.ts +2 -0
  68. package/dist/mouse.test.d.ts.map +1 -0
  69. package/dist/mouse.test.js +36 -0
  70. package/dist/native-modifiers.d.ts +3 -0
  71. package/dist/native-modifiers.d.ts.map +1 -0
  72. package/dist/native-modifiers.js +52 -0
  73. package/dist/stdin-buffer.d.ts +50 -0
  74. package/dist/stdin-buffer.d.ts.map +1 -0
  75. package/dist/stdin-buffer.js +360 -0
  76. package/dist/terminal-colors.d.ts +10 -0
  77. package/dist/terminal-colors.d.ts.map +1 -0
  78. package/dist/terminal-colors.js +58 -0
  79. package/dist/terminal-image.d.ts +90 -0
  80. package/dist/terminal-image.d.ts.map +1 -0
  81. package/dist/terminal-image.js +375 -0
  82. package/dist/terminal.d.ts +110 -0
  83. package/dist/terminal.d.ts.map +1 -0
  84. package/dist/terminal.js +432 -0
  85. package/dist/tui-scrollback.test.d.ts +2 -0
  86. package/dist/tui-scrollback.test.d.ts.map +1 -0
  87. package/dist/tui-scrollback.test.js +51 -0
  88. package/dist/tui.d.ts +330 -0
  89. package/dist/tui.d.ts.map +1 -0
  90. package/dist/tui.js +1568 -0
  91. package/dist/undo-stack.d.ts +17 -0
  92. package/dist/undo-stack.d.ts.map +1 -0
  93. package/dist/undo-stack.js +24 -0
  94. package/dist/utils.d.ts +85 -0
  95. package/dist/utils.d.ts.map +1 -0
  96. package/dist/utils.js +1066 -0
  97. package/dist/vendor/mermaid-ascii/ascii/ansi.d.ts +42 -0
  98. package/dist/vendor/mermaid-ascii/ascii/ansi.d.ts.map +1 -0
  99. package/dist/vendor/mermaid-ascii/ascii/ansi.js +361 -0
  100. package/dist/vendor/mermaid-ascii/ascii/canvas.d.ts +90 -0
  101. package/dist/vendor/mermaid-ascii/ascii/canvas.d.ts.map +1 -0
  102. package/dist/vendor/mermaid-ascii/ascii/canvas.js +414 -0
  103. package/dist/vendor/mermaid-ascii/ascii/class-diagram.d.ts +8 -0
  104. package/dist/vendor/mermaid-ascii/ascii/class-diagram.d.ts.map +1 -0
  105. package/dist/vendor/mermaid-ascii/ascii/class-diagram.js +623 -0
  106. package/dist/vendor/mermaid-ascii/ascii/converter.d.ts +13 -0
  107. package/dist/vendor/mermaid-ascii/ascii/converter.d.ts.map +1 -0
  108. package/dist/vendor/mermaid-ascii/ascii/converter.js +233 -0
  109. package/dist/vendor/mermaid-ascii/ascii/draw.d.ts +67 -0
  110. package/dist/vendor/mermaid-ascii/ascii/draw.d.ts.map +1 -0
  111. package/dist/vendor/mermaid-ascii/ascii/draw.js +1313 -0
  112. package/dist/vendor/mermaid-ascii/ascii/edge-bundling.d.ts +49 -0
  113. package/dist/vendor/mermaid-ascii/ascii/edge-bundling.d.ts.map +1 -0
  114. package/dist/vendor/mermaid-ascii/ascii/edge-bundling.js +289 -0
  115. package/dist/vendor/mermaid-ascii/ascii/edge-routing.d.ts +44 -0
  116. package/dist/vendor/mermaid-ascii/ascii/edge-routing.d.ts.map +1 -0
  117. package/dist/vendor/mermaid-ascii/ascii/edge-routing.js +302 -0
  118. package/dist/vendor/mermaid-ascii/ascii/er-diagram.d.ts +8 -0
  119. package/dist/vendor/mermaid-ascii/ascii/er-diagram.d.ts.map +1 -0
  120. package/dist/vendor/mermaid-ascii/ascii/er-diagram.js +380 -0
  121. package/dist/vendor/mermaid-ascii/ascii/grid.d.ts +57 -0
  122. package/dist/vendor/mermaid-ascii/ascii/grid.d.ts.map +1 -0
  123. package/dist/vendor/mermaid-ascii/ascii/grid.js +516 -0
  124. package/dist/vendor/mermaid-ascii/ascii/index.d.ts +66 -0
  125. package/dist/vendor/mermaid-ascii/ascii/index.d.ts.map +1 -0
  126. package/dist/vendor/mermaid-ascii/ascii/index.js +133 -0
  127. package/dist/vendor/mermaid-ascii/ascii/multiline-utils.d.ts +28 -0
  128. package/dist/vendor/mermaid-ascii/ascii/multiline-utils.d.ts.map +1 -0
  129. package/dist/vendor/mermaid-ascii/ascii/multiline-utils.js +60 -0
  130. package/dist/vendor/mermaid-ascii/ascii/pathfinder.d.ts +18 -0
  131. package/dist/vendor/mermaid-ascii/ascii/pathfinder.d.ts.map +1 -0
  132. package/dist/vendor/mermaid-ascii/ascii/pathfinder.js +224 -0
  133. package/dist/vendor/mermaid-ascii/ascii/sequence.d.ts +8 -0
  134. package/dist/vendor/mermaid-ascii/ascii/sequence.d.ts.map +1 -0
  135. package/dist/vendor/mermaid-ascii/ascii/sequence.js +416 -0
  136. package/dist/vendor/mermaid-ascii/ascii/shapes/circle.d.ts +12 -0
  137. package/dist/vendor/mermaid-ascii/ascii/shapes/circle.d.ts.map +1 -0
  138. package/dist/vendor/mermaid-ascii/ascii/shapes/circle.js +22 -0
  139. package/dist/vendor/mermaid-ascii/ascii/shapes/corners.d.ts +35 -0
  140. package/dist/vendor/mermaid-ascii/ascii/shapes/corners.d.ts.map +1 -0
  141. package/dist/vendor/mermaid-ascii/ascii/shapes/corners.js +91 -0
  142. package/dist/vendor/mermaid-ascii/ascii/shapes/diamond.d.ts +12 -0
  143. package/dist/vendor/mermaid-ascii/ascii/shapes/diamond.d.ts.map +1 -0
  144. package/dist/vendor/mermaid-ascii/ascii/shapes/diamond.js +22 -0
  145. package/dist/vendor/mermaid-ascii/ascii/shapes/hexagon.d.ts +12 -0
  146. package/dist/vendor/mermaid-ascii/ascii/shapes/hexagon.d.ts.map +1 -0
  147. package/dist/vendor/mermaid-ascii/ascii/shapes/hexagon.js +22 -0
  148. package/dist/vendor/mermaid-ascii/ascii/shapes/index.d.ts +27 -0
  149. package/dist/vendor/mermaid-ascii/ascii/shapes/index.d.ts.map +1 -0
  150. package/dist/vendor/mermaid-ascii/ascii/shapes/index.js +66 -0
  151. package/dist/vendor/mermaid-ascii/ascii/shapes/rectangle.d.ts +32 -0
  152. package/dist/vendor/mermaid-ascii/ascii/shapes/rectangle.d.ts.map +1 -0
  153. package/dist/vendor/mermaid-ascii/ascii/shapes/rectangle.js +149 -0
  154. package/dist/vendor/mermaid-ascii/ascii/shapes/rounded.d.ts +12 -0
  155. package/dist/vendor/mermaid-ascii/ascii/shapes/rounded.d.ts.map +1 -0
  156. package/dist/vendor/mermaid-ascii/ascii/shapes/rounded.js +22 -0
  157. package/dist/vendor/mermaid-ascii/ascii/shapes/special.d.ts +60 -0
  158. package/dist/vendor/mermaid-ascii/ascii/shapes/special.d.ts.map +1 -0
  159. package/dist/vendor/mermaid-ascii/ascii/shapes/special.js +253 -0
  160. package/dist/vendor/mermaid-ascii/ascii/shapes/stadium.d.ts +18 -0
  161. package/dist/vendor/mermaid-ascii/ascii/shapes/stadium.d.ts.map +1 -0
  162. package/dist/vendor/mermaid-ascii/ascii/shapes/stadium.js +103 -0
  163. package/dist/vendor/mermaid-ascii/ascii/shapes/state.d.ts +31 -0
  164. package/dist/vendor/mermaid-ascii/ascii/shapes/state.d.ts.map +1 -0
  165. package/dist/vendor/mermaid-ascii/ascii/shapes/state.js +167 -0
  166. package/dist/vendor/mermaid-ascii/ascii/shapes/types.d.ts +56 -0
  167. package/dist/vendor/mermaid-ascii/ascii/shapes/types.d.ts.map +1 -0
  168. package/dist/vendor/mermaid-ascii/ascii/shapes/types.js +4 -0
  169. package/dist/vendor/mermaid-ascii/ascii/types.d.ts +207 -0
  170. package/dist/vendor/mermaid-ascii/ascii/types.d.ts.map +1 -0
  171. package/dist/vendor/mermaid-ascii/ascii/types.js +39 -0
  172. package/dist/vendor/mermaid-ascii/ascii/validate.d.ts +52 -0
  173. package/dist/vendor/mermaid-ascii/ascii/validate.d.ts.map +1 -0
  174. package/dist/vendor/mermaid-ascii/ascii/validate.js +97 -0
  175. package/dist/vendor/mermaid-ascii/ascii/xychart.d.ts +3 -0
  176. package/dist/vendor/mermaid-ascii/ascii/xychart.d.ts.map +1 -0
  177. package/dist/vendor/mermaid-ascii/ascii/xychart.js +719 -0
  178. package/dist/vendor/mermaid-ascii/class/parser.d.ts +7 -0
  179. package/dist/vendor/mermaid-ascii/class/parser.d.ts.map +1 -0
  180. package/dist/vendor/mermaid-ascii/class/parser.js +265 -0
  181. package/dist/vendor/mermaid-ascii/class/types.d.ts +103 -0
  182. package/dist/vendor/mermaid-ascii/class/types.d.ts.map +1 -0
  183. package/dist/vendor/mermaid-ascii/class/types.js +7 -0
  184. package/dist/vendor/mermaid-ascii/er/parser.d.ts +7 -0
  185. package/dist/vendor/mermaid-ascii/er/parser.d.ts.map +1 -0
  186. package/dist/vendor/mermaid-ascii/er/parser.js +162 -0
  187. package/dist/vendor/mermaid-ascii/er/types.d.ts +77 -0
  188. package/dist/vendor/mermaid-ascii/er/types.d.ts.map +1 -0
  189. package/dist/vendor/mermaid-ascii/er/types.js +7 -0
  190. package/dist/vendor/mermaid-ascii/index.d.ts +2 -0
  191. package/dist/vendor/mermaid-ascii/index.d.ts.map +1 -0
  192. package/dist/vendor/mermaid-ascii/index.js +13 -0
  193. package/dist/vendor/mermaid-ascii/multiline-utils.d.ts +10 -0
  194. package/dist/vendor/mermaid-ascii/multiline-utils.d.ts.map +1 -0
  195. package/dist/vendor/mermaid-ascii/multiline-utils.js +29 -0
  196. package/dist/vendor/mermaid-ascii/parser.d.ts +8 -0
  197. package/dist/vendor/mermaid-ascii/parser.d.ts.map +1 -0
  198. package/dist/vendor/mermaid-ascii/parser.js +558 -0
  199. package/dist/vendor/mermaid-ascii/sequence/parser.d.ts +7 -0
  200. package/dist/vendor/mermaid-ascii/sequence/parser.d.ts.map +1 -0
  201. package/dist/vendor/mermaid-ascii/sequence/parser.js +182 -0
  202. package/dist/vendor/mermaid-ascii/sequence/types.d.ts +131 -0
  203. package/dist/vendor/mermaid-ascii/sequence/types.d.ts.map +1 -0
  204. package/dist/vendor/mermaid-ascii/sequence/types.js +7 -0
  205. package/dist/vendor/mermaid-ascii/text-metrics.d.ts +24 -0
  206. package/dist/vendor/mermaid-ascii/text-metrics.d.ts.map +1 -0
  207. package/dist/vendor/mermaid-ascii/text-metrics.js +69 -0
  208. package/dist/vendor/mermaid-ascii/types.d.ts +115 -0
  209. package/dist/vendor/mermaid-ascii/types.d.ts.map +1 -0
  210. package/dist/vendor/mermaid-ascii/types.js +4 -0
  211. package/dist/vendor/mermaid-ascii/xychart/colors.d.ts +26 -0
  212. package/dist/vendor/mermaid-ascii/xychart/colors.d.ts.map +1 -0
  213. package/dist/vendor/mermaid-ascii/xychart/colors.js +145 -0
  214. package/dist/vendor/mermaid-ascii/xychart/parser.d.ts +7 -0
  215. package/dist/vendor/mermaid-ascii/xychart/parser.d.ts.map +1 -0
  216. package/dist/vendor/mermaid-ascii/xychart/parser.js +105 -0
  217. package/dist/vendor/mermaid-ascii/xychart/types.d.ts +146 -0
  218. package/dist/vendor/mermaid-ascii/xychart/types.d.ts.map +1 -0
  219. package/dist/vendor/mermaid-ascii/xychart/types.js +8 -0
  220. package/dist/virtual-terminal.d.ts +80 -0
  221. package/dist/virtual-terminal.d.ts.map +1 -0
  222. package/dist/virtual-terminal.js +284 -0
  223. package/dist/word-navigation.d.ts +25 -0
  224. package/dist/word-navigation.d.ts.map +1 -0
  225. package/dist/word-navigation.js +97 -0
  226. package/package.json +38 -0
@@ -0,0 +1,432 @@
1
+ import * as fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { setKittyProtocolActive } from "./keys.js";
6
+ import { isNativeModifierPressed } from "./native-modifiers.js";
7
+ import { StdinBuffer } from "./stdin-buffer.js";
8
+ const cjsRequire = createRequire(import.meta.url);
9
+ const TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;
10
+ const TERMINAL_PROGRESS_ACTIVE_SEQUENCE = "\x1b]9;4;3\x07";
11
+ const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0;\x07";
12
+ const APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = "\x1b[13;2u";
13
+ const DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
14
+ const KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
15
+ const KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
16
+ export function parseKeyboardProtocolNegotiationSequence(sequence) {
17
+ const kittyFlags = sequence.match(/^\x1b\[\?(\d+)u$/);
18
+ if (kittyFlags) {
19
+ return { type: "kitty-flags", flags: Number.parseInt(kittyFlags[1], 10) };
20
+ }
21
+ if (/^\x1b\[\?[\d;]*c$/.test(sequence)) {
22
+ return { type: "device-attributes" };
23
+ }
24
+ return undefined;
25
+ }
26
+ function isKeyboardProtocolNegotiationSequencePrefix(sequence) {
27
+ return sequence === "\x1b[" || /^\x1b\[\?[\d;]*$/.test(sequence);
28
+ }
29
+ export function isAppleTerminalSession() {
30
+ return process.platform === "darwin" && process.env.TERM_PROGRAM === "Apple_Terminal";
31
+ }
32
+ export function normalizeAppleTerminalInput(data, isAppleTerminal, isShiftPressed) {
33
+ if (isAppleTerminal && data === "\r" && isShiftPressed)
34
+ return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;
35
+ return data;
36
+ }
37
+ /**
38
+ * Real terminal using process.stdin/stdout
39
+ */
40
+ export class ProcessTerminal {
41
+ wasRaw = false;
42
+ inputHandler;
43
+ resizeHandler;
44
+ _kittyProtocolActive = false;
45
+ _modifyOtherKeysActive = false;
46
+ keyboardProtocolPushed = false;
47
+ keyboardProtocolNegotiationBuffer = "";
48
+ keyboardProtocolBufferFlushTimer;
49
+ stdinBuffer;
50
+ stdinDataHandler;
51
+ progressInterval;
52
+ writeLogPath = (() => {
53
+ const env = process.env.PI_TUI_WRITE_LOG || "";
54
+ if (!env)
55
+ return "";
56
+ try {
57
+ if (fs.statSync(env).isDirectory()) {
58
+ const now = new Date();
59
+ const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}-${String(now.getSeconds()).padStart(2, "0")}`;
60
+ return path.join(env, `tui-${ts}-${process.pid}.log`);
61
+ }
62
+ }
63
+ catch {
64
+ // Not an existing directory - use as-is (file path)
65
+ }
66
+ return env;
67
+ })();
68
+ get kittyProtocolActive() {
69
+ return this._kittyProtocolActive;
70
+ }
71
+ get modifyOtherKeysActive() {
72
+ return this._modifyOtherKeysActive;
73
+ }
74
+ start(onInput, onResize) {
75
+ this.inputHandler = onInput;
76
+ this.resizeHandler = onResize;
77
+ // Save previous state and enable raw mode
78
+ this.wasRaw = process.stdin.isRaw || false;
79
+ if (process.stdin.setRawMode) {
80
+ process.stdin.setRawMode(true);
81
+ }
82
+ process.stdin.setEncoding("utf8");
83
+ process.stdin.resume();
84
+ // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
85
+ process.stdout.write("\x1b[?2004h");
86
+ // Set up resize handler immediately
87
+ process.stdout.on("resize", this.resizeHandler);
88
+ // Refresh terminal dimensions - they may be stale after suspend/resume
89
+ // (SIGWINCH is lost while process is stopped). Unix only.
90
+ if (process.platform !== "win32") {
91
+ process.kill(process.pid, "SIGWINCH");
92
+ }
93
+ // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
94
+ // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
95
+ // events that lose modifier information. Must run AFTER setRawMode(true)
96
+ // since that resets console mode flags.
97
+ this.enableWindowsVTInput();
98
+ // Query Kitty keyboard protocol and fall back to modifyOtherKeys when DA confirms no Kitty response.
99
+ // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
100
+ this.queryAndEnableKittyProtocol();
101
+ }
102
+ /**
103
+ * Set up StdinBuffer to split batched input into individual sequences.
104
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
105
+ *
106
+ * Also watches for Kitty protocol response and enables it when detected.
107
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
108
+ * to handle the case where the response arrives split across multiple events.
109
+ */
110
+ setupStdinBuffer() {
111
+ this.stdinBuffer = new StdinBuffer({ timeout: 10 });
112
+ // Forward individual sequences to the input handler
113
+ this.stdinBuffer.on("data", (sequence) => {
114
+ const negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence);
115
+ if (negotiationSequence === "pending") {
116
+ this.scheduleKeyboardProtocolNegotiationBufferFlush();
117
+ return; // Wait briefly for the rest of a split Kitty response.
118
+ }
119
+ if (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {
120
+ return;
121
+ }
122
+ this.forwardInputSequence(sequence);
123
+ });
124
+ // Re-wrap paste content with bracketed paste markers for existing editor handling
125
+ this.stdinBuffer.on("paste", (content) => {
126
+ if (this.inputHandler) {
127
+ this.inputHandler(`\x1b[200~${content}\x1b[201~`);
128
+ }
129
+ });
130
+ // Handler that pipes stdin data through the buffer
131
+ this.stdinDataHandler = (data) => {
132
+ this.stdinBuffer.process(data);
133
+ };
134
+ }
135
+ /**
136
+ * Query terminal for Kitty keyboard protocol support and enable it if available.
137
+ *
138
+ * Kitty's progressive enhancement detection requires requesting the desired
139
+ * flags before querying them. The trailing DA query is a sentinel supported by
140
+ * terminals that do not know Kitty keyboard protocol; receiving DA before a
141
+ * Kitty response enables modifyOtherKeys fallback without a startup timeout.
142
+ *
143
+ * The requested flags are:
144
+ * - 1 = disambiguate escape codes
145
+ * - 2 = report event types (press/repeat/release)
146
+ * - 4 = report alternate keys (shifted key, base layout key)
147
+ */
148
+ queryAndEnableKittyProtocol() {
149
+ this.setupStdinBuffer();
150
+ process.stdin.on("data", this.stdinDataHandler);
151
+ this.keyboardProtocolPushed = true;
152
+ this.clearKeyboardProtocolNegotiationBuffer();
153
+ process.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);
154
+ }
155
+ handleKeyboardProtocolNegotiationSequence(negotiationSequence) {
156
+ if (!negotiationSequence)
157
+ return false;
158
+ this.clearKeyboardProtocolNegotiationBuffer();
159
+ if (negotiationSequence.type === "kitty-flags") {
160
+ if (negotiationSequence.flags !== 0) {
161
+ this.disableModifyOtherKeys();
162
+ if (!this._kittyProtocolActive) {
163
+ this._kittyProtocolActive = true;
164
+ setKittyProtocolActive(true);
165
+ }
166
+ }
167
+ else {
168
+ this.enableModifyOtherKeys();
169
+ }
170
+ return true;
171
+ }
172
+ if (!this._kittyProtocolActive) {
173
+ this.enableModifyOtherKeys();
174
+ }
175
+ return true;
176
+ }
177
+ readKeyboardProtocolNegotiationSequence(sequence) {
178
+ if (this.keyboardProtocolNegotiationBuffer) {
179
+ const bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;
180
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);
181
+ if (negotiationSequence) {
182
+ this.clearKeyboardProtocolNegotiationBuffer();
183
+ return negotiationSequence;
184
+ }
185
+ if (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence)) {
186
+ this.setKeyboardProtocolNegotiationBuffer(bufferedSequence);
187
+ return "pending";
188
+ }
189
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
190
+ }
191
+ const negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);
192
+ if (negotiationSequence)
193
+ return negotiationSequence;
194
+ if (isKeyboardProtocolNegotiationSequencePrefix(sequence)) {
195
+ this.setKeyboardProtocolNegotiationBuffer(sequence);
196
+ return "pending";
197
+ }
198
+ return undefined;
199
+ }
200
+ setKeyboardProtocolNegotiationBuffer(sequence) {
201
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
202
+ this.keyboardProtocolNegotiationBuffer = sequence;
203
+ }
204
+ clearKeyboardProtocolNegotiationBuffer() {
205
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer();
206
+ this.keyboardProtocolNegotiationBuffer = "";
207
+ }
208
+ flushKeyboardProtocolNegotiationBufferAsInput() {
209
+ if (!this.keyboardProtocolNegotiationBuffer)
210
+ return;
211
+ const sequence = this.keyboardProtocolNegotiationBuffer;
212
+ this.clearKeyboardProtocolNegotiationBuffer();
213
+ this.forwardInputSequence(sequence);
214
+ }
215
+ scheduleKeyboardProtocolNegotiationBufferFlush() {
216
+ if (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer)
217
+ return;
218
+ this.keyboardProtocolBufferFlushTimer = setTimeout(() => {
219
+ this.keyboardProtocolBufferFlushTimer = undefined;
220
+ this.flushKeyboardProtocolNegotiationBufferAsInput();
221
+ }, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);
222
+ }
223
+ clearKeyboardProtocolNegotiationBufferFlushTimer() {
224
+ if (!this.keyboardProtocolBufferFlushTimer)
225
+ return;
226
+ clearTimeout(this.keyboardProtocolBufferFlushTimer);
227
+ this.keyboardProtocolBufferFlushTimer = undefined;
228
+ }
229
+ forwardInputSequence(sequence) {
230
+ if (!this.inputHandler)
231
+ return;
232
+ const isAppleTerminal = sequence === "\r" && isAppleTerminalSession();
233
+ const input = normalizeAppleTerminalInput(sequence, isAppleTerminal, isAppleTerminal && isNativeModifierPressed("shift"));
234
+ this.inputHandler(input);
235
+ }
236
+ enableModifyOtherKeys() {
237
+ if (this._kittyProtocolActive || this._modifyOtherKeysActive)
238
+ return;
239
+ process.stdout.write("\x1b[>4;2m");
240
+ this._modifyOtherKeysActive = true;
241
+ }
242
+ disableModifyOtherKeys() {
243
+ if (!this._modifyOtherKeysActive)
244
+ return;
245
+ process.stdout.write("\x1b[>4;0m");
246
+ this._modifyOtherKeysActive = false;
247
+ }
248
+ /**
249
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
250
+ * console handle so the terminal sends VT sequences for modified keys
251
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
252
+ * discards modifier state and Shift+Tab arrives as plain \t.
253
+ */
254
+ enableWindowsVTInput() {
255
+ if (process.platform !== "win32")
256
+ return;
257
+ try {
258
+ const arch = process.arch;
259
+ if (arch !== "x64" && arch !== "arm64")
260
+ return;
261
+ // Dynamic require so non-Windows and bundled/browser paths never load the
262
+ // native helper. In the npm package native/ is next to dist/; in compiled
263
+ // binary archives native/ is copied next to the executable.
264
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
265
+ const nativePath = path.join("native", "win32", "prebuilds", `win32-${arch}`, "win32-console-mode.node");
266
+ const candidates = [
267
+ path.join(moduleDir, "..", nativePath),
268
+ path.join(moduleDir, nativePath),
269
+ path.join(path.dirname(process.execPath), nativePath),
270
+ ];
271
+ for (const modulePath of candidates) {
272
+ try {
273
+ const helper = cjsRequire(modulePath);
274
+ helper.enableVirtualTerminalInput?.();
275
+ return;
276
+ }
277
+ catch {
278
+ // Try the next possible packaging location.
279
+ }
280
+ }
281
+ }
282
+ catch {
283
+ // Native helper not available — Shift+Tab won't be distinguishable from Tab.
284
+ }
285
+ }
286
+ async drainInput(maxMs = 1000, idleMs = 50) {
287
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
288
+ this.clearKeyboardProtocolNegotiationBuffer();
289
+ if (shouldDisableKittyProtocol) {
290
+ // Disable Kitty keyboard protocol first so any late key releases
291
+ // do not generate new Kitty escape sequences.
292
+ process.stdout.write("\x1b[<u");
293
+ this.keyboardProtocolPushed = false;
294
+ this._kittyProtocolActive = false;
295
+ setKittyProtocolActive(false);
296
+ }
297
+ this.disableModifyOtherKeys();
298
+ const previousHandler = this.inputHandler;
299
+ this.inputHandler = undefined;
300
+ let lastDataTime = Date.now();
301
+ const onData = () => {
302
+ lastDataTime = Date.now();
303
+ };
304
+ process.stdin.on("data", onData);
305
+ const endTime = Date.now() + maxMs;
306
+ try {
307
+ while (true) {
308
+ const now = Date.now();
309
+ const timeLeft = endTime - now;
310
+ if (timeLeft <= 0)
311
+ break;
312
+ if (now - lastDataTime >= idleMs)
313
+ break;
314
+ await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
315
+ }
316
+ }
317
+ finally {
318
+ process.stdin.removeListener("data", onData);
319
+ this.inputHandler = previousHandler;
320
+ }
321
+ }
322
+ stop() {
323
+ if (this.clearProgressInterval()) {
324
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
325
+ }
326
+ // Disable bracketed paste mode
327
+ process.stdout.write("\x1b[?2004l");
328
+ const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
329
+ this.clearKeyboardProtocolNegotiationBuffer();
330
+ // Disable Kitty keyboard protocol if not already done by drainInput()
331
+ if (shouldDisableKittyProtocol) {
332
+ process.stdout.write("\x1b[<u");
333
+ this.keyboardProtocolPushed = false;
334
+ this._kittyProtocolActive = false;
335
+ setKittyProtocolActive(false);
336
+ }
337
+ this.disableModifyOtherKeys();
338
+ // Clean up StdinBuffer
339
+ if (this.stdinBuffer) {
340
+ this.stdinBuffer.destroy();
341
+ this.stdinBuffer = undefined;
342
+ }
343
+ // Remove event handlers
344
+ if (this.stdinDataHandler) {
345
+ process.stdin.removeListener("data", this.stdinDataHandler);
346
+ this.stdinDataHandler = undefined;
347
+ }
348
+ this.inputHandler = undefined;
349
+ if (this.resizeHandler) {
350
+ process.stdout.removeListener("resize", this.resizeHandler);
351
+ this.resizeHandler = undefined;
352
+ }
353
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
354
+ // re-interpreted after raw mode is disabled. This fixes a race condition
355
+ // where Ctrl+D could close the parent shell over SSH.
356
+ process.stdin.pause();
357
+ // Restore raw mode state
358
+ if (process.stdin.setRawMode) {
359
+ process.stdin.setRawMode(this.wasRaw);
360
+ }
361
+ }
362
+ write(data) {
363
+ process.stdout.write(data);
364
+ if (this.writeLogPath) {
365
+ try {
366
+ fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
367
+ }
368
+ catch {
369
+ // Ignore logging errors
370
+ }
371
+ }
372
+ }
373
+ get columns() {
374
+ return process.stdout.columns || Number(process.env.COLUMNS) || 80;
375
+ }
376
+ get rows() {
377
+ return process.stdout.rows || Number(process.env.LINES) || 24;
378
+ }
379
+ moveBy(lines) {
380
+ if (lines > 0) {
381
+ // Move down
382
+ process.stdout.write(`\x1b[${lines}B`);
383
+ }
384
+ else if (lines < 0) {
385
+ // Move up
386
+ process.stdout.write(`\x1b[${-lines}A`);
387
+ }
388
+ // lines === 0: no movement
389
+ }
390
+ hideCursor() {
391
+ process.stdout.write("\x1b[?25l");
392
+ }
393
+ showCursor() {
394
+ process.stdout.write("\x1b[?25h");
395
+ }
396
+ clearLine() {
397
+ process.stdout.write("\x1b[K");
398
+ }
399
+ clearFromCursor() {
400
+ process.stdout.write("\x1b[J");
401
+ }
402
+ clearScreen() {
403
+ process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
404
+ }
405
+ setTitle(title) {
406
+ // OSC 0;title BEL - set terminal window title
407
+ process.stdout.write(`\x1b]0;${title}\x07`);
408
+ }
409
+ setProgress(active) {
410
+ if (active) {
411
+ // OSC 9;4;3 - indeterminate progress
412
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
413
+ if (!this.progressInterval) {
414
+ this.progressInterval = setInterval(() => {
415
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
416
+ }, TERMINAL_PROGRESS_KEEPALIVE_MS);
417
+ }
418
+ }
419
+ else {
420
+ this.clearProgressInterval();
421
+ // OSC 9;4;0 - clear progress
422
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
423
+ }
424
+ }
425
+ clearProgressInterval() {
426
+ if (!this.progressInterval)
427
+ return false;
428
+ clearInterval(this.progressInterval);
429
+ this.progressInterval = undefined;
430
+ return true;
431
+ }
432
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=tui-scrollback.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tui-scrollback.test.d.ts","sourceRoot":"","sources":["../src/tui-scrollback.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,51 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { Text } from "./components/text.js";
3
+ import { TUI } from "./tui.js";
4
+ import { VirtualTerminal } from "./virtual-terminal.js";
5
+ describe("TUI resize scrollback", () => {
6
+ test("width change clears native scrollback so old-width wraps do not remain", async () => {
7
+ const vt = new VirtualTerminal(20, 5);
8
+ const tui = new TUI(vt);
9
+ for (let i = 0; i < 10; i++) {
10
+ tui.addChild(new Text("A".repeat(20), 0, 0));
11
+ }
12
+ tui.start();
13
+ await vt.waitForRender();
14
+ const before = vt.getScrollBuffer();
15
+ expect(before.some((line) => line.includes("A".repeat(20)))).toBe(true);
16
+ vt.resize(10, 5);
17
+ await vt.waitForRender();
18
+ const after = vt.getScrollBuffer();
19
+ // The 20-column rows must not survive a 10-column rerender; content is
20
+ // re-wrapped into 10-column rows instead.
21
+ expect(after.some((line) => line.includes("A".repeat(20)))).toBe(false);
22
+ expect(after.some((line) => line.includes("A".repeat(10)))).toBe(true);
23
+ });
24
+ });
25
+ describe("TUI provider native scrollback", () => {
26
+ test("history rows land in terminal scrollback and the viewport stays bounded", async () => {
27
+ const vt = new VirtualTerminal(20, 5);
28
+ const tui = new TUI(vt);
29
+ let frame = 0;
30
+ tui.setFrameProvider({
31
+ renderFrame() {
32
+ frame++;
33
+ const viewport = ["V0", "V1", "V2", "V3", "V4"];
34
+ if (frame === 1)
35
+ return { viewport, history: { id: 1, rows: ["H0", "H1"] } };
36
+ if (frame === 2)
37
+ return { viewport, history: { id: 2, rows: ["H2"] } };
38
+ return { viewport };
39
+ },
40
+ acknowledgeHistory() { },
41
+ });
42
+ tui.start();
43
+ await vt.waitForRender();
44
+ // Drain the provider's history batches (requestRender recurses after ack).
45
+ await new Promise((r) => setTimeout(r, 30));
46
+ expect(frame).toBe(3);
47
+ const scroll = vt.getScrollBuffer();
48
+ expect(scroll.filter((l) => l.startsWith("H"))).toEqual(["H0", "H1", "H2"]);
49
+ expect(vt.getViewport().slice(-5)).toEqual(["V0", "V1", "V2", "V3", "V4"]);
50
+ });
51
+ });