@bigpixelrocket/uiok 0.0.0-stage → 0.1.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.
Files changed (280) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +569 -0
  4. package/README.md +44 -2
  5. package/dist/VisuallyHidden.d.ts +13 -0
  6. package/dist/VisuallyHidden.js +13 -0
  7. package/dist/activity/ActivityBar.d.ts +29 -0
  8. package/dist/activity/ActivityBar.js +21 -0
  9. package/dist/activity/activity.css +43 -0
  10. package/dist/activity/index.d.ts +2 -0
  11. package/dist/activity/index.js +2 -0
  12. package/dist/button/Button.d.ts +26 -0
  13. package/dist/button/Button.js +14 -0
  14. package/dist/button/IconButton.d.ts +18 -0
  15. package/dist/button/IconButton.js +14 -0
  16. package/dist/button/button.css +95 -0
  17. package/dist/button/index.d.ts +3 -0
  18. package/dist/button/index.js +3 -0
  19. package/dist/charts/Drawing.d.ts +27 -0
  20. package/dist/charts/Drawing.js +117 -0
  21. package/dist/charts/Drawing.logic.d.ts +2 -0
  22. package/dist/charts/Drawing.logic.js +22 -0
  23. package/dist/charts/Line.logic.d.ts +33 -0
  24. package/dist/charts/Line.logic.js +72 -0
  25. package/dist/charts/LineChart.d.ts +34 -0
  26. package/dist/charts/LineChart.js +100 -0
  27. package/dist/charts/Pie.logic.d.ts +16 -0
  28. package/dist/charts/Pie.logic.js +28 -0
  29. package/dist/charts/PieChart.d.ts +20 -0
  30. package/dist/charts/PieChart.js +16 -0
  31. package/dist/charts/ResultChart.d.ts +47 -0
  32. package/dist/charts/ResultChart.js +175 -0
  33. package/dist/charts/ResultChart.logic.d.ts +42 -0
  34. package/dist/charts/ResultChart.logic.js +165 -0
  35. package/dist/charts/Scatter.logic.d.ts +55 -0
  36. package/dist/charts/Scatter.logic.js +134 -0
  37. package/dist/charts/ScatterChart.d.ts +36 -0
  38. package/dist/charts/ScatterChart.js +99 -0
  39. package/dist/charts/charts.css +310 -0
  40. package/dist/charts/index.d.ts +14 -0
  41. package/dist/charts/index.js +11 -0
  42. package/dist/charts/seriesColour.d.ts +2 -0
  43. package/dist/charts/seriesColour.js +8 -0
  44. package/dist/clock/index.d.ts +2 -0
  45. package/dist/clock/index.js +2 -0
  46. package/dist/clock/useClock.d.ts +14 -0
  47. package/dist/clock/useClock.js +57 -0
  48. package/dist/datetime/DateTimePicker.d.ts +50 -0
  49. package/dist/datetime/DateTimePicker.js +98 -0
  50. package/dist/datetime/DateTimePicker.logic.d.ts +59 -0
  51. package/dist/datetime/DateTimePicker.logic.js +103 -0
  52. package/dist/datetime/datetime.css +115 -0
  53. package/dist/datetime/index.d.ts +7 -0
  54. package/dist/datetime/index.js +7 -0
  55. package/dist/dialog/ConfirmDialog.d.ts +73 -0
  56. package/dist/dialog/ConfirmDialog.js +30 -0
  57. package/dist/dialog/DialogLegend.d.ts +21 -0
  58. package/dist/dialog/DialogLegend.js +28 -0
  59. package/dist/dialog/DialogLegend.logic.d.ts +145 -0
  60. package/dist/dialog/DialogLegend.logic.js +71 -0
  61. package/dist/dialog/ModalDialog.d.ts +101 -0
  62. package/dist/dialog/ModalDialog.js +184 -0
  63. package/dist/dialog/dialog.css +283 -0
  64. package/dist/dialog/index.d.ts +8 -0
  65. package/dist/dialog/index.js +8 -0
  66. package/dist/filter/FilterEscape.d.ts +16 -0
  67. package/dist/filter/FilterEscape.js +15 -0
  68. package/dist/filter/FilterIcon.d.ts +8 -0
  69. package/dist/filter/FilterIcon.js +11 -0
  70. package/dist/filter/filter.css +42 -0
  71. package/dist/filter/index.d.ts +3 -0
  72. package/dist/filter/index.js +3 -0
  73. package/dist/grid/DataGrid.d.ts +149 -0
  74. package/dist/grid/DataGrid.js +373 -0
  75. package/dist/grid/DataGrid.logic.d.ts +57 -0
  76. package/dist/grid/DataGrid.logic.js +121 -0
  77. package/dist/grid/grid.css +206 -0
  78. package/dist/grid/index.d.ts +7 -0
  79. package/dist/grid/index.js +7 -0
  80. package/dist/index.d.ts +32 -0
  81. package/dist/index.js +32 -0
  82. package/dist/keyboard/BrowserKeys.d.ts +15 -0
  83. package/dist/keyboard/BrowserKeys.js +28 -0
  84. package/dist/keyboard/KeyChord.logic.d.ts +25 -0
  85. package/dist/keyboard/KeyChord.logic.js +50 -0
  86. package/dist/keyboard/Keyboard.logic.d.ts +84 -0
  87. package/dist/keyboard/Keyboard.logic.js +137 -0
  88. package/dist/keyboard/OverlayWatch.d.ts +28 -0
  89. package/dist/keyboard/OverlayWatch.js +119 -0
  90. package/dist/keyboard/PageSelectAll.d.ts +14 -0
  91. package/dist/keyboard/PageSelectAll.js +22 -0
  92. package/dist/keyboard/index.d.ts +9 -0
  93. package/dist/keyboard/index.js +9 -0
  94. package/dist/keychord/KeyChord.d.ts +16 -0
  95. package/dist/keychord/KeyChord.js +55 -0
  96. package/dist/keychord/index.d.ts +2 -0
  97. package/dist/keychord/index.js +2 -0
  98. package/dist/keychord/keychord.css +41 -0
  99. package/dist/labels/UiokLabels.d.ts +41 -0
  100. package/dist/labels/UiokLabels.js +31 -0
  101. package/dist/labels/UiokProvider.d.ts +44 -0
  102. package/dist/labels/UiokProvider.js +54 -0
  103. package/dist/labels/charts.d.ts +34 -0
  104. package/dist/labels/charts.js +15 -0
  105. package/dist/labels/dateTime.d.ts +32 -0
  106. package/dist/labels/dateTime.js +14 -0
  107. package/dist/labels/dialog.d.ts +18 -0
  108. package/dist/labels/dialog.js +6 -0
  109. package/dist/labels/index.d.ts +13 -0
  110. package/dist/labels/index.js +13 -0
  111. package/dist/labels/keys.d.ts +28 -0
  112. package/dist/labels/keys.js +53 -0
  113. package/dist/labels/legend.d.ts +21 -0
  114. package/dist/labels/legend.js +7 -0
  115. package/dist/labels/listing.d.ts +16 -0
  116. package/dist/labels/listing.js +8 -0
  117. package/dist/labels/pager.d.ts +32 -0
  118. package/dist/labels/pager.js +20 -0
  119. package/dist/labels/palette.d.ts +17 -0
  120. package/dist/labels/palette.js +6 -0
  121. package/dist/labels/selectAll.d.ts +15 -0
  122. package/dist/labels/selectAll.js +6 -0
  123. package/dist/labels/terminal.d.ts +25 -0
  124. package/dist/labels/terminal.js +9 -0
  125. package/dist/legend/KeyLegend.logic.d.ts +84 -0
  126. package/dist/legend/KeyLegend.logic.js +109 -0
  127. package/dist/legend/KeyLegendStrip.d.ts +36 -0
  128. package/dist/legend/KeyLegendStrip.js +82 -0
  129. package/dist/legend/index.d.ts +3 -0
  130. package/dist/legend/index.js +3 -0
  131. package/dist/legend/legend.css +148 -0
  132. package/dist/listing/CurrentDot.d.ts +15 -0
  133. package/dist/listing/CurrentDot.js +13 -0
  134. package/dist/listing/Listing.d.ts +230 -0
  135. package/dist/listing/Listing.js +265 -0
  136. package/dist/listing/PathParts.logic.d.ts +17 -0
  137. package/dist/listing/PathParts.logic.js +18 -0
  138. package/dist/listing/index.d.ts +10 -0
  139. package/dist/listing/index.js +10 -0
  140. package/dist/listing/listing.css +867 -0
  141. package/dist/menu/MenuQuery.logic.d.ts +69 -0
  142. package/dist/menu/MenuQuery.logic.js +75 -0
  143. package/dist/menu/fuzzyMatch.d.ts +31 -0
  144. package/dist/menu/fuzzyMatch.js +296 -0
  145. package/dist/menu/index.d.ts +9 -0
  146. package/dist/menu/index.js +9 -0
  147. package/dist/menu/menu.css +203 -0
  148. package/dist/menu/useBellBeat.d.ts +8 -0
  149. package/dist/menu/useBellBeat.js +26 -0
  150. package/dist/namecut/NameCut.d.ts +22 -0
  151. package/dist/namecut/NameCut.js +28 -0
  152. package/dist/namecut/NameCut.logic.d.ts +51 -0
  153. package/dist/namecut/NameCut.logic.js +120 -0
  154. package/dist/namecut/index.d.ts +3 -0
  155. package/dist/namecut/index.js +3 -0
  156. package/dist/namecut/namecut.css +67 -0
  157. package/dist/pager/Pager.d.ts +37 -0
  158. package/dist/pager/Pager.js +38 -0
  159. package/dist/pager/Pager.logic.d.ts +13 -0
  160. package/dist/pager/Pager.logic.js +63 -0
  161. package/dist/pager/index.d.ts +7 -0
  162. package/dist/pager/index.js +7 -0
  163. package/dist/pager/pager.css +62 -0
  164. package/dist/palette/Palette.d.ts +79 -0
  165. package/dist/palette/Palette.js +60 -0
  166. package/dist/palette/index.d.ts +6 -0
  167. package/dist/palette/index.js +6 -0
  168. package/dist/palette/palette.css +159 -0
  169. package/dist/pane/PaneActions.d.ts +104 -0
  170. package/dist/pane/PaneActions.js +62 -0
  171. package/dist/pane/PaneFrame.d.ts +51 -0
  172. package/dist/pane/PaneFrame.js +28 -0
  173. package/dist/pane/PaneKeys.d.ts +41 -0
  174. package/dist/pane/PaneKeys.js +104 -0
  175. package/dist/pane/PaneKeys.logic.d.ts +95 -0
  176. package/dist/pane/PaneKeys.logic.js +109 -0
  177. package/dist/pane/index.d.ts +11 -0
  178. package/dist/pane/index.js +11 -0
  179. package/dist/pane/usePaneKeys.d.ts +141 -0
  180. package/dist/pane/usePaneKeys.js +313 -0
  181. package/dist/run/RunHeader.d.ts +50 -0
  182. package/dist/run/RunHeader.js +31 -0
  183. package/dist/run/RunProgress.logic.d.ts +29 -0
  184. package/dist/run/RunProgress.logic.js +34 -0
  185. package/dist/run/index.d.ts +3 -0
  186. package/dist/run/index.js +3 -0
  187. package/dist/run/run.css +190 -0
  188. package/dist/segmented/SegmentedChoice.d.ts +22 -0
  189. package/dist/segmented/SegmentedChoice.js +31 -0
  190. package/dist/segmented/index.d.ts +2 -0
  191. package/dist/segmented/index.js +2 -0
  192. package/dist/segmented/segmented.css +49 -0
  193. package/dist/selectall/CheckRange.logic.d.ts +8 -0
  194. package/dist/selectall/CheckRange.logic.js +23 -0
  195. package/dist/selectall/SelectAllBar.d.ts +25 -0
  196. package/dist/selectall/SelectAllBar.js +24 -0
  197. package/dist/selectall/index.d.ts +7 -0
  198. package/dist/selectall/index.js +7 -0
  199. package/dist/selectall/selectall.css +31 -0
  200. package/dist/store/KeepUnchanged.logic.d.ts +19 -0
  201. package/dist/store/KeepUnchanged.logic.js +33 -0
  202. package/dist/store/SameProps.d.ts +15 -0
  203. package/dist/store/SameProps.js +46 -0
  204. package/dist/store/ValueStore.d.ts +17 -0
  205. package/dist/store/ValueStore.js +23 -0
  206. package/dist/store/index.d.ts +8 -0
  207. package/dist/store/index.js +8 -0
  208. package/dist/store/useStableHandlers.d.ts +13 -0
  209. package/dist/store/useStableHandlers.js +22 -0
  210. package/dist/styles.css +85 -0
  211. package/dist/tabs/PageTabs.d.ts +38 -0
  212. package/dist/tabs/PageTabs.js +33 -0
  213. package/dist/tabs/index.d.ts +2 -0
  214. package/dist/tabs/index.js +2 -0
  215. package/dist/tabs/tabs.css +64 -0
  216. package/dist/terminal/Terminal.d.ts +104 -0
  217. package/dist/terminal/Terminal.js +309 -0
  218. package/dist/terminal/Terminal.logic.d.ts +66 -0
  219. package/dist/terminal/Terminal.logic.js +156 -0
  220. package/dist/terminal/TerminalMenu.d.ts +36 -0
  221. package/dist/terminal/TerminalMenu.js +87 -0
  222. package/dist/terminal/TerminalMenu.logic.d.ts +78 -0
  223. package/dist/terminal/TerminalMenu.logic.js +68 -0
  224. package/dist/terminal/TerminalScrollback.d.ts +10 -0
  225. package/dist/terminal/TerminalScrollback.js +11 -0
  226. package/dist/terminal/ghostty/LICENSE +21 -0
  227. package/dist/terminal/ghostty/core.d.ts +315 -0
  228. package/dist/terminal/ghostty/core.js +1189 -0
  229. package/dist/terminal/ghostty/fallbackColors.d.ts +12 -0
  230. package/dist/terminal/ghostty/fallbackColors.js +23 -0
  231. package/dist/terminal/ghostty/fonts/LICENSE +21 -0
  232. package/dist/terminal/ghostty/fonts/SymbolsNerdFontMono-Regular.woff2 +0 -0
  233. package/dist/terminal/ghostty/keyCodes.logic.d.ts +20 -0
  234. package/dist/terminal/ghostty/keyCodes.logic.js +249 -0
  235. package/dist/terminal/ghostty/links.logic.d.ts +39 -0
  236. package/dist/terminal/ghostty/links.logic.js +84 -0
  237. package/dist/terminal/ghostty/renderer.d.ts +98 -0
  238. package/dist/terminal/ghostty/renderer.js +481 -0
  239. package/dist/terminal/ghostty/runtime.d.ts +126 -0
  240. package/dist/terminal/ghostty/runtime.js +346 -0
  241. package/dist/terminal/ghostty/spriteGlyphs.logic.d.ts +64 -0
  242. package/dist/terminal/ghostty/spriteGlyphs.logic.js +546 -0
  243. package/dist/terminal/ghostty/surface.d.ts +285 -0
  244. package/dist/terminal/ghostty/surface.js +1565 -0
  245. package/dist/terminal/ghostty/surface.logic.d.ts +181 -0
  246. package/dist/terminal/ghostty/surface.logic.js +392 -0
  247. package/dist/terminal/ghostty/vendor/LICENSE +21 -0
  248. package/dist/terminal/ghostty/vendor/ghostty-effects.wasm +0 -0
  249. package/dist/terminal/ghostty/vendor/ghostty-vt.wasm +0 -0
  250. package/dist/terminal/index.d.ts +12 -0
  251. package/dist/terminal/index.js +12 -0
  252. package/dist/terminal/terminal.css +169 -0
  253. package/dist/text/MarkedText.d.ts +14 -0
  254. package/dist/text/MarkedText.js +11 -0
  255. package/dist/text/highlightSegments.d.ts +13 -0
  256. package/dist/text/highlightSegments.js +29 -0
  257. package/dist/text/index.d.ts +3 -0
  258. package/dist/text/index.js +3 -0
  259. package/dist/text/text.css +11 -0
  260. package/dist/themes/attributes.d.ts +21 -0
  261. package/dist/themes/attributes.js +41 -0
  262. package/dist/themes/catalog.d.ts +125 -0
  263. package/dist/themes/catalog.js +940 -0
  264. package/dist/themes/color.d.ts +29 -0
  265. package/dist/themes/color.js +52 -0
  266. package/dist/themes/ids.d.ts +139 -0
  267. package/dist/themes/ids.js +59 -0
  268. package/dist/themes/index.d.ts +12 -0
  269. package/dist/themes/index.js +12 -0
  270. package/dist/themes/themes.generated.css +1830 -0
  271. package/dist/themes/tokens.d.ts +189 -0
  272. package/dist/themes/tokens.js +462 -0
  273. package/dist/tooltip/Tooltip.d.ts +21 -0
  274. package/dist/tooltip/Tooltip.js +105 -0
  275. package/dist/tooltip/Tooltip.logic.d.ts +49 -0
  276. package/dist/tooltip/Tooltip.logic.js +50 -0
  277. package/dist/tooltip/index.d.ts +3 -0
  278. package/dist/tooltip/index.js +3 -0
  279. package/dist/tooltip/tooltip.css +45 -0
  280. package/package.json +91 -4
