@adecore/terminal 0.39.0 → 0.40.0

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.
@@ -68,15 +68,17 @@ export function TerminalView({
68
68
  // Through the parser (RIS), since `Terminal.reset()` runs at once and output still queued would land on the fresh screen.
69
69
  reset: () => live.current?.term.write('\x1bc'),
70
70
  focus: () => {
71
- live.current?.term.focus();
72
- if (live.current?.webgl) {
73
- webglBudget.focus(live.current.id);
71
+ const current_0 = live.current;
72
+ current_0?.term.focus();
73
+ if (current_0?.webgl) {
74
+ webglBudget.focus(current_0.id);
74
75
  }
75
76
  },
76
77
  blur: () => {
77
- live.current?.term.blur();
78
- if (live.current?.webgl) {
79
- webglBudget.blur(live.current.id);
78
+ const current_1 = live.current;
79
+ current_1?.term.blur();
80
+ if (current_1?.webgl) {
81
+ webglBudget.blur(current_1.id);
80
82
  }
81
83
  },
82
84
  paste: text => live.current?.term.paste(text),
@@ -122,11 +124,8 @@ export function TerminalView({
122
124
  if (initial.scaledByAncestor) {
123
125
  followAncestorScale(term_0);
124
126
  }
125
- /*
126
- * The grid this terminal fits and tells the program, and the grid the program has. They part while
127
- * another client sizes the same program; this one then draws that grid, clipped or with room to
128
- * spare, until a fit here changes the grid and claims it back. Null until a fit had room.
129
- */
127
+ // The grid this terminal fits and the grid the program has. They part while another client sizes the
128
+ // program; this one then draws that grid until a fit here claims it back. Null until a fit had room.
130
129
  let claimed = fitToHost(term_0, fit) ? {
131
130
  cols: term_0.cols,
132
131
  rows: term_0.rows
@@ -156,9 +155,10 @@ export function TerminalView({
156
155
  let theme = JSON.stringify(term_0.options.theme);
157
156
  const restyle = (size_0, height) => {
158
157
  const next = readTerminalTheme();
158
+ const nextKey = JSON.stringify(next);
159
159
  // A fresh theme object repaints every cell, so only a different one is handed over.
160
- if (JSON.stringify(next) !== theme) {
161
- theme = JSON.stringify(next);
160
+ if (nextKey !== theme) {
161
+ theme = nextKey;
162
162
  term_0.options.theme = next;
163
163
  }
164
164
  term_0.options.fontFamily = readTerminalFont();
@@ -169,9 +169,8 @@ export function TerminalView({
169
169
  };
170
170
  const id = `terminal-${++terminals}`;
171
171
  let releaseWebgl = null;
172
- const current_0 = {
172
+ const current_2 = {
173
173
  term: term_0,
174
- refit,
175
174
  restyle,
176
175
  followGrid: size_1 => {
177
176
  shared = size_1;
@@ -183,7 +182,7 @@ export function TerminalView({
183
182
  term_0.options.convertEol = convertEol_0;
184
183
  },
185
184
  setWebgl: on => {
186
- current_0.webgl = on;
185
+ current_2.webgl = on;
187
186
  if (on && releaseWebgl === null) {
188
187
  releaseWebgl = webglBudget.register(id, term_0, refit);
189
188
  } else if (!on && releaseWebgl !== null) {
@@ -194,7 +193,7 @@ export function TerminalView({
194
193
  webgl: false,
195
194
  id
196
195
  };
197
- live.current = current_0;
196
+ live.current = current_2;
198
197
  const data_0 = term_0.onData(input => latest.current.onData?.(input));
199
198
  let timer = null;
200
199
  const resizes = new ResizeObserver(() => {
@@ -220,7 +219,7 @@ export function TerminalView({
220
219
  themes.disconnect();
221
220
  data_0.dispose();
222
221
  // The context goes back before the terminal is gone, so the next one can take it.
223
- current_0.setWebgl(false);
222
+ current_2.setWebgl(false);
224
223
  disposeLinks();
225
224
  term_0.dispose();
226
225
  live.current = null;
@@ -1,9 +1,7 @@
1
1
  import type { Terminal } from '@xterm/xterm';
2
2
  /**
3
- * Keeps the number of live WebGL renderers under the cap, however many terminals a page shows.
4
- * A browser drops the oldest of its own contexts without telling anyone, which left a terminal on
5
- * the DOM renderer for good; here a terminal that loses its context queues up again instead.
6
- * `WebglSlots` decides who holds one, this class loads and disposes the addons.
3
+ * Keeps the live WebGL renderers under the cap. A browser silently drops its oldest context, which left
4
+ * a terminal on the DOM renderer for good; here a terminal that loses its context queues up again.
7
5
  */
8
6
  declare class WebglBudget {
9
7
  private readonly slots;
@@ -20,10 +20,8 @@ const rendererCanvas = term => {
20
20
  return [...canvases].filter(canvas => canvas.classList.length === 0).at(-1) ?? null;
21
21
  };
22
22
  /**
23
- * Keeps the number of live WebGL renderers under the cap, however many terminals a page shows.
24
- * A browser drops the oldest of its own contexts without telling anyone, which left a terminal on
25
- * the DOM renderer for good; here a terminal that loses its context queues up again instead.
26
- * `WebglSlots` decides who holds one, this class loads and disposes the addons.
23
+ * Keeps the live WebGL renderers under the cap. A browser silently drops its oldest context, which left
24
+ * a terminal on the DOM renderer for good; here a terminal that loses its context queues up again.
27
25
  */
28
26
  class WebglBudget {
29
27
  slots = new WebglSlots(DEFAULT_WEBGL_CONTEXTS);
@@ -111,8 +109,7 @@ class WebglBudget {
111
109
  return;
112
110
  }
113
111
  this.drop(entry);
114
- // Disposing the addon puts the DOM renderer back and queues a full repaint; the fit runs
115
- // after that frame, on the cell size that renderer measured.
112
+ // The fit runs after the DOM renderer's repaint, on the cell size it measured.
116
113
  this.scheduleRefit(entry);
117
114
  }
118
115
  handleLoss(id) {
@@ -127,8 +124,7 @@ class WebglBudget {
127
124
  }
128
125
  entry.addon?.dispose();
129
126
  entry.addon = null;
130
- // The addon leaves its canvas to the garbage collector, and until that runs the browser
131
- // still counts the context. Losing it by hand is what makes a released slot a free one.
127
+ // The browser counts the context until the canvas is collected, so it is lost by hand.
132
128
  entry.canvas?.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();
133
129
  entry.canvas = null;
134
130
  }
@@ -5,9 +5,8 @@ export interface SlotChange {
5
5
  revoked: string[];
6
6
  }
7
7
  /**
8
- * Hands a fixed number of WebGL contexts to the terminals that deserve them most, the focused one
9
- * first, then the ones most recently focused or written to. Knows nothing about xterm or the DOM;
10
- * the budget turns a `SlotChange` into addons that are loaded and disposed.
8
+ * Hands a fixed number of WebGL contexts to the focused terminal first, then the ones most recently
9
+ * focused or written to. Knows nothing about xterm or the DOM; the budget turns a change into addons.
11
10
  */
12
11
  export declare class WebglSlots {
13
12
  private readonly members;
@@ -27,6 +26,7 @@ export declare class WebglSlots {
27
26
  touch(id: string): SlotChange;
28
27
  lost(id: string): SlotChange;
29
28
  setCap(cap: number): SlotChange;
29
+ private bump;
30
30
  private ranked;
31
31
  private rankOf;
32
32
  private target;
@@ -1,6 +1,5 @@
1
- /* How many terminals may hold a WebGL renderer at the same time. A browser keeps about 16 live
2
- contexts per page and silently drops the oldest, so the budget stays well under that and leaves
3
- room for whatever else on the page draws with WebGL. */
1
+ /* A browser keeps about 16 live contexts per page and silently drops the oldest, so this leaves room
2
+ for whatever else on the page draws with WebGL. */
4
3
  export const DEFAULT_WEBGL_CONTEXTS = 10;
5
4
  /* Output moves a context at most once in this window, and only away from a holder that was quiet
6
5
  for as long. Without it, more writing terminals than slots trade contexts on every chunk, and
@@ -11,9 +10,8 @@ const nothing = () => ({
11
10
  revoked: []
12
11
  });
13
12
  /**
14
- * Hands a fixed number of WebGL contexts to the terminals that deserve them most, the focused one
15
- * first, then the ones most recently focused or written to. Knows nothing about xterm or the DOM;
16
- * the budget turns a `SlotChange` into addons that are loaded and disposed.
13
+ * Hands a fixed number of WebGL contexts to the focused terminal first, then the ones most recently
14
+ * focused or written to. Knows nothing about xterm or the DOM; the budget turns a change into addons.
17
15
  */
18
16
  export class WebglSlots {
19
17
  members = new Map();
@@ -42,8 +40,7 @@ export class WebglSlots {
42
40
  request(id) {
43
41
  const member = this.members.get(id);
44
42
  if (member) {
45
- member.seq = ++this.stamp;
46
- member.activeAt = this.now();
43
+ this.bump(member, this.now());
47
44
  } else {
48
45
  this.members.set(id, {
49
46
  seq: ++this.stamp,
@@ -70,8 +67,7 @@ export class WebglSlots {
70
67
  if (!member) {
71
68
  return nothing();
72
69
  }
73
- member.seq = ++this.stamp;
74
- member.activeAt = this.now();
70
+ this.bump(member, this.now());
75
71
  // Focusing is how a terminal that lost its context asks for a new one.
76
72
  member.blocked = false;
77
73
  return this.reconcile();
@@ -90,8 +86,7 @@ export class WebglSlots {
90
86
  return nothing();
91
87
  }
92
88
  const now = this.now();
93
- member.seq = ++this.stamp;
94
- member.activeAt = now;
89
+ this.bump(member, now);
95
90
  // A holder that climbs stays a holder; only a waiter can change who holds what.
96
91
  if (member.holding || now - this.outputSwitchedAt < OUTPUT_SWITCH_INTERVAL_MS) {
97
92
  return nothing();
@@ -122,6 +117,10 @@ export class WebglSlots {
122
117
  this.cap = Math.max(1, cap);
123
118
  return this.reconcile();
124
119
  }
120
+ bump(member, now) {
121
+ member.seq = ++this.stamp;
122
+ member.activeAt = now;
123
+ }
125
124
  ranked() {
126
125
  return [...this.members.keys()].sort((a, b) => this.rankOf(b) - this.rankOf(a));
127
126
  }
@@ -3,11 +3,9 @@
3
3
  * version of xterm that moves these fields needs a look here before the range widens.
4
4
  */
5
5
  /*
6
- * FitAddon measures the host's border box, so a vertical padding on the host would count as room for a
7
- * row that is cut off. The host has none; what a whole row does not fill is split above and below, as an
8
- * offset rather than a padding, since FitAddon subtracts the terminal element's own padding too.
9
- * False, without a fit, for a host the layout has given no room yet: FitAddon would make two columns
10
- * of it, a grid nobody sees that a shell still redraws its prompt for.
6
+ * FitAddon measures the host's border box and subtracts the terminal element's padding, so what a whole
7
+ * row does not fill is split above and below as an offset, never a padding. False, without a fit, for a
8
+ * host with no room yet: FitAddon would make a two-column grid a shell still redraws its prompt for.
11
9
  */
12
10
  export const fitToHost = (term, fit) => {
13
11
  const host = term.element?.parentElement;
@@ -33,10 +31,9 @@ export const unscaledPointer = (pointer, rect, layout) => {
33
31
  };
34
32
  };
35
33
  /*
36
- * xterm measures a pointer against the screen's scaled bounding box but divides by unscaled cells, so
37
- * under an ancestor's scale() a selection or a click lands rows off, more so further down. Its one mouse
38
- * service (private, shared by selection, links and mouse reporting) gets the pointer as it would stand
39
- * without the transform. Call after `open`, which creates that service.
34
+ * xterm measures a pointer against the scaled bounding box but divides by unscaled cells, so under an
35
+ * ancestor's scale() a click lands rows off. Its private mouse service (shared by selection, links and
36
+ * mouse reporting) gets the unscaled pointer. Call after `open`, which creates that service.
40
37
  */
41
38
  export const followAncestorScale = term => {
42
39
  const mouse = term._core._mouseService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adecore/terminal",
3
- "version": "0.39.0",
3
+ "version": "0.40.0",
4
4
  "description": "A themed terminal pane on xterm.js that fits its container and is fed by the app.",
5
5
  "license": "FSL-1.1-MIT",
6
6
  "author": "Bas Milius",
@@ -53,15 +53,15 @@
53
53
  "react-dom": "^19.3.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@types/bun": "^1.4.2",
56
+ "@types/bun": "^1.4.4",
57
57
  "@types/react": "^19.3.0",
58
58
  "@types/react-dom": "^19.3.0",
59
59
  "@xterm/addon-fit": "^0.11.0",
60
60
  "@xterm/addon-web-links": "^0.12.0",
61
61
  "@xterm/addon-webgl": "^0.19.0",
62
62
  "@xterm/xterm": "^6.0.0",
63
- "react": "^19.3.0",
64
- "react-dom": "^19.3.0",
63
+ "react": "^19.3.1",
64
+ "react-dom": "^19.3.1",
65
65
  "typescript": "^7.0.2"
66
66
  }
67
67
  }
@@ -65,7 +65,6 @@ export interface TerminalViewProps {
65
65
 
66
66
  interface Live {
67
67
  term: Terminal;
68
- refit(): void;
69
68
  restyle(fontSize: number, lineHeight: number): void;
70
69
  setInput(readOnly: boolean, convertEol: boolean): void;
71
70
  followGrid(size: TerminalSize): void;
@@ -109,10 +108,13 @@ export function TerminalView({
109
108
  },
110
109
  write: (data, done) => {
111
110
  const current = live.current;
111
+
112
112
  if (!current) {
113
113
  return;
114
114
  }
115
+
115
116
  current.term.write(data, done);
117
+
116
118
  if (current.webgl) {
117
119
  // A terminal that is being written to outranks an idle one when contexts are scarce.
118
120
  webglBudget.touch(current.id);
@@ -121,15 +123,19 @@ export function TerminalView({
121
123
  // Through the parser (RIS), since `Terminal.reset()` runs at once and output still queued would land on the fresh screen.
122
124
  reset: () => live.current?.term.write('\x1bc'),
123
125
  focus: () => {
124
- live.current?.term.focus();
125
- if (live.current?.webgl) {
126
- webglBudget.focus(live.current.id);
126
+ const current = live.current;
127
+ current?.term.focus();
128
+
129
+ if (current?.webgl) {
130
+ webglBudget.focus(current.id);
127
131
  }
128
132
  },
129
133
  blur: () => {
130
- live.current?.term.blur();
131
- if (live.current?.webgl) {
132
- webglBudget.blur(live.current.id);
134
+ const current = live.current;
135
+ current?.term.blur();
136
+
137
+ if (current?.webgl) {
138
+ webglBudget.blur(current.id);
133
139
  }
134
140
  },
135
141
  paste: (text) => live.current?.term.paste(text),
@@ -138,14 +144,18 @@ export function TerminalView({
138
144
  size: () => ({ cols: live.current?.term.cols ?? 80, rows: live.current?.term.rows ?? 24 }),
139
145
  visibleText: () => {
140
146
  const term = live.current?.term;
147
+
141
148
  if (!term) {
142
149
  return '';
143
150
  }
151
+
144
152
  const buffer = term.buffer.active;
145
153
  const lines: string[] = [];
154
+
146
155
  for (let row = 0; row < term.rows; row++) {
147
156
  lines.push(buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '');
148
157
  }
158
+
149
159
  return lines.join('\n').replace(/\s+$/, '');
150
160
  },
151
161
  followGrid: (size) => live.current?.followGrid(size)
@@ -155,10 +165,13 @@ export function TerminalView({
155
165
 
156
166
  useEffect(() => {
157
167
  const host = hostRef.current;
168
+
158
169
  if (!host) {
159
170
  return;
160
171
  }
172
+
161
173
  const initial = latest.current;
174
+
162
175
  const term = new Terminal({
163
176
  theme: readTerminalTheme(),
164
177
  fontFamily: readTerminalFont(),
@@ -168,47 +181,55 @@ export function TerminalView({
168
181
  scrollback: 5000,
169
182
  macOptionIsMeta: true
170
183
  });
184
+
171
185
  const fit = new FitAddon();
172
186
  term.loadAddon(fit);
173
187
  term.open(host);
174
188
  const disposeLinks = bindTerminalLinks(term, () => latest.current);
189
+
175
190
  if (initial.scaledByAncestor) {
176
191
  followAncestorScale(term);
177
192
  }
178
- /*
179
- * The grid this terminal fits and tells the program, and the grid the program has. They part while
180
- * another client sizes the same program; this one then draws that grid, clipped or with room to
181
- * spare, until a fit here changes the grid and claims it back. Null until a fit had room.
182
- */
193
+
194
+ // The grid this terminal fits and the grid the program has. They part while another client sizes the
195
+ // program; this one then draws that grid until a fit here claims it back. Null until a fit had room.
183
196
  let claimed: TerminalSize | null = fitToHost(term, fit) ? { cols: term.cols, rows: term.rows } : null;
184
197
  let shared = claimed;
198
+
185
199
  const drawShared = (): void => {
186
200
  if (shared !== null && (term.cols !== shared.cols || term.rows !== shared.rows)) {
187
201
  term.resize(shared.cols, shared.rows);
188
202
  }
189
203
  };
204
+
190
205
  // A resize, a font change and a renderer swap all land here: WebGL and the DOM measure a glyph
191
206
  // differently, so a swap can change how many cells fit.
192
207
  const refit = (): void => {
193
208
  if (!fitToHost(term, fit)) {
194
209
  return;
195
210
  }
211
+
196
212
  if (claimed === null || term.cols !== claimed.cols || term.rows !== claimed.rows) {
197
213
  claimed = { cols: term.cols, rows: term.rows };
198
214
  shared = claimed;
199
215
  latest.current.onResize?.(claimed.cols, claimed.rows);
200
216
  }
217
+
201
218
  drawShared();
202
219
  };
203
220
 
204
221
  let theme = JSON.stringify(term.options.theme);
222
+
205
223
  const restyle = (size: number, height: number): void => {
206
224
  const next = readTerminalTheme();
225
+ const nextKey = JSON.stringify(next);
226
+
207
227
  // A fresh theme object repaints every cell, so only a different one is handed over.
208
- if (JSON.stringify(next) !== theme) {
209
- theme = JSON.stringify(next);
228
+ if (nextKey !== theme) {
229
+ theme = nextKey;
210
230
  term.options.theme = next;
211
231
  }
232
+
212
233
  term.options.fontFamily = readTerminalFont();
213
234
  term.options.fontSize = size;
214
235
  term.options.lineHeight = height;
@@ -218,9 +239,9 @@ export function TerminalView({
218
239
 
219
240
  const id = `terminal-${++terminals}`;
220
241
  let releaseWebgl: (() => void) | null = null;
242
+
221
243
  const current: Live = {
222
244
  term,
223
- refit,
224
245
  restyle,
225
246
  followGrid: (size) => {
226
247
  shared = size;
@@ -233,6 +254,7 @@ export function TerminalView({
233
254
  },
234
255
  setWebgl: (on) => {
235
256
  current.webgl = on;
257
+
236
258
  if (on && releaseWebgl === null) {
237
259
  releaseWebgl = webglBudget.register(id, term, refit);
238
260
  } else if (!on && releaseWebgl !== null) {
@@ -243,20 +265,24 @@ export function TerminalView({
243
265
  webgl: false,
244
266
  id
245
267
  };
268
+
246
269
  live.current = current;
247
270
 
248
271
  const data = term.onData((input) => latest.current.onData?.(input));
249
272
 
250
273
  let timer: number | null = null;
274
+
251
275
  const resizes = new ResizeObserver(() => {
252
276
  if (timer !== null) {
253
277
  window.clearTimeout(timer);
254
278
  }
279
+
255
280
  timer = window.setTimeout(() => {
256
281
  timer = null;
257
282
  refit();
258
283
  }, RESIZE_DEBOUNCE_MS);
259
284
  });
285
+
260
286
  resizes.observe(host);
261
287
 
262
288
  const themes = new MutationObserver(() => restyle(latest.current.fontSize, latest.current.lineHeight));
@@ -266,6 +292,7 @@ export function TerminalView({
266
292
  if (timer !== null) {
267
293
  window.clearTimeout(timer);
268
294
  }
295
+
269
296
  resizes.disconnect();
270
297
  themes.disconnect();
271
298
  data.dispose();
package/src/links.ts CHANGED
@@ -17,11 +17,13 @@ export function linkLineBounds(
17
17
  if (screen.width <= 0 || screen.height <= 0) {
18
18
  return null;
19
19
  }
20
+
20
21
  const cellWidth = screen.width / grid.cols;
21
22
  const cellHeight = screen.height / grid.rows;
22
23
  const row = Math.max(range.start.y, Math.min(range.end.y, grid.viewportY + Math.floor((pointerY - screen.top) / cellHeight) + 1));
23
24
  const start = row === range.start.y ? range.start.x : 1;
24
25
  const end = row === range.end.y ? range.end.x : grid.cols;
26
+
25
27
  return {
26
28
  x: screen.left + (start - 1) * cellWidth,
27
29
  y: screen.top + (row - grid.viewportY - 1) * cellHeight,
@@ -38,24 +40,31 @@ interface TerminalLinks {
38
40
  export function bindTerminalLinks(term: Terminal, callbacks: () => TerminalLinks): () => void {
39
41
  const element = term.element!;
40
42
  let press: { x: number; y: number } | null = null;
43
+
41
44
  const rememberPress = (event: MouseEvent): void => {
42
45
  press = event.button === 0 ? { x: event.clientX, y: event.clientY } : null;
43
46
  };
47
+
44
48
  const cancelPress = (): void => {
45
49
  press = null;
46
50
  };
51
+
47
52
  const activate = (event: MouseEvent, uri: string): void => {
48
53
  const start = press;
49
54
  press = null;
55
+
50
56
  // xterm 6 activates on mouseup, including selection drags and non-primary buttons.
51
57
  if (!start || event.button !== 0 || event.defaultPrevented || term.hasSelection() || Math.hypot(event.clientX - start.x, event.clientY - start.y) > 3) {
52
58
  return;
53
59
  }
60
+
54
61
  // OSC 8 targets and detected URLs share the same web-only boundary.
55
62
  if (!/^https?:\/\//i.test(uri) || !URL.canParse(uri)) {
56
63
  return;
57
64
  }
65
+
58
66
  const open = callbacks().onOpenLink;
67
+
59
68
  if (open) {
60
69
  open(uri, event);
61
70
  } else {
@@ -63,15 +72,20 @@ export function bindTerminalLinks(term: Terminal, callbacks: () => TerminalLinks
63
72
  window.open(uri, '_blank', 'noopener,noreferrer');
64
73
  }
65
74
  };
75
+
66
76
  const hover = (event: MouseEvent, uri: string, range: IBufferRange): void => {
67
77
  const screen = element.querySelector('.xterm-screen')?.getBoundingClientRect();
78
+
68
79
  // Screen bounds include canvas zoom; xterm ranges are one-based buffer coordinates, including scrollback.
69
80
  const bounds = screen
70
81
  ? linkLineBounds(range, { cols: term.cols, rows: term.rows, viewportY: term.buffer.active.viewportY }, screen, event.clientY)
71
82
  : null;
83
+
72
84
  callbacks().onLinkHover?.(bounds ? uri : null, bounds);
73
85
  };
86
+
74
87
  const leave = (): void => callbacks().onLinkHover?.(null, null);
88
+
75
89
  const previous = term.options.linkHandler;
76
90
  term.options.linkHandler = { activate, hover, leave, allowNonHttpProtocols: false };
77
91
  const addon = new WebLinksAddon(activate, { hover, leave });
@@ -79,6 +93,7 @@ export function bindTerminalLinks(term: Terminal, callbacks: () => TerminalLinks
79
93
  element.addEventListener('mousedown', rememberPress, true);
80
94
  element.addEventListener('pointercancel', cancelPress);
81
95
  element.addEventListener('mouseleave', cancelPress);
96
+
82
97
  return () => {
83
98
  element.removeEventListener('mousedown', rememberPress, true);
84
99
  element.removeEventListener('pointercancel', cancelPress);
package/src/theme.ts CHANGED
@@ -12,6 +12,7 @@ const brightKey = (name: AnsiName): BrightName => `bright${name[0]!.toUpperCase(
12
12
  /* xterm takes literal colors, so the tokens are resolved from the root on every theme change. */
13
13
  export const readTerminalTheme = (): ITheme => {
14
14
  const style = getComputedStyle(document.documentElement);
15
+
15
16
  const theme: ITheme = {
16
17
  background: token(style, '--term-bg'),
17
18
  foreground: token(style, '--term-fg'),
@@ -19,10 +20,12 @@ export const readTerminalTheme = (): ITheme => {
19
20
  cursorAccent: token(style, '--term-bg'),
20
21
  selectionBackground: token(style, '--selection')
21
22
  };
23
+
22
24
  for (const name of ANSI) {
23
25
  theme[name] = token(style, `--term-ansi-${name}`);
24
26
  theme[brightKey(name)] = token(style, `--term-ansi-bright-${name}`);
25
27
  }
28
+
26
29
  return theme;
27
30
  };
28
31
 
@@ -16,6 +16,7 @@ const hasWebgl2 = (): boolean => {
16
16
  webgl2Available = context !== null;
17
17
  context?.getExtension('WEBGL_lose_context')?.loseContext();
18
18
  }
19
+
19
20
  return webgl2Available;
20
21
  };
21
22
 
@@ -23,6 +24,7 @@ const hasWebgl2 = (): boolean => {
23
24
  (`xterm-link-layer`); the WebGL one is the nameless one. */
24
25
  const rendererCanvas = (term: Terminal): HTMLCanvasElement | null => {
25
26
  const canvases = term.element?.querySelectorAll<HTMLCanvasElement>('.xterm-screen canvas') ?? [];
27
+
26
28
  return [...canvases].filter((canvas) => canvas.classList.length === 0).at(-1) ?? null;
27
29
  };
28
30
 
@@ -36,10 +38,8 @@ interface Entry {
36
38
  }
37
39
 
38
40
  /**
39
- * Keeps the number of live WebGL renderers under the cap, however many terminals a page shows.
40
- * A browser drops the oldest of its own contexts without telling anyone, which left a terminal on
41
- * the DOM renderer for good; here a terminal that loses its context queues up again instead.
42
- * `WebglSlots` decides who holds one, this class loads and disposes the addons.
41
+ * Keeps the live WebGL renderers under the cap. A browser silently drops its oldest context, which left
42
+ * a terminal on the DOM renderer for good; here a terminal that loses its context queues up again.
43
43
  */
44
44
  class WebglBudget {
45
45
  private readonly slots = new WebglSlots(DEFAULT_WEBGL_CONTEXTS);
@@ -49,13 +49,16 @@ class WebglBudget {
49
49
  register(id: string, term: Terminal, refit: () => void): () => void {
50
50
  const entry: Entry = { term, refit, addon: null, canvas: null, frame: null };
51
51
  this.entries.set(id, entry);
52
+
52
53
  if (hasWebgl2()) {
53
54
  this.apply(this.slots.request(id));
54
55
  }
56
+
55
57
  return () => {
56
58
  if (this.entries.get(id) !== entry) {
57
59
  return;
58
60
  }
61
+
59
62
  this.entries.delete(id);
60
63
  // The context goes back before the next terminal asks for one, never after.
61
64
  this.drop(entry);
@@ -80,6 +83,7 @@ class WebglBudget {
80
83
  holders(): Terminal[] {
81
84
  return this.slots.holders().flatMap((id) => {
82
85
  const entry = this.entries.get(id);
86
+
83
87
  return entry ? [entry.term] : [];
84
88
  });
85
89
  }
@@ -89,6 +93,7 @@ class WebglBudget {
89
93
  for (const id of change.revoked) {
90
94
  this.unload(id);
91
95
  }
96
+
92
97
  for (const id of change.granted) {
93
98
  this.load(id);
94
99
  }
@@ -96,13 +101,16 @@ class WebglBudget {
96
101
 
97
102
  private load(id: string): void {
98
103
  const entry = this.entries.get(id);
104
+
99
105
  if (!entry || entry.addon) {
100
106
  return;
101
107
  }
108
+
102
109
  if (Addon === null) {
103
110
  addonLoad ??= import('@xterm/addon-webgl').then((module) => {
104
111
  Addon = module.WebglAddon;
105
112
  });
113
+
106
114
  void addonLoad.then(
107
115
  () => {
108
116
  if (this.slots.holds(id)) {
@@ -111,8 +119,10 @@ class WebglBudget {
111
119
  },
112
120
  () => this.apply(this.slots.lost(id))
113
121
  );
122
+
114
123
  return;
115
124
  }
125
+
116
126
  try {
117
127
  const addon = new Addon();
118
128
  addon.onContextLoss(() => this.handleLoss(id));
@@ -128,12 +138,13 @@ class WebglBudget {
128
138
 
129
139
  private unload(id: string): void {
130
140
  const entry = this.entries.get(id);
141
+
131
142
  if (!entry?.addon) {
132
143
  return;
133
144
  }
145
+
134
146
  this.drop(entry);
135
- // Disposing the addon puts the DOM renderer back and queues a full repaint; the fit runs
136
- // after that frame, on the cell size that renderer measured.
147
+ // The fit runs after the DOM renderer's repaint, on the cell size it measured.
137
148
  this.scheduleRefit(entry);
138
149
  }
139
150
 
@@ -148,10 +159,10 @@ class WebglBudget {
148
159
  window.cancelAnimationFrame(entry.frame);
149
160
  entry.frame = null;
150
161
  }
162
+
151
163
  entry.addon?.dispose();
152
164
  entry.addon = null;
153
- // The addon leaves its canvas to the garbage collector, and until that runs the browser
154
- // still counts the context. Losing it by hand is what makes a released slot a free one.
165
+ // The browser counts the context until the canvas is collected, so it is lost by hand.
155
166
  entry.canvas?.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();
156
167
  entry.canvas = null;
157
168
  }
@@ -160,6 +171,7 @@ class WebglBudget {
160
171
  if (entry.frame !== null) {
161
172
  return;
162
173
  }
174
+
163
175
  entry.frame = window.requestAnimationFrame(() => {
164
176
  entry.frame = null;
165
177
  entry.refit();
@@ -1,6 +1,5 @@
1
- /* How many terminals may hold a WebGL renderer at the same time. A browser keeps about 16 live
2
- contexts per page and silently drops the oldest, so the budget stays well under that and leaves
3
- room for whatever else on the page draws with WebGL. */
1
+ /* A browser keeps about 16 live contexts per page and silently drops the oldest, so this leaves room
2
+ for whatever else on the page draws with WebGL. */
4
3
  export const DEFAULT_WEBGL_CONTEXTS = 10;
5
4
 
6
5
  /* Output moves a context at most once in this window, and only away from a holder that was quiet
@@ -26,9 +25,8 @@ interface Member {
26
25
  const nothing = (): SlotChange => ({ granted: [], revoked: [] });
27
26
 
28
27
  /**
29
- * Hands a fixed number of WebGL contexts to the terminals that deserve them most, the focused one
30
- * first, then the ones most recently focused or written to. Knows nothing about xterm or the DOM;
31
- * the budget turns a `SlotChange` into addons that are loaded and disposed.
28
+ * Hands a fixed number of WebGL contexts to the focused terminal first, then the ones most recently
29
+ * focused or written to. Knows nothing about xterm or the DOM; the budget turns a change into addons.
32
30
  */
33
31
  export class WebglSlots {
34
32
  private readonly members = new Map<string, Member>();
@@ -61,12 +59,13 @@ export class WebglSlots {
61
59
  /* A terminal that just became visible asks for a context. */
62
60
  request(id: string): SlotChange {
63
61
  const member = this.members.get(id);
62
+
64
63
  if (member) {
65
- member.seq = ++this.stamp;
66
- member.activeAt = this.now();
64
+ this.bump(member, this.now());
67
65
  } else {
68
66
  this.members.set(id, { seq: ++this.stamp, activeAt: this.now(), holding: false, blocked: false });
69
67
  }
68
+
70
69
  return this.reconcile();
71
70
  }
72
71
 
@@ -75,22 +74,26 @@ export class WebglSlots {
75
74
  if (!this.members.delete(id)) {
76
75
  return nothing();
77
76
  }
77
+
78
78
  if (this.focusedId === id) {
79
79
  this.focusedId = null;
80
80
  }
81
+
81
82
  return this.reconcile();
82
83
  }
83
84
 
84
85
  focus(id: string): SlotChange {
85
86
  this.focusedId = id;
86
87
  const member = this.members.get(id);
88
+
87
89
  if (!member) {
88
90
  return nothing();
89
91
  }
90
- member.seq = ++this.stamp;
91
- member.activeAt = this.now();
92
+
93
+ this.bump(member, this.now());
92
94
  // Focusing is how a terminal that lost its context asks for a new one.
93
95
  member.blocked = false;
96
+
94
97
  return this.reconcile();
95
98
  }
96
99
 
@@ -98,54 +101,73 @@ export class WebglSlots {
98
101
  if (this.focusedId !== id) {
99
102
  return nothing();
100
103
  }
104
+
101
105
  this.focusedId = null;
106
+
102
107
  return this.reconcile();
103
108
  }
104
109
 
105
110
  /* Output arrived, so this terminal is worth more than an idle one. */
106
111
  touch(id: string): SlotChange {
107
112
  const member = this.members.get(id);
113
+
108
114
  if (!member) {
109
115
  return nothing();
110
116
  }
117
+
111
118
  const now = this.now();
112
- member.seq = ++this.stamp;
113
- member.activeAt = now;
119
+ this.bump(member, now);
120
+
114
121
  // A holder that climbs stays a holder; only a waiter can change who holds what.
115
122
  if (member.holding || now - this.outputSwitchedAt < OUTPUT_SWITCH_INTERVAL_MS) {
116
123
  return nothing();
117
124
  }
125
+
118
126
  const target = this.target();
127
+
119
128
  const evictsBusyHolder = [...this.members].some(
120
129
  ([other, entry]) => entry.holding && !target.has(other) && now - entry.activeAt < OUTPUT_SWITCH_INTERVAL_MS
121
130
  );
131
+
122
132
  // The waiter keeps its new rank; its next write tries again, and so does any request, focus or release.
123
133
  if (evictsBusyHolder) {
124
134
  return nothing();
125
135
  }
136
+
126
137
  const change = this.reconcile(target);
138
+
127
139
  if (change.granted.length > 0 || change.revoked.length > 0) {
128
140
  this.outputSwitchedAt = now;
129
141
  }
142
+
130
143
  return change;
131
144
  }
132
145
 
133
146
  /* The browser reported a context loss, free the slot and wait for a focus before asking again. */
134
147
  lost(id: string): SlotChange {
135
148
  const member = this.members.get(id);
149
+
136
150
  if (!member) {
137
151
  return nothing();
138
152
  }
153
+
139
154
  member.holding = false;
140
155
  member.blocked = true;
156
+
141
157
  return this.reconcile();
142
158
  }
143
159
 
144
160
  setCap(cap: number): SlotChange {
145
161
  this.cap = Math.max(1, cap);
162
+
146
163
  return this.reconcile();
147
164
  }
148
165
 
166
+ private bump(member: Member, now: number): void {
167
+ member.seq = ++this.stamp;
168
+ member.activeAt = now;
169
+ }
170
+
149
171
  private ranked(): string[] {
150
172
  return [...this.members.keys()].sort((a, b) => this.rankOf(b) - this.rankOf(a));
151
173
  }
@@ -155,17 +177,20 @@ export class WebglSlots {
155
177
  if (id === this.focusedId) {
156
178
  return Number.MAX_SAFE_INTEGER;
157
179
  }
180
+
158
181
  return this.members.get(id)?.seq ?? -1;
159
182
  }
160
183
 
161
184
  private target(): Set<string> {
162
185
  const eligible = this.ranked().filter((id) => this.members.get(id)?.blocked !== true);
186
+
163
187
  return new Set(eligible.slice(0, this.cap));
164
188
  }
165
189
 
166
190
  private reconcile(target: Set<string> = this.target()): SlotChange {
167
191
  const granted: string[] = [];
168
192
  const revoked: string[] = [];
193
+
169
194
  for (const [id, member] of this.members) {
170
195
  if (target.has(id) && !member.holding) {
171
196
  member.holding = true;
@@ -175,6 +200,7 @@ export class WebglSlots {
175
200
  revoked.push(id);
176
201
  }
177
202
  }
203
+
178
204
  return { granted, revoked };
179
205
  }
180
206
  }
@@ -7,25 +7,28 @@ import type { Terminal } from '@xterm/xterm';
7
7
  */
8
8
 
9
9
  /*
10
- * FitAddon measures the host's border box, so a vertical padding on the host would count as room for a
11
- * row that is cut off. The host has none; what a whole row does not fill is split above and below, as an
12
- * offset rather than a padding, since FitAddon subtracts the terminal element's own padding too.
13
- * False, without a fit, for a host the layout has given no room yet: FitAddon would make two columns
14
- * of it, a grid nobody sees that a shell still redraws its prompt for.
10
+ * FitAddon measures the host's border box and subtracts the terminal element's padding, so what a whole
11
+ * row does not fill is split above and below as an offset, never a padding. False, without a fit, for a
12
+ * host with no room yet: FitAddon would make a two-column grid a shell still redraws its prompt for.
15
13
  */
16
14
  export const fitToHost = (term: Terminal, fit: FitAddon): boolean => {
17
15
  const host = term.element?.parentElement;
16
+
18
17
  if (!host || host.clientWidth === 0 || host.clientHeight === 0) {
19
18
  return false;
20
19
  }
20
+
21
21
  fit.fit();
22
+
22
23
  // The same private dimensions FitAddon itself divides by.
23
24
  const cellHeight: number = (term as unknown as { _core: { _renderService: { dimensions: { css: { cell: { height: number } } } } } })._core._renderService
24
25
  .dimensions.css.cell.height;
26
+
25
27
  if (cellHeight !== 0) {
26
28
  const slack = host.clientHeight - term.rows * cellHeight;
27
29
  host.style.setProperty('--term-offset', `${Math.max(0, Math.floor(slack / 2))}px`);
28
30
  }
31
+
29
32
  return true;
30
33
  };
31
34
 
@@ -47,6 +50,7 @@ export const unscaledPointer = (
47
50
  ): Pointer => {
48
51
  const scaleX = layout.width > 0 && rect.width > 0 ? rect.width / layout.width : 1;
49
52
  const scaleY = layout.height > 0 && rect.height > 0 ? rect.height / layout.height : 1;
53
+
50
54
  return {
51
55
  clientX: rect.left + (pointer.clientX - rect.left) / scaleX,
52
56
  clientY: rect.top + (pointer.clientY - rect.top) / scaleY
@@ -54,18 +58,20 @@ export const unscaledPointer = (
54
58
  };
55
59
 
56
60
  /*
57
- * xterm measures a pointer against the screen's scaled bounding box but divides by unscaled cells, so
58
- * under an ancestor's scale() a selection or a click lands rows off, more so further down. Its one mouse
59
- * service (private, shared by selection, links and mouse reporting) gets the pointer as it would stand
60
- * without the transform. Call after `open`, which creates that service.
61
+ * xterm measures a pointer against the scaled bounding box but divides by unscaled cells, so under an
62
+ * ancestor's scale() a click lands rows off. Its private mouse service (shared by selection, links and
63
+ * mouse reporting) gets the unscaled pointer. Call after `open`, which creates that service.
61
64
  */
62
65
  export const followAncestorScale = (term: Terminal): void => {
63
66
  const mouse = (term as unknown as { _core: { _mouseService?: MouseService } })._core._mouseService;
67
+
64
68
  if (!mouse) {
65
69
  return;
66
70
  }
71
+
67
72
  const unscaled = (pointer: Pointer, element: HTMLElement): Pointer =>
68
73
  unscaledPointer(pointer, element.getBoundingClientRect(), { width: element.offsetWidth, height: element.offsetHeight });
74
+
69
75
  const getCoords = mouse.getCoords.bind(mouse);
70
76
  const getMouseReportCoords = mouse.getMouseReportCoords.bind(mouse);
71
77
  mouse.getCoords = (event, element, ...rest) => getCoords(unscaled(event, element), element, ...rest);