dsh-oc-tui 0.1.4 → 0.2.0-pre.13

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.
package/lib/term.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { spawn } from 'node:child_process'
5
5
  import { EventEmitter } from 'node:events'
6
6
  import { runeWidth, truncateWidth, fitWidth } from './util.js'
7
+ import { encodeKittyTransmission, kittyPlacement, kittyDelete, kittyDeleteAll, encodeITerm2 } from './image.js'
7
8
 
8
9
  // ---- ANSI helpers -------------------------------------------------------
9
10
 
@@ -18,7 +19,8 @@ export function hexToAnsi(hex) {
18
19
  }
19
20
 
20
21
  // Immutable-ish style bundle: { fg, bg (hex or null), bold, dim, italic,
21
- // underline }. Merges by producing a new object.
22
+ // underline, link (sanitized OSC 8 url or undefined) }. Merges by producing a
23
+ // new object.
22
24
  export function makeStyle(partial = {}) {
23
25
  return {
24
26
  fg: partial.fg ?? null,
@@ -27,6 +29,7 @@ export function makeStyle(partial = {}) {
27
29
  dim: partial.dim ?? false,
28
30
  italic: partial.italic ?? false,
29
31
  underline: partial.underline ?? false,
32
+ link: partial.link,
30
33
  }
31
34
  }
32
35
 
@@ -38,9 +41,21 @@ export function mergeStyle(base, over) {
38
41
  dim: over.dim ?? base.dim ?? false,
39
42
  italic: over.italic ?? base.italic ?? false,
40
43
  underline: over.underline ?? base.underline ?? false,
44
+ link: over.link ?? base.link,
41
45
  }
42
46
  }
43
47
 