@@ -0,0 +1,1565 @@
1
+ /**
2
+ * The browser side of one terminal: a Canvas 2D view over a libghostty-vt
3
+ * core plus everything a terminal needs from the DOM. It owns sizing (a
4
+ * ResizeObserver fit), frame scheduling, batched output parsing, keyboard and
5
+ * IME input through a hidden textarea, clipboard, selection, scrollback and
6
+ * its scrollbar, mouse reporting, web links, and cursor blinking. React never
7
+ * runs in its frame loop.
8
+ *
9
+ * A read-only surface creates no input element and draws no cursor; it keeps
10
+ * selection and copy, with the mount itself as the keyboard target.
11
+ *
12
+ * Copy and paste run through the DOM `copy` and `paste` events, because a
13
+ * host's Edit menu may answer Command-C and Command-V with the
14
+ * document's copy and paste commands whether or not the page saw the keydown. A settled
15
+ * selection is therefore always parked in a real DOM selection (the input
16
+ * element, or a hidden copy buffer when read-only) so the copy command has
17
+ * something to act on. The Edit menu's Cut does nothing here: its `cut`
18
+ * event is cancelled, so neither the clipboard nor the parked copy changes.
19
+ * `paste` is the same paste for a host that read the clipboard itself.
20
+ *
21
+ * A secondary click (the right button, or a Control-click) is the host's
22
+ * (`onContextMenu`): it never reaches a program tracking the mouse and leaves
23
+ * the selection as it was, and the browser's own menu never shows.
24
+ */
25
+ import { GhosttyTerminalCore } from './core.js';
26
+ import { isTerminalUrl } from './links.logic.js';
27
+ import { GhosttyTextInkCache, measureGhosttyCell, renderGhosttySnapshot, terminalGridSize } from './renderer.js';
28
+ import { DEFAULT_TERMINAL_FONT_FAMILY, advanceTerminalSelectionClickSequence, applyTerminalCopyEvent, areFontAdvancesMonospace, clearPrimedTerminalCopyInput, ghosttyMouseButton, isEmptyTerminalFontFamily, isSameTerminalLink, isTerminalAltGraphText, isTerminalCompositionCommitInput, isTerminalCompositionKey, isTerminalCopyShortcut, isTerminalPasteShortcut, isTerminalPointerDrag, isTerminalSecondaryPress, primeTerminalCopyInput, resolveTerminalMouseData, resolveTerminalMouseTrackingState, shouldBlinkTerminalCursor, shouldReportTerminalMouse, terminalCanvasBackingChange, terminalFontSize, terminalFontStack, terminalGridCellAt, terminalLineHeight, terminalLinkAtPositionWithRange, terminalScrollbarGeometry, terminalScrollbarOffsetAtPointer, terminalWheelArrowData, terminalWheelDeltaRows } from './surface.logic.js';
29
+ import { DEFAULT_TERMINAL_LABELS } from '../../labels/terminal.js';
30
+ // The symbols font is named as the engine's WebAssembly is (runtime.ts): a
31
+ // relative string literal beside import.meta.url, which bundlers emit.
32
+ const SYMBOLS_FONT_URL = new URL('./fonts/SymbolsNerdFontMono-Regular.woff2', import.meta.url);
33
+ const CONTENT_PADDING = 4;
34
+ /** Half a blink cycle: the visible and hidden phases are equally long. */
35
+ const CURSOR_BLINK_INTERVAL_MS = 500;
36
+ /**
37
+ * Queued output normally parses in the next animation frame, right before it
38
+ * is drawn. An occluded window gets no frames, so a timer parses the queue
39
+ * anyway: output keeps flowing (and keeps being acknowledged) while nobody
40
+ * can see it.
41
+ */
42
+ const QUEUED_OUTPUT_DEADLINE_MS = 50;
43
+ /**
44
+ * A synchronized update (DEC 2026) holds every paint until the program ends
45
+ * it, so a frame is never shown half drawn. One left open this long is ended
46
+ * and painted instead of freezing the last frame.
47
+ */
48
+ const SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS = 500;
49
+ const TERMINAL_FONT_LOAD_TEXT = 'iMW0@# .';
50
+ const TERMINAL_FONT_LOAD_VARIANTS = [
51
+ 'normal 400',
52
+ 'normal 700',
53
+ 'italic 400',
54
+ 'italic 700'
55
+ ];
56
+ const MONOSPACE_PROBE_GLYPHS = ['i', 'M', 'W', '0', '@', '#', '.', ' '];
57
+ let symbolsFontLoad = null;
58
+ /**
59
+ * Register the bundled symbols-only Nerd Font once per page. It loads lazily
60
+ * with the first terminal, and because it carries no regular text glyphs it
61
+ * composes with any text face without changing metrics: prompt symbols and
62
+ * devicons render even on machines without a locally installed Nerd Font.
63
+ */
64
+ function ensureTerminalSymbolsFont() {
65
+ if (symbolsFontLoad !== null)
66
+ return symbolsFontLoad;
67
+ symbolsFontLoad = (async () => {
68
+ try {
69
+ const face = new FontFace('Symbols Nerd Font Mono', `url(${SYMBOLS_FONT_URL.href})`);
70
+ document.fonts.add(await face.load());
71
+ }
72
+ catch {
73
+ // Locally installed fallback faces still apply.
74
+ }
75
+ })();
76
+ return symbolsFontLoad;
77
+ }
78
+ let fontProbeContext;
79
+ /**
80
+ * Whether a family renders every character on the same advance. The cell
81
+ * grid requires it: a proportional face draws its text narrower than the
82
+ * lattice the cursor and selection are placed on. Unmeasurable environments
83
+ * answer true, so a missing canvas never blocks a legitimate font.
84
+ */
85
+ function isMonospaceFamily(families) {
86
+ try {
87
+ if (fontProbeContext === undefined) {
88
+ fontProbeContext = document.createElement('canvas').getContext('2d');
89
+ }
90
+ if (fontProbeContext === null)
91
+ return true;
92
+ const context = fontProbeContext;
93
+ // Fall back to a generic mono so an absent face measures as monospace and
94
+ // is left for the normal fallback chain to resolve.
95
+ for (const variant of TERMINAL_FONT_LOAD_VARIANTS) {
96
+ context.font = `${variant} 32px ${families}, monospace`;
97
+ const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
98
+ if (!areFontAdvancesMonospace(advances))
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ catch {
104
+ return true;
105
+ }
106
+ }
107
+ /**
108
+ * The font stack the canvas uses for a requested family: the family with the
109
+ * glyph fallbacks behind it, or the default stack when the family is empty or
110
+ * proportional (a ragged grid with a stranded cursor is worse than a
111
+ * different face). Exported for `surface.test.ts`, which checks the
112
+ * proportional-face guard against measured advances.
113
+ */
114
+ export function terminalFontFamily(family) {
115
+ if (isEmptyTerminalFontFamily(family))
116
+ return DEFAULT_TERMINAL_FONT_FAMILY;
117
+ const stack = terminalFontStack(family);
118
+ return isMonospaceFamily(stack) ? stack : DEFAULT_TERMINAL_FONT_FAMILY;
119
+ }
120
+ /** Loads every style the renderer can request, then validates the actual face. */
121
+ async function loadTerminalFontFamily(family, size) {
122
+ const candidate = terminalFontStack(family);
123
+ try {
124
+ await Promise.all(TERMINAL_FONT_LOAD_VARIANTS.map((variant) => document.fonts.load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT)));
125
+ }
126
+ catch {
127
+ // The fixed-width fallback stack remains available if a face cannot load.
128
+ }
129
+ return terminalFontFamily(family);
130
+ }
131
+ /** One mounted terminal; create with `GhosttyTerminalSurface.create`, release with `dispose`. */
132
+ export class GhosttyTerminalSurface {
133
+ canvas;
134
+ /** The hidden IME textarea; null for a read-only surface. */
135
+ input;
136
+ /** The read-only surface's hidden copy buffer, holding the selection as DOM text; null otherwise. */
137
+ copyBuffer;
138
+ scrollbar;
139
+ cols = 1;
140
+ rows = 1;
141
+ mount;
142
+ /** The element keyboard focus lives on: the textarea, or the mount when read-only. */
143
+ keyTarget;
144
+ readOnly;
145
+ context;
146
+ core;
147
+ options;
148
+ hasSize = false;
149
+ metrics;
150
+ fontFamily;
151
+ requestedFontFamily;
152
+ fontSize;
153
+ lineHeight;
154
+ resizeObserver;
155
+ scrollbarThumb;
156
+ snapshot = null;
157
+ frame = 0;
158
+ cursorTimer = null;
159
+ synchronizedRenderTimer = null;
160
+ pendingOutput = [];
161
+ pendingOutputTimer = null;
162
+ compositionInputToSuppress = null;
163
+ compositionSuppressionTimer = null;
164
+ cursorOn = true;
165
+ renderedCursorY = null;
166
+ forceFullRender = true;
167
+ scrollbarDirty = true;
168
+ scrollbarState = null;
169
+ scrollbarPointerId = null;
170
+ scrollbarPointerOffset = 0;
171
+ disposed = false;
172
+ resizeNotifyTimer = null;
173
+ selectionEnd = null;
174
+ selectionAnchorScreen = null;
175
+ selectionMode = 'cell';
176
+ // Word/line selection base in screen coordinates so streaming output cannot
177
+ // shift the origin of a drag selection.
178
+ selectionBase = null;
179
+ selectionScrollTimer = null;
180
+ selectionScrollDelta = 0;
181
+ selectionPointer = null;
182
+ mouseReportingPointerId = null;
183
+ mouseReportingButton = null;
184
+ /** The secondary press under way, which belongs to the host's menu until its release. */
185
+ secondaryPointerId = null;
186
+ linkActivationPointerId = null;
187
+ linkActivationLink = null;
188
+ linkActivationOrigin = null;
189
+ hoveredLink = null;
190
+ hoverPointer = null;
191
+ selectionClickSequence = null;
192
+ selectionMoved = false;
193
+ composing = false;
194
+ focused = false;
195
+ resizeNotified = false;
196
+ /** The canvas backing store installed; null until the first paint installs one. */
197
+ canvasBacking = null;
198
+ /** A backing store a fit asked for, installed by the next paint (resizing clears the canvas). */
199
+ pendingCanvasBacking = null;
200
+ theme;
201
+ // Codes whose press this surface encoded and sent. Only these earn a release:
202
+ // a press stopped before the terminal saw it, or one made while the focus was
203
+ // elsewhere, must not reach a Kitty report-event-types program as a release.
204
+ encodedKeyCodes = new Set();
205
+ textInk = new GhosttyTextInkCache();
206
+ primedCopySelection = '';
207
+ wheelRemainder = 0;
208
+ lastMouseMotionData = '';
209
+ mouseAnyEventTracking = false;
210
+ dprMedia = null;
211
+ // Read live on every blink decision, and watched so that dropping the
212
+ // preference restarts a blink cycle that has no timer left to notice it.
213
+ reducedMotionMedia = window.matchMedia?.('(prefers-reduced-motion: reduce)');
214
+ inputLeft = -1;
215
+ inputTop = -1;
216
+ constructor(mount, canvas, input, copyBuffer, scrollbar, scrollbarThumb, context, core, metrics, fontFamily, options) {
217
+ this.mount = mount;
218
+ this.canvas = canvas;
219
+ this.input = input;
220
+ this.copyBuffer = copyBuffer;
221
+ this.keyTarget = input ?? mount;
222
+ this.readOnly = input === null;
223
+ this.scrollbar = scrollbar;
224
+ this.scrollbarThumb = scrollbarThumb;
225
+ this.context = context;
226
+ this.core = core;
227
+ this.mouseAnyEventTracking = core.isMouseAnyEventTracking();
228
+ this.metrics = metrics;
229
+ this.options = options;
230
+ this.theme = options.theme;
231
+ this.fontFamily = fontFamily;
232
+ this.requestedFontFamily = options.font?.family;
233
+ this.fontSize = terminalFontSize(options.font?.size);
234
+ this.lineHeight = terminalLineHeight(this.fontSize, options.font?.lineHeight);
235
+ this.resizeObserver = new ResizeObserver(() => this.fit());
236
+ this.installEvents();
237
+ this.watchDevicePixelRatio();
238
+ this.reducedMotionMedia?.addEventListener('change', this.onReducedMotionChange);
239
+ document.fonts.addEventListener('loadingdone', this.onFontsLoaded);
240
+ this.resizeObserver.observe(mount);
241
+ }
242
+ /** Builds the surface inside `mount`, replacing its children, once fonts and WASM are loaded. */
243
+ static async create(mount, options) {
244
+ const canvas = document.createElement('canvas');
245
+ canvas.className = 'terminal-canvas';
246
+ canvas.setAttribute('aria-hidden', 'true');
247
+ let input = null;
248
+ let copyBuffer = null;
249
+ if (options.readOnly === true) {
250
+ copyBuffer = document.createElement('span');
251
+ copyBuffer.className = 'terminal-copy-buffer';
252
+ copyBuffer.setAttribute('aria-hidden', 'true');
253
+ }
254
+ else {
255
+ input = document.createElement('textarea');
256
+ input.className = 'terminal-input';
257
+ input.setAttribute('aria-label', options.inputLabel ?? DEFAULT_TERMINAL_LABELS.input);
258
+ input.autocapitalize = 'off';
259
+ input.autocomplete = 'off';
260
+ input.spellcheck = false;
261
+ input.style.cssText =
262
+ 'position:absolute;left:4px;top:4px;width:1px;height:1px;opacity:0;padding:0;border:0;resize:none;pointer-events:none;';
263
+ }
264
+ const scrollbar = document.createElement('div');
265
+ scrollbar.className = 'terminal-scrollbar';
266
+ scrollbar.setAttribute('role', 'scrollbar');
267
+ scrollbar.setAttribute('aria-label', options.scrollbackLabel ?? DEFAULT_TERMINAL_LABELS.scrollback);
268
+ scrollbar.setAttribute('aria-orientation', 'vertical');
269
+ scrollbar.tabIndex = 0;
270
+ scrollbar.hidden = true;
271
+ const scrollbarThumb = document.createElement('div');
272
+ scrollbarThumb.className = 'terminal-scrollbar-thumb';
273
+ scrollbar.append(scrollbarThumb);
274
+ const keyElement = input ?? copyBuffer;
275
+ if (keyElement === null)
276
+ mount.replaceChildren(canvas, scrollbar);
277
+ else
278
+ mount.replaceChildren(canvas, keyElement, scrollbar);
279
+ try {
280
+ const context = canvas.getContext('2d', { alpha: false });
281
+ if (!context)
282
+ throw new Error('Canvas 2D is unavailable');
283
+ // An opaque canvas backing store initializes to solid black, and the font
284
+ // and WASM loads below leave it on screen for the whole setup window; paint
285
+ // the theme background first so the mount never flashes a black box.
286
+ context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
287
+ context.fillRect(0, 0, canvas.width, canvas.height);
288
+ const fontSize = terminalFontSize(options.font?.size);
289
+ try {
290
+ // Cell metrics must come from the faces that will render; measuring before
291
+ // the bundled webfonts load would size the grid from a fallback font.
292
+ await ensureTerminalSymbolsFont();
293
+ }
294
+ catch {
295
+ // Metrics fall back to whichever faces are already available.
296
+ }
297
+ const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
298
+ const metrics = measureGhosttyCell(context, fontSize, fontFamily, terminalLineHeight(fontSize, options.font?.lineHeight));
299
+ const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
300
+ const core = await GhosttyTerminalCore.create(grid.cols, grid.rows, metrics.width, metrics.height, options.theme, options.scrollbackLines,
301
+ // A read-only terminal has no program listening for its replies, nor
302
+ // one whose bell anyone waits on.
303
+ options.readOnly === true ? () => { } : options.onData, options.readOnly === true ? undefined : options.onBell);
304
+ const surface = new GhosttyTerminalSurface(mount, canvas, input, copyBuffer, scrollbar, scrollbarThumb, context, core, metrics, fontFamily, options);
305
+ surface.fit();
306
+ return surface;
307
+ }
308
+ catch (error) {
309
+ // Leave the mount empty, as it was found, for the host to show a failure.
310
+ mount.replaceChildren();
311
+ throw error;
312
+ }
313
+ }
314
+ /** Parses output now and schedules its paint. */
315
+ write(data) {
316
+ if (this.disposed)
317
+ return;
318
+ this.parseQueuedOutput();
319
+ this.parse(data);
320
+ this.requestRender();
321
+ }
322
+ /**
323
+ * Queues output to parse in the next frame, right before it is painted, so
324
+ * a burst of chunks costs one parse and one paint. `onParsed` reports each
325
+ * chunk once it is parsed.
326
+ */
327
+ enqueue(data) {
328
+ if (this.disposed || data.length === 0)
329
+ return;
330
+ this.pendingOutput.push(data);
331
+ if (!this.canRender()) {
332
+ // Nothing will be painted, so there is no frame worth waiting for.
333
+ this.parseQueuedOutput();
334
+ return;
335
+ }
336
+ this.requestRender();
337
+ this.pendingOutputTimer ??= window.setTimeout(() => {
338
+ this.pendingOutputTimer = null;
339
+ this.parseQueuedOutput();
340
+ }, QUEUED_OUTPUT_DEADLINE_MS);
341
+ }
342
+ /** Resets every mode, the screen, and scrollback, then replays `data` without answering its queries. */
343
+ resetAndWrite(data) {
344
+ if (this.disposed)
345
+ return;
346
+ this.parseQueuedOutput();
347
+ // The reset ends any open update; one the replay opens gets its own deadline.
348
+ this.cancelSynchronizedRenderTimer();
349
+ this.lastMouseMotionData = '';
350
+ this.core.resetAndWrite(data);
351
+ this.synchronizeMouseTrackingState();
352
+ // A replayed session starts from the visible phase like any other write:
353
+ // reattaching mid-blink must not open on an invisible cursor.
354
+ this.cursorOn = true;
355
+ this.forceFullRender = true;
356
+ this.scrollbarDirty = true;
357
+ this.requestRender();
358
+ }
359
+ /**
360
+ * Erases the scrollback and the rows above the cursor (Command-K). The
361
+ * program is not told; a shell keeps its prompt and line where they are.
362
+ */
363
+ clearToStart() {
364
+ if (this.disposed)
365
+ return;
366
+ this.parseQueuedOutput();
367
+ this.clearSelection();
368
+ this.core.clearToStart();
369
+ this.forceFullRender = true;
370
+ this.scrollbarDirty = true;
371
+ this.requestRender();
372
+ }
373
+ /** Replaces the default colors and repaints. */
374
+ setTheme(theme) {
375
+ if (this.disposed)
376
+ return;
377
+ this.theme = theme;
378
+ this.core.setTheme(theme);
379
+ this.forceFullRender = true;
380
+ this.requestRender();
381
+ }
382
+ /**
383
+ * Keeps at least `lines` rows of history from now on; a shorter length
384
+ * drops the oldest rows at once, so the scrollbar and the view repaint.
385
+ */
386
+ setScrollbackLines(lines) {
387
+ if (this.disposed)
388
+ return;
389
+ this.core.setScrollbackLines(lines);
390
+ this.forceFullRender = true;
391
+ this.scrollbarDirty = true;
392
+ this.requestRender();
393
+ }
394
+ parse(data) {
395
+ // An update's deadline ends with it: one the same data opens next starts its own.
396
+ this.core.write(data, this.synchronizedRenderTimer === null ? undefined : () => this.cancelSynchronizedRenderTimer());
397
+ this.synchronizeMouseTrackingState();
398
+ // Restart the blink cycle from the visible phase so the cursor never sits
399
+ // invisible through a stream of output or a burst of typing echo.
400
+ this.cursorOn = true;
401
+ this.scrollbarDirty = true;
402
+ }
403
+ parseQueuedOutput() {
404
+ if (this.pendingOutputTimer !== null) {
405
+ window.clearTimeout(this.pendingOutputTimer);
406
+ this.pendingOutputTimer = null;
407
+ }
408
+ if (this.pendingOutput.length === 0)
409
+ return;
410
+ const chunks = this.pendingOutput;
411
+ this.pendingOutput = [];
412
+ this.parse(chunks.length === 1 ? (chunks[0] ?? '') : chunks.join(''));
413
+ // A parse that ran outside a frame still needs one to show its output.
414
+ this.requestRender();
415
+ const onParsed = this.options.onParsed;
416
+ if (onParsed !== undefined)
417
+ for (const chunk of chunks)
418
+ onParsed(chunk.length);
419
+ }
420
+ applyFontMetrics() {
421
+ this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily, this.lineHeight);
422
+ this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
423
+ // Cached IME textarea coordinates are stale in the new cell geometry.
424
+ this.inputLeft = -1;
425
+ this.inputTop = -1;
426
+ this.forceFullRender = true;
427
+ this.scrollbarDirty = true;
428
+ this.fit();
429
+ this.requestRender();
430
+ }
431
+ onReducedMotionChange = () => {
432
+ if (this.disposed)
433
+ return;
434
+ // Nothing else wakes an idle steady cursor: the blink timer only reschedules
435
+ // from a render, and reduced motion is exactly the state that stopped it.
436
+ this.cursorOn = true;
437
+ this.requestRender();
438
+ };
439
+ onFontsLoaded = () => {
440
+ if (this.disposed)
441
+ return;
442
+ // A loaded face draws different glyphs under the same font string.
443
+ this.textInk.clear();
444
+ // A face may become available after an earlier fallback measurement. Run
445
+ // the fixed-width guard again before using its newly loaded metrics.
446
+ const fontFamily = terminalFontFamily(this.requestedFontFamily);
447
+ if (fontFamily !== this.fontFamily) {
448
+ this.fontFamily = fontFamily;
449
+ this.applyFontMetrics();
450
+ return;
451
+ }
452
+ // A face that finished loading after the initial measurement changes glyph
453
+ // advances; re-measure and refit so the grid matches what actually renders.
454
+ const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily, this.lineHeight);
455
+ if (metrics.width === this.metrics.width &&
456
+ metrics.height === this.metrics.height &&
457
+ metrics.baseline === this.metrics.baseline) {
458
+ return;
459
+ }
460
+ this.applyFontMetrics();
461
+ };
462
+ /** Sizes the canvas and grid to the mount; false while the mount has no size. */
463
+ fit() {
464
+ if (this.disposed)
465
+ return false;
466
+ const width = this.mount.clientWidth;
467
+ const height = this.mount.clientHeight;
468
+ if (width <= 0 || height <= 0) {
469
+ this.hasSize = false;
470
+ this.forceFullRender = true;
471
+ this.cancelRender();
472
+ return false;
473
+ }
474
+ this.hasSize = true;
475
+ let shouldRender = false;
476
+ // Resizing the backing store clears the canvas, so the paint installs it:
477
+ // an open synchronized update then keeps its last frame on screen, and a
478
+ // size that returns to the installed one before that paint cancels it.
479
+ this.pendingCanvasBacking = terminalCanvasBackingChange(this.canvasBacking, width, height, window.devicePixelRatio || 1);
480
+ if (this.pendingCanvasBacking !== null) {
481
+ this.forceFullRender = true;
482
+ this.scrollbarDirty = true;
483
+ shouldRender = true;
484
+ }
485
+ const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING);
486
+ // onResize is the only PTY resize channel, so the first successful fit must
487
+ // notify even when the measured grid equals the 1x1 construction sentinel.
488
+ if (grid.cols !== this.cols || grid.rows !== this.rows || !this.resizeNotified) {
489
+ this.cols = grid.cols;
490
+ this.rows = grid.rows;
491
+ this.core.resize(grid.cols, grid.rows, this.metrics.width, this.metrics.height);
492
+ this.notifyResize();
493
+ this.forceFullRender = true;
494
+ this.scrollbarDirty = true;
495
+ shouldRender = true;
496
+ }
497
+ // Rendering synchronously keeps the repaint inside the same frame as the
498
+ // layout change: ResizeObserver fires before paint, so the browser never
499
+ // composites the old backing store stretched into the new element box.
500
+ if (shouldRender || this.forceFullRender)
501
+ this.renderFrame();
502
+ return true;
503
+ }
504
+ /**
505
+ * The local grid reflows immediately, but the PTY only hears about settled
506
+ * dimensions: notifying on every drag step makes the shell reprint its
507
+ * prompt mid-drag, which reads as jitter. The first size goes out at once,
508
+ * since a session cannot start before it knows it.
509
+ */
510
+ notifyResize() {
511
+ const first = !this.resizeNotified;
512
+ this.resizeNotified = true;
513
+ if (this.resizeNotifyTimer !== null)
514
+ window.clearTimeout(this.resizeNotifyTimer);
515
+ this.resizeNotifyTimer = null;
516
+ if (first) {
517
+ this.options.onResize(this.cols, this.rows);
518
+ return;
519
+ }
520
+ this.resizeNotifyTimer = window.setTimeout(() => {
521
+ this.resizeNotifyTimer = null;
522
+ if (!this.disposed)
523
+ this.options.onResize(this.cols, this.rows);
524
+ }, 150);
525
+ }
526
+ /** Moves keyboard focus into the terminal. */
527
+ focus() {
528
+ if (this.disposed)
529
+ return;
530
+ this.keyTarget.focus({ preventScroll: true });
531
+ }
532
+ /** Whether any text is selected. */
533
+ hasSelection() {
534
+ return this.core.selectionText().length > 0;
535
+ }
536
+ /** The selection as plain text. */
537
+ getSelection() {
538
+ return this.core.selectionText();
539
+ }
540
+ /** Removes the selection and repaints. */
541
+ clearSelection() {
542
+ this.clearPrimedCopy();
543
+ this.core.clearSelection();
544
+ this.selectionEnd = null;
545
+ this.selectionAnchorScreen = null;
546
+ this.selectionMode = 'cell';
547
+ this.selectionBase = null;
548
+ this.setSelectionAutoscroll(0);
549
+ // Selection highlights span rows Ghostty may not mark dirty for this change.
550
+ this.forceFullRender = true;
551
+ this.requestRender();
552
+ }
553
+ /**
554
+ * Pastes `text` as Command-V does: bracketed when the program asked for
555
+ * bracketed paste, and taking a reader in scrollback back to the live
556
+ * screen. Nothing happens on a read-only surface.
557
+ */
558
+ paste(text) {
559
+ if (this.disposed || text.length === 0)
560
+ return;
561
+ this.sendInput(this.core.encodePaste(text));
562
+ }
563
+ /** Returns the viewport from scrollback to the live screen. */
564
+ scrollToBottom() {
565
+ this.core.scrollToBottom();
566
+ this.forceFullRender = true;
567
+ this.scrollbarDirty = true;
568
+ this.requestRender();
569
+ }
570
+ /** Stops every listener, timer, and frame and frees the terminal's WASM handles. */
571
+ dispose() {
572
+ if (this.disposed)
573
+ return;
574
+ this.disposed = true;
575
+ this.resizeObserver.disconnect();
576
+ document.fonts.removeEventListener('loadingdone', this.onFontsLoaded);
577
+ this.dprMedia?.removeEventListener('change', this.onDevicePixelRatioChange);
578
+ this.dprMedia = null;
579
+ this.reducedMotionMedia?.removeEventListener('change', this.onReducedMotionChange);
580
+ if (this.selectionScrollTimer !== null)
581
+ window.clearInterval(this.selectionScrollTimer);
582
+ if (this.resizeNotifyTimer !== null) {
583
+ window.clearTimeout(this.resizeNotifyTimer);
584
+ this.resizeNotifyTimer = null;
585
+ // Flush the settled dimensions so the PTY keeps the final size even when
586
+ // the surface unmounts inside the debounce window.
587
+ this.options.onResize(this.cols, this.rows);
588
+ }
589
+ if (this.pendingOutputTimer !== null)
590
+ window.clearTimeout(this.pendingOutputTimer);
591
+ // Queued output is dropped unparsed but still reported, so a session that
592
+ // outlives this surface is not left waiting on acknowledgements.
593
+ const dropped = this.pendingOutput;
594
+ this.pendingOutput = [];
595
+ this.cancelRender();
596
+ if (this.compositionSuppressionTimer !== null) {
597
+ window.clearTimeout(this.compositionSuppressionTimer);
598
+ }
599
+ this.removeEvents();
600
+ this.core.dispose();
601
+ this.clearPrimedCopy();
602
+ for (const element of [this.canvas, this.input, this.copyBuffer, this.scrollbar]) {
603
+ if (element?.parentElement === this.mount)
604
+ element.remove();
605
+ }
606
+ const onParsed = this.options.onParsed;
607
+ if (onParsed !== undefined)
608
+ for (const chunk of dropped)
609
+ onParsed(chunk.length);
610
+ }
611
+ /** Sends user input, bringing a reader in scrollback back to the live screen first. */
612
+ sendInput(data) {
613
+ if (this.readOnly || data.length === 0)
614
+ return;
615
+ if (!this.core.isViewportActive())
616
+ this.scrollToBottom();
617
+ this.options.onData(data);
618
+ }
619
+ onKeyDown = (event) => {
620
+ // A fresh press starts over; a repeat the app claims still leaves the
621
+ // original encoded press its release.
622
+ if (!event.repeat)
623
+ this.encodedKeyCodes.delete(event.code);
624
+ // A modified chord an earlier listener already claimed (a space switch) is
625
+ // not also typed into the shell. Unmodified keys are still the shell's:
626
+ // page-level listeners cancel scrolling defaults for them, not their meaning.
627
+ const claimedChord = event.defaultPrevented && (event.ctrlKey || event.metaKey);
628
+ if (claimedChord ||
629
+ isTerminalAltGraphText(event) ||
630
+ (this.options.beforeKey !== undefined && !this.options.beforeKey(event))) {
631
+ return;
632
+ }
633
+ if (isTerminalCopyShortcut(event)) {
634
+ // The default (the browser's copy, or the Edit menu's) fires the copy
635
+ // event this surface answers; re-park the selection in case output
636
+ // replaced it since it settled.
637
+ if (this.hasSelection())
638
+ this.primeCopy(this.getSelection());
639
+ return;
640
+ }
641
+ if (this.readOnly)
642
+ return;
643
+ if (isTerminalPasteShortcut(event)) {
644
+ // The default fires the paste event this surface answers.
645
+ return;
646
+ }
647
+ if (event.metaKey) {
648
+ // Other Command chords are the app's menu accelerators, never shell input.
649
+ return;
650
+ }
651
+ // keyCode 229 is Safari's only signal that this keydown opens an IME
652
+ // composition; encoding it would double the committed text. Do not blank
653
+ // the textarea first: onInput leaves the in-progress candidate there.
654
+ if (isTerminalCompositionKey(event, this.composing)) {
655
+ return;
656
+ }
657
+ const data = this.core.encodeKey(event);
658
+ if (data.length === 0)
659
+ return;
660
+ // Typing ends the selection, as in Ghostty, so a parked copy never
661
+ // outlives what the screen shows selected.
662
+ if (this.primedCopySelection.length > 0)
663
+ this.clearSelection();
664
+ this.encodedKeyCodes.add(event.code);
665
+ event.preventDefault();
666
+ event.stopPropagation();
667
+ this.sendInput(data);
668
+ };
669
+ onKeyUp = (event) => {
670
+ if (!this.encodedKeyCodes.delete(event.code))
671
+ return;
672
+ if (isTerminalCompositionKey(event, this.composing))
673
+ return;
674
+ // Ghostty's encoder only emits release codes when the terminal enabled the
675
+ // Kitty report-event-types flag, so legacy sessions send nothing here.
676
+ const data = this.core.encodeKey(event, 'release');
677
+ if (data.length === 0)
678
+ return;
679
+ event.preventDefault();
680
+ event.stopPropagation();
681
+ this.options.onData(data);
682
+ };
683
+ // A release outside the terminal ends its press, so a later press the app
684
+ // claims cannot inherit that press's release.
685
+ onWindowKeyUp = (event) => {
686
+ if (event.composedPath().includes(this.keyTarget))
687
+ return;
688
+ this.encodedKeyCodes.delete(event.code);
689
+ };
690
+ // A fresh press anywhere proves an earlier release was missed. A repeat is
691
+ // left alone, since a held key's repeats can span a focus round trip.
692
+ onWindowKeyDown = (event) => {
693
+ if (!event.repeat)
694
+ this.encodedKeyCodes.delete(event.code);
695
+ };
696
+ onFocus = () => {
697
+ this.focused = true;
698
+ this.cursorOn = true;
699
+ this.requestRender();
700
+ };
701
+ onBlur = () => {
702
+ this.focused = false;
703
+ // The steady unfocused hollow cursor must not inherit an off blink phase.
704
+ this.cursorOn = true;
705
+ this.requestRender();
706
+ };
707
+ onDevicePixelRatioChange = () => {
708
+ this.watchDevicePixelRatio();
709
+ this.fit();
710
+ };
711
+ watchDevicePixelRatio() {
712
+ this.dprMedia?.removeEventListener('change', this.onDevicePixelRatioChange);
713
+ // A resolution media query only fires once for the ratio it was created at,
714
+ // so re-arm it after every change (display moves).
715
+ this.dprMedia = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
716
+ this.dprMedia.addEventListener('change', this.onDevicePixelRatioChange);
717
+ }
718
+ primeCopy(selection) {
719
+ this.primedCopySelection = selection;
720
+ if (this.input !== null) {
721
+ primeTerminalCopyInput(this.input, selection);
722
+ return;
723
+ }
724
+ if (this.copyBuffer === null)
725
+ return;
726
+ this.copyBuffer.textContent = selection;
727
+ if (selection.length > 0)
728
+ document.getSelection()?.selectAllChildren(this.copyBuffer);
729
+ }
730
+ clearPrimedCopy() {
731
+ if (this.input !== null) {
732
+ clearPrimedTerminalCopyInput(this.input, this.primedCopySelection);
733
+ }
734
+ else if (this.copyBuffer !== null && this.copyBuffer.textContent !== '') {
735
+ this.copyBuffer.textContent = '';
736
+ const selection = document.getSelection();
737
+ if (selection?.anchorNode !== null &&
738
+ this.copyBuffer.contains(selection?.anchorNode ?? null)) {
739
+ selection?.removeAllRanges();
740
+ }
741
+ }
742
+ this.primedCopySelection = '';
743
+ }
744
+ /** Parks a settled selection where the copy command finds it. */
745
+ primeSettledSelection() {
746
+ const selection = this.getSelection();
747
+ if (selection.length > 0)
748
+ this.primeCopy(selection);
749
+ }
750
+ /** The Edit menu's Copy, chosen with the pointer, arrives here rather than as a keydown. */
751
+ onCopyEvent = (event) => {
752
+ const selection = this.hasSelection() ? this.getSelection() : (this.input?.value ?? '');
753
+ // The native action reads the textarea, so park the current selection
754
+ // there first, including when clipboardData is missing and the default
755
+ // must run.
756
+ this.primeCopy(selection);
757
+ if (applyTerminalCopyEvent(selection, event.clipboardData).preventDefault) {
758
+ event.preventDefault();
759
+ }
760
+ };
761
+ onPaste = (event) => {
762
+ // Always suppress the browser's default insertion: content the textarea
763
+ // would receive (for example an html-only clipboard converted to text)
764
+ // leaks through onInput without bracketed-paste encoding.
765
+ event.preventDefault();
766
+ this.paste(event.clipboardData?.getData('text/plain') ?? '');
767
+ };
768
+ /**
769
+ * Cut has no meaning in a terminal: the screen cannot give up its text,
770
+ * and the Edit menu's Cut would otherwise copy the parked selection and
771
+ * blank it. A cancelled cut that set no data leaves the clipboard alone.
772
+ */
773
+ onCut = (event) => {
774
+ event.preventDefault();
775
+ };
776
+ onCompositionStart = () => {
777
+ // The textarea now holds the IME candidate, not the parked selection.
778
+ if (this.primedCopySelection.length > 0)
779
+ this.clearSelection();
780
+ this.clearCompositionInputSuppression();
781
+ this.composing = true;
782
+ };
783
+ onCompositionEnd = (event) => {
784
+ if (this.input === null)
785
+ return;
786
+ this.composing = false;
787
+ const data = this.input.value || event.data;
788
+ this.sendInput(data);
789
+ this.input.value = '';
790
+ this.compositionInputToSuppress = data;
791
+ this.compositionSuppressionTimer = window.setTimeout(() => {
792
+ this.compositionInputToSuppress = null;
793
+ this.compositionSuppressionTimer = null;
794
+ }, 100);
795
+ };
796
+ onInput = (event) => {
797
+ if (this.input === null)
798
+ return;
799
+ const inputEvent = event;
800
+ if (this.composing || inputEvent.isComposing)
801
+ return;
802
+ const data = this.input.value || inputEvent.data || '';
803
+ if (data === this.compositionInputToSuppress && isTerminalCompositionCommitInput(inputEvent)) {
804
+ this.clearCompositionInputSuppression();
805
+ this.input.value = '';
806
+ return;
807
+ }
808
+ this.clearCompositionInputSuppression();
809
+ this.sendInput(data);
810
+ this.input.value = '';
811
+ };
812
+ clearCompositionInputSuppression() {
813
+ if (this.compositionSuppressionTimer !== null) {
814
+ window.clearTimeout(this.compositionSuppressionTimer);
815
+ this.compositionSuppressionTimer = null;
816
+ }
817
+ this.compositionInputToSuppress = null;
818
+ }
819
+ mouseTracking() {
820
+ return !this.readOnly && this.core.isMouseTracking();
821
+ }
822
+ onPointerDown = (event) => {
823
+ this.focus();
824
+ this.secondaryPointerId = null;
825
+ if (isTerminalSecondaryPress(event)) {
826
+ // The menu its `contextmenu` opens is the press's whole meaning. The
827
+ // capture brings the release back here, since the menu may open under
828
+ // the pointer.
829
+ this.secondaryPointerId = event.pointerId;
830
+ this.canvas.setPointerCapture(event.pointerId);
831
+ return;
832
+ }
833
+ if (shouldReportTerminalMouse(this.mouseTracking(), event)) {
834
+ const button = ghosttyMouseButton(event.button);
835
+ if (button === null)
836
+ return;
837
+ event.preventDefault();
838
+ event.stopPropagation();
839
+ this.clearHoveredLink('default');
840
+ this.mouseReportingPointerId = event.pointerId;
841
+ this.mouseReportingButton = button;
842
+ this.sendMouse('press', button, event);
843
+ this.canvas.setPointerCapture(event.pointerId);
844
+ return;
845
+ }
846
+ if (event.button !== 0)
847
+ return;
848
+ const clickCount = this.recordSelectionClick(event);
849
+ const link = event.metaKey ? this.linkAt(event.clientX, event.clientY) : null;
850
+ if (link && !event.shiftKey && clickCount === 1) {
851
+ event.preventDefault();
852
+ event.stopPropagation();
853
+ this.linkActivationPointerId = event.pointerId;
854
+ this.linkActivationLink = link;
855
+ this.linkActivationOrigin = {
856
+ x: event.clientX,
857
+ y: event.clientY,
858
+ clickCount
859
+ };
860
+ this.canvas.setPointerCapture(event.pointerId);
861
+ return;
862
+ }
863
+ this.clearHoveredLink();
864
+ this.beginSelection(event, clickCount);
865
+ this.canvas.setPointerCapture(event.pointerId);
866
+ };
867
+ recordSelectionClick(event) {
868
+ this.selectionClickSequence = advanceTerminalSelectionClickSequence(this.selectionClickSequence, event);
869
+ return this.selectionClickSequence.count;
870
+ }
871
+ beginSelection(event, clickCount) {
872
+ const cell = this.cellAt(event.clientX, event.clientY);
873
+ this.selectionMoved = false;
874
+ this.selectionMode = clickCount >= 3 ? 'line' : clickCount === 2 ? 'word' : 'cell';
875
+ const range = this.selectionMode === 'line'
876
+ ? this.core.selectLine(cell.x, cell.y)
877
+ : this.selectionMode === 'word'
878
+ ? this.core.selectWord(cell.x, cell.y)
879
+ : null;
880
+ if (range) {
881
+ this.selectionBase = range.screen;
882
+ this.selectionEnd = range.viewport.end;
883
+ this.selectionAnchorScreen = range.screen.start;
884
+ }
885
+ else {
886
+ this.selectionMode = 'cell';
887
+ this.selectionBase = null;
888
+ this.selectionEnd = cell;
889
+ const screen = this.core.viewportPointToScreen(cell.x, cell.y);
890
+ this.selectionAnchorScreen = screen;
891
+ if (screen) {
892
+ this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
893
+ }
894
+ else {
895
+ this.core.setSelection(cell, cell);
896
+ }
897
+ }
898
+ this.forceFullRender = true;
899
+ this.requestRender();
900
+ }
901
+ onPointerMove = (event) => {
902
+ // A held secondary press drags neither a report nor a selection.
903
+ if (this.secondaryPointerId === event.pointerId)
904
+ return;
905
+ if (this.linkActivationPointerId === event.pointerId) {
906
+ const origin = this.linkActivationOrigin;
907
+ if (origin === null || !isTerminalPointerDrag(origin, event)) {
908
+ return;
909
+ }
910
+ this.linkActivationPointerId = null;
911
+ this.linkActivationLink = null;
912
+ this.linkActivationOrigin = null;
913
+ this.clearHoveredLink();
914
+ this.beginSelection({
915
+ clientX: origin.x,
916
+ clientY: origin.y
917
+ }, origin.clickCount);
918
+ }
919
+ // Hover motion is only reportable in any-event tracking (DEC 1003); normal and
920
+ // button-event tracking never report motion without a captured pressed button.
921
+ const anyEventTracking = !this.readOnly && this.synchronizeMouseTrackingState();
922
+ if (this.mouseReportingPointerId === event.pointerId ||
923
+ shouldReportTerminalMouse(anyEventTracking, event)) {
924
+ event.preventDefault();
925
+ this.hoverPointer = { x: event.clientX, y: event.clientY };
926
+ // A drag whose press was already sent to the terminal application cannot
927
+ // turn into link activation midway through, so link feedback would lie.
928
+ this.setHoveredLink(null);
929
+ this.canvas.style.cursor = 'default';
930
+ this.sendMouse('motion', this.buttonFromButtons(event.buttons), event);
931
+ return;
932
+ }
933
+ this.lastMouseMotionData = '';
934
+ if (!this.selectionAnchorScreen || !this.canvas.hasPointerCapture(event.pointerId)) {
935
+ this.updateHoverCursor(event);
936
+ return;
937
+ }
938
+ this.clearHoveredLink();
939
+ this.selectionPointer = { x: event.clientX, y: event.clientY };
940
+ const bounds = this.canvas.getBoundingClientRect();
941
+ this.setSelectionAutoscroll(event.clientY < bounds.top ? -1 : event.clientY > bounds.bottom ? 1 : 0);
942
+ const cell = this.cellAt(event.clientX, event.clientY);
943
+ if (cell.x === this.selectionEnd?.x && cell.y === this.selectionEnd.y)
944
+ return;
945
+ this.extendSelectionTo(event.clientX, event.clientY);
946
+ };
947
+ extendSelectionTo(clientX, clientY) {
948
+ const anchorScreen = this.selectionAnchorScreen;
949
+ if (anchorScreen === null)
950
+ return;
951
+ const cell = this.cellAt(clientX, clientY);
952
+ this.selectionMoved = true;
953
+ this.selectionEnd = cell;
954
+ const range = this.selectionMode === 'line'
955
+ ? this.core.selectLine(cell.x, cell.y)
956
+ : this.selectionMode === 'word'
957
+ ? this.core.selectWord(cell.x, cell.y)
958
+ : null;
959
+ const cellScreen = this.core.viewportPointToScreen(cell.x, cell.y);
960
+ if (cellScreen === null)
961
+ return;
962
+ const base = this.selectionBase;
963
+ const beforeBase = base !== null &&
964
+ (cellScreen.y < base.start.y ||
965
+ (cellScreen.y === base.start.y && cellScreen.x < base.start.x));
966
+ const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
967
+ const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
968
+ this.selectionAnchorScreen = anchor;
969
+ this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
970
+ this.forceFullRender = true;
971
+ this.requestRender();
972
+ }
973
+ setSelectionAutoscroll(delta) {
974
+ this.selectionScrollDelta = delta;
975
+ if (delta === 0) {
976
+ if (this.selectionScrollTimer !== null) {
977
+ window.clearInterval(this.selectionScrollTimer);
978
+ this.selectionScrollTimer = null;
979
+ }
980
+ return;
981
+ }
982
+ if (this.selectionScrollTimer !== null)
983
+ return;
984
+ // Dragging past the edge scrolls the viewport and keeps extending the
985
+ // selection into the newly revealed rows, like xterm's drag scroller.
986
+ this.selectionScrollTimer = window.setInterval(() => {
987
+ if (this.disposed || this.selectionScrollDelta === 0)
988
+ return;
989
+ this.scrollViewport(this.selectionScrollDelta);
990
+ const pointer = this.selectionPointer;
991
+ if (pointer)
992
+ this.extendSelectionTo(pointer.x, pointer.y);
993
+ }, 80);
994
+ }
995
+ updateHoverCursor(event) {
996
+ // Links only light up while Command is held, the chord that opens them.
997
+ this.hoverPointer = event.metaKey ? { x: event.clientX, y: event.clientY } : null;
998
+ this.refreshHoveredLink();
999
+ }
1000
+ onPointerLeave = () => {
1001
+ this.lastMouseMotionData = '';
1002
+ this.clearHoveredLink();
1003
+ };
1004
+ clearHoveredLink(cursor = '') {
1005
+ this.hoverPointer = null;
1006
+ this.setHoveredLink(null);
1007
+ this.canvas.style.cursor = cursor;
1008
+ }
1009
+ refreshHoveredLink() {
1010
+ const pointer = this.hoverPointer;
1011
+ const link = pointer ? this.linkAt(pointer.x, pointer.y) : null;
1012
+ this.setHoveredLink(link);
1013
+ }
1014
+ setHoveredLink(link) {
1015
+ const previous = this.hoveredLink;
1016
+ const unchanged = previous === null ? link === null : link !== null && isSameTerminalLink(previous, link);
1017
+ this.canvas.style.cursor = link ? 'pointer' : '';
1018
+ if (unchanged)
1019
+ return;
1020
+ this.hoveredLink = link;
1021
+ this.forceFullRender = true;
1022
+ this.requestRender();
1023
+ }
1024
+ onPointerUp = (event) => {
1025
+ this.setSelectionAutoscroll(0);
1026
+ if (this.secondaryPointerId === event.pointerId) {
1027
+ this.secondaryPointerId = null;
1028
+ if (this.canvas.hasPointerCapture(event.pointerId)) {
1029
+ this.canvas.releasePointerCapture(event.pointerId);
1030
+ }
1031
+ return;
1032
+ }
1033
+ if (this.linkActivationPointerId === event.pointerId) {
1034
+ event.preventDefault();
1035
+ event.stopPropagation();
1036
+ const link = this.linkActivationLink;
1037
+ this.linkActivationPointerId = null;
1038
+ this.linkActivationLink = null;
1039
+ this.linkActivationOrigin = null;
1040
+ if (this.canvas.hasPointerCapture(event.pointerId)) {
1041
+ this.canvas.releasePointerCapture(event.pointerId);
1042
+ }
1043
+ if (event.type !== 'pointercancel') {
1044
+ if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY))) {
1045
+ this.options.onLinkActivate?.(link.text, event);
1046
+ }
1047
+ }
1048
+ return;
1049
+ }
1050
+ if (this.mouseReportingPointerId === event.pointerId) {
1051
+ event.preventDefault();
1052
+ event.stopPropagation();
1053
+ this.sendMouse('release', this.mouseReportingButton, event);
1054
+ this.mouseReportingPointerId = null;
1055
+ this.mouseReportingButton = null;
1056
+ if (this.canvas.hasPointerCapture(event.pointerId)) {
1057
+ this.canvas.releasePointerCapture(event.pointerId);
1058
+ }
1059
+ if (event.type === 'pointercancel') {
1060
+ this.clearHoveredLink();
1061
+ }
1062
+ else {
1063
+ this.updateHoverCursor(event);
1064
+ }
1065
+ return;
1066
+ }
1067
+ if (this.canvas.hasPointerCapture(event.pointerId)) {
1068
+ this.canvas.releasePointerCapture(event.pointerId);
1069
+ }
1070
+ if (event.button !== 0)
1071
+ return;
1072
+ if (!this.selectionMoved && this.selectionMode === 'cell') {
1073
+ this.clearSelection();
1074
+ return;
1075
+ }
1076
+ this.primeSettledSelection();
1077
+ };
1078
+ onWheel = (event) => {
1079
+ if (event.deltaY === 0)
1080
+ return;
1081
+ event.preventDefault();
1082
+ const delta = terminalWheelDeltaRows(event, this.metrics.height, this.rows, this.wheelRemainder);
1083
+ this.wheelRemainder = delta.remainder;
1084
+ if (delta.rows === 0)
1085
+ return;
1086
+ const magnitude = Math.abs(delta.rows);
1087
+ if (shouldReportTerminalMouse(this.mouseTracking(), event)) {
1088
+ const button = delta.rows < 0 ? 4 : 5;
1089
+ for (let index = 0; index < magnitude; index += 1) {
1090
+ this.sendMouse('press', button, event);
1091
+ }
1092
+ return;
1093
+ }
1094
+ if (!this.readOnly && this.core.isAlternateScreen()) {
1095
+ // The alternate screen has no scrollback: translate wheel motion into
1096
+ // arrow keys so full-screen apps like vim and less scroll, matching xterm.
1097
+ this.options.onData(terminalWheelArrowData(delta.rows, this.core.isApplicationCursorKeys()));
1098
+ return;
1099
+ }
1100
+ this.scrollViewport(delta.rows);
1101
+ };
1102
+ onMouseDown = (event) => {
1103
+ // The canvas has no native selection or focus behavior worth keeping. A
1104
+ // secondary click's `contextmenu` still fires after a cancelled press.
1105
+ if (event.button === 0 || isTerminalSecondaryPress(event))
1106
+ event.preventDefault();
1107
+ this.focus();
1108
+ };
1109
+ onContextMenu = (event) => {
1110
+ // The browser's own menu has nothing for a canvas; the host draws one.
1111
+ event.preventDefault();
1112
+ this.options.onContextMenu?.({ clientX: event.clientX, clientY: event.clientY });
1113
+ };
1114
+ onScrollbarPointerDown = (event) => {
1115
+ if (event.button !== 0)
1116
+ return;
1117
+ const state = this.readScrollbarState();
1118
+ if (state === null)
1119
+ return;
1120
+ const bounds = this.scrollbar.getBoundingClientRect();
1121
+ const geometry = terminalScrollbarGeometry(state, bounds.height);
1122
+ if (geometry === null)
1123
+ return;
1124
+ event.preventDefault();
1125
+ event.stopPropagation();
1126
+ this.scrollbarPointerId = event.pointerId;
1127
+ this.scrollbarPointerOffset =
1128
+ event.target === this.scrollbarThumb
1129
+ ? event.clientY - bounds.top - geometry.thumbTop
1130
+ : geometry.thumbHeight / 2;
1131
+ this.scrollbar.setPointerCapture(event.pointerId);
1132
+ this.scrollbarToPointer(event.clientY, bounds);
1133
+ };
1134
+ onScrollbarPointerMove = (event) => {
1135
+ if (event.pointerId !== this.scrollbarPointerId || this.scrollbarState === null)
1136
+ return;
1137
+ event.preventDefault();
1138
+ this.scrollbarToPointer(event.clientY, this.scrollbar.getBoundingClientRect());
1139
+ };
1140
+ onScrollbarPointerUp = (event) => {
1141
+ if (event.pointerId !== this.scrollbarPointerId)
1142
+ return;
1143
+ event.preventDefault();
1144
+ this.scrollbarPointerId = null;
1145
+ if (this.scrollbar.hasPointerCapture(event.pointerId)) {
1146
+ this.scrollbar.releasePointerCapture(event.pointerId);
1147
+ }
1148
+ };
1149
+ onScrollbarKeyDown = (event) => {
1150
+ const state = this.readScrollbarState();
1151
+ if (state === null)
1152
+ return;
1153
+ let delta;
1154
+ switch (event.key) {
1155
+ case 'ArrowUp':
1156
+ delta = -1;
1157
+ break;
1158
+ case 'ArrowDown':
1159
+ delta = 1;
1160
+ break;
1161
+ case 'PageUp':
1162
+ delta = -Math.max(1, state.len);
1163
+ break;
1164
+ case 'PageDown':
1165
+ delta = Math.max(1, state.len);
1166
+ break;
1167
+ case 'Home':
1168
+ delta = -state.offset;
1169
+ break;
1170
+ case 'End':
1171
+ delta = state.total - state.len - state.offset;
1172
+ break;
1173
+ default:
1174
+ return;
1175
+ }
1176
+ event.preventDefault();
1177
+ event.stopPropagation();
1178
+ this.scrollViewport(delta);
1179
+ };
1180
+ installEvents() {
1181
+ this.keyTarget.addEventListener('keydown', this.onKeyDown);
1182
+ this.keyTarget.addEventListener('keyup', this.onKeyUp);
1183
+ // Capture on the window, ahead of any ancestor that stops a key before it
1184
+ // reaches the terminal.
1185
+ window.addEventListener('keyup', this.onWindowKeyUp, { capture: true });
1186
+ window.addEventListener('keydown', this.onWindowKeyDown, { capture: true });
1187
+ this.keyTarget.addEventListener('focus', this.onFocus);
1188
+ this.keyTarget.addEventListener('blur', this.onBlur);
1189
+ this.keyTarget.addEventListener('copy', this.onCopyEvent);
1190
+ this.keyTarget.addEventListener('cut', this.onCut);
1191
+ if (this.input !== null) {
1192
+ this.input.addEventListener('input', this.onInput);
1193
+ this.input.addEventListener('paste', this.onPaste);
1194
+ this.input.addEventListener('compositionstart', this.onCompositionStart);
1195
+ this.input.addEventListener('compositionend', this.onCompositionEnd);
1196
+ }
1197
+ this.canvas.addEventListener('pointerdown', this.onPointerDown);
1198
+ this.canvas.addEventListener('pointermove', this.onPointerMove);
1199
+ this.canvas.addEventListener('pointerleave', this.onPointerLeave);
1200
+ this.canvas.addEventListener('pointerup', this.onPointerUp);
1201
+ this.canvas.addEventListener('pointercancel', this.onPointerUp);
1202
+ this.canvas.addEventListener('wheel', this.onWheel, { passive: false });
1203
+ this.canvas.addEventListener('mousedown', this.onMouseDown);
1204
+ this.canvas.addEventListener('contextmenu', this.onContextMenu);
1205
+ this.scrollbar.addEventListener('pointerdown', this.onScrollbarPointerDown);
1206
+ this.scrollbar.addEventListener('pointermove', this.onScrollbarPointerMove);
1207
+ this.scrollbar.addEventListener('pointerup', this.onScrollbarPointerUp);
1208
+ this.scrollbar.addEventListener('pointercancel', this.onScrollbarPointerUp);
1209
+ this.scrollbar.addEventListener('keydown', this.onScrollbarKeyDown);
1210
+ }
1211
+ removeEvents() {
1212
+ this.keyTarget.removeEventListener('keydown', this.onKeyDown);
1213
+ this.keyTarget.removeEventListener('keyup', this.onKeyUp);
1214
+ window.removeEventListener('keyup', this.onWindowKeyUp, { capture: true });
1215
+ window.removeEventListener('keydown', this.onWindowKeyDown, { capture: true });
1216
+ this.keyTarget.removeEventListener('focus', this.onFocus);
1217
+ this.keyTarget.removeEventListener('blur', this.onBlur);
1218
+ this.keyTarget.removeEventListener('copy', this.onCopyEvent);
1219
+ this.keyTarget.removeEventListener('cut', this.onCut);
1220
+ if (this.input !== null) {
1221
+ this.input.removeEventListener('input', this.onInput);
1222
+ this.input.removeEventListener('paste', this.onPaste);
1223
+ this.input.removeEventListener('compositionstart', this.onCompositionStart);
1224
+ this.input.removeEventListener('compositionend', this.onCompositionEnd);
1225
+ }
1226
+ this.canvas.removeEventListener('pointerdown', this.onPointerDown);
1227
+ this.canvas.removeEventListener('pointermove', this.onPointerMove);
1228
+ this.canvas.removeEventListener('pointerleave', this.onPointerLeave);
1229
+ this.canvas.removeEventListener('pointerup', this.onPointerUp);
1230
+ this.canvas.removeEventListener('pointercancel', this.onPointerUp);
1231
+ this.canvas.removeEventListener('wheel', this.onWheel);
1232
+ this.canvas.removeEventListener('mousedown', this.onMouseDown);
1233
+ this.canvas.removeEventListener('contextmenu', this.onContextMenu);
1234
+ this.scrollbar.removeEventListener('pointerdown', this.onScrollbarPointerDown);
1235
+ this.scrollbar.removeEventListener('pointermove', this.onScrollbarPointerMove);
1236
+ this.scrollbar.removeEventListener('pointerup', this.onScrollbarPointerUp);
1237
+ this.scrollbar.removeEventListener('pointercancel', this.onScrollbarPointerUp);
1238
+ this.scrollbar.removeEventListener('keydown', this.onScrollbarKeyDown);
1239
+ }
1240
+ scrollViewport(deltaRows) {
1241
+ let delta = Math.trunc(deltaRows);
1242
+ const state = this.readScrollbarState();
1243
+ if (state !== null) {
1244
+ const maxOffset = Math.max(0, state.total - state.len);
1245
+ const offset = Math.max(0, Math.min(state.offset + delta, maxOffset));
1246
+ delta = offset - state.offset;
1247
+ this.scrollbarState = { ...state, offset };
1248
+ }
1249
+ if (delta === 0)
1250
+ return;
1251
+ this.core.scroll(delta);
1252
+ this.forceFullRender = true;
1253
+ this.scrollbarDirty = true;
1254
+ this.requestRender();
1255
+ }
1256
+ scrollbarToPointer(clientY, bounds) {
1257
+ const state = this.scrollbarState;
1258
+ if (state === null)
1259
+ return;
1260
+ const offset = terminalScrollbarOffsetAtPointer(state, bounds.height, clientY - bounds.top, this.scrollbarPointerOffset);
1261
+ this.scrollViewport(offset - state.offset);
1262
+ }
1263
+ updateScrollbar() {
1264
+ const state = this.readScrollbarState();
1265
+ const geometry = state === null
1266
+ ? null
1267
+ : terminalScrollbarGeometry(state, Math.max(0, this.mount.clientHeight - CONTENT_PADDING * 2));
1268
+ this.scrollbar.hidden = geometry === null;
1269
+ if (state === null || geometry === null)
1270
+ return;
1271
+ this.scrollbar.setAttribute('aria-valuemin', '0');
1272
+ this.scrollbar.setAttribute('aria-valuemax', String(geometry.maxOffset));
1273
+ this.scrollbar.setAttribute('aria-valuenow', String(Math.max(0, Math.min(state.offset, geometry.maxOffset))));
1274
+ this.scrollbarThumb.style.height = `${geometry.thumbHeight}px`;
1275
+ this.scrollbarThumb.style.transform = `translateY(${geometry.thumbTop}px)`;
1276
+ }
1277
+ readScrollbarState() {
1278
+ const state = this.core.scrollbarState();
1279
+ this.scrollbarState = state;
1280
+ return state;
1281
+ }
1282
+ canRender() {
1283
+ return !this.disposed && this.hasSize;
1284
+ }
1285
+ requestRender() {
1286
+ if (!this.canRender())
1287
+ return;
1288
+ // During an open update a frame still parses and acknowledges queued
1289
+ // output; with none queued there is nothing for it to do.
1290
+ if (this.deferSynchronizedRender() && this.pendingOutput.length === 0)
1291
+ return;
1292
+ if (this.frame !== 0)
1293
+ return;
1294
+ this.frame = window.requestAnimationFrame(() => {
1295
+ this.frame = 0;
1296
+ this.renderFrame();
1297
+ });
1298
+ }
1299
+ cancelRender() {
1300
+ this.cancelSynchronizedRenderTimer();
1301
+ if (this.frame !== 0) {
1302
+ window.cancelAnimationFrame(this.frame);
1303
+ this.frame = 0;
1304
+ }
1305
+ if (this.cursorTimer !== null) {
1306
+ window.clearTimeout(this.cursorTimer);
1307
+ this.cursorTimer = null;
1308
+ }
1309
+ }
1310
+ cancelSynchronizedRenderTimer() {
1311
+ if (this.synchronizedRenderTimer === null)
1312
+ return;
1313
+ window.clearTimeout(this.synchronizedRenderTimer);
1314
+ this.synchronizedRenderTimer = null;
1315
+ }
1316
+ /**
1317
+ * Whether painting must wait for an open synchronized update. The first
1318
+ * check that finds one open starts its deadline, which ends the update and
1319
+ * paints; the cursor holds its phase until then.
1320
+ */
1321
+ deferSynchronizedRender() {
1322
+ if (!this.core.isSynchronizedOutput()) {
1323
+ this.cancelSynchronizedRenderTimer();
1324
+ return false;
1325
+ }
1326
+ if (this.cursorTimer !== null) {
1327
+ window.clearTimeout(this.cursorTimer);
1328
+ this.cursorTimer = null;
1329
+ }
1330
+ if (this.synchronizedRenderTimer === null) {
1331
+ const deadline = window.setTimeout(() => {
1332
+ // Output queued before the deadline belongs to the update it ends, so
1333
+ // it parses first; if it ends that update itself, the paint (or the
1334
+ // deadline of the update it opens next) is already scheduled.
1335
+ this.parseQueuedOutput();
1336
+ if (this.synchronizedRenderTimer !== deadline)
1337
+ return;
1338
+ this.synchronizedRenderTimer = null;
1339
+ this.core.endSynchronizedOutput();
1340
+ this.renderFrame();
1341
+ }, SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS);
1342
+ this.synchronizedRenderTimer = deadline;
1343
+ }
1344
+ return true;
1345
+ }
1346
+ renderFrame() {
1347
+ if (this.disposed)
1348
+ return;
1349
+ if (this.frame !== 0) {
1350
+ window.cancelAnimationFrame(this.frame);
1351
+ this.frame = 0;
1352
+ }
1353
+ // A hidden terminal stays mounted so showing it again is instant, but a
1354
+ // display:none canvas has nothing to show. Ghostty keeps parsing; the
1355
+ // ResizeObserver refits and repaints in full once the mount has a size.
1356
+ if (this.mount.clientWidth === 0 || this.mount.clientHeight === 0) {
1357
+ this.hasSize = false;
1358
+ this.forceFullRender = true;
1359
+ this.cancelRender();
1360
+ this.parseQueuedOutput();
1361
+ return;
1362
+ }
1363
+ this.parseQueuedOutput();
1364
+ // Parsing queued output asks for a frame; this one already paints it.
1365
+ if (this.frame !== 0) {
1366
+ window.cancelAnimationFrame(this.frame);
1367
+ this.frame = 0;
1368
+ }
1369
+ // Output is parsed and acknowledged above whether or not it may be shown.
1370
+ if (this.deferSynchronizedRender())
1371
+ return;
1372
+ const backing = this.pendingCanvasBacking;
1373
+ if (backing !== null) {
1374
+ this.pendingCanvasBacking = null;
1375
+ this.canvas.width = backing.width;
1376
+ this.canvas.height = backing.height;
1377
+ this.context.setTransform(backing.ratio, 0, 0, backing.ratio, 0, 0);
1378
+ this.canvasBacking = backing;
1379
+ }
1380
+ this.snapshot = this.core.snapshot();
1381
+ // A cursor that is not blinking right now must be drawn, never caught in an
1382
+ // off phase left behind by a blink that has since been turned off.
1383
+ if (!this.blinkEnabled())
1384
+ this.cursorOn = true;
1385
+ this.refreshHoveredLink();
1386
+ const cursorOn = !this.readOnly && this.cursorOn;
1387
+ renderGhosttySnapshot({
1388
+ context: this.context,
1389
+ snapshot: this.snapshot,
1390
+ metrics: this.metrics,
1391
+ fontSize: this.fontSize,
1392
+ fontFamily: this.fontFamily,
1393
+ padding: CONTENT_PADDING,
1394
+ forceFull: this.forceFullRender,
1395
+ cursorOn,
1396
+ previousCursorY: this.renderedCursorY,
1397
+ focused: this.focused,
1398
+ hoveredLinkRange: this.hoveredLink?.range ?? null,
1399
+ pixelRatio: this.canvasBacking?.ratio ?? 1,
1400
+ textInk: this.textInk,
1401
+ ...(this.theme.selectionBackground !== undefined
1402
+ ? { selectionBackground: this.theme.selectionBackground }
1403
+ : {})
1404
+ });
1405
+ this.positionInput();
1406
+ this.renderedCursorY =
1407
+ cursorOn && this.snapshot.cursorVisible && this.snapshot.cursorY >= 0
1408
+ ? this.snapshot.cursorY
1409
+ : null;
1410
+ if (this.scrollbarDirty) {
1411
+ this.scrollbarDirty = false;
1412
+ this.updateScrollbar();
1413
+ }
1414
+ this.forceFullRender = false;
1415
+ this.scheduleCursorBlink();
1416
+ }
1417
+ scheduleCursorBlink() {
1418
+ if (this.cursorTimer !== null)
1419
+ window.clearTimeout(this.cursorTimer);
1420
+ this.cursorTimer = null;
1421
+ if (!this.blinkEnabled())
1422
+ return;
1423
+ this.cursorTimer = window.setTimeout(() => {
1424
+ this.cursorTimer = null;
1425
+ this.cursorOn = !this.cursorOn;
1426
+ this.requestRender();
1427
+ }, CURSOR_BLINK_INTERVAL_MS);
1428
+ }
1429
+ blinkEnabled() {
1430
+ const snapshot = this.snapshot;
1431
+ if (!snapshot || this.readOnly || !this.hasSize)
1432
+ return false;
1433
+ return shouldBlinkTerminalCursor({
1434
+ focused: this.focused,
1435
+ cursorBlinking: snapshot.cursorBlinking,
1436
+ cursorVisible: snapshot.cursorVisible,
1437
+ reducedMotion: this.reducedMotionMedia?.matches ?? false
1438
+ });
1439
+ }
1440
+ positionInput() {
1441
+ const snapshot = this.snapshot;
1442
+ if (this.input === null ||
1443
+ !snapshot ||
1444
+ !snapshot.cursorVisible ||
1445
+ snapshot.cursorX < 0 ||
1446
+ snapshot.cursorY < 0) {
1447
+ return;
1448
+ }
1449
+ // The IME candidate window anchors to the textarea, so it must follow the
1450
+ // terminal cursor for composition to appear where the user is typing.
1451
+ const left = CONTENT_PADDING + snapshot.cursorX * this.metrics.width;
1452
+ const top = CONTENT_PADDING + snapshot.cursorY * this.metrics.height;
1453
+ if (left === this.inputLeft && top === this.inputTop)
1454
+ return;
1455
+ this.inputLeft = left;
1456
+ this.inputTop = top;
1457
+ this.input.style.left = `${left}px`;
1458
+ this.input.style.top = `${top}px`;
1459
+ this.input.style.height = `${this.metrics.height}px`;
1460
+ }
1461
+ cellAt(clientX, clientY) {
1462
+ const bounds = this.canvas.getBoundingClientRect();
1463
+ return {
1464
+ x: Math.max(0, Math.min(this.cols - 1, Math.floor((clientX - bounds.left - CONTENT_PADDING) / this.metrics.width))),
1465
+ y: Math.max(0, Math.min(this.rows - 1, Math.floor((clientY - bounds.top - CONTENT_PADDING) / this.metrics.height)))
1466
+ };
1467
+ }
1468
+ linkAt(clientX, clientY) {
1469
+ if (!this.snapshot || this.options.onLinkActivate === undefined)
1470
+ return null;
1471
+ const cell = terminalGridCellAt({
1472
+ bounds: this.canvas.getBoundingClientRect(),
1473
+ clientX,
1474
+ clientY,
1475
+ cols: this.cols,
1476
+ rows: this.rows,
1477
+ metrics: this.metrics,
1478
+ padding: CONTENT_PADDING
1479
+ });
1480
+ if (!cell)
1481
+ return null;
1482
+ const explicitHyperlink = this.core.hyperlinkAt(cell.x, cell.y);
1483
+ // Only web links open; an OSC 8 link to anything else (file:, custom
1484
+ // schemes) stays inert.
1485
+ if (explicitHyperlink !== null && isTerminalUrl(explicitHyperlink)) {
1486
+ const start = { ...cell };
1487
+ const end = { ...cell };
1488
+ while (true) {
1489
+ const previous = start.x > 0
1490
+ ? { x: start.x - 1, y: start.y }
1491
+ : start.y > 0 && this.snapshot.rowData[start.y]?.isWrapContinuation
1492
+ ? { x: this.cols - 1, y: start.y - 1 }
1493
+ : null;
1494
+ if (!previous || this.core.hyperlinkAt(previous.x, previous.y) !== explicitHyperlink)
1495
+ break;
1496
+ start.x = previous.x;
1497
+ start.y = previous.y;
1498
+ }
1499
+ while (true) {
1500
+ const next = end.x + 1 < this.cols
1501
+ ? { x: end.x + 1, y: end.y }
1502
+ : end.y + 1 < this.rows && this.snapshot.rowData[end.y]?.wrapsToNext
1503
+ ? { x: 0, y: end.y + 1 }
1504
+ : null;
1505
+ if (!next || this.core.hyperlinkAt(next.x, next.y) !== explicitHyperlink)
1506
+ break;
1507
+ end.x = next.x;
1508
+ end.y = next.y;
1509
+ }
1510
+ return {
1511
+ text: explicitHyperlink,
1512
+ range: { start, end }
1513
+ };
1514
+ }
1515
+ return terminalLinkAtPositionWithRange(this.snapshot.rowData, cell.y, cell.x);
1516
+ }
1517
+ sendMouse(action, button, event) {
1518
+ const bounds = this.canvas.getBoundingClientRect();
1519
+ const data = this.core.encodeMouse({
1520
+ action,
1521
+ button,
1522
+ mods: (event.shiftKey ? 1 : 0) |
1523
+ (event.ctrlKey ? 1 << 1 : 0) |
1524
+ (event.altKey ? 1 << 2 : 0) |
1525
+ (event.metaKey ? 1 << 3 : 0),
1526
+ x: Math.max(0, event.clientX - bounds.left),
1527
+ y: Math.max(0, event.clientY - bounds.top),
1528
+ screenWidth: bounds.width,
1529
+ screenHeight: bounds.height,
1530
+ cellWidth: this.metrics.width,
1531
+ cellHeight: this.metrics.height,
1532
+ paddingLeft: CONTENT_PADDING,
1533
+ paddingRight: CONTENT_PADDING,
1534
+ paddingTop: CONTENT_PADDING,
1535
+ paddingBottom: Math.max(0, bounds.height - CONTENT_PADDING - this.rows * this.metrics.height),
1536
+ anyButtonPressed: event.buttons !== 0
1537
+ });
1538
+ const resolution = resolveTerminalMouseData(action, data, this.lastMouseMotionData);
1539
+ this.lastMouseMotionData = resolution.nextMotionData;
1540
+ if (resolution.send)
1541
+ this.options.onData(data);
1542
+ }
1543
+ synchronizeMouseTrackingState() {
1544
+ // Output writes can toggle DEC 1003 without moving the pointer. Keep the
1545
+ // previous mode so the next same-cell motion starts a fresh tracking session.
1546
+ const tracking = this.core.isMouseAnyEventTracking();
1547
+ const state = resolveTerminalMouseTrackingState(this.mouseAnyEventTracking, tracking, this.lastMouseMotionData);
1548
+ this.mouseAnyEventTracking = state.tracking;
1549
+ this.lastMouseMotionData = state.motionData;
1550
+ return tracking;
1551
+ }
1552
+ buttonFromButtons(buttons) {
1553
+ if ((buttons & 1) !== 0)
1554
+ return 1;
1555
+ if ((buttons & 4) !== 0)
1556
+ return 3;
1557
+ if ((buttons & 2) !== 0)
1558
+ return 2;
1559
+ if ((buttons & 8) !== 0)
1560
+ return 4;
1561
+ if ((buttons & 16) !== 0)
1562
+ return 5;
1563
+ return null;
1564
+ }
1565
+ }