@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/paint.ts ADDED
@@ -0,0 +1,1063 @@
1
+ import * as system from '@yaks/process/system'
2
+ import { visualLines } from './visual.js'
3
+ import { scrollbar } from './scrollbar.js'
4
+ /**
5
+ * The ANSI backend: a tree of fake-DOM nodes becomes lines, and lines become
6
+ * bytes on a terminal.
7
+ *
8
+ * The seam. A `Backend` is `{size, start, draw, reset, stop}` — five calls,
9
+ * the whole contract `run()` knows. `draw(root)` is handed the rendered tree
10
+ * and returns `{written, metrics}`: how many screen lines it actually wrote
11
+ * (diagnostics, and what the snappiness test asserts on) and what it measured
12
+ * while laying out (`{total, height}` per `id`, which is how a scroll region
13
+ * learns how much content it has). Swapping this file for another renderer —
14
+ * OpenTUI's renderable tree, say — means implementing those five, not touching
15
+ * the widgets.
16
+ *
17
+ * Layout is structural attributes, because only the painter knows how wide
18
+ * and tall the terminal is: `row` lays element children side by side
19
+ * (`width` fixed, `grow` takes the rest), `col` stacks them (`grow` takes the
20
+ * leftover rows), `height` fixes a box, and `scroll` windows a box's content
21
+ * from that offset. A class's style in the sheet can say `row`, `col`,
22
+ * `width`, `grow`, `wrap` and `border` as well, and `grid`, which gives every
23
+ * row under it the same columns (./grid.ts); `ellipsis` and `align` say how
24
+ * an element sits in the width it is cut or padded to, as CSS's
25
+ * `text-overflow` and `text-align` do. Everything else flows: block elements
26
+ * stack as lines, inline elements run into them, class names look up the
27
+ * sheet. A form field paints what a browser shows of it: a text field
28
+ * (`input`, `textarea`) its `value`, or its `placeholder` while empty, with a
29
+ * painted cursor at `data-caret`; a checkbox or a radio its mark; a `select`
30
+ * its chosen option.
31
+ *
32
+ * The boundary. Every text node and every href loses the C0/DEL/C1 class
33
+ * before anything is painted (`@yaks/text`'s `safe`, with `\n` kept because a
34
+ * newline inside a text node means a line break here). Every escape the
35
+ * terminal sees is emitted by `ansi()` or by `draw()` — never by content.
36
+ *
37
+ * @module
38
+ */
39
+
40
+ import { safe as strip, safeHref } from '@yaks/text'
41
+ import type { TElement, TNode } from '@yaks/dom'
42
+ import { doc, touch, TText } from '@yaks/dom'
43
+ import { table } from './table.js'
44
+ import { type Track, tracks } from './grid.js'
45
+ import { graphics } from './graphics.js'
46
+ import type { Sheet, Style } from 'jsr:@yaks/ui@0.2.36/sheet'
47
+ import { base, compose } from './theme.js'
48
+ import type { ImageSource } from './Image.ts'
49
+
50
+ /** A run of text under one style. */
51
+ export type Seg = {
52
+ /** Layout decoration, excluded from text selection copies. */
53
+ decorative?: boolean
54
+ /** This segment ends a visual wrap, not a source line break. */
55
+ softBreak?: boolean
56
+ text: string
57
+ style: Style
58
+ owner?: TElement
59
+ image?: {
60
+ source: ImageSource
61
+ row: number
62
+ rows: number
63
+ width: number
64
+ }
65
+ }
66
+
67
+ /** A virtual list's window: the lines it shows at a width and height. */
68
+ export type Viewport = (
69
+ width: number,
70
+ height: number,
71
+ style: Style,
72
+ sheet: Sheet,
73
+ ) => Line[]
74
+
75
+ // What an element paints in place of its children, kept here by the element
76
+ // rather than on it: the DOM is every painter's, and these are the
77
+ // terminal's.
78
+ /** The image an element (`Image`) paints. */
79
+ export let images: WeakMap<TElement, ImageSource> = new WeakMap()
80
+ /** The window a virtual list's element paints. */
81
+ export let viewports: WeakMap<TElement, Viewport> = new WeakMap()
82
+ /** One screen line, as styled runs. */
83
+ export type Line = Seg[]
84
+ /** What a scroll region measured on the last paint, per element id: its
85
+ * content lines, the rows it shows, its width, and the first line of the
86
+ * element inside it marked `reveal`, where one is. */
87
+ export type Metrics = Record<
88
+ string,
89
+ { total: number; height: number; width: number; reveal?: number }
90
+ >
91
+
92
+ /** The five calls `run()` makes of whatever draws the screen. */
93
+ export type Backend = {
94
+ /** Receive an APC/DCS terminal protocol response, never keyboard text. */
95
+ control?: (body: string) => void
96
+ /** The terminal's size, in cells. */
97
+ size: () => { columns: number; rows: number }
98
+ /** Take the screen (alt screen, raw mode's escapes, hidden cursor). */
99
+ start: () => void
100
+ /** Paint the tree; report lines written and what was measured. */
101
+ draw: (
102
+ root: TElement,
103
+ ) => {
104
+ written: number
105
+ metrics: Metrics
106
+ lines?: Line[]
107
+ /** what the sheet hid */
108
+ hidden?: Set<TElement>
109
+ }
110
+ /** Forget what is on screen, so the next draw repaints every line. */
111
+ reset: () => void
112
+ /** Request clipboard write; terminals may deny it. */
113
+ copy?: (text: string) => void
114
+ /** Give the screen back exactly as it was found. */
115
+ stop: () => void
116
+ }
117
+
118
+ // A newline inside a text node is a line break the painter honours, so the
119
+ // text host's boundary is applied per line rather than to the whole string.
120
+ let safe = (text: string) =>
121
+ text.replaceAll('\t', ' ').split('\n').map(strip).join('\n')
122
+
123
+ // Semantic HTML emitted by shared Preact renderers. ANSI stays in this backend.
124
+ // A bare anchor wears the sheet's `Link`; one with a class is a part that
125
+ // says its own look there.
126
+ let semantic = (el: TElement, sheet: Sheet): Style => {
127
+ let tag = el.localName
128
+ if (tag == 'a' && !el.className) return { ...sheet.Link }
129
+ if (tag == 'strong' || tag == 'b' || /^h[1-6]$/.test(tag) || tag == 'th') {
130
+ return { bold: true }
131
+ }
132
+ if (tag == 'em' || tag == 'i') return { italic: true }
133
+ if (tag == 'del') return { strike: true }
134
+ if (tag == 'code' || tag == 'pre') return { ...sheet.Code }
135
+ if (tag == 'blockquote') return { indent: 2, ...sheet.Quote }
136
+ if (tag == 'hr') return { glyph: '────────', dim: true }
137
+ return {}
138
+ }
139
+
140
+ // A link's href is part of its style, however it is laid out: inline, or as
141
+ // a block its sheet makes of it. An href is content too, and it is emitted
142
+ // inside an OSC 8 sequence, where a single BEL byte ends the sequence and lets
143
+ // the rest of the URL be interpreted as terminal input.
144
+ let own = (el: TElement, sheet: Sheet): Style => {
145
+ let out = semantic(el, sheet)
146
+ if (el.className) {
147
+ for (let name of el.className.split(/\s+/)) {
148
+ if (name && sheet[name]) Object.assign(out, sheet[name])
149
+ }
150
+ }
151
+ // The cursor (@yaks/ux/keys) and the focus show as a browser rings them;
152
+ // never a box focused only to hear keys (tabindex -1, a dialog).
153
+ let focused = doc.activeElement == el && el.attr('tabindex') != '-1'
154
+ if (focused || el.attr('data-cursor') != null) out.inverse = true
155
+ let href = el.localName == 'a' && el.attr('href')
156
+ if (href) out.href = safeHref(href)
157
+ return out
158
+ }
159
+
160
+ // Inherit text style down the tree; glyph/indent/gap act only where set.
161
+ let inherit = (parent: Style, node: Style): Style => ({
162
+ fg: node.fg ?? parent.fg,
163
+ bg: node.bg ?? parent.bg,
164
+ bold: node.bold ?? parent.bold,
165
+ dim: node.dim ?? parent.dim,
166
+ italic: node.italic ?? parent.italic,
167
+ underline: node.underline ?? parent.underline,
168
+ strike: node.strike ?? parent.strike,
169
+ inverse: node.inverse ?? parent.inverse,
170
+ href: node.href ?? parent.href,
171
+ })
172
+
173
+ let INLINE = new Set([
174
+ 'span',
175
+ 'br',
176
+ 'b',
177
+ 'i',
178
+ 'strong',
179
+ 'em',
180
+ 'del',
181
+ 'mark',
182
+ 'code',
183
+ 'a',
184
+ 'time',
185
+ 'button',
186
+ 'label',
187
+ 'input',
188
+ 'textarea',
189
+ 'select',
190
+ ])
191
+
192
+ // Whether a node runs into its line: text does, and an inline tag does unless
193
+ // its sheet says `block`.
194
+ let runs = (n: TNode, sheet: Sheet) =>
195
+ n instanceof TText ||
196
+ (INLINE.has((n as TElement).localName) &&
197
+ !(n as TElement).className.split(/\s+/).some((k) => sheet[k]?.block))
198
+
199
+ // `spaced` is for a tree drawn by components written for a browser, whose
200
+ // inline siblings are kept apart by CSS gaps rather than by characters: a space
201
+ // goes between two inline siblings unless one side brings its own, except
202
+ // inside an `Md_Code` run, where every character is the code's. `columns` are
203
+ // the widths a grid gives the rows under it.
204
+ type Ctx = {
205
+ sheet: Sheet
206
+ metrics: Metrics
207
+ spaced?: boolean
208
+ columns?: number[]
209
+ /** what the sheet hid, for elements to say they don't show */
210
+ hidden?: Set<TElement>
211
+ }
212
+
213
+ // What a closed `details` holds but its summary, which a browser does not
214
+ // show until it is opened.
215
+ let shut = (el: TElement) => {
216
+ let up = el.parentNode as TElement | null
217
+ return up?.localName == 'details' && !up.hasAttribute('open') &&
218
+ el.localName != 'summary'
219
+ }
220
+
221
+ // Whether an element shows; one its sheet hides, or a closed `details`, is
222
+ // noted as hidden.
223
+ let shows = (el: TElement, o: Style, c: Ctx) => {
224
+ let hid = o.hidden || shut(el)
225
+ if (hid) c.hidden?.add(el)
226
+ return !hid
227
+ }
228
+
229
+ // Whether a spaced layout puts a space between what a line holds and the run
230
+ // that follows it: when neither side brings its own.
231
+ let apart = (cur: Seg[], next: Seg[]): boolean =>
232
+ !!cur.length && !!next.length && !/\s$/.test(cur[cur.length - 1].text) &&
233
+ !/^\s/.test(next[0].text)
234
+
235
+ let inline = (n: TNode, st: Style, c: Ctx): Seg[] => {
236
+ if (n instanceof TText) {
237
+ let text = safe(n.data)
238
+ return text ? [{ text, style: st, owner: n.parentNode ?? undefined }] : []
239
+ }
240
+ let el = n as TElement
241
+ if (el.localName == 'br') return [{ text: '\n', style: st, owner: el }]
242
+ let o = own(el, c.sheet)
243
+ if (!shows(el, o, c)) return []
244
+ let s = inherit(st, o)
245
+ if (o.glyph) return [{ text: o.glyph, style: s, owner: el }]
246
+ let typed = el.attr('data-caret') != null && el.isContentEditable
247
+ if (el.localName == 'input' || el.localName == 'textarea' || typed) {
248
+ return field(el, s, c)
249
+ }
250
+ if (el.localName == 'select') {
251
+ return [{ text: `${chosen(el)} ▾`, style: s, owner: el }]
252
+ }
253
+ // A block the sheet makes of an element keeps its runs apart, as it would
254
+ // on a line of its own, even where it is painted inline (a `dd`); so does
255
+ // one its sheet spaces, wherever it is painted.
256
+ let spaced = (c.spaced && o.block) || o.spaced
257
+ let out: Seg[] = []
258
+ for (let k of el.childNodes) {
259
+ let segs = inline(k, s, c)
260
+ if (spaced && apart(out, segs)) out.push({ text: ' ', style: s })
261
+ out.push(...segs)
262
+ }
263
+ return out
264
+ }
265
+
266
+ // What a checkbox and a radio show, unchecked and checked.
267
+ let MARKS: Record<string, [string, string]> = {
268
+ checkbox: ['☐', '☑'],
269
+ radio: ['○', '◉'],
270
+ }
271
+
272
+ // A field paints what a browser shows in it: a checkbox or a radio its mark,
273
+ // a password its dots, and any other its value (text typed over in place, its
274
+ // text), its placeholder (dimmed, as the text entry's hint is) while empty,
275
+ // and a painted cursor where `data-caret` puts the caret, since a terminal has
276
+ // no focus to show it by.
277
+ let field = (el: TElement, s: Style, c: Ctx): Seg[] => {
278
+ let type = el.attr('type') ?? 'text'
279
+ let seg = (text: string, style: Style): Seg[] =>
280
+ text ? [{ text, style, owner: el }] : []
281
+ let mark = MARKS[type]
282
+ if (mark) return seg(mark[el.attr('checked') == null ? 0 : 1], s)
283
+ if (!shows(el, { hidden: type == 'hidden' }, c)) return []
284
+ let value = safe(
285
+ el.isContentEditable ? el.textContent : el.attr('value') ?? '',
286
+ )
287
+ if (type == 'password') value = '•'.repeat(value.length)
288
+ let hint = value ? [] : seg(
289
+ safe(el.attr('placeholder') ?? ''),
290
+ inherit(s, c.sheet.Entry_Hint ?? base.Entry_Hint),
291
+ )
292
+ let at = num(el, 'data-caret')
293
+ if (at == null) return value ? seg(value, s) : hint
294
+ at = Math.min(Math.max(0, at), value.length)
295
+ // At the end of the value, or of one of its lines, the cursor is a cell of
296
+ // its own.
297
+ let under = value[at] && value[at] != '\n' ? value[at] : ''
298
+ return [
299
+ ...seg(value.slice(0, at), s),
300
+ ...seg(under || ' ', inherit(s, c.sheet.Cursor ?? base.Cursor)),
301
+ ...seg(value.slice(at + under.length), s),
302
+ ...hint,
303
+ ]
304
+ }
305
+
306
+ // A node's text, sanitized by the same function — a text node's data is never
307
+ // painted raw, whichever branch reaches it.
308
+ let text = (n: TNode): string =>
309
+ n instanceof TText
310
+ ? safe(n.data)
311
+ : (n as TElement).childNodes.map(text).join('')
312
+
313
+ // A select's chosen option, as it shows closed: the one its value names, or
314
+ // the one marked selected, or the first.
315
+ let chosen = (el: TElement): string => {
316
+ let options = kids(el).flatMap((k) =>
317
+ k.localName == 'optgroup' ? kids(k) : [k]
318
+ ).filter((k) => k.localName == 'option')
319
+ let value = el.attr('value')
320
+ let pick = options.find((o) => (o.attr('value') ?? text(o)) == value) ??
321
+ options.find((o) => o.attr('selected') != null) ?? options[0]
322
+ return pick ? text(pick) : ''
323
+ }
324
+
325
+ let kids = (el: TElement) =>
326
+ el.childNodes.filter((n) => !(n instanceof TText)) as TElement[]
327
+
328
+ let num = (el: TElement, k: string) => {
329
+ let v = el.attr(k)
330
+ return v == null || v === '' ? null : +v
331
+ }
332
+
333
+ // How an element is boxed: by its attribute, or by its classes in the sheet,
334
+ // so a part styled for a browser and a terminal alike says its layout where
335
+ // it says its colours.
336
+ let grows = (el: TElement, sheet: Sheet) =>
337
+ el.attr('grow') != null || !!own(el, sheet).grow
338
+ let wide = (el: TElement, sheet: Sheet) =>
339
+ num(el, 'width') ?? own(el, sheet).width ?? null
340
+
341
+ // Block flow: text and inline children run into a line, element children stack.
342
+ // A lone element child inherits the box: a wrapper div is not a layout, so the
343
+ // screen's height reaches the `col` or `row` an app returns from its root.
344
+ let flow = (
345
+ el: TElement,
346
+ s: Style,
347
+ w: number,
348
+ h: number | null,
349
+ c: Ctx,
350
+ o = own(el, c.sheet),
351
+ ): Line[] => {
352
+ let wrapper = kids(el).length == 1 &&
353
+ !el.childNodes.some((n) => runs(n, c.sheet))
354
+ let lines: Line[] = []
355
+ let cur: Seg[] = []
356
+ let flush = () => {
357
+ if (cur.length) lines.push(cur)
358
+ cur = []
359
+ }
360
+ if (el.localName == 'tr') {
361
+ for (let [i, cell] of kids(el).entries()) {
362
+ if (i) cur.push({ text: ' | ', style: s })
363
+ cur.push(...inline(cell, s, c))
364
+ }
365
+ flush()
366
+ return lines
367
+ }
368
+ if (el.localName == 'hr') return [[{ text: '────────', style: s }]]
369
+ if (el.localName == 'dl') {
370
+ // A term and the description after it share a line, `term: description`,
371
+ // as @yaks/text prints them.
372
+ for (let k of kids(el)) {
373
+ if (k.localName == 'dd' && cur.length) {
374
+ cur.push({ text: ' ', style: s }, ...inline(k, s, c))
375
+ flush()
376
+ } else if (k.localName == 'dt') {
377
+ flush()
378
+ cur.push(...inline(k, s, c), { text: ':', style: s })
379
+ } else {
380
+ flush()
381
+ lines.push(...lay(k, s, w, null, c))
382
+ }
383
+ }
384
+ flush()
385
+ return lines
386
+ }
387
+ if (el.localName == 'pre') {
388
+ // A preformatted block keeps its newlines and the styles of what it holds
389
+ // (a highlighter's spans), and paints its allocated width, including
390
+ // blank rows. Keep long lines intact so the enclosing layout retains its
391
+ // wrap policy.
392
+ let rows: Seg[][] = [[]]
393
+ for (let seg of el.childNodes.flatMap((k) => inline(k, s, c))) {
394
+ seg.text.split('\n').forEach((t, i) => {
395
+ if (i) rows.push([])
396
+ if (t) rows.at(-1)!.push({ ...seg, text: t })
397
+ })
398
+ }
399
+ for (let row of rows) {
400
+ let used = row.reduce((n, seg) => n + seg.text.length, 0)
401
+ let pad = ' '.repeat(Math.max(0, w - used))
402
+ let last = row.at(-1)
403
+ lines.push(
404
+ last && alike(last.style, s)
405
+ ? [...row.slice(0, -1), { ...last, text: last.text + pad }]
406
+ : pad || !row.length
407
+ ? [...row, { text: pad, style: s }]
408
+ : row,
409
+ )
410
+ }
411
+ return lines
412
+ }
413
+ let previousParagraph = false
414
+ let spaced = (c.spaced || o.spaced) &&
415
+ !el.className.split(/\s+/).includes('Md_Code')
416
+ for (let n of el.childNodes) {
417
+ // White space opening a line says nothing, as a browser collapses it: the
418
+ // space a tree puts between two blocks for a plain-text reader is no line.
419
+ if (n instanceof TText && !cur.length && !n.data.trim()) continue
420
+ if (runs(n, c.sheet)) {
421
+ let segs = inline(n, s, c)
422
+ if (!segs.length) continue
423
+ previousParagraph = false
424
+ if (spaced && apart(cur, segs)) cur.push({ text: ' ', style: s })
425
+ for (let seg of segs) {
426
+ // Newlines inside a text node are line breaks.
427
+ seg.text.split('\n').forEach((part, i) => {
428
+ if (i) {
429
+ lines.push(cur) // even empty — a blank line is content here
430
+ cur = []
431
+ }
432
+ if (part) cur.push({ ...seg, text: part })
433
+ })
434
+ }
435
+ } else {
436
+ flush()
437
+ // HTML paragraphs have a visual boundary even without literal newlines.
438
+ // Keep it between paragraphs, not after every paragraph/list item.
439
+ let paragraph = (n as TElement).localName == 'p'
440
+ if (paragraph && previousParagraph) lines.push([])
441
+ previousParagraph = paragraph
442
+ lines.push(...lay(n as TElement, s, w, wrapper ? h : null, c))
443
+ }
444
+ }
445
+ flush()
446
+ return lines
447
+ }
448
+
449
+ // Stack element children; `grow` children share whatever rows are left.
450
+ let col = (el: TElement, s: Style, w: number, h: number | null, c: Ctx) => {
451
+ let all = kids(el)
452
+ let fixed = new Map<TElement, Line[]>()
453
+ for (let k of all) {
454
+ if (!grows(k, c.sheet)) fixed.set(k, lay(k, s, w, null, c))
455
+ }
456
+ let used = [...fixed.values()].reduce((n, l) => n + l.length, 0)
457
+ let growers = all.filter((k) => grows(k, c.sheet))
458
+ let left = h == null ? null : Math.max(0, h - used)
459
+ let out: Line[] = []
460
+ if (left != null) {
461
+ let shares = new Map<TElement, number>()
462
+ let fitters = growers.filter((k) => k.attr('grow-fit') != null)
463
+ let fair = Math.floor(left / Math.max(1, growers.length))
464
+ for (let k of fitters) {
465
+ let natural = lay(k, s, w, null, c).length
466
+ let share = Math.min(natural, fair)
467
+ shares.set(k, share)
468
+ left -= share
469
+ }
470
+ let expanding = growers.filter((k) => !shares.has(k))
471
+ expanding.forEach((k, i) => {
472
+ let share = Math.floor(left! / (expanding.length - i))
473
+ shares.set(k, share)
474
+ left! -= share
475
+ })
476
+ for (let k of growers) fixed.set(k, lay(k, s, w, shares.get(k)!, c))
477
+ }
478
+ for (let k of all) out.push(...(fixed.get(k) ?? lay(k, s, w, null, c)))
479
+ return out
480
+ }
481
+
482
+ // Lay element children side by side; `width` is fixed, `grow` takes the rest.
483
+ // Under a grid, the grid's columns say how wide each is instead (`cells`).
484
+ let row = (el: TElement, s: Style, w: number, h: number | null, c: Ctx) => {
485
+ if (c.columns) return cells(el, s, w, h, c)
486
+ let all = kids(el).filter((k) => shows(k, own(k, c.sheet), c))
487
+ let fixed = all.map((k) => wide(k, c.sheet))
488
+ let spare = w - fixed.reduce((n: number, v) => n + (v ?? 0), 0)
489
+ let growers = fixed.filter((v) => v == null).length
490
+ let taken = 0
491
+ let widths = fixed.map((v, i) => {
492
+ if (v != null) return v
493
+ let last = fixed.lastIndexOf(null) == i
494
+ let share = last ? spare - taken : Math.floor(spare / growers)
495
+ taken += share
496
+ return Math.max(0, share)
497
+ })
498
+ let cols = all.map((k, i) => lay(k, s, widths[i], h, c))
499
+ let rows = h ?? Math.max(0, ...cols.map((l) => l.length))
500
+ return Array.from({ length: rows }, (_, y) =>
501
+ all.flatMap((k, i) => {
502
+ let o = own(k, c.sheet)
503
+ let line = clip(cols[i][y] ?? [], widths[i], o.ellipsis)
504
+ // The last column is not padded: the screen's own erase ends the line.
505
+ return i == all.length - 1 ? line : pad(line, widths[i], o.align)
506
+ }))
507
+ }
508
+
509
+ // How far apart a grid's columns stand.
510
+ let GAP = 2
511
+
512
+ // How wide a grid measures a cell's content at: wider than any terminal.
513
+ let MEASURE = 1000
514
+
515
+ // The rows under a grid, through whatever holds them (a head, a body), but
516
+ // not into a row, or a grid of its own.
517
+ let rowsUnder = (el: TElement, sheet: Sheet): TElement[] =>
518
+ kids(el).flatMap((k) =>
519
+ k.attr('row') != null || own(k, sheet).row
520
+ ? [k]
521
+ : own(k, sheet).grid
522
+ ? []
523
+ : rowsUnder(k, sheet)
524
+ )
525
+
526
+ // Lay a grid out: measure every row's cells, column by column, give each
527
+ // column its width (./grid.ts), then lay the grid's children out as they
528
+ // would be, every row under it in those columns.
529
+ let grid = (el: TElement, s: Style, w: number, h: number | null, c: Ctx) => {
530
+ let free = { ...c, columns: undefined }
531
+ let cols: Track[] = []
532
+ for (let r of rowsUnder(el, c.sheet)) {
533
+ kids(r).forEach((k, i) => {
534
+ let t = cols[i] ??= { content: 0 }
535
+ let lines = layout(k, s, MEASURE, null, free)
536
+ t.content = Math.max(
537
+ t.content,
538
+ ...lines.map((l) => l.map((seg) => seg.text).join('').trimEnd().length),
539
+ )
540
+ t.grow ||= grows(k, c.sheet)
541
+ t.width ??= wide(k, c.sheet)
542
+ })
543
+ }
544
+ return flow(el, s, w, h, { ...c, columns: tracks(cols, w, GAP) })
545
+ }
546
+
547
+ // A row under a grid: its cells in the grid's columns, a gap apart, each cut
548
+ // to its column and set to its side of it, and the row's own colours under
549
+ // the whole line, as a subgrid row's background runs under its gaps.
550
+ let cells = (el: TElement, s: Style, w: number, h: number | null, c: Ctx) => {
551
+ let widths = c.columns!
552
+ let free = { ...c, columns: undefined }
553
+ let all = kids(el)
554
+ let laid = all.map((k, i) => owned(k, layout(k, s, widths[i] ?? 0, h, free)))
555
+ let rows = h ?? Math.max(0, ...laid.map((l) => l.length))
556
+ let gap: Seg = { text: ' '.repeat(GAP), style: s, decorative: true }
557
+ return Array.from({ length: rows }, (_, y) =>
558
+ pad(
559
+ all.flatMap((k, i) => {
560
+ let o = own(k, c.sheet)
561
+ let n = widths[i] ?? 0
562
+ let cell = pad(clip(laid[i][y] ?? [], n, o.ellipsis), n, o.align, s)
563
+ return i ? [gap, ...cell] : cell
564
+ }),
565
+ w,
566
+ 'left',
567
+ s,
568
+ ))
569
+ }
570
+
571
+ // The first element under `el` marked `reveal`, and everything under it.
572
+ let mark = (el: TElement): TElement[] | undefined => {
573
+ if (el.attr('reveal') != null) {
574
+ let all: TElement[] = []
575
+ let add = (n: TElement) => (all.push(n), kids(n).forEach(add))
576
+ add(el)
577
+ return all
578
+ }
579
+ for (let k of kids(el)) {
580
+ let found = mark(k)
581
+ if (found) return found
582
+ }
583
+ }
584
+
585
+ // The first of a box's lines that an element marked `reveal` inside it paints,
586
+ // or -1.
587
+ let marked = (box: TElement, lines: Line[]) => {
588
+ let own = new Set(kids(box).flatMap((k) => mark(k) ?? []))
589
+ return own.size
590
+ ? lines.findIndex((l) => l.some((seg) => own.has(seg.owner!)))
591
+ : -1
592
+ }
593
+
594
+ // Window a box's content from its scroll offset, recording what it measured.
595
+ let windowed = (
596
+ el: TElement,
597
+ lines: Line[],
598
+ h: number | null,
599
+ c: Ctx,
600
+ width: number,
601
+ ) => {
602
+ let height = h ?? lines.length
603
+ let id = el.attr('id')
604
+ if (id) {
605
+ let reveal = marked(el, lines)
606
+ c.metrics[id] = {
607
+ total: lines.length,
608
+ height,
609
+ width,
610
+ ...reveal < 0 ? {} : { reveal },
611
+ }
612
+ }
613
+ let top = Math.min(
614
+ Math.max(0, num(el, 'scroll') ?? 0),
615
+ Math.max(0, lines.length - height),
616
+ )
617
+ return lines.slice(top, top + height)
618
+ }
619
+
620
+ /** The lines an element becomes, given a content width and allotted rows. */
621
+ let layout = (
622
+ el: TElement,
623
+ st: Style,
624
+ w: number,
625
+ h: number | null,
626
+ c: Ctx,
627
+ o = own(el, c.sheet),
628
+ ): Line[] => {
629
+ let image = images.get(el)
630
+ if (image) {
631
+ let rows = Math.max(1, Math.min(16, Math.floor(image.rows) || 8))
632
+ return Array.from({ length: rows }, (_, row) => [{
633
+ text: row == 0
634
+ ? safe(image.alt).replaceAll('\n', ' ').slice(0, w).padEnd(w)
635
+ : ' '.repeat(w),
636
+ style: st,
637
+ owner: el,
638
+ image: { source: image, row, rows, width: w },
639
+ }])
640
+ }
641
+ let selected = visualLines(el.attr('id') ?? '', w, h ?? 6)
642
+ if (selected) return selected
643
+ let viewport = viewports.get(el)
644
+ if (viewport) return viewport(w, h ?? 0, st, c.sheet)
645
+ let s = inherit(st, o)
646
+ if (el.localName == 'svg') {
647
+ return o.glyph ? [[{ text: o.glyph, style: s, owner: el }]] : []
648
+ }
649
+ let wraps = el.attr('wrap') != null || !!o.wrap
650
+ let outer = num(el, 'height') ?? h
651
+ // Borders consume real layout space; descendants measure the inner width.
652
+ let border = el.attr('border') ?? o.border
653
+ let framed = border != null && w >= 3
654
+ let box = outer == null ? null : Math.max(0, outer - (framed ? 2 : 0))
655
+ let bar = el.attr('scrollbar') != null && el.attr('scroll') != null &&
656
+ w - (o.indent ?? 0) - (framed ? 2 : 0) >= 2
657
+ let contentWidth = Math.max(
658
+ 0,
659
+ w - (o.indent ?? 0) - (framed ? 2 : 0) - (bar ? 1 : 0),
660
+ )
661
+ let lines = el.matches('input,textarea,select')
662
+ ? [inline(el, st, c)]
663
+ : el.localName == 'table'
664
+ ? table(
665
+ el,
666
+ contentWidth,
667
+ s,
668
+ c.sheet,
669
+ (cell, width) => {
670
+ let ancestors: TElement[] = []
671
+ for (
672
+ let node = cell.parentNode;
673
+ node && node !== el;
674
+ node = node.parentNode
675
+ ) {
676
+ ancestors.unshift(node)
677
+ }
678
+ let inherited = ancestors.reduce(
679
+ (style, node) => inherit(style, own(node, c.sheet)),
680
+ s,
681
+ )
682
+ return lay(cell, inherited, width, null, c)
683
+ },
684
+ wrap,
685
+ )
686
+ : o.grid
687
+ ? grid(el, s, contentWidth, box, c)
688
+ : el.attr('row') != null || o.row
689
+ ? row(el, s, contentWidth, box, c)
690
+ : el.attr('col') != null || o.col
691
+ ? col(el, s, contentWidth, box, c)
692
+ : flow(
693
+ el,
694
+ s,
695
+ contentWidth,
696
+ wraps || el.attr('scroll') != null ? null : box,
697
+ c,
698
+ o,
699
+ )
700
+ if (el.localName == 'summary' && lines.length) {
701
+ // The mark a browser puts before a summary: whether it is open.
702
+ let open = (el.parentNode as TElement | null)?.hasAttribute('open')
703
+ lines = [
704
+ [{ text: open ? '▾ ' : '▸ ', style: s }, ...lines[0]],
705
+ ...lines.slice(1),
706
+ ]
707
+ }
708
+ if (el.localName == 'li') {
709
+ let marker = safe(el.attr('data-marker') ?? '• ')
710
+ lines = lines.map((
711
+ line,
712
+ i,
713
+ ) => [{ text: i ? ' '.repeat(marker.length) : marker, style: s }, ...line])
714
+ }
715
+ if (wraps) {
716
+ lines = lines.flatMap((line) => wrap(line, contentWidth))
717
+ }
718
+ const maximum = num(el, 'max-height')
719
+ if (maximum != null && maximum >= 0 && lines.length > maximum) {
720
+ lines = lines.slice(0, maximum)
721
+ const overflow = el.attr('overflow-text')
722
+ if (overflow) lines.push([{ text: safe(overflow), style: s }])
723
+ }
724
+ if (el.attr('scroll') != null) {
725
+ let total = lines.length
726
+ lines = windowed(el, lines, box, c, contentWidth)
727
+ if (bar) {
728
+ lines = scrollbar(lines, contentWidth + 1, {
729
+ total,
730
+ height: box ?? total,
731
+ top: Math.min(
732
+ Math.max(0, total - (box ?? total)),
733
+ Math.max(0, num(el, 'scroll') ?? 0),
734
+ ),
735
+ bottom: el.attr('scroll-snapped') != null,
736
+ }, c.sheet)
737
+ }
738
+ }
739
+ if (o.indent) {
740
+ lines = lines.map((
741
+ l,
742
+ ) => [{ text: ' '.repeat(o.indent!), style: s, decorative: true }, ...l])
743
+ }
744
+ if (o.gap && lines.length) lines.push([])
745
+ if (box != null) lines = fit(lines, box)
746
+ if (framed) {
747
+ let edge = c.sheet[border!] ?? {}
748
+ let rule = (left: string, right: string): Line => [{
749
+ text: left + '─'.repeat(Math.max(0, w - 2)) + right,
750
+ style: edge,
751
+ decorative: true,
752
+ }]
753
+ lines = [
754
+ rule('╭', '╮'),
755
+ ...lines.map((line): Line => [
756
+ { text: '│', style: edge, decorative: true },
757
+ ...pad(clip(line, w - 2), w - 2),
758
+ { text: '│', style: edge, decorative: true },
759
+ ]),
760
+ rule('╰', '╯'),
761
+ ]
762
+ }
763
+ if (el.attr('fill') != null) {
764
+ lines = lines.map((line) => {
765
+ let clipped = clip(line, w)
766
+ let remaining = Math.max(
767
+ 0,
768
+ w - clipped.reduce((n, part) => n + part.text.length, 0),
769
+ )
770
+ return [...clipped, {
771
+ text: ' '.repeat(remaining),
772
+ style: s,
773
+ decorative: true,
774
+ }]
775
+ })
776
+ }
777
+ return outer == null ? lines : fit(lines, outer)
778
+ }
779
+
780
+ /** Ownership travels with the painted cells through windowing, wrapping and clipping. */
781
+ export let lay = (
782
+ el: TElement,
783
+ st: Style,
784
+ w: number,
785
+ h: number | null,
786
+ c: Ctx,
787
+ ): Line[] => {
788
+ let o = own(el, c.sheet)
789
+ if (!shows(el, o, c)) return []
790
+ let boxed = viewports.has(el) || el.attr('scroll') != null ||
791
+ num(el, 'width') != null || o.width != null ||
792
+ el.attr('grow') != null || o.grow
793
+ let lines = layout(el, st, w, h, c, o)
794
+ return owned(
795
+ el,
796
+ boxed ? lines.map((l) => pad(clip(l, w, o.ellipsis), w, o.align)) : lines,
797
+ )
798
+ }
799
+
800
+ // Every cell an element painted is its own, unless something under it
801
+ // claimed it first; a viewport's are all its own.
802
+ let owned = (el: TElement, lines: Line[]): Line[] =>
803
+ lines.map((line) =>
804
+ line.map((seg) =>
805
+ !viewports.has(el) && seg.owner ? seg : { ...seg, owner: el }
806
+ )
807
+ )
808
+
809
+ let fit = (lines: Line[], h: number): Line[] =>
810
+ lines.length >= h
811
+ ? lines.slice(0, h)
812
+ : [...lines, ...Array.from({ length: h - lines.length }, () => [] as Line)]
813
+
814
+ let width = (l: Line) => l.reduce((n, s) => n + s.text.length, 0)
815
+
816
+ // Fill a line out to `w` columns in `style`, the line set to `align`'s side.
817
+ let pad = (
818
+ l: Line,
819
+ w: number,
820
+ align: Style['align'] = 'left',
821
+ style: Style = {},
822
+ ): Line => {
823
+ let n = w - width(l)
824
+ if (n <= 0) return l
825
+ let before = align == 'right' ? n : align == 'center' ? n >> 1 : 0
826
+ let fill = (k: number): Line =>
827
+ k ? [{ text: ' '.repeat(k), style, decorative: true }] : []
828
+ return [...fill(before), ...l, ...fill(n - before)]
829
+ }
830
+
831
+ /// let texts = (l: Line) => l.map((s) => s.text)
832
+ /// let line = [{ text: 'hello ', style: {} }, { text: 'world', style: {} }]
833
+ /// texts(clip(line, 8)) -> ['hello ', 'wo']
834
+ /// texts(clip(line, 8, true)) -> ['hello ', 'w', '…']
835
+ /// texts(clip(line, 11, true)) -> ['hello ', 'world']
836
+ /** Cut a line to a column count, keeping whole segments where it can; with
837
+ * `ellipsis`, a line that is cut ends in `…`. */
838
+ export let clip = (line: Line, w: number, ellipsis = false): Line => {
839
+ if (ellipsis && w > 0 && width(line) > w) {
840
+ let out = clip(line, w - 1)
841
+ let { style, owner } = out.at(-1) ?? line[0]
842
+ return [...out, { text: '…', style, owner }]
843
+ }
844
+ let out: Line = []
845
+ let len = 0
846
+ for (let s of line) {
847
+ if (len + s.text.length <= w) {
848
+ out.push(s)
849
+ len += s.text.length
850
+ } else {
851
+ if (w > len) out.push({ ...s, text: s.text.slice(0, w - len) })
852
+ break
853
+ }
854
+ }
855
+ return out
856
+ }
857
+
858
+ /** Fold at word boundaries (hard-fold long words), preserving every styled
859
+ * character. Uses the same column units as clip; runs before scroll measures. */
860
+ export let wrap = (line: Line, columns: number): Line[] => {
861
+ let w = Math.floor(columns)
862
+ if (w <= 0) return [[]]
863
+ let text = line.map((s) => s.text).join('')
864
+ if (text.length <= w) return [line]
865
+ let out: Line[] = []
866
+ let start = 0, seg = 0, offset = 0
867
+ while (start < text.length) {
868
+ let end = Math.min(start + w, text.length)
869
+ if (end < text.length) {
870
+ let space = text.slice(start, end).lastIndexOf(' ')
871
+ if (space >= 0) end = start + space + 1
872
+ }
873
+ let row: Line = []
874
+ let left = end - start
875
+ while (left > 0 && seg < line.length) {
876
+ let s = line[seg]
877
+ let n = Math.min(left, s.text.length - offset)
878
+ if (n) {
879
+ row.push({ ...s, text: s.text.slice(offset, offset + n) })
880
+ }
881
+ left -= n
882
+ offset += n
883
+ if (offset == s.text.length) {
884
+ seg++
885
+ offset = 0
886
+ }
887
+ }
888
+ if (end < text.length && row.length) {
889
+ row[row.length - 1] = { ...row.at(-1)!, softBreak: true }
890
+ }
891
+ out.push(row)
892
+ start = end
893
+ }
894
+ return out
895
+ }
896
+
897
+ let rgb = (hex: string) =>
898
+ [hex.slice(1, 3), hex.slice(3, 5), hex.slice(5, 7)].map((h) =>
899
+ parseInt(h, 16)
900
+ )
901
+
902
+ // Whether two styles paint alike, so a run in one can carry on in the other.
903
+ let alike = (a: Style, b: Style) =>
904
+ ansi([{ text: '', style: a }]) == ansi([{ text: '', style: b }])
905
+
906
+ /** The bytes a line becomes — every escape the terminal sees is emitted here. */
907
+ export let ansi = (line: Line): string =>
908
+ line.map((s) => {
909
+ let codes: string[] = []
910
+ if (s.style.fg) codes.push(`38;2;${rgb(s.style.fg).join(';')}`)
911
+ if (s.style.bg) codes.push(`48;2;` + rgb(s.style.bg).join(';'))
912
+ if (s.style.bold) codes.push('1')
913
+ if (s.style.dim) codes.push('2')
914
+ if (s.style.italic) codes.push('3')
915
+ if (s.style.underline) codes.push('4')
916
+ if (s.style.inverse) codes.push('7')
917
+ if (s.style.strike) codes.push('9')
918
+ let t = codes.length ? `\x1b[${codes.join(';')}m${s.text}\x1b[0m` : s.text
919
+ return s.style.href // OSC 8: the terminal makes it clickable
920
+ ? `\x1b]8;;${s.style.href}\x07${t}\x1b]8;;\x07`
921
+ : t
922
+ }).join('')
923
+
924
+ /** The whole screen a tree produces at a given size — the function the tests
925
+ * assert against. */
926
+ export let screenful = (
927
+ root: TElement,
928
+ columns: number,
929
+ rows: number,
930
+ sheet: Sheet = {},
931
+ ): { lines: Line[]; metrics: Metrics; hidden: Set<TElement> } => {
932
+ let c: Ctx = { sheet: compose(sheet), metrics: {}, hidden: new Set() }
933
+ let lines = lay(root, {}, columns, rows, c)
934
+ return { lines, metrics: c.metrics, hidden: c.hidden! }
935
+ }
936
+
937
+ /** A tree painted once, as tall as it is, for a command that prints and exits:
938
+ * the layout and escapes a held screen gets, folded at word boundaries to the
939
+ * terminal's width, with no screen kept. `sheet` extends {@link base}, as it
940
+ * does for {@link ansiBackend}. */
941
+ export let printout = (
942
+ root: TElement,
943
+ columns: number,
944
+ sheet: Sheet = {},
945
+ ): string => {
946
+ let lines = lay(root, {}, columns, null, {
947
+ sheet: compose(sheet),
948
+ metrics: {},
949
+ }).flatMap((line) => wrap(line, columns))
950
+ while (lines.length && !width(lines.at(-1)!)) lines.pop()
951
+ return lines.map((line) => ansi(line).trimEnd()).join('\n')
952
+ }
953
+
954
+ let enc = new TextEncoder()
955
+
956
+ /**
957
+ * OSC 52: hand text to the clipboard through the terminal — the escape travels
958
+ * the tty like any output, so it works across ssh (tmux needs set-clipboard on).
959
+ */
960
+ export let clipboard = (text: string): string =>
961
+ `\x1b]52;c;${
962
+ btoa(Array.from(enc.encode(text), (b) => String.fromCharCode(b)).join(''))
963
+ }\x07`
964
+
965
+ // A DEC private mode the terminal may already have set (a parent app's mouse,
966
+ // its focus reports): saved before it is set, and on the way out reset and
967
+ // then restored. A terminal that keeps saved modes gets back what it had; one
968
+ // that ignores save and restore (tmux among them) is left with it off, never
969
+ // still on.
970
+ let saved = (n: number): [string, string] => [
971
+ `\x1b[?${n}s\x1b[?${n}h`,
972
+ `\x1b[?${n}l\x1b[?${n}r`,
973
+ ]
974
+
975
+ /**
976
+ * Every mode the ANSI backend turns on, as `[on, off]`: `start` writes each
977
+ * `on` in order and `stop` each `off` in reverse, so the terminal is given
978
+ * back as it was found.
979
+ */
980
+ export let MODES: [on: string, off: string][] = [
981
+ ['\x1b[?1049h', '\x1b[?1049l'], // alt screen
982
+ ['\x1b[?25l', '\x1b[?25h'], // hidden cursor
983
+ ['\x1b[?2004h', '\x1b[?2004l'], // bracketed paste
984
+ ['\x1b[?1007h', '\x1b[?1007l'], // alternate scroll: the wheel as arrow keys
985
+ saved(1004), // focus reports
986
+ saved(1000), // mouse clicks and wheel
987
+ saved(1006), // mouse reported as SGR
988
+ ['\x1b[>4;2m', '\x1b[>4;0m'], // modifyOtherKeys
989
+ // kitty disambiguate: without it the terminal collapses Shift+Enter to CR
990
+ ['\x1b[>1u', '\x1b[<u'],
991
+ ]
992
+
993
+ /**
994
+ * The ANSI backend. Paints only the lines that changed since the last frame:
995
+ * a keystroke moves one line, so a keystroke writes one line. `size` and
996
+ * `write` are injected so a test can drive it without a terminal. A `sheet`
997
+ * given as a function is read at every paint, so the theme can change while
998
+ * the app runs.
999
+ */
1000
+ export let ansiBackend = (opts: {
1001
+ sheet?: Sheet | (() => Sheet)
1002
+ size?: () => { columns: number; rows: number }
1003
+ write?: (s: string) => void
1004
+ graphics?: 'kitty' | 'none'
1005
+ tmux?: boolean
1006
+ } = {}): Backend => {
1007
+ let pictures = graphics({
1008
+ enabled: opts.graphics == 'kitty',
1009
+ tmux: opts.tmux,
1010
+ changed: touch,
1011
+ })
1012
+ let sheet = () => typeof opts.sheet == 'function' ? opts.sheet() : opts.sheet
1013
+ let size = opts.size ?? (() => system.consoleSize())
1014
+ let write = opts.write ??
1015
+ ((s: string) => void system.stdout.writeSync(enc.encode(s)))
1016
+ let last: string[] = []
1017
+ return {
1018
+ size,
1019
+ copy: (text) => write(osc52(text)),
1020
+ control: pictures.reply,
1021
+ start: () => write(MODES.map(([on]) => on).join('')),
1022
+ stop: () =>
1023
+ write(pictures.close() + MODES.map(([, off]) => off).reverse().join('')),
1024
+ reset: () => {
1025
+ last = []
1026
+ pictures.reset()
1027
+ },
1028
+ draw: (root) => {
1029
+ let { columns, rows } = size()
1030
+ let { lines, metrics, hidden } = screenful(root, columns, rows, sheet())
1031
+ let annotated = pictures.annotate(lines)
1032
+ let out = ''
1033
+ let written = 0
1034
+ for (let y = 0; y < rows; y++) {
1035
+ let s = ansi(clip(annotated[y] ?? [], columns))
1036
+ if (s === last[y]) continue
1037
+ last[y] = s
1038
+ out += `\x1b[${y + 1};1H${s}\x1b[K`
1039
+ written++
1040
+ }
1041
+ last.length = rows
1042
+ out += pictures.draw(
1043
+ lines.slice(0, rows).map((line) => clip(line, columns)),
1044
+ !!out,
1045
+ )
1046
+ if (out) write(out)
1047
+ return {
1048
+ written,
1049
+ metrics,
1050
+ hidden,
1051
+ lines: lines.slice(0, rows).map((line) => clip(line, columns)),
1052
+ }
1053
+ },
1054
+ }
1055
+ }
1056
+
1057
+ /** Clipboard bytes are base64, never interpolated as terminal controls. */
1058
+ export let osc52 = (text: string): string => {
1059
+ let bytes = new TextEncoder().encode(text)
1060
+ let binary = ''
1061
+ for (let b of bytes) binary += String.fromCharCode(b)
1062
+ return '\x1b]52;c;' + btoa(binary) + '\x07'
1063
+ }