Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 106 additions & 4 deletions apps/web/src/components/ThreadTerminalDrawer.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import "../index.css";

import { scopeThreadRef } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import type * as React from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";

Expand All @@ -10,6 +11,8 @@ const {
terminalDisposeSpy,
fitAddonFitSpy,
fitAddonLoadSpy,
attachedCustomKeyEventHandlerSpy,
latestCustomKeyEventHandler,
environmentApiById,
readEnvironmentApiMock,
readLocalApiMock,
Expand All @@ -18,6 +21,10 @@ const {
terminalDisposeSpy: vi.fn(),
fitAddonFitSpy: vi.fn(),
fitAddonLoadSpy: vi.fn(),
attachedCustomKeyEventHandlerSpy: vi.fn(),
latestCustomKeyEventHandler: {
current: undefined,
} as React.MutableRefObject<((event: KeyboardEvent) => boolean) | undefined>,
environmentApiById: new Map<string, { terminal: { open: ReturnType<typeof vi.fn> } }>(),
readEnvironmentApiMock: vi.fn((environmentId: string) => environmentApiById.get(environmentId)),
readLocalApiMock: vi.fn<
Expand Down Expand Up @@ -86,8 +93,9 @@ vi.mock("@xterm/xterm", () => ({
return null;
}

attachCustomKeyEventHandler() {
return true;
attachCustomKeyEventHandler(handler?: (event: KeyboardEvent) => boolean) {
latestCustomKeyEventHandler.current = handler;
attachedCustomKeyEventHandlerSpy(handler);
}

registerLinkProvider() {
Expand Down Expand Up @@ -148,6 +156,7 @@ async function mountTerminalViewport(props: {
threadRef: ReturnType<typeof scopeThreadRef>;
drawerBackgroundColor?: string;
drawerTextColor?: string;
keybindings?: React.ComponentProps<typeof TerminalViewport>["keybindings"];
}) {
const drawer = document.createElement("div");
drawer.className = "thread-terminal-drawer";
Expand Down Expand Up @@ -177,7 +186,7 @@ async function mountTerminalViewport(props: {
autoFocus={false}
resizeEpoch={0}
drawerHeight={320}
keybindings={[]}
keybindings={props.keybindings ?? []}
/>,
{ container: host },
);
Expand All @@ -197,7 +206,7 @@ async function mountTerminalViewport(props: {
autoFocus={false}
resizeEpoch={0}
drawerHeight={320}
keybindings={[]}
keybindings={props.keybindings ?? []}
/>,
);
},
Expand All @@ -217,6 +226,8 @@ describe("TerminalViewport", () => {
terminalDisposeSpy.mockClear();
fitAddonFitSpy.mockClear();
fitAddonLoadSpy.mockClear();
attachedCustomKeyEventHandlerSpy.mockClear();
latestCustomKeyEventHandler.current = undefined;
});

it("does not create a terminal when APIs are unavailable", async () => {
Expand Down Expand Up @@ -317,4 +328,95 @@ describe("TerminalViewport", () => {
await mounted.cleanup();
}
});

it.each([
{
name: "macOS",
platform: "MacIntel",
keyboardEvent: {
type: "keydown",
key: "j",
code: "KeyJ",
ctrlKey: false,
metaKey: true,
shiftKey: false,
altKey: false,
},
},
{
name: "Linux",
platform: "Linux x86_64",
keyboardEvent: {
type: "keydown",
key: "j",
code: "KeyJ",
ctrlKey: true,
metaKey: false,
shiftKey: false,
altKey: false,
},
},
{
name: "Windows control-character",
platform: "Win32",
keyboardEvent: {
type: "keydown",
key: "\n",
code: "KeyJ",
ctrlKey: true,
metaKey: false,
shiftKey: false,
altKey: false,
},
},
])("yields $name terminal.toggle events back to the app", async ({ platform, keyboardEvent }) => {
const environment = createEnvironmentApi();
environmentApiById.set("environment-a", environment);
const platformDescriptor = Object.getOwnPropertyDescriptor(window.navigator, "platform");
Object.defineProperty(window.navigator, "platform", {
configurable: true,
value: platform,
});

try {
const mounted = await mountTerminalViewport({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
keybindings: [
{
command: "terminal.toggle",
shortcut: {
key: "j",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
},
],
});

try {
await vi.waitFor(() => {
expect(attachedCustomKeyEventHandlerSpy).toHaveBeenCalledTimes(1);
});

const handledByTerminal = latestCustomKeyEventHandler.current?.({
...keyboardEvent,
preventDefault() {},
stopPropagation() {},
} as unknown as KeyboardEvent);

expect(handledByTerminal).toBe(false);
} finally {
await mounted.cleanup();
}
} finally {
if (platformDescriptor) {
Object.defineProperty(window.navigator, "platform", platformDescriptor);
} else {
delete (window.navigator as { platform?: string }).platform;
}
}
});
});
17 changes: 17 additions & 0 deletions apps/web/src/keybindings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,23 @@ describe("isTerminalToggleShortcut", () => {
}),
);
});

it("matches Ctrl+J on non-macOS from a control-character key event", () => {
assert.isTrue(
isTerminalToggleShortcut(
event({
key: "\n",
code: "KeyJ",
ctrlKey: true,
}),
DEFAULT_BINDINGS,
{
platform: "Win32",
context: { terminalFocus: true },
},
),
);
});
});

describe("split/new/close terminal shortcuts", () => {
Expand Down
15 changes: 11 additions & 4 deletions apps/web/src/keybindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ const EVENT_CODE_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {
Digit9: ["9"],
};

function eventCodeAliases(code: string | undefined): readonly string[] {
if (!code) return [];

if (code.startsWith("Key") && code.length === 4) {
return [code.slice(3).toLowerCase()];
}

return EVENT_CODE_KEY_ALIASES[code] ?? [];
}

function normalizeEventKey(key: string): string {
const normalized = key.toLowerCase();
if (normalized === "esc") return "escape";
Expand All @@ -70,10 +80,7 @@ function normalizeEventKey(key: string): string {

function resolveEventKeys(event: ShortcutEventLike): Set<string> {
const keys = new Set([normalizeEventKey(event.key)]);
const aliases = event.code ? EVENT_CODE_KEY_ALIASES[event.code] : undefined;
if (!aliases) return keys;

for (const alias of aliases) {
for (const alias of eventCodeAliases(event.code)) {
keys.add(alias);
}
return keys;
Expand Down
Loading