48
+ // URLs painted into cells are emitted later as OSC 8 hyperlinks — raw paint
49
+ // output — so they get the same trust boundary as cell characters: only
50
+ // http(s)/file schemes, no control characters, parens percent-encoded so the
51
+ // OSC terminator logic can never be confused by the URL body.
52
+ export function safeLink(url) {
53
+ if (typeof url !== 'string' || url.length === 0 || url.length > 2048) return null
54
+ if (/[\u0000-\u001f\u007f-\u009f]/.test(url)) return null
55
+ if (!/^(https?:\/\/|file:\/\/)/i.test(url)) return null
56
+ return url.replace(/[()]/g, (ch) => '%' + ch.charCodeAt(0).toString(16).toUpperCase())
57
+ }
58
+
44
59
  function styleAnsi(style) {
45
60
  const parts = []
46
61
  if (style.bold) parts.push('1')
@@ -84,6 +99,11 @@ export class Screen {
84
99
  this.cols = cols
85
100
  this.rows = rows
86
101
  this.cells = []
102
+ // Image annotations for the current frame: rows whose cells stand in for
103
+ // graphics-protocol output (kitty placement / sixel / iTerm2 payloads
104
+ // emitted by Terminal.paint). Text cells stay blank so the diffing engine
105
+ // and the width invariant keep working unchanged.
106
+ this.images = []
87
107
  for (let y = 0; y < rows; y++) {
88
108
  const row = []
89
109
  for (let x = 0; x < cols; x++) row.push({ ch: ' ', style: null })
@@ -117,6 +137,12 @@ export class Screen {
117
137
 
118
138
  set(x, y, ch, style = null) {
119
139
  if (x < 0 || y < 0 || x >= this.cols || y >= this.rows) return
140
+ // A link on a style is paint output, not cell text: sanitize it once here
141
+ // so paint() can emit it verbatim as OSC 8.
142
+ if (style?.link) {
143
+ const link = safeLink(style.link)
144
+ style = { ...style, link: link ?? undefined }
145
+ }
120
146
  this.cells[y][x] = { ch: cellCharacter(ch), style }
121
147
  }
122
148
 
@@ -145,6 +171,13 @@ export class Screen {
145
171
  for (let i = 0; i < width; i++) this.set(x + i, y, ch, style)
146
172
  }
147
173
 
174
+ // Record that the cell area of an image starts at row `y` (top: true only on
175
+ // the image's first row, carrying the full placement info).
176
+ setImageRow(y, info) {
177
+ if (y < 0 || y >= this.rows) return
178
+ if (info?.top) this.images.push({ ...info, y })
179
+ }
180
+
148
181
  // Fill an entire row to its right edge (used to keep background continuous).
149
182
  fillToEnd(x, y, style = null) {
150
183
  this.fill(x, y, Math.max(0, this.cols - x), ' ', style)
@@ -154,14 +187,17 @@ export class Screen {
154
187
  // bg null) the given default background. Without this, fg-only styles
155
188
  // (markdown text, row tail fills) emit no background SGR and the terminal
156
189
  // falls back to its own default background - usually black - instead of
157
- // the app canvas.
190
+ // the app canvas. `== null` rather than `=== null`: Screen.text stores the
191
+ // style object it is handed verbatim, so a caller that builds the style
192
+ // inline instead of through makeStyle leaves the key absent (undefined)
193
+ // rather than null, and those cells would keep the black background.
158
194
  defaultBackground(hex) {
159
195
  for (let y = 0; y < this.rows; y++) {
160
196
  const row = this.cells[y]
161
197
  for (let x = 0; x < this.cols; x++) {
162
198
  const cell = row[x]
163
199
  if (cell.style === null) cell.style = makeStyle({ bg: hex })
164
- else if (cell.style.bg === null) cell.style = mergeStyle(cell.style, { bg: hex })
200
+ else if (cell.style.bg == null) cell.style = mergeStyle(cell.style, { bg: hex })
165
201
  }
166
202
  }
167
203
  }
@@ -181,6 +217,15 @@ const CTRL_NAMES = {
181
217
  '\x16': 'v', '\x17': 'w', '\x18': 'x', '\x19': 'y', '\x1a': 'z',
182
218
  }
183
219
 
220
+ // xterm-style modifier parameter of `CSI 1;<mods>` final sequences. The
221
+ // parameter is 1+bitmask (shift=1, alt=2, ctrl=4), so the bits are `mods-1`.
222
+ // Arrows arrive with the parameter whenever a modifier is held; without one
223
+ // they stay plain.
224
+ function csiModifierFlags(param) {
225
+ const bits = Math.max(0, (Number(String(param ?? '').split(';')[1]) || 1) - 1)
226
+ return { shift: (bits & 1) !== 0, alt: (bits & 2) !== 0, ctrl: (bits & 4) !== 0 }
227
+ }
228
+
184
229
  // Decode one key event from a raw-mode byte buffer. Returns { key } or null
185
230
  // when more bytes are needed.
186
231
  export function decodeKey(input) {
@@ -242,7 +287,7 @@ export function decodeKey(input) {
242
287
  }
243
288
  // Legacy X10 mouse (no SGR): ESC [ M <button+32> <x+32> <y+32>.
244
289
  // Without this, wheel/click bytes that follow \x1b[M would be misread as
245
- // printable text and inserted into the composer.
290
+ // printable text and inserted into the input text.
246
291
  if (s.startsWith('\x1b[M')) {
247
292
  if (input.length < 6) return null
248
293
  const b = input[3] - 32
@@ -266,16 +311,56 @@ export function decodeKey(input) {
266
311
  }
267
312
  }
268
313
  if (s.startsWith('\x1b[<')) return null
314
+ // Terminal replies. Probes (capability detection) and in-band queries make
315
+ // the client terminal answer on stdin; every answer must be consumed as a
316
+ // reply event or it leaks into the composer as garbage keys. A reply
317
+ // without its ST/BEL terminator yet waits for more bytes.
318
+ if (s.startsWith('\x1bP')) {
319
+ const dcs = /^\x1bP([^]*?)(?:\x1b\\|\x07)/.exec(s)
320
+ if (!dcs) return null
321
+ return { key: { name: 'terminal-reply', reply: { kind: 'dcs', body: dcs[1] } }, consumed: dcs[0].length }
322
+ }
323
+ if (s.startsWith('\x1b_')) {
324
+ const apc = /^\x1b_([^]*?)(?:\x1b\\|\x07)/.exec(s)
325
+ if (!apc) return null
326
+ return { key: { name: 'terminal-reply', reply: { kind: 'apc', body: apc[1] } }, consumed: apc[0].length }
327
+ }
328
+ if (s.startsWith('\x1b]')) {
329
+ const osc = /^\x1b\]([^]*?)(?:\x1b\\|\x07)/.exec(s)
330
+ if (!osc) return null
331
+ return { key: { name: 'terminal-reply', reply: { kind: 'osc', body: osc[1] } }, consumed: osc[0].length }
332
+ }
333
+ // CSI report forms: DA1 attributes ('?...c'), XTWINOPS reports ('...t'),
334
+ // CPR ('...R'), kitty keyboard attributes ('?...u'). The '?'-prefixed 'c'
335
+ // and 'u' finals are replies — bare 'c'/'u' finals are keyboard key events
336
+ // (Ctrl+Enter arrives as CSI 13;5u) and must keep falling through to the
337
+ // key decoder below.
338
+ const report = /^\x1b\[(\??[0-9;:?<>=]*)([cRtu])/.exec(s)
339
+ if (report) {
340
+ const params = report[1]
341
+ const final = report[2]
342
+ const isReplyish = params.startsWith('?') || final === 'R' || final === 't'
343
+ if (isReplyish) {
344
+ let kind = 'unknown'
345
+ if (final === 'c') kind = 'da1'
346
+ else if (final === 't') kind = /^8;\d+;\d+$/.test(params) ? 'windowops' : 'unknown'
347
+ return { key: { name: 'terminal-reply', reply: { kind, body: params } }, consumed: report[0].length }
348
+ }
349
+ }
350
+ // A CSI sequence that has not reached its final byte yet: keep waiting
351
+ // instead of decoding a prefix (a partial DA1 reply would otherwise fall
352
+ // through to the alt-key path below and type "?62" into the composer).
353
+ if (/^\x1b\[[0-9;:?<>=]*$/.test(s)) return null
269
354
  const m = /^\x1b\[([0-9;]*)([A-Za-z~])/.exec(s)
270
355
  if (m) {
271
356
  const param = m[1]
272
357
  const final = m[2]
273
358
  const consumed = m[0].length
274
359
  if (consumed > input.length) return null
275
- if (final === 'A') return { key: { name: 'up' }, consumed }
276
- if (final === 'B') return { key: { name: 'down' }, consumed }
277
- if (final === 'C') return { key: { name: 'right' }, consumed }
278
- if (final === 'D') return { key: { name: 'left' }, consumed }
360
+ if (final === 'A') return { key: { name: 'up', ...csiModifierFlags(param) }, consumed }
361
+ if (final === 'B') return { key: { name: 'down', ...csiModifierFlags(param) }, consumed }
362
+ if (final === 'C') return { key: { name: 'right', ...csiModifierFlags(param) }, consumed }
363
+ if (final === 'D') return { key: { name: 'left', ...csiModifierFlags(param) }, consumed }
279
364
  if (final === 'H') return { key: { name: 'home' }, consumed }
280
365
  if (final === 'F') return { key: { name: 'end' }, consumed }
281
366
  if (final === 'Z') return { key: { name: 'shift-tab' }, consumed }
@@ -351,6 +436,16 @@ export class Terminal extends EventEmitter {
351
436
  this._buffer = Buffer.alloc(0)
352
437
  this.cols = output.columns || 80
353
438
  this.rows = output.rows || 24
439
+ // Graphics state, filled in by the app: caps from lib/caps.js probing,
440
+ // payload registry keyed by image hash (App renders payloads through
441
+ // lib/image.js and hands them here). With caps unset, paint() is pure
442
+ // text — halfblock images need no protocol output at all.
443
+ this.caps = null
444
+ this._imagePayloads = new Map()
445
+ this._kittyIds = new Map()
446
+ this._kittyNextId = 1
447
+ this._kittySent = new Set()
448
+ this._prevImageRows = []
354
449
  this._onData = (chunk) => this._handleData(chunk)
355
450
  this._onResize = () => {
356
451
  this.cols = this.output.columns || this.cols
@@ -363,6 +458,13 @@ export class Terminal extends EventEmitter {
363
458
  return Boolean(this.input.isTTY && this.output.isTTY)
364
459
  }
365
460
 
461
+ // Release one image payload. The view model drops the cropped variants it no
462
+ // longer shows — each holds an encoded raster, and a payload that outlives its
463
+ // placement would be re-transmitted the moment its key comes back.
464
+ dropImagePayload(key) {
465
+ this._imagePayloads.delete(key)
466
+ }
467
+
366
468
  start() {
367
469
  if (this.started) return
368
470
  this.started = true
@@ -386,6 +488,13 @@ export class Terminal extends EventEmitter {
386
488
  this.started = false
387
489
  this.input.off('data', this._onData)
388
490
  this.output.off('resize', this._onResize)
491
+ // Kitty images live in the terminal's own storage and would otherwise
492
+ // outlive the alt screen they were placed on.
493
+ if (this.caps?.kitty) this.write(kittyDeleteAll())
494
+ this._kittyIds.clear()
495
+ this._kittySent.clear()
496
+ this._imagePayloads.clear()
497
+ this._prevImageRows = []
389
498
  if (this.input.isTTY) {
390
499
  this.input.setRawMode(false)
391
500
  this.input.pause()
@@ -479,6 +588,44 @@ export class Terminal extends EventEmitter {
479
588
  }
480
589
  const prev = this._prev
481
590
  const W = screen.cols
591
+ // A graphics image is not text: it is pixel payload the terminal drew into
592
+ // the text grid, and any text write over those cells erases it. That cuts
593
+ // both ways, so the two cases are kept apart:
594
+ // - a row the previous frame showed an image on, that the SAME image no
595
+ // longer covers, must be force-rewritten: only a text rewrite clears
596
+ // the pixels an image leaves behind when it moves, shrinks, or scrolls
597
+ // away (_paintImages has no delete to send, unlike the kitty path);
598
+ // - a row the image still covers must not be, unless the payload is
599
+ // re-emitted right after the rewrite (rewrittenImageRows below) —
600
+ // otherwise a stationary image is erased by the very frames that render
601
+ // around it, and never comes back.
602
+ // "Still covers" has to mean the same cells, not just the same row: an
603
+ // image re-rendered narrower (or taller) keeps every one of its rows but
604
+ // vacates cells inside them, and those vacated cells would never see a
605
+ // text write. They keep whatever the wider footprint drew — the image
606
+ // looks wider than the text it sits beside, with a stale strip down its
607
+ // right hand edge. So the key carries the position and size as well as the
608
+ // row, and any change to any of them counts as "no longer covered".
609
+ const covered = new Set()
610
+ for (const img of screen.images) {
611
+ for (let i = 0; i < img.cellsH; i++) {
612
+ covered.add(img.key + ':' + img.x + ':' + img.cellsW + ':' + img.cellsH + ':' + (img.y + i))
613
+ }
614
+ }
615
+ const dirtyRows = new Set()
616
+ for (const img of this._prevImageRows) {
617
+ for (let i = 0; i < img.cellsH; i++) {
618
+ const row = img.y + i
619
+ if (covered.has(img.key + ':' + img.x + ':' + img.cellsW + ':' + img.cellsH + ':' + row)) continue
620
+ dirtyRows.add(row)
621
+ }
622
+ }
623
+ // Which image owns each row, so a rewrite knows which payload it destroyed.
624
+ const imageRowOwner = new Map()
625
+ for (const img of screen.images) {
626
+ for (let i = 0; i < img.cellsH; i++) imageRowOwner.set(img.y + i, img.key)
627
+ }
628
+ const rewrittenImageRows = new Set()
482
629
  for (let y = 0; y < screen.rows; y++) {
483
630
  let changed = false
484
631
  for (let x = 0; x < W; x++) {
@@ -489,14 +636,24 @@ export class Terminal extends EventEmitter {
489
636
  break
490
637
  }
491
638
  }
492
- if (!changed) continue
639
+ if (!changed && !dirtyRows.has(y)) continue
640
+ if (imageRowOwner.has(y)) rewrittenImageRows.add(imageRowOwner.get(y))
493
641
  // Rewrite the whole row: move cursor, emit styled runes, pad to width.
494
642
  out.push('\x1b[' + (y + 1) + ';1H')
495
643
  let lastStyle = null
644
+ let openLink
496
645
  for (let x = 0; x < W; x++) {
497
646
  const cell = screen.cells[y][x]
498
647
  if (cell.ch === '') continue // wide-rune continuation cell
499
648
  const st = cell.style
649
+ // OSC 8 hyperlinks: open before a linked run, close after. The URL
650
+ // was sanitized when it entered the cell (Screen.set → safeLink).
651
+ const link = st?.link
652
+ if (link !== openLink) {
653
+ if (openLink) out.push('\x1b]8;;\x07')
654
+ if (link) out.push('\x1b]8;;' + link + '\x07')
655
+ openLink = link
656
+ }
500
657
  if (!sameStyle(st, lastStyle)) {
501
658
  if (lastStyle !== null) out.push(RESET)
502
659
  if (st !== null) out.push(styleAnsi(st))
@@ -521,10 +678,17 @@ export class Terminal extends EventEmitter {
521
678
  out.push(cell.ch)
522
679
  }
523
680
  }
681
+ if (openLink) out.push('\x1b]8;;\x07')
524
682
  if (lastStyle !== null) out.push(RESET)
525
683
  }
526
684
  this._prev.cells = screen.cells
527
685
  if (out.length > 0) this.write(out.join(''))
686
+ this._paintImages(screen.images, rewrittenImageRows)
687
+ // Snapshot, not a reference: the caller may keep annotating the same
688
+ // Screen before the next paint, and the diff must not see the future.
689
+ // hasPayload rides along so the next paint can tell a placement whose
690
+ // pixels are on screen from one that was reserved before its render landed.
691
+ this._prevImageRows = screen.images.map((i) => ({ ...i, hasPayload: this._imagePayloads.has(i.key) }))
528
692
  // Park the (hidden) terminal cursor at the input caret so the OS IME
529
693
  // anchors its composition window inside the composer instead of at the
530
694
  // bottom-left corner. Screen coords are 0-based; the CSI cursor address
@@ -533,11 +697,79 @@ export class Terminal extends EventEmitter {
533
697
  const cursorX = (screen.cursorX ?? 0) + 1
534
698
  this.write('\x1b[' + cursorY + ';' + cursorX + 'H')
535
699
  }
700
+
701
+ // Emit graphics-protocol output for the frame's images. Kitty transmits
702
+ // each image once and moves placements by reference; sixel and iTerm2 have
703
+ // no terminal-side registry, so their payloads re-emit at the new position
704
+ // whenever the top row moves. `rewrittenImageRows` lists the images whose
705
+ // cells this frame's text diff just wrote over: for every protocol except
706
+ // kitty that destroys the image, so the payload goes out again — a stationary
707
+ // image must survive the frames that render around it. Missing payloads
708
+ // (still decoding) leave the blank placeholder cells visible until the result
709
+ // arrives.
710
+ _paintImages(images, rewrittenImageRows) {
711
+ if (!this.caps) return
712
+ const w = []
713
+ if (this.caps.kitty) {
714
+ const prevByKey = new Map(this._prevImageRows.map((i) => [i.key, i]))
715
+ for (const img of images) {
716
+ let id = this._kittyIds.get(img.key)
717
+ if (id === undefined) {
718
+ id = this._kittyNextId++
719
+ this._kittyIds.set(img.key, id)
720
+ }
721
+ if (!this._kittySent.has(img.key)) {
722
+ const payload = this._imagePayloads.get(img.key)
723
+ if (payload?.kind === 'kitty') {
724
+ w.push(encodeKittyTransmission(id, payload.b64))
725
+ this._kittySent.add(img.key)
726
+ w.push(kittyPlacement(id, img.x, img.y))
727
+ }
728
+ // Without a payload yet there is nothing to transmit or place.
729
+ continue
730
+ }
731
+ const prev = prevByKey.get(img.key)
732
+ if (!prev || prev.x !== img.x || prev.y !== img.y || rewrittenImageRows.has(img.key)) {
733
+ w.push(kittyPlacement(id, img.x, img.y))
734
+ }
735
+ }
736
+ const alive = new Set(images.map((i) => i.key))
737
+ for (const [key, id] of this._kittyIds) {
738
+ if (!alive.has(key)) {
739
+ w.push(kittyDelete(id))
740
+ this._kittyIds.delete(key)
741
+ this._kittySent.delete(key)
742
+ }
743
+ }
744
+ } else if (this.caps.sixel || this.caps.iterm2) {
745
+ const prevByKey = new Map(this._prevImageRows.map((i) => [i.key, i]))
746
+ for (const img of images) {
747
+ const prev = prevByKey.get(img.key)
748
+ // A footprint change counts as a move: the payload is sized to the
749
+ // reserved cells, so the old pixels cover the wrong area either way. So
750
+ // does a placement that had nothing to send last time — the rows can be
751
+ // reserved before the render they need has landed (a cropped variant
752
+ // registers the moment the window scrolls, its payload arrives after),
753
+ // and calling that "unmoved" would leave the reserved cells blank for
754
+ // good. Kitty has no such hole: it keys off what it really transmitted.
755
+ const unmoved = prev && prev.x === img.x && prev.y === img.y
756
+ && prev.cellsW === img.cellsW && prev.cellsH === img.cellsH
757
+ && prev.hasPayload !== false
758
+ if (unmoved && !rewrittenImageRows.has(img.key)) continue
759
+ const payload = this._imagePayloads.get(img.key)
760
+ if (!payload) continue
761
+ w.push('\x1b[' + (img.y + 1) + ';' + (img.x + 1) + 'H')
762
+ if (payload.kind === 'sixel') w.push(payload.s)
763
+ else if (payload.kind === 'iterm2') w.push(encodeITerm2(payload.b64, payload.pxW, payload.pxH, payload.bytes))
764
+ }
765
+ }
766
+ if (w.length > 0) this.write(w.join(''))
767
+ }
536
768
  }
537
769
 
538
770
  function sameStyle(a, b) {
539
771
  if (a === b) return true
540
772
  if (a === null || b === null) return false
541
773
  return a.fg === b.fg && a.bg === b.bg && a.bold === b.bold && a.dim === b.dim
542
- && a.italic === b.italic && a.underline === b.underline
774
+ && a.italic === b.italic && a.underline === b.underline && a.link === b.link
543
775
  }