@yaks/tui 0.0.0-stage → 0.2.36

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 (121) hide show
  1. package/Frame.js +52 -0
  2. package/Frame.js.map +1 -0
  3. package/Frame.ts +92 -0
  4. package/Image.js +10 -0
  5. package/Image.js.map +1 -0
  6. package/Image.ts +22 -0
  7. package/LICENSE +202 -0
  8. package/README.md +524 -2
  9. package/RenderedCursor.js +103 -0
  10. package/RenderedCursor.js.map +1 -0
  11. package/RenderedCursor.ts +127 -0
  12. package/Scroll.js +88 -0
  13. package/Scroll.js.map +1 -0
  14. package/Scroll.ts +155 -0
  15. package/Textarea.js +186 -0
  16. package/Textarea.js.map +1 -0
  17. package/Textarea.ts +234 -0
  18. package/VirtualList.js +729 -0
  19. package/VirtualList.js.map +1 -0
  20. package/VirtualList.ts +838 -0
  21. package/_dist/Frame.d.ts +25 -0
  22. package/_dist/Frame.d.ts.map +1 -0
  23. package/_dist/Image.d.ts +13 -0
  24. package/_dist/Image.d.ts.map +1 -0
  25. package/_dist/RenderedCursor.d.ts +9 -0
  26. package/_dist/RenderedCursor.d.ts.map +1 -0
  27. package/_dist/Scroll.d.ts +30 -0
  28. package/_dist/Scroll.d.ts.map +1 -0
  29. package/_dist/Textarea.d.ts +26 -0
  30. package/_dist/Textarea.d.ts.map +1 -0
  31. package/_dist/VirtualList.d.ts +103 -0
  32. package/_dist/VirtualList.d.ts.map +1 -0
  33. package/_dist/guide.d.ts +21 -0
  34. package/_dist/guide.d.ts.map +1 -0
  35. package/_dist/history.d.ts +12 -0
  36. package/_dist/history.d.ts.map +1 -0
  37. package/_dist/input.d.ts +47 -0
  38. package/_dist/input.d.ts.map +1 -0
  39. package/_dist/interaction.d.ts +15 -0
  40. package/_dist/interaction.d.ts.map +1 -0
  41. package/_dist/keymap.d.ts +4 -0
  42. package/_dist/keymap.d.ts.map +1 -0
  43. package/_dist/mod.d.ts +42 -0
  44. package/_dist/mod.d.ts.map +1 -0
  45. package/_dist/mouse.d.ts +15 -0
  46. package/_dist/mouse.d.ts.map +1 -0
  47. package/_dist/paint.d.ts +86 -0
  48. package/_dist/paint.d.ts.map +1 -0
  49. package/_dist/print.d.ts +20 -0
  50. package/_dist/print.d.ts.map +1 -0
  51. package/_dist/run.d.ts +19 -0
  52. package/_dist/run.d.ts.map +1 -0
  53. package/_dist/screen.d.ts +22 -0
  54. package/_dist/screen.d.ts.map +1 -0
  55. package/_dist/scrollbar.d.ts +7 -0
  56. package/_dist/scrollbar.d.ts.map +1 -0
  57. package/_dist/testing.d.ts +19 -0
  58. package/_dist/testing.d.ts.map +1 -0
  59. package/_dist/theme.d.ts +11 -0
  60. package/_dist/theme.d.ts.map +1 -0
  61. package/_dist/visual.d.ts +28 -0
  62. package/_dist/visual.d.ts.map +1 -0
  63. package/deno.json +1 -0
  64. package/graphics.js +157 -0
  65. package/graphics.js.map +1 -0
  66. package/graphics.ts +191 -0
  67. package/grid.js +38 -0
  68. package/grid.js.map +1 -0
  69. package/grid.ts +46 -0
  70. package/guide.js +144 -0
  71. package/guide.js.map +1 -0
  72. package/guide.ts +169 -0
  73. package/history.js +58 -0
  74. package/history.js.map +1 -0
  75. package/history.ts +59 -0
  76. package/input.js +356 -0
  77. package/input.js.map +1 -0
  78. package/input.ts +324 -0
  79. package/interaction.js +180 -0
  80. package/interaction.js.map +1 -0
  81. package/interaction.ts +185 -0
  82. package/keymap.js +20 -0
  83. package/keymap.js.map +1 -0
  84. package/keymap.ts +23 -0
  85. package/mod.js +39 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +92 -0
  88. package/mouse.js +65 -0
  89. package/mouse.js.map +1 -0
  90. package/mouse.ts +98 -0
  91. package/package.json +49 -4
  92. package/paint.js +1010 -0
  93. package/paint.js.map +1 -0
  94. package/paint.ts +1063 -0
  95. package/print.js +31 -0
  96. package/print.js.map +1 -0
  97. package/print.ts +40 -0
  98. package/run.js +220 -0
  99. package/run.js.map +1 -0
  100. package/run.ts +237 -0
  101. package/screen.js +97 -0
  102. package/screen.js.map +1 -0
  103. package/screen.ts +139 -0
  104. package/scrollbar.js +30 -0
  105. package/scrollbar.js.map +1 -0
  106. package/scrollbar.ts +33 -0
  107. package/table.js +134 -0
  108. package/table.js.map +1 -0
  109. package/table.ts +152 -0
  110. package/testing.js +86 -0
  111. package/testing.js.map +1 -0
  112. package/testing.ts +95 -0
  113. package/textRows.js +38 -0
  114. package/textRows.js.map +1 -0
  115. package/textRows.ts +31 -0
  116. package/theme.js +50 -0
  117. package/theme.js.map +1 -0
  118. package/theme.ts +39 -0
  119. package/visual.js +195 -0
  120. package/visual.js.map +1 -0
  121. package/visual.ts +209 -0
