@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,976 @@
1
+ /**
2
+ * RichText — styled text with spans. The primary text type for the library.
3
+ */
4
+ import { cellLen, cellCount, cellFit, cellFitEnd, asCellCol } from "./cells.js";
5
+ import { divideLine } from "./wrap.js";
6
+ import { Segment } from "./segment.js";
7
+ import { Style, NULL_STYLE, StyleSyntaxError } from "./style.js";
8
+ import { stripOscTerminators } from "./osc8.js";
9
+ import { drawable, getStyle, withBoundedWidth } from "./protocol.js";
10
+ // Strip control characters except \t and \n
11
+ // [LAW:single-enforcer] Single place where control chars are sanitized
12
+ const CONTROL_CHARS_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
13
+ export function stripControlChars(text) {
14
+ return text.replace(CONTROL_CHARS_RE, "");
15
+ }
16
+ const TRAILING_WHITESPACE_RE = /\s+$/;
17
+ /**
18
+ * The plain text of one line of segments, in the coordinate system
19
+ * `divideLine` and `Segment.divide` share: cell offsets into the styled line
20
+ * are cell offsets into this string. [LAW:one-source-of-truth] for that
21
+ * correspondence — the offsets are found in this text and applied to the
22
+ * segments it came from.
23
+ */
24
+ function plainOf(line) {
25
+ return line.map((segment) => segment.text).join("");
26
+ }
27
+ /**
28
+ * The cells of trailing whitespace on a wrapped line.
29
+ *
30
+ * A wrap cuts before a word, so the line it closes ends with the whitespace
31
+ * that followed *its* last word — padding the break created, not content the
32
+ * author wrote. Measuring it is what lets the overflow method tell "this line
33
+ * was cut" from "this line ends in spaces" and stamp an ellipsis only on the
34
+ * first, and what keeps a centred line from drifting half a space off true.
35
+ *
36
+ * Asked of the line's text rather than walked back through its segments,
37
+ * because where a line ends is a fact about the characters and not about how
38
+ * they were split. Walking the segments made it a fact about both: it read a
39
+ * segment with no trailing whitespace as content and stopped there, which an
40
+ * empty segment also looks like — and a crop leaves one behind. A styled line
41
+ * whose last cells were cropped therefore reported no hanging whitespace at
42
+ * all and was centred as though it were content to the edge, so a span landing
43
+ * anywhere in a wrap's whitespace un-centred the line it closed.
44
+ */
45
+ function hangingWhitespace(line) {
46
+ return cellLen(TRAILING_WHITESPACE_RE.exec(plainOf(line))?.[0] ?? "");
47
+ }
48
+ // [LAW:single-enforcer] RichText is the data-model trust boundary for link
49
+ // URLs: a `Style` is sanitized as it enters (`admitStyle`), and the `Style` a
50
+ // stored string resolves to is sanitized as it leaves for a render
51
+ // (`resolveStyle`). Wire-byte safety is enforced separately by `osc8Open`
52
+ // (core/osc8.ts), which every link producer calls and which applies the same
53
+ // `stripOscTerminators`.
54
+ function sanitizeStyleLink(style) {
55
+ const link = style.link;
56
+ if (!link)
57
+ return style;
58
+ const cleaned = stripOscTerminators(link);
59
+ if (cleaned === link)
60
+ return style;
61
+ return style.withLink(cleaned);
62
+ }
63
+ /**
64
+ * A style as a RichText keeps it: as given. A name stays a name because what
65
+ * it stands for depends on the theme of the render that draws it, which no
66
+ * RichText knows when the name arrives — the reference stores span styles the
67
+ * same way. A string holds no link until it is parsed, so only a `Style` has
68
+ * one to sanitize here.
69
+ *
70
+ * [LAW:single-enforcer] Nor does a RichText keep an anchor (`./anchor.ts`). It
71
+ * lays its text out anew, so a stamp naming where a cell sat in the output it
72
+ * came from would name the wrong cell once it wraps, slices or overlaps; the
73
+ * owner that renders the RichText is the one that stamps its cells.
74
+ */
75
+ function admitStyle(style) {
76
+ if (!(style instanceof Style))
77
+ return style;
78
+ return sanitizeStyleLink(style.anchor ? style.withAnchor(undefined) : style);
79
+ }
80
+ /** A style that adds nothing: the empty definition, or a null `Style`. */
81
+ function isEmptyStyle(style) {
82
+ return style instanceof Style ? style.isNull : style === "";
83
+ }
84
+ /**
85
+ * The style a stored `string | Style` stands for in this render.
86
+ *
87
+ * A parsed string can carry a link, so the result is sanitized on the way out
88
+ * as well.
89
+ */
90
+ function resolveStyle(options, style) {
91
+ return sanitizeStyleLink(style instanceof Style ? style : resolveDefinition(options, style));
92
+ }
93
+ /**
94
+ * [LAW:single-enforcer] Styling is non-critical — an unrecognized style name
95
+ * (typo, missing theme key, bad concatenation) degrades to unstyled rather
96
+ * than crashing, as the reference's `Text.render` resolves with a null
97
+ * default. Absorb only StyleSyntaxError here; other errors are genuine bugs
98
+ * and must surface. The render's `onStyleError` hears about each one first,
99
+ * and a handler that throws turns the degrade into a failure.
100
+ */
101
+ function resolveDefinition(options, style) {
102
+ try {
103
+ return getStyle(options, style);
104
+ }
105
+ catch (err) {
106
+ if (!(err instanceof StyleSyntaxError))
107
+ throw err;
108
+ options.onStyleError?.(err, style);
109
+ return NULL_STYLE;
110
+ }
111
+ }
112
+ // --- Span ---
113
+ export class Span {
114
+ start;
115
+ end;
116
+ style;
117
+ constructor(start, end, style) {
118
+ this.start = start;
119
+ this.end = end;
120
+ this.style = style;
121
+ }
122
+ get hasLength() {
123
+ return this.end > this.start;
124
+ }
125
+ toString() {
126
+ return `Span(${this.start}, ${this.end})`;
127
+ }
128
+ split(offset) {
129
+ if (offset <= this.start || offset >= this.end)
130
+ return [this, undefined];
131
+ return [
132
+ new Span(this.start, offset, this.style),
133
+ new Span(offset, this.end, this.style),
134
+ ];
135
+ }
136
+ move(delta) {
137
+ return new Span(this.start + delta, this.end + delta, this.style);
138
+ }
139
+ rightCrop(offset) {
140
+ if (offset >= this.end)
141
+ return this;
142
+ return new Span(this.start, Math.min(this.end, offset), this.style);
143
+ }
144
+ extend(count) {
145
+ return new Span(this.start, this.end + count, this.style);
146
+ }
147
+ }
148
+ export class RichText {
149
+ _text;
150
+ _spans;
151
+ _style;
152
+ _justify;
153
+ _overflow;
154
+ _end;
155
+ _tabSize;
156
+ _noWrap;
157
+ constructor(text, options) {
158
+ this._text = text ? stripControlChars(text) : "";
159
+ this._spans = [];
160
+ // [LAW:single-enforcer] `admitStyle` is the boundary that sanitizes
161
+ // any link URL crossing into a RichText; downstream trusts the invariant.
162
+ this._style = admitStyle(options?.style ?? NULL_STYLE);
163
+ this._justify = options?.justify;
164
+ this._overflow = options?.overflow;
165
+ this._end = options?.end ?? "\n";
166
+ this._tabSize = options?.tabSize ?? 8;
167
+ this._noWrap = options?.noWrap ?? false;
168
+ }
169
+ // --- Properties ---
170
+ get plain() {
171
+ return this._text;
172
+ }
173
+ set plain(value) {
174
+ const sanitized = stripControlChars(value);
175
+ this._text = sanitized;
176
+ // Trim spans that extend beyond new length
177
+ const len = sanitized.length;
178
+ this._spans = this._spans
179
+ .map((s) => (s.end > len ? new Span(s.start, Math.min(s.end, len), s.style) : s))
180
+ .filter((s) => s.start < len);
181
+ }
182
+ get length() {
183
+ return this._text.length;
184
+ }
185
+ get cellLength() {
186
+ return cellLen(this._text);
187
+ }
188
+ get hasContent() {
189
+ return this._text.length > 0;
190
+ }
191
+ /** The base style every span layers over: a `Style`, or a name resolved at render. */
192
+ get style() {
193
+ return this._style;
194
+ }
195
+ set style(value) {
196
+ this._style = admitStyle(value);
197
+ }
198
+ get justify() {
199
+ return this._justify;
200
+ }
201
+ set justify(value) {
202
+ this._justify = value;
203
+ }
204
+ get overflow() {
205
+ return this._overflow;
206
+ }
207
+ set overflow(value) {
208
+ this._overflow = value;
209
+ }
210
+ get end() {
211
+ return this._end;
212
+ }
213
+ set end(value) {
214
+ this._end = value;
215
+ }
216
+ get noWrap() {
217
+ return this._noWrap;
218
+ }
219
+ set noWrap(value) {
220
+ this._noWrap = value;
221
+ }
222
+ get spans() {
223
+ return this._spans;
224
+ }
225
+ /**
226
+ * This text's own style, spans aside, as the render drawing it resolves it.
227
+ * A name the render's theme does not define resolves to no style, because
228
+ * text forgives a missing name.
229
+ */
230
+ resolvedStyle(options) {
231
+ return resolveStyle(options, this._style);
232
+ }
233
+ /**
234
+ * The style of the cell-column at the named edge — base style merged with
235
+ * any spans covering the leftmost (side="left") or rightmost (side="right")
236
+ * character.
237
+ *
238
+ * [LAW:locality-or-seam] Used by `Joiner`s to paint the transition between
239
+ * adjacent `Strip` items. Joiners only ever need the column adjacent to
240
+ * them, so the cell type exposes that column rather than constraining its
241
+ * interior to be uniform. For RichText with uniform styling, both edges
242
+ * return the same style; for RichText with edge variation, each edge
243
+ * accurately reports the column the joiner actually meets.
244
+ *
245
+ * Position is by character index (not cell column). For wide-character
246
+ * text, the last character occupies the rightmost cell column — the bg
247
+ * of that character covers both columns, so character-index lookup gives
248
+ * the correct edge color.
249
+ *
250
+ * Takes the render's options because the edge is reported as it will be
251
+ * drawn, and a style name draws as whatever the render's theme says.
252
+ */
253
+ edgeStyle(side, options) {
254
+ const base = this.resolvedStyle(options);
255
+ if (this._text.length === 0)
256
+ return base;
257
+ const pos = side === "left" ? 0 : this._text.length - 1;
258
+ let result = base;
259
+ for (const span of this._spans) {
260
+ if (span.start <= pos && pos < span.end) {
261
+ result = result.add(resolveStyle(options, span.style));
262
+ }
263
+ }
264
+ return result;
265
+ }
266
+ // --- Content Operations ---
267
+ append(content, style) {
268
+ if (content instanceof RichText) {
269
+ if (style !== undefined) {
270
+ throw new Error("Style argument must not be provided when appending RichText");
271
+ }
272
+ const offset = this._text.length;
273
+ this._text += content._text;
274
+ // Its base style becomes a span under its own spans, as the reference's
275
+ // `append` does, so appended text looks as it did alone.
276
+ this._addSpan(offset, this._text.length, content._style);
277
+ for (const span of content._spans) {
278
+ this._spans.push(span.move(offset));
279
+ }
280
+ return this;
281
+ }
282
+ const sanitized = stripControlChars(content);
283
+ const start = this._text.length;
284
+ this._text += sanitized;
285
+ this._addSpan(start, this._text.length, style ?? "");
286
+ return this;
287
+ }
288
+ contains(needle) {
289
+ const searchText = needle instanceof RichText ? needle._text : needle;
290
+ return this._text.includes(searchText);
291
+ }
292
+ at(index) {
293
+ const resolved = index < 0 ? this._text.length + index : index;
294
+ const char = this._text[resolved];
295
+ if (char === undefined)
296
+ return new RichText("");
297
+ return this.slice(resolved, resolved + 1);
298
+ }
299
+ slice(start, end) {
300
+ const text = this._text;
301
+ const len = text.length;
302
+ const s = start ?? 0;
303
+ const e = end ?? len;
304
+ const resolvedStart = s < 0 ? Math.max(0, len + s) : Math.min(s, len);
305
+ const resolvedEnd = e < 0 ? Math.max(0, len + e) : Math.min(e, len);
306
+ if (resolvedStart >= resolvedEnd) {
307
+ return this.blankCopy();
308
+ }
309
+ const slicedText = text.slice(resolvedStart, resolvedEnd);
310
+ const result = this.blankCopy(slicedText);
311
+ for (const span of this._spans) {
312
+ const spanStart = Math.max(span.start, resolvedStart) - resolvedStart;
313
+ const spanEnd = Math.min(span.end, resolvedEnd) - resolvedStart;
314
+ if (spanStart < spanEnd) {
315
+ result._spans.push(new Span(spanStart, spanEnd, span.style));
316
+ }
317
+ }
318
+ return result;
319
+ }
320
+ // --- Styling Operations ---
321
+ /**
322
+ * The one way a span enters this text. [LAW:single-enforcer] An empty style
323
+ * adds nothing, as the reference's `if style:` has it, and every other style
324
+ * is admitted as given.
325
+ */
326
+ _addSpan(start, end, style) {
327
+ const admitted = admitStyle(style);
328
+ if (isEmptyStyle(admitted))
329
+ return;
330
+ this._spans.push(new Span(start, end, admitted));
331
+ }
332
+ stylize(style, start, end) {
333
+ const len = this._text.length;
334
+ const s = start !== undefined ? (start < 0 ? len + start : start) : 0;
335
+ const e = end !== undefined ? (end < 0 ? len + end : end) : len;
336
+ if (s >= e || s >= len || e <= 0)
337
+ return this;
338
+ const clampedStart = Math.max(0, s);
339
+ const clampedEnd = Math.min(len, e);
340
+ this._addSpan(clampedStart, clampedEnd, style);
341
+ return this;
342
+ }
343
+ highlightRegex(pattern, style) {
344
+ const text = this._text;
345
+ let count = 0;
346
+ // Ensure global flag
347
+ const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g";
348
+ const re = new RegExp(pattern.source, flags);
349
+ let match;
350
+ while ((match = re.exec(text)) !== null) {
351
+ if (match[0].length === 0) {
352
+ re.lastIndex++;
353
+ continue;
354
+ }
355
+ // Named capture groups are applied as style names
356
+ if (match.groups) {
357
+ let searchFrom = 0;
358
+ for (const [groupName, groupValue] of Object.entries(match.groups)) {
359
+ if (groupValue !== undefined) {
360
+ const posInMatch = match[0].indexOf(groupValue, searchFrom);
361
+ if (posInMatch >= 0) {
362
+ const groupStart = match.index + posInMatch;
363
+ this._addSpan(groupStart, groupStart + groupValue.length, groupName);
364
+ searchFrom = posInMatch + groupValue.length;
365
+ }
366
+ }
367
+ }
368
+ count++;
369
+ continue;
370
+ }
371
+ this._addSpan(match.index, match.index + match[0].length, style ?? "");
372
+ count++;
373
+ }
374
+ return count;
375
+ }
376
+ highlightWords(words, style, options) {
377
+ const caseSensitive = options?.caseSensitive !== false;
378
+ let count = 0;
379
+ for (const word of words) {
380
+ if (word.length === 0)
381
+ continue;
382
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
383
+ const flags = caseSensitive ? "g" : "gi";
384
+ const re = new RegExp(`\\b${escaped}\\b`, flags);
385
+ let match;
386
+ while ((match = re.exec(this._text)) !== null) {
387
+ this._addSpan(match.index, match.index + match[0].length, style);
388
+ count++;
389
+ }
390
+ }
391
+ return count;
392
+ }
393
+ // --- Copy Operations ---
394
+ copy() {
395
+ const result = new RichText(this._text, {
396
+ style: this._style,
397
+ justify: this._justify,
398
+ overflow: this._overflow,
399
+ end: this._end,
400
+ tabSize: this._tabSize,
401
+ noWrap: this._noWrap,
402
+ });
403
+ result._spans = this._spans.slice();
404
+ return result;
405
+ }
406
+ blankCopy(text) {
407
+ return new RichText(text ?? "", {
408
+ style: this._style,
409
+ justify: this._justify,
410
+ overflow: this._overflow,
411
+ end: this._end,
412
+ tabSize: this._tabSize,
413
+ noWrap: this._noWrap,
414
+ });
415
+ }
416
+ // --- Splitting ---
417
+ split(separator) {
418
+ const sep = separator ?? "\n";
419
+ const text = this._text;
420
+ const parts = [];
421
+ let start = 0;
422
+ while (true) {
423
+ const idx = text.indexOf(sep, start);
424
+ if (idx === -1) {
425
+ parts.push(this.slice(start));
426
+ break;
427
+ }
428
+ parts.push(this.slice(start, idx));
429
+ start = idx + sep.length;
430
+ }
431
+ return parts;
432
+ }
433
+ divide(offsets) {
434
+ if (offsets.length === 0)
435
+ return [this.copy()];
436
+ const parts = [];
437
+ let prev = 0;
438
+ for (const offset of offsets) {
439
+ parts.push(this.slice(prev, offset));
440
+ prev = offset;
441
+ }
442
+ parts.push(this.slice(prev));
443
+ return parts;
444
+ }
445
+ // --- Whitespace Operations ---
446
+ rstrip() {
447
+ const trimmed = this._text.replace(/\s+$/, "");
448
+ if (trimmed.length < this._text.length) {
449
+ this.plain = trimmed;
450
+ }
451
+ return this;
452
+ }
453
+ pad(count, char) {
454
+ const c = char ?? " ";
455
+ const padding = c.repeat(count);
456
+ // Shift all spans to the right
457
+ this._spans = this._spans.map((s) => s.move(count));
458
+ this._text = padding + this._text + padding;
459
+ return this;
460
+ }
461
+ padLeft(count, char) {
462
+ const c = char ?? " ";
463
+ this._spans = this._spans.map((s) => s.move(count));
464
+ this._text = c.repeat(count) + this._text;
465
+ return this;
466
+ }
467
+ padRight(count, char) {
468
+ const c = char ?? " ";
469
+ this._text += c.repeat(count);
470
+ return this;
471
+ }
472
+ setLength(length) {
473
+ if (this._text.length < length) {
474
+ this._text += " ".repeat(length - this._text.length);
475
+ }
476
+ else if (this._text.length > length) {
477
+ this.plain = this._text.slice(0, length);
478
+ }
479
+ return this;
480
+ }
481
+ extendStyle(count) {
482
+ const oldLen = this._text.length;
483
+ this._text += " ".repeat(count);
484
+ // Extend existing spans to cover new spaces
485
+ this._spans = this._spans.map((s) => s.end === oldLen ? s.extend(count) : s);
486
+ return this;
487
+ }
488
+ // --- Truncation ---
489
+ /**
490
+ * Truncate to a fixed cell-column width, in one of three modes.
491
+ *
492
+ * - `mode: "right"` (default) \u2014 drop characters from the right; append
493
+ * `marker` (if any) at the cut.
494
+ * - `mode: "left"` \u2014 drop characters from the left; prepend `marker` at
495
+ * the cut.
496
+ * - `mode: "middle"` \u2014 keep equal halves from both ends; place `marker`
497
+ * in the middle.
498
+ *
499
+ * Marker default is `"\u2026"`. Pass `marker: ""` for raw cropping without an
500
+ * indicator glyph. A marker wider than `width` is itself cut to the glyphs
501
+ * that fit, and the text takes whatever cells that leaves — all of them, when
502
+ * not one glyph of the marker fits — so the result is never wider than asked.
503
+ * Every cut, marker and text alike, falls between grapheme clusters.
504
+ *
505
+ * Spans are preserved through the cut: characters that survive keep their
506
+ * styling; the marker (if any) is inserted as plain text with no span.
507
+ * Use `stylize(...)` on the result to color the marker if needed.
508
+ *
509
+ * [LAW:dataflow-not-control-flow] mode/marker/width all flow as values;
510
+ * the walk is the same shape regardless. No "if truncated then rebuild"
511
+ * branch \u2014 the unchanged path just early-returns when content fits.
512
+ */
513
+ truncate(width, options) {
514
+ if (this.cellLength <= width)
515
+ return this;
516
+ const mode = options?.mode ?? "right";
517
+ // [LAW:dataflow-not-control-flow] the marker is fitted to the width as a
518
+ // value, so width 0 and a marker wider than the width run the same walk
519
+ // as every other call: what is drawn plus what is kept is `cells` wide.
520
+ const cells = cellCount(width);
521
+ const marker = cellFit(options?.marker ?? "\u2026", cells);
522
+ const budget = asCellCol(cells - cellLen(marker));
523
+ if (mode === "right") {
524
+ this._cropRightTo(budget);
525
+ if (marker)
526
+ this._text += marker;
527
+ return this;
528
+ }
529
+ if (mode === "left") {
530
+ this._cropLeftTo(budget);
531
+ if (marker) {
532
+ this._spans = this._spans.map((s) => s.move(marker.length));
533
+ this._text = marker + this._text;
534
+ }
535
+ return this;
536
+ }
537
+ // middle
538
+ const leftBudget = asCellCol(Math.floor(budget / 2));
539
+ const rightBudget = asCellCol(budget - leftBudget);
540
+ // Find the char-index ranges to keep from each side.
541
+ const leftEndCharIdx = cellFit(this._text, leftBudget).length;
542
+ const rightStartCharIdx = this._text.length - cellFitEnd(this._text, rightBudget).length;
543
+ const leftText = this._text.slice(0, leftEndCharIdx);
544
+ const rightText = this._text.slice(rightStartCharIdx);
545
+ const droppedStart = leftEndCharIdx;
546
+ const droppedEnd = rightStartCharIdx;
547
+ const shift = marker.length - (droppedEnd - droppedStart);
548
+ // Spans falling entirely before the drop stay; entirely after shift by
549
+ // (marker.length - dropped chars); spans crossing the drop are clipped.
550
+ const newSpans = [];
551
+ for (const s of this._spans) {
552
+ if (s.end <= droppedStart) {
553
+ newSpans.push(s);
554
+ }
555
+ else if (s.start >= droppedEnd) {
556
+ newSpans.push(s.move(shift));
557
+ }
558
+ else {
559
+ // crosses \u2014 clip to left side and to right side as two spans
560
+ if (s.start < droppedStart) {
561
+ newSpans.push(new Span(s.start, droppedStart, s.style));
562
+ }
563
+ if (s.end > droppedEnd) {
564
+ newSpans.push(new Span(droppedEnd + shift, s.end + shift, s.style));
565
+ }
566
+ }
567
+ }
568
+ this._text = leftText + marker + rightText;
569
+ this._spans = newSpans;
570
+ return this;
571
+ }
572
+ _cropRightTo(targetWidth) {
573
+ this.plain = cellFit(this._text, targetWidth);
574
+ }
575
+ _cropLeftTo(targetWidth) {
576
+ const charIdx = this._text.length - cellFitEnd(this._text, targetWidth).length;
577
+ // Shift spans left by charIdx; clip spans that started before.
578
+ const shift = -charIdx;
579
+ this._spans = this._spans
580
+ .map((s) => {
581
+ if (s.end <= charIdx)
582
+ return undefined;
583
+ const newStart = Math.max(0, s.start + shift);
584
+ const newEnd = s.end + shift;
585
+ return new Span(newStart, newEnd, s.style);
586
+ })
587
+ .filter((s) => s !== undefined);
588
+ this._text = this._text.slice(charIdx);
589
+ }
590
+ // --- Alignment ---
591
+ align(justify, width) {
592
+ const currentWidth = this.cellLength;
593
+ if (currentWidth >= width)
594
+ return this;
595
+ const gap = width - currentWidth;
596
+ switch (justify) {
597
+ case "left":
598
+ this.padRight(gap);
599
+ break;
600
+ case "right":
601
+ this.padLeft(gap);
602
+ break;
603
+ case "center": {
604
+ const leftPad = Math.floor(gap / 2);
605
+ const rightPad = gap - leftPad;
606
+ this.padLeft(leftPad);
607
+ this.padRight(rightPad);
608
+ break;
609
+ }
610
+ }
611
+ return this;
612
+ }
613
+ // --- Suffix Removal ---
614
+ removeSuffix(suffix) {
615
+ if (this._text.endsWith(suffix)) {
616
+ this.plain = this._text.slice(0, -suffix.length);
617
+ }
618
+ return this;
619
+ }
620
+ // --- Token Appending ---
621
+ appendTokens(tokens) {
622
+ for (const [text, style] of tokens) {
623
+ this.append(text, style);
624
+ }
625
+ return this;
626
+ }
627
+ // --- Static Factories ---
628
+ static assemble(parts, options) {
629
+ const result = new RichText("", { style: options?.style });
630
+ for (const part of parts) {
631
+ if (typeof part === "string") {
632
+ result.append(part);
633
+ }
634
+ else if (part instanceof RichText) {
635
+ result.append(part);
636
+ }
637
+ else {
638
+ const [text, style] = part;
639
+ result.append(text, style);
640
+ }
641
+ }
642
+ return result;
643
+ }
644
+ static styled(text, style) {
645
+ const result = new RichText(text);
646
+ result.stylize(style);
647
+ return result;
648
+ }
649
+ /**
650
+ * Concatenate a sequence of `RichText` fragments into a single `RichText`,
651
+ * flattening each fragment's wrapping `style` onto a span over that
652
+ * fragment's range so downstream rendering preserves the original styling.
653
+ *
654
+ * Designed for the template engine's `RichText[]` output: a top-level
655
+ * `{{ red "x" }}{{ blue "y" }}` evaluates to two fragments — one with
656
+ * wrapping `style = red`, one with `blue` — and consumers that want a
657
+ * single styled string for downstream rendering need both styles
658
+ * preserved as spans on the concatenated result, which is what `append()`
659
+ * does with each fragment.
660
+ *
661
+ * Empty input → empty `RichText` with `end: ""`. Caller can override
662
+ * `end` (defaults to `""` — the engine-output case rarely wants a
663
+ * trailing newline added by the container).
664
+ */
665
+ static fromFragments(fragments, options) {
666
+ const result = new RichText("", { end: options?.end ?? "" });
667
+ for (const frag of fragments)
668
+ result.append(frag);
669
+ return result;
670
+ }
671
+ // --- Renderable ---
672
+ *render(options) {
673
+ const text = this._expandTabs(this._text);
674
+ const base = this.resolvedStyle(options);
675
+ const allSegments = this._buildSegments(text, base, options);
676
+ const logicalLines = Segment.splitLines(allSegments);
677
+ // [LAW:single-enforcer] The one crossing for this renderable's width, and
678
+ // the call every other renderable already makes. A bare `cellCount` stood
679
+ // here doing half of it: it caught a NaN width, which had made every
680
+ // overflow arm a no-op, but passed an unbounded one through to `justify`,
681
+ // which pads — and `" ".repeat(Infinity)` throws.
682
+ const maxWidth = cellCount(withBoundedWidth(options, this).maxWidth);
683
+ const overflow = this._overflow ?? options.overflow ?? "fold";
684
+ const noWrap = this._noWrap || (options.noWrap ?? false);
685
+ // Two widths, and they are the reference's `no_wrap` and `"ignore"` told
686
+ // apart. `edge` is where a line is cut: gone under `"ignore"`, so the line
687
+ // leaves at its natural width and whatever drew it decides about the
688
+ // overhang. `wrapAt` is where a line may break: gone under `noWrap` too,
689
+ // which keeps one line per line and still cuts it at the edge by the
690
+ // overflow method — Rich's `Text.wrap` truncates its no-wrap arm.
691
+ //
692
+ // [LAW:dataflow-not-control-flow] Each reaches the pipeline as a width, not
693
+ // as a step to skip: an unbounded width has no edge to break at, so
694
+ // `divideLine` finds no cuts and `_fitLine` finds nothing past the edge,
695
+ // and every line runs the same three steps. `Infinity` is already this
696
+ // library's spelling of an unbounded width offer — `withBoundedWidth` in
697
+ // protocol.ts parses one on the way in.
698
+ const edge = overflow === "ignore" ? cellCount(Infinity) : maxWidth;
699
+ const wrapAt = noWrap ? cellCount(Infinity) : edge;
700
+ // A line with no edge has no width to be justified in, so under `"ignore"`
701
+ // it is not justified — the reference's `Text.wrap` returns that arm before
702
+ // `justify`. `undefined` is the placement that leaves a line as it is.
703
+ const justify = overflow === "ignore" ? undefined : this._justify ?? options.justify;
704
+ // One cell either way, so the marker's stand-in leaves the cut where it was.
705
+ const ellipsis = drawable(options, "\u2026", ".");
706
+ const endsWithNewline = text.endsWith("\n");
707
+ for (let index = 0; index < logicalLines.length; index += 1) {
708
+ const line = logicalLines[index];
709
+ const terminateLine = index < logicalLines.length - 1 || endsWithNewline;
710
+ // Wrap first, overflow last — the reference's order, and the reason a
711
+ // long sentence grows a table row while an unbreakable word in the same
712
+ // column still ellipsizes.
713
+ const cuts = divideLine(plainOf(line), wrapAt, { fold: overflow === "fold" });
714
+ const wrapped = Segment.divide(line, cuts);
715
+ const placed = this._justifyLines(wrapped.map((piece) => [...this._fitLine(piece, edge, overflow, ellipsis)]), maxWidth, base, justify);
716
+ for (let piece = 0; piece < placed.length; piece += 1) {
717
+ yield* placed[piece];
718
+ if (piece < placed.length - 1 || terminateLine) {
719
+ yield Segment.line();
720
+ }
721
+ }
722
+ }
723
+ // [LAW:single-enforcer] The one place `end` is emitted, for empty and
724
+ // non-empty text alike — the pre-fix code checked it once for empty text
725
+ // (truthy) and again for non-empty text (truthy and not the default
726
+ // "\n"), which gave `end` two meanings depending on whether the text was
727
+ // empty (rich-text-5ai). Empty text takes zero iterations of the loop
728
+ // above, so this is reached either way with nothing yielded but this.
729
+ if (this._end) {
730
+ yield new Segment(this._end);
731
+ }
732
+ }
733
+ // --- Measurable ---
734
+ measure(options) {
735
+ const text = this._expandTabs(this._text);
736
+ const lines = text.split("\n");
737
+ let maxLineWidth = 0;
738
+ let maxWordWidth = 0;
739
+ for (const line of lines) {
740
+ const lineWidth = cellLen(line);
741
+ maxLineWidth = Math.max(maxLineWidth, lineWidth);
742
+ // Minimum is the longest word
743
+ const words = line.split(/\s+/);
744
+ for (const word of words) {
745
+ if (word.length > 0) {
746
+ maxWordWidth = Math.max(maxWordWidth, cellLen(word));
747
+ }
748
+ }
749
+ }
750
+ // Parsed for the same reason `render` parses it: an unparsed NaN ceiling
751
+ // makes both `Math.min` calls NaN, and a range of NaN..NaN is one no parent
752
+ // layout can divide.
753
+ const ceiling = cellCount(options.maxWidth);
754
+ return {
755
+ minimum: Math.min(maxWordWidth, ceiling),
756
+ maximum: Math.min(maxLineWidth, ceiling),
757
+ };
758
+ }
759
+ // --- Internal ---
760
+ _expandTabs(text) {
761
+ if (!text.includes("\t"))
762
+ return text;
763
+ return text.replace(/\t/g, " ".repeat(this._tabSize));
764
+ }
765
+ /**
766
+ * The rendered text cut at every span edge, each piece carrying the base
767
+ * style plus every span covering it.
768
+ *
769
+ * Walked span-first rather than piece-first, and that direction is the whole
770
+ * performance argument. The pieces are cut at the span edges themselves, so
771
+ * a span covers a piece exactly when it covers the piece's first character —
772
+ * which makes each span's run of pieces a contiguous range it can be written
773
+ * into once, instead of a question every piece asks of every span. The
774
+ * piece-first form charged `spans x pieces`, and the pieces are themselves
775
+ * cut by the spans, so anything styling densely paid the square in ordinary
776
+ * use: 8,000 one-character spans took 211ms where 1,000 took 3.2ms. Every
777
+ * `Highlighter` over a large value reaches that, and so does `Pretty`, whose
778
+ * indent guides emit a span per indent character.
779
+ *
780
+ * Span-first is also what keeps the composition honest, for free. `Style.add`
781
+ * is order-dependent and the last writer wins, so the pieces have to fold
782
+ * their styles in `_spans` order — which iterating `_spans` is, and which a
783
+ * sweep ordered by position would have had to reconstruct.
784
+ *
785
+ * [LAW:dataflow-not-control-flow] A span covering nothing — empty, reversed,
786
+ * or entirely past the text — still cuts the text where its edges land, as it
787
+ * always did, and then folds into no piece at all: its range comes out empty
788
+ * and no case handles it.
789
+ */
790
+ _buildSegments(text, base, options) {
791
+ const clamp = (offset) => Math.max(0, Math.min(offset, text.length));
792
+ const positions = new Set([0, text.length]);
793
+ for (const span of this._spans) {
794
+ positions.add(clamp(span.start));
795
+ positions.add(clamp(span.end));
796
+ }
797
+ const boundaries = [...positions].sort((a, b) => a - b);
798
+ // Every span edge is a boundary, so where a span's range opens is a lookup
799
+ // rather than a search.
800
+ const pieceAt = new Map(boundaries.map((position, piece) => [position, piece]));
801
+ const styles = boundaries.slice(0, -1).map(() => base);
802
+ for (const span of this._spans) {
803
+ const end = clamp(span.end);
804
+ const style = resolveStyle(options, span.style);
805
+ const opensAt = pieceAt.get(clamp(span.start));
806
+ for (let piece = opensAt; boundaries[piece] < end; piece++) {
807
+ styles[piece] = styles[piece].add(style);
808
+ }
809
+ }
810
+ return styles.map((style, piece) => new Segment(text.slice(boundaries[piece], boundaries[piece + 1]), style.isNull ? undefined : style));
811
+ }
812
+ /**
813
+ * The pieces one logical line wrapped into, each placed in a canvas
814
+ * `maxWidth` wide, as Rich's `Lines.justify` places them — pinned block for
815
+ * block against the reference in `test/core/text-justify.test.ts`.
816
+ *
817
+ * It is handed the whole wrapped line because `full` is the one mode a
818
+ * piece cannot answer alone: the reference leaves a paragraph's last line
819
+ * ragged, so where the piece sits decides its answer where the other three
820
+ * modes need only the piece itself. The set that decides "last" is this one
821
+ * and not the whole render — `Text.wrap` calls `Lines.justify` once per
822
+ * *logical* line — and `Segment.divide` already handed it over whole.
823
+ */
824
+ _justifyLines(lines, maxWidth, base, justify) {
825
+ if (justify !== "full") {
826
+ return lines.map((line) => [...this._justifyLine(line, maxWidth, justify)]);
827
+ }
828
+ return lines.map((line, index) => index === lines.length - 1 ? line : this._fillLine(line, maxWidth, base));
829
+ }
830
+ /**
831
+ * One line placed in a canvas `maxWidth` wide.
832
+ *
833
+ * Centre and right align on the line's *content*. The whitespace a wrap
834
+ * leaves on the end of the line it closed is the break's own padding, not
835
+ * text, and aligning around it pushes the text half a gap off true — a
836
+ * centred title that wraps drifts left on every line that happens to end in
837
+ * a space. Left keeps that whitespace, because there it is already on the
838
+ * side the padding goes.
839
+ *
840
+ * `undefined` is not `"left"`: it is Rich's `"default"`, which places the
841
+ * line without padding it at all. That distinction is what lets a soft-wrapped
842
+ * `Console.print` leave its lines at their natural width.
843
+ */
844
+ *_justifyLine(line, maxWidth,
845
+ // [LAW:types-are-the-program] `full` is absent rather than ignored: it
846
+ // needs the lines either side of this one, so the type refuses it here
847
+ // instead of a branch quietly rendering it as `left`, which is the bug
848
+ // this signature replaces (rich-justify-0cr.1).
849
+ justify) {
850
+ switch (justify) {
851
+ case "center":
852
+ case "right": {
853
+ const body = Segment.adjustLineLength(line, Segment.getLineLength(line) - hangingWhitespace(line), undefined, false);
854
+ const gap = Math.max(maxWidth - Segment.getLineLength(body), 0);
855
+ const leftPad = justify === "center" ? Math.floor(gap / 2) : gap;
856
+ if (leftPad > 0)
857
+ yield new Segment(" ".repeat(leftPad));
858
+ yield* body;
859
+ const rightPad = gap - leftPad;
860
+ if (rightPad > 0)
861
+ yield new Segment(" ".repeat(rightPad));
862
+ break;
863
+ }
864
+ case "left":
865
+ yield* Segment.adjustLineLength(line, Math.max(maxWidth, Segment.getLineLength(line)));
866
+ break;
867
+ default:
868
+ yield* line;
869
+ break;
870
+ }
871
+ }
872
+ /**
873
+ * One line of a wrapped paragraph, its gaps widened until it fills the
874
+ * canvas — what `justify: "full"` promises, and what the reference's
875
+ * `Lines.justify` does to every line of a paragraph but the last.
876
+ *
877
+ * Slack goes in a cell at a time, starting at the rightmost gap and walking
878
+ * left, round and round until the line is full. That order is the
879
+ * reference's own, and what it decides is where an odd cell lands when the
880
+ * slack will not divide evenly: the right-hand gaps take it.
881
+ *
882
+ * The words come from the line's *text* split on a single space, with the
883
+ * blank a trailing separator leaves behind dropped — `Text.split` and
884
+ * `String.prototype.split` agree on that list, empty words and all. Two
885
+ * consequences read as bugs until you know whose they are: a run of n
886
+ * spaces is n gaps rather than one, so spacing an author widened stretches
887
+ * instead of collapsing, and the whitespace a wrap left hanging is a gap
888
+ * like the rest, which is why a filled line does not keep it. Both are
889
+ * pinned in `text-justify.golden.txt`, by the `uneven` and `sentence`
890
+ * blocks respectively.
891
+ */
892
+ _fillLine(line, maxWidth, base) {
893
+ const plain = plainOf(line);
894
+ const words = plain.split(" ");
895
+ if (plain.endsWith(" "))
896
+ words.pop();
897
+ const gaps = words.length - 1;
898
+ const spaces = new Array(gaps).fill(1);
899
+ let filled = words.reduce((total, word) => total + cellLen(word), 0) + gaps;
900
+ for (let turn = 0; filled < maxWidth && gaps > 0; turn = (turn + 1) % gaps) {
901
+ spaces[gaps - 1 - turn] += 1;
902
+ filled += 1;
903
+ }
904
+ // Cut at both edges of every gap, so a word is an even piece and the
905
+ // separator that followed it is the odd piece after it. Measured in cells
906
+ // because that is the coordinate system `Segment.divide` reads, which a
907
+ // line of wide glyphs is the only thing that notices.
908
+ const cuts = [];
909
+ let edge = 0;
910
+ for (let index = 0; index < words.length; index += 1) {
911
+ edge += cellLen(words[index]);
912
+ cuts.push(edge);
913
+ edge += 1;
914
+ if (index < gaps)
915
+ cuts.push(edge);
916
+ }
917
+ const pieces = Segment.divide(line, cuts);
918
+ // A widened gap takes the style the words either side of it agree on, and
919
+ // the line's own where they disagree — the reference reads that off the
920
+ // character each side turns towards the gap, which is the offset `at` is
921
+ // given here. A word with no characters turns none and answers with the
922
+ // line's style, which is what two adjacent separators leave between them.
923
+ const edgeStyle = (word, at) => word.filter((segment) => segment.hasText).at(at)?.style ?? base;
924
+ const result = [];
925
+ for (let index = 0; index < words.length; index += 1) {
926
+ result.push(...pieces[index * 2]);
927
+ if (index < gaps) {
928
+ const before = edgeStyle(pieces[index * 2], -1);
929
+ const after = edgeStyle(pieces[index * 2 + 2], 0);
930
+ const style = before.equals(after) ? before : base;
931
+ result.push(new Segment(" ".repeat(spaces[index]), style.isNull ? undefined : style));
932
+ }
933
+ }
934
+ return result;
935
+ }
936
+ /**
937
+ * One wrapped line cut to the canvas.
938
+ *
939
+ * Everything reaching here already survived wrapping, so the only text still
940
+ * too wide is text no break could help: a word longer than the canvas under
941
+ * a non-folding overflow method, a glyph wider than the budget, a canvas
942
+ * with no cells at all, or a `noWrap` line, which no break was allowed to
943
+ * help. That is what makes the overflow method a last resort rather than the
944
+ * first thing a long cell meets. `"fold"` has nothing left to fold here and
945
+ * cuts as `"crop"` does, as the reference's `truncate` does.
946
+ */
947
+ *_fitLine(line, maxWidth, overflow, ellipsis) {
948
+ const lineWidth = Segment.getLineLength(line);
949
+ const contentWidth = lineWidth - hangingWhitespace(line);
950
+ // Whitespace hanging past the edge is the wrap's own padding: cropping it
951
+ // away is not truncation, so it earns no marker. Without this an ellipsis
952
+ // landed on any break that fell a space past the column — the common case
953
+ // in a table, not an edge one.
954
+ if (contentWidth <= maxWidth) {
955
+ yield* Segment.adjustLineLength(line, Math.min(lineWidth, maxWidth), undefined, false);
956
+ return;
957
+ }
958
+ // The marker takes the last cell and the text keeps the rest. At maxWidth 1
959
+ // that is zero cells of text and the marker alone, which is the honest
960
+ // rendering of "all of this was cut"; the `maxWidth > 1` guard that used to
961
+ // stand here emitted no line at all, so every table column squeezed to a
962
+ // single cell rendered blank rather than truncated — `ellipsis` being the
963
+ // default column overflow, a hard-squeezed table looked like an empty frame.
964
+ //
965
+ // At maxWidth 0 there is no cell to put the marker in, so every method
966
+ // yields the same bare empty line. Agreement there is what keeps a
967
+ // `Columns` or `Layout` squeezed to no width at all from rendering
968
+ // three different kinds of nothing.
969
+ if (overflow === "ellipsis" && maxWidth > 0) {
970
+ yield* Segment.adjustLineLength(line, maxWidth - 1, undefined, false);
971
+ yield new Segment(ellipsis);
972
+ return;
973
+ }
974
+ yield* Segment.adjustLineLength(line, maxWidth, undefined, false);
975
+ }
976
+ }