feat(web): render terminals with libghostty-vt (#4860)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
ab8182cb4e
commit
acf761b2f5
28 files changed
+5217
-518
No files matched your search
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
|
||||
);
|
||||
assert.include(
|
||||
response.headers.get("content-security-policy") ?? "",
|
||||
@@ -212,6 +212,7 @@ describe("ElectronProtocol", () => {
|
||||
assert.deepEqual(directives["script-src"], [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
"https://clerk.t3.codes",
|
||||
"https://challenges.cloudflare.com",
|
||||
]);
|
||||
|
||||
@@ -71,6 +71,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
|
||||
const scriptSources = [
|
||||
"'self'",
|
||||
"'unsafe-inline'",
|
||||
"'wasm-unsafe-eval'",
|
||||
...(clerkOrigin ? [clerkOrigin] : []),
|
||||
"https://challenges.cloudflare.com",
|
||||
];
|
||||
|
||||
@@ -18,13 +18,14 @@ Ghostty's MIT license applies to the vendored framework. Keep this notice in syn
|
||||
## Ghostty / libghostty-vt
|
||||
|
||||
The Android terminal renderer vendors upstream `libghostty-vt` shared libraries and C headers.
|
||||
The web terminal vendors a WebAssembly build from the same revision and uses the same C ABI.
|
||||
|
||||
- Upstream project: https://github.com/ghostty-org/ghostty
|
||||
- Vendored revision: `9f62873bf195e4d8a762d768a1405a5f2f7b1697`
|
||||
- License: MIT
|
||||
|
||||
Ghostty's MIT license applies to the vendored Android libraries. Keep this notice in sync when
|
||||
updating `Vendor/libghostty-vt`.
|
||||
Ghostty's MIT license applies to the vendored Android and web libraries. Keep this notice and both
|
||||
artifacts in sync when updating `Vendor/libghostty-vt`.
|
||||
|
||||
## MesloLGS NF (Android terminal font)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build:ghostty-wasm": "bash scripts/build-libghostty-wasm.sh",
|
||||
"dev": "vp dev",
|
||||
"build": "vp build",
|
||||
"preview": "vp preview",
|
||||
@@ -31,8 +32,6 @@
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"jose": "catalog:",
|
||||
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
WEB_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
REPO_DIR="$(cd "${WEB_DIR}/../.." && pwd)"
|
||||
MOBILE_VENDOR_DIR="${REPO_DIR}/apps/mobile/modules/t3-terminal/Vendor/libghostty-vt"
|
||||
VENDOR_DIR="${WEB_DIR}/src/terminal/ghostty/vendor"
|
||||
|
||||
GHOSTTY_REVISION="$(tr -d '[:space:]' < "${MOBILE_VENDOR_DIR}/VERSION")"
|
||||
GHOSTTY_SOURCE_DIR="${GHOSTTY_SOURCE_DIR:-${HOME}/.cache/t3code/ghostty-${GHOSTTY_REVISION:0:8}}"
|
||||
GHOSTTY_ZIG_VERSION="${GHOSTTY_ZIG_VERSION:-0.15.2}"
|
||||
GHOSTTY_ZIG="${GHOSTTY_ZIG:-}"
|
||||
|
||||
log() {
|
||||
printf '[libghostty-vt-wasm] %s\n' "$*"
|
||||
}
|
||||
|
||||
die() {
|
||||
printf '[libghostty-vt-wasm] error: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"
|
||||
}
|
||||
|
||||
ensure_zig() {
|
||||
if [[ -n "${GHOSTTY_ZIG}" ]]; then
|
||||
[[ -x "${GHOSTTY_ZIG}" ]] || die "GHOSTTY_ZIG is not executable: ${GHOSTTY_ZIG}"
|
||||
return
|
||||
fi
|
||||
if command -v zig >/dev/null 2>&1 && [[ "$(zig version)" == "${GHOSTTY_ZIG_VERSION}" ]]; then
|
||||
GHOSTTY_ZIG="$(command -v zig)"
|
||||
return
|
||||
fi
|
||||
|
||||
local host_os host_arch cache_dir
|
||||
host_os="$(uname -s | tr '[:upper:]' '[:lower:]')"
|
||||
host_arch="$(uname -m)"
|
||||
case "${host_os}" in
|
||||
darwin) host_os="macos" ;;
|
||||
linux) ;;
|
||||
*) die "unsupported host OS for Zig download: ${host_os}" ;;
|
||||
esac
|
||||
case "${host_arch}" in
|
||||
arm64) host_arch="aarch64" ;;
|
||||
aarch64 | x86_64) ;;
|
||||
*) die "unsupported host architecture: ${host_arch}" ;;
|
||||
esac
|
||||
|
||||
cache_dir="${HOME}/.cache/t3code/zig-${GHOSTTY_ZIG_VERSION}"
|
||||
GHOSTTY_ZIG="${cache_dir}/zig"
|
||||
if [[ -x "${GHOSTTY_ZIG}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
require_cmd curl
|
||||
require_cmd tar
|
||||
mkdir -p "${cache_dir}"
|
||||
log "downloading Zig ${GHOSTTY_ZIG_VERSION}"
|
||||
curl -fsSL \
|
||||
"https://ziglang.org/download/${GHOSTTY_ZIG_VERSION}/zig-${host_arch}-${host_os}-${GHOSTTY_ZIG_VERSION}.tar.xz" \
|
||||
| tar -xJ --strip-components=1 -C "${cache_dir}"
|
||||
}
|
||||
|
||||
ensure_ghostty_source() {
|
||||
require_cmd git
|
||||
if [[ ! -d "${GHOSTTY_SOURCE_DIR}/.git" ]]; then
|
||||
mkdir -p "$(dirname "${GHOSTTY_SOURCE_DIR}")"
|
||||
log "cloning Ghostty ${GHOSTTY_REVISION}"
|
||||
git clone --filter=blob:none --no-checkout https://github.com/ghostty-org/ghostty.git \
|
||||
"${GHOSTTY_SOURCE_DIR}"
|
||||
fi
|
||||
|
||||
# A cached checkout may still be on a previously pinned revision; converge on
|
||||
# the pinned one instead of failing the rebuild.
|
||||
local actual_revision
|
||||
actual_revision="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD 2>/dev/null || echo none)"
|
||||
if [[ "${actual_revision}" != "${GHOSTTY_REVISION}" ]]; then
|
||||
log "checking out Ghostty ${GHOSTTY_REVISION}"
|
||||
git -C "${GHOSTTY_SOURCE_DIR}" fetch --depth=1 origin "${GHOSTTY_REVISION}"
|
||||
git -C "${GHOSTTY_SOURCE_DIR}" checkout --detach "${GHOSTTY_REVISION}"
|
||||
fi
|
||||
|
||||
actual_revision="$(git -C "${GHOSTTY_SOURCE_DIR}" rev-parse HEAD)"
|
||||
[[ "${actual_revision}" == "${GHOSTTY_REVISION}" ]] || \
|
||||
die "expected Ghostty ${GHOSTTY_REVISION}, found ${actual_revision}"
|
||||
}
|
||||
|
||||
ensure_zig
|
||||
ensure_ghostty_source
|
||||
|
||||
build_root="$(mktemp -d)"
|
||||
trap 'rm -rf "${build_root}"' EXIT
|
||||
|
||||
log "building ${GHOSTTY_REVISION} for wasm32-freestanding"
|
||||
(
|
||||
cd "${GHOSTTY_SOURCE_DIR}"
|
||||
# The pinned revision rides along as semver build metadata so the artifact
|
||||
# identifies its own provenance through ghostty_build_info(); mobile's
|
||||
# VERSION file stays the single source of truth for the pin.
|
||||
"${GHOSTTY_ZIG}" build \
|
||||
-Demit-lib-vt \
|
||||
-Dtarget=wasm32-freestanding \
|
||||
-Doptimize=ReleaseSmall \
|
||||
-Dstrip=true \
|
||||
-Dlib-version-string="0.1.0-dev+${GHOSTTY_REVISION}" \
|
||||
-p "${build_root}"
|
||||
)
|
||||
|
||||
mkdir -p "${VENDOR_DIR}"
|
||||
cp "${build_root}/bin/ghostty-vt.wasm" "${VENDOR_DIR}/ghostty-vt.wasm"
|
||||
"${GHOSTTY_ZIG}" build-exe \
|
||||
"${SCRIPT_DIR}/ghostty-write-pty.zig" \
|
||||
-target wasm32-freestanding \
|
||||
-O ReleaseSmall \
|
||||
-fno-entry \
|
||||
-rdynamic \
|
||||
-femit-bin="${VENDOR_DIR}/ghostty-write-pty.wasm"
|
||||
chmod 0644 "${VENDOR_DIR}/ghostty-write-pty.wasm"
|
||||
log "wrote ${VENDOR_DIR}/ghostty-vt.wasm"
|
||||
@@ -0,0 +1,5 @@
|
||||
extern "env" fn t3_write_pty(terminal: u32, userdata: u32, data: u32, len: u32) void;
|
||||
|
||||
export fn ghostty_write_pty(terminal: u32, userdata: u32, data: u32, len: u32) void {
|
||||
t3_write_pty(terminal, userdata, data, len);
|
||||
}
|
||||
@@ -704,6 +704,19 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
() => drawerTerminalSessions.map((session) => session.target.terminalId),
|
||||
[drawerTerminalSessions],
|
||||
);
|
||||
// Every client-side id source participates in allocation: the server list
|
||||
// lags fresh opens, and panel terminals are filtered out of the drawer's
|
||||
// sessions — an id collision attaches two viewports to one PTY session.
|
||||
const allocatableTerminalIds = useMemo(
|
||||
() => [
|
||||
...new Set([
|
||||
...serverOrderedTerminalIds,
|
||||
...terminalUiState.terminalIds,
|
||||
...panelTerminalIds,
|
||||
]),
|
||||
],
|
||||
[panelTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds],
|
||||
);
|
||||
const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);
|
||||
const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);
|
||||
const storeSplitTerminalVertical = useTerminalUiStateStore(
|
||||
@@ -773,7 +786,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(serverOrderedTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableTerminalIds);
|
||||
storeSplitTerminal(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
void openTerminal({
|
||||
@@ -787,11 +800,11 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
},
|
||||
});
|
||||
}, [
|
||||
allocatableTerminalIds,
|
||||
bumpFocusRequestId,
|
||||
cwd,
|
||||
effectiveWorktreePath,
|
||||
runtimeEnv,
|
||||
serverOrderedTerminalIds,
|
||||
storeSplitTerminal,
|
||||
threadId,
|
||||
threadRef,
|
||||
@@ -801,7 +814,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(serverOrderedTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableTerminalIds);
|
||||
storeSplitTerminalVertical(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
void openTerminal({
|
||||
@@ -815,12 +828,12 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
},
|
||||
});
|
||||
}, [
|
||||
allocatableTerminalIds,
|
||||
bumpFocusRequestId,
|
||||
cwd,
|
||||
effectiveWorktreePath,
|
||||
openTerminal,
|
||||
runtimeEnv,
|
||||
serverOrderedTerminalIds,
|
||||
storeSplitTerminalVertical,
|
||||
threadId,
|
||||
threadRef,
|
||||
@@ -830,7 +843,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(serverOrderedTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableTerminalIds);
|
||||
storeNewTerminal(threadRef, terminalId);
|
||||
bumpFocusRequestId();
|
||||
void openTerminal({
|
||||
@@ -847,8 +860,8 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
|
||||
bumpFocusRequestId,
|
||||
cwd,
|
||||
effectiveWorktreePath,
|
||||
allocatableTerminalIds,
|
||||
runtimeEnv,
|
||||
serverOrderedTerminalIds,
|
||||
storeNewTerminal,
|
||||
threadId,
|
||||
threadRef,
|
||||
@@ -1521,6 +1534,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
),
|
||||
[rightPanelState.surfaces],
|
||||
);
|
||||
const allocatableActiveTerminalIds = useMemo(
|
||||
() => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])],
|
||||
[activeKnownTerminalIds, panelTerminalIds],
|
||||
);
|
||||
const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();
|
||||
const rightPanelOpen = rightPanelState.isOpen;
|
||||
const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet;
|
||||
@@ -2628,7 +2645,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!cwdForOpen) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId([...activeKnownTerminalIds, ...panelTerminalIds]);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
storeEnsureTerminal(activeThreadRef, terminalId, { open: true });
|
||||
void openTerminal({
|
||||
environmentId,
|
||||
@@ -2647,15 +2664,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
setTerminalOpen(nextOpen);
|
||||
}, [
|
||||
activeKnownTerminalIds,
|
||||
activeProject,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
allocatableActiveTerminalIds,
|
||||
environmentId,
|
||||
gitCwd,
|
||||
openTerminal,
|
||||
panelTerminalIds,
|
||||
setTerminalOpen,
|
||||
storeEnsureTerminal,
|
||||
terminalUiState.terminalIds.length,
|
||||
@@ -2670,7 +2686,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!cwdForOpen) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(activeKnownTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
if (direction === "vertical") {
|
||||
storeSplitTerminalVertical(activeThreadRef, terminalId);
|
||||
} else {
|
||||
@@ -2693,8 +2709,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
activeKnownTerminalIds,
|
||||
activeThreadId,
|
||||
allocatableActiveTerminalIds,
|
||||
activeThreadRef,
|
||||
openTerminal,
|
||||
activeThreadWorktreePath,
|
||||
@@ -2713,7 +2729,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!cwdForOpen) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId(activeKnownTerminalIds);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
storeNewTerminal(activeThreadRef, terminalId);
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
void openTerminal({
|
||||
@@ -2731,8 +2747,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
}, [
|
||||
activeProject,
|
||||
activeKnownTerminalIds,
|
||||
activeThreadId,
|
||||
allocatableActiveTerminalIds,
|
||||
activeThreadRef,
|
||||
openTerminal,
|
||||
activeThreadWorktreePath,
|
||||
@@ -2818,7 +2834,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
...(options?.env ? { extraEnv: options.env } : {}),
|
||||
});
|
||||
const targetTerminalId = shouldCreateNewTerminal
|
||||
? nextTerminalId(activeKnownTerminalIds)
|
||||
? nextTerminalId(allocatableActiveTerminalIds)
|
||||
: baseTerminalId;
|
||||
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
|
||||
? {
|
||||
@@ -2886,6 +2902,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
environmentId,
|
||||
openTerminal,
|
||||
activeKnownTerminalIds,
|
||||
allocatableActiveTerminalIds,
|
||||
runningTerminalIds,
|
||||
terminalUiState.activeTerminalId,
|
||||
writeTerminal,
|
||||
@@ -3144,7 +3161,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const addTerminalSurface = useCallback(() => {
|
||||
if (!activeThreadRef || !activeThreadId || !activeProject) return;
|
||||
const cwd = gitCwd ?? activeProject.workspaceRoot;
|
||||
const terminalId = nextTerminalId([...activeKnownTerminalIds, ...panelTerminalIds]);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId);
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
void openTerminal({
|
||||
@@ -3161,14 +3178,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
});
|
||||
}, [
|
||||
activeKnownTerminalIds,
|
||||
activeProject,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
allocatableActiveTerminalIds,
|
||||
gitCwd,
|
||||
openTerminal,
|
||||
panelTerminalIds,
|
||||
]);
|
||||
const splitPanelTerminal = useCallback(
|
||||
(direction: "horizontal" | "vertical" = "horizontal") => {
|
||||
@@ -3181,7 +3197,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const terminalId = nextTerminalId([...activeKnownTerminalIds, ...panelTerminalIds]);
|
||||
const terminalId = nextTerminalId(allocatableActiveTerminalIds);
|
||||
const cwd = gitCwd ?? activeProject.workspaceRoot;
|
||||
useRightPanelStore
|
||||
.getState()
|
||||
@@ -3202,15 +3218,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
},
|
||||
[
|
||||
activeKnownTerminalIds,
|
||||
activeProject,
|
||||
activeRightPanelSurface,
|
||||
activeThreadId,
|
||||
activeThreadRef,
|
||||
activeThreadWorktreePath,
|
||||
allocatableActiveTerminalIds,
|
||||
gitCwd,
|
||||
openTerminal,
|
||||
panelTerminalIds,
|
||||
],
|
||||
);
|
||||
const splitPanelTerminalVertical = useCallback(() => {
|
||||
|
||||
@@ -2,8 +2,10 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveTerminalSelectionActionPosition,
|
||||
shouldHandleTerminalExit,
|
||||
shouldHandleTerminalSelectionMouseUp,
|
||||
terminalSelectionActionDelayForClickCount,
|
||||
terminalSelectionLineRange,
|
||||
} from "./ThreadTerminalDrawer";
|
||||
|
||||
describe("resolveTerminalSelectionActionPosition", () => {
|
||||
@@ -72,4 +74,19 @@ describe("resolveTerminalSelectionActionPosition", () => {
|
||||
expect(shouldHandleTerminalSelectionMouseUp(false, 0)).toBe(false);
|
||||
expect(shouldHandleTerminalSelectionMouseUp(true, 1)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses Ghostty's physical screen range for visually wrapped selections", () => {
|
||||
expect(
|
||||
terminalSelectionLineRange({
|
||||
start: { y: 4 },
|
||||
end: { y: 6 },
|
||||
}),
|
||||
).toEqual({ lineStart: 5, lineEnd: 7 });
|
||||
});
|
||||
|
||||
it("handles an exit that lands while the terminal surface is still loading", () => {
|
||||
expect(shouldHandleTerminalExit("exited", "running", false)).toBe(true);
|
||||
expect(shouldHandleTerminalExit("exited", "exited", false)).toBe(false);
|
||||
expect(shouldHandleTerminalExit("closed", "running", true)).toBe(false);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
+30
-14
@@ -1049,6 +1049,36 @@ code {
|
||||
background: var(--app-scrollbar-thumb-hover);
|
||||
}
|
||||
|
||||
.t3-ghostty-canvas {
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.t3-ghostty-scrollbar {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 4px;
|
||||
right: 1px;
|
||||
bottom: 4px;
|
||||
width: var(--app-scrollbar-width);
|
||||
cursor: default;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.t3-ghostty-scrollbar-thumb {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 1px;
|
||||
left: 1px;
|
||||
border-radius: 3px;
|
||||
background: var(--app-scrollbar-thumb);
|
||||
transition: background-color 120ms ease-out;
|
||||
}
|
||||
|
||||
.t3-ghostty-scrollbar:hover .t3-ghostty-scrollbar-thumb,
|
||||
.t3-ghostty-scrollbar:focus-visible .t3-ghostty-scrollbar-thumb {
|
||||
background: var(--app-scrollbar-thumb-hover);
|
||||
}
|
||||
|
||||
.model-picker-list::-webkit-scrollbar-track {
|
||||
margin-block: 0.5rem;
|
||||
}
|
||||
@@ -1101,20 +1131,6 @@ code {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Terminal drawer scrollbar parity with chat */
|
||||
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
|
||||
width: 6px !important;
|
||||
}
|
||||
|
||||
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar > .slider {
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical > .slider {
|
||||
width: 6px !important;
|
||||
left: 0 !important;
|
||||
}
|
||||
|
||||
/* Reasoning select -- clickable label surface */
|
||||
label:has(> select#reasoning-effort) {
|
||||
position: relative;
|
||||
|
||||
@@ -8,7 +8,6 @@ import { createHashHistory, createBrowserHistory } from "@tanstack/react-router"
|
||||
import "@fontsource-variable/dm-sans/index.css";
|
||||
import "@fontsource/jetbrains-mono/400.css";
|
||||
import "@fontsource/jetbrains-mono/500.css";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "./index.css";
|
||||
|
||||
import { isElectron } from "./env";
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Ghostty web terminal
|
||||
|
||||
This directory is the browser adapter for the same official `libghostty-vt` C ABI used by Android.
|
||||
It is intentionally not an xterm compatibility layer.
|
||||
|
||||
- `runtime.ts` owns the singleton WebAssembly instance and runtime ABI layouts.
|
||||
- `ghostty-write-pty.wasm` is a 112-byte callback trampoline for terminal-generated PTY replies.
|
||||
- `core.ts` owns per-terminal Ghostty handles and translates the C ABI into render snapshots.
|
||||
- `renderer.ts` batches backgrounds and style runs into a Canvas 2D frame.
|
||||
- `surface.ts` owns browser input, IME, selection, scrolling, sizing, links, and cursor blinking.
|
||||
- `fonts/` vendors the symbols-only Nerd Font (MIT) the surface registers lazily, so
|
||||
prompt glyphs render without a locally installed Nerd Font.
|
||||
- `vendor/` holds only the artifacts, reproducibly generated by
|
||||
`apps/web/scripts/build-libghostty-wasm.sh`. The upstream pin and license live once, at
|
||||
`apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/`; the wasm embeds the pinned revision
|
||||
in its build info and the ABI test verifies it against mobile's `VERSION`.
|
||||
|
||||
Keep browser behavior here and terminal transport in the existing client runtime. Do not add React
|
||||
state to the render loop. Both WASM artifacts are ordinary read-only assets, not executables.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Ryan L McIntyre
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Binary file not shown.
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ghosttyKeyForCode, ghosttyUnshiftedCodepoint } from "./keyCodes";
|
||||
|
||||
describe("ghosttyKeyForCode", () => {
|
||||
it("keeps the tail of the pinned Ghostty key enum in order", () => {
|
||||
expect(ghosttyKeyForCode("F25")).toBe(ghosttyKeyForCode("F24") + 1);
|
||||
expect(ghosttyKeyForCode("PrintScreen")).toBe(ghosttyKeyForCode("FnLock") + 1);
|
||||
expect(ghosttyKeyForCode("Pause")).toBe(ghosttyKeyForCode("ScrollLock") + 1);
|
||||
expect(ghosttyKeyForCode("Paste")).toBe(ghosttyKeyForCode("Cut") + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ghosttyUnshiftedCodepoint", () => {
|
||||
it("provides the logical base character for Kitty keyboard encoding", () => {
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "KeyC", key: "c", shiftKey: false })).toBe(
|
||||
"c".codePointAt(0),
|
||||
);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "KeyC", key: "C", shiftKey: true })).toBe(
|
||||
"c".codePointAt(0),
|
||||
);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "Digit1", key: "!", shiftKey: true })).toBe(
|
||||
"1".codePointAt(0),
|
||||
);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "Slash", key: "?", shiftKey: true })).toBe(
|
||||
"/".codePointAt(0),
|
||||
);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "Digit1", key: "&", shiftKey: false })).toBe(
|
||||
"&".codePointAt(0),
|
||||
);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "Enter", key: "Enter", shiftKey: false })).toBe(0);
|
||||
});
|
||||
|
||||
it("reports unknown instead of the shifted character without layout data", () => {
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "Digit7", key: "/", shiftKey: true })).toBe(0);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "KeyD", key: "Д", shiftKey: true })).toBe(
|
||||
"д".codePointAt(0),
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers the active browser layout over US physical key positions", () => {
|
||||
const layoutMap = new Map([
|
||||
["Digit1", "&"],
|
||||
["KeyC", "j"],
|
||||
]);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "Digit1", key: "1", shiftKey: true }, layoutMap)).toBe(
|
||||
"&".codePointAt(0),
|
||||
);
|
||||
expect(ghosttyUnshiftedCodepoint({ code: "KeyC", key: "J", shiftKey: true }, layoutMap)).toBe(
|
||||
"j".codePointAt(0),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
// This order mirrors GhosttyKey in ghostty/vt/key/event.h. The values are
|
||||
// intentionally derived from the official W3C-aligned enum instead of
|
||||
// maintaining a second keyboard protocol.
|
||||
const ghosttyKeyboardCodes = [
|
||||
"Unidentified",
|
||||
"Backquote",
|
||||
"Backslash",
|
||||
"BracketLeft",
|
||||
"BracketRight",
|
||||
"Comma",
|
||||
"Digit0",
|
||||
"Digit1",
|
||||
"Digit2",
|
||||
"Digit3",
|
||||
"Digit4",
|
||||
"Digit5",
|
||||
"Digit6",
|
||||
"Digit7",
|
||||
"Digit8",
|
||||
"Digit9",
|
||||
"Equal",
|
||||
"IntlBackslash",
|
||||
"IntlRo",
|
||||
"IntlYen",
|
||||
"KeyA",
|
||||
"KeyB",
|
||||
"KeyC",
|
||||
"KeyD",
|
||||
"KeyE",
|
||||
"KeyF",
|
||||
"KeyG",
|
||||
"KeyH",
|
||||
"KeyI",
|
||||
"KeyJ",
|
||||
"KeyK",
|
||||
"KeyL",
|
||||
"KeyM",
|
||||
"KeyN",
|
||||
"KeyO",
|
||||
"KeyP",
|
||||
"KeyQ",
|
||||
"KeyR",
|
||||
"KeyS",
|
||||
"KeyT",
|
||||
"KeyU",
|
||||
"KeyV",
|
||||
"KeyW",
|
||||
"KeyX",
|
||||
"KeyY",
|
||||
"KeyZ",
|
||||
"Minus",
|
||||
"Period",
|
||||
"Quote",
|
||||
"Semicolon",
|
||||
"Slash",
|
||||
"AltLeft",
|
||||
"AltRight",
|
||||
"Backspace",
|
||||
"CapsLock",
|
||||
"ContextMenu",
|
||||
"ControlLeft",
|
||||
"ControlRight",
|
||||
"Enter",
|
||||
"MetaLeft",
|
||||
"MetaRight",
|
||||
"ShiftLeft",
|
||||
"ShiftRight",
|
||||
"Space",
|
||||
"Tab",
|
||||
"Convert",
|
||||
"KanaMode",
|
||||
"NonConvert",
|
||||
"Delete",
|
||||
"End",
|
||||
"Help",
|
||||
"Home",
|
||||
"Insert",
|
||||
"PageDown",
|
||||
"PageUp",
|
||||
"ArrowDown",
|
||||
"ArrowLeft",
|
||||
"ArrowRight",
|
||||
"ArrowUp",
|
||||
"NumLock",
|
||||
"Numpad0",
|
||||
"Numpad1",
|
||||
"Numpad2",
|
||||
"Numpad3",
|
||||
"Numpad4",
|
||||
"Numpad5",
|
||||
"Numpad6",
|
||||
"Numpad7",
|
||||
"Numpad8",
|
||||
"Numpad9",
|
||||
"NumpadAdd",
|
||||
"NumpadBackspace",
|
||||
"NumpadClear",
|
||||
"NumpadClearEntry",
|
||||
"NumpadComma",
|
||||
"NumpadDecimal",
|
||||
"NumpadDivide",
|
||||
"NumpadEnter",
|
||||
"NumpadEqual",
|
||||
"NumpadMemoryAdd",
|
||||
"NumpadMemoryClear",
|
||||
"NumpadMemoryRecall",
|
||||
"NumpadMemoryStore",
|
||||
"NumpadMemorySubtract",
|
||||
"NumpadMultiply",
|
||||
"NumpadParenLeft",
|
||||
"NumpadParenRight",
|
||||
"NumpadSubtract",
|
||||
"NumpadSeparator",
|
||||
"NumpadArrowUp",
|
||||
"NumpadArrowDown",
|
||||
"NumpadArrowRight",
|
||||
"NumpadArrowLeft",
|
||||
"NumpadBegin",
|
||||
"NumpadHome",
|
||||
"NumpadEnd",
|
||||
"NumpadInsert",
|
||||
"NumpadDelete",
|
||||
"NumpadPageUp",
|
||||
"NumpadPageDown",
|
||||
"Escape",
|
||||
"F1",
|
||||
"F2",
|
||||
"F3",
|
||||
"F4",
|
||||
"F5",
|
||||
"F6",
|
||||
"F7",
|
||||
"F8",
|
||||
"F9",
|
||||
"F10",
|
||||
"F11",
|
||||
"F12",
|
||||
"F13",
|
||||
"F14",
|
||||
"F15",
|
||||
"F16",
|
||||
"F17",
|
||||
"F18",
|
||||
"F19",
|
||||
"F20",
|
||||
"F21",
|
||||
"F22",
|
||||
"F23",
|
||||
"F24",
|
||||
"F25",
|
||||
"Fn",
|
||||
"FnLock",
|
||||
"PrintScreen",
|
||||
"ScrollLock",
|
||||
"Pause",
|
||||
"BrowserBack",
|
||||
"BrowserFavorites",
|
||||
"BrowserForward",
|
||||
"BrowserHome",
|
||||
"BrowserRefresh",
|
||||
"BrowserSearch",
|
||||
"BrowserStop",
|
||||
"Eject",
|
||||
"LaunchApp1",
|
||||
"LaunchApp2",
|
||||
"LaunchMail",
|
||||
"MediaPlayPause",
|
||||
"MediaSelect",
|
||||
"MediaStop",
|
||||
"MediaTrackNext",
|
||||
"MediaTrackPrevious",
|
||||
"Power",
|
||||
"Sleep",
|
||||
"AudioVolumeDown",
|
||||
"AudioVolumeMute",
|
||||
"AudioVolumeUp",
|
||||
"WakeUp",
|
||||
"Copy",
|
||||
"Cut",
|
||||
"Paste",
|
||||
] as const;
|
||||
|
||||
const codeToGhosttyKey = new Map<string, number>(
|
||||
ghosttyKeyboardCodes.map((code, index) => [code, index]),
|
||||
);
|
||||
|
||||
export function ghosttyKeyForCode(code: string): number {
|
||||
return codeToGhosttyKey.get(code) ?? 0;
|
||||
}
|
||||
|
||||
export interface GhosttyKeyboardLayoutMap {
|
||||
get(code: string): string | undefined;
|
||||
}
|
||||
|
||||
const shiftedToUnshiftedCharacter = new Map<string, string>([
|
||||
["!", "1"],
|
||||
["@", "2"],
|
||||
["#", "3"],
|
||||
["$", "4"],
|
||||
["%", "5"],
|
||||
["^", "6"],
|
||||
["&", "7"],
|
||||
["*", "8"],
|
||||
["(", "9"],
|
||||
[")", "0"],
|
||||
["~", "`"],
|
||||
["_", "-"],
|
||||
["+", "="],
|
||||
["{", "["],
|
||||
["}", "]"],
|
||||
["|", "\\"],
|
||||
[":", ";"],
|
||||
['"', "'"],
|
||||
["<", ","],
|
||||
[">", "."],
|
||||
["?", "/"],
|
||||
]);
|
||||
|
||||
let keyboardLayoutMapPromise: Promise<GhosttyKeyboardLayoutMap | undefined> | undefined;
|
||||
|
||||
export function loadGhosttyKeyboardLayoutMap(): Promise<GhosttyKeyboardLayoutMap | undefined> {
|
||||
if (keyboardLayoutMapPromise) return keyboardLayoutMapPromise;
|
||||
const browserNavigator = globalThis.navigator as
|
||||
| (Navigator & {
|
||||
readonly keyboard?: {
|
||||
getLayoutMap(): Promise<GhosttyKeyboardLayoutMap>;
|
||||
};
|
||||
})
|
||||
| undefined;
|
||||
const keyboard = browserNavigator?.keyboard;
|
||||
const promise = keyboard?.getLayoutMap().catch(() => undefined) ?? Promise.resolve(undefined);
|
||||
keyboardLayoutMapPromise = promise;
|
||||
return promise;
|
||||
}
|
||||
|
||||
export function ghosttyUnshiftedCodepoint(
|
||||
event: Pick<KeyboardEvent, "code" | "key" | "shiftKey">,
|
||||
layoutMap?: GhosttyKeyboardLayoutMap,
|
||||
): number {
|
||||
if ([...event.key].length !== 1) return 0;
|
||||
const layoutCharacter = layoutMap?.get(event.code);
|
||||
if (layoutCharacter && [...layoutCharacter].length === 1) {
|
||||
return layoutCharacter.codePointAt(0) ?? 0;
|
||||
}
|
||||
if (/^[A-Z]$/u.test(event.key)) return event.key.charCodeAt(0) + 32;
|
||||
if (event.shiftKey) {
|
||||
const unshiftedCharacter = shiftedToUnshiftedCharacter.get(event.key);
|
||||
if (unshiftedCharacter) return unshiftedCharacter.codePointAt(0) ?? 0;
|
||||
const lowercase = event.key.toLowerCase();
|
||||
if (lowercase !== event.key && [...lowercase].length === 1) {
|
||||
return lowercase.codePointAt(0) ?? 0;
|
||||
}
|
||||
// Without layout data the unshifted form of a shifted key is unknowable;
|
||||
// reporting the shifted character as unshifted corrupts Kitty alternate keys.
|
||||
return 0;
|
||||
}
|
||||
return event.key.codePointAt(0) ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { GHOSTTY_CELL_WIDE, type GhosttyCell, type GhosttySnapshot } from "./core";
|
||||
import {
|
||||
ghosttyTextRunEnd,
|
||||
measureGhosttyCell,
|
||||
renderGhosttySnapshot,
|
||||
terminalGridSize,
|
||||
} from "./renderer";
|
||||
|
||||
const cell = (text: string, wide = 0): GhosttyCell => ({
|
||||
text,
|
||||
wide,
|
||||
foreground: { r: 255, g: 255, b: 255 },
|
||||
background: { r: 0, g: 0, b: 0 },
|
||||
bold: false,
|
||||
italic: false,
|
||||
invisible: false,
|
||||
strikethrough: false,
|
||||
overline: false,
|
||||
underline: false,
|
||||
selected: false,
|
||||
});
|
||||
|
||||
describe("terminalGridSize", () => {
|
||||
it("matches the mobile renderer's cell-and-padding sizing model", () => {
|
||||
expect(terminalGridSize(808, 408, { width: 10, height: 20, baseline: 15 }, 4)).toEqual({
|
||||
cols: 80,
|
||||
rows: 20,
|
||||
});
|
||||
});
|
||||
|
||||
it("never sends an invalid zero-sized terminal to libghostty", () => {
|
||||
expect(terminalGridSize(0, 0, { width: 10, height: 20, baseline: 15 }, 4)).toEqual({
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("measureGhosttyCell", () => {
|
||||
it("uses descender-aware metrics and the mobile terminal line-height", () => {
|
||||
const measureText = (text: string) =>
|
||||
text === "M"
|
||||
? { width: 7.2, actualBoundingBoxAscent: 9, actualBoundingBoxDescent: 0 }
|
||||
: { width: 14.4, actualBoundingBoxAscent: 9, actualBoundingBoxDescent: 3 };
|
||||
const context = {
|
||||
font: "",
|
||||
measureText,
|
||||
} as unknown as CanvasRenderingContext2D;
|
||||
|
||||
expect(measureGhosttyCell(context, 12, "monospace")).toEqual({
|
||||
width: 7.2,
|
||||
height: 16,
|
||||
baseline: 11,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ghosttyTextRunEnd", () => {
|
||||
it("includes wide spacer tails in the visual clip without rendering spaces", () => {
|
||||
const cells = [
|
||||
cell("界", GHOSTTY_CELL_WIDE.wide),
|
||||
cell("", GHOSTTY_CELL_WIDE.spacerTail),
|
||||
cell("🙂", GHOSTTY_CELL_WIDE.wide),
|
||||
cell("", GHOSTTY_CELL_WIDE.spacerTail),
|
||||
cell(""),
|
||||
];
|
||||
expect(ghosttyTextRunEnd(cells, 0, () => true)).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderGhosttySnapshot", () => {
|
||||
it("constrains text runs and cursor glyphs to their terminal cells", () => {
|
||||
const fillTextCalls: unknown[][] = [];
|
||||
const context = {
|
||||
canvas: { width: 200, height: 40 },
|
||||
beginPath: () => {},
|
||||
clip: () => {},
|
||||
fillRect: () => {},
|
||||
fillText: (...args: unknown[]) => fillTextCalls.push(args),
|
||||
rect: () => {},
|
||||
resetTransform: () => {},
|
||||
restore: () => {},
|
||||
save: () => {},
|
||||
set fillStyle(_value: string) {},
|
||||
set font(_value: string) {},
|
||||
set textBaseline(_value: string) {},
|
||||
} as unknown as CanvasRenderingContext2D;
|
||||
const cells = [cell("a"), cell("b"), cell("x")];
|
||||
const snapshot: GhosttySnapshot = {
|
||||
cols: 3,
|
||||
rows: 1,
|
||||
foreground: { r: 255, g: 255, b: 255 },
|
||||
background: { r: 0, g: 0, b: 0 },
|
||||
cursor: { r: 255, g: 255, b: 255 },
|
||||
cursorX: 2,
|
||||
cursorY: 0,
|
||||
cursorVisible: true,
|
||||
cursorBlinking: false,
|
||||
cursorStyle: 1,
|
||||
dirtyRows: new Set([0]),
|
||||
rowData: [{ cells, text: "abx", isWrapContinuation: false, wrapsToNext: false }],
|
||||
};
|
||||
|
||||
renderGhosttySnapshot({
|
||||
context,
|
||||
snapshot,
|
||||
metrics: { width: 7.2, height: 16, baseline: 11 },
|
||||
fontSize: 12,
|
||||
fontFamily: "monospace",
|
||||
padding: 4,
|
||||
forceFull: false,
|
||||
cursorOn: true,
|
||||
});
|
||||
|
||||
expect(fillTextCalls).toEqual([
|
||||
["abx", 4, 15, 21.6],
|
||||
["x", 18.4, 15, 7.2],
|
||||
]);
|
||||
});
|
||||
|
||||
it("repaints the previous cursor row after the cursor moves", () => {
|
||||
const clearedRows: number[] = [];
|
||||
const context = {
|
||||
canvas: { width: 200, height: 80 },
|
||||
beginPath: () => {},
|
||||
clip: () => {},
|
||||
fillRect: (_left: number, top: number, _width: number, height: number) => {
|
||||
if (height === 16) clearedRows.push(top);
|
||||
},
|
||||
fillText: () => {},
|
||||
rect: () => {},
|
||||
resetTransform: () => {},
|
||||
restore: () => {},
|
||||
save: () => {},
|
||||
set fillStyle(_value: string) {},
|
||||
set font(_value: string) {},
|
||||
set textBaseline(_value: string) {},
|
||||
} as unknown as CanvasRenderingContext2D;
|
||||
const snapshot: GhosttySnapshot = {
|
||||
cols: 1,
|
||||
rows: 3,
|
||||
foreground: { r: 255, g: 255, b: 255 },
|
||||
background: { r: 0, g: 0, b: 0 },
|
||||
cursor: { r: 255, g: 255, b: 255 },
|
||||
cursorX: 0,
|
||||
cursorY: 2,
|
||||
cursorVisible: true,
|
||||
cursorBlinking: false,
|
||||
cursorStyle: 1,
|
||||
dirtyRows: new Set(),
|
||||
rowData: [0, 1, 2].map(() => ({
|
||||
cells: [cell("")],
|
||||
text: "",
|
||||
isWrapContinuation: false,
|
||||
wrapsToNext: false,
|
||||
})),
|
||||
};
|
||||
|
||||
renderGhosttySnapshot({
|
||||
context,
|
||||
snapshot,
|
||||
metrics: { width: 7.2, height: 16, baseline: 11 },
|
||||
fontSize: 12,
|
||||
fontFamily: "monospace",
|
||||
padding: 4,
|
||||
forceFull: false,
|
||||
cursorOn: true,
|
||||
previousCursorY: 0,
|
||||
});
|
||||
|
||||
expect(clearedRows).toEqual([4, 36, 36]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
import {
|
||||
GHOSTTY_CELL_WIDE,
|
||||
ghosttyColorsEqual,
|
||||
type GhosttyCell,
|
||||
type GhosttyColor,
|
||||
type GhosttySnapshot,
|
||||
} from "./core";
|
||||
|
||||
export interface GhosttyCellMetrics {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly baseline: number;
|
||||
}
|
||||
|
||||
const DEFAULT_SELECTION_BACKGROUND = "rgba(72, 122, 191, 0.35)";
|
||||
|
||||
function cssColor(color: GhosttyColor): string {
|
||||
return `rgb(${color.r}, ${color.g}, ${color.b})`;
|
||||
}
|
||||
|
||||
function sameTextStyle(left: GhosttyCell, right: GhosttyCell): boolean {
|
||||
// Selection deliberately does not participate: it only tints the background
|
||||
// overlay, and splitting a text run at a selection boundary visibly shifts
|
||||
// glyph spacing whenever the face's true advance differs from the cell width.
|
||||
return (
|
||||
ghosttyColorsEqual(left.foreground, right.foreground) &&
|
||||
left.bold === right.bold &&
|
||||
left.italic === right.italic &&
|
||||
left.invisible === right.invisible
|
||||
);
|
||||
}
|
||||
|
||||
export function ghosttyTextRunEnd(
|
||||
cells: readonly GhosttyCell[],
|
||||
start: number,
|
||||
sameStyle: (cell: GhosttyCell) => boolean,
|
||||
): number {
|
||||
let end = start + 1;
|
||||
while (end < cells.length) {
|
||||
const next = cells[end];
|
||||
if (!next) break;
|
||||
if (next.wide === GHOSTTY_CELL_WIDE.spacerTail) {
|
||||
end += 1;
|
||||
continue;
|
||||
}
|
||||
if (next.text.length === 0 || !sameStyle(next)) break;
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
function fontForCell(cell: GhosttyCell, fontSize: number, fontFamily: string): string {
|
||||
const style = cell.italic ? "italic" : "normal";
|
||||
const weight = cell.bold ? "700" : "400";
|
||||
return `${style} ${weight} ${fontSize}px ${fontFamily}`;
|
||||
}
|
||||
|
||||
export function measureGhosttyCell(
|
||||
context: CanvasRenderingContext2D,
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
): GhosttyCellMetrics {
|
||||
context.font = `normal 400 ${fontSize}px ${fontFamily}`;
|
||||
const widthMeasurement = context.measureText("M");
|
||||
const verticalMeasurement = context.measureText("Mg");
|
||||
const ascent = verticalMeasurement.actualBoundingBoxAscent || fontSize;
|
||||
const descent = verticalMeasurement.actualBoundingBoxDescent;
|
||||
const glyphHeight = ascent + descent;
|
||||
const height = Math.max(1, Math.round(fontSize * 1.35), Math.ceil(glyphHeight));
|
||||
return {
|
||||
width: Math.max(1, widthMeasurement.width),
|
||||
height,
|
||||
baseline: Math.round((height - glyphHeight) / 2 + ascent),
|
||||
};
|
||||
}
|
||||
|
||||
export function terminalGridSize(
|
||||
width: number,
|
||||
height: number,
|
||||
metrics: GhosttyCellMetrics,
|
||||
padding: number,
|
||||
): { cols: number; rows: number } {
|
||||
return {
|
||||
cols: Math.max(1, Math.floor((width - padding * 2) / metrics.width)),
|
||||
rows: Math.max(1, Math.floor((height - padding * 2) / metrics.height)),
|
||||
};
|
||||
}
|
||||
|
||||
export function renderGhosttySnapshot(options: {
|
||||
readonly context: CanvasRenderingContext2D;
|
||||
readonly snapshot: GhosttySnapshot;
|
||||
readonly metrics: GhosttyCellMetrics;
|
||||
readonly fontSize: number;
|
||||
readonly fontFamily: string;
|
||||
readonly padding: number;
|
||||
readonly forceFull: boolean;
|
||||
readonly cursorOn: boolean;
|
||||
readonly previousCursorY?: number | null;
|
||||
readonly focused?: boolean;
|
||||
readonly selectionBackground?: string;
|
||||
/** Vertical origin of row 0; defaults to the horizontal padding. */
|
||||
readonly originY?: number;
|
||||
}): void {
|
||||
const {
|
||||
context,
|
||||
snapshot,
|
||||
metrics,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
padding,
|
||||
forceFull,
|
||||
cursorOn,
|
||||
previousCursorY,
|
||||
} = options;
|
||||
const focused = options.focused ?? true;
|
||||
const selectionBackground = options.selectionBackground ?? DEFAULT_SELECTION_BACKGROUND;
|
||||
const originY = options.originY ?? padding;
|
||||
const rowsToDraw = forceFull
|
||||
? Array.from({ length: snapshot.rows }, (_, index) => index)
|
||||
: [...snapshot.dirtyRows];
|
||||
if (
|
||||
previousCursorY !== null &&
|
||||
previousCursorY !== undefined &&
|
||||
previousCursorY >= 0 &&
|
||||
!rowsToDraw.includes(previousCursorY)
|
||||
) {
|
||||
rowsToDraw.push(previousCursorY);
|
||||
}
|
||||
if (snapshot.cursorVisible && snapshot.cursorY >= 0 && !rowsToDraw.includes(snapshot.cursorY)) {
|
||||
rowsToDraw.push(snapshot.cursorY);
|
||||
}
|
||||
|
||||
if (forceFull) {
|
||||
context.save();
|
||||
context.resetTransform();
|
||||
context.fillStyle = cssColor(snapshot.background);
|
||||
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
|
||||
context.restore();
|
||||
}
|
||||
|
||||
context.textBaseline = "alphabetic";
|
||||
for (const rowIndex of rowsToDraw) {
|
||||
const row = snapshot.rowData[rowIndex];
|
||||
if (!row) continue;
|
||||
const top = originY + rowIndex * metrics.height;
|
||||
|
||||
context.fillStyle = cssColor(snapshot.background);
|
||||
context.fillRect(padding, top, snapshot.cols * metrics.width, metrics.height);
|
||||
|
||||
let backgroundStart = 0;
|
||||
while (backgroundStart < row.cells.length) {
|
||||
const first = row.cells[backgroundStart];
|
||||
if (!first) break;
|
||||
let backgroundEnd = backgroundStart + 1;
|
||||
while (backgroundEnd < row.cells.length) {
|
||||
const next = row.cells[backgroundEnd];
|
||||
if (
|
||||
!next ||
|
||||
next.selected !== first.selected ||
|
||||
!ghosttyColorsEqual(next.background, first.background)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
backgroundEnd += 1;
|
||||
}
|
||||
if (first.selected || !ghosttyColorsEqual(first.background, snapshot.background)) {
|
||||
const left = padding + backgroundStart * metrics.width;
|
||||
const width = (backgroundEnd - backgroundStart) * metrics.width;
|
||||
if (!ghosttyColorsEqual(first.background, snapshot.background)) {
|
||||
context.fillStyle = cssColor(first.background);
|
||||
context.fillRect(left, top, width, metrics.height);
|
||||
}
|
||||
if (first.selected) {
|
||||
context.fillStyle = selectionBackground;
|
||||
context.fillRect(left, top, width, metrics.height);
|
||||
}
|
||||
}
|
||||
backgroundStart = backgroundEnd;
|
||||
}
|
||||
|
||||
let runStart = 0;
|
||||
while (runStart < row.cells.length) {
|
||||
const first = row.cells[runStart];
|
||||
if (!first) break;
|
||||
if (first.text.length === 0) {
|
||||
runStart += 1;
|
||||
continue;
|
||||
}
|
||||
const runEnd = ghosttyTextRunEnd(row.cells, runStart, (cell) => sameTextStyle(cell, first));
|
||||
const text = row.cells
|
||||
.slice(runStart, runEnd)
|
||||
.map((cell) => cell.text)
|
||||
.join("");
|
||||
if (!first.invisible && text.trim().length > 0) {
|
||||
context.save();
|
||||
context.beginPath();
|
||||
context.rect(
|
||||
padding + runStart * metrics.width,
|
||||
top,
|
||||
(runEnd - runStart) * metrics.width,
|
||||
metrics.height,
|
||||
);
|
||||
context.clip();
|
||||
context.font = fontForCell(first, fontSize, fontFamily);
|
||||
context.fillStyle = cssColor(first.foreground);
|
||||
context.fillText(
|
||||
text,
|
||||
padding + runStart * metrics.width,
|
||||
top + metrics.baseline,
|
||||
(runEnd - runStart) * metrics.width,
|
||||
);
|
||||
context.restore();
|
||||
}
|
||||
runStart = runEnd;
|
||||
}
|
||||
|
||||
for (let column = 0; column < row.cells.length; column += 1) {
|
||||
const cell = row.cells[column];
|
||||
if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline)) continue;
|
||||
context.fillStyle = cssColor(cell.foreground);
|
||||
const left = padding + column * metrics.width;
|
||||
if (cell.underline) context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
|
||||
if (cell.strikethrough) {
|
||||
context.fillRect(left, top + Math.floor(metrics.height * 0.55), metrics.width, 1);
|
||||
}
|
||||
if (cell.overline) context.fillRect(left, top + 1, metrics.width, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (cursorOn && snapshot.cursorVisible && snapshot.cursorX >= 0 && snapshot.cursorY >= 0) {
|
||||
const left = padding + snapshot.cursorX * metrics.width;
|
||||
const top = originY + snapshot.cursorY * metrics.height;
|
||||
context.fillStyle = cssColor(snapshot.cursor);
|
||||
if (!focused) {
|
||||
// An unfocused terminal draws a hollow cursor so the active pane is obvious.
|
||||
context.strokeStyle = cssColor(snapshot.cursor);
|
||||
context.strokeRect(left + 0.5, top + 0.5, metrics.width - 1, metrics.height - 1);
|
||||
} else if (snapshot.cursorStyle === 0) {
|
||||
context.fillRect(left, top, 2, metrics.height);
|
||||
} else if (snapshot.cursorStyle === 2) {
|
||||
context.fillRect(left, top + metrics.height - 2, metrics.width, 2);
|
||||
} else if (snapshot.cursorStyle === 3) {
|
||||
context.strokeStyle = cssColor(snapshot.cursor);
|
||||
context.strokeRect(left + 0.5, top + 0.5, metrics.width - 1, metrics.height - 1);
|
||||
} else {
|
||||
context.fillRect(left, top, metrics.width, metrics.height);
|
||||
const cell = snapshot.rowData[snapshot.cursorY]?.cells[snapshot.cursorX];
|
||||
if (cell?.text) {
|
||||
context.font = fontForCell(cell, fontSize, fontFamily);
|
||||
context.fillStyle = cssColor(snapshot.background);
|
||||
context.fillText(cell.text, left, top + metrics.baseline, metrics.width);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import ghosttyWasmUrl from "./vendor/ghostty-vt.wasm?url";
|
||||
import ghosttyWritePtyWasmUrl from "./vendor/ghostty-write-pty.wasm?url&no-inline";
|
||||
|
||||
type WasmFunction = (...args: Array<number | bigint>) => number;
|
||||
|
||||
interface TypeField {
|
||||
readonly offset: number;
|
||||
readonly size: number;
|
||||
readonly type: string;
|
||||
}
|
||||
|
||||
interface TypeLayout {
|
||||
readonly size: number;
|
||||
readonly align: number;
|
||||
readonly fields: Readonly<Record<string, TypeField>>;
|
||||
}
|
||||
|
||||
type TypeLayouts = Readonly<Record<string, TypeLayout>>;
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
export class GhosttyRuntime {
|
||||
readonly memory: WebAssembly.Memory;
|
||||
readonly layouts: TypeLayouts;
|
||||
private readonly exports: WebAssembly.Exports;
|
||||
private readonly ptyWriters = new Map<number, (data: string) => void>();
|
||||
private nextPtyWriterId = 1;
|
||||
private writePtyFunctionIndex = 0;
|
||||
|
||||
private constructor(instance: WebAssembly.Instance) {
|
||||
this.exports = instance.exports;
|
||||
const memory = instance.exports.memory;
|
||||
if (!(memory instanceof WebAssembly.Memory)) {
|
||||
throw new Error("libghostty-vt did not export WebAssembly memory");
|
||||
}
|
||||
this.memory = memory;
|
||||
const jsonPointer = this.call("ghostty_type_json");
|
||||
const bytes = new Uint8Array(memory.buffer);
|
||||
let end = jsonPointer;
|
||||
while (end < bytes.length && bytes[end] !== 0) end += 1;
|
||||
this.layouts = JSON.parse(textDecoder.decode(bytes.subarray(jsonPointer, end))) as TypeLayouts;
|
||||
}
|
||||
|
||||
static async load(): Promise<GhosttyRuntime> {
|
||||
const response = await fetch(ghosttyWasmUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unable to load libghostty-vt (${response.status})`);
|
||||
}
|
||||
let instance: WebAssembly.Instance | undefined;
|
||||
const imports = {
|
||||
env: {
|
||||
log: (pointer: number, length: number) => {
|
||||
if (!instance) return;
|
||||
const memory = instance.exports.memory;
|
||||
if (!(memory instanceof WebAssembly.Memory)) return;
|
||||
const message = textDecoder.decode(new Uint8Array(memory.buffer, pointer, length));
|
||||
console.debug("[libghostty-vt]", message);
|
||||
},
|
||||
},
|
||||
};
|
||||
const result = await WebAssembly.instantiate(await response.arrayBuffer(), imports);
|
||||
instance = result.instance;
|
||||
const runtime = new GhosttyRuntime(result.instance);
|
||||
await runtime.installWritePtyTrampoline();
|
||||
return runtime;
|
||||
}
|
||||
|
||||
call(name: string, ...args: Array<number | bigint>): number {
|
||||
const fn = this.exports[name];
|
||||
if (typeof fn !== "function") {
|
||||
throw new Error(`libghostty-vt export is unavailable: ${name}`);
|
||||
}
|
||||
return (fn as WasmFunction)(...args);
|
||||
}
|
||||
|
||||
layout(name: string): TypeLayout {
|
||||
const layout = this.layouts[name];
|
||||
if (!layout) throw new Error(`libghostty-vt type layout is unavailable: ${name}`);
|
||||
return layout;
|
||||
}
|
||||
|
||||
alloc(size: number): number {
|
||||
const pointer = this.call("ghostty_wasm_alloc_u8_array", size);
|
||||
if (pointer === 0) throw new Error(`libghostty-vt failed to allocate ${size} bytes`);
|
||||
new Uint8Array(this.memory.buffer, pointer, size).fill(0);
|
||||
return pointer;
|
||||
}
|
||||
|
||||
free(pointer: number, size: number): void {
|
||||
if (pointer !== 0) this.call("ghostty_wasm_free_u8_array", pointer, size);
|
||||
}
|
||||
|
||||
allocOpaque(): number {
|
||||
const pointer = this.call("ghostty_wasm_alloc_opaque");
|
||||
if (pointer === 0) throw new Error("libghostty-vt failed to allocate an opaque pointer");
|
||||
// The slot is uninitialized until a *_new call writes it; zero it so dispose
|
||||
// paths that run after a partial initialization never free a garbage pointer.
|
||||
new DataView(this.memory.buffer).setUint32(pointer, 0, true);
|
||||
return pointer;
|
||||
}
|
||||
|
||||
freeOpaque(pointer: number): void {
|
||||
if (pointer !== 0) this.call("ghostty_wasm_free_opaque", pointer);
|
||||
}
|
||||
|
||||
readPointer(slot: number): number {
|
||||
return new DataView(this.memory.buffer).getUint32(slot, true);
|
||||
}
|
||||
|
||||
attachPtyWriter(terminal: number, writer: (data: string) => void): number {
|
||||
if (this.writePtyFunctionIndex === 0) {
|
||||
throw new Error("libghostty-vt PTY callback trampoline is unavailable");
|
||||
}
|
||||
const id = this.nextPtyWriterId++;
|
||||
this.ptyWriters.set(id, writer);
|
||||
this.call("ghostty_terminal_set", terminal, 0, id);
|
||||
this.call("ghostty_terminal_set", terminal, 1, this.writePtyFunctionIndex);
|
||||
return id;
|
||||
}
|
||||
|
||||
detachPtyWriter(terminal: number, id: number): void {
|
||||
this.call("ghostty_terminal_set", terminal, 1, 0);
|
||||
this.call("ghostty_terminal_set", terminal, 0, 0);
|
||||
this.ptyWriters.delete(id);
|
||||
}
|
||||
|
||||
view(pointer: number, size?: number): DataView {
|
||||
return new DataView(this.memory.buffer, pointer, size);
|
||||
}
|
||||
|
||||
bytes(pointer: number, size: number): Uint8Array {
|
||||
return new Uint8Array(this.memory.buffer, pointer, size);
|
||||
}
|
||||
|
||||
setField(pointer: number, structName: string, fieldName: string, value: number): void {
|
||||
const field = this.layout(structName).fields[fieldName];
|
||||
if (!field) throw new Error(`libghostty-vt field is unavailable: ${structName}.${fieldName}`);
|
||||
const view = this.view(pointer + field.offset, field.size);
|
||||
switch (field.type) {
|
||||
case "bool":
|
||||
case "u8":
|
||||
view.setUint8(0, value);
|
||||
return;
|
||||
case "u16":
|
||||
view.setUint16(0, value, true);
|
||||
return;
|
||||
case "i32":
|
||||
view.setInt32(0, value, true);
|
||||
return;
|
||||
case "u32":
|
||||
case "enum":
|
||||
view.setUint32(0, value, true);
|
||||
return;
|
||||
case "u64":
|
||||
view.setBigUint64(0, BigInt(value), true);
|
||||
return;
|
||||
default:
|
||||
throw new Error(`Unsupported libghostty-vt field type: ${field.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
readField(pointer: number, structName: string, fieldName: string): number {
|
||||
const field = this.layout(structName).fields[fieldName];
|
||||
if (!field) throw new Error(`libghostty-vt field is unavailable: ${structName}.${fieldName}`);
|
||||
const view = this.view(pointer + field.offset, field.size);
|
||||
switch (field.type) {
|
||||
case "bool":
|
||||
case "u8":
|
||||
return view.getUint8(0);
|
||||
case "u16":
|
||||
return view.getUint16(0, true);
|
||||
case "i32":
|
||||
return view.getInt32(0, true);
|
||||
case "u32":
|
||||
case "enum":
|
||||
return view.getUint32(0, true);
|
||||
case "u64":
|
||||
return Number(view.getBigUint64(0, true));
|
||||
default:
|
||||
throw new Error(`Unsupported libghostty-vt field type: ${field.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async installWritePtyTrampoline(): Promise<void> {
|
||||
const response = await fetch(ghosttyWritePtyWasmUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unable to load the libghostty-vt PTY trampoline (${response.status})`);
|
||||
}
|
||||
const result = await WebAssembly.instantiate(await response.arrayBuffer(), {
|
||||
env: {
|
||||
t3_write_pty: (_terminal: number, userdata: number, pointer: number, length: number) => {
|
||||
const writer = this.ptyWriters.get(userdata);
|
||||
if (!writer || length === 0) return;
|
||||
writer(textDecoder.decode(new Uint8Array(this.memory.buffer, pointer, length)));
|
||||
},
|
||||
},
|
||||
});
|
||||
const trampoline = result.instance.exports.ghostty_write_pty;
|
||||
const table = this.exports.__indirect_function_table;
|
||||
if (typeof trampoline !== "function" || !(table instanceof WebAssembly.Table)) {
|
||||
throw new Error("libghostty-vt did not expose its callback table");
|
||||
}
|
||||
const index = table.length;
|
||||
// grow-then-set instead of grow(1, fn): WebKit stores a grow init value
|
||||
// with broken type information and every later call_indirect through the
|
||||
// entry traps with a signature mismatch. table.set canonicalizes correctly.
|
||||
table.grow(1);
|
||||
table.set(index, trampoline);
|
||||
this.writePtyFunctionIndex = index;
|
||||
}
|
||||
}
|
||||
|
||||
let runtimePromise: Promise<GhosttyRuntime> | null = null;
|
||||
|
||||
export function loadGhosttyRuntime(): Promise<GhosttyRuntime> {
|
||||
runtimePromise ??= GhosttyRuntime.load().catch((error) => {
|
||||
runtimePromise = null;
|
||||
throw error;
|
||||
});
|
||||
return runtimePromise;
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import wasmDataUrl from "./vendor/ghostty-vt.wasm?inline";
|
||||
import writePtyWasmDataUrl from "./vendor/ghostty-write-pty.wasm?inline";
|
||||
import mobileVersion from "../../../../mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION?raw";
|
||||
import { ghosttyKeyForCode } from "./keyCodes";
|
||||
|
||||
type WasmFunction = (...args: number[]) => number;
|
||||
|
||||
function decodeWasmDataUrl(dataUrl: string): Uint8Array {
|
||||
const encoded = dataUrl.split(",", 2)[1];
|
||||
if (!encoded) throw new Error("The vendored Ghostty WASM data URL is invalid");
|
||||
return Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
|
||||
}
|
||||
|
||||
describe("vendored libghostty-vt WebAssembly", () => {
|
||||
it("stays pinned to mobile's canonical revision and size budget", async () => {
|
||||
const wasm = decodeWasmDataUrl(wasmDataUrl);
|
||||
expect(wasm.byteLength).toBeLessThan(750_000);
|
||||
|
||||
// The artifact carries its own provenance: the build embeds the pinned
|
||||
// revision as semver build metadata, so mobile's VERSION file is the
|
||||
// single source of truth and drift is caught here without a copy.
|
||||
const result = await WebAssembly.instantiate(wasm.buffer as ArrayBuffer, {
|
||||
env: { log: () => {} },
|
||||
});
|
||||
const instance = result instanceof WebAssembly.Instance ? result : result.instance;
|
||||
const memory = instance.exports.memory as WebAssembly.Memory;
|
||||
const call = (name: string, ...args: number[]) =>
|
||||
(instance.exports[name] as WasmFunction)(...args);
|
||||
const out = call("ghostty_wasm_alloc_u8_array", 8);
|
||||
expect(call("ghostty_build_info", 10, out)).toBe(0);
|
||||
const view = new DataView(memory.buffer, out, 8);
|
||||
const embeddedRevision = new TextDecoder().decode(
|
||||
new Uint8Array(memory.buffer, view.getUint32(0, true), view.getUint32(4, true)),
|
||||
);
|
||||
call("ghostty_wasm_free_u8_array", out, 8);
|
||||
expect(embeddedRevision).toBe(mobileVersion.trim());
|
||||
});
|
||||
|
||||
it("creates, writes multi-codepoint graphemes, and frees repeated terminals", async () => {
|
||||
const bytes = decodeWasmDataUrl(wasmDataUrl);
|
||||
let memory: WebAssembly.Memory | null = null;
|
||||
const instantiated = await WebAssembly.instantiate(bytes.buffer as ArrayBuffer, {
|
||||
env: {
|
||||
log: () => {},
|
||||
},
|
||||
});
|
||||
const instance =
|
||||
instantiated instanceof WebAssembly.Instance ? instantiated : instantiated.instance;
|
||||
const exports = instance.exports;
|
||||
memory = exports.memory as WebAssembly.Memory;
|
||||
const call = (name: string, ...args: number[]) => (exports[name] as WasmFunction)(...args);
|
||||
const jsonPointer = call("ghostty_type_json");
|
||||
const jsonBytes = new Uint8Array(memory.buffer, jsonPointer);
|
||||
const jsonEnd = jsonBytes.indexOf(0);
|
||||
const layouts = JSON.parse(new TextDecoder().decode(jsonBytes.subarray(0, jsonEnd))) as Record<
|
||||
string,
|
||||
{ size: number }
|
||||
>;
|
||||
const optionsSize = layouts.GhosttyTerminalOptions?.size;
|
||||
expect(optionsSize).toBe(8);
|
||||
if (optionsSize === undefined) throw new Error("GhosttyTerminalOptions layout is missing");
|
||||
|
||||
for (let iteration = 0; iteration < 25; iteration += 1) {
|
||||
const options = call("ghostty_wasm_alloc_u8_array", optionsSize);
|
||||
const optionsView = new DataView(memory.buffer, options, optionsSize);
|
||||
optionsView.setUint16(0, 80, true);
|
||||
optionsView.setUint16(2, 24, true);
|
||||
optionsView.setUint32(4, 5_000, true);
|
||||
const terminalSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_terminal_new", 0, terminalSlot, options)).toBe(0);
|
||||
const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
|
||||
|
||||
const input = new TextEncoder().encode("e\u0301 👨👩👧👦 العربية\r\n");
|
||||
const inputPointer = call("ghostty_wasm_alloc_u8_array", input.length);
|
||||
new Uint8Array(memory.buffer, inputPointer, input.length).set(input);
|
||||
call("ghostty_terminal_vt_write", terminal, inputPointer, input.length);
|
||||
call("ghostty_wasm_free_u8_array", inputPointer, input.length);
|
||||
call("ghostty_terminal_free", terminal);
|
||||
call("ghostty_wasm_free_opaque", terminalSlot);
|
||||
call("ghostty_wasm_free_u8_array", options, optionsSize);
|
||||
}
|
||||
});
|
||||
|
||||
it("reports and scrolls the viewport with Ghostty's scrollbar state", async () => {
|
||||
const result = await WebAssembly.instantiate(
|
||||
decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
|
||||
{ env: { log: () => {} } },
|
||||
);
|
||||
const instance = result instanceof WebAssembly.Instance ? result : result.instance;
|
||||
const memory = instance.exports.memory as WebAssembly.Memory;
|
||||
const call = (name: string, ...args: number[]) =>
|
||||
(instance.exports[name] as WasmFunction)(...args);
|
||||
const alloc = (size: number) => call("ghostty_wasm_alloc_u8_array", size);
|
||||
const options = alloc(8);
|
||||
const optionsView = new DataView(memory.buffer, options, 8);
|
||||
optionsView.setUint16(0, 80, true);
|
||||
optionsView.setUint16(2, 10, true);
|
||||
optionsView.setUint32(4, 1_000, true);
|
||||
const terminalSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_terminal_new", 0, terminalSlot, options)).toBe(0);
|
||||
const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
|
||||
const input = new TextEncoder().encode(
|
||||
Array.from({ length: 50 }, (_, index) => `${index + 1}\r\n`).join(""),
|
||||
);
|
||||
const inputPointer = alloc(input.length);
|
||||
new Uint8Array(memory.buffer, inputPointer, input.length).set(input);
|
||||
call("ghostty_terminal_vt_write", terminal, inputPointer, input.length);
|
||||
|
||||
const scrollbar = alloc(24);
|
||||
const scrollbarView = new DataView(memory.buffer, scrollbar, 24);
|
||||
expect(call("ghostty_terminal_get", terminal, 9, scrollbar)).toBe(0);
|
||||
expect([0, 8, 16].map((offset) => Number(scrollbarView.getBigUint64(offset, true)))).toEqual([
|
||||
51, 41, 10,
|
||||
]);
|
||||
|
||||
const scroll = alloc(24);
|
||||
const scrollView = new DataView(memory.buffer, scroll, 24);
|
||||
scrollView.setUint32(0, 2, true);
|
||||
scrollView.setInt32(8, -5, true);
|
||||
call("ghostty_terminal_scroll_viewport", terminal, scroll);
|
||||
expect(call("ghostty_terminal_get", terminal, 9, scrollbar)).toBe(0);
|
||||
expect(Number(scrollbarView.getBigUint64(8, true))).toBe(36);
|
||||
|
||||
call("ghostty_wasm_free_u8_array", scroll, 24);
|
||||
call("ghostty_wasm_free_u8_array", scrollbar, 24);
|
||||
call("ghostty_wasm_free_u8_array", inputPointer, input.length);
|
||||
call("ghostty_terminal_free", terminal);
|
||||
call("ghostty_wasm_free_opaque", terminalSlot);
|
||||
call("ghostty_wasm_free_u8_array", options, 8);
|
||||
});
|
||||
|
||||
it("routes terminal-generated replies through the shared callback table", async () => {
|
||||
const mainResult = await WebAssembly.instantiate(
|
||||
decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
|
||||
{ env: { log: () => {} } },
|
||||
);
|
||||
const main = mainResult instanceof WebAssembly.Instance ? mainResult : mainResult.instance;
|
||||
const memory = main.exports.memory as WebAssembly.Memory;
|
||||
let reply = "";
|
||||
const trampolineResult = await WebAssembly.instantiate(
|
||||
decodeWasmDataUrl(writePtyWasmDataUrl).buffer as ArrayBuffer,
|
||||
{
|
||||
env: {
|
||||
t3_write_pty: (_terminal: number, _userdata: number, pointer: number, length: number) => {
|
||||
reply += new TextDecoder().decode(new Uint8Array(memory.buffer, pointer, length));
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
const trampoline =
|
||||
trampolineResult instanceof WebAssembly.Instance
|
||||
? trampolineResult
|
||||
: trampolineResult.instance;
|
||||
const table = main.exports.__indirect_function_table as WebAssembly.Table;
|
||||
const callbackIndex = table.length;
|
||||
table.grow(1, trampoline.exports.ghostty_write_pty as CallableFunction);
|
||||
const call = (name: string, ...args: number[]) => (main.exports[name] as WasmFunction)(...args);
|
||||
const options = call("ghostty_wasm_alloc_u8_array", 8);
|
||||
const optionsView = new DataView(memory.buffer, options, 8);
|
||||
optionsView.setUint16(0, 80, true);
|
||||
optionsView.setUint16(2, 24, true);
|
||||
const terminalSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_terminal_new", 0, terminalSlot, options)).toBe(0);
|
||||
const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
|
||||
call("ghostty_terminal_set", terminal, 0, 1);
|
||||
call("ghostty_terminal_set", terminal, 1, callbackIndex);
|
||||
const query = new TextEncoder().encode("\u001b[5n");
|
||||
const queryPointer = call("ghostty_wasm_alloc_u8_array", query.length);
|
||||
new Uint8Array(memory.buffer, queryPointer, query.length).set(query);
|
||||
call("ghostty_terminal_vt_write", terminal, queryPointer, query.length);
|
||||
|
||||
expect(reply).toBe("\u001b[0n");
|
||||
reply = "";
|
||||
call("ghostty_terminal_set", terminal, 1, 0);
|
||||
call("ghostty_terminal_set", terminal, 0, 0);
|
||||
call("ghostty_terminal_vt_write", terminal, queryPointer, query.length);
|
||||
expect(reply).toBe("");
|
||||
call("ghostty_terminal_set", terminal, 0, 1);
|
||||
call("ghostty_terminal_set", terminal, 1, callbackIndex);
|
||||
call("ghostty_terminal_vt_write", terminal, queryPointer, query.length);
|
||||
expect(reply).toBe("\u001b[0n");
|
||||
call("ghostty_wasm_free_u8_array", queryPointer, query.length);
|
||||
call("ghostty_terminal_free", terminal);
|
||||
call("ghostty_wasm_free_opaque", terminalSlot);
|
||||
call("ghostty_wasm_free_u8_array", options, 8);
|
||||
});
|
||||
|
||||
it("formats the active selection with Ghostty's copy semantics", async () => {
|
||||
const result = await WebAssembly.instantiate(
|
||||
decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
|
||||
{ env: { log: () => {} } },
|
||||
);
|
||||
const instance = result instanceof WebAssembly.Instance ? result : result.instance;
|
||||
const memory = instance.exports.memory as WebAssembly.Memory;
|
||||
const call = (name: string, ...args: number[]) =>
|
||||
(instance.exports[name] as WasmFunction)(...args);
|
||||
const options = call("ghostty_wasm_alloc_u8_array", 8);
|
||||
const optionsView = new DataView(memory.buffer, options, 8);
|
||||
optionsView.setUint16(0, 80, true);
|
||||
optionsView.setUint16(2, 24, true);
|
||||
const terminalSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_terminal_new", 0, terminalSlot, options)).toBe(0);
|
||||
const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
|
||||
const input = new TextEncoder().encode("a\r\n\r\nb");
|
||||
const inputPointer = call("ghostty_wasm_alloc_u8_array", input.length);
|
||||
new Uint8Array(memory.buffer, inputPointer, input.length).set(input);
|
||||
call("ghostty_terminal_vt_write", terminal, inputPointer, input.length);
|
||||
|
||||
const selection = call("ghostty_wasm_alloc_u8_array", 32);
|
||||
new DataView(memory.buffer, selection, 32).setUint32(0, 32, true);
|
||||
expect(call("ghostty_terminal_select_all", terminal, selection)).toBe(0);
|
||||
expect(call("ghostty_terminal_set", terminal, 21, selection)).toBe(0);
|
||||
const formatOptions = call("ghostty_wasm_alloc_u8_array", 16);
|
||||
const formatView = new DataView(memory.buffer, formatOptions, 16);
|
||||
formatView.setUint32(0, 16, true);
|
||||
formatView.setUint8(8, 1);
|
||||
formatView.setUint8(9, 1);
|
||||
const written = call("ghostty_wasm_alloc_usize");
|
||||
expect(
|
||||
call("ghostty_terminal_selection_format_buf", terminal, formatOptions, 0, 0, written),
|
||||
).toBe(-3);
|
||||
const outputSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const output = call("ghostty_wasm_alloc_u8_array", outputSize);
|
||||
expect(
|
||||
call(
|
||||
"ghostty_terminal_selection_format_buf",
|
||||
terminal,
|
||||
formatOptions,
|
||||
output,
|
||||
outputSize,
|
||||
written,
|
||||
),
|
||||
).toBe(0);
|
||||
expect(new TextDecoder().decode(new Uint8Array(memory.buffer, output, outputSize))).toBe(
|
||||
"a\n\nb",
|
||||
);
|
||||
|
||||
call("ghostty_wasm_free_u8_array", output, outputSize);
|
||||
call("ghostty_wasm_free_usize", written);
|
||||
call("ghostty_wasm_free_u8_array", formatOptions, 16);
|
||||
call("ghostty_wasm_free_u8_array", selection, 32);
|
||||
call("ghostty_wasm_free_u8_array", inputPointer, input.length);
|
||||
call("ghostty_terminal_free", terminal);
|
||||
call("ghostty_wasm_free_opaque", terminalSlot);
|
||||
call("ghostty_wasm_free_u8_array", options, 8);
|
||||
});
|
||||
|
||||
it("uses Ghostty for mouse encoding, word selection, and OSC 8 hit testing", async () => {
|
||||
const result = await WebAssembly.instantiate(
|
||||
decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
|
||||
{ env: { log: () => {} } },
|
||||
);
|
||||
const instance = result instanceof WebAssembly.Instance ? result : result.instance;
|
||||
const memory = instance.exports.memory as WebAssembly.Memory;
|
||||
const call = (name: string, ...args: number[]) =>
|
||||
(instance.exports[name] as WasmFunction)(...args);
|
||||
const alloc = (size: number) => call("ghostty_wasm_alloc_u8_array", size);
|
||||
const free = (pointer: number, size: number) =>
|
||||
call("ghostty_wasm_free_u8_array", pointer, size);
|
||||
|
||||
const terminalOptions = alloc(8);
|
||||
const terminalOptionsView = new DataView(memory.buffer, terminalOptions, 8);
|
||||
terminalOptionsView.setUint16(0, 80, true);
|
||||
terminalOptionsView.setUint16(2, 24, true);
|
||||
const terminalSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_terminal_new", 0, terminalSlot, terminalOptions)).toBe(0);
|
||||
const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
|
||||
const input = new TextEncoder().encode(
|
||||
"\u001b[?1000h\u001b[?1006h\u001b]8;;https://t3.codes/docs\u001b\\linked\u001b]8;;\u001b\\ plain",
|
||||
);
|
||||
const inputPointer = alloc(input.length);
|
||||
new Uint8Array(memory.buffer, inputPointer, input.length).set(input);
|
||||
call("ghostty_terminal_vt_write", terminal, inputPointer, input.length);
|
||||
|
||||
const modeFlag = alloc(1);
|
||||
new Uint8Array(memory.buffer, modeFlag, 1)[0] = 0;
|
||||
expect(call("ghostty_terminal_get", terminal, 11, modeFlag)).toBe(0);
|
||||
expect(new Uint8Array(memory.buffer, modeFlag, 1)[0]).toBe(1);
|
||||
new Uint8Array(memory.buffer, modeFlag, 1)[0] = 1;
|
||||
expect(call("ghostty_terminal_mode_get", terminal, 1003, modeFlag)).toBe(0);
|
||||
expect(new Uint8Array(memory.buffer, modeFlag, 1)[0]).toBe(0);
|
||||
const anyEventInput = new TextEncoder().encode("\u001b[?1003h");
|
||||
const anyEventPointer = alloc(anyEventInput.length);
|
||||
new Uint8Array(memory.buffer, anyEventPointer, anyEventInput.length).set(anyEventInput);
|
||||
call("ghostty_terminal_vt_write", terminal, anyEventPointer, anyEventInput.length);
|
||||
expect(call("ghostty_terminal_mode_get", terminal, 1003, modeFlag)).toBe(0);
|
||||
expect(new Uint8Array(memory.buffer, modeFlag, 1)[0]).toBe(1);
|
||||
const anyEventReset = new TextEncoder().encode("\u001b[?1003l\u001b[?1000h");
|
||||
const anyEventResetPointer = alloc(anyEventReset.length);
|
||||
new Uint8Array(memory.buffer, anyEventResetPointer, anyEventReset.length).set(anyEventReset);
|
||||
call("ghostty_terminal_vt_write", terminal, anyEventResetPointer, anyEventReset.length);
|
||||
expect(call("ghostty_terminal_mode_get", terminal, 1003, modeFlag)).toBe(0);
|
||||
expect(new Uint8Array(memory.buffer, modeFlag, 1)[0]).toBe(0);
|
||||
free(anyEventResetPointer, anyEventReset.length);
|
||||
free(anyEventPointer, anyEventInput.length);
|
||||
free(modeFlag, 1);
|
||||
|
||||
const point = alloc(24);
|
||||
const pointView = new DataView(memory.buffer, point, 24);
|
||||
pointView.setUint32(0, 1, true);
|
||||
pointView.setUint16(8, 1, true);
|
||||
pointView.setUint32(12, 0, true);
|
||||
const gridRef = alloc(12);
|
||||
new DataView(memory.buffer, gridRef, 12).setUint32(0, 12, true);
|
||||
expect(call("ghostty_terminal_grid_ref", terminal, point, gridRef)).toBe(0);
|
||||
|
||||
const written = call("ghostty_wasm_alloc_usize");
|
||||
expect(call("ghostty_grid_ref_hyperlink_uri", gridRef, 0, 0, written)).toBe(-3);
|
||||
const hyperlinkSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const hyperlink = alloc(hyperlinkSize);
|
||||
expect(call("ghostty_grid_ref_hyperlink_uri", gridRef, hyperlink, hyperlinkSize, written)).toBe(
|
||||
0,
|
||||
);
|
||||
expect(new TextDecoder().decode(new Uint8Array(memory.buffer, hyperlink, hyperlinkSize))).toBe(
|
||||
"https://t3.codes/docs",
|
||||
);
|
||||
|
||||
const wordOptions = alloc(24);
|
||||
const wordOptionsView = new DataView(memory.buffer, wordOptions, 24);
|
||||
wordOptionsView.setUint32(0, 24, true);
|
||||
new Uint8Array(memory.buffer, wordOptions + 4, 12).set(
|
||||
new Uint8Array(memory.buffer, gridRef, 12),
|
||||
);
|
||||
const selection = alloc(32);
|
||||
new DataView(memory.buffer, selection, 32).setUint32(0, 32, true);
|
||||
expect(call("ghostty_terminal_select_word", terminal, wordOptions, selection)).toBe(0);
|
||||
expect(call("ghostty_terminal_set", terminal, 21, selection)).toBe(0);
|
||||
const formatOptions = alloc(16);
|
||||
const formatView = new DataView(memory.buffer, formatOptions, 16);
|
||||
formatView.setUint32(0, 16, true);
|
||||
formatView.setUint8(8, 1);
|
||||
formatView.setUint8(9, 1);
|
||||
expect(
|
||||
call("ghostty_terminal_selection_format_buf", terminal, formatOptions, 0, 0, written),
|
||||
).toBe(-3);
|
||||
const selectionSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const selectionText = alloc(selectionSize);
|
||||
expect(
|
||||
call(
|
||||
"ghostty_terminal_selection_format_buf",
|
||||
terminal,
|
||||
formatOptions,
|
||||
selectionText,
|
||||
selectionSize,
|
||||
written,
|
||||
),
|
||||
).toBe(0);
|
||||
expect(
|
||||
new TextDecoder().decode(new Uint8Array(memory.buffer, selectionText, selectionSize)),
|
||||
).toBe("linked");
|
||||
|
||||
const lineOptions = alloc(28);
|
||||
const lineOptionsView = new DataView(memory.buffer, lineOptions, 28);
|
||||
lineOptionsView.setUint32(0, 28, true);
|
||||
new Uint8Array(memory.buffer, lineOptions + 4, 12).set(
|
||||
new Uint8Array(memory.buffer, gridRef, 12),
|
||||
);
|
||||
expect(call("ghostty_terminal_select_line", terminal, lineOptions, selection)).toBe(0);
|
||||
expect(call("ghostty_terminal_set", terminal, 21, selection)).toBe(0);
|
||||
expect(
|
||||
call("ghostty_terminal_selection_format_buf", terminal, formatOptions, 0, 0, written),
|
||||
).toBe(-3);
|
||||
const lineSelectionSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const lineSelectionText = alloc(lineSelectionSize);
|
||||
expect(
|
||||
call(
|
||||
"ghostty_terminal_selection_format_buf",
|
||||
terminal,
|
||||
formatOptions,
|
||||
lineSelectionText,
|
||||
lineSelectionSize,
|
||||
written,
|
||||
),
|
||||
).toBe(0);
|
||||
expect(
|
||||
new TextDecoder().decode(new Uint8Array(memory.buffer, lineSelectionText, lineSelectionSize)),
|
||||
).toBe("linked plain");
|
||||
|
||||
const mouseEncoderSlot = call("ghostty_wasm_alloc_opaque");
|
||||
const mouseEventSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_mouse_encoder_new", 0, mouseEncoderSlot)).toBe(0);
|
||||
expect(call("ghostty_mouse_event_new", 0, mouseEventSlot)).toBe(0);
|
||||
const view = new DataView(memory.buffer);
|
||||
const mouseEncoder = view.getUint32(mouseEncoderSlot, true);
|
||||
const mouseEvent = view.getUint32(mouseEventSlot, true);
|
||||
call("ghostty_mouse_encoder_setopt_from_terminal", mouseEncoder, terminal);
|
||||
const mouseSize = alloc(36);
|
||||
const mouseSizeView = new DataView(memory.buffer, mouseSize, 36);
|
||||
for (const [offset, value] of [
|
||||
[0, 36],
|
||||
[4, 800],
|
||||
[8, 480],
|
||||
[12, 10],
|
||||
[16, 20],
|
||||
] as const) {
|
||||
mouseSizeView.setUint32(offset, value, true);
|
||||
}
|
||||
call("ghostty_mouse_encoder_setopt", mouseEncoder, 2, mouseSize);
|
||||
call("ghostty_mouse_event_set_action", mouseEvent, 0);
|
||||
call("ghostty_mouse_event_set_button", mouseEvent, 1);
|
||||
const mousePosition = new DataView(new ArrayBuffer(8));
|
||||
mousePosition.setFloat32(0, 15, true);
|
||||
mousePosition.setFloat32(4, 25, true);
|
||||
const mousePositionPointer = alloc(8);
|
||||
new Uint8Array(memory.buffer, mousePositionPointer, 8).set(
|
||||
new Uint8Array(mousePosition.buffer),
|
||||
);
|
||||
call("ghostty_mouse_event_set_position", mouseEvent, mousePositionPointer);
|
||||
const mouseOutput = alloc(128);
|
||||
expect(
|
||||
call("ghostty_mouse_encoder_encode", mouseEncoder, mouseEvent, mouseOutput, 128, written),
|
||||
).toBe(0);
|
||||
const mouseOutputSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
expect(
|
||||
new TextDecoder().decode(new Uint8Array(memory.buffer, mouseOutput, mouseOutputSize)),
|
||||
).toBe("\u001b[<0;2;2M");
|
||||
|
||||
call("ghostty_mouse_event_free", mouseEvent);
|
||||
call("ghostty_mouse_encoder_free", mouseEncoder);
|
||||
call("ghostty_wasm_free_opaque", mouseEventSlot);
|
||||
call("ghostty_wasm_free_opaque", mouseEncoderSlot);
|
||||
free(mousePositionPointer, 8);
|
||||
free(mouseOutput, 128);
|
||||
free(mouseSize, 36);
|
||||
free(lineSelectionText, lineSelectionSize);
|
||||
free(lineOptions, 28);
|
||||
free(selectionText, selectionSize);
|
||||
free(formatOptions, 16);
|
||||
free(selection, 32);
|
||||
free(wordOptions, 24);
|
||||
free(hyperlink, hyperlinkSize);
|
||||
call("ghostty_wasm_free_usize", written);
|
||||
free(gridRef, 12);
|
||||
free(point, 24);
|
||||
free(inputPointer, input.length);
|
||||
call("ghostty_terminal_free", terminal);
|
||||
call("ghostty_wasm_free_opaque", terminalSlot);
|
||||
free(terminalOptions, 8);
|
||||
});
|
||||
|
||||
it("encodes modified printable keys in Kitty keyboard mode", async () => {
|
||||
const result = await WebAssembly.instantiate(
|
||||
decodeWasmDataUrl(wasmDataUrl).buffer as ArrayBuffer,
|
||||
{ env: { log: () => {} } },
|
||||
);
|
||||
const instance = result instanceof WebAssembly.Instance ? result : result.instance;
|
||||
const memory = instance.exports.memory as WebAssembly.Memory;
|
||||
const call = (name: string, ...args: number[]) =>
|
||||
(instance.exports[name] as WasmFunction)(...args);
|
||||
const alloc = (size: number) => call("ghostty_wasm_alloc_u8_array", size);
|
||||
const free = (pointer: number, size: number) =>
|
||||
call("ghostty_wasm_free_u8_array", pointer, size);
|
||||
|
||||
const terminalOptions = alloc(8);
|
||||
const terminalOptionsView = new DataView(memory.buffer, terminalOptions, 8);
|
||||
terminalOptionsView.setUint16(0, 80, true);
|
||||
terminalOptionsView.setUint16(2, 24, true);
|
||||
const terminalSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_terminal_new", 0, terminalSlot, terminalOptions)).toBe(0);
|
||||
const terminal = new DataView(memory.buffer).getUint32(terminalSlot, true);
|
||||
const kittyMode = new TextEncoder().encode("\u001b[>1u");
|
||||
const kittyModePointer = alloc(kittyMode.length);
|
||||
new Uint8Array(memory.buffer, kittyModePointer, kittyMode.length).set(kittyMode);
|
||||
call("ghostty_terminal_vt_write", terminal, kittyModePointer, kittyMode.length);
|
||||
|
||||
const encoderSlot = call("ghostty_wasm_alloc_opaque");
|
||||
const eventSlot = call("ghostty_wasm_alloc_opaque");
|
||||
expect(call("ghostty_key_encoder_new", 0, encoderSlot)).toBe(0);
|
||||
expect(call("ghostty_key_event_new", 0, eventSlot)).toBe(0);
|
||||
const view = new DataView(memory.buffer);
|
||||
const keyEncoder = view.getUint32(encoderSlot, true);
|
||||
const keyEvent = view.getUint32(eventSlot, true);
|
||||
call("ghostty_key_encoder_setopt_from_terminal", keyEncoder, terminal);
|
||||
call("ghostty_key_event_set_action", keyEvent, 1);
|
||||
call("ghostty_key_event_set_key", keyEvent, ghosttyKeyForCode("KeyC"));
|
||||
call("ghostty_key_event_set_mods", keyEvent, 1 << 1);
|
||||
call("ghostty_key_event_set_consumed_mods", keyEvent, 0);
|
||||
call("ghostty_key_event_set_composing", keyEvent, 0);
|
||||
call("ghostty_key_event_set_unshifted_codepoint", keyEvent, "c".codePointAt(0)!);
|
||||
const text = new TextEncoder().encode("c");
|
||||
const textPointer = alloc(text.length);
|
||||
new Uint8Array(memory.buffer, textPointer, text.length).set(text);
|
||||
call("ghostty_key_event_set_utf8", keyEvent, textPointer, text.length);
|
||||
|
||||
const written = call("ghostty_wasm_alloc_usize");
|
||||
expect(call("ghostty_key_encoder_encode", keyEncoder, keyEvent, 0, 0, written)).toBe(-3);
|
||||
const outputSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const output = alloc(outputSize);
|
||||
expect(
|
||||
call("ghostty_key_encoder_encode", keyEncoder, keyEvent, output, outputSize, written),
|
||||
).toBe(0);
|
||||
const outputLength = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
expect(new TextDecoder().decode(new Uint8Array(memory.buffer, output, outputLength))).toBe(
|
||||
"\u001b[99;5u",
|
||||
);
|
||||
|
||||
const remappedText = new TextEncoder().encode("j");
|
||||
const remappedTextPointer = alloc(remappedText.length);
|
||||
new Uint8Array(memory.buffer, remappedTextPointer, remappedText.length).set(remappedText);
|
||||
call("ghostty_key_event_set_unshifted_codepoint", keyEvent, "j".codePointAt(0)!);
|
||||
call("ghostty_key_event_set_utf8", keyEvent, remappedTextPointer, remappedText.length);
|
||||
expect(call("ghostty_key_encoder_encode", keyEncoder, keyEvent, 0, 0, written)).toBe(-3);
|
||||
const remappedOutputSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const remappedOutput = alloc(remappedOutputSize);
|
||||
expect(
|
||||
call(
|
||||
"ghostty_key_encoder_encode",
|
||||
keyEncoder,
|
||||
keyEvent,
|
||||
remappedOutput,
|
||||
remappedOutputSize,
|
||||
written,
|
||||
),
|
||||
).toBe(0);
|
||||
const remappedOutputLength = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
expect(
|
||||
new TextDecoder().decode(new Uint8Array(memory.buffer, remappedOutput, remappedOutputLength)),
|
||||
).toBe("\u001b[106;5u");
|
||||
|
||||
// Without the Kitty report-event-types flag a release encodes nothing, so
|
||||
// the surface's keyup handler stays silent for legacy sessions.
|
||||
call("ghostty_key_event_set_action", keyEvent, 0);
|
||||
expect(call("ghostty_key_encoder_encode", keyEncoder, keyEvent, 0, 0, written)).toBe(0);
|
||||
expect(new DataView(memory.buffer, written, 4).getUint32(0, true)).toBe(0);
|
||||
|
||||
// With report-event-types enabled the same release encodes an event-typed code.
|
||||
const reportEvents = new TextEncoder().encode("\u001b[>3u");
|
||||
const reportEventsPointer = alloc(reportEvents.length);
|
||||
new Uint8Array(memory.buffer, reportEventsPointer, reportEvents.length).set(reportEvents);
|
||||
call("ghostty_terminal_vt_write", terminal, reportEventsPointer, reportEvents.length);
|
||||
call("ghostty_key_encoder_setopt_from_terminal", keyEncoder, terminal);
|
||||
expect(call("ghostty_key_encoder_encode", keyEncoder, keyEvent, 0, 0, written)).toBe(-3);
|
||||
const releaseSize = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
const releaseOutput = alloc(releaseSize);
|
||||
expect(
|
||||
call("ghostty_key_encoder_encode", keyEncoder, keyEvent, releaseOutput, releaseSize, written),
|
||||
).toBe(0);
|
||||
const releaseLength = new DataView(memory.buffer, written, 4).getUint32(0, true);
|
||||
expect(
|
||||
new TextDecoder().decode(new Uint8Array(memory.buffer, releaseOutput, releaseLength)),
|
||||
).toBe("\u001b[106;5:3u");
|
||||
free(releaseOutput, releaseSize);
|
||||
free(reportEventsPointer, reportEvents.length);
|
||||
|
||||
free(remappedOutput, remappedOutputSize);
|
||||
free(remappedTextPointer, remappedText.length);
|
||||
free(output, outputSize);
|
||||
call("ghostty_wasm_free_usize", written);
|
||||
free(textPointer, text.length);
|
||||
call("ghostty_key_event_free", keyEvent);
|
||||
call("ghostty_key_encoder_free", keyEncoder);
|
||||
call("ghostty_wasm_free_opaque", eventSlot);
|
||||
call("ghostty_wasm_free_opaque", encoderSlot);
|
||||
free(kittyModePointer, kittyMode.length);
|
||||
call("ghostty_terminal_free", terminal);
|
||||
call("ghostty_wasm_free_opaque", terminalSlot);
|
||||
free(terminalOptions, 8);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,383 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { GhosttyCell, GhosttyRow } from "./core";
|
||||
import {
|
||||
DEFAULT_TERMINAL_FONT_FAMILY,
|
||||
DEFAULT_TERMINAL_FONT_SIZE,
|
||||
advanceTerminalSelectionClickSequence,
|
||||
ghosttyMouseButton,
|
||||
isTerminalAltGraphText,
|
||||
isTerminalCompositionCommitInput,
|
||||
isTerminalCopyShortcut,
|
||||
isTerminalLinkPointerGesture,
|
||||
isTerminalPasteShortcut,
|
||||
shouldReportTerminalMouse,
|
||||
terminalScrollbarGeometry,
|
||||
terminalScrollbarOffsetAtPointer,
|
||||
terminalLinkAtColumn,
|
||||
terminalLinkAtPosition,
|
||||
terminalContentOriginY,
|
||||
terminalFontFamily,
|
||||
terminalFontSize,
|
||||
terminalWheelArrowData,
|
||||
terminalWheelDeltaRows,
|
||||
} from "./surface";
|
||||
|
||||
const cell = (text: string): GhosttyCell => ({
|
||||
text,
|
||||
wide: 0,
|
||||
foreground: { r: 255, g: 255, b: 255 },
|
||||
background: { r: 0, g: 0, b: 0 },
|
||||
bold: false,
|
||||
italic: false,
|
||||
invisible: false,
|
||||
strikethrough: false,
|
||||
overline: false,
|
||||
underline: false,
|
||||
selected: false,
|
||||
});
|
||||
|
||||
describe("isTerminalAltGraphText", () => {
|
||||
it("defers printable AltGr output to the textarea input event", () => {
|
||||
expect(
|
||||
isTerminalAltGraphText({
|
||||
key: "@",
|
||||
getModifierState: (modifier) => modifier === "AltGraph",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTerminalAltGraphText({
|
||||
key: "ArrowRight",
|
||||
getModifierState: (modifier) => modifier === "AltGraph",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalLinkAtColumn", () => {
|
||||
it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
|
||||
const cells = [
|
||||
cell("🙂"),
|
||||
cell(""),
|
||||
...Array.from("https://t3.codes", (character) => cell(character)),
|
||||
];
|
||||
const row: GhosttyRow = {
|
||||
cells,
|
||||
text: cells
|
||||
.map((value) => value.text || " ")
|
||||
.join("")
|
||||
.trimEnd(),
|
||||
isWrapContinuation: false,
|
||||
wrapsToNext: false,
|
||||
};
|
||||
|
||||
expect(terminalLinkAtColumn(row, 2)).toBe("https://t3.codes");
|
||||
expect(terminalLinkAtColumn(row, cells.length - 1)).toBe("https://t3.codes");
|
||||
expect(terminalLinkAtColumn(row, 0)).toBeNull();
|
||||
});
|
||||
|
||||
it("uses shared path matching and reconstructs soft-wrapped links", () => {
|
||||
const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
|
||||
cells: Array.from(text.padEnd(16), (character) => cell(character)),
|
||||
text: text.trimEnd(),
|
||||
isWrapContinuation,
|
||||
wrapsToNext,
|
||||
});
|
||||
const rows = [
|
||||
row("https://example.", false),
|
||||
row("com/reference", true),
|
||||
row("~/project/file", false),
|
||||
row("C:\\repo\\file.ts", false),
|
||||
];
|
||||
|
||||
expect(terminalLinkAtPosition(rows, 0, 8)).toBe("https://example.com/reference");
|
||||
expect(terminalLinkAtPosition(rows, 1, 4)).toBe("https://example.com/reference");
|
||||
expect(terminalLinkAtPosition(rows, 2, 2)).toBe("~/project/file");
|
||||
expect(terminalLinkAtPosition(rows, 3, 4)).toBe("C:\\repo\\file.ts");
|
||||
});
|
||||
|
||||
it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
|
||||
const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
|
||||
cells: Array.from(text.padEnd(16), (character) => cell(character)),
|
||||
text: text.trimEnd(),
|
||||
isWrapContinuation,
|
||||
wrapsToNext,
|
||||
});
|
||||
// The head of the wrapped line scrolled above the viewport.
|
||||
const headCut = [row("ple.com/missing", true), row("head", true)];
|
||||
expect(terminalLinkAtPosition(headCut, 0, 4)).toBeNull();
|
||||
// The bottom row soft-wraps on below the viewport.
|
||||
const tailCut = [row("https://t3.codes", false, true)];
|
||||
expect(terminalLinkAtPosition(tailCut, 0, 8)).toBeNull();
|
||||
// A partial bottom row is provably complete and still resolves.
|
||||
const complete = [row("https://t3.codes", false), row("", false)];
|
||||
expect(terminalLinkAtPosition(complete, 0, 8)).toBe("https://t3.codes");
|
||||
// A wide grapheme earlier in the row must not break truncation detection:
|
||||
// the soft-wrap flag decides, not string-length-versus-cell-count.
|
||||
const wideFull: GhosttyRow = {
|
||||
cells: [
|
||||
{ ...cell("🙂"), wide: 1 },
|
||||
{ ...cell(""), wide: 2 },
|
||||
...Array.from("https://t3.code", (character) => cell(character)),
|
||||
],
|
||||
text: "🙂 https://t3.code",
|
||||
isWrapContinuation: false,
|
||||
wrapsToNext: true,
|
||||
};
|
||||
expect(terminalLinkAtPosition([wideFull], 0, 8)).toBeNull();
|
||||
// Unwritten trailing cells prove the bottom row is complete.
|
||||
const unwrittenTail: GhosttyRow = {
|
||||
cells: [
|
||||
...Array.from("https://t3.codes", (character) => cell(character)),
|
||||
cell(""),
|
||||
cell(""),
|
||||
],
|
||||
text: "https://t3.codes",
|
||||
isWrapContinuation: false,
|
||||
wrapsToNext: false,
|
||||
};
|
||||
expect(terminalLinkAtPosition([unwrittenTail], 0, 8)).toBe("https://t3.codes");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalCopyShortcut", () => {
|
||||
const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
|
||||
ctrlKey: false,
|
||||
key: "c",
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("keeps Ctrl+C available for SIGINT on macOS", () => {
|
||||
expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
|
||||
expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
|
||||
});
|
||||
|
||||
it("uses the conventional Ctrl+Shift+C shortcut elsewhere", () => {
|
||||
expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);
|
||||
expect(isTerminalCopyShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the produced character instead of the physical key position", () => {
|
||||
expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
|
||||
expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalPasteShortcut", () => {
|
||||
const event = (overrides: Partial<Parameters<typeof isTerminalPasteShortcut>[0]> = {}) => ({
|
||||
ctrlKey: false,
|
||||
key: "v",
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("uses Cmd+V on macOS", () => {
|
||||
expect(isTerminalPasteShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
|
||||
expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves Ctrl+V and uses Ctrl+Shift+V elsewhere", () => {
|
||||
expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);
|
||||
expect(isTerminalPasteShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalCompositionCommitInput", () => {
|
||||
it("identifies browser composition follow-up input", () => {
|
||||
expect(isTerminalCompositionCommitInput({ inputType: "" })).toBe(true);
|
||||
expect(isTerminalCompositionCommitInput({ inputType: "insertCompositionText" })).toBe(true);
|
||||
expect(isTerminalCompositionCommitInput({ inputType: "insertFromComposition" })).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a fast repeated input as legitimate text", () => {
|
||||
expect(isTerminalCompositionCommitInput({ inputType: "insertText" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("application mouse reporting", () => {
|
||||
const event = (overrides: Partial<Parameters<typeof shouldReportTerminalMouse>[1]> = {}) => ({
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("keeps Shift and link activation modifiers available to the browser", () => {
|
||||
expect(shouldReportTerminalMouse(true, event())).toBe(true);
|
||||
expect(shouldReportTerminalMouse(true, event({ shiftKey: true }))).toBe(false);
|
||||
expect(shouldReportTerminalMouse(true, event({ ctrlKey: true }))).toBe(false);
|
||||
expect(shouldReportTerminalMouse(true, event({ metaKey: true }))).toBe(false);
|
||||
expect(shouldReportTerminalMouse(false, event())).toBe(false);
|
||||
});
|
||||
|
||||
it("maps browser buttons to Ghostty's button enum", () => {
|
||||
expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal font resolution", () => {
|
||||
it("keeps the glyph fallbacks behind a custom text face", () => {
|
||||
expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
|
||||
expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
|
||||
const custom = terminalFontFamily('"Fira Code"');
|
||||
expect(custom.startsWith('"Fira Code", ')).toBe(true);
|
||||
expect(custom).toContain('"Symbols Nerd Font Mono"');
|
||||
expect(custom.endsWith("monospace")).toBe(true);
|
||||
});
|
||||
|
||||
it("clamps requested font sizes to the supported range", () => {
|
||||
expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
expect(terminalFontSize(13.4)).toBe(13);
|
||||
expect(terminalFontSize(2)).toBe(6);
|
||||
expect(terminalFontSize(90)).toBe(32);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalContentOriginY", () => {
|
||||
it("stays top-anchored like a fresh terminal until scrollback exists", () => {
|
||||
expect(terminalContentOriginY(100, 4, 5, 16, false)).toBe(4);
|
||||
});
|
||||
|
||||
it("pins the grid to the bottom by moving the sub-row slack above row 0", () => {
|
||||
// 100px mount, 4px padding, 5 rows of 16px: 92 - 80 = 12px slack on top.
|
||||
expect(terminalContentOriginY(100, 4, 5, 16, true)).toBe(16);
|
||||
// Exact fit keeps the origin at the padding.
|
||||
expect(terminalContentOriginY(88, 4, 5, 16, true)).toBe(4);
|
||||
// A mount smaller than the grid never pushes the origin above the padding.
|
||||
expect(terminalContentOriginY(80, 4, 5, 16, true)).toBe(4);
|
||||
});
|
||||
|
||||
it("keeps the prompt stationary while a drag crosses row boundaries", () => {
|
||||
// Growing the mount pixel by pixel: the bottom edge (origin + rows*cell)
|
||||
// tracks the mount bottom exactly until a new row fits.
|
||||
for (let height = 88; height < 104; height += 1) {
|
||||
const rows = Math.max(1, Math.floor((height - 8) / 16));
|
||||
const origin = terminalContentOriginY(height, 4, rows, 16, true);
|
||||
expect(origin + rows * 16).toBe(height - 4);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalWheelDeltaRows", () => {
|
||||
it("converts line-mode deltas into whole rows", () => {
|
||||
const result = terminalWheelDeltaRows({ deltaY: 3, deltaMode: 1 }, 16, 24, 0);
|
||||
expect(result.rows).toBe(3);
|
||||
expect(result.remainder).toBe(0);
|
||||
});
|
||||
|
||||
it("accumulates fractional pixel deltas across events", () => {
|
||||
let remainder = 0;
|
||||
let scrolled = 0;
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
|
||||
remainder = result.remainder;
|
||||
scrolled += result.rows;
|
||||
}
|
||||
expect(scrolled).toBe(1);
|
||||
expect(remainder).toBeCloseTo(4 / 16);
|
||||
});
|
||||
|
||||
it("keeps direction for negative page-mode deltas", () => {
|
||||
const result = terminalWheelDeltaRows({ deltaY: -1, deltaMode: 2 }, 16, 24, 0);
|
||||
expect(result.rows).toBe(-24);
|
||||
expect(result.remainder).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalWheelArrowData", () => {
|
||||
it("emits one arrow per row honoring application cursor keys", () => {
|
||||
expect(terminalWheelArrowData(-2, false)).toBe("\u001b[A\u001b[A");
|
||||
expect(terminalWheelArrowData(3, false)).toBe("\u001b[B\u001b[B\u001b[B");
|
||||
expect(terminalWheelArrowData(-1, true)).toBe("\u001bOA");
|
||||
expect(terminalWheelArrowData(0, true)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalLinkPointerGesture", () => {
|
||||
it("uses Command on macOS and Control elsewhere", () => {
|
||||
expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "MacIntel")).toBe(true);
|
||||
expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "MacIntel")).toBe(false);
|
||||
expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "Linux x86_64")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "Linux x86_64")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("advanceTerminalSelectionClickSequence", () => {
|
||||
it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
|
||||
const first = advanceTerminalSelectionClickSequence(null, {
|
||||
clientX: 20,
|
||||
clientY: 30,
|
||||
timeStamp: 1_000,
|
||||
});
|
||||
const second = advanceTerminalSelectionClickSequence(first, {
|
||||
clientX: 22,
|
||||
clientY: 29,
|
||||
timeStamp: 1_200,
|
||||
});
|
||||
const third = advanceTerminalSelectionClickSequence(second, {
|
||||
clientX: 21,
|
||||
clientY: 31,
|
||||
timeStamp: 1_400,
|
||||
});
|
||||
|
||||
expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("starts over after movement, delay, or a completed triple click", () => {
|
||||
const previous = { count: 3, time: 1_000, x: 20, y: 30 };
|
||||
expect(
|
||||
advanceTerminalSelectionClickSequence(previous, {
|
||||
clientX: 20,
|
||||
clientY: 30,
|
||||
timeStamp: 1_100,
|
||||
}).count,
|
||||
).toBe(1);
|
||||
expect(
|
||||
advanceTerminalSelectionClickSequence(previous, {
|
||||
clientX: 30,
|
||||
clientY: 30,
|
||||
timeStamp: 1_100,
|
||||
}).count,
|
||||
).toBe(1);
|
||||
expect(
|
||||
advanceTerminalSelectionClickSequence(previous, {
|
||||
clientX: 20,
|
||||
clientY: 30,
|
||||
timeStamp: 1_501,
|
||||
}).count,
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal scrollbar", () => {
|
||||
it("maps Ghostty's viewport state to a proportional thumb", () => {
|
||||
expect(terminalScrollbarGeometry({ total: 100, offset: 40, len: 20 }, 200)).toEqual({
|
||||
thumbHeight: 40,
|
||||
thumbTop: 80,
|
||||
maxOffset: 80,
|
||||
});
|
||||
expect(terminalScrollbarGeometry({ total: 100, offset: 0, len: 100 }, 200)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the thumb usable for large scrollback and maps dragging back to rows", () => {
|
||||
const state = { total: 10_000, offset: 0, len: 20 };
|
||||
expect(terminalScrollbarGeometry(state, 200)).toEqual({
|
||||
thumbHeight: 18,
|
||||
thumbTop: 0,
|
||||
maxOffset: 9_980,
|
||||
});
|
||||
expect(terminalScrollbarOffsetAtPointer(state, 200, 191, 9)).toBe(9_980);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
@@ -126,6 +126,7 @@ const allowedHosts = [".ts.net", ...configuredAllowedHosts];
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
assetsInclude: ["**/*.wasm"],
|
||||
plugins: [
|
||||
tanstackRouter(),
|
||||
react(),
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Terminal renderers
|
||||
|
||||
Terminal sessions remain server-owned PTYs. Clients receive the existing raw byte stream and send
|
||||
input and resize events over the existing terminal contracts; renderer choices never cross the
|
||||
wire.
|
||||
|
||||
## Ghostty alignment
|
||||
|
||||
Android and web use the official `libghostty-vt` C ABI for parsing, terminal state, grapheme
|
||||
boundaries, keyboard encoding, selection, and scrollback:
|
||||
|
||||
- Android links the native shared library and converts render state into a compact JNI snapshot.
|
||||
- Web loads a separately cached WebAssembly build and reads render state into a Canvas 2D surface.
|
||||
- Both artifacts are built from the revision in
|
||||
`apps/mobile/modules/t3-terminal/Vendor/libghostty-vt/VERSION`.
|
||||
|
||||
The platform adapters deliberately own only platform behavior. Android owns its Kotlin Canvas and
|
||||
touch integration. Web owns browser font shaping, the hidden IME textarea, clipboard and DOM input,
|
||||
and its Canvas renderer. The web adapter also delegates application mouse encoding, word and line
|
||||
selection, and OSC 8 hyperlink metadata to the official ABI. Browser conventions remain available:
|
||||
holding Shift bypasses application mouse capture, and the platform link modifier opens hyperlinks.
|
||||
React does not participate in terminal frames.
|
||||
|
||||
The web runtime is singleton-scoped per browser tab so split terminals share one compiled module
|
||||
and memory. Each visible terminal owns and frees its own terminal, render state, row iterator, cell
|
||||
iterator, key and mouse encoder, and input event handles. Restoring captured scrollback temporarily
|
||||
detaches the PTY callback so historical device queries cannot emit replies into the current shell.
|
||||
|
||||
## Updating Ghostty
|
||||
|
||||
Update and rebuild Android first, because mobile's `VERSION` file is the single source of truth for
|
||||
the upstream pin (the upstream `LICENSE` lives beside it). Then run:
|
||||
|
||||
```sh
|
||||
pnpm --dir apps/web build:ghostty-wasm
|
||||
```
|
||||
|
||||
Commit the regenerated web `wasm` artifacts. The build embeds the pinned revision into the binary as
|
||||
semver build metadata, and the focused web ABI test reads it back through `ghostty_build_info` and
|
||||
compares it against mobile's `VERSION` — so the web vendor directory holds only the artifacts, drift
|
||||
cannot hide, and there is no second pin to keep in sync. The same test enforces the artifact budget
|
||||
and exercises repeated create/write/free cycles with multi-codepoint graphemes.
|
||||
Generated
-16
@@ -570,12 +570,6 @@ importers:
|
||||
'@tanstack/react-router':
|
||||
specifier: ^1.160.2
|
||||
version: 1.170.10([email protected]([email protected]))([email protected])
|
||||
'@xterm/addon-fit':
|
||||
specifier: ^0.11.0
|
||||
version: 0.11.0
|
||||
'@xterm/xterm':
|
||||
specifier: ^6.0.0
|
||||
version: 6.0.0
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
@@ -5156,12 +5150,6 @@ packages:
|
||||
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
|
||||
engines: {node: '>=14.6'}
|
||||
|
||||
'@xterm/[email protected]':
|
||||
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
|
||||
|
||||
'@xterm/[email protected]':
|
||||
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
|
||||
|
||||
'@yuuang/[email protected]':
|
||||
resolution: {integrity: sha512-eDYLT0kVBkp7e2BwdRDmt6N1rkeDPUHDefk3ZX0/nok+GLsqfy1WBoSL3Yg7HVXN1EyW8OBVc2uK8Zq8HbmaSA==}
|
||||
engines: {node: '>= 12'}
|
||||
@@ -15283,10 +15271,6 @@ snapshots:
|
||||
|
||||
'@xmldom/[email protected]': {}
|
||||
|
||||
'@xterm/[email protected]': {}
|
||||
|
||||
'@xterm/[email protected]': {}
|
||||
|
||||
'@yuuang/[email protected]':
|
||||
optional: true
|
||||
|
||||
|
||||
Reference in new issue
Block a user