@promptctl/rich-js 0.18.0 → 0.18.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 (221) hide show
  1. package/dist/core/anchor.d.ts +45 -0
  2. package/dist/core/anchor.js +39 -0
  3. package/dist/core/ansi.d.ts +65 -0
  4. package/dist/core/ansi.js +231 -0
  5. package/dist/core/box.d.ts +143 -0
  6. package/dist/core/box.js +379 -0
  7. package/dist/core/cells.d.ts +159 -0
  8. package/dist/core/cells.js +287 -0
  9. package/dist/core/color.d.ts +246 -0
  10. package/dist/core/color.js +1038 -0
  11. package/dist/core/console.d.ts +165 -0
  12. package/dist/core/console.js +527 -0
  13. package/dist/core/emoji.d.ts +24 -0
  14. package/dist/core/emoji.js +391 -0
  15. package/dist/core/export-html.d.ts +59 -0
  16. package/dist/core/export-html.js +200 -0
  17. package/dist/core/export-lines.d.ts +121 -0
  18. package/dist/core/export-lines.js +141 -0
  19. package/dist/core/highlighter.d.ts +33 -0
  20. package/dist/core/highlighter.js +124 -0
  21. package/dist/core/json.d.ts +27 -0
  22. package/dist/core/json.js +53 -0
  23. package/dist/core/markup.d.ts +119 -0
  24. package/dist/core/markup.js +731 -0
  25. package/dist/core/measure.d.ts +27 -0
  26. package/dist/core/measure.js +62 -0
  27. package/dist/core/oklch.d.ts +161 -0
  28. package/dist/core/oklch.js +312 -0
  29. package/dist/core/osc8.d.ts +68 -0
  30. package/dist/core/osc8.js +90 -0
  31. package/dist/core/place.d.ts +30 -0
  32. package/dist/core/place.js +51 -0
  33. package/dist/core/pretty.d.ts +144 -0
  34. package/dist/core/pretty.js +476 -0
  35. package/dist/core/protocol.d.ts +267 -0
  36. package/dist/core/protocol.js +163 -0
  37. package/dist/core/render.d.ts +84 -0
  38. package/dist/core/render.js +145 -0
  39. package/dist/core/segment.d.ts +161 -0
  40. package/dist/core/segment.js +492 -0
  41. package/dist/core/spinnerData.d.ts +12 -0
  42. package/dist/core/spinnerData.js +117 -0
  43. package/dist/core/strip.d.ts +141 -0
  44. package/dist/core/strip.js +305 -0
  45. package/dist/core/style.d.ts +169 -0
  46. package/dist/core/style.js +695 -0
  47. package/dist/core/subscription.d.ts +12 -0
  48. package/dist/core/subscription.js +12 -0
  49. package/dist/core/text.d.ts +256 -0
  50. package/dist/core/text.js +976 -0
  51. package/dist/core/wrap.d.ts +41 -0
  52. package/dist/core/wrap.js +127 -0
  53. package/dist/host/app.d.ts +121 -0
  54. package/dist/host/app.js +255 -0
  55. package/dist/host/host-environment.d.ts +26 -0
  56. package/dist/host/host-environment.js +44 -0
  57. package/dist/host/index.d.ts +5 -0
  58. package/dist/host/index.js +3 -0
  59. package/dist/host/terminal-host.d.ts +179 -0
  60. package/dist/host/terminal-host.js +186 -0
  61. package/dist/index.d.ts +91 -0
  62. package/dist/index.js +107 -0
  63. package/dist/node/prompt.d.ts +21 -0
  64. package/dist/node/prompt.js +30 -0
  65. package/dist/node/save.d.ts +17 -0
  66. package/dist/node/save.js +21 -0
  67. package/dist/node/terminal-host.d.ts +113 -0
  68. package/dist/node/terminal-host.js +227 -0
  69. package/dist/node/traceback.d.ts +37 -0
  70. package/dist/node/traceback.js +134 -0
  71. package/dist/renderables/align.d.ts +16 -0
  72. package/dist/renderables/align.js +33 -0
  73. package/dist/renderables/columns.d.ts +61 -0
  74. package/dist/renderables/columns.js +152 -0
  75. package/dist/renderables/constrain.d.ts +15 -0
  76. package/dist/renderables/constrain.js +37 -0
  77. package/dist/renderables/embed.d.ts +50 -0
  78. package/dist/renderables/embed.js +71 -0
  79. package/dist/renderables/flexStrip.d.ts +41 -0
  80. package/dist/renderables/flexStrip.js +200 -0
  81. package/dist/renderables/group.d.ts +11 -0
  82. package/dist/renderables/group.js +17 -0
  83. package/dist/renderables/layout.d.ts +92 -0
  84. package/dist/renderables/layout.js +312 -0
  85. package/dist/renderables/live.d.ts +50 -0
  86. package/dist/renderables/live.js +175 -0
  87. package/dist/renderables/markdown.d.ts +24 -0
  88. package/dist/renderables/markdown.js +184 -0
  89. package/dist/renderables/padding.d.ts +38 -0
  90. package/dist/renderables/padding.js +141 -0
  91. package/dist/renderables/panel.d.ts +116 -0
  92. package/dist/renderables/panel.js +307 -0
  93. package/dist/renderables/progress.d.ts +90 -0
  94. package/dist/renderables/progress.js +238 -0
  95. package/dist/renderables/progressBar.d.ts +31 -0
  96. package/dist/renderables/progressBar.js +53 -0
  97. package/dist/renderables/prompt.d.ts +49 -0
  98. package/dist/renderables/prompt.js +125 -0
  99. package/dist/renderables/rule.d.ts +25 -0
  100. package/dist/renderables/rule.js +90 -0
  101. package/dist/renderables/spinner.d.ts +31 -0
  102. package/dist/renderables/spinner.js +70 -0
  103. package/dist/renderables/status.d.ts +23 -0
  104. package/dist/renderables/status.js +60 -0
  105. package/dist/renderables/syntax.d.ts +35 -0
  106. package/dist/renderables/syntax.js +115 -0
  107. package/dist/renderables/table.d.ts +194 -0
  108. package/dist/renderables/table.js +795 -0
  109. package/dist/renderables/traceback.d.ts +31 -0
  110. package/dist/renderables/traceback.js +108 -0
  111. package/dist/renderables/tree.d.ts +68 -0
  112. package/dist/renderables/tree.js +150 -0
  113. package/dist/renderables/viewport.d.ts +114 -0
  114. package/dist/renderables/viewport.js +198 -0
  115. package/dist/template-bindings/color-funcs.d.ts +87 -0
  116. package/dist/template-bindings/color-funcs.js +217 -0
  117. package/dist/template-bindings/helpers.d.ts +24 -0
  118. package/dist/template-bindings/helpers.js +48 -0
  119. package/dist/template-bindings/index.d.ts +107 -0
  120. package/dist/template-bindings/index.js +146 -0
  121. package/dist/template-bindings/palette-funcs.d.ts +94 -0
  122. package/dist/template-bindings/palette-funcs.js +141 -0
  123. package/dist/template-bindings/style-funcs.d.ts +28 -0
  124. package/dist/template-bindings/style-funcs.js +155 -0
  125. package/dist/themes/buildPalette.d.ts +36 -0
  126. package/dist/themes/buildPalette.js +56 -0
  127. package/dist/themes/colorMath.d.ts +82 -0
  128. package/dist/themes/colorMath.js +254 -0
  129. package/dist/themes/colorRef.d.ts +51 -0
  130. package/dist/themes/colorRef.js +96 -0
  131. package/dist/themes/data/ansi-tables.d.ts +14 -0
  132. package/dist/themes/data/ansi-tables.js +49 -0
  133. package/dist/themes/data/atom-one-dark.d.ts +3 -0
  134. package/dist/themes/data/atom-one-dark.js +177 -0
  135. package/dist/themes/data/atom-one-light.d.ts +3 -0
  136. package/dist/themes/data/atom-one-light.js +177 -0
  137. package/dist/themes/data/catppuccin-frappe.d.ts +3 -0
  138. package/dist/themes/data/catppuccin-frappe.js +177 -0
  139. package/dist/themes/data/catppuccin-latte.d.ts +3 -0
  140. package/dist/themes/data/catppuccin-latte.js +177 -0
  141. package/dist/themes/data/catppuccin-macchiato.d.ts +3 -0
  142. package/dist/themes/data/catppuccin-macchiato.js +177 -0
  143. package/dist/themes/data/catppuccin-mocha.d.ts +3 -0
  144. package/dist/themes/data/catppuccin-mocha.js +177 -0
  145. package/dist/themes/data/cyberpunk.d.ts +17 -0
  146. package/dist/themes/data/cyberpunk.js +193 -0
  147. package/dist/themes/data/default.d.ts +3 -0
  148. package/dist/themes/data/default.js +160 -0
  149. package/dist/themes/data/dracula.d.ts +3 -0
  150. package/dist/themes/data/dracula.js +177 -0
  151. package/dist/themes/data/flexoki.d.ts +3 -0
  152. package/dist/themes/data/flexoki.js +177 -0
  153. package/dist/themes/data/gruvbox.d.ts +3 -0
  154. package/dist/themes/data/gruvbox.js +177 -0
  155. package/dist/themes/data/index.d.ts +35 -0
  156. package/dist/themes/data/index.js +64 -0
  157. package/dist/themes/data/monokai.d.ts +3 -0
  158. package/dist/themes/data/monokai.js +177 -0
  159. package/dist/themes/data/nord.d.ts +3 -0
  160. package/dist/themes/data/nord.js +177 -0
  161. package/dist/themes/data/rose-pine-dawn.d.ts +3 -0
  162. package/dist/themes/data/rose-pine-dawn.js +177 -0
  163. package/dist/themes/data/rose-pine-moon.d.ts +3 -0
  164. package/dist/themes/data/rose-pine-moon.js +177 -0
  165. package/dist/themes/data/rose-pine.d.ts +3 -0
  166. package/dist/themes/data/rose-pine.js +177 -0
  167. package/dist/themes/data/solarized-dark.d.ts +3 -0
  168. package/dist/themes/data/solarized-dark.js +177 -0
  169. package/dist/themes/data/solarized-light.d.ts +3 -0
  170. package/dist/themes/data/solarized-light.js +177 -0
  171. package/dist/themes/data/svg-export.d.ts +3 -0
  172. package/dist/themes/data/svg-export.js +177 -0
  173. package/dist/themes/data/textual-ansi.d.ts +3 -0
  174. package/dist/themes/data/textual-ansi.js +160 -0
  175. package/dist/themes/data/textual-dark.d.ts +3 -0
  176. package/dist/themes/data/textual-dark.js +160 -0
  177. package/dist/themes/data/textual-light.d.ts +3 -0
  178. package/dist/themes/data/textual-light.js +160 -0
  179. package/dist/themes/data/tokyo-night.d.ts +3 -0
  180. package/dist/themes/data/tokyo-night.js +177 -0
  181. package/dist/themes/data/types.d.ts +31 -0
  182. package/dist/themes/data/types.js +10 -0
  183. package/dist/themes/palette.d.ts +21 -0
  184. package/dist/themes/palette.js +28 -0
  185. package/dist/themes/ramp.d.ts +83 -0
  186. package/dist/themes/ramp.js +122 -0
  187. package/dist/themes/registry.d.ts +44 -0
  188. package/dist/themes/registry.js +94 -0
  189. package/dist/themes/terminalThemes.d.ts +49 -0
  190. package/dist/themes/terminalThemes.js +63 -0
  191. package/dist/themes/transpose.d.ts +87 -0
  192. package/dist/themes/transpose.js +138 -0
  193. package/dist/widgets/button.d.ts +49 -0
  194. package/dist/widgets/button.js +208 -0
  195. package/dist/widgets/checkbox.d.ts +41 -0
  196. package/dist/widgets/checkbox.js +157 -0
  197. package/dist/widgets/dropdown.d.ts +67 -0
  198. package/dist/widgets/dropdown.js +450 -0
  199. package/dist/widgets/event-router.d.ts +71 -0
  200. package/dist/widgets/event-router.js +629 -0
  201. package/dist/widgets/focus-manager.d.ts +45 -0
  202. package/dist/widgets/focus-manager.js +191 -0
  203. package/dist/widgets/hit.d.ts +64 -0
  204. package/dist/widgets/hit.js +113 -0
  205. package/dist/widgets/index.d.ts +20 -0
  206. package/dist/widgets/index.js +14 -0
  207. package/dist/widgets/slider.d.ts +57 -0
  208. package/dist/widgets/slider.js +270 -0
  209. package/dist/widgets/static-item.d.ts +34 -0
  210. package/dist/widgets/static-item.js +54 -0
  211. package/dist/widgets/text-input.d.ts +274 -0
  212. package/dist/widgets/text-input.js +1165 -0
  213. package/dist/widgets/toggle.d.ts +44 -0
  214. package/dist/widgets/toggle.js +180 -0
  215. package/dist/widgets/types.d.ts +87 -0
  216. package/dist/widgets/types.js +30 -0
  217. package/dist/widgets/widget-app.d.ts +63 -0
  218. package/dist/widgets/widget-app.js +199 -0
  219. package/dist/widgets/widget-base.d.ts +40 -0
  220. package/dist/widgets/widget-base.js +165 -0
  221. package/package.json +6 -2
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Word wrapping: the offsets one logical line is cut at so its pieces fit a
3
+ * cell budget.
4
+ *
5
+ * This is deliberately not in `cells.ts` next door. That module answers
6
+ * geometry — how wide is this, where does cell column N fall — and knows
7
+ * nothing about language. This one answers where a line may *break*, which is
8
+ * a fact about words, and the only thing it borrows from geometry is how to
9
+ * measure one.
10
+ *
11
+ * It returns offsets rather than pieces because the caller holds styled
12
+ * `Segment[]`, not a string: cutting the text here would drop every span
13
+ * attached to it. Offsets are the one representation both sides can act on —
14
+ * `Segment.divide` cuts the styled line at exactly the places this function
15
+ * found in the plain one.
16
+ *
17
+ * Wrapping is the *first* step, and overflow is the last resort applied to a
18
+ * line still too wide once wrapping is done. That order is the whole reason a
19
+ * long sentence in a table cell grows the row while an unbreakable word in the
20
+ * same cell still ellipsizes.
21
+ */
22
+ import { type CellCol } from "./cells.js";
23
+ /**
24
+ * The cell offsets `text` should be cut at to wrap it into lines of at most
25
+ * `width` cells, for `Segment.divide` to apply to the styled line.
26
+ *
27
+ * `fold` decides what happens to a word that fits on no line at all: folded,
28
+ * it is chopped across as many lines as it needs; unfolded, it is left whole
29
+ * on its own line for the caller's overflow method to cut. Only the `fold`
30
+ * overflow method folds — `crop` and `ellipsis` want the word intact so they
31
+ * can truncate it, which is what makes an unbreakable word ellipsize while the
32
+ * sentence around it merely wraps.
33
+ *
34
+ * Requires `width >= 1`. A zero-cell canvas gets no cuts, because "no cut
35
+ * fits" and "no cell fits" are different facts and only one of them is a list
36
+ * of offsets — the caller answers the second one by cropping the single
37
+ * uncut piece to nothing, which is what every overflow method does there.
38
+ */
39
+ export declare function divideLine(text: string, width: CellCol, options: {
40
+ fold: boolean;
41
+ }): CellCol[];
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Word wrapping: the offsets one logical line is cut at so its pieces fit a
3
+ * cell budget.
4
+ *
5
+ * This is deliberately not in `cells.ts` next door. That module answers
6
+ * geometry — how wide is this, where does cell column N fall — and knows
7
+ * nothing about language. This one answers where a line may *break*, which is
8
+ * a fact about words, and the only thing it borrows from geometry is how to
9
+ * measure one.
10
+ *
11
+ * It returns offsets rather than pieces because the caller holds styled
12
+ * `Segment[]`, not a string: cutting the text here would drop every span
13
+ * attached to it. Offsets are the one representation both sides can act on —
14
+ * `Segment.divide` cuts the styled line at exactly the places this function
15
+ * found in the plain one.
16
+ *
17
+ * Wrapping is the *first* step, and overflow is the last resort applied to a
18
+ * line still too wide once wrapping is done. That order is the whole reason a
19
+ * long sentence in a table cell grows the row while an unbreakable word in the
20
+ * same cell still ellipsizes.
21
+ */
22
+ import { cellLen, chopCells, asCellCol } from "./cells.js";
23
+ /**
24
+ * Each word of `text` in order, where a "word" carries its own trailing
25
+ * whitespace — the run of spaces that follows it belongs to it, because that
26
+ * is the whitespace a break at the *next* word leaves hanging past the edge.
27
+ *
28
+ * The matches tile the text: each begins exactly where the last ended, so a
29
+ * caller can track absolute offsets by accumulating widths alone. Text with no
30
+ * non-whitespace character yields nothing, which is the honest answer — there
31
+ * is nowhere to break.
32
+ */
33
+ function* words(text) {
34
+ // Constructed per call rather than hoisted: a sticky regex carries its
35
+ // `lastIndex` as mutable state, and a shared one would corrupt any two
36
+ // interleaved walks. [LAW:no-shared-mutable-globals]
37
+ const re = /\s*\S+\s*/y;
38
+ for (let match = re.exec(text); match !== null; match = re.exec(text)) {
39
+ yield match[0];
40
+ }
41
+ }
42
+ /**
43
+ * A word chopped into pieces of at most `width` cells, as the reference chops
44
+ * it.
45
+ *
46
+ * `chopCells` next door and Rich's `chop_cells` disagree in exactly one place.
47
+ * Rich opens a new line for any glyph that does not fit and emits whatever line
48
+ * it was already on, so a word beginning with a glyph wider than the entire
49
+ * canvas folds with an empty piece in front of it — and that piece reaches the
50
+ * output as a blank line. `chopCells` force-takes the glyph instead and never
51
+ * returns an empty piece.
52
+ *
53
+ * Restoring the blank is what keeps `test/core/text-wrap.golden.txt`
54
+ * regenerable from the reference. A fixture is only an oracle while the command
55
+ * in its header reproduces it byte for byte; smoothing away one byte the
56
+ * reference emits costs that, everywhere, to tidy a blank line reachable only
57
+ * by folding a two-cell glyph onto a one-cell canvas.
58
+ */
59
+ function foldWord(word, width) {
60
+ const pieces = chopCells(word, width);
61
+ // `chopCells` overshoots the budget only when it force-takes one glyph, so an
62
+ // over-wide first piece is exactly the case Rich opens a blank line for.
63
+ return cellLen(pieces[0]) > width ? ["", ...pieces] : pieces;
64
+ }
65
+ /**
66
+ * The cell offsets `text` should be cut at to wrap it into lines of at most
67
+ * `width` cells, for `Segment.divide` to apply to the styled line.
68
+ *
69
+ * `fold` decides what happens to a word that fits on no line at all: folded,
70
+ * it is chopped across as many lines as it needs; unfolded, it is left whole
71
+ * on its own line for the caller's overflow method to cut. Only the `fold`
72
+ * overflow method folds — `crop` and `ellipsis` want the word intact so they
73
+ * can truncate it, which is what makes an unbreakable word ellipsize while the
74
+ * sentence around it merely wraps.
75
+ *
76
+ * Requires `width >= 1`. A zero-cell canvas gets no cuts, because "no cut
77
+ * fits" and "no cell fits" are different facts and only one of them is a list
78
+ * of offsets — the caller answers the second one by cropping the single
79
+ * uncut piece to nothing, which is what every overflow method does there.
80
+ */
81
+ export function divideLine(text, width, options) {
82
+ if (width <= 0)
83
+ return [];
84
+ const cuts = [];
85
+ // A cut at the start of the text is not a cut: it would open the line with
86
+ // an empty piece. [LAW:single-enforcer] for that rule, so neither arm below
87
+ // has to restate it.
88
+ const cutAt = (cell) => {
89
+ if (cell > 0)
90
+ cuts.push(asCellCol(cell));
91
+ };
92
+ let used = 0; // cells already committed to the line being filled
93
+ let wordStart = 0; // absolute cell offset where the current word begins
94
+ for (const word of words(text)) {
95
+ // Measured without its trailing whitespace: a word is allowed to end the
96
+ // line with its spaces hanging past the edge, and the caller crops them.
97
+ const wordWidth = cellLen(word.trimEnd());
98
+ if (width - used >= wordWidth) {
99
+ used += cellLen(word);
100
+ }
101
+ else if (options.fold && wordWidth > width) {
102
+ // No line, however empty, can hold this word whole, and folding is
103
+ // allowed — so it is chopped across as many lines as it needs. Unfolded,
104
+ // it takes the arm below and is left whole for the overflow method.
105
+ const pieces = foldWord(word, width);
106
+ let pieceStart = wordStart;
107
+ for (let index = 0; index < pieces.length; index += 1) {
108
+ cutAt(pieceStart);
109
+ const piece = pieces[index];
110
+ // The last piece is what the *next* word finds already on the line;
111
+ // the rest are whole lines of their own.
112
+ if (index === pieces.length - 1)
113
+ used = cellLen(piece);
114
+ else
115
+ pieceStart += cellLen(piece);
116
+ }
117
+ }
118
+ else {
119
+ // It does not fit here. Either it fits on a line of its own, or nothing
120
+ // can hold it and the caller's overflow method will cut it there.
121
+ cutAt(wordStart);
122
+ used = cellLen(word);
123
+ }
124
+ wordStart += cellLen(word);
125
+ }
126
+ return cuts;
127
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * App — the runtime a terminal application runs in: it takes the terminal,
3
+ * paints one renderable on it every frame, and hands the terminal back on
4
+ * every path out.
5
+ *
6
+ * [LAW:single-enforcer] Every change this runtime makes to the terminal —
7
+ * the alternate screen, pointer reporting, the hidden cursor, raw mode — is
8
+ * made by `enter` and
9
+ * undone by `leave`, and nothing else touches them. Stopping, suspending, an
10
+ * error in a frame and the program ending by a signal or a crash all hand the
11
+ * terminal back through `leave`, so there is one list of what to undo and no
12
+ * exit path can hold a shorter one.
13
+ *
14
+ * [LAW:one-source-of-truth] The frame on screen is one value: the rows last
15
+ * painted, carrying on every cell where its owner drew it (`core/anchor`).
16
+ * Nothing about it is cached beside it, so a resize invalidates nothing — it
17
+ * is input to the next frame, which replaces the rows and their anchors at
18
+ * once. An event arriving before that repaint lands on the frame on screen,
19
+ * which is the one the user pointed at.
20
+ *
21
+ * [LAW:locality-or-seam] The terminal's bytes are identical under every host
22
+ * and live here: entering and leaving the alternate screen, the cursor, the
23
+ * frame's encoding. What differs per host — whether the program can end
24
+ * under us, how it is suspended — is the `TerminalHost`'s, so the same app
25
+ * runs in node and in a browser with no path of its own for either.
26
+ */
27
+ import { Segment } from "../core/segment.js";
28
+ import { type Renderable } from "../core/protocol.js";
29
+ import type { Unsubscribe } from "../core/subscription.js";
30
+ import type { TerminalHost } from "./terminal-host.js";
31
+ /**
32
+ * Where the frame is painted. `alternate` is the whole terminal, in the
33
+ * alternate screen buffer, so the rows the program printed before it are
34
+ * there again when it stops; the terminal reports the pointer on it. `inline`
35
+ * starts at the cursor's line, as tall as the frame, and stays on the
36
+ * terminal when the app stops. It gets no pointer events: the terminal
37
+ * reports a pointer by its row on the screen, and the app does not know
38
+ * which row of the screen its frame starts on.
39
+ */
40
+ export type Surface = "alternate" | "inline";
41
+ /**
42
+ * Where an app is in its life. `idle` has not run; `running` holds the
43
+ * terminal and paints; `suspended` has handed it back until the host resumes
44
+ * the program; `stopped` has handed it back for good.
45
+ */
46
+ export type AppPhase = "idle" | "running" | "suspended" | "stopped";
47
+ export interface AppOptions {
48
+ /** The terminal the app runs on. The app starts and stops it. */
49
+ readonly host: TerminalHost;
50
+ readonly surface: Surface;
51
+ /**
52
+ * The app's root renderable, asked for once per frame, so a view of the
53
+ * app's state is drawn from the state as it is at that frame.
54
+ */
55
+ readonly view: () => Renderable;
56
+ /**
57
+ * The terminal can draw only ASCII, so every frame draws its boxes, guides
58
+ * and widget marks with ASCII characters. Default false.
59
+ */
60
+ readonly asciiOnly?: boolean;
61
+ }
62
+ export declare class App {
63
+ private readonly host;
64
+ private readonly surface;
65
+ private readonly view;
66
+ private readonly console;
67
+ private _phase;
68
+ private _frame;
69
+ private rows;
70
+ private refreshQueued;
71
+ private subscriptions;
72
+ private readonly paintHandlers;
73
+ private settle;
74
+ constructor(options: AppOptions);
75
+ get phase(): AppPhase;
76
+ /** The rows on screen now, as painted: what a pointer event lands on. */
77
+ get frame(): readonly (readonly Segment[])[];
78
+ /**
79
+ * Take the terminal, paint the first frame, and resolve when the app stops
80
+ * — or reject with the error a frame threw or `fail` was given, the terminal
81
+ * handed back first.
82
+ * When the program ends under the app, `run` does not settle: nothing after
83
+ * it runs, as nothing after it would have without the app. An app runs once.
84
+ */
85
+ run(): Promise<void>;
86
+ /**
87
+ * Paint a new frame from the view, once, in a later task: every change made
88
+ * before then lands in the one frame.
89
+ *
90
+ * [LAW:no-ambient-temporal-coupling] A task, not a microtask. Input is read
91
+ * between tasks, so a view whose every frame asks for another still hears
92
+ * its keys — Ctrl+C included — where a microtask chain would starve them
93
+ * for as long as it ran.
94
+ */
95
+ refresh(): void;
96
+ /**
97
+ * Hand the terminal to whatever launched the program, and take it back and
98
+ * repaint when that resumes it. What sends the app here is the app's own —
99
+ * in raw mode Ctrl+Z arrives as a key.
100
+ */
101
+ suspend(): Promise<void>;
102
+ /**
103
+ * Hear each frame once it is on screen — what `frame` now returns. A
104
+ * handler that throws fails the app as a frame that throws does.
105
+ */
106
+ onPaint(handler: (frame: readonly (readonly Segment[])[]) => void): Unsubscribe;
107
+ /** Hand the terminal back for good; `run` resolves. */
108
+ stop(): void;
109
+ /**
110
+ * Hand the terminal back for good; `run` rejects with `error`. For an error
111
+ * thrown where the app's own code runs outside a frame — a key handler, a
112
+ * timer — which would otherwise reach neither `run`'s caller nor the
113
+ * terminal's hand-back.
114
+ */
115
+ fail(error: unknown): void;
116
+ private enter;
117
+ private leave;
118
+ private end;
119
+ private paint;
120
+ private draw;
121
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * App — the runtime a terminal application runs in: it takes the terminal,
3
+ * paints one renderable on it every frame, and hands the terminal back on
4
+ * every path out.
5
+ *
6
+ * [LAW:single-enforcer] Every change this runtime makes to the terminal —
7
+ * the alternate screen, pointer reporting, the hidden cursor, raw mode — is
8
+ * made by `enter` and
9
+ * undone by `leave`, and nothing else touches them. Stopping, suspending, an
10
+ * error in a frame and the program ending by a signal or a crash all hand the
11
+ * terminal back through `leave`, so there is one list of what to undo and no
12
+ * exit path can hold a shorter one.
13
+ *
14
+ * [LAW:one-source-of-truth] The frame on screen is one value: the rows last
15
+ * painted, carrying on every cell where its owner drew it (`core/anchor`).
16
+ * Nothing about it is cached beside it, so a resize invalidates nothing — it
17
+ * is input to the next frame, which replaces the rows and their anchors at
18
+ * once. An event arriving before that repaint lands on the frame on screen,
19
+ * which is the one the user pointed at.
20
+ *
21
+ * [LAW:locality-or-seam] The terminal's bytes are identical under every host
22
+ * and live here: entering and leaving the alternate screen, the cursor, the
23
+ * frame's encoding. What differs per host — whether the program can end
24
+ * under us, how it is suspended — is the `TerminalHost`'s, so the same app
25
+ * runs in node and in a browser with no path of its own for either.
26
+ */
27
+ import { Console } from "../core/console.js";
28
+ import { Segment } from "../core/segment.js";
29
+ import { segmentsToString } from "../core/render.js";
30
+ import { fitHeight } from "../core/protocol.js";
31
+ import { hostEnvironment } from "./host-environment.js";
32
+ // Button presses, motion and the wheel, in the SGR encoding: coordinates as
33
+ // decimal numbers, so a terminal wider than 223 columns still reports them.
34
+ const POINTER_ON = "\x1b[?1006h\x1b[?1000h\x1b[?1003h";
35
+ const POINTER_OFF = "\x1b[?1003l\x1b[?1000l\x1b[?1006l";
36
+ const SURFACES = {
37
+ alternate: {
38
+ exact: true,
39
+ enter: "\x1b[?1049h" + POINTER_ON,
40
+ leave: () => POINTER_OFF + "\x1b[?1049l",
41
+ home: () => "\x1b[H",
42
+ // The frame is every row of the screen, so there is nothing left under it
43
+ // — and after the terminal shrinks, painting the old count would scroll.
44
+ painted: (frameRows) => frameRows,
45
+ },
46
+ inline: {
47
+ exact: false,
48
+ enter: "",
49
+ // Below the frame, where the program's next line belongs.
50
+ leave: (rows) => (rows > 0 ? "\n" : ""),
51
+ // After N rows written with N-1 newlines between them, the cursor is on
52
+ // the last. `ESC[0A` still moves a row on some terminals, so a one-row
53
+ // frame is returned to with the carriage return alone.
54
+ home: (rows) => (rows > 1 ? `\x1b[${rows - 1}A\r` : "\r"),
55
+ // A shorter frame blanks the rows the last one left below it.
56
+ painted: (frameRows, lastRows) => Math.max(frameRows, lastRows),
57
+ },
58
+ };
59
+ const HIDE_CURSOR = "\x1b[?25l";
60
+ const SHOW_CURSOR = "\x1b[?25h";
61
+ const RESET_STYLE = "\x1b[0m";
62
+ const ERASE_LINE = "\x1b[2K";
63
+ export class App {
64
+ host;
65
+ surface;
66
+ view;
67
+ // [LAW:one-source-of-truth] The host is the console's whole environment:
68
+ // its size, its colours, where bytes go. Every frame renders with this
69
+ // console's options and is encoded for its destination.
70
+ console;
71
+ _phase = "idle";
72
+ _frame = [];
73
+ // The last frame's own rows on the terminal — what `home` rewinds.
74
+ rows = 0;
75
+ refreshQueued = false;
76
+ subscriptions = [];
77
+ paintHandlers = new Set();
78
+ settle = () => { };
79
+ constructor(options) {
80
+ this.host = options.host;
81
+ this.surface = SURFACES[options.surface];
82
+ this.view = options.view;
83
+ this.console = new Console({ environment: hostEnvironment(options.host), asciiOnly: options.asciiOnly });
84
+ }
85
+ get phase() {
86
+ return this._phase;
87
+ }
88
+ /** The rows on screen now, as painted: what a pointer event lands on. */
89
+ get frame() {
90
+ return this._frame;
91
+ }
92
+ /**
93
+ * Take the terminal, paint the first frame, and resolve when the app stops
94
+ * — or reject with the error a frame threw or `fail` was given, the terminal
95
+ * handed back first.
96
+ * When the program ends under the app, `run` does not settle: nothing after
97
+ * it runs, as nothing after it would have without the app. An app runs once.
98
+ */
99
+ run() {
100
+ if (this._phase !== "idle") {
101
+ return Promise.reject(new Error(`App.run: an app runs once, and this one is ${this._phase}`));
102
+ }
103
+ return new Promise((resolve, reject) => {
104
+ this.settle = (outcome) => {
105
+ switch (outcome.kind) {
106
+ case "stopped":
107
+ return resolve();
108
+ case "failed":
109
+ return reject(outcome.error);
110
+ // The rest of a crash — its report, then its exit — is still
111
+ // running, and code resumed after `run` would run inside it.
112
+ case "ended":
113
+ return;
114
+ }
115
+ };
116
+ this._phase = "running";
117
+ this.host.start();
118
+ this.subscriptions = [
119
+ this.host.onResize(() => this.refresh()),
120
+ // The program is ending under the app — by a signal, a crash, or an
121
+ // exit the app's own code never saw. Ending hands the terminal back,
122
+ // and the program then ends as it was going to.
123
+ this.host.onExit(() => this.end({ kind: "ended" })),
124
+ ];
125
+ this.enter();
126
+ this.paint();
127
+ });
128
+ }
129
+ /**
130
+ * Paint a new frame from the view, once, in a later task: every change made
131
+ * before then lands in the one frame.
132
+ *
133
+ * [LAW:no-ambient-temporal-coupling] A task, not a microtask. Input is read
134
+ * between tasks, so a view whose every frame asks for another still hears
135
+ * its keys — Ctrl+C included — where a microtask chain would starve them
136
+ * for as long as it ran.
137
+ */
138
+ refresh() {
139
+ if (this.refreshQueued)
140
+ return;
141
+ this.refreshQueued = true;
142
+ setTimeout(() => {
143
+ this.refreshQueued = false;
144
+ // [LAW:types-are-the-program] Only a running app holds the terminal; a
145
+ // suspended one repaints when it resumes, and a stopped one never does.
146
+ if (this._phase === "running")
147
+ this.paint();
148
+ });
149
+ }
150
+ /**
151
+ * Hand the terminal to whatever launched the program, and take it back and
152
+ * repaint when that resumes it. What sends the app here is the app's own —
153
+ * in raw mode Ctrl+Z arrives as a key.
154
+ */
155
+ async suspend() {
156
+ if (this._phase !== "running")
157
+ return;
158
+ this._phase = "suspended";
159
+ this.leave();
160
+ await this.host.suspend();
161
+ // Stopped while suspended — by a signal, say: the terminal is already
162
+ // handed back for good.
163
+ if (this._phase !== "suspended")
164
+ return;
165
+ this._phase = "running";
166
+ // What the last frame occupied is gone under whatever ran meanwhile, so
167
+ // the next one starts where the cursor is.
168
+ this.rows = 0;
169
+ this.enter();
170
+ this.paint();
171
+ }
172
+ /**
173
+ * Hear each frame once it is on screen — what `frame` now returns. A
174
+ * handler that throws fails the app as a frame that throws does.
175
+ */
176
+ onPaint(handler) {
177
+ this.paintHandlers.add(handler);
178
+ return () => this.paintHandlers.delete(handler);
179
+ }
180
+ /** Hand the terminal back for good; `run` resolves. */
181
+ stop() {
182
+ this.end({ kind: "stopped" });
183
+ }
184
+ /**
185
+ * Hand the terminal back for good; `run` rejects with `error`. For an error
186
+ * thrown where the app's own code runs outside a frame — a key handler, a
187
+ * timer — which would otherwise reach neither `run`'s caller nor the
188
+ * terminal's hand-back.
189
+ */
190
+ fail(error) {
191
+ this.end({ kind: "failed", error });
192
+ }
193
+ // --- the terminal ---
194
+ enter() {
195
+ this.host.setRawMode(true);
196
+ this.host.write(this.surface.enter + HIDE_CURSOR);
197
+ }
198
+ leave() {
199
+ this.host.write(RESET_STYLE + SHOW_CURSOR + this.surface.leave(this.rows));
200
+ this.host.setRawMode(false);
201
+ }
202
+ end(outcome) {
203
+ const phase = this._phase;
204
+ if (phase === "idle" || phase === "stopped")
205
+ return;
206
+ this._phase = "stopped";
207
+ for (const unsubscribe of this.subscriptions)
208
+ unsubscribe();
209
+ this.subscriptions = [];
210
+ // A suspended app handed the terminal back when it suspended.
211
+ if (phase === "running")
212
+ this.leave();
213
+ this.host.stop();
214
+ this.settle(outcome);
215
+ }
216
+ // [LAW:no-silent-failure] A frame that throws ends the app with that
217
+ // error: the terminal is handed back, and `run` rejects with it.
218
+ paint() {
219
+ try {
220
+ this.draw();
221
+ }
222
+ catch (error) {
223
+ this.end({ kind: "failed", error });
224
+ }
225
+ }
226
+ draw() {
227
+ const options = this.console.options;
228
+ const { maxWidth: cols } = options;
229
+ const height = { rows: options.height.rows, exact: this.surface.exact };
230
+ const lines = Segment.splitLines(this.view().render({ ...options, height }));
231
+ // The app set the budget, so the app shapes what comes back: no deeper
232
+ // than the terminal — a taller frame would scroll the rows `home` counts
233
+ // back over — and, as a region, exactly that deep. No row wider than the
234
+ // terminal either: one that soft-wrapped would push every row below it
235
+ // down a row the frame does not know about.
236
+ const frame = fitHeight(lines.slice(0, height.rows), height).map((line) => Segment.adjustLineLength(line, cols, undefined, false));
237
+ const painted = Math.min(this.surface.painted(frame.length, this.rows), height.rows);
238
+ // Each row is erased as it is reached rather than the frame cleared
239
+ // first, so no blank screen shows between two frames. The erase leads
240
+ // its row: after a row that fills the width, the cursor sits on its last
241
+ // cell, and an erase there would take it.
242
+ const destination = this.console.destination;
243
+ const body = Array.from({ length: painted }, (_, row) => ERASE_LINE + segmentsToString(frame[row] ?? [], destination)).join("\n");
244
+ // Rows blanked below the frame are not the frame's: the cursor goes back
245
+ // up to its last row, so the next frame and the program's next line start
246
+ // from the frame's own height.
247
+ const blanked = painted - Math.max(frame.length, 1);
248
+ const back = blanked > 0 ? `\x1b[${blanked}A` : "";
249
+ this.host.write(this.surface.home(this.rows) + body + back);
250
+ this._frame = frame;
251
+ this.rows = frame.length;
252
+ for (const handler of [...this.paintHandlers])
253
+ handler(frame);
254
+ }
255
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * hostEnvironment — a `TerminalHost` as the `ConsoleEnvironment` a `Console`
3
+ * consults, so a console writing through a host asks that host every question
4
+ * it has about its destination.
5
+ *
6
+ * [LAW:one-source-of-truth] A console asks its destination four things: where
7
+ * bytes go, is it a terminal, how big is it, and — through the environment —
8
+ * what colours it draws. A bare sink answers only the first, and the other
9
+ * three fall to the ambient `process`: some other stream's answer in node,
10
+ * none in a browser, where a console on xterm.js saw an unnamed TTY and drew
11
+ * 16 colours. Handing the console the whole environment keeps all four
12
+ * answers the host's.
13
+ *
14
+ * The host's size is `size()`, so the environment handed on carries no
15
+ * `COLUMNS` or `LINES`: a console reads those ahead of the stream, and an
16
+ * exported `COLUMNS` in the shell that launched a node host would pin the
17
+ * console's width while the terminal it draws on is resized. The stream's
18
+ * `columns` and `rows` are getters, so a console that was not given a fixed
19
+ * size follows the host through resizes.
20
+ */
21
+ import type { ConsoleEnvironment, ConsoleStream } from "../core/console.js";
22
+ import type { TerminalHost } from "./terminal-host.js";
23
+ export declare function hostEnvironment(host: TerminalHost): ConsoleEnvironment & {
24
+ readonly stdout: ConsoleStream;
25
+ readonly stderr: ConsoleStream;
26
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * hostEnvironment — a `TerminalHost` as the `ConsoleEnvironment` a `Console`
3
+ * consults, so a console writing through a host asks that host every question
4
+ * it has about its destination.
5
+ *
6
+ * [LAW:one-source-of-truth] A console asks its destination four things: where
7
+ * bytes go, is it a terminal, how big is it, and — through the environment —
8
+ * what colours it draws. A bare sink answers only the first, and the other
9
+ * three fall to the ambient `process`: some other stream's answer in node,
10
+ * none in a browser, where a console on xterm.js saw an unnamed TTY and drew
11
+ * 16 colours. Handing the console the whole environment keeps all four
12
+ * answers the host's.
13
+ *
14
+ * The host's size is `size()`, so the environment handed on carries no
15
+ * `COLUMNS` or `LINES`: a console reads those ahead of the stream, and an
16
+ * exported `COLUMNS` in the shell that launched a node host would pin the
17
+ * console's width while the terminal it draws on is resized. The stream's
18
+ * `columns` and `rows` are getters, so a console that was not given a fixed
19
+ * size follows the host through resizes.
20
+ */
21
+ // [LAW:types-are-the-program] A host always has a stream, so the return type
22
+ // says so rather than inheriting `ConsoleEnvironment`'s optional ones. It is
23
+ // one terminal, so stdout and stderr are the same stream — which is where a
24
+ // program's two streams land when both are attached to a terminal.
25
+ export function hostEnvironment(host) {
26
+ const { COLUMNS: _columns, LINES: _lines, ...env } = host.env;
27
+ const stream = {
28
+ write(chunk) {
29
+ host.write(chunk);
30
+ },
31
+ // [LAW:one-source-of-truth] A console asks whether its output is a
32
+ // terminal, which is the host's `writesToTerminal`, not its `isTTY`.
33
+ get isTTY() {
34
+ return host.writesToTerminal;
35
+ },
36
+ get columns() {
37
+ return host.size().cols;
38
+ },
39
+ get rows() {
40
+ return host.size().rows;
41
+ },
42
+ };
43
+ return { env, stdout: stream, stderr: stream };
44
+ }
@@ -0,0 +1,5 @@
1
+ export { BrowserTerminalHost } from "./terminal-host.js";
2
+ export type { TerminalHost, TerminalSize, DataHandler, ResizeHandler, ExitHandler, BrowserTerminalHostOptions, XtermTerminal, XtermDisposable, XtermResizeEvent, } from "./terminal-host.js";
3
+ export { hostEnvironment } from "./host-environment.js";
4
+ export { App } from "./app.js";
5
+ export type { AppOptions, AppPhase, Surface } from "./app.js";
@@ -0,0 +1,3 @@
1
+ export { BrowserTerminalHost } from "./terminal-host.js";
2
+ export { hostEnvironment } from "./host-environment.js";
3
+ export { App } from "./app.js";