Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59b1d5d20f | ||
|
|
00d7519728 | ||
|
|
6de0ca3e7b | ||
|
|
0cd10a9a20 | ||
|
|
367d4f35f0 | ||
|
|
aca3edd044 | ||
|
|
b8dfe54154 | ||
|
|
e1660c6bf2 | ||
|
|
514570a680 | ||
|
|
3e1bfcbbbb | ||
|
|
3b2f559d7e | ||
|
|
5a1a5de724 | ||
|
|
b81b5616ec | ||
|
|
be32ce9792 | ||
|
|
c70e2d5adc | ||
|
|
1c80b4f1fe | ||
|
|
5fac591417 | ||
|
|
e94a47aa2f | ||
|
|
ea140aae21 | ||
|
|
0707d4a826 | ||
|
|
9cebeeeda1 | ||
|
|
68f3184d3f | ||
|
|
ce4ad7ec18 | ||
|
|
384b5e0887 |
No files matched your search
@@ -0,0 +1,95 @@
|
||||
# Keybindings
|
||||
|
||||
T3 Code reads keybindings from:
|
||||
|
||||
- `~/.t3/keybindings.json`
|
||||
|
||||
The file must be a JSON array of rules:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "key": "mod+g", "command": "terminal.toggle" },
|
||||
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
|
||||
]
|
||||
```
|
||||
|
||||
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
|
||||
|
||||
## Defaults
|
||||
|
||||
```json
|
||||
[
|
||||
{ "key": "mod+j", "command": "terminal.toggle" },
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new" },
|
||||
{ "key": "mod+o", "command": "editor.openFavorite" }
|
||||
]
|
||||
```
|
||||
|
||||
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
|
||||
|
||||
## Configuration
|
||||
|
||||
### Rule Shape
|
||||
|
||||
Each entry supports:
|
||||
|
||||
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
|
||||
- `command` (required): action ID
|
||||
- `when` (optional): boolean expression controlling when the shortcut is active
|
||||
|
||||
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
|
||||
|
||||
### Available Commands
|
||||
|
||||
- `terminal.toggle`: open/close terminal drawer
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `chat.new`: create a new chat thread for the active project
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
### Key Syntax
|
||||
|
||||
Supported modifiers:
|
||||
|
||||
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
|
||||
- `cmd` / `meta`
|
||||
- `ctrl` / `control`
|
||||
- `shift`
|
||||
- `alt` / `option`
|
||||
|
||||
Examples:
|
||||
|
||||
- `mod+j`
|
||||
- `mod+shift+d`
|
||||
- `ctrl+l`
|
||||
- `cmd+k`
|
||||
|
||||
### `when` Conditions
|
||||
|
||||
Currently available context keys:
|
||||
|
||||
- `terminalFocus`
|
||||
- `terminalOpen`
|
||||
|
||||
Supported operators:
|
||||
|
||||
- `!` (not)
|
||||
- `&&` (and)
|
||||
- `||` (or)
|
||||
- parentheses: `(` `)`
|
||||
|
||||
Examples:
|
||||
|
||||
- `"when": "terminalFocus"`
|
||||
- `"when": "terminalOpen && !terminalFocus"`
|
||||
- `"when": "terminalFocus || terminalOpen"`
|
||||
|
||||
Unknown condition keys evaluate to `false`.
|
||||
|
||||
### Precedence
|
||||
|
||||
- Rules are evaluated in array order.
|
||||
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
|
||||
- That means precedence is across commands, not only within the same command.
|
||||
@@ -0,0 +1,69 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings";
|
||||
|
||||
describe("server keybindings", () => {
|
||||
it("parses shortcuts including plus key", () => {
|
||||
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
});
|
||||
assert.deepEqual(parseKeybindingShortcut("mod++"), {
|
||||
key: "+",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("compiles valid rule with parsed when AST", () => {
|
||||
const compiled = compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalOpen && !terminalFocus",
|
||||
});
|
||||
|
||||
assert.deepEqual(compiled, {
|
||||
command: "terminal.split",
|
||||
shortcut: {
|
||||
key: "d",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "terminalOpen" },
|
||||
right: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid rules", () => {
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+shift+d+o",
|
||||
command: "terminal.new",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalFocus && (",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
KeybindingRule,
|
||||
KeybindingsConfig,
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { keybindingRuleSchema } from "@t3tools/contracts";
|
||||
|
||||
interface KeybindingsLogger {
|
||||
warn(message: string, context?: Record<string, unknown>): void;
|
||||
}
|
||||
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
| { type: "not" }
|
||||
| { type: "and" }
|
||||
| { type: "or" }
|
||||
| { type: "lparen" }
|
||||
| { type: "rparen" };
|
||||
|
||||
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
];
|
||||
|
||||
function normalizeKeyToken(token: string): string {
|
||||
if (token === "space") return " ";
|
||||
if (token === "esc") return "escape";
|
||||
return token;
|
||||
}
|
||||
|
||||
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
|
||||
const rawTokens = value
|
||||
.toLowerCase()
|
||||
.split("+")
|
||||
.map((token) => token.trim());
|
||||
const tokens = [...rawTokens];
|
||||
let trailingEmptyCount = 0;
|
||||
while (tokens[tokens.length - 1] === "") {
|
||||
trailingEmptyCount += 1;
|
||||
tokens.pop();
|
||||
}
|
||||
if (trailingEmptyCount > 0) {
|
||||
tokens.push("+");
|
||||
}
|
||||
if (tokens.some((token) => token.length === 0)) {
|
||||
return null;
|
||||
}
|
||||
if (tokens.length === 0) return null;
|
||||
|
||||
let key: string | null = null;
|
||||
let metaKey = false;
|
||||
let ctrlKey = false;
|
||||
let shiftKey = false;
|
||||
let altKey = false;
|
||||
let modKey = false;
|
||||
|
||||
for (const token of tokens) {
|
||||
switch (token) {
|
||||
case "cmd":
|
||||
case "meta":
|
||||
metaKey = true;
|
||||
break;
|
||||
case "ctrl":
|
||||
case "control":
|
||||
ctrlKey = true;
|
||||
break;
|
||||
case "shift":
|
||||
shiftKey = true;
|
||||
break;
|
||||
case "alt":
|
||||
case "option":
|
||||
altKey = true;
|
||||
break;
|
||||
case "mod":
|
||||
modKey = true;
|
||||
break;
|
||||
default: {
|
||||
if (key !== null) return null;
|
||||
key = normalizeKeyToken(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (key === null) return null;
|
||||
return {
|
||||
key,
|
||||
metaKey,
|
||||
ctrlKey,
|
||||
shiftKey,
|
||||
altKey,
|
||||
modKey,
|
||||
};
|
||||
}
|
||||
|
||||
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
|
||||
const tokens: WhenToken[] = [];
|
||||
let index = 0;
|
||||
|
||||
while (index < expression.length) {
|
||||
const current = expression[index];
|
||||
if (!current) break;
|
||||
|
||||
if (/\s/.test(current)) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (expression.startsWith("&&", index)) {
|
||||
tokens.push({ type: "and" });
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (expression.startsWith("||", index)) {
|
||||
tokens.push({ type: "or" });
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (current === "!") {
|
||||
tokens.push({ type: "not" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (current === "(") {
|
||||
tokens.push({ type: "lparen" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (current === ")") {
|
||||
tokens.push({ type: "rparen" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
|
||||
if (!identifier) {
|
||||
return null;
|
||||
}
|
||||
tokens.push({ type: "identifier", value: identifier[0] });
|
||||
index += identifier[0].length;
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
||||
const tokens = tokenizeWhenExpression(expression);
|
||||
if (!tokens || tokens.length === 0) return null;
|
||||
let index = 0;
|
||||
|
||||
const parsePrimary = (): KeybindingWhenNode | null => {
|
||||
const token = tokens[index];
|
||||
if (!token) return null;
|
||||
|
||||
if (token.type === "identifier") {
|
||||
index += 1;
|
||||
return { type: "identifier", name: token.value };
|
||||
}
|
||||
|
||||
if (token.type === "lparen") {
|
||||
index += 1;
|
||||
const expressionNode = parseOr();
|
||||
const closeToken = tokens[index];
|
||||
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
|
||||
return null;
|
||||
}
|
||||
index += 1;
|
||||
return expressionNode;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseUnary = (): KeybindingWhenNode | null => {
|
||||
const token = tokens[index];
|
||||
if (token?.type === "not") {
|
||||
index += 1;
|
||||
const node = parseUnary();
|
||||
if (!node) return null;
|
||||
return { type: "not", node };
|
||||
}
|
||||
return parsePrimary();
|
||||
};
|
||||
|
||||
const parseAnd = (): KeybindingWhenNode | null => {
|
||||
let left = parseUnary();
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "and") {
|
||||
index += 1;
|
||||
const right = parseUnary();
|
||||
if (!right) return null;
|
||||
left = { type: "and", left, right };
|
||||
}
|
||||
|
||||
return left;
|
||||
};
|
||||
|
||||
const parseOr = (): KeybindingWhenNode | null => {
|
||||
let left = parseAnd();
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "or") {
|
||||
index += 1;
|
||||
const right = parseAnd();
|
||||
if (!right) return null;
|
||||
left = { type: "or", left, right };
|
||||
}
|
||||
|
||||
return left;
|
||||
};
|
||||
|
||||
const ast = parseOr();
|
||||
if (!ast || index !== tokens.length) return null;
|
||||
return ast;
|
||||
}
|
||||
|
||||
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
|
||||
const key = rule.key.trim();
|
||||
if (key.length === 0) return null;
|
||||
const shortcut = parseKeybindingShortcut(key);
|
||||
if (!shortcut) return null;
|
||||
|
||||
const when = rule.when?.trim();
|
||||
if (when && when.length > 0) {
|
||||
const whenAst = parseKeybindingWhenExpression(when);
|
||||
if (!whenAst) return null;
|
||||
return {
|
||||
command: rule.command,
|
||||
shortcut,
|
||||
whenAst,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
command: rule.command,
|
||||
shortcut,
|
||||
};
|
||||
}
|
||||
|
||||
export function compileResolvedKeybindingsConfig(
|
||||
config: KeybindingsConfig,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const compiled: ResolvedKeybindingsConfig = [];
|
||||
for (const rule of config) {
|
||||
const resolved = compileResolvedKeybindingRule(rule);
|
||||
if (!resolved) continue;
|
||||
compiled.push(resolved);
|
||||
}
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
|
||||
const resolved: ResolvedKeybindingsConfig = [];
|
||||
for (const rule of DEFAULT_KEYBINDINGS) {
|
||||
const compiled = compileResolvedKeybindingRule(rule);
|
||||
if (!compiled) {
|
||||
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
|
||||
}
|
||||
resolved.push(compiled);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
|
||||
|
||||
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
if (custom.length === 0) {
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
|
||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
||||
const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
|
||||
(binding) => !overriddenCommands.has(binding.command),
|
||||
);
|
||||
const merged = [...retainedDefaults, ...custom];
|
||||
|
||||
if (merged.length <= 256) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
|
||||
return merged.slice(-256);
|
||||
}
|
||||
|
||||
export function loadResolvedKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
|
||||
try {
|
||||
const raw = fs.readFileSync(configPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) {
|
||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
||||
path: configPath,
|
||||
});
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
|
||||
const sanitized: ResolvedKeybindingsConfig = [];
|
||||
let invalidEntries = 0;
|
||||
for (const entry of parsed) {
|
||||
const result = keybindingRuleSchema.safeParse(entry);
|
||||
if (result.success) {
|
||||
const compiled = compileResolvedKeybindingRule(result.data);
|
||||
if (!compiled) {
|
||||
invalidEntries += 1;
|
||||
continue;
|
||||
}
|
||||
sanitized.push(compiled);
|
||||
continue;
|
||||
}
|
||||
invalidEntries += 1;
|
||||
}
|
||||
if (invalidEntries > 0) {
|
||||
logger.warn("ignoring invalid keybinding entries", {
|
||||
path: configPath,
|
||||
invalidEntries,
|
||||
totalEntries: parsed.length,
|
||||
});
|
||||
}
|
||||
const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
|
||||
const mergedBeforeCapLength =
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
|
||||
.length + sanitized.length;
|
||||
const merged = mergeWithDefaultKeybindings(sanitized);
|
||||
if (mergedBeforeCapLength > 256) {
|
||||
logger.warn("truncating merged keybindings config to max entries", {
|
||||
path: configPath,
|
||||
maxEntries: 256,
|
||||
});
|
||||
}
|
||||
return merged;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
logger.warn("ignoring malformed keybindings config", {
|
||||
path: configPath,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
@@ -11,10 +11,13 @@ import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type KeybindingsConfig,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type WsPush,
|
||||
type WsResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -192,6 +195,32 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
|
||||
}
|
||||
}
|
||||
|
||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
const resolved: ResolvedKeybindingsConfig = [];
|
||||
for (const binding of bindings) {
|
||||
const compiled = compileResolvedKeybindingRule(binding);
|
||||
if (!compiled) {
|
||||
throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`);
|
||||
}
|
||||
resolved.push(compiled);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
||||
|
||||
function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
if (custom.length === 0) {
|
||||
return DEFAULT_RESOLVED_KEYBINDINGS;
|
||||
}
|
||||
|
||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
||||
const retainedDefaults = DEFAULT_KEYBINDINGS.filter(
|
||||
(binding) => !overriddenCommands.has(binding.command),
|
||||
);
|
||||
return compileKeybindings([...retainedDefaults, ...custom].slice(-256));
|
||||
}
|
||||
|
||||
describe("WebSocket Server", () => {
|
||||
let server: ReturnType<typeof createServer> | null = null;
|
||||
const connections: WebSocket[] = [];
|
||||
@@ -307,7 +336,225 @@ describe("WebSocket Server", () => {
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({ cwd: "/my/workspace" });
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads keybindings from ~/.t3/keybindings.json", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify([
|
||||
{ key: "cmd+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([
|
||||
{ key: "cmd+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("warns and ignores invalid keybinding entries", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-invalid-entry-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+z", command: "invalid.command", when: "terminalFocus" },
|
||||
]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("ignoring invalid keybinding entries"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("warns and ignores keybindings with malformed when expressions", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-invalid-when-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle", when: "terminalFocus && (" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("ignoring invalid keybinding entries"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("reads keybindings once at startup and caches the resolved config", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-cached-config-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const keybindingsPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "cmd+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const firstResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(firstResponse.error).toBeUndefined();
|
||||
expect(firstResponse.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: mergeWithDefaultsForTest([{ key: "cmd+j", command: "terminal.toggle" }]),
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
keybindingsPath,
|
||||
JSON.stringify([{ key: "cmd+k", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const secondResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(secondResponse.error).toBeUndefined();
|
||||
expect(secondResponse.result).toEqual(firstResponse.result);
|
||||
});
|
||||
|
||||
it("warns and ignores unsupported keybindings config format", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, "keybindings.json"),
|
||||
JSON.stringify({ "terminal.toggle": "mod+j" }),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("unsupported format; expected array"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("warns and ignores malformed keybindings config files", async () => {
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const fakeHome = makeTempDir("t3code-home-invalid-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(configDir, "keybindings.json"), "{not-json", "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
server = createTestServer({ cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
cwd: "/my/workspace",
|
||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
});
|
||||
expect(
|
||||
warnSpy.mock.calls.some(([message]) =>
|
||||
String(message).includes("ignoring malformed keybindings config"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns error for unknown methods", async () => {
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
removeGitWorktree,
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig } from "./keybindings";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -90,6 +91,7 @@ export function createServer(options: ServerOptions) {
|
||||
const logger = createLogger("ws");
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||
const keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
||||
|
||||
function logOutgoingPush(push: WsPush, recipients: number) {
|
||||
if (!logWebSocketEvents) return;
|
||||
@@ -410,7 +412,10 @@ export function createServer(options: ServerOptions) {
|
||||
return undefined;
|
||||
|
||||
case WS_METHODS.serverGetConfig:
|
||||
return { cwd };
|
||||
return {
|
||||
cwd,
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import {
|
||||
EDITORS,
|
||||
type EditorId,
|
||||
ModelSlug,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ProviderSendTurnAttachmentInput,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
ModelSlug,
|
||||
type ProviderSendTurnAttachmentInput,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
type ClipboardEvent,
|
||||
@@ -20,12 +23,9 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitCreateWorktreeMutationOptions,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { isElectron } from "../env";
|
||||
import { buildBootstrapInput } from "../historyBootstrap";
|
||||
import {
|
||||
@@ -49,7 +49,13 @@ import { useStore } from "../store";
|
||||
import type { ChatImageAttachment } from "../types";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import { isTerminalToggleShortcut } from "../terminal-shortcuts";
|
||||
import {
|
||||
isOpenFavoriteEditorShortcut,
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
shortcutLabelForCommand,
|
||||
} from "../keybindings";
|
||||
import ChatMarkdown from "./ChatMarkdown";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
@@ -69,7 +75,7 @@ import { Separator } from "./ui/separator";
|
||||
import { Group, GroupSeparator } from "./ui/group";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
|
||||
import { CursorIcon, Icon } from "./Icons";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { Badge } from "./ui/badge";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
@@ -82,6 +88,7 @@ const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
|
||||
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
|
||||
@@ -129,7 +136,9 @@ export default function ChatView() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ api, queryClient }));
|
||||
const createWorktreeMutation = useMutation(
|
||||
gitCreateWorktreeMutationOptions({ api, queryClient }),
|
||||
);
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
@@ -252,14 +261,28 @@ export default function ChatView() {
|
||||
} as const);
|
||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(api, gitCwd));
|
||||
const keybindingsQuery = useQuery({
|
||||
...serverConfigQueryOptions(api),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = branchesQuery.data?.isRepo ?? true;
|
||||
const splitTerminalShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.split"),
|
||||
[keybindings],
|
||||
);
|
||||
const newTerminalShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.new"),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
if (!image.previewUrl) continue;
|
||||
@@ -477,15 +500,64 @@ export default function ChatView() {
|
||||
}, [activeThread?.terminalOpen, activeThreadId, focusComposer]);
|
||||
|
||||
useEffect(() => {
|
||||
const isTerminalFocused = (): boolean => {
|
||||
const activeElement = document.activeElement;
|
||||
if (!(activeElement instanceof HTMLElement)) return false;
|
||||
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
|
||||
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
|
||||
};
|
||||
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (!activeThreadId) return;
|
||||
if (!isTerminalToggleShortcut(event)) return;
|
||||
if (!activeThreadId || event.defaultPrevented) return;
|
||||
const shortcutContext = {
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: Boolean(activeThread?.terminalOpen),
|
||||
};
|
||||
|
||||
if (isTerminalToggleShortcut(event, keybindings, { context: shortcutContext })) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleTerminalVisibility();
|
||||
return;
|
||||
}
|
||||
|
||||
if (isTerminalSplitShortcut(event, keybindings, { context: shortcutContext })) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!activeThread?.terminalOpen) {
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThreadId,
|
||||
open: true,
|
||||
});
|
||||
}
|
||||
splitTerminal();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
|
||||
event.preventDefault();
|
||||
toggleTerminalVisibility();
|
||||
event.stopPropagation();
|
||||
if (!activeThread?.terminalOpen) {
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThreadId,
|
||||
open: true,
|
||||
});
|
||||
}
|
||||
createNewTerminal();
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [activeThreadId, toggleTerminalVisibility]);
|
||||
}, [
|
||||
activeThread?.terminalOpen,
|
||||
activeThreadId,
|
||||
createNewTerminal,
|
||||
dispatch,
|
||||
splitTerminal,
|
||||
keybindings,
|
||||
toggleTerminalVisibility,
|
||||
]);
|
||||
|
||||
const setThreadError = (threadId: string | null, error: string | null) => {
|
||||
if (!threadId) return;
|
||||
@@ -852,7 +924,7 @@ export default function ChatView() {
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Open in editor */}
|
||||
{activeProject && <OpenInPicker />}
|
||||
{activeProject && <OpenInPicker keybindings={keybindings} />}
|
||||
{/* Git actions */}
|
||||
{activeProject && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
|
||||
@@ -1333,6 +1405,8 @@ export default function ChatView() {
|
||||
focusRequestId={terminalFocusRequestId}
|
||||
onSplitTerminal={splitTerminal}
|
||||
onNewTerminal={createNewTerminal}
|
||||
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
|
||||
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
|
||||
onActiveTerminalChange={activateTerminal}
|
||||
onCloseTerminal={closeTerminal}
|
||||
onHeightChange={(height) =>
|
||||
@@ -1428,7 +1502,7 @@ function ReasoningEffortPicker(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function OpenInPicker() {
|
||||
function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig }) {
|
||||
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
|
||||
const stored = localStorage.getItem(LAST_EDITOR_KEY);
|
||||
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
|
||||
@@ -1441,9 +1515,9 @@ function OpenInPicker() {
|
||||
value: "cursor",
|
||||
},
|
||||
{
|
||||
label: navigator.platform.includes("Mac")
|
||||
label: isMacPlatform(navigator.platform)
|
||||
? "Finder"
|
||||
: navigator.platform.includes("Win")
|
||||
: isWindowsPlatform(navigator.platform)
|
||||
? "Explorer"
|
||||
: "Files",
|
||||
Icon: FolderClosedIcon,
|
||||
@@ -1469,20 +1543,23 @@ function OpenInPicker() {
|
||||
[api, activeProject, activeThread, lastEditor, setLastEditor],
|
||||
);
|
||||
|
||||
// Cmd+O / Ctrl+O to open in last-used editor
|
||||
const openFavoriteEditorShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: globalThis.KeyboardEvent) => {
|
||||
if (e.key === "o" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
|
||||
if (api && activeProject) {
|
||||
e.preventDefault();
|
||||
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
|
||||
void api.shell.openInEditor(cwd, lastEditor);
|
||||
}
|
||||
}
|
||||
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
|
||||
if (!api || !activeProject) return;
|
||||
|
||||
e.preventDefault();
|
||||
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
|
||||
void api.shell.openInEditor(cwd, lastEditor);
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [api, activeProject, activeThread, lastEditor]);
|
||||
}, [api, activeProject, activeThread, keybindings, lastEditor]);
|
||||
|
||||
return (
|
||||
<Group aria-label="Subscription actions">
|
||||
@@ -1500,10 +1577,8 @@ function OpenInPicker() {
|
||||
<MenuItem key={value} onClick={() => openInEditor(value)}>
|
||||
<Icon aria-hidden="true" className="text-muted-foreground" />
|
||||
{label}
|
||||
{value === lastEditor && (
|
||||
<MenuShortcut>
|
||||
{navigator.platform.includes("Mac") ? "\u2318O" : "Ctrl+O"}
|
||||
</MenuShortcut>
|
||||
{value === lastEditor && openFavoriteEditorShortcutLabel && (
|
||||
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
|
||||
)}
|
||||
</MenuItem>
|
||||
))}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewShortcut } from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -14,9 +16,12 @@ import {
|
||||
} from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const minutes = Math.floor(diff / 60_000);
|
||||
@@ -112,8 +117,14 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
|
||||
...serverConfigQueryOptions(api),
|
||||
select: (config) => config.keybindings,
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ api, queryClient }));
|
||||
const removeWorktreeMutation = useMutation(
|
||||
gitRemoveWorktreeMutationOptions({ api, queryClient }),
|
||||
);
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
@@ -324,13 +335,7 @@ export default function Sidebar() {
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const isNewThreadShortcut =
|
||||
event.metaKey &&
|
||||
event.shiftKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
event.key.toLowerCase() === "o";
|
||||
if (!isNewThreadShortcut) return;
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
@@ -344,7 +349,7 @@ export default function Sidebar() {
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
|
||||
}, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
|
||||
|
||||
return (
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
preferredTerminalEditor,
|
||||
resolvePathLinkTarget,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut } from "../terminal-shortcuts";
|
||||
import { isTerminalClearShortcut } from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -416,6 +416,8 @@ interface ThreadTerminalDrawerProps {
|
||||
focusRequestId: number;
|
||||
onSplitTerminal: () => void;
|
||||
onNewTerminal: () => void;
|
||||
splitShortcutLabel?: string | undefined;
|
||||
newShortcutLabel?: string | undefined;
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
@@ -468,6 +470,8 @@ export default function ThreadTerminalDrawer({
|
||||
focusRequestId,
|
||||
onSplitTerminal,
|
||||
onNewTerminal,
|
||||
splitShortcutLabel,
|
||||
newShortcutLabel,
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
@@ -694,7 +698,7 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
label="Split Terminal"
|
||||
label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -702,7 +706,7 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalActionButton
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
label="New Terminal"
|
||||
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
@@ -779,14 +783,20 @@ export default function ThreadTerminalDrawer({
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onSplitTerminal}
|
||||
label="Split Terminal"
|
||||
label={
|
||||
splitShortcutLabel
|
||||
? `Split Terminal (${splitShortcutLabel})`
|
||||
: "Split Terminal"
|
||||
}
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminal}
|
||||
label="New Terminal"
|
||||
label={
|
||||
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
|
||||
}
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
type KeybindingWhenNode,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
formatShortcutLabel,
|
||||
isChatNewShortcut,
|
||||
isOpenFavoriteEditorShortcut,
|
||||
isTerminalClearShortcut,
|
||||
isTerminalNewShortcut,
|
||||
isTerminalSplitShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
shortcutLabelForCommand,
|
||||
type ShortcutEventLike,
|
||||
} from "./keybindings";
|
||||
|
||||
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
|
||||
return {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function modShortcut(
|
||||
key: string,
|
||||
overrides: Partial<Omit<KeybindingShortcut, "key">> = {},
|
||||
): KeybindingShortcut {
|
||||
return {
|
||||
key,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function whenIdentifier(name: string): KeybindingWhenNode {
|
||||
return { type: "identifier", name };
|
||||
}
|
||||
|
||||
function whenNot(node: KeybindingWhenNode): KeybindingWhenNode {
|
||||
return { type: "not", node };
|
||||
}
|
||||
|
||||
function whenAnd(left: KeybindingWhenNode, right: KeybindingWhenNode): KeybindingWhenNode {
|
||||
return { type: "and", left, right };
|
||||
}
|
||||
|
||||
interface TestBinding {
|
||||
shortcut: KeybindingShortcut;
|
||||
command: KeybindingCommand;
|
||||
whenAst?: KeybindingWhenNode;
|
||||
}
|
||||
|
||||
function compile(bindings: TestBinding[]): ResolvedKeybindingsConfig {
|
||||
return bindings.map((binding) => ({
|
||||
command: binding.command,
|
||||
shortcut: binding.shortcut,
|
||||
...(binding.whenAst ? { whenAst: binding.whenAst } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
const DEFAULT_BINDINGS = compile([
|
||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
||||
{
|
||||
shortcut: modShortcut("d"),
|
||||
command: "terminal.split",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("d", { shiftKey: true }),
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||
]);
|
||||
|
||||
describe("isTerminalToggleShortcut", () => {
|
||||
it("matches Cmd+J on macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, { platform: "MacIntel" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches Ctrl+J on non-macOS", () => {
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ ctrlKey: true }), DEFAULT_BINDINGS, { platform: "Win32" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("split/new terminal shortcuts", () => {
|
||||
it("requires terminalFocus for default split/new bindings", () => {
|
||||
assert.isFalse(
|
||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches split/new when terminalFocus is true", () => {
|
||||
assert.isTrue(
|
||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("supports when expressions", () => {
|
||||
const keybindings = compile([
|
||||
{
|
||||
shortcut: modShortcut("\\"),
|
||||
command: "terminal.split",
|
||||
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("n", { shiftKey: true }),
|
||||
command: "terminal.new",
|
||||
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
|
||||
},
|
||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
||||
]);
|
||||
assert.isTrue(
|
||||
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
|
||||
platform: "Win32",
|
||||
context: { terminalOpen: true, terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
|
||||
platform: "Win32",
|
||||
context: { terminalOpen: false, terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), keybindings, {
|
||||
platform: "Win32",
|
||||
context: { terminalOpen: true, terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("supports when boolean literals", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("n"), command: "terminal.new", whenAst: whenIdentifier("true") },
|
||||
{ shortcut: modShortcut("m"), command: "terminal.new", whenAst: whenIdentifier("false") },
|
||||
]);
|
||||
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "m", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortcutLabelForCommand", () => {
|
||||
it("returns the most recent binding label", () => {
|
||||
const bindings = compile([
|
||||
{
|
||||
shortcut: modShortcut("\\"),
|
||||
command: "terminal.split",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{
|
||||
shortcut: modShortcut("\\", { shiftKey: true }),
|
||||
command: "terminal.split",
|
||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
|
||||
});
|
||||
|
||||
it("returns labels for non-terminal commands", () => {
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
|
||||
"Ctrl+O",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chat/editor shortcuts", () => {
|
||||
it("matches chat.new shortcut", () => {
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "o", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "o", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("matches editor.openFavorite shortcut", () => {
|
||||
assert.isTrue(
|
||||
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isOpenFavoriteEditorShortcut(event({ key: "o", ctrlKey: true }), DEFAULT_BINDINGS, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-command precedence", () => {
|
||||
it("uses when + order so a later focused rule overrides a global rule", () => {
|
||||
const keybindings = compile([
|
||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
||||
{
|
||||
shortcut: modShortcut("n"),
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
]);
|
||||
|
||||
assert.isTrue(
|
||||
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
||||
platform: "MacIntel",
|
||||
context: { terminalFocus: false },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("still lets a later global rule win when both rules match", () => {
|
||||
const keybindings = compile([
|
||||
{
|
||||
shortcut: modShortcut("n"),
|
||||
command: "terminal.new",
|
||||
whenAst: whenIdentifier("terminalFocus"),
|
||||
},
|
||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
||||
]);
|
||||
|
||||
assert.isFalse(
|
||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isChatNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
||||
platform: "Linux",
|
||||
context: { terminalFocus: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatShortcutLabel", () => {
|
||||
it("formats labels for macOS", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"), "⇧⌘D");
|
||||
});
|
||||
|
||||
it("formats labels for non-macOS", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"), "Ctrl+Shift+D");
|
||||
});
|
||||
|
||||
it("formats labels for plus key", () => {
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "MacIntel"), "⌘+");
|
||||
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "Linux"), "Ctrl++");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalClearShortcut", () => {
|
||||
it("matches Ctrl+L on all platforms", () => {
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"));
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"));
|
||||
});
|
||||
|
||||
it("matches Cmd+K on macOS", () => {
|
||||
assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("plus key parsing", () => {
|
||||
it("matches the plus key shortcut", () => {
|
||||
const plusBindings = compile([{ shortcut: modShortcut("+"), command: "terminal.toggle" }]);
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ key: "+", metaKey: true }), plusBindings, {
|
||||
platform: "MacIntel",
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isTerminalToggleShortcut(event({ key: "+", ctrlKey: true }), plusBindings, {
|
||||
platform: "Linux",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
type KeybindingWhenNode,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { isMacPlatform } from "./lib/utils";
|
||||
|
||||
export interface ShortcutEventLike {
|
||||
key: string;
|
||||
metaKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
shiftKey: boolean;
|
||||
altKey: boolean;
|
||||
}
|
||||
|
||||
export interface ShortcutMatchContext {
|
||||
terminalFocus: boolean;
|
||||
terminalOpen: boolean;
|
||||
[key: string]: boolean;
|
||||
}
|
||||
|
||||
interface ShortcutMatchOptions {
|
||||
platform?: string;
|
||||
context?: Partial<ShortcutMatchContext>;
|
||||
}
|
||||
|
||||
function normalizeEventKey(key: string): string {
|
||||
const normalized = key.toLowerCase();
|
||||
if (normalized === "esc") return "escape";
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function matchesShortcut(
|
||||
event: ShortcutEventLike,
|
||||
shortcut: KeybindingShortcut,
|
||||
platform = navigator.platform,
|
||||
): boolean {
|
||||
const key = normalizeEventKey(event.key);
|
||||
if (key !== shortcut.key) return false;
|
||||
|
||||
const useMetaForMod = isMacPlatform(platform);
|
||||
const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
|
||||
const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
|
||||
return (
|
||||
event.metaKey === expectedMeta &&
|
||||
event.ctrlKey === expectedCtrl &&
|
||||
event.shiftKey === shortcut.shiftKey &&
|
||||
event.altKey === shortcut.altKey
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
|
||||
return options?.platform ?? navigator.platform;
|
||||
}
|
||||
|
||||
function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
|
||||
return {
|
||||
terminalFocus: false,
|
||||
terminalOpen: false,
|
||||
...options?.context,
|
||||
};
|
||||
}
|
||||
|
||||
function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
if (node.name === "true") return true;
|
||||
if (node.name === "false") return false;
|
||||
return Boolean(context[node.name]);
|
||||
case "not":
|
||||
return !evaluateWhenNode(node.node, context);
|
||||
case "and":
|
||||
return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
|
||||
case "or":
|
||||
return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
|
||||
}
|
||||
}
|
||||
|
||||
function matchesWhenClause(
|
||||
whenAst: KeybindingWhenNode | undefined,
|
||||
context: ShortcutMatchContext,
|
||||
): boolean {
|
||||
if (!whenAst) return true;
|
||||
return evaluateWhenNode(whenAst, context);
|
||||
}
|
||||
|
||||
function matchesCommandShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
command: KeybindingCommand,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return resolveShortcutCommand(event, keybindings, options) === command;
|
||||
}
|
||||
|
||||
function resolveShortcutCommand(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): KeybindingCommand | null {
|
||||
const platform = resolvePlatform(options);
|
||||
const context = resolveContext(options);
|
||||
|
||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
||||
const binding = keybindings[index];
|
||||
if (!binding) continue;
|
||||
if (!matchesWhenClause(binding.whenAst, context)) continue;
|
||||
if (!matchesShortcut(event, binding.shortcut, platform)) continue;
|
||||
return binding.command;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatShortcutKeyLabel(key: string): string {
|
||||
if (key === " ") return "Space";
|
||||
if (key.length === 1) return key.toUpperCase();
|
||||
if (key === "escape") return "Esc";
|
||||
if (key === "arrowup") return "Up";
|
||||
if (key === "arrowdown") return "Down";
|
||||
if (key === "arrowleft") return "Left";
|
||||
if (key === "arrowright") return "Right";
|
||||
return key.slice(0, 1).toUpperCase() + key.slice(1);
|
||||
}
|
||||
|
||||
export function formatShortcutLabel(
|
||||
shortcut: KeybindingShortcut,
|
||||
platform = navigator.platform,
|
||||
): string {
|
||||
const keyLabel = formatShortcutKeyLabel(shortcut.key);
|
||||
const useMetaForMod = isMacPlatform(platform);
|
||||
const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
|
||||
const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
|
||||
const showAlt = shortcut.altKey;
|
||||
const showShift = shortcut.shiftKey;
|
||||
|
||||
if (useMetaForMod) {
|
||||
return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
if (showCtrl) parts.push("Ctrl");
|
||||
if (showAlt) parts.push("Alt");
|
||||
if (showShift) parts.push("Shift");
|
||||
if (showMeta) parts.push("Meta");
|
||||
parts.push(keyLabel);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
export function shortcutLabelForCommand(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
command: KeybindingCommand,
|
||||
platform = navigator.platform,
|
||||
): string | null {
|
||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
||||
const binding = keybindings[index];
|
||||
if (!binding || binding.command !== command) continue;
|
||||
return formatShortcutLabel(binding.shortcut, platform);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isTerminalToggleShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
|
||||
}
|
||||
|
||||
export function isTerminalSplitShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.split", options);
|
||||
}
|
||||
|
||||
export function isTerminalNewShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "terminal.new", options);
|
||||
}
|
||||
|
||||
export function isChatNewShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "chat.new", options);
|
||||
}
|
||||
|
||||
export function isOpenFavoriteEditorShortcut(
|
||||
event: ShortcutEventLike,
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
options?: ShortcutMatchOptions,
|
||||
): boolean {
|
||||
return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
|
||||
}
|
||||
|
||||
export function isTerminalClearShortcut(
|
||||
event: ShortcutEventLike,
|
||||
platform = navigator.platform,
|
||||
): boolean {
|
||||
const key = event.key.toLowerCase();
|
||||
|
||||
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
isMacPlatform(platform) &&
|
||||
key === "k" &&
|
||||
event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export const serverQueryKeys = {
|
||||
all: ["server"] as const,
|
||||
config: () => ["server", "config"] as const,
|
||||
};
|
||||
|
||||
export function serverConfigQueryOptions(api: NativeApi | undefined) {
|
||||
return queryOptions({
|
||||
queryKey: serverQueryKeys.config(),
|
||||
queryFn: async () => {
|
||||
if (!api || !api.server || typeof api.server.getConfig !== "function") {
|
||||
throw new Error("Server config is unavailable.");
|
||||
}
|
||||
return api.server.getConfig();
|
||||
},
|
||||
enabled: !!api && !!api.server && typeof api.server.getConfig === "function",
|
||||
staleTime: Infinity,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import { isWindowsPlatform } from "./utils";
|
||||
|
||||
describe("isWindowsPlatform", () => {
|
||||
it("matches Windows platform identifiers", () => {
|
||||
assert.isTrue(isWindowsPlatform("Win32"));
|
||||
assert.isTrue(isWindowsPlatform("Windows"));
|
||||
assert.isTrue(isWindowsPlatform("windows_nt"));
|
||||
});
|
||||
|
||||
it("does not match darwin", () => {
|
||||
assert.isFalse(isWindowsPlatform("darwin"));
|
||||
});
|
||||
});
|
||||
@@ -4,3 +4,11 @@ import { twMerge } from "tailwind-merge";
|
||||
export function cn(...inputs: CxOptions) {
|
||||
return twMerge(cx(inputs));
|
||||
}
|
||||
|
||||
export function isMacPlatform(platform: string): boolean {
|
||||
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||
}
|
||||
|
||||
export function isWindowsPlatform(platform: string): boolean {
|
||||
return /^win(dows)?/i.test(platform);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { isMacPlatform } from "./lib/utils";
|
||||
|
||||
export type TerminalLinkKind = "url" | "path";
|
||||
|
||||
@@ -15,10 +16,6 @@ const FILE_PATH_PATTERN =
|
||||
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
|
||||
const LAST_EDITOR_KEY = "t3code:last-editor";
|
||||
|
||||
function isMacPlatform(platform: string): boolean {
|
||||
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||
}
|
||||
|
||||
function trimClosingDelimiters(value: string): string {
|
||||
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
|
||||
if (output.length === 0) return output;
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
isTerminalClearShortcut,
|
||||
isTerminalToggleShortcut,
|
||||
type ShortcutEventLike,
|
||||
} from "./terminal-shortcuts";
|
||||
|
||||
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
|
||||
return {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isTerminalToggleShortcut", () => {
|
||||
it("matches Cmd+J on macOS", () => {
|
||||
expect(isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
|
||||
});
|
||||
|
||||
it("matches Ctrl+J on non-macOS", () => {
|
||||
expect(isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects wrong modifiers", () => {
|
||||
expect(isTerminalToggleShortcut(event({ ctrlKey: true, shiftKey: true }), "Win32")).toBe(false);
|
||||
expect(isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects non-j keys", () => {
|
||||
expect(isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalClearShortcut", () => {
|
||||
it("matches Ctrl+L on all platforms", () => {
|
||||
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux")).toBe(true);
|
||||
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel")).toBe(true);
|
||||
});
|
||||
|
||||
it("matches Cmd+K on macOS", () => {
|
||||
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects Cmd+K on non-macOS", () => {
|
||||
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects wrong modifiers", () => {
|
||||
expect(
|
||||
isTerminalClearShortcut(event({ key: "l", ctrlKey: true, shiftKey: true }), "Linux"),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isTerminalClearShortcut(event({ key: "k", metaKey: true, altKey: true }), "MacIntel"),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
export interface ShortcutEventLike {
|
||||
key: string;
|
||||
metaKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
shiftKey: boolean;
|
||||
altKey: boolean;
|
||||
}
|
||||
|
||||
function isMacPlatform(platform: string): boolean {
|
||||
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||
}
|
||||
|
||||
export function isTerminalToggleShortcut(
|
||||
event: ShortcutEventLike,
|
||||
platform = navigator.platform,
|
||||
): boolean {
|
||||
const key = event.key.toLowerCase();
|
||||
if (key !== "j") return false;
|
||||
if (event.shiftKey || event.altKey) return false;
|
||||
|
||||
if (isMacPlatform(platform)) {
|
||||
return event.metaKey && !event.ctrlKey;
|
||||
}
|
||||
|
||||
return event.ctrlKey && !event.metaKey;
|
||||
}
|
||||
|
||||
export function isTerminalClearShortcut(
|
||||
event: ShortcutEventLike,
|
||||
platform = navigator.platform,
|
||||
): boolean {
|
||||
const key = event.key.toLowerCase();
|
||||
|
||||
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
isMacPlatform(platform) &&
|
||||
key === "k" &&
|
||||
event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey
|
||||
);
|
||||
}
|
||||
@@ -139,6 +139,9 @@ export function createWsNativeApi(): NativeApi {
|
||||
return showContextMenuFallback(items, position);
|
||||
},
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
|
||||
@@ -5,5 +5,7 @@ export * from "./terminal";
|
||||
export * from "./provider";
|
||||
export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
ProjectListResult,
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -113,4 +114,7 @@ export interface NativeApi {
|
||||
position?: { x: number; y: number },
|
||||
) => Promise<T | null>;
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import {
|
||||
keybindingRuleSchema,
|
||||
keybindingsConfigSchema,
|
||||
resolvedKeybindingRuleSchema,
|
||||
resolvedKeybindingsConfigSchema,
|
||||
} from "./keybindings";
|
||||
|
||||
describe("keybindings contracts", () => {
|
||||
it("parses keybinding rules", () => {
|
||||
const parsed = keybindingRuleSchema.parse({
|
||||
key: "mod+j",
|
||||
command: "terminal.toggle",
|
||||
});
|
||||
assert.strictEqual(parsed.command, "terminal.toggle");
|
||||
});
|
||||
|
||||
it("rejects invalid command values", () => {
|
||||
assert.throws(() =>
|
||||
keybindingRuleSchema.parse({
|
||||
key: "mod+j",
|
||||
command: "invalid.command",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("parses keybindings array payload", () => {
|
||||
const parsed = keybindingsConfigSchema.parse([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
]);
|
||||
assert.lengthOf(parsed, 2);
|
||||
});
|
||||
|
||||
it("parses resolved keybinding rules", () => {
|
||||
const parsed = resolvedKeybindingRuleSchema.parse({
|
||||
command: "terminal.split",
|
||||
shortcut: {
|
||||
key: "d",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "terminalOpen" },
|
||||
right: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.strictEqual(parsed.shortcut.key, "d");
|
||||
});
|
||||
|
||||
it("parses resolved keybindings arrays", () => {
|
||||
const parsed = resolvedKeybindingsConfigSchema.parse([
|
||||
{
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.lengthOf(parsed, 1);
|
||||
});
|
||||
|
||||
it("rejects unknown fields in resolved keybinding rules", () => {
|
||||
assert.throws(() =>
|
||||
resolvedKeybindingRuleSchema.parse({
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
key: "mod+j",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const keybindingCommandSchema = z.enum([
|
||||
"terminal.toggle",
|
||||
"terminal.split",
|
||||
"terminal.new",
|
||||
"chat.new",
|
||||
"editor.openFavorite",
|
||||
]);
|
||||
|
||||
const keybindingValueSchema = z.string().trim().min(1).max(64);
|
||||
const keybindingWhenSchema = z.string().trim().min(1).max(256);
|
||||
|
||||
export const keybindingRuleSchema = z.object({
|
||||
key: keybindingValueSchema,
|
||||
command: keybindingCommandSchema,
|
||||
when: keybindingWhenSchema.optional(),
|
||||
});
|
||||
|
||||
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
|
||||
|
||||
export const keybindingShortcutSchema = z.object({
|
||||
key: z.string().trim().min(1).max(32),
|
||||
metaKey: z.boolean(),
|
||||
ctrlKey: z.boolean(),
|
||||
shiftKey: z.boolean(),
|
||||
altKey: z.boolean(),
|
||||
modKey: z.boolean(),
|
||||
}).strict();
|
||||
|
||||
export type KeybindingWhenNode =
|
||||
| { type: "identifier"; name: string }
|
||||
| { type: "not"; node: KeybindingWhenNode }
|
||||
| { type: "and"; left: KeybindingWhenNode; right: KeybindingWhenNode }
|
||||
| { type: "or"; left: KeybindingWhenNode; right: KeybindingWhenNode };
|
||||
|
||||
export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(() =>
|
||||
z.union([
|
||||
z.object({
|
||||
type: z.literal("identifier"),
|
||||
name: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("not"),
|
||||
node: keybindingWhenNodeSchema,
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("and"),
|
||||
left: keybindingWhenNodeSchema,
|
||||
right: keybindingWhenNodeSchema,
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal("or"),
|
||||
left: keybindingWhenNodeSchema,
|
||||
right: keybindingWhenNodeSchema,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
export const resolvedKeybindingRuleSchema = z.object({
|
||||
command: keybindingCommandSchema,
|
||||
shortcut: keybindingShortcutSchema,
|
||||
whenAst: keybindingWhenNodeSchema.optional(),
|
||||
}).strict();
|
||||
|
||||
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
|
||||
|
||||
export type KeybindingCommand = z.infer<typeof keybindingCommandSchema>;
|
||||
export type KeybindingRule = z.infer<typeof keybindingRuleSchema>;
|
||||
export type KeybindingsConfig = z.infer<typeof keybindingsConfigSchema>;
|
||||
export type KeybindingShortcut = z.infer<typeof keybindingShortcutSchema>;
|
||||
export type ResolvedKeybindingRule = z.infer<typeof resolvedKeybindingRuleSchema>;
|
||||
export type ResolvedKeybindingsConfig = z.infer<typeof resolvedKeybindingsConfigSchema>;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import { resolvedKeybindingsConfigSchema } from "./keybindings";
|
||||
|
||||
export const serverConfigSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
keybindings: resolvedKeybindingsConfigSchema.default([]),
|
||||
});
|
||||
|
||||
export type ServerConfig = z.infer<typeof serverConfigSchema>;
|
||||
Reference in new issue
Block a user