package/print.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A Preact tree painted once, for a command that prints and exits: mounted in
3
+ * the fake document, laid out and colored by the ANSI painter at `columns`
4
+ * wide, then unmounted, with no screen taken and nothing held. Its own entry
5
+ * (`@yaks/tui/print`), so a printout loads the painter without the widgets.
6
+ *
7
+ * ```ts
8
+ * import { assertEquals } from '@std/assert'
9
+ * import { createElement as h } from 'react'
10
+ * import { print } from '@yaks/tui/print'
11
+ *
12
+ * let tree = h('dl', null, h('dt', null, 'size'), h('dd', null, h('b', null, 'big')))
13
+ * assertEquals(print(tree, 40), 'size: \x1b[1mbig\x1b[0m')
14
+ * ```
15
+ *
16
+ * @module
17
+ */ /* @ts-types="npm:@types/react@19.3.0" */ import { render } from "@yaks/react/draw";
18
+ import { install } from "@yaks/dom";
19
+ import { printout } from "./paint.js";
20
+ /** The text a terminal prints for `node`; `sheet` extends the widgets' `base`. */ export let print = (node, columns, sheet = {})=>{
21
+ let screen = install();
22
+ let root = screen.root;
23
+ try {
24
+ render(node, root);
25
+ return printout(screen.root, columns, sheet);
26
+ } finally{
27
+ render(null, root);
28
+ screen.free();
29
+ }
30
+ };
31
+ //# sourceMappingURL=print.js.map
package/print.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"print.js","sources":["./print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;CAgBC,GAED,uCAAuC,GACvC,SAAS,MAAM,gCAAqC;AACpD,SAAS,OAAO,yBAA8B;AAC9C,SAAS,QAAQ,qBAAoB;AAGrC,gFAAgF,GAChF,OAAO,IAAI,QAAQ,CACjB,MACA,SACA,QAAe,CAAC,CAAC;EAEjB,IAAI,SAAS;EACb,IAAI,OAAO,OAAO,IAAI;EACtB,IAAI;IACF,OAAO,MAAM;IACb,OAAO,SAAS,OAAO,IAAI,EAAE,SAAS;EACxC,SAAU;IACR,OAAO,MAAM;IACb,OAAO,IAAI;EACb;AACF,EAAC"}
package/print.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * A Preact tree painted once, for a command that prints and exits: mounted in
3
+ * the fake document, laid out and colored by the ANSI painter at `columns`
4
+ * wide, then unmounted, with no screen taken and nothing held. Its own entry
5
+ * (`@yaks/tui/print`), so a printout loads the painter without the widgets.
6
+ *
7
+ * ```ts
8
+ * import { assertEquals } from '@std/assert'
9
+ * import { createElement as h } from 'react'
10
+ * import { print } from '@yaks/tui/print'
11
+ *
12
+ * let tree = h('dl', null, h('dt', null, 'size'), h('dd', null, h('b', null, 'big')))
13
+ * assertEquals(print(tree, 40), 'size: \x1b[1mbig\x1b[0m')
14
+ * ```
15
+ *
16
+ * @module
17
+ */
18
+
19
+ /* @ts-types="npm:@types/react@19.3.0" */ import type { ReactNode } from 'npm:react@19.3.0'
20
+ import { render } from '@yaks/react/draw'
21
+ import { install } from '@yaks/dom'
22
+ import { printout } from './paint.js'
23
+ import type { Sheet } from 'jsr:@yaks/ui@0.2.36/sheet'
24
+
25
+ /** The text a terminal prints for `node`; `sheet` extends the widgets' `base`. */
26
+ export let print = (
27
+ node: ReactNode,
28
+ columns: number,
29
+ sheet: Sheet = {},
30
+ ): string => {
31
+ let screen = install()
32
+ let root = screen.root as unknown as Parameters<typeof render>[1]
33
+ try {
34
+ render(node, root)
35
+ return printout(screen.root, columns, sheet)
36
+ } finally {
37
+ render(null, root)
38
+ screen.free()
39
+ }
40
+ }
package/run.js ADDED
@@ -0,0 +1,220 @@
1
+ import * as system from "@yaks/process/system";
2
+ /**
3
+ * The entry point: take the terminal, mount the app, and give the terminal
4
+ * back. Raw mode and the alt screen go up, the fake document is installed, a
5
+ * dirty tree repaints on the next microtask (so a burst of keys costs one
6
+ * paint), SIGWINCH is a resize and a full repaint, and every exit — a clean
7
+ * quit, an interrupt, a throw, an uncaught error or rejection anywhere, or a
8
+ * system.exit — gives the terminal back exactly once.
9
+ *
10
+ * Ctrl-C is the process's interrupt, the same one a signal is
11
+ * (@yaks/process/wind): the terminal holds the process open while it winds
12
+ * down, so the first waits for what the mounted components are finishing and
13
+ * a second forces them, and the process ends once the terminal is given back.
14
+ *
15
+ * @module
16
+ */ import { resolvers } from "@yaks/fp";
17
+ /* @ts-types="npm:@types/react@19.3.0" */ import { createElement as h, useEffect } from "react";
18
+ import { draw } from "@yaks/react/draw";
19
+ import { listen, wind } from "@yaks/process/wind";
20
+ import { install, onPaint, place, touch } from "@yaks/dom";
21
+ import { ansiBackend } from "./paint.js";
22
+ import { clearMouse, routeMouse } from "./mouse.js";
23
+ import { feed } from "./input.js";
24
+ import { clear, measured, press, size } from "./screen.js";
25
+ import { setClipboard } from "./visual.js";
26
+ let stop = {
27
+ fn: ()=>{}
28
+ };
29
+ // What the mounted components are still finishing: an app that is one view
30
+ // among others holds the exit the same way.
31
+ let holds = new Set();
32
+ /** Hold the exit open while this component finishes: the first interrupt
33
+ * waits for `drain`, a second calls `force`. Let go when it unmounts. */ export let useHold = (drain, force)=>useEffect(()=>{
34
+ let hold = {
35
+ drain,
36
+ force
37
+ };
38
+ holds.add(hold);
39
+ return ()=>void holds.delete(hold);
40
+ }, [
41
+ drain,
42
+ force
43
+ ]);
44
+ let attempt = (fn)=>{
45
+ try {
46
+ fn();
47
+ } catch {}
48
+ };
49
+ let once = (fn)=>{
50
+ let done = false;
51
+ return ()=>{
52
+ if (done) return;
53
+ done = true;
54
+ fn();
55
+ };
56
+ };
57
+ /**
58
+ * Call `release` when the process ends without unwinding: an uncaught error,
59
+ * an unhandled rejection, or `unload` (system.exit, or the event loop running
60
+ * dry). An event a listener prevented does not end the process, so it
61
+ * releases nothing. Returns the function that stops listening.
62
+ */ export let fatal = (target, release)=>{
63
+ let on = (event)=>event.defaultPrevented || release();
64
+ let types = [
65
+ 'error',
66
+ 'unhandledrejection',
67
+ 'unload'
68
+ ];
69
+ for (let type of types)target.addEventListener(type, on);
70
+ return ()=>{
71
+ for (let type of types)target.removeEventListener(type, on);
72
+ };
73
+ };
74
+ /** Ask the running app to exit; the terminal is restored on the way out. */ export let quit = ()=>stop.fn();
75
+ /**
76
+ * Run an app until it quits. `backend` swaps the renderer (the ANSI painter by
77
+ * default); `sheet` extends the widgets' `base`, and as a function it is read
78
+ * at every paint; Ctrl-C interrupts the process ({@link useHold}).
79
+ */ export let run = async (App, opts = {})=>{
80
+ let backend = opts.backend ?? ansiBackend({
81
+ sheet: opts.sheet,
82
+ // What this terminal can do, unless the caller says: inside tmux, and
83
+ // whether it draws kitty graphics (HARNESS_GRAPHICS=kitty).
84
+ graphics: opts.graphics ?? (system.env.get('HARNESS_GRAPHICS') == 'kitty' ? 'kitty' : 'none'),
85
+ tmux: opts.tmux ?? !!system.env.get('TMUX')
86
+ });
87
+ let screen = opts.screen ?? install();
88
+ let host = screen.root;
89
+ let hide;
90
+ let cancelRead;
91
+ let done = false;
92
+ // The terminal's hold on the process: the input loop ends once the
93
+ // components have drained, or been forced, and the hold is answered once
94
+ // the terminal is given back. A drain that fails ends it too, and `run`
95
+ // throws what it threw.
96
+ let ending = resolvers();
97
+ let given = resolvers();
98
+ let failure;
99
+ let unhold = wind.hold({
100
+ drain: async ()=>{
101
+ try {
102
+ await Promise.all([
103
+ ...holds
104
+ ].map((d)=>d.drain()));
105
+ } catch (error) {
106
+ failure ??= error;
107
+ }
108
+ ending.resolve();
109
+ await given.promise;
110
+ },
111
+ force: ()=>{
112
+ for (let d of holds)d.force?.();
113
+ ending.resolve();
114
+ return given.promise;
115
+ }
116
+ });
117
+ let unlisten = listen();
118
+ let interrupt = ()=>wind.interrupt(130);
119
+ let escapeTimer;
120
+ stop.fn = ()=>{
121
+ done = true;
122
+ ending.resolve();
123
+ };
124
+ let resize = ()=>{
125
+ size.value = backend.size();
126
+ painted = [];
127
+ backend.reset();
128
+ touch();
129
+ };
130
+ let painted = [];
131
+ // The terminal given back, once: every mode the backend turned on, then
132
+ // cooked input. Each step runs even when one before it throws (a terminal
133
+ // gone after SIGHUP refuses the write).
134
+ let release = once(()=>{
135
+ attempt(()=>setClipboard());
136
+ attempt(()=>backend.stop());
137
+ attempt(()=>system.stdin.setRaw(false));
138
+ });
139
+ // A throw nobody caught (a render that crashes), a rejection nobody
140
+ // handled, or a system.exit from anywhere ends the process without reaching
141
+ // the finally below: the terminal is given back on the way out all the same.
142
+ let unguard = fatal(globalThis, release);
143
+ let bye = ()=>{
144
+ clearTimeout(escapeTimer);
145
+ painted = [];
146
+ attempt(()=>hide?.());
147
+ onPaint(()=>{});
148
+ clearMouse();
149
+ clear();
150
+ screen.free();
151
+ try {
152
+ system.removeSignalListener('SIGWINCH', resize);
153
+ } catch {}
154
+ release();
155
+ unguard();
156
+ };
157
+ try {
158
+ system.stdin.setRaw(true);
159
+ backend.start();
160
+ setClipboard(backend.copy ? (text)=>backend.copy(text) : undefined);
161
+ size.value = backend.size();
162
+ system.addSignalListener('SIGWINCH', resize);
163
+ onPaint(()=>{
164
+ let frame = backend.draw(screen.root);
165
+ painted = frame.lines ?? [];
166
+ measured(frame.metrics);
167
+ place(painted, frame.hidden);
168
+ });
169
+ hide = draw(/*#__PURE__*/ h(App, {}), host);
170
+ let keys = feed((body)=>backend.control?.(body));
171
+ let dispatch = (events)=>{
172
+ for (let key of events){
173
+ if (key.name != 'mouse' && key.ctrl && key.text == 'c') {
174
+ interrupt();
175
+ continue;
176
+ }
177
+ if (wind.draining) continue;
178
+ if (key.name == 'mouse') {
179
+ routeMouse(key, painted);
180
+ continue;
181
+ }
182
+ if (press(key)) continue;
183
+ if (key.ctrl && key.text == 'c') done = true;
184
+ }
185
+ };
186
+ let reader = system.stdin.readable.getReader();
187
+ cancelRead = ()=>reader.cancel().catch(()=>{});
188
+ let dec = new TextDecoder();
189
+ while(!done){
190
+ let n = await Promise.race([
191
+ reader.read().then(({ value, done })=>done ? null : value),
192
+ ending.promise.then(()=>null)
193
+ ]);
194
+ if (n == null) {
195
+ // Input that ended is an interrupt nobody typed.
196
+ if (!wind.draining) {
197
+ interrupt();
198
+ await ending.promise;
199
+ }
200
+ break;
201
+ }
202
+ clearTimeout(escapeTimer);
203
+ dispatch(keys(dec.decode(n, {
204
+ stream: true
205
+ })));
206
+ escapeTimer = setTimeout(()=>dispatch(keys.flush()), 25);
207
+ }
208
+ clearTimeout(escapeTimer);
209
+ } finally{
210
+ bye();
211
+ unlisten();
212
+ unhold();
213
+ // Cancel the pending read after restoring raw mode; it otherwise keeps
214
+ // the process alive after an asynchronous drain completes.
215
+ await cancelRead?.();
216
+ given.resolve();
217
+ }
218
+ if (failure) throw failure;
219
+ };
220
+ //# sourceMappingURL=run.js.map
package/run.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sources":["./run.ts"],"names":[],"mappings":"AAAA,YAAY,wCAA6C;AACzD;;;;;;;;;;;;;;CAcC,GAED,SAAS,SAAS,wBAA6B;AAC/C,uCAAuC,GAAG,SAA6B,iBAAiB,CAAC,EAAE,SAAS,gBAA0B;AAC9H,SAAS,IAAI,gCAAqC;AAClD,SAAoB,MAAM,EAAE,IAAI,kCAAuC;AACvE,SAAS,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,yBAA8B;AACrE,SAAS,WAAW,qBAAkC;AACtD,SAAS,UAAU,EAAE,UAAU,qBAAoB;AAEnD,SAAS,IAAI,qBAAoB;AACjC,SAAS,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE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ACA;MACF;MACA,aAAa;MACb,SAAS,KAAK,IAAI,MAAM,CAAC,GAAG;QAAE,QAAQ;MAAK;MAC3C,cAAc,WAAW,IAAM,SAAS,KAAK,KAAK,KAAK;IACzD;IACA,aAAa;EACf,SAAU;IACR;IACA;IACA;IACA,uEAAuE;IACvE,2DAA2D;IAC3D,MAAM;IACN,MAAM,OAAO;EACf;EACA,IAAI,SAAS,MAAM;AACrB,EAAC"}
package/run.ts ADDED
@@ -0,0 +1,237 @@
1
+ import * as system from '@yaks/process/system'
2
+ /**
3
+ * The entry point: take the terminal, mount the app, and give the terminal
4
+ * back. Raw mode and the alt screen go up, the fake document is installed, a
5
+ * dirty tree repaints on the next microtask (so a burst of keys costs one
6
+ * paint), SIGWINCH is a resize and a full repaint, and every exit — a clean
7
+ * quit, an interrupt, a throw, an uncaught error or rejection anywhere, or a
8
+ * system.exit — gives the terminal back exactly once.
9
+ *
10
+ * Ctrl-C is the process's interrupt, the same one a signal is
11
+ * (@yaks/process/wind): the terminal holds the process open while it winds
12
+ * down, so the first waits for what the mounted components are finishing and
13
+ * a second forces them, and the process ends once the terminal is given back.
14
+ *
15
+ * @module
16
+ */
17
+
18
+ import { resolvers } from '@yaks/fp'
19
+ /* @ts-types="npm:@types/react@19.3.0" */ import { type ComponentType, createElement as h, useEffect } from 'react'
20
+ import { draw } from '@yaks/react/draw'
21
+ import { type Hold, listen, wind } from '@yaks/process/wind'
22
+ import { install, onPaint, place, touch } from '@yaks/dom'
23
+ import { ansiBackend, type Backend } from './paint.js'
24
+ import { clearMouse, routeMouse } from './mouse.js'
25
+ import type { Line } from './paint.js'
26
+ import { feed } from './input.js'
27
+ import { clear, measured, press, size } from './screen.js'
28
+ import type { Sheet } from 'jsr:@yaks/ui@0.2.36/sheet'
29
+ import { setClipboard } from './visual.js'
30
+
31
+ let stop = { fn: () => {} }
32
+
33
+ // What the mounted components are still finishing: an app that is one view
34
+ // among others holds the exit the same way.
35
+ let holds = new Set<Hold>()
36
+
37
+ /** Hold the exit open while this component finishes: the first interrupt
38
+ * waits for `drain`, a second calls `force`. Let go when it unmounts. */
39
+ export let useHold = (
40
+ drain: () => Promise<unknown>,
41
+ force?: () => void,
42
+ ): void =>
43
+ useEffect(() => {
44
+ let hold = { drain, force }
45
+ holds.add(hold)
46
+ return () => void holds.delete(hold)
47
+ }, [drain, force])
48
+
49
+ let attempt = (fn: () => unknown) => {
50
+ try {
51
+ fn()
52
+ } catch { /* the rest still runs */ }
53
+ }
54
+
55
+ let once = (fn: () => void) => {
56
+ let done = false
57
+ return () => {
58
+ if (done) return
59
+ done = true
60
+ fn()
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Call `release` when the process ends without unwinding: an uncaught error,
66
+ * an unhandled rejection, or `unload` (system.exit, or the event loop running
67
+ * dry). An event a listener prevented does not end the process, so it
68
+ * releases nothing. Returns the function that stops listening.
69
+ */
70
+ export let fatal = (target: EventTarget, release: () => void): () => void => {
71
+ let on = (event: Event) => event.defaultPrevented || release()
72
+ let types = ['error', 'unhandledrejection', 'unload']
73
+ for (let type of types) target.addEventListener(type, on)
74
+ return () => {
75
+ for (let type of types) target.removeEventListener(type, on)
76
+ }
77
+ }
78
+
79
+ /** Ask the running app to exit; the terminal is restored on the way out. */
80
+ export let quit = (): void => stop.fn()
81
+
82
+ /**
83
+ * Run an app until it quits. `backend` swaps the renderer (the ANSI painter by
84
+ * default); `sheet` extends the widgets' `base`, and as a function it is read
85
+ * at every paint; Ctrl-C interrupts the process ({@link useHold}).
86
+ */
87
+ export let run = async (
88
+ App: ComponentType,
89
+ opts: {
90
+ screen?: ReturnType<typeof install>
91
+ backend?: Backend
92
+ sheet?: Sheet | (() => Sheet)
93
+ graphics?: 'kitty' | 'none'
94
+ tmux?: boolean
95
+ } = {},
96
+ ): Promise<void> => {
97
+ let backend = opts.backend ??
98
+ ansiBackend({
99
+ sheet: opts.sheet,
100
+ // What this terminal can do, unless the caller says: inside tmux, and
101
+ // whether it draws kitty graphics (HARNESS_GRAPHICS=kitty).
102
+ graphics: opts.graphics ??
103
+ (system.env.get('HARNESS_GRAPHICS') == 'kitty' ? 'kitty' : 'none'),
104
+ tmux: opts.tmux ?? !!system.env.get('TMUX'),
105
+ })
106
+ let screen = opts.screen ?? install()
107
+ let host = screen.root as unknown as Element
108
+ let hide: (() => void) | undefined
109
+ let cancelRead: (() => Promise<void>) | undefined
110
+ let done = false
111
+ // The terminal's hold on the process: the input loop ends once the
112
+ // components have drained, or been forced, and the hold is answered once
113
+ // the terminal is given back. A drain that fails ends it too, and `run`
114
+ // throws what it threw.
115
+ let ending = resolvers<void>()
116
+ let given = resolvers<void>()
117
+ let failure: unknown
118
+ let unhold = wind.hold({
119
+ drain: async () => {
120
+ try {
121
+ await Promise.all([...holds].map((d) => d.drain()))
122
+ } catch (error) {
123
+ failure ??= error
124
+ }
125
+ ending.resolve()
126
+ await given.promise
127
+ },
128
+ force: () => {
129
+ for (let d of holds) d.force?.()
130
+ ending.resolve()
131
+ return given.promise
132
+ },
133
+ })
134
+ let unlisten = listen()
135
+ let interrupt = () => wind.interrupt(130)
136
+ let escapeTimer: ReturnType<typeof setTimeout> | undefined
137
+ stop.fn = () => {
138
+ done = true
139
+ ending.resolve()
140
+ }
141
+
142
+ let resize = () => {
143
+ size.value = backend.size()
144
+ painted = []
145
+ backend.reset()
146
+ touch()
147
+ }
148
+ let painted: Line[] = []
149
+ // The terminal given back, once: every mode the backend turned on, then
150
+ // cooked input. Each step runs even when one before it throws (a terminal
151
+ // gone after SIGHUP refuses the write).
152
+ let release = once(() => {
153
+ attempt(() => setClipboard())
154
+ attempt(() => backend.stop())
155
+ attempt(() => system.stdin.setRaw(false))
156
+ })
157
+ // A throw nobody caught (a render that crashes), a rejection nobody
158
+ // handled, or a system.exit from anywhere ends the process without reaching
159
+ // the finally below: the terminal is given back on the way out all the same.
160
+ let unguard = fatal(globalThis, release)
161
+ let bye = () => {
162
+ clearTimeout(escapeTimer)
163
+ painted = []
164
+ attempt(() => hide?.())
165
+ onPaint(() => {})
166
+ clearMouse()
167
+ clear()
168
+ screen.free()
169
+ try {
170
+ system.removeSignalListener('SIGWINCH', resize)
171
+ } catch { /* never added */ }
172
+ release()
173
+ unguard()
174
+ }
175
+
176
+ try {
177
+ system.stdin.setRaw(true)
178
+ backend.start()
179
+ setClipboard(backend.copy ? (text) => backend.copy!(text) : undefined)
180
+ size.value = backend.size()
181
+ system.addSignalListener('SIGWINCH', resize)
182
+ onPaint(() => {
183
+ let frame = backend.draw(screen.root)
184
+ painted = frame.lines ?? []
185
+ measured(frame.metrics)
186
+ place(painted, frame.hidden)
187
+ })
188
+ hide = draw(h(App, {}), host)
189
+
190
+ let keys = feed((body) => backend.control?.(body))
191
+ let dispatch = (events: ReturnType<typeof keys>) => {
192
+ for (let key of events) {
193
+ if (key.name != 'mouse' && key.ctrl && key.text == 'c') {
194
+ interrupt()
195
+ continue
196
+ }
197
+ if (wind.draining) continue
198
+ if (key.name == 'mouse') {
199
+ routeMouse(key, painted)
200
+ continue
201
+ }
202
+ if (press(key)) continue
203
+ if (key.ctrl && key.text == 'c') done = true
204
+ }
205
+ }
206
+ let reader = system.stdin.readable.getReader()
207
+ cancelRead = () => reader.cancel().catch(() => {})
208
+ let dec = new TextDecoder()
209
+ while (!done) {
210
+ let n = await Promise.race([
211
+ reader.read().then(({ value, done }) => done ? null : value),
212
+ ending.promise.then(() => null),
213
+ ])
214
+ if (n == null) {
215
+ // Input that ended is an interrupt nobody typed.
216
+ if (!wind.draining) {
217
+ interrupt()
218
+ await ending.promise
219
+ }
220
+ break
221
+ }
222
+ clearTimeout(escapeTimer)
223
+ dispatch(keys(dec.decode(n, { stream: true })))
224
+ escapeTimer = setTimeout(() => dispatch(keys.flush()), 25)
225
+ }
226
+ clearTimeout(escapeTimer)
227
+ } finally {
228
+ bye()
229
+ unlisten()
230
+ unhold()
231
+ // Cancel the pending read after restoring raw mode; it otherwise keeps
232
+ // the process alive after an asynchronous drain completes.
233
+ await cancelRead?.()
234
+ given.resolve()
235
+ }
236
+ if (failure) throw failure
237
+ }
package/screen.js ADDED
@@ -0,0 +1,97 @@
1
+ import { interceptKey } from "./keymap.js";
2
+ /**
3
+ * What a widget knows about the screen it is on, and how a key reaches it.
4
+ * Three signals in one place: the terminal's size (a widget that collapses
5
+ * needs it), the measurements the last paint took (a scroll region learns its
6
+ * content height from the painter, since only the painter does layout), and
7
+ * the focus stack — `useKeys` puts a handler on it while mounted, and `press`
8
+ * offers a key to the topmost handler first, walking down until one takes it.
9
+ * Last mounted has focus; a handler that returns anything falsy passes.
10
+ *
11
+ * @module
12
+ */ import { visualKey } from "./visual.js";
13
+ import { computed, signal } from "@preact/signals-core";
14
+ /* @ts-types="npm:@types/react@19.3.0" */ import { useCallback, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from "react";
15
+ /** The terminal's size in cells, kept current by `run`. */ export let size = signal({
16
+ columns: 80,
17
+ rows: 24
18
+ });
19
+ /** Terminal focus reporting is independent of application/widget focus.
20
+ * Defaults to focused when the terminal does not send focus reports. */ export let terminalFocused = signal(true);
21
+ /** What the last paint measured, per element id. */ export let metrics = signal({});
22
+ let stack = [];
23
+ let targets = new Map();
24
+ /** Deliver a command to a named widget without changing keyboard focus. */ export let pressTo = (id, key)=>!!targets.get(id)?.(key);
25
+ /** Offer a key to the focus stack, topmost first. */ export let press = (key)=>{
26
+ if (key.name == 'focusin' || key.name == 'focusout') {
27
+ terminalFocused.value = key.name == 'focusin';
28
+ return true;
29
+ }
30
+ if (interceptKey(key)) return true;
31
+ if (visualKey(key)) return true;
32
+ return pressFocused(key);
33
+ };
34
+ /** Forward an already-routed key to the focused widget stack. */ export let pressFocused = (key)=>{
35
+ for(let i = stack.length - 1; i >= 0; i--)if (stack[i](key)) return true;
36
+ return false;
37
+ };
38
+ /** Take keys while this component is mounted; the newest mount has focus. */ export let useKeys = (fn, id)=>{
39
+ // The handler closes over this render's state, so the stack holds a stable
40
+ // shim and the shim reads the newest closure — registering the closure
41
+ // itself would reorder focus on every render.
42
+ let ref = useRef(fn);
43
+ ref.current = fn;
44
+ // A layout effect, not an effect: outside a browser Preact defers effects
45
+ // to a frame that may be 100ms away, and a key pressed before then would
46
+ // reach nobody.
47
+ useLayoutEffect(()=>{
48
+ let shim = (k)=>ref.current(k);
49
+ stack.push(shim);
50
+ return ()=>{
51
+ stack.splice(stack.indexOf(shim), 1);
52
+ };
53
+ }, []);
54
+ useLayoutEffect(()=>{
55
+ if (!id) return;
56
+ let shim = (k)=>ref.current(k);
57
+ targets.set(id, shim);
58
+ return ()=>{
59
+ if (targets.get(id) === shim) targets.delete(id);
60
+ };
61
+ }, [
62
+ id
63
+ ]);
64
+ };
65
+ let empty = {
66
+ total: 0,
67
+ height: 0,
68
+ width: 0
69
+ };
70
+ /** Read presentation state and repaint when it changes. */ export let useScreen = (state)=>{
71
+ let subscribe = useCallback((wake)=>state.subscribe(wake), [
72
+ state
73
+ ]);
74
+ return useSyncExternalStore(subscribe, ()=>state.peek());
75
+ };
76
+ export function useMetric(id, key) {
77
+ // Read through a signal of its own, so a component re-renders only when what
78
+ // it reads changed, and a fresh one when the id it measures changes.
79
+ let measure = useMemo(()=>computed(()=>{
80
+ let value = metrics.value[id] ?? empty;
81
+ return key == null ? value : value[key];
82
+ }), [
83
+ id,
84
+ key
85
+ ]);
86
+ return useScreen(measure);
87
+ }
88
+ /** Publish a paint's measurements; unchanged measurements re-render nothing. */ export let measured = (next)=>{
89
+ let now = metrics.value;
90
+ let same = Object.keys(next).length == Object.keys(now).length && Object.entries(next).every(([k, v])=>now[k]?.total == v.total && now[k]?.height == v.height && now[k]?.width == v.width && now[k]?.reveal == v.reveal);
91
+ if (!same) metrics.value = next;
92
+ };
93
+ /** Forget the focus stack — for a test that mounts more than one app. */ export let clear = ()=>{
94
+ stack.length = 0;
95
+ terminalFocused.value = true;
96
+ };
97
+ //# sourceMappingURL=screen.js.map
package/screen.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screen.js","sources":["./screen.ts"],"names":[],"mappings":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