Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

surface.ts

1,437 lines52.6 KB

1import { isMacPlatform } from "../../lib/utils";
2import { collectWrappedTerminalLinkLine, extractTerminalLinks } from "../../terminal-links";
3import {
4 GhosttyTerminalCore,
5 type GhosttyScrollbar,
6 type GhosttySnapshot,
7 type GhosttyTheme,
8} from "./core";
9import {
10 measureGhosttyCell,
11 renderGhosttySnapshot,
12 terminalGridSize,
13 type GhosttyCellMetrics,
14} from "./renderer";
15import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
16​
17export const DEFAULT_TERMINAL_FONT_SIZE = 12;
18const MIN_TERMINAL_FONT_SIZE = 6;
19const MAX_TERMINAL_FONT_SIZE = 32;
20// The glyph fallbacks only supply symbols the text faces are missing (powerline
21// separators, devicons, and other private-use prompt symbols), so shells
22// configured for a locally installed Nerd Font keep their prompt glyphs no
23// matter which text face is active.
24const TERMINAL_GLYPH_FALLBACKS =
25 '"Symbols Nerd Font Mono", "Symbols Nerd Font", "JetBrainsMono Nerd Font", ' +
26 '"JetBrainsMono NF", "FiraCode Nerd Font", "Hack Nerd Font", "MesloLGS NF", ' +
27 '"CaskaydiaCove Nerd Font", "PowerlineSymbols", monospace';
28// SF Mono where the platform has it (macOS), otherwise the bundled JetBrains
29// Mono webfont, so the default rendering is identical everywhere else.
30export const DEFAULT_TERMINAL_FONT_FAMILY =
31 '"SF Mono", "SFMono-Regular", "JetBrains Mono", ' + TERMINAL_GLYPH_FALLBACKS;
32const CONTENT_PADDING = 4;
33const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
34/** Half a blink cycle: the visible and hidden phases are equally long. */
35const CURSOR_BLINK_INTERVAL_MS = 500;
36​
37/** Requested terminal font; omitted fields fall back to the defaults. */
38export interface GhosttyTerminalFont {
39 readonly family?: string;
40 readonly size?: number;
42​
43let symbolsFontLoad: Promise<void> | null = null;
44​
45/**
46 * Register the bundled symbols-only Nerd Font once per page. It loads lazily
47 * with the first terminal, and because it carries no regular text glyphs it
48 * composes with any text face without changing metrics — prompt symbols and
49 * devicons render even on machines without a locally installed Nerd Font.
50 */
51function ensureTerminalSymbolsFont(): Promise<void> {
52 if (symbolsFontLoad !== null) return symbolsFontLoad;
53 symbolsFontLoad = (async () => {
54 try {
55 const face = new FontFace("Symbols Nerd Font Mono", `url(${symbolsFontUrl})`);
56 document.fonts.add(await face.load());
57 } catch {
58 // Locally installed fallback faces still apply.
59 }
60 })();
61 return symbolsFontLoad;
63​
64export function terminalFontFamily(family?: string): string {
65 const custom = family?.trim();
66 if (!custom) return DEFAULT_TERMINAL_FONT_FAMILY;
67 // A custom face keeps the glyph fallbacks so prompt symbols stay covered.
68 return `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
70​
71export function terminalFontSize(size?: number): number {
72 if (size === undefined || !Number.isFinite(size)) return DEFAULT_TERMINAL_FONT_SIZE;
73 return Math.max(MIN_TERMINAL_FONT_SIZE, Math.min(MAX_TERMINAL_FONT_SIZE, Math.round(size)));
75​
76/**
77 * Whether the cursor should keep toggling. An unfocused surface draws a steady
78 * hollow cursor instead of blinking, and a reduced-motion reader gets a steady
79 * cursor too rather than a permanently animating element.
80 */
81export function shouldBlinkTerminalCursor(state: {
82 readonly focused: boolean;
83 readonly cursorBlinking: boolean;
84 readonly cursorVisible: boolean;
85 readonly reducedMotion: boolean;
86}): boolean {
87 return state.focused && state.cursorBlinking && state.cursorVisible && !state.reducedMotion;
89​
90/**
91 * Vertical origin of the grid inside the mount. While content is shorter than
92 * the viewport the grid sits at the top like a fresh terminal. Once scrollback
93 * exists the prompt lives on the bottom row, so the grid anchors to the bottom
94 * edge instead: the sub-row remainder moves above row 0 and resizing within a
95 * row boundary keeps the prompt pinned instead of snapping up and down.
96 */
97export function terminalContentOriginY(
98 mountHeight: number,
99 padding: number,
100 rows: number,
101 cellHeight: number,
102 anchorBottom: boolean,
103): number {
104 if (!anchorBottom) return padding;
105 const slack = mountHeight - padding * 2 - rows * cellHeight;
106 return padding + Math.max(0, slack);
108​
109export interface TerminalScrollbarGeometry {
110 readonly thumbHeight: number;
111 readonly thumbTop: number;
112 readonly maxOffset: number;
114​
115export function terminalScrollbarGeometry(
116 state: GhosttyScrollbar,
117 trackHeight: number,
118): TerminalScrollbarGeometry | null {
119 const total = Math.max(0, state.total);
120 const len = Math.max(0, Math.min(state.len, total));
121 const maxOffset = Math.max(0, total - len);
122 if (trackHeight <= 0 || len <= 0 || maxOffset === 0) return null;
123 const thumbHeight = Math.min(
124 trackHeight,
125 Math.max(MIN_SCROLLBAR_THUMB_HEIGHT, (trackHeight * len) / total),
126 );
127 const travel = Math.max(0, trackHeight - thumbHeight);
128 const offset = Math.max(0, Math.min(state.offset, maxOffset));
129 return {
130 thumbHeight,
131 thumbTop: travel * (offset / maxOffset),
132 maxOffset,
133 };
135​
136export function terminalScrollbarOffsetAtPointer(
137 state: GhosttyScrollbar,
138 trackHeight: number,
139 pointerY: number,
140 pointerOffset: number,
141): number {
142 const geometry = terminalScrollbarGeometry(state, trackHeight);
143 if (geometry === null) return 0;
144 const travel = Math.max(0, trackHeight - geometry.thumbHeight);
145 if (travel === 0) return 0;
146 const thumbTop = Math.max(0, Math.min(pointerY - pointerOffset, travel));
147 return Math.round((thumbTop / travel) * geometry.maxOffset);
149​
150function terminalRowText(row: GhosttySnapshot["rowData"][number], trimRight: boolean): string {
151 const text = row.cells.map((cell) => cell.text || " ").join("");
152 return trimRight ? text.trimEnd() : text;
154​
155function terminalColumnOffset(row: GhosttySnapshot["rowData"][number], column: number): number {
156 let offset = 0;
157 for (let cellIndex = 0; cellIndex < column; cellIndex += 1) {
158 offset += row.cells[cellIndex]?.text.length || 1;
159 }
160 return offset;
162​
163export function terminalLinkAtPosition(
164 rows: GhosttySnapshot["rowData"],
165 rowIndex: number,
166 column: number,
167): string | null {
168 const wrappedLine = collectWrappedTerminalLinkLine(rowIndex + 1, (index) => {
169 const row = rows[index];
170 if (!row) return null;
171 return {
172 isWrapped: row.isWrapContinuation,
173 translateToString: (trimRight = false) => terminalRowText(row, trimRight),
174 };
175 });
176 if (!wrappedLine) return null;
177 // Only viewport rows are available: a wrapped line whose head scrolled above
178 // the viewport would resolve a truncated match into a wrong link.
179 const firstSegment = wrappedLine.segments[0];
180 if (firstSegment && rows[firstSegment.bufferLineNumber - 1]?.isWrapContinuation) {
181 return null;
182 }
183 const segment = wrappedLine.segments.find((value) => value.bufferLineNumber === rowIndex + 1);
184 const row = rows[rowIndex];
185 if (!segment || !row) return null;
186 const lastSegment = wrappedLine.segments.at(-1);
187 const lastRow = lastSegment ? rows[lastSegment.bufferLineNumber - 1] : undefined;
188 // Ghostty's soft-wrap flag is authoritative: when the last collected row
189 // still wraps onward, its continuation is outside the viewport.
190 const continuesBelowViewport = lastRow !== undefined && lastRow.wrapsToNext;
191 const offset = segment.startIndex + terminalColumnOffset(row, column);
192 for (const match of extractTerminalLinks(wrappedLine.text)) {
193 if (offset >= match.start && offset < match.end) {
194 // A truncated tail must not activate as a complete link.
195 if (match.end === wrappedLine.text.length && continuesBelowViewport) return null;
196 return match.text;
197 }
198 }
199 return null;
201​
202export function terminalLinkAtColumn(row: GhosttySnapshot["rowData"][number], column: number) {
203 return terminalLinkAtPosition([row], 0, column);
205​
206export function isTerminalCopyShortcut(
207 event: Pick<KeyboardEvent, "ctrlKey" | "key" | "metaKey" | "shiftKey">,
208 platform = navigator.platform,
209) {
210 if (event.key.toLowerCase() !== "c") return false;
211 return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey;
213​
214export function isTerminalPasteShortcut(
215 event: Pick<KeyboardEvent, "ctrlKey" | "key" | "metaKey" | "shiftKey">,
216 platform = navigator.platform,
217) {
218 if (event.key.toLowerCase() !== "v") return false;
219 return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey;
221​
222export function isTerminalCompositionCommitInput(event: Pick<InputEvent, "inputType">): boolean {
223 return (
224 event.inputType === "" ||
225 event.inputType === "insertCompositionText" ||
226 event.inputType === "insertFromComposition"
227 );
229​
230export function isTerminalAltGraphText(
231 event: Pick<KeyboardEvent, "getModifierState" | "key">,
232): boolean {
233 return event.getModifierState("AltGraph") && [...event.key].length === 1;
235​
236export function shouldReportTerminalMouse(
237 tracking: boolean,
238 event: Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">,
239): boolean {
240 return tracking && !event.shiftKey && !event.ctrlKey && !event.metaKey;
242​
243export function terminalWheelDeltaRows(
244 event: Pick<WheelEvent, "deltaY" | "deltaMode">,
245 cellHeight: number,
246 viewportRows: number,
247 remainder: number,
248): { readonly rows: number; readonly remainder: number } {
249 // deltaMode: 0 pixels, 1 lines, 2 pages.
250 const pixels =
251 event.deltaMode === 1
252 ? event.deltaY * cellHeight
253 : event.deltaMode === 2
254 ? event.deltaY * viewportRows * cellHeight
255 : event.deltaY;
256 const total = remainder + pixels / cellHeight;
257 const rows = Math.trunc(total);
258 return { rows, remainder: total - rows };
260​
261export function terminalWheelArrowData(rows: number, applicationCursorKeys: boolean): string {
262 if (rows === 0) return "";
263 const sequence =
264 rows < 0
265 ? applicationCursorKeys
266 ? "\u001bOA"
267 : "\u001b[A"
268 : applicationCursorKeys
269 ? "\u001bOB"
270 : "\u001b[B";
271 return sequence.repeat(Math.abs(rows));
273​
274export function isTerminalLinkPointerGesture(
275 event: Pick<MouseEvent, "ctrlKey" | "metaKey">,
276 platform = navigator.platform,
277): boolean {
278 return isMacPlatform(platform)
279 ? event.metaKey && !event.ctrlKey
280 : event.ctrlKey && !event.metaKey;
282​
283export function ghosttyMouseButton(button: number): number | null {
284 switch (button) {
285 case 0:
286 return 1;
287 case 1:
288 return 3;
289 case 2:
290 return 2;
291 case 3:
292 return 4;
293 case 4:
294 return 5;
295 default:
296 return null;
297 }
299​
300export interface TerminalSelectionClickSequence {
301 readonly count: number;
302 readonly time: number;
303 readonly x: number;
304 readonly y: number;
306​
307export function advanceTerminalSelectionClickSequence(
308 previous: TerminalSelectionClickSequence | null,
309 event: Pick<PointerEvent, "clientX" | "clientY" | "timeStamp">,
310): TerminalSelectionClickSequence {
311 const repeats =
312 previous !== null &&
313 event.timeStamp - previous.time <= 500 &&
314 Math.hypot(event.clientX - previous.x, event.clientY - previous.y) <= 4;
315 return {
316 count: repeats ? (previous.count >= 3 ? 1 : previous.count + 1) : 1,
317 time: event.timeStamp,
318 x: event.clientX,
319 y: event.clientY,
320 };
322​
323export interface GhosttySelectionPosition {
324 readonly start: { readonly x: number; readonly y: number };
325 readonly end: { readonly x: number; readonly y: number };
327​
328export interface GhosttyTerminalSurfaceOptions {
329 readonly theme: GhosttyTheme;
330 readonly font?: GhosttyTerminalFont;
331 readonly onData: (data: string) => void;
332 readonly onResize: (cols: number, rows: number) => void;
333 readonly onSelectionChange: () => void;
334 readonly onCopy: (text: string) => void;
335 readonly beforeKey: (event: KeyboardEvent) => boolean;
336 readonly onLinkActivate: (text: string, event: MouseEvent) => void;
338​
339export class GhosttyTerminalSurface {
340 readonly canvas: HTMLCanvasElement;
341 readonly input: HTMLTextAreaElement;
342 readonly scrollbar: HTMLDivElement;
343 cols = 1;
344 rows = 1;
345​
346 private readonly mount: HTMLElement;
347 private readonly context: CanvasRenderingContext2D;
348 private readonly core: GhosttyTerminalCore;
349 private readonly options: GhosttyTerminalSurfaceOptions;
350 private metrics: GhosttyCellMetrics;
351 private fontFamily: string;
352 private fontSize: number;
353 private fontEpoch = 0;
354 private readonly resizeObserver: ResizeObserver;
355 private readonly scrollbarThumb: HTMLDivElement;
356 private snapshot: GhosttySnapshot | null = null;
357 private frame = 0;
358 private cursorTimer: number | null = null;
359 private compositionInputToSuppress: string | null = null;
360 private compositionSuppressionTimer: number | null = null;
361 private cursorOn = true;
362 private renderedCursorY: number | null = null;
363 private forceFullRender = true;
364 private scrollbarDirty = true;
365 private scrollbarState: GhosttyScrollbar | null = null;
366 private scrollbarPointerId: number | null = null;
367 private scrollbarPointerOffset = 0;
368 private disposed = false;
369 private resizeNotifyTimer: number | null = null;
370 private originY = CONTENT_PADDING;
371 private mountHeight = 0;
372 private selectionEnd: { x: number; y: number } | null = null;
373 private selectionAnchorScreen: { x: number; y: number } | null = null;
374 private selectionEndScreen: { x: number; y: number } | null = null;
375 private selectionMode: "cell" | "word" | "line" = "cell";
376 // Word/line selection base in screen coordinates so streaming output cannot
377 // shift the origin of a drag selection.
378 private selectionBase: {
379 start: { x: number; y: number };
380 end: { x: number; y: number };
381 } | null = null;
382 private selectionScrollTimer: number | null = null;
383 private selectionScrollDelta = 0;
384 private selectionPointer: { x: number; y: number } | null = null;
385 private mouseReportingPointerId: number | null = null;
386 private mouseReportingButton: number | null = null;
387 private linkActivationPointerId: number | null = null;
388 private selectionClickSequence: TerminalSelectionClickSequence | null = null;
389 private selectionMoved = false;
390 private composing = false;
391 private focused = false;
392 private resizeNotified = false;
393 private canvasConfigured = false;
394 private theme: GhosttyTheme;
395 private readonly suppressedKeyCodes = new Set<string>();
396 private pasteShortcutToken = 0;
397 private wheelRemainder = 0;
398 private dprMedia: MediaQueryList | null = null;
399 // Read live on every blink decision, and watched so that dropping the
400 // preference restarts a blink cycle that has no timer left to notice it.
401 private readonly reducedMotionMedia = window.matchMedia?.("(prefers-reduced-motion: reduce)");
402 private inputLeft = -1;
403 private inputTop = -1;
404​
405 private constructor(
406 mount: HTMLElement,
407 canvas: HTMLCanvasElement,
408 input: HTMLTextAreaElement,
409 scrollbar: HTMLDivElement,
410 scrollbarThumb: HTMLDivElement,
411 context: CanvasRenderingContext2D,
412 core: GhosttyTerminalCore,
413 metrics: GhosttyCellMetrics,
414 options: GhosttyTerminalSurfaceOptions,
415 ) {
416 this.mount = mount;
417 this.canvas = canvas;
418 this.input = input;
419 this.scrollbar = scrollbar;
420 this.scrollbarThumb = scrollbarThumb;
421 this.context = context;
422 this.core = core;
423 this.metrics = metrics;
424 this.options = options;
425 this.theme = options.theme;
426 this.fontFamily = terminalFontFamily(options.font?.family);
427 this.fontSize = terminalFontSize(options.font?.size);
428 this.resizeObserver = new ResizeObserver(() => this.fit());
429 this.installEvents();
430 this.watchDevicePixelRatio();
431 this.reducedMotionMedia?.addEventListener("change", this.onReducedMotionChange);
432 document.fonts.addEventListener("loadingdone", this.onFontsLoaded);
433 this.resizeObserver.observe(mount);
434 }
435​
436 static async create(
437 mount: HTMLElement,
438 options: GhosttyTerminalSurfaceOptions,
439 ): Promise<GhosttyTerminalSurface> {
440 const canvas = document.createElement("canvas");
441 canvas.className = "t3-ghostty-canvas";
442 canvas.style.cssText = "display:block;width:100%;height:100%;";
443 canvas.setAttribute("aria-hidden", "true");
444​
445 const input = document.createElement("textarea");
446 input.className = "t3-ghostty-input";
447 input.setAttribute("aria-label", "Terminal input");
448 input.autocapitalize = "off";
449 input.autocomplete = "off";
450 input.spellcheck = false;
451 input.style.cssText =
452 "position:absolute;left:4px;top:4px;width:1px;height:1px;opacity:0;padding:0;border:0;resize:none;pointer-events:none;";
453​
454 const scrollbar = document.createElement("div");
455 scrollbar.className = "t3-ghostty-scrollbar";
456 scrollbar.setAttribute("role", "scrollbar");
457 scrollbar.setAttribute("aria-label", "Terminal scrollback");
458 scrollbar.setAttribute("aria-orientation", "vertical");
459 scrollbar.tabIndex = 0;
460 scrollbar.hidden = true;
461 const scrollbarThumb = document.createElement("div");
462 scrollbarThumb.className = "t3-ghostty-scrollbar-thumb";
463 scrollbar.append(scrollbarThumb);
464 mount.replaceChildren(canvas, input, scrollbar);
465​
466 const context = canvas.getContext("2d", { alpha: false });
467 if (!context) throw new Error("Canvas 2D is unavailable");
468 const fontFamily = terminalFontFamily(options.font?.family);
469 const fontSize = terminalFontSize(options.font?.size);
470 try {
471 // Cell metrics must come from the faces that will render; measuring before
472 // the bundled webfonts load would size the grid from a fallback font.
473 await ensureTerminalSymbolsFont();
474 await document.fonts.load(`${fontSize}px ${fontFamily}`);
475 } catch {
476 // Metrics fall back to whichever faces are already available.
477 }
478 const metrics = measureGhosttyCell(context, fontSize, fontFamily);
479 const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
480 const core = await GhosttyTerminalCore.create(
481 grid.cols,
482 grid.rows,
483 metrics.width,
484 metrics.height,
485 options.theme,
486 options.onData,
487 );
488 const surface = new GhosttyTerminalSurface(
489 mount,
490 canvas,
491 input,
492 scrollbar,
493 scrollbarThumb,
494 context,
495 core,
496 metrics,
497 options,
498 );
499 surface.fit();
500 surface.requestRender();
501 return surface;
502 }
503​
504 write(data: string): void {
505 if (this.disposed) return;
506 this.core.write(data);
507 // Restart the blink cycle from the visible phase so the cursor never sits
508 // invisible through a stream of output or a burst of typing echo.
509 this.cursorOn = true;
510 this.scrollbarDirty = true;
511 this.requestRender();
512 }
513​
514 resetAndWrite(data: string): void {
515 if (this.disposed) return;
516 this.core.resetAndWrite(data);
517 // A replayed session starts from the visible phase like any other write:
518 // reattaching mid-blink must not open on an invisible cursor.
519 this.cursorOn = true;
520 this.forceFullRender = true;
521 this.scrollbarDirty = true;
522 this.requestRender();
523 }
524​
525 setTheme(theme: GhosttyTheme): void {
526 if (this.disposed) return;
527 this.theme = theme;
528 this.core.setTheme(theme);
529 this.forceFullRender = true;
530 this.requestRender();
531 }
532​
533 async setFont(font: GhosttyTerminalFont): Promise<void> {
534 if (this.disposed) return;
535 const fontFamily = terminalFontFamily(font.family);
536 const fontSize = terminalFontSize(font.size);
537 // The fields only change together with their metrics after the load, and
538 // the epoch lets the newest overlapping call win regardless of load order.
539 const epoch = ++this.fontEpoch;
540 try {
541 await document.fonts.load(`${fontSize}px ${fontFamily}`);
542 } catch {
543 // Metrics fall back to whichever faces are already available.
544 }
545 if (this.disposed || epoch !== this.fontEpoch) return;
546 this.fontFamily = fontFamily;
547 this.fontSize = fontSize;
548 this.applyFontMetrics();
549 }
550​
551 private applyFontMetrics(): void {
552 this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
553 this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
554 // Cached IME textarea coordinates are stale in the new cell geometry.
555 this.inputLeft = -1;
556 this.inputTop = -1;
557 this.forceFullRender = true;
558 this.scrollbarDirty = true;
559 this.fit();
560 this.requestRender();
561 }
562​
563 private readonly onReducedMotionChange = () => {
564 if (this.disposed) return;
565 // Nothing else wakes an idle steady cursor: the blink timer only reschedules
566 // from a render, and reduced motion is exactly the state that stopped it.
567 this.cursorOn = true;
568 this.requestRender();
569 };
570​
571 private readonly onFontsLoaded = () => {
572 if (this.disposed) return;
573 // A face that finished loading after the initial measurement changes glyph
574 // advances; re-measure and refit so the grid matches what actually renders.
575 const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
576 if (
577 metrics.width === this.metrics.width &&
578 metrics.height === this.metrics.height &&
579 metrics.baseline === this.metrics.baseline
580 ) {
581 return;
582 }
583 this.applyFontMetrics();
584 };
585​
586 fit(): boolean {
587 if (this.disposed) return false;
588 const width = this.mount.clientWidth;
589 const height = this.mount.clientHeight;
590 if (width <= 0 || height <= 0) return false;
591 const ratio = window.devicePixelRatio || 1;
592 const pixelWidth = Math.max(1, Math.round(width * ratio));
593 const pixelHeight = Math.max(1, Math.round(height * ratio));
594 let shouldRender = false;
595 // The DPR transform must be installed even when the target size happens to
596 // equal the canvas default 300x150 backing store, so the first fit always
597 // schedules a canvas configuration.
598 if (
599 this.canvas.width !== pixelWidth ||
600 this.canvas.height !== pixelHeight ||
601 !this.canvasConfigured
602 ) {
603 this.canvas.width = pixelWidth;
604 this.canvas.height = pixelHeight;
605 this.context.setTransform(ratio, 0, 0, ratio, 0, 0);
606 this.canvasConfigured = true;
607 this.forceFullRender = true;
608 this.scrollbarDirty = true;
609 shouldRender = true;
610 }
611 const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING);
612 this.mountHeight = height;
613 // onResize is the only PTY resize channel, so the first successful fit must
614 // notify even when the measured grid equals the 1x1 construction sentinel.
615 if (grid.cols !== this.cols || grid.rows !== this.rows || !this.resizeNotified) {
616 this.cols = grid.cols;
617 this.rows = grid.rows;
618 this.core.resize(grid.cols, grid.rows, this.metrics.width, this.metrics.height);
619 this.notifyResize();
620 this.forceFullRender = true;
621 this.scrollbarDirty = true;
622 shouldRender = true;
623 }
624 // Rendering synchronously keeps the repaint inside the same frame as the
625 // layout change: ResizeObserver fires before paint, so the browser never
626 // composites the old backing store stretched into the new element box.
627 if (shouldRender) this.renderFrame();
628 return true;
629 }
630​
631 /**
632 * The local grid reflows immediately, but the PTY only hears about settled
633 * dimensions: notifying on every drag step makes the shell reprint its
634 * prompt mid-drag, which reads as jitter.
635 */
636 private notifyResize(): void {
637 this.resizeNotified = true;
638 if (this.resizeNotifyTimer !== null) window.clearTimeout(this.resizeNotifyTimer);
639 this.resizeNotifyTimer = window.setTimeout(() => {
640 this.resizeNotifyTimer = null;
641 if (!this.disposed) this.options.onResize(this.cols, this.rows);
642 }, 150);
643 }
644​
645 focus(): void {
646 this.input.focus({ preventScroll: true });
647 }
648​
649 hasSelection(): boolean {
650 return this.core.selectionText().length > 0;
651 }
652​
653 getSelection(): string {
654 return this.core.selectionText();
655 }
656​
657 getSelectionPosition(): GhosttySelectionPosition | null {
658 if (!this.selectionAnchorScreen || !this.selectionEndScreen || !this.hasSelection())
659 return null;
660 const before =
661 this.selectionAnchorScreen.y < this.selectionEndScreen.y ||
662 (this.selectionAnchorScreen.y === this.selectionEndScreen.y &&
663 this.selectionAnchorScreen.x <= this.selectionEndScreen.x);
664 return before
665 ? { start: this.selectionAnchorScreen, end: this.selectionEndScreen }
666 : { start: this.selectionEndScreen, end: this.selectionAnchorScreen };
667 }
668​
669 getSelectionEndClientRect(): { readonly right: number; readonly bottom: number } | null {
670 const position = this.getSelectionPosition();
671 if (!position) return null;
672 const viewportEnd = this.core.screenPointToViewport(position.end.x, position.end.y);
673 if (!viewportEnd) return null;
674 const bounds = this.canvas.getBoundingClientRect();
675 return {
676 right: bounds.left + CONTENT_PADDING + (viewportEnd.x + 1) * this.metrics.width,
677 bottom: bounds.top + this.originY + (viewportEnd.y + 1) * this.metrics.height,
678 };
679 }
680​
681 clearSelection(): void {
682 this.core.clearSelection();
683 this.selectionEnd = null;
684 this.selectionAnchorScreen = null;
685 this.selectionEndScreen = null;
686 this.selectionMode = "cell";
687 this.selectionBase = null;
688 this.setSelectionAutoscroll(0);
689 this.options.onSelectionChange();
690 // Selection highlights span rows Ghostty may not mark dirty for this change.
691 this.forceFullRender = true;
692 this.requestRender();
693 }
694​
695 scrollToBottom(): void {
696 this.core.scrollToBottom();
697 this.forceFullRender = true;
698 this.scrollbarDirty = true;
699 this.requestRender();
700 }
701​
702 isAtBottom(): boolean {
703 return this.core.isViewportActive();
704 }
705​
706 dispose(): void {
707 if (this.disposed) return;
708 this.disposed = true;
709 this.resizeObserver.disconnect();
710 document.fonts.removeEventListener("loadingdone", this.onFontsLoaded);
711 this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
712 this.dprMedia = null;
713 this.reducedMotionMedia?.removeEventListener("change", this.onReducedMotionChange);
714 if (this.selectionScrollTimer !== null) window.clearInterval(this.selectionScrollTimer);
715 if (this.resizeNotifyTimer !== null) {
716 window.clearTimeout(this.resizeNotifyTimer);
717 this.resizeNotifyTimer = null;
718 // Flush the settled dimensions so the PTY keeps the final size even when
719 // the surface unmounts inside the debounce window.
720 this.options.onResize(this.cols, this.rows);
721 }
722 if (this.frame !== 0) window.cancelAnimationFrame(this.frame);
723 if (this.cursorTimer !== null) window.clearTimeout(this.cursorTimer);
724 if (this.compositionSuppressionTimer !== null) {
725 window.clearTimeout(this.compositionSuppressionTimer);
726 }
727 this.removeEvents();
728 this.core.dispose();
729 if (
730 this.canvas.parentElement === this.mount ||
731 this.input.parentElement === this.mount ||
732 this.scrollbar.parentElement === this.mount
733 ) {
734 this.canvas.remove();
735 this.input.remove();
736 this.scrollbar.remove();
737 }
738 }
739​
740 private readonly onKeyDown = (event: KeyboardEvent) => {
741 // Presses handled outside the terminal must also swallow their release:
742 // beforeKey runs side effects (keybindings, navigation sends), so it cannot
743 // be consulted again on keyup, and Kitty report-event-types sessions would
744 // otherwise receive a release for a press the shell never saw.
745 if (isTerminalAltGraphText(event) || !this.options.beforeKey(event)) {
746 this.suppressedKeyCodes.add(event.code);
747 return;
748 }
749 if (isTerminalCopyShortcut(event) && this.hasSelection()) {
750 event.preventDefault();
751 this.suppressedKeyCodes.add(event.code);
752 this.options.onCopy(this.getSelection());
753 return;
754 }
755 if (isTerminalPasteShortcut(event)) {
756 this.suppressedKeyCodes.add(event.code);
757 const clipboard = navigator.clipboard;
758 if (typeof clipboard?.readText === "function") {
759 // Race the async clipboard read against the browser's own paste event:
760 // the native event (dispatched synchronously with the default action)
761 // always claims the token first when it fires, and the read covers
762 // browsers whose paste shortcut produces no paste event. Not preventing
763 // the default keeps the native path alive when the read is denied.
764 const token = ++this.pasteShortcutToken;
765 void clipboard.readText().then(
766 (text) => {
767 if (this.disposed || this.pasteShortcutToken !== token) return;
768 this.pasteShortcutToken += 1;
769 if (text.length > 0) this.options.onData(this.core.encodePaste(text));
770 },
771 () => {
772 // Clipboard read denied; the native paste event remains the path.
773 },
774 );
775 }
776 return;
777 }
778 // keyCode 229 is Safari's only signal that this keydown opens an IME
779 // composition; encoding it would double the committed text.
780 if (event.isComposing || this.composing || event.key === "Process" || event.keyCode === 229) {
781 return;
782 }
783 const data = this.core.encodeKey(event);
784 if (data.length === 0) return;
785 this.suppressedKeyCodes.delete(event.code);
786 event.preventDefault();
787 event.stopPropagation();
788 this.options.onData(data);
789 };
790​
791 private readonly onKeyUp = (event: KeyboardEvent) => {
792 if (this.suppressedKeyCodes.delete(event.code)) return;
793 if (event.isComposing || this.composing || event.key === "Process" || event.keyCode === 229) {
794 return;
795 }
796 // Ghostty's encoder only emits release codes when the terminal enabled the
797 // Kitty report-event-types flag, so legacy sessions send nothing here.
798 const data = this.core.encodeKey(event, "release");
799 if (data.length === 0) return;
800 event.preventDefault();
801 event.stopPropagation();
802 this.options.onData(data);
803 };
804​
805 private readonly onFocus = () => {
806 this.focused = true;
807 this.cursorOn = true;
808 this.requestRender();
809 };
810​
811 private readonly onBlur = () => {
812 this.focused = false;
813 // Suppressions survive blur deliberately: a shortcut that moves focus (for
814 // example terminal-toggle) must still swallow its own keyup if focus comes
815 // back before release. Stale entries are harmless — an encoding keydown
816 // always removes its code first.
817 // The steady unfocused hollow cursor must not inherit an off blink phase.
818 this.cursorOn = true;
819 this.requestRender();
820 };
821​
822 private readonly onDevicePixelRatioChange = () => {
823 this.watchDevicePixelRatio();
824 this.fit();
825 };
826​
827 private watchDevicePixelRatio(): void {
828 this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
829 // A resolution media query only fires once for the ratio it was created at,
830 // so re-arm it after every change (monitor moves, browser zoom).
831 this.dprMedia = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
832 this.dprMedia.addEventListener("change", this.onDevicePixelRatioChange);
833 }
834​
835 private readonly onPaste = (event: ClipboardEvent) => {
836 // Always suppress the browser's default insertion: content the textarea
837 // would receive (for example an html-only clipboard converted to text)
838 // leaks through onInput without bracketed-paste encoding.
839 event.preventDefault();
840 const data = event.clipboardData?.getData("text/plain") ?? "";
841 if (data.length === 0) return;
842 // The native paste won the race with actual text; a pending clipboard read
843 // must not double. An empty native paste leaves the read as the only path.
844 this.pasteShortcutToken += 1;
845 this.options.onData(this.core.encodePaste(data));
846 };
847​
848 private readonly onCompositionStart = () => {
849 this.clearCompositionInputSuppression();
850 this.composing = true;
851 };
852​
853 private readonly onCompositionEnd = (event: CompositionEvent) => {
854 this.composing = false;
855 const data = this.input.value || event.data;
856 if (data.length > 0) this.options.onData(data);
857 this.input.value = "";
858 this.compositionInputToSuppress = data;
859 this.compositionSuppressionTimer = window.setTimeout(() => {
860 this.compositionInputToSuppress = null;
861 this.compositionSuppressionTimer = null;
862 }, 100);
863 };
864​
865 private readonly onInput = (event: Event) => {
866 const inputEvent = event as InputEvent;
867 if (this.composing || inputEvent.isComposing) return;
868 const data = this.input.value || inputEvent.data || "";
869 if (data === this.compositionInputToSuppress && isTerminalCompositionCommitInput(inputEvent)) {
870 this.clearCompositionInputSuppression();
871 this.input.value = "";
872 return;
873 }
874 this.clearCompositionInputSuppression();
875 if (data.length > 0) this.options.onData(data);
876 this.input.value = "";
877 };
878​
879 private clearCompositionInputSuppression(): void {
880 if (this.compositionSuppressionTimer !== null) {
881 window.clearTimeout(this.compositionSuppressionTimer);
882 this.compositionSuppressionTimer = null;
883 }
884 this.compositionInputToSuppress = null;
885 }
886​
887 private readonly onPointerDown = (event: PointerEvent) => {
888 this.focus();
889 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
890 const button = ghosttyMouseButton(event.button);
891 if (button === null) return;
892 event.preventDefault();
893 event.stopPropagation();
894 this.mouseReportingPointerId = event.pointerId;
895 this.mouseReportingButton = button;
896 this.sendMouse("press", button, event);
897 this.canvas.setPointerCapture(event.pointerId);
898 return;
899 }
900 if (event.button !== 0) return;
901 if (isTerminalLinkPointerGesture(event)) {
902 event.preventDefault();
903 event.stopPropagation();
904 this.linkActivationPointerId = event.pointerId;
905 this.canvas.setPointerCapture(event.pointerId);
906 return;
907 }
908 const cell = this.cellAt(event.clientX, event.clientY);
909 this.selectionMoved = false;
910 this.selectionClickSequence = advanceTerminalSelectionClickSequence(
911 this.selectionClickSequence,
912 event,
913 );
914 const clickCount = this.selectionClickSequence.count;
915 this.selectionMode = clickCount >= 3 ? "line" : clickCount === 2 ? "word" : "cell";
916 const range =
917 this.selectionMode === "line"
918 ? this.core.selectLine(cell.x, cell.y)
919 : this.selectionMode === "word"
920 ? this.core.selectWord(cell.x, cell.y)
921 : null;
922 if (range) {
923 this.selectionBase = range.screen;
924 this.selectionEnd = range.viewport.end;
925 this.selectionAnchorScreen = range.screen.start;
926 this.selectionEndScreen = range.screen.end;
927 this.options.onSelectionChange();
928 } else {
929 this.selectionMode = "cell";
930 this.selectionBase = null;
931 this.selectionEnd = cell;
932 const screen = this.core.viewportPointToScreen(cell.x, cell.y);
933 this.selectionAnchorScreen = screen;
934 this.selectionEndScreen = screen;
935 if (screen) {
936 this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
937 } else {
938 this.core.setSelection(cell, cell);
939 }
940 }
941 this.forceFullRender = true;
942 this.canvas.setPointerCapture(event.pointerId);
943 this.requestRender();
944 };
945​
946 private readonly onPointerMove = (event: PointerEvent) => {
947 if (this.linkActivationPointerId === event.pointerId) return;
948 // Hover motion is only reportable in any-event tracking (DEC 1003); normal and
949 // button-event tracking never report motion without a captured pressed button.
950 if (
951 this.mouseReportingPointerId === event.pointerId ||
952 shouldReportTerminalMouse(this.core.isMouseAnyEventTracking(), event)
953 ) {
954 event.preventDefault();
955 this.canvas.style.cursor = "default";
956 this.sendMouse("motion", this.buttonFromButtons(event.buttons), event);
957 return;
958 }
959 if (!this.selectionAnchorScreen || !this.canvas.hasPointerCapture(event.pointerId)) {
960 this.updateHoverCursor(event);
961 return;
962 }
963 this.selectionPointer = { x: event.clientX, y: event.clientY };
964 const bounds = this.canvas.getBoundingClientRect();
965 this.setSelectionAutoscroll(
966 event.clientY < bounds.top ? -1 : event.clientY > bounds.bottom ? 1 : 0,
967 );
968 const cell = this.cellAt(event.clientX, event.clientY);
969 if (cell.x === this.selectionEnd?.x && cell.y === this.selectionEnd.y) return;
970 this.extendSelectionTo(event.clientX, event.clientY);
971 };
972​
973 private extendSelectionTo(clientX: number, clientY: number): void {
974 const anchorScreen = this.selectionAnchorScreen;
975 if (anchorScreen === null) return;
976 const cell = this.cellAt(clientX, clientY);
977 this.selectionMoved = true;
978 this.selectionEnd = cell;
979 const range =
980 this.selectionMode === "line"
981 ? this.core.selectLine(cell.x, cell.y)
982 : this.selectionMode === "word"
983 ? this.core.selectWord(cell.x, cell.y)
984 : null;
985 const cellScreen = this.core.viewportPointToScreen(cell.x, cell.y);
986 if (cellScreen === null) return;
987 const base = this.selectionBase;
988 const beforeBase =
989 base !== null &&
990 (cellScreen.y < base.start.y ||
991 (cellScreen.y === base.start.y && cellScreen.x < base.start.x));
992 const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
993 const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
994 this.selectionAnchorScreen = anchor;
995 this.selectionEndScreen = end;
996 this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
997 this.options.onSelectionChange();
998 this.forceFullRender = true;
999 this.requestRender();
1001​
1002 private setSelectionAutoscroll(delta: number): void {
1003 this.selectionScrollDelta = delta;
1004 if (delta === 0) {
1005 if (this.selectionScrollTimer !== null) {
1006 window.clearInterval(this.selectionScrollTimer);
1007 this.selectionScrollTimer = null;
1009 return;
1011 if (this.selectionScrollTimer !== null) return;
1012 // Dragging past the edge scrolls the viewport and keeps extending the
1013 // selection into the newly revealed rows, like xterm's drag scroller.
1014 this.selectionScrollTimer = window.setInterval(() => {
1015 if (this.disposed || this.selectionScrollDelta === 0) return;
1016 this.scrollViewport(this.selectionScrollDelta);
1017 const pointer = this.selectionPointer;
1018 if (pointer) this.extendSelectionTo(pointer.x, pointer.y);
1019 }, 80);
1021​
1022 private updateHoverCursor(event: PointerEvent): void {
1023 const overLink =
1024 isTerminalLinkPointerGesture(event) && this.linkAt(event.clientX, event.clientY) !== null;
1025 const cursor = overLink ? "pointer" : "";
1026 if (this.canvas.style.cursor !== cursor) this.canvas.style.cursor = cursor;
1028​
1029 private readonly onPointerUp = (event: PointerEvent) => {
1030 this.setSelectionAutoscroll(0);
1031 if (this.linkActivationPointerId === event.pointerId) {
1032 event.preventDefault();
1033 event.stopPropagation();
1034 this.linkActivationPointerId = null;
1035 if (this.canvas.hasPointerCapture(event.pointerId)) {
1036 this.canvas.releasePointerCapture(event.pointerId);
1038 if (event.type !== "pointercancel") {
1039 const link = this.linkAt(event.clientX, event.clientY);
1040 if (link) this.options.onLinkActivate(link, event);
1042 return;
1044 if (this.mouseReportingPointerId === event.pointerId) {
1045 event.preventDefault();
1046 event.stopPropagation();
1047 this.sendMouse("release", this.mouseReportingButton, event);
1048 this.mouseReportingPointerId = null;
1049 this.mouseReportingButton = null;
1050 if (this.canvas.hasPointerCapture(event.pointerId)) {
1051 this.canvas.releasePointerCapture(event.pointerId);
1053 return;
1055 if (this.canvas.hasPointerCapture(event.pointerId)) {
1056 this.canvas.releasePointerCapture(event.pointerId);
1058 if (event.button !== 0) return;
1059 if (!this.selectionMoved && this.selectionMode === "cell") {
1060 this.clearSelection();
1062 this.options.onSelectionChange();
1063 };
1064​
1065 private readonly onWheel = (event: WheelEvent) => {
1066 if (event.deltaY === 0) return;
1067 event.preventDefault();
1068 const delta = terminalWheelDeltaRows(
1069 event,
1070 this.metrics.height,
1071 this.rows,
1072 this.wheelRemainder,
1073 );
1074 this.wheelRemainder = delta.remainder;
1075 if (delta.rows === 0) return;
1076 const magnitude = Math.abs(delta.rows);
1077 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
1078 const button = delta.rows < 0 ? 4 : 5;
1079 for (let index = 0; index < magnitude; index += 1) {
1080 this.sendMouse("press", button, event);
1082 return;
1084 if (this.core.isAlternateScreen()) {
1085 // The alternate screen has no scrollback: translate wheel motion into
1086 // arrow keys so full-screen apps like vim and less scroll, matching xterm.
1087 this.options.onData(terminalWheelArrowData(delta.rows, this.core.isApplicationCursorKeys()));
1088 return;
1090 this.scrollViewport(delta.rows);
1091 };
1092​
1093 private readonly onMouseDown = (event: MouseEvent) => {
1094 if (event.button === 0) event.preventDefault();
1095 this.focus();
1096 };
1097​
1098 private readonly onContextMenu = (event: MouseEvent) => {
1099 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
1100 event.preventDefault();
1102 };
1103​
1104 private readonly onScrollbarPointerDown = (event: PointerEvent) => {
1105 if (event.button !== 0) return;
1106 const state = this.readScrollbarState();
1107 if (state === null) return;
1108 const bounds = this.scrollbar.getBoundingClientRect();
1109 const geometry = terminalScrollbarGeometry(state, bounds.height);
1110 if (geometry === null) return;
1111 event.preventDefault();
1112 event.stopPropagation();
1113 this.scrollbarPointerId = event.pointerId;
1114 this.scrollbarPointerOffset =
1115 event.target === this.scrollbarThumb
1116 ? event.clientY - bounds.top - geometry.thumbTop
1117 : geometry.thumbHeight / 2;
1118 this.scrollbar.setPointerCapture(event.pointerId);
1119 this.scrollbarToPointer(event.clientY, bounds);
1120 };
1121​
1122 private readonly onScrollbarPointerMove = (event: PointerEvent) => {
1123 if (event.pointerId !== this.scrollbarPointerId || this.scrollbarState === null) return;
1124 event.preventDefault();
1125 this.scrollbarToPointer(event.clientY, this.scrollbar.getBoundingClientRect());
1126 };
1127​
1128 private readonly onScrollbarPointerUp = (event: PointerEvent) => {
1129 if (event.pointerId !== this.scrollbarPointerId) return;
1130 event.preventDefault();
1131 this.scrollbarPointerId = null;
1132 if (this.scrollbar.hasPointerCapture(event.pointerId)) {
1133 this.scrollbar.releasePointerCapture(event.pointerId);
1135 };
1136​
1137 private readonly onScrollbarKeyDown = (event: KeyboardEvent) => {
1138 const state = this.readScrollbarState();
1139 if (state === null) return;
1140 let delta = 0;
1141 switch (event.key) {
1142 case "ArrowUp":
1143 delta = -1;
1144 break;
1145 case "ArrowDown":
1146 delta = 1;
1147 break;
1148 case "PageUp":
1149 delta = -Math.max(1, state.len);
1150 break;
1151 case "PageDown":
1152 delta = Math.max(1, state.len);
1153 break;
1154 case "Home":
1155 delta = -state.offset;
1156 break;
1157 case "End":
1158 delta = state.total - state.len - state.offset;
1159 break;
1160 default:
1161 return;
1163 event.preventDefault();
1164 event.stopPropagation();
1165 this.scrollViewport(delta);
1166 };
1167​
1168 private installEvents(): void {
1169 this.input.addEventListener("keydown", this.onKeyDown);
1170 this.input.addEventListener("keyup", this.onKeyUp);
1171 this.input.addEventListener("focus", this.onFocus);
1172 this.input.addEventListener("blur", this.onBlur);
1173 this.input.addEventListener("input", this.onInput);
1174 this.input.addEventListener("paste", this.onPaste);
1175 this.input.addEventListener("compositionstart", this.onCompositionStart);
1176 this.input.addEventListener("compositionend", this.onCompositionEnd);
1177 this.canvas.addEventListener("pointerdown", this.onPointerDown);
1178 this.canvas.addEventListener("pointermove", this.onPointerMove);
1179 this.canvas.addEventListener("pointerup", this.onPointerUp);
1180 this.canvas.addEventListener("pointercancel", this.onPointerUp);
1181 this.canvas.addEventListener("wheel", this.onWheel, { passive: false });
1182 this.canvas.addEventListener("mousedown", this.onMouseDown);
1183 this.canvas.addEventListener("contextmenu", this.onContextMenu);
1184 this.scrollbar.addEventListener("pointerdown", this.onScrollbarPointerDown);
1185 this.scrollbar.addEventListener("pointermove", this.onScrollbarPointerMove);
1186 this.scrollbar.addEventListener("pointerup", this.onScrollbarPointerUp);
1187 this.scrollbar.addEventListener("pointercancel", this.onScrollbarPointerUp);
1188 this.scrollbar.addEventListener("keydown", this.onScrollbarKeyDown);
1190​
1191 private removeEvents(): void {
1192 this.input.removeEventListener("keydown", this.onKeyDown);
1193 this.input.removeEventListener("keyup", this.onKeyUp);
1194 this.input.removeEventListener("focus", this.onFocus);
1195 this.input.removeEventListener("blur", this.onBlur);
1196 this.input.removeEventListener("input", this.onInput);
1197 this.input.removeEventListener("paste", this.onPaste);
1198 this.input.removeEventListener("compositionstart", this.onCompositionStart);
1199 this.input.removeEventListener("compositionend", this.onCompositionEnd);
1200 this.canvas.removeEventListener("pointerdown", this.onPointerDown);
1201 this.canvas.removeEventListener("pointermove", this.onPointerMove);
1202 this.canvas.removeEventListener("pointerup", this.onPointerUp);
1203 this.canvas.removeEventListener("pointercancel", this.onPointerUp);
1204 this.canvas.removeEventListener("wheel", this.onWheel);
1205 this.canvas.removeEventListener("mousedown", this.onMouseDown);
1206 this.canvas.removeEventListener("contextmenu", this.onContextMenu);
1207 this.scrollbar.removeEventListener("pointerdown", this.onScrollbarPointerDown);
1208 this.scrollbar.removeEventListener("pointermove", this.onScrollbarPointerMove);
1209 this.scrollbar.removeEventListener("pointerup", this.onScrollbarPointerUp);
1210 this.scrollbar.removeEventListener("pointercancel", this.onScrollbarPointerUp);
1211 this.scrollbar.removeEventListener("keydown", this.onScrollbarKeyDown);
1213​
1214 private scrollViewport(deltaRows: number): void {
1215 let delta = Math.trunc(deltaRows);
1216 const state = this.readScrollbarState();
1217 if (state !== null) {
1218 const maxOffset = Math.max(0, state.total - state.len);
1219 const offset = Math.max(0, Math.min(state.offset + delta, maxOffset));
1220 delta = offset - state.offset;
1221 this.scrollbarState = { ...state, offset };
1223 if (delta === 0) return;
1224 this.core.scroll(delta);
1225 this.forceFullRender = true;
1226 this.scrollbarDirty = true;
1227 this.requestRender();
1229​
1230 private scrollbarToPointer(clientY: number, bounds: DOMRect): void {
1231 const state = this.scrollbarState;
1232 if (state === null) return;
1233 const offset = terminalScrollbarOffsetAtPointer(
1234 state,
1235 bounds.height,
1236 clientY - bounds.top,
1237 this.scrollbarPointerOffset,
1238 );
1239 this.scrollViewport(offset - state.offset);
1241​
1242 private updateScrollbar(): void {
1243 const state = this.readScrollbarState();
1244 const geometry =
1245 state === null
1246 ? null
1247 : terminalScrollbarGeometry(
1248 state,
1249 Math.max(0, this.mount.clientHeight - CONTENT_PADDING * 2),
1250 );
1251 this.scrollbar.hidden = geometry === null;
1252 if (state === null || geometry === null) return;
1253 this.scrollbar.setAttribute("aria-valuemin", "0");
1254 this.scrollbar.setAttribute("aria-valuemax", String(geometry.maxOffset));
1255 this.scrollbar.setAttribute(
1256 "aria-valuenow",
1257 String(Math.max(0, Math.min(state.offset, geometry.maxOffset))),
1258 );
1259 this.scrollbarThumb.style.height = `${geometry.thumbHeight}px`;
1260 this.scrollbarThumb.style.transform = `translateY(${geometry.thumbTop}px)`;
1262​
1263 private readScrollbarState(): GhosttyScrollbar | null {
1264 const state = this.core.scrollbarState();
1265 this.scrollbarState = state;
1266 return state;
1268​
1269 private requestRender(): void {
1270 if (this.disposed || this.frame !== 0) return;
1271 this.frame = window.requestAnimationFrame(() => {
1272 this.frame = 0;
1273 this.renderFrame();
1274 });
1276​
1277 private renderFrame(): void {
1278 if (this.disposed) return;
1279 if (this.frame !== 0) {
1280 window.cancelAnimationFrame(this.frame);
1281 this.frame = 0;
1283 this.snapshot = this.core.snapshot();
1284 // A cursor that is not blinking right now must be drawn, never caught in an
1285 // off phase left behind by a blink that has since been turned off.
1286 if (!this.blinkEnabled()) this.cursorOn = true;
1287 // The origin only moves together with a forced full repaint: partial
1288 // dirty-row redraws must never composite rows at a shifted origin over
1289 // rows painted at the previous one. Bottom anchoring starts once
1290 // scrollback exists, i.e. when the prompt actually lives at the bottom.
1291 const scrollState = this.readScrollbarState();
1292 const anchorBottom = scrollState !== null && scrollState.total > scrollState.len;
1293 const nextOriginY = terminalContentOriginY(
1294 this.mountHeight,
1295 CONTENT_PADDING,
1296 this.rows,
1297 this.metrics.height,
1298 anchorBottom,
1299 );
1300 if (nextOriginY !== this.originY) {
1301 this.originY = nextOriginY;
1302 this.forceFullRender = true;
1304 renderGhosttySnapshot({
1305 context: this.context,
1306 snapshot: this.snapshot,
1307 metrics: this.metrics,
1308 fontSize: this.fontSize,
1309 fontFamily: this.fontFamily,
1310 padding: CONTENT_PADDING,
1311 originY: this.originY,
1312 forceFull: this.forceFullRender,
1313 cursorOn: this.cursorOn,
1314 previousCursorY: this.renderedCursorY,
1315 focused: this.focused,
1316 ...(this.theme.selectionBackground !== undefined
1317 ? { selectionBackground: this.theme.selectionBackground }
1318 : {}),
1319 });
1320 this.positionInput();
1321 this.renderedCursorY =
1322 this.cursorOn && this.snapshot.cursorVisible && this.snapshot.cursorY >= 0
1323 ? this.snapshot.cursorY
1324 : null;
1325 if (this.scrollbarDirty) {
1326 this.scrollbarDirty = false;
1327 this.updateScrollbar();
1329 this.forceFullRender = false;
1330 this.scheduleCursorBlink();
1332​
1333 private scheduleCursorBlink(): void {
1334 if (this.cursorTimer !== null) window.clearTimeout(this.cursorTimer);
1335 this.cursorTimer = null;
1336 if (!this.blinkEnabled()) return;
1337 this.cursorTimer = window.setTimeout(() => {
1338 this.cursorTimer = null;
1339 this.cursorOn = !this.cursorOn;
1340 this.requestRender();
1341 }, CURSOR_BLINK_INTERVAL_MS);
1343​
1344 private blinkEnabled(): boolean {
1345 const snapshot = this.snapshot;
1346 if (!snapshot) return false;
1347 return shouldBlinkTerminalCursor({
1348 focused: this.focused,
1349 cursorBlinking: snapshot.cursorBlinking,
1350 cursorVisible: snapshot.cursorVisible,
1351 reducedMotion: this.reducedMotionMedia?.matches ?? false,
1352 });
1354​
1355 private positionInput(): void {
1356 const snapshot = this.snapshot;
1357 if (!snapshot || !snapshot.cursorVisible || snapshot.cursorX < 0 || snapshot.cursorY < 0) {
1358 return;
1360 // The IME candidate window anchors to the textarea, so it must follow the
1361 // terminal cursor for composition to appear where the user is typing.
1362 const left = CONTENT_PADDING + snapshot.cursorX * this.metrics.width;
1363 const top = this.originY + snapshot.cursorY * this.metrics.height;
1364 if (left === this.inputLeft && top === this.inputTop) return;
1365 this.inputLeft = left;
1366 this.inputTop = top;
1367 this.input.style.left = `${left}px`;
1368 this.input.style.top = `${top}px`;
1369 this.input.style.height = `${this.metrics.height}px`;
1371​
1372 private cellAt(clientX: number, clientY: number): { x: number; y: number } {
1373 const bounds = this.canvas.getBoundingClientRect();
1374 return {
1375 x: Math.max(
1376 0,
1377 Math.min(
1378 this.cols - 1,
1379 Math.floor((clientX - bounds.left - CONTENT_PADDING) / this.metrics.width),
1380 ),
1381 ),
1382 y: Math.max(
1383 0,
1384 Math.min(
1385 this.rows - 1,
1386 Math.floor((clientY - bounds.top - this.originY) / this.metrics.height),
1387 ),
1388 ),
1389 };
1391​
1392 private linkAt(clientX: number, clientY: number): string | null {
1393 if (!this.snapshot) return null;
1394 const cell = this.cellAt(clientX, clientY);
1395 const explicitHyperlink = this.core.hyperlinkAt(cell.x, cell.y);
1396 if (explicitHyperlink) return explicitHyperlink;
1397 return terminalLinkAtPosition(this.snapshot.rowData, cell.y, cell.x);
1399​
1400 private sendMouse(
1401 action: "press" | "release" | "motion",
1402 button: number | null,
1403 event: MouseEvent,
1404 ): void {
1405 const bounds = this.canvas.getBoundingClientRect();
1406 const data = this.core.encodeMouse({
1407 action,
1408 button,
1409 mods:
1410 (event.shiftKey ? 1 : 0) |
1411 (event.ctrlKey ? 1 << 1 : 0) |
1412 (event.altKey ? 1 << 2 : 0) |
1413 (event.metaKey ? 1 << 3 : 0),
1414 x: Math.max(0, event.clientX - bounds.left),
1415 y: Math.max(0, event.clientY - bounds.top),
1416 screenWidth: bounds.width,
1417 screenHeight: bounds.height,
1418 cellWidth: this.metrics.width,
1419 cellHeight: this.metrics.height,
1420 paddingLeft: CONTENT_PADDING,
1421 paddingRight: CONTENT_PADDING,
1422 paddingTop: this.originY,
1423 paddingBottom: Math.max(0, bounds.height - this.originY - this.rows * this.metrics.height),
1424 anyButtonPressed: event.buttons !== 0,
1425 });
1426 if (data.length > 0) this.options.onData(data);
1428​
1429 private buttonFromButtons(buttons: number): number | null {
1430 if ((buttons & 1) !== 0) return 1;
1431 if ((buttons & 4) !== 0) return 3;
1432 if ((buttons & 2) !== 0) return 2;
1433 if ((buttons & 8) !== 0) return 4;
1434 if ((buttons & 16) !== 0) return 5;
1435 return null;