Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77544333e0 | ||
|
|
10ca14a362 | ||
|
|
ee203ed518 | ||
|
|
f6df16ab1e | ||
|
|
a423e3c4b1 | ||
|
|
c656e071e4 | ||
|
|
856fc61e65 | ||
|
|
3158e1dc12 | ||
|
|
a930a44212 | ||
|
|
5bfd2161be | ||
|
|
258a36a7f0 | ||
|
|
a838270400 | ||
|
|
92404ecfd8 | ||
|
|
c77e6af72a | ||
|
|
dfbfc25a8f | ||
|
|
8fb62e1ba3 | ||
|
|
c70e6b5c34 | ||
|
|
ffdacaf73d | ||
|
|
7cddaba1da | ||
|
|
035eb3b2e6 | ||
|
|
c1f87cc48b | ||
|
|
c11d0c68e7 | ||
|
|
1b7051a5d3 | ||
|
|
34379b6f5e | ||
|
|
27606a9c94 | ||
|
|
2caf6dd1be | ||
|
|
af87ceced9 | ||
|
|
9083c716ea | ||
|
|
b00deefb03 | ||
|
|
f5d4d7b63c | ||
|
|
a0e0b6ef71 | ||
|
|
3e4b357a86 | ||
|
|
0f3201e699 | ||
|
|
2c00d79902 | ||
|
|
9e52f110e2 | ||
|
|
051160cfec | ||
|
|
fdac1fbcd4 | ||
|
|
036e481ec0 | ||
|
|
29ffec87c0 | ||
|
|
6c96dc7e92 | ||
|
|
2f4fdfa03e | ||
|
|
89139e9394 | ||
|
|
fcb6b03380 | ||
|
|
b5ef318748 | ||
|
|
59af9dce68 | ||
|
|
a4472d0f49 | ||
|
|
ce72ed4eb8 | ||
|
|
5a1138cf39 | ||
|
|
618506f135 | ||
|
|
873a000567 | ||
|
|
b83af8a48e | ||
|
|
80208bc2c4 | ||
|
|
c2aba434a1 | ||
|
|
bf00c7e8a6 | ||
|
|
43b9724418 | ||
|
|
bcf070aa2c | ||
|
|
42a2275bbd | ||
|
|
5efa2df4ab | ||
|
|
e4ec3cfca7 | ||
|
|
75f0e90c03 | ||
|
|
ea8339ec90 | ||
|
|
7f81813feb | ||
|
|
c4e63e0648 | ||
|
|
4689c43c98 | ||
|
|
32e1983e61 | ||
|
|
babbf90197 | ||
|
|
8351e7ca31 | ||
|
|
d353476417 | ||
|
|
a896942bc7 | ||
|
|
cf0f731bc8 | ||
|
|
80d2b26d94 | ||
|
|
6245c547c2 | ||
|
|
24abab789e | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
c2776c2336 | ||
|
|
22f021ed69 | ||
|
|
a4964b3b36 | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"ios": {
|
||||
"bundleIdentifier": "com.juliusmarminge.-t3toolsmonorepo"
|
||||
}
|
||||
}
|
||||
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
const envEntries = [
|
||||
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", process.env.T3CODE_PORT],
|
||||
["T3CODE_HOME", process.env.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
|
||||
["T3CODE_PORT", environment.T3CODE_PORT],
|
||||
["T3CODE_HOME", environment.T3CODE_HOME],
|
||||
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
|
||||
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
|
||||
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
|
||||
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
|
||||
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
|
||||
return [
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(
|
||||
([name, value]) =>
|
||||
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
|
||||
),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
NodeFS.writeFileSync(
|
||||
targetBinaryPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -286,6 +302,12 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
if (isDevelopment) {
|
||||
// The launcher also handles protocol activations outside the dev runner,
|
||||
// so refresh its fallback environment on every launch. Never let a value
|
||||
// captured by an older parent app override the live dev-runner environment.
|
||||
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
|
||||
}
|
||||
registerMacLauncherBundle(targetAppBundlePath);
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
const script = makeDevelopmentLauncherScript({
|
||||
electronBinaryPath: "/repo/node_modules/electron/Electron",
|
||||
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
|
||||
desktopRoot: "/repo/apps/desktop",
|
||||
environment: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
|
||||
T3CODE_PORT: "16566",
|
||||
T3CODE_HOME: "/tmp/t3",
|
||||
},
|
||||
});
|
||||
|
||||
assert.include(
|
||||
script,
|
||||
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
|
||||
);
|
||||
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
|
||||
assert.include(
|
||||
script,
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,16 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
handler!(
|
||||
new Request("t3code-dev://app/api/health?verbose=1", {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
origin: "t3code-dev://app",
|
||||
referer: "t3code-dev://app/",
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -70,6 +79,11 @@ describe("ElectronProtocol", () => {
|
||||
["t3code-dev"],
|
||||
);
|
||||
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
|
||||
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
|
||||
assert.equal(forwardedHeaders.get("accept"), "application/json");
|
||||
assert.isNull(forwardedHeaders.get("origin"));
|
||||
assert.isNull(forwardedHeaders.get("referer"));
|
||||
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
|
||||
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
@@ -99,6 +113,34 @@ describe("ElectronProtocol", () => {
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("retries transient renderer target failures", () =>
|
||||
Effect.gen(function* () {
|
||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||
handleMock.mockImplementation((_scheme, nextHandler) => {
|
||||
handler = nextHandler;
|
||||
});
|
||||
netFetchMock
|
||||
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
|
||||
.mockResolvedValueOnce(new Response("ready"));
|
||||
|
||||
const response = yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const protocol = yield* ElectronProtocol.ElectronProtocol;
|
||||
yield* protocol.registerDesktopProtocol({
|
||||
scheme: "t3code-dev",
|
||||
targetOrigin: new URL("http://127.0.0.1:5733/"),
|
||||
backendOrigin: new URL("http://127.0.0.1:3773/"),
|
||||
clerkFrontendApiHostname: undefined,
|
||||
});
|
||||
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ready");
|
||||
assert.equal(netFetchMock.mock.calls.length, 2);
|
||||
}).pipe(Effect.provide(ElectronProtocol.layer)),
|
||||
);
|
||||
|
||||
it.effect("preserves protocol registration failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("protocol registration failed");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as NodeTimersPromises from "node:timers/promises";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -114,18 +115,60 @@ async function proxyRequest(
|
||||
}
|
||||
|
||||
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
|
||||
const headers = new Headers(request.headers);
|
||||
const headersToRemove: string[] = [];
|
||||
for (const name of headers.keys()) {
|
||||
if (
|
||||
name === "host" ||
|
||||
name === "origin" ||
|
||||
name === "referer" ||
|
||||
name === "connection" ||
|
||||
name === "content-length" ||
|
||||
name === "accept-encoding" ||
|
||||
name === "upgrade-insecure-requests" ||
|
||||
name.startsWith("sec-fetch-")
|
||||
) {
|
||||
headersToRemove.push(name);
|
||||
}
|
||||
}
|
||||
for (const name of headersToRemove) {
|
||||
headers.delete(name);
|
||||
}
|
||||
const init: RequestInit = {
|
||||
method: request.method,
|
||||
headers: request.headers,
|
||||
headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: await Electron.net.fetch(targetUrl.toString(), init);
|
||||
return withContentSecurityPolicy(response, contentSecurityPolicy);
|
||||
}
|
||||
|
||||
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
|
||||
|
||||
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
|
||||
if (delayMs > 0) {
|
||||
await NodeTimersPromises.setTimeout(delayMs);
|
||||
}
|
||||
|
||||
try {
|
||||
return await Electron.net.fetch(url, init);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registered = yield* Ref.make(false);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -18,16 +19,25 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
|
||||
vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
const {
|
||||
createFromPath,
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
mkdir,
|
||||
showItemInFolder,
|
||||
webviewSend,
|
||||
writeFile,
|
||||
writeImage,
|
||||
} = vi.hoisted(() => ({
|
||||
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
|
||||
fromId: vi.fn(() => null),
|
||||
getFocusedWebContents: vi.fn(() => null),
|
||||
mkdir: vi.fn((_path: string) => undefined),
|
||||
showItemInFolder: vi.fn(),
|
||||
webviewSend: vi.fn(),
|
||||
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
|
||||
writeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -44,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -81,6 +92,7 @@ const layer = PreviewManager.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(fileSystemLayer),
|
||||
Layer.provideMerge(Path.layer),
|
||||
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
|
||||
);
|
||||
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
|
||||
|
||||
@@ -97,6 +109,8 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -250,6 +264,197 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
let zoomReadable = true;
|
||||
let url = "https://example.com";
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => {
|
||||
if (!zoomReadable) throw new Error("zoom unavailable");
|
||||
return effectiveZoom;
|
||||
},
|
||||
setZoomFactor,
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.navStatus).toEqual({
|
||||
kind: "Success",
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 43,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: replacementSetZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const url = "http://localhost:5733/";
|
||||
let loading = false;
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => url,
|
||||
getTitle: () => "localhost:5733",
|
||||
isLoading: () => loading,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const statuses: PreviewManager.PreviewNavStatus[] = [];
|
||||
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
statuses.push(state.navStatus);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_failed");
|
||||
yield* manager.registerWebview("tab_failed", 42);
|
||||
|
||||
listeners.get("did-fail-load")?.(
|
||||
{},
|
||||
-105,
|
||||
"ERR_NAME_NOT_RESOLVED",
|
||||
"https://missing-frame.example/",
|
||||
false,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
listeners.get("did-stop-loading")?.();
|
||||
listeners.get("page-title-updated")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)).toEqual({
|
||||
kind: "LoadFailed",
|
||||
url,
|
||||
title: "localhost:5733",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
});
|
||||
|
||||
loading = true;
|
||||
listeners.get("did-start-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Loading");
|
||||
|
||||
loading = false;
|
||||
listeners.get("did-stop-loading")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
|
||||
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
|
||||
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
expect(statuses.at(-1)?.kind).toBe("Success");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -511,6 +716,178 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("types in background webviews and enables native key input", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let failKeyDown = false;
|
||||
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
|
||||
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
|
||||
if (
|
||||
failKeyDown &&
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
throw new Error("key dispatch failed");
|
||||
}
|
||||
if (
|
||||
method === "Input.dispatchKeyEvent" &&
|
||||
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
|
||||
) {
|
||||
humanInput?.(
|
||||
{},
|
||||
{
|
||||
kind: "key",
|
||||
key: params["key"],
|
||||
code: params["code"] ?? "Digit1",
|
||||
},
|
||||
);
|
||||
}
|
||||
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
|
||||
});
|
||||
const restoreFocus = vi.fn();
|
||||
const focus = vi.fn();
|
||||
getFocusedWebContents.mockReturnValue({
|
||||
id: 7,
|
||||
isDestroyed: () => false,
|
||||
focus: restoreFocus,
|
||||
} as never);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
isDevToolsOpened: () => false,
|
||||
focus,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof humanInput) => {
|
||||
if (channel === "preview:human-input") humanInput = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_input");
|
||||
yield* manager.registerWebview("tab_input", 42);
|
||||
yield* manager.automationType("tab_input", { text: "hello", clear: true });
|
||||
yield* manager.automationType("tab_input", { text: "", clear: true });
|
||||
yield* manager.automationPress("tab_input", { key: "x" });
|
||||
|
||||
const calls = sendCommand.mock.calls;
|
||||
const methods = calls.map(([method]) => method);
|
||||
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
|
||||
const focusOnIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
|
||||
);
|
||||
const keyDownIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
|
||||
);
|
||||
const keyUpIndex = calls.findIndex(
|
||||
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
);
|
||||
const focusOffIndex = calls.findIndex(
|
||||
([method, params]) =>
|
||||
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
|
||||
);
|
||||
const typeEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('document.execCommand("insertText"'),
|
||||
);
|
||||
expect(typeEvaluation).toBeDefined();
|
||||
const clearOnlyEvaluation = sendCommand.mock.calls.find(
|
||||
([method, params]) =>
|
||||
method === "Runtime.evaluate" &&
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"expression" in params &&
|
||||
typeof params.expression === "string" &&
|
||||
params.expression.includes('const text = ""') &&
|
||||
params.expression.includes("Object.getOwnPropertyDescriptor"),
|
||||
);
|
||||
expect(clearOnlyEvaluation).toBeDefined();
|
||||
expect(methods).not.toContain("Input.insertText");
|
||||
expect(enableIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(focus).toHaveBeenCalledOnce();
|
||||
expect(restoreFocus).toHaveBeenCalledOnce();
|
||||
expect(methods).toContain("Page.bringToFront");
|
||||
expect(enableIndex).toBeLessThan(focusOnIndex);
|
||||
expect(focusOnIndex).toBeLessThan(keyDownIndex);
|
||||
expect(keyDownIndex).toBeLessThan(keyUpIndex);
|
||||
expect(keyUpIndex).toBeLessThan(focusOffIndex);
|
||||
expect(
|
||||
calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = true;
|
||||
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
|
||||
|
||||
expect(Exit.isFailure(failedPress)).toBe(true);
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyUp",
|
||||
key: "y",
|
||||
code: "KeyY",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 89,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
|
||||
enabled: false,
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
sendCommand.mock.calls.filter(
|
||||
([method, params]) =>
|
||||
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
sendCommand.mockClear();
|
||||
failKeyDown = false;
|
||||
yield* manager.automationPress("tab_input", { key: "!" });
|
||||
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
|
||||
type: "keyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "!",
|
||||
unmodifiedText: "!",
|
||||
});
|
||||
expect(restoreFocus).toHaveBeenCalledTimes(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -378,6 +380,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
artifactDirectory: string,
|
||||
) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const path = yield* Path.Path;
|
||||
const parentScope = yield* Scope.Scope;
|
||||
const context = yield* Effect.context<never>();
|
||||
@@ -854,11 +857,24 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
commandParams?: Record<string, unknown>,
|
||||
) => Effect.Effect<unknown, PreviewManagerError>;
|
||||
|
||||
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
|
||||
send: SendCommand,
|
||||
enableRuntime: boolean,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
...(enableRuntime ? [send("Runtime.enable")] : []),
|
||||
send("Input.setIgnoreInputEvents", { ignore: false }),
|
||||
],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
action: string,
|
||||
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -899,7 +915,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
return yield* use(send);
|
||||
// Cleanup commands must still run after human input invalidates the action's
|
||||
// control epoch. Otherwise a partially dispatched input can leave Chromium
|
||||
// with a held key or focus emulation enabled for subsequent actions.
|
||||
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
|
||||
function* (method, commandParams) {
|
||||
return yield* attemptPromise(
|
||||
{
|
||||
operation: `${action}.cleanup.${method}`,
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand(method, commandParams),
|
||||
);
|
||||
},
|
||||
);
|
||||
return yield* use(send, sendCleanup);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1091,22 +1122,62 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
|
||||
() => wc.getZoomFactor(),
|
||||
).pipe(Effect.option);
|
||||
const computedNavStatus = computeNavStatus(wc);
|
||||
const canGoBack = wc.navigationHistory.canGoBack();
|
||||
const canGoForward = wc.navigationHistory.canGoForward();
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
const navStatus =
|
||||
preserveLoadFailure &&
|
||||
current.navStatus.kind === "LoadFailed" &&
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
description: string,
|
||||
validatedUrl: string,
|
||||
isMainFrame: boolean,
|
||||
): void => {
|
||||
if (code === -3 || !isMainFrame) return;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: wc.getURL(),
|
||||
url: validatedUrl || wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1161,8 +1232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1173,8 +1244,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-navigate", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1280,21 +1351,40 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
);
|
||||
yield* update(tabId, { zoomFactor });
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
}
|
||||
const zoomFactor =
|
||||
replacedWebContentsId !== null
|
||||
? yield* attempt(
|
||||
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
|
||||
() => {
|
||||
wc.setZoomFactor(tab.zoomFactor);
|
||||
return tab.zoomFactor;
|
||||
},
|
||||
)
|
||||
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
@@ -1313,6 +1403,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor,
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
@@ -1330,11 +1421,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
@@ -1946,10 +2032,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
yield* prepareAutomationInput(send, true);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2011,7 +2094,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2021,8 +2104,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const locatorJson = locator
|
||||
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
|
||||
: null;
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
const result = yield* evaluateWithDebugger<
|
||||
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
|
||||
| { ok: true }
|
||||
| { invalidSelector: true; message: string }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2030,12 +2120,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
try {
|
||||
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
|
||||
if (!element) return { notFound: true };
|
||||
const textControl =
|
||||
element instanceof HTMLTextAreaElement ||
|
||||
(element instanceof HTMLInputElement &&
|
||||
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
|
||||
const editable = textControl || element.isContentEditable;
|
||||
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
|
||||
element.focus();
|
||||
if (${input.clear ?? false}) {
|
||||
if ("value" in element) element.value = "";
|
||||
else if (element.isContentEditable) element.textContent = "";
|
||||
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
||||
if (document.activeElement !== element) return { notEditable: true };
|
||||
const clear = ${input.clear ?? false};
|
||||
if (clear) {
|
||||
if (textControl) {
|
||||
element.select();
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const selection = document.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
const text = ${textJson};
|
||||
let inserted = true;
|
||||
if (text.length > 0) {
|
||||
inserted = document.execCommand("insertText", false, text);
|
||||
} else if (clear) {
|
||||
document.execCommand("delete", false);
|
||||
const cleared = textControl
|
||||
? element.value.length === 0
|
||||
: (element.textContent ?? "").length === 0;
|
||||
if (!cleared) {
|
||||
if (textControl) {
|
||||
const prototype = element instanceof HTMLTextAreaElement
|
||||
? HTMLTextAreaElement.prototype
|
||||
: HTMLInputElement.prototype;
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
||||
if (valueSetter) valueSetter.call(element, "");
|
||||
else element.value = "";
|
||||
} else {
|
||||
element.replaceChildren();
|
||||
}
|
||||
element.dispatchEvent(new InputEvent("input", {
|
||||
bubbles: true,
|
||||
inputType: "deleteContentBackward",
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (!inserted) return { notEditable: true };
|
||||
element.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { invalidSelector: true, message: String(error) };
|
||||
@@ -2059,6 +2191,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
if ("notEditable" in result) {
|
||||
return yield* new PreviewAutomationTargetNotEditableError({
|
||||
tabId,
|
||||
...automationSelectorDiagnostics(input),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
|
||||
@@ -2066,23 +2204,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* send("Runtime.enable");
|
||||
yield* focusAutomationTarget(tabId, send, input);
|
||||
yield* send("Input.insertText", { text: input.text });
|
||||
const textJson = yield* encodeJson(
|
||||
{ operation: "automationType.encodeText", tabId },
|
||||
input.text,
|
||||
);
|
||||
yield* evaluateWithDebugger(
|
||||
tabId,
|
||||
send,
|
||||
`(() => {
|
||||
const element = document.activeElement;
|
||||
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
|
||||
element?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
})()`,
|
||||
false,
|
||||
);
|
||||
// CDP Input.insertText silently drops text until Electron has activated a hidden
|
||||
// guest WebContents with a pointer event. Editing in the page runtime keeps
|
||||
// background automation deterministic without stealing foreground app focus.
|
||||
yield* typeIntoAutomationTarget(tabId, send, input);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2097,32 +2222,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
|
||||
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
|
||||
tabId: string,
|
||||
wc: Electron.WebContents,
|
||||
input: PreviewAutomationPressInput,
|
||||
send: SendCommand,
|
||||
sendCleanup: SendCommand,
|
||||
) {
|
||||
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
yield* prepareAutomationInput(send, false);
|
||||
const keySequence = makePreviewAutomationKeySequence(input, {
|
||||
isMac: hostPlatform === "darwin",
|
||||
});
|
||||
const previouslyFocused = yield* attempt(
|
||||
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
|
||||
() => webContents.getFocusedWebContents(),
|
||||
);
|
||||
let keyDownAttempted = false;
|
||||
const releaseInput = Effect.gen(function* () {
|
||||
if (keyDownAttempted) {
|
||||
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
|
||||
}
|
||||
}, 0);
|
||||
const key = input.key;
|
||||
const text = key.length === 1 ? key : undefined;
|
||||
const params = {
|
||||
key,
|
||||
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
|
||||
modifiers,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
};
|
||||
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
|
||||
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
|
||||
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "automationPress.restoreFocusedWebContents",
|
||||
tabId,
|
||||
webContentsId: previouslyFocused.id,
|
||||
},
|
||||
() => previouslyFocused.focus(),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
// Focus the guest WebContents itself, not its containing BrowserWindow. This
|
||||
// activates native keyboard behavior for hidden/background previews without
|
||||
// changing which thread is mounted in the UI. Restore the previous renderer
|
||||
// after dispatch so automation never leaves the app's input focus behind.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* attempt(
|
||||
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
|
||||
() => wc.focus(),
|
||||
);
|
||||
yield* send("Page.bringToFront");
|
||||
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
|
||||
yield* expectAgentInput(tabId, keySequence.signal);
|
||||
keyDownAttempted = true;
|
||||
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
|
||||
}).pipe(Effect.ensuring(releaseInput));
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2130,8 +2277,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2529,6 +2676,20 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
|
||||
"PreviewAutomationTargetNotEditableError",
|
||||
{
|
||||
tabId: Schema.String,
|
||||
selectorKind: PreviewAutomationSelectorKind,
|
||||
selectorLength: Schema.optionalKey(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
|
||||
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
|
||||
"PreviewAutomationCoordinatesOutsideViewportError",
|
||||
{
|
||||
@@ -2631,6 +2792,7 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
describe("preview keyboard packets", () => {
|
||||
it("includes the Chromium virtual key code and Enter text", () => {
|
||||
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
|
||||
keyDown: {
|
||||
type: "keyDown",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
text: "\r",
|
||||
unmodifiedText: "\r",
|
||||
},
|
||||
keyUp: {
|
||||
type: "keyUp",
|
||||
key: "Enter",
|
||||
code: "Enter",
|
||||
modifiers: 0,
|
||||
windowsVirtualKeyCode: 13,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
},
|
||||
signal: { kind: "key", key: "Enter", code: "Enter" },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches printable keys as text key-down events", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "z" });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
type: "keyDown",
|
||||
key: "z",
|
||||
code: "KeyZ",
|
||||
windowsVirtualKeyCode: 90,
|
||||
text: "z",
|
||||
});
|
||||
expect(sequence.keyUp).not.toHaveProperty("text");
|
||||
});
|
||||
|
||||
it("suppresses text and uses raw key-down for shortcuts", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
|
||||
).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "a",
|
||||
code: "KeyA",
|
||||
modifiers: 4,
|
||||
windowsVirtualKeyCode: 65,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
commands: ["selectAll"],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps common macOS editing shortcuts without changing other platforms", () => {
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
|
||||
.keyDown.commands,
|
||||
).toEqual(["redo"]);
|
||||
expect(
|
||||
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
|
||||
).not.toHaveProperty("commands");
|
||||
});
|
||||
|
||||
it("resolves shifted printable keys to their browser values", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
|
||||
expect(sequence.keyDown).toMatchObject({
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 8,
|
||||
windowsVirtualKeyCode: 49,
|
||||
text: "!",
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
|
||||
it("keeps shifted key values while suppressing text for modified chords", () => {
|
||||
const sequence = makePreviewAutomationKeySequence({
|
||||
key: "1",
|
||||
modifiers: ["Control", "Shift"],
|
||||
});
|
||||
expect(sequence.keyDown).toEqual({
|
||||
type: "rawKeyDown",
|
||||
key: "!",
|
||||
code: "Digit1",
|
||||
modifiers: 10,
|
||||
windowsVirtualKeyCode: 49,
|
||||
location: 0,
|
||||
isKeypad: false,
|
||||
});
|
||||
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
|
||||
|
||||
interface KeyDefinition {
|
||||
readonly code: string;
|
||||
readonly key: string;
|
||||
readonly keyCode: number;
|
||||
readonly text?: string;
|
||||
readonly location?: number;
|
||||
readonly shiftedKey?: string;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeyEvent {
|
||||
readonly [key: string]: unknown;
|
||||
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
readonly modifiers: number;
|
||||
readonly windowsVirtualKeyCode: number;
|
||||
readonly location: number;
|
||||
readonly isKeypad: boolean;
|
||||
readonly text?: string;
|
||||
readonly unmodifiedText?: string;
|
||||
readonly commands?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface PreviewAutomationKeySequence {
|
||||
readonly keyDown: PreviewAutomationKeyEvent;
|
||||
readonly keyUp: PreviewAutomationKeyEvent;
|
||||
readonly signal: {
|
||||
readonly kind: "key";
|
||||
readonly key: string;
|
||||
readonly code: string;
|
||||
};
|
||||
}
|
||||
|
||||
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
|
||||
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
|
||||
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
|
||||
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
|
||||
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
|
||||
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
|
||||
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
|
||||
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
|
||||
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
|
||||
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
|
||||
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
|
||||
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
|
||||
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
|
||||
End: { code: "End", key: "End", keyCode: 35 },
|
||||
Home: { code: "Home", key: "Home", keyCode: 36 },
|
||||
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
|
||||
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
|
||||
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
|
||||
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
|
||||
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
|
||||
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
|
||||
};
|
||||
|
||||
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
|
||||
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
|
||||
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
|
||||
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
|
||||
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
|
||||
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
|
||||
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
|
||||
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
|
||||
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
|
||||
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
|
||||
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
|
||||
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
|
||||
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
|
||||
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
|
||||
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
|
||||
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
|
||||
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
|
||||
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
|
||||
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
|
||||
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
|
||||
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
|
||||
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Chromium does not infer macOS editing commands from synthetic Meta chords.
|
||||
* Keep the common browser editing/navigation shortcuts explicit so dispatched
|
||||
* key events behave like their physical-key equivalents.
|
||||
*/
|
||||
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
|
||||
"Meta+Backspace": "deleteToBeginningOfLine",
|
||||
"Meta+ArrowUp": "moveToBeginningOfDocument",
|
||||
"Meta+ArrowDown": "moveToEndOfDocument",
|
||||
"Meta+ArrowLeft": "moveToLeftEndOfLine",
|
||||
"Meta+ArrowRight": "moveToRightEndOfLine",
|
||||
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
|
||||
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
|
||||
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
|
||||
"Meta+KeyA": "selectAll",
|
||||
"Meta+KeyC": "copy",
|
||||
"Meta+KeyX": "cut",
|
||||
"Meta+KeyV": "paste",
|
||||
"Meta+KeyZ": "undo",
|
||||
"Shift+Meta+KeyZ": "redo",
|
||||
};
|
||||
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
|
||||
|
||||
const macEditingCommands = (
|
||||
code: string,
|
||||
modifiers: PreviewAutomationPressInput["modifiers"],
|
||||
): ReadonlyArray<string> => {
|
||||
const shortcut = [
|
||||
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
|
||||
code,
|
||||
].join("+");
|
||||
const command = MAC_EDITING_COMMANDS[shortcut];
|
||||
return command ? [command] : [];
|
||||
};
|
||||
|
||||
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
|
||||
(modifiers ?? []).reduce((value, modifier) => {
|
||||
switch (modifier) {
|
||||
case "Alt":
|
||||
return value | 1;
|
||||
case "Control":
|
||||
return value | 2;
|
||||
case "Meta":
|
||||
return value | 4;
|
||||
case "Shift":
|
||||
return value | 8;
|
||||
}
|
||||
}, 0);
|
||||
|
||||
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
|
||||
const named = NAMED_KEYS[input.key];
|
||||
if (named) return named;
|
||||
|
||||
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
|
||||
if (functionKey) {
|
||||
const number = Number(functionKey[1]);
|
||||
return { code: input.key, key: input.key, keyCode: 111 + number };
|
||||
}
|
||||
|
||||
if (/^[a-z]$/i.test(input.key)) {
|
||||
const upper = input.key.toUpperCase();
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key = shifted || input.key === upper ? upper : input.key;
|
||||
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
|
||||
}
|
||||
|
||||
const printable = PRINTABLE_KEYS.find(
|
||||
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
|
||||
);
|
||||
if (printable) {
|
||||
const shifted = input.modifiers?.includes("Shift") ?? false;
|
||||
const key =
|
||||
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
|
||||
? printable.shiftedKey
|
||||
: printable.key;
|
||||
return { ...printable, key, text: key };
|
||||
}
|
||||
|
||||
return {
|
||||
code: input.key.length > 1 ? input.key : "",
|
||||
key: input.key,
|
||||
keyCode: 0,
|
||||
...(input.key.length === 1 ? { text: input.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Chromium CDP key packets using the same required fields and down-event
|
||||
* choice as Playwright's pinned Chromium keyboard implementation.
|
||||
*/
|
||||
export function makePreviewAutomationKeySequence(
|
||||
input: PreviewAutomationPressInput,
|
||||
options?: { readonly isMac?: boolean },
|
||||
): PreviewAutomationKeySequence {
|
||||
const definition = resolveKeyDefinition(input);
|
||||
const modifiers = modifierMask(input.modifiers);
|
||||
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
|
||||
const text = suppressText ? "" : (definition.text ?? "");
|
||||
const location = definition.location ?? 0;
|
||||
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
|
||||
const shared = {
|
||||
key: definition.key,
|
||||
code: definition.code,
|
||||
modifiers,
|
||||
windowsVirtualKeyCode: definition.keyCode,
|
||||
location,
|
||||
isKeypad: location === 3,
|
||||
};
|
||||
|
||||
return {
|
||||
keyDown: {
|
||||
type: text ? "keyDown" : "rawKeyDown",
|
||||
...shared,
|
||||
...(text ? { text, unmodifiedText: text } : {}),
|
||||
...(commands.length > 0 ? { commands } : {}),
|
||||
},
|
||||
keyUp: { type: "keyUp", ...shared },
|
||||
signal: { kind: "key", key: definition.key, code: definition.code },
|
||||
};
|
||||
}
|
||||
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
import { vi } from "vite-plus/test";
|
||||
@@ -47,12 +48,14 @@ function makeFakeBrowserWindow() {
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
getURL: vi.fn(() => "t3code-dev://app/"),
|
||||
isLoadingMainFrame: vi.fn(() => false),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
webContentsListeners.set(eventName, listener);
|
||||
}),
|
||||
once: vi.fn(),
|
||||
openDevTools: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
replaceMisspelling: vi.fn(),
|
||||
send: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
@@ -79,6 +82,7 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -237,6 +241,73 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers when the development renderer is temporarily unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady;
|
||||
|
||||
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
|
||||
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
|
||||
if (!didFailLoad || !didFinishLoad) {
|
||||
return yield* Effect.die("renderer load listeners were not registered");
|
||||
}
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
|
||||
|
||||
yield* TestClock.adjust(100);
|
||||
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
|
||||
["t3code-dev://app/"],
|
||||
["t3code-dev://app/"],
|
||||
]);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
|
||||
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
|
||||
didFinishLoad();
|
||||
yield* TestClock.adjust(250);
|
||||
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
|
||||
assert.equal(fakeWindow.reload.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it("retries only transient failures for the development renderer", () => {
|
||||
assert.isTrue(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -3,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "t3code-dev://app/",
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl: "t3code-dev://app/",
|
||||
errorCode: -102,
|
||||
isMainFrame: true,
|
||||
validatedUrl: "https://example.com/",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -22,6 +23,16 @@ const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
|
||||
-102, // ERR_CONNECTION_REFUSED
|
||||
-105, // ERR_NAME_NOT_RESOLVED
|
||||
-106, // ERR_INTERNET_DISCONNECTED
|
||||
-118, // ERR_CONNECTION_TIMED_OUT
|
||||
]);
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
Electron.BrowserWindowConstructorOptions,
|
||||
@@ -86,6 +97,22 @@ export function isSameOriginRendererNavigation(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRetryableDevelopmentRendererLoadFailure(input: {
|
||||
readonly applicationUrl: string;
|
||||
readonly errorCode: number;
|
||||
readonly isMainFrame: boolean;
|
||||
readonly validatedUrl: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isMainFrame &&
|
||||
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
|
||||
isSameOriginRendererNavigation({
|
||||
applicationUrl: input.applicationUrl,
|
||||
navigationUrl: input.validatedUrl,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(
|
||||
shouldUseDarkColors: boolean,
|
||||
platform: NodeJS.Platform,
|
||||
@@ -152,6 +179,7 @@ export const make = Effect.gen(function* () {
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const state = yield* DesktopState.DesktopState;
|
||||
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
|
||||
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
|
||||
@@ -277,7 +305,61 @@ export const make = Effect.gen(function* () {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
}
|
||||
const retryFiber = developmentLoadRetryFiber;
|
||||
developmentLoadRetryFiber = undefined;
|
||||
runFork(Fiber.interrupt(retryFiber));
|
||||
};
|
||||
const loadApplication = () => {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
void window.loadURL(applicationUrl).catch(() => undefined);
|
||||
};
|
||||
const scheduleDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const retryIndex = Math.min(
|
||||
developmentLoadRetryIndex,
|
||||
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
|
||||
);
|
||||
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
|
||||
developmentLoadRetryIndex += 1;
|
||||
developmentLoadRetryFiber = runFork(
|
||||
Effect.sleep(retryInMs).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
developmentLoadRetryFiber = undefined;
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return retryInMs;
|
||||
};
|
||||
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
if (
|
||||
environment.isDevelopment &&
|
||||
!isSameOriginRendererNavigation({
|
||||
applicationUrl,
|
||||
navigationUrl: window.webContents.getURL(),
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearDevelopmentLoadRetry();
|
||||
developmentLoadRetryIndex = 0;
|
||||
window.setTitle(environment.displayName);
|
||||
});
|
||||
window.webContents.on(
|
||||
@@ -286,11 +368,22 @@ export const make = Effect.gen(function* () {
|
||||
if (!isMainFrame) {
|
||||
return;
|
||||
}
|
||||
const retryInMs =
|
||||
environment.isDevelopment &&
|
||||
isRetryableDevelopmentRendererLoadFailure({
|
||||
applicationUrl,
|
||||
errorCode,
|
||||
isMainFrame,
|
||||
validatedUrl: validatedURL,
|
||||
})
|
||||
? scheduleDevelopmentLoadRetry()
|
||||
: undefined;
|
||||
void runPromise(
|
||||
logWindowWarning("main window failed to load", {
|
||||
errorCode,
|
||||
errorDescription,
|
||||
url: validatedURL,
|
||||
...(retryInMs === undefined ? {} : { retryInMs }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -312,14 +405,13 @@ export const make = Effect.gen(function* () {
|
||||
void runPromise(electronWindow.reveal(window));
|
||||
});
|
||||
|
||||
loadApplication();
|
||||
if (environment.isDevelopment) {
|
||||
void window.loadURL(applicationUrl);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(applicationUrl);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
clearDevelopmentLoadRetry();
|
||||
void runPromise(electronWindow.clearMain(Option.some(window)));
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^6.0.4"
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.7",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
included:
|
||||
- ios/T3Code
|
||||
- modules/t3-composer-editor/ios
|
||||
- modules/t3-native-controls/ios
|
||||
- modules/t3-terminal/ios
|
||||
- modules/t3-review-diff/ios
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const VARIANT_CONFIG: Record<
|
||||
readonly iosIcon: string;
|
||||
readonly iosBundleIdentifier: string;
|
||||
readonly androidPackage: string;
|
||||
readonly relyingParty?: string;
|
||||
}
|
||||
> = {
|
||||
development: {
|
||||
@@ -25,6 +26,7 @@ const VARIANT_CONFIG: Record<
|
||||
iosIcon: "./assets/icon-composer-dev.icon",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.dev",
|
||||
androidPackage: "com.t3tools.t3code.dev",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
},
|
||||
preview: {
|
||||
appName: "T3 Code Preview",
|
||||
@@ -32,6 +34,7 @@ const VARIANT_CONFIG: Record<
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
iosBundleIdentifier: "com.t3tools.t3code.preview",
|
||||
androidPackage: "com.t3tools.t3code.preview",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
},
|
||||
production: {
|
||||
appName: "T3 Code",
|
||||
@@ -39,6 +42,7 @@ const VARIANT_CONFIG: Record<
|
||||
iosIcon: "./assets/icon-composer-prod.icon",
|
||||
iosBundleIdentifier: "com.t3tools.t3code",
|
||||
androidPackage: "com.t3tools.t3code",
|
||||
relyingParty: "clerk.t3.codes",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -77,6 +81,10 @@ const config: ExpoConfig = {
|
||||
icon: variant.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
associatedDomains: [
|
||||
`applinks:${variant.relyingParty}`,
|
||||
`webcredentials:${variant.relyingParty}`,
|
||||
],
|
||||
infoPlist: {
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
@@ -101,7 +109,6 @@ const config: ExpoConfig = {
|
||||
favicon: "./assets/favicon.png",
|
||||
},
|
||||
plugins: [
|
||||
"expo-router",
|
||||
"expo-font",
|
||||
"expo-secure-store",
|
||||
["@clerk/expo", { theme: "./clerk-theme.json" }],
|
||||
@@ -139,6 +146,7 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
],
|
||||
"./plugins/withIosCocoaPodsUuidCache.cjs",
|
||||
[
|
||||
"expo-widgets",
|
||||
{
|
||||
@@ -155,6 +163,7 @@ const config: ExpoConfig = {
|
||||
],
|
||||
},
|
||||
],
|
||||
"./plugins/withIosSceneLifecycle.cjs",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
],
|
||||
extra: {
|
||||
|
||||
@@ -1,2 +1,6 @@
|
||||
import "react-native-gesture-handler";
|
||||
import "expo-router/entry";
|
||||
import { registerRootComponent } from "expo";
|
||||
|
||||
import App from "./src/App";
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -5,14 +5,8 @@ public class T3ComposerEditorModule: Module {
|
||||
Name("T3ComposerEditor")
|
||||
|
||||
View(T3ComposerEditorView.self) {
|
||||
Prop("value") { (view: T3ComposerEditorView, value: String) in
|
||||
view.setValue(value)
|
||||
}
|
||||
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
|
||||
view.setSelectionJson(selectionJson)
|
||||
Prop("controlledDocumentJson") { (view: T3ComposerEditorView, documentJson: String) in
|
||||
view.setControlledDocumentJson(documentJson)
|
||||
}
|
||||
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
|
||||
view.setThemeJson(themeJson)
|
||||
@@ -53,6 +47,7 @@ public class T3ComposerEditorModule: Module {
|
||||
"onComposerSelectionChange",
|
||||
"onComposerFocus",
|
||||
"onComposerBlur",
|
||||
"onComposerSubmit",
|
||||
"onComposerPasteImages",
|
||||
"onComposerContentSizeChange"
|
||||
)
|
||||
|
||||
@@ -15,6 +15,14 @@ private struct ComposerSelectionPayload: Decodable {
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ComposerControlledDocumentPayload: Decodable {
|
||||
let value: String
|
||||
let selection: ComposerSelectionPayload?
|
||||
let tokensJson: String
|
||||
let mostRecentEventCount: Int
|
||||
let isNativeEcho: Bool
|
||||
}
|
||||
|
||||
private struct ComposerThemePayload: Decodable {
|
||||
let text: String
|
||||
let placeholder: String
|
||||
@@ -55,6 +63,24 @@ private final class ComposerTextView: UITextView {
|
||||
|
||||
var onPasteImages: (([String]) -> Void)?
|
||||
var onAttributedMutation: (() -> Void)?
|
||||
var onSubmit: (() -> Void)?
|
||||
|
||||
override var keyCommands: [UIKeyCommand]? {
|
||||
var commands = super.keyCommands ?? []
|
||||
let submit = UIKeyCommand(
|
||||
input: "\r",
|
||||
modifierFlags: .command,
|
||||
action: #selector(submitMessage(_:))
|
||||
)
|
||||
submit.discoverabilityTitle = "Send Message"
|
||||
submit.wantsPriorityOverSystemBehavior = true
|
||||
commands.append(submit)
|
||||
return commands
|
||||
}
|
||||
|
||||
@objc private func submitMessage(_ sender: UIKeyCommand) {
|
||||
onSubmit?()
|
||||
}
|
||||
|
||||
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
||||
if action == #selector(paste(_:)) {
|
||||
@@ -281,6 +307,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
private var shouldAutoFocus = false
|
||||
private var didAutoFocus = false
|
||||
private var isApplyingControlledValue = false
|
||||
private var nativeEventCount = 0
|
||||
private var lastContentSize = CGSize.zero
|
||||
private var iconImages: [String: UIImage] = [:]
|
||||
private var pendingIconUris = Set<String>()
|
||||
@@ -290,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
let onComposerSelectionChange = EventDispatcher()
|
||||
let onComposerFocus = EventDispatcher()
|
||||
let onComposerBlur = EventDispatcher()
|
||||
let onComposerSubmit = EventDispatcher()
|
||||
let onComposerPasteImages = EventDispatcher()
|
||||
let onComposerContentSizeChange = EventDispatcher()
|
||||
|
||||
@@ -311,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
textView.onAttributedMutation = { [weak self] in
|
||||
self?.emitTextChange()
|
||||
}
|
||||
textView.onSubmit = { [weak self] in
|
||||
self?.onComposerSubmit([:])
|
||||
}
|
||||
addSubview(textView)
|
||||
|
||||
placeholderLabel.numberOfLines = 0
|
||||
@@ -350,32 +381,28 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
func setValue(_ value: String) {
|
||||
self.value = value
|
||||
applyControlledDocument(force: tokensNeedRebuild)
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensJson(_ tokensJson: String) {
|
||||
guard self.tokensJson != tokensJson else {
|
||||
func setControlledDocumentJson(_ documentJson: String) {
|
||||
guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
|
||||
document.mostRecentEventCount >= nativeEventCount else {
|
||||
return
|
||||
}
|
||||
self.tokensJson = tokensJson
|
||||
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
|
||||
tokensNeedRebuild = true
|
||||
applyControlledDocument(force: true)
|
||||
if document.isNativeEcho && textView.serializedText() != document.value {
|
||||
return
|
||||
}
|
||||
if tokensJson != document.tokensJson {
|
||||
tokensJson = document.tokensJson
|
||||
tokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
|
||||
tokensNeedRebuild = true
|
||||
}
|
||||
value = document.value
|
||||
requestedSelection = document.selection
|
||||
applyControlledDocument(force: tokensNeedRebuild)
|
||||
applyRequestedSelection()
|
||||
if tokensMatchCurrentValue() {
|
||||
tokensNeedRebuild = false
|
||||
}
|
||||
}
|
||||
|
||||
func setSelectionJson(_ selectionJson: String) {
|
||||
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
|
||||
applyRequestedSelection()
|
||||
}
|
||||
|
||||
func setThemeJson(_ themeJson: String) {
|
||||
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
|
||||
return
|
||||
@@ -700,18 +727,23 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
}
|
||||
value = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
nativeEventCount += 1
|
||||
onComposerChange([
|
||||
"value": value,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
"eventCount": nativeEventCount,
|
||||
])
|
||||
updatePlaceholderVisibility()
|
||||
emitContentSizeIfNeeded()
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
let currentValue = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
onComposerSelectionChange([
|
||||
"value": currentValue,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
"eventCount": nativeEventCount,
|
||||
])
|
||||
}
|
||||
|
||||
@@ -752,6 +784,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
self.requestedSelection = nil
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3HeaderButtonView: ExpoView {
|
||||
private static let size: CGFloat = 44
|
||||
private static let symbolSize: CGFloat = 18
|
||||
|
||||
private let button = UIButton(type: .system)
|
||||
private var systemImage = "circle"
|
||||
|
||||
let onTriggered = EventDispatcher()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
|
||||
isAccessibilityElement = false
|
||||
button.frame = bounds
|
||||
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
|
||||
addSubview(button)
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
public override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: Self.size, height: Self.size)
|
||||
}
|
||||
|
||||
public func setLabel(_ label: String) {
|
||||
button.accessibilityLabel = label
|
||||
}
|
||||
|
||||
public func setSystemImage(_ systemImage: String) {
|
||||
guard self.systemImage != systemImage else {
|
||||
return
|
||||
}
|
||||
self.systemImage = systemImage
|
||||
applyConfiguration()
|
||||
}
|
||||
|
||||
private func applyConfiguration() {
|
||||
var configuration: UIButton.Configuration
|
||||
if #available(iOS 26.0, *) {
|
||||
configuration = .glass()
|
||||
configuration.cornerStyle = .capsule
|
||||
} else {
|
||||
configuration = .plain()
|
||||
}
|
||||
|
||||
configuration.baseForegroundColor = .label
|
||||
configuration.contentInsets = .zero
|
||||
configuration.image = UIImage(systemName: systemImage)
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
|
||||
pointSize: Self.symbolSize,
|
||||
weight: .regular
|
||||
)
|
||||
button.configuration = configuration
|
||||
}
|
||||
|
||||
@objc private func handlePress() {
|
||||
onTriggered()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public final class T3KeyboardCommandsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3KeyboardCommands")
|
||||
|
||||
View(T3KeyboardCommandsView.self) {
|
||||
Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in
|
||||
view.setEnabledCommands(commands)
|
||||
}
|
||||
Events("onCommand")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final class T3KeyboardCommandsView: ExpoView {
|
||||
let onCommand = EventDispatcher()
|
||||
private var enabledCommands = Set<String>()
|
||||
|
||||
public override var canBecomeFirstResponder: Bool { true }
|
||||
|
||||
public override var keyCommands: [UIKeyCommand]? {
|
||||
[
|
||||
enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"),
|
||||
enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"),
|
||||
enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"),
|
||||
enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"),
|
||||
enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
|
||||
enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
|
||||
enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
|
||||
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
|
||||
].compactMap { $0 }
|
||||
}
|
||||
|
||||
func setEnabledCommands(_ commands: [String]) {
|
||||
enabledCommands = Set(commands)
|
||||
if isFirstResponder {
|
||||
resignFirstResponder()
|
||||
}
|
||||
reclaimFirstResponderIfAvailable()
|
||||
}
|
||||
|
||||
private func enabledCommand(
|
||||
_ identifier: String,
|
||||
input: String,
|
||||
modifiers: UIKeyModifierFlags,
|
||||
action: Selector,
|
||||
title: String
|
||||
) -> UIKeyCommand? {
|
||||
guard enabledCommands.contains(identifier) else { return nil }
|
||||
return command(input, modifiers: modifiers, action: action, title: title)
|
||||
}
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reclaimFirstResponderIfAvailable),
|
||||
name: UITextView.textDidEndEditingNotification,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reclaimFirstResponderIfAvailable),
|
||||
name: UITextField.textDidEndEditingNotification,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reclaimFirstResponderIfAvailable),
|
||||
name: UIApplication.didBecomeActiveNotification,
|
||||
object: nil
|
||||
)
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
public override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
reclaimFirstResponderIfAvailable()
|
||||
}
|
||||
|
||||
public override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
reclaimFirstResponderIfAvailable()
|
||||
}
|
||||
|
||||
private func command(
|
||||
_ input: String,
|
||||
modifiers: UIKeyModifierFlags,
|
||||
action: Selector,
|
||||
title: String
|
||||
) -> UIKeyCommand {
|
||||
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
|
||||
command.discoverabilityTitle = title
|
||||
command.wantsPriorityOverSystemBehavior = true
|
||||
return command
|
||||
}
|
||||
|
||||
@objc private func newTask() { emit("newTask") }
|
||||
@objc private func focusSearch() { emit("focusSearch") }
|
||||
@objc private func goBack() { emit("back") }
|
||||
@objc private func openFiles() { emit("files") }
|
||||
@objc private func openTerminal() { emit("terminal") }
|
||||
@objc private func openReview() { emit("review") }
|
||||
@objc private func handleToggleSidebar() { emit("toggleSidebar") }
|
||||
|
||||
private func emit(_ command: String) {
|
||||
onCommand(["command": command])
|
||||
}
|
||||
|
||||
@objc private func reclaimFirstResponderIfAvailable() {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, self.window?.t3FirstResponder == nil else { return }
|
||||
self.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension UIView {
|
||||
var t3FirstResponder: UIResponder? {
|
||||
if isFirstResponder { return self }
|
||||
for subview in subviews {
|
||||
if let responder = subview.t3FirstResponder { return responder }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3NativeControls'
|
||||
s.version = '1.0.0'
|
||||
s.summary = 'Native UIKit controls for T3 Code mobile.'
|
||||
s.description = 'UIKit-backed controls that match native iOS navigation chrome.'
|
||||
s.author = 'T3 Tools'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.platforms = {
|
||||
:ios => '18.0',
|
||||
}
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
}
|
||||
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
import ExpoModulesCore
|
||||
|
||||
public final class T3NativeControlsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3NativeControls")
|
||||
|
||||
View(T3HeaderButtonView.self) {
|
||||
Prop("label") { (view: T3HeaderButtonView, label: String) in
|
||||
view.setLabel(label)
|
||||
}
|
||||
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
|
||||
view.setSystemImage(systemImage)
|
||||
}
|
||||
|
||||
Events("onTriggered")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module {
|
||||
Name("T3ReviewDiffSurface")
|
||||
|
||||
View(T3ReviewDiffView.self) {
|
||||
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
|
||||
view.setRowsJson(rowsJson)
|
||||
}
|
||||
|
||||
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
|
||||
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
|
||||
view.setTokensPatchJson(tokensPatchJson)
|
||||
}
|
||||
|
||||
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
|
||||
view.setTokensResetKey(tokensResetKey)
|
||||
}
|
||||
|
||||
Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in
|
||||
view.setContentResetKey(contentResetKey)
|
||||
}
|
||||
|
||||
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
|
||||
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
|
||||
}
|
||||
@@ -61,7 +53,37 @@ public class T3ReviewDiffModule: Module {
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
|
||||
Events(
|
||||
"onDebug",
|
||||
"onVisibleFileChange",
|
||||
"onToggleFile",
|
||||
"onToggleViewedFile",
|
||||
"onPressLine",
|
||||
"onToggleComment"
|
||||
)
|
||||
|
||||
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
|
||||
view.scrollToFile(fileId, animated: animated)
|
||||
}
|
||||
|
||||
AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in
|
||||
view.scrollToTop(animated: animated)
|
||||
}
|
||||
|
||||
// Large, frequently changing JSON values cannot be regular Fabric props. Expo's
|
||||
// prop adapter compares strings on the main thread before invoking a setter, which
|
||||
// makes a syntax-token patch capable of blocking a frame by itself.
|
||||
AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
|
||||
view.setRowsJson(rowsJson)
|
||||
}
|
||||
|
||||
AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
|
||||
AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
|
||||
view.setTokensPatchJson(tokensPatchJson)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
private struct ReviewDiffNativeRow: Decodable {
|
||||
private struct ReviewDiffNativeRow: Decodable, Sendable {
|
||||
let kind: String
|
||||
let id: String
|
||||
let fileId: String?
|
||||
@@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable {
|
||||
let commentSectionTitle: String?
|
||||
}
|
||||
|
||||
private struct ReviewDiffNativeWordDiffRange: Decodable {
|
||||
private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
|
||||
let start: Int
|
||||
let end: Int
|
||||
}
|
||||
|
||||
private struct ReviewDiffNativeToken: Decodable {
|
||||
private struct ReviewDiffNativeToken: Decodable, Sendable {
|
||||
let content: String
|
||||
let color: String?
|
||||
let fontStyle: Int?
|
||||
}
|
||||
|
||||
private struct ReviewDiffNativeTokenPatch: Decodable {
|
||||
private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
|
||||
let resetKey: String?
|
||||
let chunkIndex: Int?
|
||||
let tokensByRowId: [String: [ReviewDiffNativeToken]]?
|
||||
@@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle {
|
||||
}
|
||||
|
||||
public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
private let payloadDecodeQueue = DispatchQueue(
|
||||
label: "com.t3tools.review-diff.payload-decode",
|
||||
qos: .userInitiated
|
||||
)
|
||||
private let scrollView = UIScrollView()
|
||||
private let contentView = ReviewDiffContentView()
|
||||
private var rows: [ReviewDiffNativeRow] = []
|
||||
@@ -323,10 +327,18 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
private var lastMetricsDebugKey = ""
|
||||
private var lastVisibleRangeDebugKey = ""
|
||||
private var tokensResetKey = ""
|
||||
private var contentResetKey = ""
|
||||
private var initialRowIndex: Int?
|
||||
private var hasAppliedInitialRowIndex = false
|
||||
private var lastVisibleFileId: String?
|
||||
private var pendingScrollFileId: String?
|
||||
private var pendingScrollAnimated = false
|
||||
private var isProgrammaticScrollActive = false
|
||||
private var rowsDecodeGeneration = 0
|
||||
private var tokensDecodeGeneration = 0
|
||||
|
||||
let onDebug = EventDispatcher()
|
||||
let onVisibleFileChange = EventDispatcher()
|
||||
let onToggleFile = EventDispatcher()
|
||||
let onToggleViewedFile = EventDispatcher()
|
||||
let onPressLine = EventDispatcher()
|
||||
@@ -379,6 +391,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
updateViewportFrame()
|
||||
}
|
||||
|
||||
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
|
||||
// A direct gesture takes ownership from any interrupted programmatic jump.
|
||||
// Resume visible-file events immediately so the inspector follows the finger.
|
||||
isProgrammaticScrollActive = false
|
||||
contentView.isVerticalScrollActive = true
|
||||
}
|
||||
|
||||
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
|
||||
guard !decelerate else {
|
||||
return
|
||||
@@ -396,77 +415,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
}
|
||||
|
||||
func setRowsJson(_ rowsJson: String) {
|
||||
guard let data = rowsJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
rowsDecodeGeneration += 1
|
||||
let generation = rowsDecodeGeneration
|
||||
|
||||
do {
|
||||
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
|
||||
contentView.rows = rows
|
||||
hasAppliedInitialRowIndex = false
|
||||
emitDebug("rows-decoded", [
|
||||
"rows": rows.count,
|
||||
"firstKind": rows.first?.kind ?? "none",
|
||||
])
|
||||
updateContentMetrics()
|
||||
} catch {
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
updateContentMetrics()
|
||||
emitDebug("rows-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
])
|
||||
payloadDecodeQueue.async { [weak self] in
|
||||
guard let data = rowsJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.rowsDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.rows = decodedRows
|
||||
self.contentView.rows = decodedRows
|
||||
self.hasAppliedInitialRowIndex = false
|
||||
self.lastVisibleFileId = nil
|
||||
self.emitDebug("rows-decoded", [
|
||||
"rows": decodedRows.count,
|
||||
"firstKind": decodedRows.first?.kind ?? "none",
|
||||
])
|
||||
self.updateContentMetrics()
|
||||
self.applyPendingScrollIfNeeded()
|
||||
}
|
||||
} catch {
|
||||
let message = error.localizedDescription
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.rowsDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.rows = []
|
||||
self.contentView.rows = []
|
||||
self.hasAppliedInitialRowIndex = false
|
||||
self.lastVisibleFileId = nil
|
||||
self.pendingScrollFileId = nil
|
||||
self.updateContentMetrics()
|
||||
self.emitDebug("rows-decode-failed", ["error": message])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensJson(_ tokensJson: String) {
|
||||
guard let data = tokensJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
tokensDecodeGeneration += 1
|
||||
let generation = tokensDecodeGeneration
|
||||
|
||||
do {
|
||||
contentView.tokensByRowId = try JSONDecoder().decode(
|
||||
[String: [ReviewDiffNativeToken]].self,
|
||||
from: data
|
||||
)
|
||||
} catch {
|
||||
contentView.tokensByRowId = [:]
|
||||
emitDebug("tokens-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
])
|
||||
payloadDecodeQueue.async { [weak self] in
|
||||
guard let data = tokensJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let decodedTokens = try JSONDecoder().decode(
|
||||
[String: [ReviewDiffNativeToken]].self,
|
||||
from: data
|
||||
)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.tokensDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.contentView.tokensByRowId = decodedTokens
|
||||
}
|
||||
} catch {
|
||||
let message = error.localizedDescription
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, generation == self.tokensDecodeGeneration else {
|
||||
return
|
||||
}
|
||||
self.contentView.tokensByRowId = [:]
|
||||
self.emitDebug("tokens-decode-failed", ["error": message])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setTokensPatchJson(_ tokensPatchJson: String) {
|
||||
guard let data = tokensPatchJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
let contentResetKey = self.contentResetKey
|
||||
|
||||
do {
|
||||
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
|
||||
if let resetKey = patch.resetKey, resetKey != tokensResetKey {
|
||||
tokensResetKey = resetKey
|
||||
contentView.tokensByRowId = [:]
|
||||
}
|
||||
|
||||
let tokensByRowId = patch.tokensByRowId ?? [:]
|
||||
if tokensByRowId.isEmpty {
|
||||
payloadDecodeQueue.async { [weak self] in
|
||||
guard let data = tokensPatchJson.data(using: .utf8) else {
|
||||
return
|
||||
}
|
||||
|
||||
contentView.mergeTokensByRowId(tokensByRowId)
|
||||
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
|
||||
emitDebug("tokens-patch-decoded", [
|
||||
"chunkIndex": chunkIndex,
|
||||
"rows": tokensByRowId.count,
|
||||
"totalRows": contentView.tokensByRowId.count,
|
||||
])
|
||||
do {
|
||||
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self else {
|
||||
return
|
||||
}
|
||||
guard contentResetKey == self.contentResetKey else {
|
||||
return
|
||||
}
|
||||
// A highlighter request from the previous file can finish after the view has
|
||||
// already reset. Never let that stale patch roll the native token state back.
|
||||
if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
|
||||
return
|
||||
}
|
||||
|
||||
let tokensByRowId = patch.tokensByRowId ?? [:]
|
||||
if tokensByRowId.isEmpty {
|
||||
return
|
||||
}
|
||||
|
||||
self.contentView.mergeTokensByRowId(tokensByRowId)
|
||||
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
|
||||
self.emitDebug("tokens-patch-decoded", [
|
||||
"chunkIndex": chunkIndex,
|
||||
"rows": tokensByRowId.count,
|
||||
"totalRows": self.contentView.tokensByRowId.count,
|
||||
])
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
let message = error.localizedDescription
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.emitDebug("tokens-patch-decode-failed", ["error": message])
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
emitDebug("tokens-patch-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,6 +549,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
])
|
||||
}
|
||||
|
||||
func setContentResetKey(_ contentResetKey: String) {
|
||||
guard contentResetKey != self.contentResetKey else {
|
||||
return
|
||||
}
|
||||
|
||||
self.contentResetKey = contentResetKey
|
||||
rowsDecodeGeneration += 1
|
||||
tokensDecodeGeneration += 1
|
||||
contentView.tokensByRowId = [:]
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
pendingScrollFileId = nil
|
||||
isProgrammaticScrollActive = false
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
updateContentMetrics()
|
||||
updateViewportFrame()
|
||||
lastVisibleFileId = nil
|
||||
applyInitialRowIndexIfNeeded()
|
||||
}
|
||||
|
||||
func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
|
||||
let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
|
||||
let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
|
||||
@@ -573,6 +661,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
contentView.invalidateVisibleViewport()
|
||||
contentView.setNeedsDisplay()
|
||||
applyInitialRowIndexIfNeeded()
|
||||
applyPendingScrollIfNeeded()
|
||||
emitVisibleFileIfNeeded()
|
||||
|
||||
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
|
||||
if debugKey != lastMetricsDebugKey {
|
||||
@@ -596,11 +686,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
}
|
||||
|
||||
private func finishVerticalScroll() {
|
||||
isProgrammaticScrollActive = false
|
||||
contentView.isVerticalScrollActive = false
|
||||
updateViewportFrame()
|
||||
emitVisibleRange(reason: "scroll-end")
|
||||
}
|
||||
|
||||
private func emitVisibleFileIfNeeded() {
|
||||
// Keep the explicit destination selected while UIKit animates through the files
|
||||
// between the old and new offsets. Emitting every intermediate header forces a
|
||||
// React render per crossing and makes the navigator visibly flash.
|
||||
guard !isProgrammaticScrollActive else {
|
||||
return
|
||||
}
|
||||
|
||||
// The top of the combined diff is the explicit "All files" destination.
|
||||
// Treat it as a first-class selection instead of immediately resolving the
|
||||
// first file header and undoing the navigator's optimistic selection.
|
||||
if scrollView.contentOffset.y <= 0.5 {
|
||||
guard lastVisibleFileId != nil else {
|
||||
return
|
||||
}
|
||||
lastVisibleFileId = nil
|
||||
onVisibleFileChange(["fileId": NSNull()])
|
||||
return
|
||||
}
|
||||
|
||||
guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y),
|
||||
fileId != lastVisibleFileId else {
|
||||
return
|
||||
}
|
||||
|
||||
lastVisibleFileId = fileId
|
||||
onVisibleFileChange(["fileId": fileId])
|
||||
}
|
||||
|
||||
private func emitVisibleRange(reason: String) {
|
||||
guard let range = contentView.currentVisibleRowRange() else {
|
||||
return
|
||||
@@ -670,6 +790,18 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
applyInitialRowIndexIfNeeded()
|
||||
}
|
||||
|
||||
func scrollToFile(_ fileId: String, animated: Bool) {
|
||||
pendingScrollFileId = fileId
|
||||
pendingScrollAnimated = animated
|
||||
applyPendingScrollIfNeeded()
|
||||
}
|
||||
|
||||
func scrollToTop(animated: Bool) {
|
||||
pendingScrollFileId = nil
|
||||
pendingScrollAnimated = false
|
||||
setVerticalContentOffset(0, animated: animated)
|
||||
}
|
||||
|
||||
private func applyStyle() {
|
||||
contentView.style = ReviewDiffNativeStyle
|
||||
.resolve(stylePayload)
|
||||
@@ -686,6 +818,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
)
|
||||
contentView.verticalOffset = scrollView.contentOffset.y
|
||||
contentView.invalidateVisibleViewport()
|
||||
emitVisibleFileIfNeeded()
|
||||
}
|
||||
|
||||
private func applyPendingScrollIfNeeded() {
|
||||
guard let fileId = pendingScrollFileId,
|
||||
bounds.height > 0 else {
|
||||
return
|
||||
}
|
||||
|
||||
guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
|
||||
if !rows.isEmpty {
|
||||
pendingScrollFileId = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let animated = pendingScrollAnimated
|
||||
pendingScrollFileId = nil
|
||||
pendingScrollAnimated = false
|
||||
setVerticalContentOffset(headerOffset, animated: animated)
|
||||
}
|
||||
|
||||
private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
|
||||
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
|
||||
let clampedOffset = min(max(targetOffset, 0), maxOffset)
|
||||
let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
|
||||
isProgrammaticScrollActive = shouldAnimate
|
||||
contentView.isVerticalScrollActive = shouldAnimate
|
||||
scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
|
||||
if !shouldAnimate {
|
||||
updateViewportFrame()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyInitialRowIndexIfNeeded() {
|
||||
@@ -1255,6 +1419,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
|
||||
return rowOffsets[rowIndex]
|
||||
}
|
||||
|
||||
func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
|
||||
guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var lowerBound = 0
|
||||
var upperBound = fileHeaderRowIndices.count
|
||||
while lowerBound < upperBound {
|
||||
let midpoint = (lowerBound + upperBound) / 2
|
||||
let rowIndex = fileHeaderRowIndices[midpoint]
|
||||
if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
|
||||
lowerBound = midpoint + 1
|
||||
} else {
|
||||
upperBound = midpoint
|
||||
}
|
||||
}
|
||||
|
||||
let rowIndex = lowerBound > 0
|
||||
? fileHeaderRowIndices[lowerBound - 1]
|
||||
: firstHeaderRowIndex
|
||||
guard rows.indices.contains(rowIndex) else {
|
||||
return nil
|
||||
}
|
||||
return resolvedFileId(for: rows[rowIndex])
|
||||
}
|
||||
|
||||
private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
|
||||
fileHeaderRowIndices.first { rowIndex in
|
||||
rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
|
||||
|
||||
@@ -17,6 +17,10 @@ public class T3TerminalModule: Module {
|
||||
view.fontSize = CGFloat(fontSize)
|
||||
}
|
||||
|
||||
Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
@@ -24,11 +24,37 @@ private enum GhosttyRuntime {
|
||||
|
||||
private final class TerminalInputField: UITextField {
|
||||
var onDeleteBackward: (() -> Void)?
|
||||
var onInsert: ((String) -> Void)?
|
||||
|
||||
override var keyCommands: [UIKeyCommand]? {
|
||||
[
|
||||
command(input: "\t", modifiers: UIKeyModifierFlags(), action: #selector(handleTab)),
|
||||
command(input: "\t", modifiers: .shift, action: #selector(handleBackTab)),
|
||||
]
|
||||
}
|
||||
|
||||
override func deleteBackward() {
|
||||
onDeleteBackward?()
|
||||
super.deleteBackward()
|
||||
}
|
||||
|
||||
private func command(
|
||||
input: String,
|
||||
modifiers: UIKeyModifierFlags,
|
||||
action: Selector
|
||||
) -> UIKeyCommand {
|
||||
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
|
||||
command.wantsPriorityOverSystemBehavior = true
|
||||
return command
|
||||
}
|
||||
|
||||
@objc private func handleTab() {
|
||||
onInsert?("\t")
|
||||
}
|
||||
|
||||
@objc private func handleBackTab() {
|
||||
onInsert?("\u{1B}[Z")
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalAppearanceScheme: String {
|
||||
@@ -108,6 +134,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
var focusRequest: Double = 0 {
|
||||
didSet {
|
||||
guard oldValue != focusRequest else { return }
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.requestKeyboardFocus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
|
||||
didSet {
|
||||
guard oldValue != appearanceScheme else { return }
|
||||
@@ -167,6 +202,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
inputField.onDeleteBackward = { [weak self] in
|
||||
self?.emitInput("\u{7F}")
|
||||
}
|
||||
inputField.onInsert = { [weak self] data in
|
||||
self?.emitInput(data)
|
||||
}
|
||||
|
||||
focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
|
||||
terminalViewport.addGestureRecognizer(focusTapGesture)
|
||||
|
||||
+23
-20
@@ -43,12 +43,16 @@
|
||||
"@clerk/expo": "catalog:",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@expo/metro-runtime": "~56.0.15",
|
||||
"@expo/ui": "~56.0.18",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@react-native-menu/menu": "^2.0.0",
|
||||
"@react-navigation/elements": "2.9.26",
|
||||
"@react-navigation/native": "7.3.4",
|
||||
"@react-navigation/native-stack": "7.17.6",
|
||||
"@shikijs/core": "4.2.0",
|
||||
"@shikijs/engine-javascript": "4.2.0",
|
||||
"@shikijs/langs": "4.2.0",
|
||||
@@ -62,31 +66,30 @@
|
||||
"clsx": "^2.1.1",
|
||||
"diff": "8.0.3",
|
||||
"effect": "catalog:",
|
||||
"expo": "^56.0.0",
|
||||
"expo-asset": "~56.0.15",
|
||||
"expo-auth-session": "~56.0.12",
|
||||
"expo-build-properties": "~56.0.15",
|
||||
"expo-camera": "~56.0.7",
|
||||
"expo-clipboard": "~56.0.3",
|
||||
"expo-constants": "~56.0.16",
|
||||
"expo": "~56.0.12",
|
||||
"expo-asset": "~56.0.17",
|
||||
"expo-auth-session": "~56.0.14",
|
||||
"expo-build-properties": "~56.0.19",
|
||||
"expo-camera": "~56.0.8",
|
||||
"expo-clipboard": "~56.0.4",
|
||||
"expo-constants": "~56.0.18",
|
||||
"expo-crypto": "~56.0.4",
|
||||
"expo-dev-client": "~56.0.16",
|
||||
"expo-file-system": "~56.0.7",
|
||||
"expo-font": "~56.0.5",
|
||||
"expo-dev-client": "~56.0.20",
|
||||
"expo-file-system": "~56.0.8",
|
||||
"expo-font": "~56.0.7",
|
||||
"expo-glass-effect": "~56.0.4",
|
||||
"expo-haptics": "~56.0.3",
|
||||
"expo-image-picker": "~56.0.14",
|
||||
"expo-linking": "~56.0.12",
|
||||
"expo-image-picker": "~56.0.18",
|
||||
"expo-linking": "~56.0.14",
|
||||
"expo-network": "~56.0.5",
|
||||
"expo-notifications": "~56.0.14",
|
||||
"expo-notifications": "~56.0.18",
|
||||
"expo-paste-input": "^0.1.15",
|
||||
"expo-router": "~56.2.7",
|
||||
"expo-secure-store": "~56.0.4",
|
||||
"expo-splash-screen": "~56.0.10",
|
||||
"expo-symbols": "~56.0.5",
|
||||
"expo-updates": "~56.0.17",
|
||||
"expo-symbols": "~56.0.6",
|
||||
"expo-updates": "~56.0.19",
|
||||
"expo-web-browser": "~56.0.5",
|
||||
"expo-widgets": "~56.0.15",
|
||||
"expo-widgets": "~56.0.19",
|
||||
"punycode": "^2.3.1",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
@@ -95,7 +98,7 @@
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const { withDangerousMod } = require("expo/config-plugins");
|
||||
|
||||
const MARKER = "# t3code: repair cached CocoaPods UUID allocation before SPM integration";
|
||||
const UUID_REPAIR = `${MARKER}
|
||||
pods_project = installer.pods_project
|
||||
existing_uuids = pods_project.objects.map(&:uuid)
|
||||
uuid_prefix = pods_project.instance_variable_get(:@uuid_prefix)[0, 6]
|
||||
sequential_uuid = /\\A#{Regexp.escape(uuid_prefix)}([0-9A-F]{7})0\\z/
|
||||
highest_index = existing_uuids.filter_map do |uuid|
|
||||
match = sequential_uuid.match(uuid)
|
||||
match && match[1].to_i(16)
|
||||
end.max || -1
|
||||
|
||||
# Pod::Project generates sequential UUIDs without collision checks because CocoaPods
|
||||
# normally creates the project in this process. EAS can restore Pods.xcodeproj from
|
||||
# cache, leaving the allocator behind the loaded objects. React Native's SPM support
|
||||
# then reuses an existing UUID and silently corrupts the project graph.
|
||||
next_index = highest_index + 1
|
||||
pods_project.instance_variable_set(:@generated_uuids, Array.new(next_index))
|
||||
pods_project.instance_variable_set(:@available_uuids, [])
|
||||
pods_project.generate_available_uuid_list(1_000)
|
||||
Pod::UI.puts "T3Code: reset CocoaPods UUID allocator at #{next_index} (#{existing_uuids.length} existing objects)"
|
||||
`;
|
||||
|
||||
module.exports = function withIosCocoaPodsUuidCache(config) {
|
||||
return withDangerousMod(config, [
|
||||
"ios",
|
||||
(nextConfig) => {
|
||||
const podfilePath = path.join(nextConfig.modRequest.platformProjectRoot, "Podfile");
|
||||
const podfile = fs.readFileSync(podfilePath, "utf8");
|
||||
|
||||
if (podfile.includes(MARKER)) {
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
const postInstallStart = "post_install do |installer|\n";
|
||||
if (!podfile.includes(postInstallStart)) {
|
||||
throw new Error("Unable to repair CocoaPods UUID allocation: post_install is missing.");
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
podfilePath,
|
||||
podfile.replace(postInstallStart, `${postInstallStart}${UUID_REPAIR}`),
|
||||
"utf8",
|
||||
);
|
||||
return nextConfig;
|
||||
},
|
||||
]);
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
const { withAppDelegate, withInfoPlist } = require("expo/config-plugins");
|
||||
|
||||
const SCENE_DELEGATE = `
|
||||
|
||||
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func scene(
|
||||
_ scene: UIScene,
|
||||
willConnectTo session: UISceneSession,
|
||||
options connectionOptions: UIScene.ConnectionOptions
|
||||
) {
|
||||
guard
|
||||
let windowScene = scene as? UIWindowScene,
|
||||
let appDelegate = UIApplication.shared.delegate as? AppDelegate
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
let appWindow: UIWindow
|
||||
if let existingWindow = appDelegate.window {
|
||||
appWindow = existingWindow
|
||||
} else {
|
||||
appWindow = UIWindow(windowScene: windowScene)
|
||||
appDelegate.window = appWindow
|
||||
appDelegate.reactNativeFactory?.startReactNative(
|
||||
withModuleName: "main",
|
||||
in: appWindow,
|
||||
launchOptions: nil)
|
||||
}
|
||||
|
||||
window = appWindow
|
||||
appWindow.windowScene = windowScene
|
||||
appWindow.makeKeyAndVisible()
|
||||
|
||||
if let url = connectionOptions.urlContexts.first?.url {
|
||||
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
|
||||
}
|
||||
|
||||
if let userActivity = connectionOptions.userActivities.first {
|
||||
_ = appDelegate.application(
|
||||
UIApplication.shared,
|
||||
continue: userActivity,
|
||||
restorationHandler: { _ in })
|
||||
}
|
||||
}
|
||||
|
||||
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
|
||||
guard
|
||||
let url = URLContexts.first?.url,
|
||||
let appDelegate = UIApplication.shared.delegate as? AppDelegate
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
|
||||
}
|
||||
|
||||
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
|
||||
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
|
||||
return
|
||||
}
|
||||
|
||||
_ = appDelegate.application(
|
||||
UIApplication.shared,
|
||||
continue: userActivity,
|
||||
restorationHandler: { _ in })
|
||||
}
|
||||
}`;
|
||||
|
||||
module.exports = function withIosSceneLifecycle(config) {
|
||||
config = withInfoPlist(config, (nextConfig) => {
|
||||
nextConfig.modResults.UIApplicationSceneManifest = {
|
||||
UIApplicationSupportsMultipleScenes: false,
|
||||
UISceneConfigurations: {
|
||||
UIWindowSceneSessionRoleApplication: [
|
||||
{
|
||||
UISceneConfigurationName: "Default Configuration",
|
||||
UISceneDelegateClassName: "$(PRODUCT_MODULE_NAME).SceneDelegate",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
return nextConfig;
|
||||
});
|
||||
|
||||
return withAppDelegate(config, (nextConfig) => {
|
||||
if (nextConfig.modResults.language !== "swift") {
|
||||
throw new Error("The iOS scene lifecycle plugin requires a Swift AppDelegate.");
|
||||
}
|
||||
|
||||
if (!nextConfig.modResults.contents.includes("class SceneDelegate:")) {
|
||||
nextConfig.modResults.contents += SCENE_DELEGATE;
|
||||
}
|
||||
|
||||
return nextConfig;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
useFonts,
|
||||
} from "@expo-google-fonts/dm-sans";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { KeyboardProvider } from "react-native-keyboard-controller";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { LoadingScreen } from "./components/LoadingScreen";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { AppNavigationProvider } from "./navigation/app-navigation";
|
||||
import { RootNavigator } from "./navigation/RootNavigator";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
|
||||
import "../global.css";
|
||||
|
||||
export default function App() {
|
||||
const [fontsLoaded] = useFonts({
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
});
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
<AppNavigationProvider>
|
||||
{fontsLoaded ? (
|
||||
<RootNavigator />
|
||||
) : (
|
||||
<LoadingScreen message="Loading remote workspace…" />
|
||||
)}
|
||||
</AppNavigationProvider>
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</CloudAuthProvider>
|
||||
</RegistryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
import "../../global.css";
|
||||
import {
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
useFonts,
|
||||
} from "@expo-google-fonts/dm-sans";
|
||||
import { usePathname } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback } from "react";
|
||||
import { StatusBar, useColorScheme } from "react-native";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { KeyboardProvider } from "react-native-keyboard-controller";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { LoadingScreen } from "../components/LoadingScreen";
|
||||
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
|
||||
import {
|
||||
ClerkSettingsSheetDetentProvider,
|
||||
useClerkSettingsSheetDetent,
|
||||
} from "../features/cloud/ClerkSettingsSheetDetent";
|
||||
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
function AppNavigator() {
|
||||
const pathname = usePathname();
|
||||
const expandedSettingsRouteIsActive =
|
||||
pathname === "/settings/archive" || pathname === "/settings/auth";
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
|
||||
<AppNavigatorContent />
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AppNavigatorContent() {
|
||||
const { state } = useWorkspaceState();
|
||||
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
const sheetStyle = useResolveClassNames("bg-sheet");
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
|
||||
const handleSettingsTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
if (event.data.closing) {
|
||||
collapse();
|
||||
}
|
||||
},
|
||||
[collapse],
|
||||
);
|
||||
|
||||
const newTaskScreenOptions = {
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
};
|
||||
|
||||
const connectionSheetScreenOptions = {
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
};
|
||||
|
||||
const settingsSheetScreenOptions = {
|
||||
...connectionSheetScreenOptions,
|
||||
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
|
||||
};
|
||||
|
||||
if (state.isLoadingConnections) {
|
||||
return <LoadingScreen message="Loading remote workspace…" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusBar
|
||||
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
|
||||
backgroundColor={String(statusBarBg)}
|
||||
translucent
|
||||
/>
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen
|
||||
name="index"
|
||||
options={{
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="settings"
|
||||
listeners={{ transitionEnd: handleSettingsTransitionEnd }}
|
||||
options={settingsSheetScreenOptions}
|
||||
/>
|
||||
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
|
||||
<Stack.Screen name="new" options={newTaskScreenOptions} />
|
||||
<Stack.Screen
|
||||
name="threads/[environmentId]/[threadId]"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RootLayout() {
|
||||
const [fontsLoaded] = useFonts({
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
});
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
{fontsLoaded ? (
|
||||
<AppNavigator />
|
||||
) : (
|
||||
<LoadingScreen message="Loading remote workspace…" />
|
||||
)}
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</CloudAuthProvider>
|
||||
</RegistryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function ConnectionsLayout() {
|
||||
const contentStyle = useResolveClassNames("bg-sheet");
|
||||
const connSheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle,
|
||||
headerStyle: { backgroundColor: connSheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
headerShadowVisible: false,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none" }} />
|
||||
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function NewTaskLayout() {
|
||||
const sheetStyle = useResolveClassNames("bg-sheet");
|
||||
const sheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
|
||||
return (
|
||||
<NewTaskFlowProvider>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: sheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none", title: "Choose project" }} />
|
||||
<Stack.Screen
|
||||
name="add-project/index"
|
||||
options={{ animation: "slide_from_right", title: "New project" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="add-project/repository"
|
||||
options={{ animation: "slide_from_right", title: "Repository" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="add-project/destination"
|
||||
options={{ animation: "slide_from_right", title: "Clone destination" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="add-project/local"
|
||||
options={{ animation: "slide_from_right", title: "Local folder" }}
|
||||
/>
|
||||
<Stack.Screen name="draft" options={{ animation: "slide_from_right", title: "New task" }} />
|
||||
</Stack>
|
||||
</NewTaskFlowProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback } from "react";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function SettingsLayout() {
|
||||
const { collapse } = useClerkSettingsSheetDetent();
|
||||
const contentStyle = useResolveClassNames("bg-sheet");
|
||||
const sheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
const handleExpandedRouteTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
if (event.data.closing) {
|
||||
collapse();
|
||||
}
|
||||
},
|
||||
[collapse],
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: sheetBg },
|
||||
headerTintColor: headerTint,
|
||||
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
|
||||
<Stack.Screen
|
||||
name="environments"
|
||||
options={{ animation: "slide_from_right", title: "Environments" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="environment-new"
|
||||
options={{ animation: "slide_from_right", title: "Add Environment" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="waitlist"
|
||||
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="archive"
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Archived Threads" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth"
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Sign in" }}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
|
||||
|
||||
export default ArchivedThreadsRouteScreen;
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "../connections/new";
|
||||
@@ -1,107 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
export default function ThreadLayout() {
|
||||
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
|
||||
const headerBg = {
|
||||
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen
|
||||
name="index"
|
||||
options={{
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
headerTitle: "",
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="git"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.85],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="git-confirm"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.4],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "Files changed",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/index"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "Files",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/[...path]"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "File",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review-comment"
|
||||
options={{
|
||||
contentStyle: sheetStyle,
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet" as const,
|
||||
sheetAllowedDetents: [0.72, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="terminal"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: { backgroundColor: "#050505" },
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFileRoute() {
|
||||
return <ThreadFileScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFilesIndexRoute() {
|
||||
return <ThreadFilesTreeScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
|
||||
|
||||
export default function GitConfirmRoute() {
|
||||
return <GitConfirmSheet />;
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
export const unstable_settings = {
|
||||
anchor: "index",
|
||||
};
|
||||
|
||||
export default function GitSheetLayout() {
|
||||
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
|
||||
const headerBg = {
|
||||
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
contentStyle: sheetStyle,
|
||||
headerShown: false,
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="index" options={{ animation: "none" }} />
|
||||
<Stack.Screen
|
||||
name="commit"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Commit changes",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="branches"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Branches & worktrees",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
headerShown: true,
|
||||
headerTitle: "Review changes",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
|
||||
|
||||
export default function GitBranchesRoute() {
|
||||
return <GitBranchesSheet />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
|
||||
|
||||
export default function GitCommitRoute() {
|
||||
return <GitCommitSheet />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
|
||||
|
||||
export default function GitRoute() {
|
||||
return <GitOverviewSheet />;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { Redirect, useLocalSearchParams } from "expo-router";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
}>();
|
||||
|
||||
return (
|
||||
<Redirect
|
||||
href={{
|
||||
pathname: "/threads/[environmentId]/[threadId]/review",
|
||||
params: { environmentId, threadId },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
|
||||
|
||||
export default function ThreadRoute() {
|
||||
return <ThreadRouteScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
|
||||
|
||||
export default function ReviewCommentRoute() {
|
||||
return <ReviewCommentComposerSheet />;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
|
||||
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
return (
|
||||
<ReviewHighlighterProvider>
|
||||
<ReviewSheet />
|
||||
</ReviewHighlighterProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
|
||||
|
||||
export default function ThreadTerminalRoute() {
|
||||
return <ThreadTerminalRouteScreen />;
|
||||
}
|
||||
@@ -18,7 +18,9 @@ import {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
OrchestrationShellSnapshot,
|
||||
ServerConfig,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -34,6 +36,10 @@ const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const SERVER_CONFIG_CACHE_DIRECTORY = "connection-server-configs";
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_DIRECTORY = "connection-vcs-refs";
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
@@ -48,6 +54,19 @@ const StoredThreadSnapshot = Schema.Struct({
|
||||
thread: OrchestrationThread,
|
||||
});
|
||||
|
||||
const StoredServerConfig = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
config: ServerConfig,
|
||||
});
|
||||
|
||||
const StoredVcsRefs = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
cwd: Schema.String,
|
||||
refs: VcsListRefsResult,
|
||||
});
|
||||
|
||||
const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
environmentId: EnvironmentId,
|
||||
@@ -55,6 +74,16 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
|
||||
const decodeStoredServerConfig = Schema.decodeUnknownResult(StoredServerConfig);
|
||||
const encodeStoredServerConfig = Schema.encodeUnknownResult(StoredServerConfig);
|
||||
const decodeStoredVcsRefs = Schema.decodeUnknownResult(StoredVcsRefs);
|
||||
const encodeStoredVcsRefs = Schema.encodeUnknownResult(StoredVcsRefs);
|
||||
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownResult(LegacyStoredShellSnapshot);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
@@ -69,6 +98,10 @@ function shellPersistenceError(
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "load-server-config"
|
||||
| "save-server-config"
|
||||
| "load-vcs-refs"
|
||||
| "save-vcs-refs"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
@@ -82,6 +115,14 @@ function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
}
|
||||
|
||||
function environmentCacheFileName(environmentId: EnvironmentId): string {
|
||||
return `${encodeURIComponent(environmentId)}.json`;
|
||||
}
|
||||
|
||||
function vcsRefsFileName(cwd: string): string {
|
||||
return `${encodeURIComponent(cwd)}.json`;
|
||||
}
|
||||
|
||||
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
|
||||
function* (
|
||||
environmentId: EnvironmentId,
|
||||
@@ -146,9 +187,54 @@ const secureCatalogStorage: SecureCatalogStorage = {
|
||||
};
|
||||
|
||||
function shellSnapshotFileName(environmentId: EnvironmentId): string {
|
||||
return `${encodeURIComponent(environmentId)}.json`;
|
||||
return environmentCacheFileName(environmentId);
|
||||
}
|
||||
|
||||
const serverConfigFile = Effect.fn("mobile.connectionStorage.serverConfigFile")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-server-config" | "save-server-config" | "clear-environment",
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, File, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(Paths.document, SERVER_CONFIG_CACHE_DIRECTORY);
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, environmentCacheFileName(environmentId));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
});
|
||||
|
||||
const vcsRefsDirectory = Effect.fn("mobile.connectionStorage.vcsRefsDirectory")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-vcs-refs" | "save-vcs-refs" | "clear-environment",
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(
|
||||
Paths.document,
|
||||
VCS_REFS_CACHE_DIRECTORY,
|
||||
encodeURIComponent(environmentId),
|
||||
);
|
||||
if (operation !== "clear-environment") {
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
});
|
||||
|
||||
const vcsRefsFile = Effect.fn("mobile.connectionStorage.vcsRefsFile")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
cwd: string,
|
||||
operation: "load-vcs-refs" | "save-vcs-refs",
|
||||
) {
|
||||
const { File } = yield* Effect.promise(() => import("expo-file-system"));
|
||||
return new File(yield* vcsRefsDirectory(environmentId, operation), vcsRefsFileName(cwd));
|
||||
});
|
||||
|
||||
const shellSnapshotFileInDirectory = Effect.fn(
|
||||
"mobile.connectionStorage.shellSnapshotFileInDirectory",
|
||||
)(function* (
|
||||
@@ -289,9 +375,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
@@ -310,7 +396,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
decodeLegacyStoredShellSnapshot(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
@@ -324,9 +410,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -337,6 +423,47 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadServerConfig: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* serverConfigFile(environmentId, "load-server-config");
|
||||
if (!file.exists) {
|
||||
return Option.none();
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-server-config", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-server-config", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(decodeStoredServerConfig(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-server-config", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.config)
|
||||
: Option.none();
|
||||
}),
|
||||
saveServerConfig: (environmentId, config) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* serverConfigFile(environmentId, "save-server-config");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
encodeStoredServerConfig({
|
||||
schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
config,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-server-config", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-server-config", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
|
||||
@@ -351,9 +478,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
@@ -362,7 +489,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
encodeStoredThreadSnapshot({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
@@ -379,6 +506,48 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
loadVcsRefs: (environmentId, cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* vcsRefsFile(environmentId, cwd, "load-vcs-refs");
|
||||
if (!file.exists) {
|
||||
return Option.none();
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(decodeStoredVcsRefs(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-vcs-refs", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.cwd === cwd
|
||||
? Option.some(stored.refs)
|
||||
: Option.none();
|
||||
}),
|
||||
saveVcsRefs: (environmentId, cwd, refs) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* vcsRefsFile(environmentId, cwd, "save-vcs-refs");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
encodeStoredVcsRefs({
|
||||
schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
cwd,
|
||||
refs,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-vcs-refs", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-vcs-refs", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
@@ -408,6 +577,13 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const configFile = yield* serverConfigFile(environmentId, "clear-environment");
|
||||
if (configFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => configFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
environmentId,
|
||||
"clear-environment",
|
||||
@@ -418,6 +594,13 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const refsDirectory = yield* vcsRefsDirectory(environmentId, "clear-environment");
|
||||
if (refsDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => refsDirectory.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useAppNavigation } from "../../navigation/native-stack-header";
|
||||
|
||||
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
|
||||
export function useAgentNotificationNavigation(): void {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const handledResponseIds = useRef(new Set<string>());
|
||||
|
||||
useEffect(() => {
|
||||
@@ -14,7 +14,7 @@ export function useAgentNotificationNavigation(): void {
|
||||
routeAgentNotificationResponseOnce({
|
||||
handledResponseIds: handledResponseIds.current,
|
||||
response,
|
||||
navigate: (deepLink) => router.push(deepLink as never),
|
||||
navigate: (deepLink) => navigation.push(deepLink as never),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, [router]);
|
||||
}, [navigation]);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useFocusEffect } from "expo-router";
|
||||
import { useFocusEffect } from "../../navigation/native-stack-header";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
|
||||
@@ -4,35 +4,37 @@ import type {
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Stack } from "expo-router";
|
||||
import {
|
||||
NativeHeaderToolbar,
|
||||
NativeStackScreenOptions,
|
||||
} from "../../navigation/native-stack-header";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { useCallback, useMemo, useRef, type ComponentProps } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Platform,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
ScrollView,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "../home/thread-swipe-actions";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
export interface ArchivedThreadsHeaderEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
@@ -57,79 +59,168 @@ function ArchivedThreadsHeader(props: {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
}) {
|
||||
const { width } = useWindowDimensions();
|
||||
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
|
||||
const usesNativeChrome = Platform.OS === "ios";
|
||||
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
|
||||
const archiveFilterMenu = {
|
||||
title: "Archived thread options",
|
||||
items: [
|
||||
{
|
||||
type: "submenu" as const,
|
||||
title: "Environment",
|
||||
items: [
|
||||
{
|
||||
type: "action" as const,
|
||||
title: "All environments",
|
||||
state: props.selectedEnvironmentId === null ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
type: "action" as const,
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "submenu" as const,
|
||||
title: "Sort by archived date",
|
||||
items: [
|
||||
{
|
||||
type: "action" as const,
|
||||
title: "Newest first",
|
||||
state: props.sortOrder === "newest" ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onSortOrderChange("newest"),
|
||||
},
|
||||
{
|
||||
type: "action" as const,
|
||||
title: "Oldest first",
|
||||
state: props.sortOrder === "oldest" ? ("on" as const) : ("off" as const),
|
||||
onPress: () => props.onSortOrderChange("oldest"),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
title: "Archived Threads",
|
||||
headerSearchBarOptions: {
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Search archived threads",
|
||||
placement: "stacked",
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
},
|
||||
headerTransparent: usesNativeChrome,
|
||||
headerStyle: usesNativeChrome ? { backgroundColor: "transparent" } : undefined,
|
||||
headerShadowVisible: usesNativeChrome ? false : undefined,
|
||||
scrollEdgeEffects: usesNativeChrome ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: usesNativeChrome ? "editor" : undefined,
|
||||
unstable_headerToolbarItems: usesCompactMailToolbar
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
composeButtonId: "archived-refresh",
|
||||
composeSystemImageName: "arrow.clockwise",
|
||||
filterMenu: archiveFilterMenu,
|
||||
filterButtonId: "archived-filter",
|
||||
filterSystemImageName: hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease",
|
||||
onComposePress: props.onRefresh,
|
||||
onSearchTextChange: props.onSearchQueryChange,
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "archived-search-text",
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions: usesCompactMailToolbar
|
||||
? undefined
|
||||
: {
|
||||
...(usesNativeChrome
|
||||
? {
|
||||
allowToolbarIntegration: true,
|
||||
placement: "integratedButton" as const,
|
||||
}
|
||||
: {
|
||||
placement: "stacked" as const,
|
||||
}),
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Search archived threads",
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
accessibilityLabel="Filter and sort archived threads"
|
||||
icon={
|
||||
hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Archived thread options"
|
||||
>
|
||||
<Stack.Toolbar.Menu title="Environment">
|
||||
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
>
|
||||
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
{usesCompactMailToolbar ? null : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{usesNativeChrome ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Refresh archived threads"
|
||||
icon="arrow.clockwise"
|
||||
onPress={props.onRefresh}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Menu
|
||||
accessibilityLabel="Filter and sort archived threads"
|
||||
icon={
|
||||
hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Archived thread options"
|
||||
>
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort by archived date">
|
||||
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "newest"}
|
||||
onPress={() => props.onSortOrderChange("newest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "oldest"}
|
||||
onPress={() => props.onSortOrderChange("oldest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
<NativeHeaderToolbar.Menu title="Sort by archived date">
|
||||
<NativeHeaderToolbar.Label>Sort by archived date</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.sortOrder === "newest"}
|
||||
onPress={() => props.onSortOrderChange("newest")}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Newest first</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.sortOrder === "oldest"}
|
||||
onPress={() => props.onSortOrderChange("oldest")}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Oldest first</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -168,26 +259,20 @@ function ArchivedThreadRow(props: {
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
readonly onUnarchive: () => void;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const cardColor = useThemeColor("--color-card");
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
|
||||
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
|
||||
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
|
||||
Boolean(part),
|
||||
);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
const handleMenuAction = useCallback(
|
||||
(event: { nativeEvent: { event: string } }) => {
|
||||
if (event.nativeEvent.event === "unarchive") {
|
||||
@@ -200,114 +285,80 @@ function ArchivedThreadRow(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: cardColor }}
|
||||
containerStyle={{ backgroundColor: cardColor }}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose(swipeableRef.current);
|
||||
}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeWidth={windowWidth - 32}
|
||||
onDelete={props.onDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Unarchive ${props.thread.title}`,
|
||||
icon: "arrow.uturn.backward",
|
||||
label: "Unarchive",
|
||||
onPress: props.onUnarchive,
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) return;
|
||||
|
||||
props.onSwipeableWillOpen(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Unarchive ${props.thread.title}`,
|
||||
icon: "arrow.uturn.backward",
|
||||
label: "Unarchive",
|
||||
onPress: props.onUnarchive,
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.thread.title}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={props.thread.title}
|
||||
>
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3"
|
||||
style={{
|
||||
borderBottomColor: separatorColor,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
|
||||
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
{() => (
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3"
|
||||
style={{
|
||||
borderBottomColor: separatorColor,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
|
||||
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
{subtitle.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
|
||||
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{subtitle.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Actions for ${props.thread.title}`}
|
||||
accessibilityRole="button"
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
hitSlop={6}
|
||||
>
|
||||
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
</ReanimatedSwipeable>
|
||||
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Actions for ${props.thread.title}`}
|
||||
accessibilityRole="button"
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
hitSlop={6}
|
||||
>
|
||||
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -341,6 +392,7 @@ export function ArchivedThreadsScreen(props: {
|
||||
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
}) {
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const refreshTint = useThemeColor("--color-icon");
|
||||
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
|
||||
@@ -361,76 +413,85 @@ export function ArchivedThreadsScreen(props: {
|
||||
<ArchivedThreadsHeader
|
||||
environments={props.environments}
|
||||
onEnvironmentChange={props.onEnvironmentChange}
|
||||
onRefresh={props.onRefresh}
|
||||
onSearchQueryChange={props.onSearchQueryChange}
|
||||
onSortOrderChange={props.onSortOrderChange}
|
||||
selectedEnvironmentId={props.selectedEnvironmentId}
|
||||
sortOrder={props.sortOrder}
|
||||
/>
|
||||
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
|
||||
<GestureDetector gesture={archiveScrollGesture}>
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
contentContainerStyle={{
|
||||
gap: 20,
|
||||
paddingBottom: 32,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
|
||||
|
||||
{isInitialLoad ? (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
|
||||
</View>
|
||||
) : props.groups.length === 0 ? (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
) : (
|
||||
props.groups.map((group) => {
|
||||
const environmentLabel =
|
||||
props.environments.find(
|
||||
(environment) => environment.environmentId === group.project.environmentId,
|
||||
)?.label ?? null;
|
||||
{isInitialLoad ? (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
|
||||
</View>
|
||||
) : props.groups.length === 0 ? (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
) : (
|
||||
props.groups.map((group) => {
|
||||
const environmentLabel =
|
||||
props.environments.find(
|
||||
(environment) => environment.environmentId === group.project.environmentId,
|
||||
)?.label ?? null;
|
||||
|
||||
return (
|
||||
<View key={group.key} collapsable={false}>
|
||||
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{group.threads.map((thread, index) => (
|
||||
<ArchivedThreadRow
|
||||
key={`${thread.environmentId}:${thread.id}`}
|
||||
environmentLabel={environmentLabel}
|
||||
isLast={index === group.threads.length - 1}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => props.onUnarchiveThread(thread)}
|
||||
thread={thread}
|
||||
/>
|
||||
))}
|
||||
return (
|
||||
<View key={group.key} collapsable={false}>
|
||||
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{group.threads.map((thread, index) => (
|
||||
<ArchivedThreadRow
|
||||
key={`${thread.environmentId}:${thread.id}`}
|
||||
environmentLabel={environmentLabel}
|
||||
isLast={index === group.threads.length - 1}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => props.onUnarchiveThread(thread)}
|
||||
simultaneousSwipeGesture={archiveScrollGesture}
|
||||
thread={thread}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
</GestureDetector>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -33,11 +33,14 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the native review diff view when the view config is installed", async () => {
|
||||
it("returns the payload bridge when the native review diff view is installed", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoMocks.requireNativeView.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
|
||||
expect(resolveNativeReviewDiffView()).toBe(nativeView);
|
||||
const resolvedView = resolveNativeReviewDiffView();
|
||||
expect(resolvedView).not.toBeNull();
|
||||
expect(resolvedView).not.toBe(nativeView);
|
||||
expect(resolveNativeReviewDiffView()).toBe(resolvedView);
|
||||
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface");
|
||||
});
|
||||
|
||||
@@ -78,3 +81,20 @@ describe("resolveNativeReviewDiffView", () => {
|
||||
expect(consoleError).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPendingNativeViewRegistration", () => {
|
||||
it("recognizes registration races for the installed native view name", async () => {
|
||||
const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
|
||||
|
||||
expect(
|
||||
isPendingNativeViewRegistration(
|
||||
new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPendingNativeViewRegistration(
|
||||
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,18 @@
|
||||
import type { ComponentType } from "react";
|
||||
import {
|
||||
createElement,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
type ComponentType,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { NativeSyntheticEvent, ViewProps } from "react-native";
|
||||
import { requireNativeView } from "expo";
|
||||
|
||||
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
|
||||
|
||||
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
|
||||
const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60;
|
||||
|
||||
interface ExpoGlobalWithViewConfig {
|
||||
readonly expo?: {
|
||||
@@ -103,6 +111,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly tokensJson?: string;
|
||||
readonly tokensPatchJson?: string;
|
||||
readonly tokensResetKey?: string;
|
||||
readonly contentResetKey?: string;
|
||||
readonly collapsedFileIdsJson?: string;
|
||||
readonly viewedFileIdsJson?: string;
|
||||
readonly selectedRowIdsJson?: string;
|
||||
@@ -113,7 +122,11 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly rowHeight: number;
|
||||
readonly contentWidth: number;
|
||||
readonly initialRowIndex?: number;
|
||||
readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
|
||||
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
|
||||
readonly onVisibleFileChange?: (
|
||||
event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
|
||||
) => void;
|
||||
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
readonly onPressLine?: (
|
||||
@@ -129,18 +142,130 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
|
||||
}
|
||||
|
||||
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
|
||||
export interface NativeReviewDiffViewHandle {
|
||||
readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
|
||||
readonly scrollToTop: (animated?: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
interface NativeReviewDiffViewRef {
|
||||
readonly setRowsJson: (rowsJson: string) => Promise<void>;
|
||||
readonly setTokensJson: (tokensJson: string) => Promise<void>;
|
||||
readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;
|
||||
readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
|
||||
readonly scrollToTop: (animated: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
type NativeReviewDiffRawViewProps = Omit<
|
||||
NativeReviewDiffViewProps,
|
||||
"nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
|
||||
> & {
|
||||
readonly ref?: Ref<NativeReviewDiffViewRef>;
|
||||
};
|
||||
|
||||
let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
|
||||
let nativeReviewDiffViewResolutionFailed = false;
|
||||
|
||||
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
|
||||
|
||||
export function isPendingNativeViewRegistration(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Error &&
|
||||
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
|
||||
);
|
||||
}
|
||||
|
||||
function useNativeReviewDiffPayload(
|
||||
nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
|
||||
method: NativeReviewDiffPayloadMethod,
|
||||
payload: string | undefined,
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (payload === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let frame: number | null = null;
|
||||
let attempts = 0;
|
||||
|
||||
const dispatch = () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const view = nativeRef.current;
|
||||
const command = view?.[method];
|
||||
if (!view || !command) {
|
||||
if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
|
||||
attempts += 1;
|
||||
frame = requestAnimationFrame(dispatch);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void command.call(view, payload).catch((error: unknown) => {
|
||||
if (
|
||||
!cancelled &&
|
||||
attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
|
||||
isPendingNativeViewRegistration(error)
|
||||
) {
|
||||
attempts += 1;
|
||||
frame = requestAnimationFrame(dispatch);
|
||||
return;
|
||||
}
|
||||
console.error(`[native-review-diff] ${method} failed`, error);
|
||||
});
|
||||
};
|
||||
|
||||
// Fabric attaches the React ref before Expo registers the native tag used by
|
||||
// view functions. Starting on the next frame avoids racing that registration.
|
||||
frame = requestAnimationFrame(dispatch);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (frame !== null) {
|
||||
cancelAnimationFrame(frame);
|
||||
}
|
||||
};
|
||||
}, [method, nativeRef, payload]);
|
||||
}
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
moduleName,
|
||||
);
|
||||
}
|
||||
|
||||
function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
|
||||
const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;
|
||||
const nativeRef = useRef<NativeReviewDiffViewRef>(null);
|
||||
useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);
|
||||
useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
|
||||
useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);
|
||||
useImperativeHandle(
|
||||
nativeViewRef,
|
||||
() => ({
|
||||
scrollToFile: async (fileId, animated = true) => {
|
||||
await nativeRef.current?.scrollToFile(fileId, animated);
|
||||
},
|
||||
scrollToTop: async (animated = true) => {
|
||||
await nativeRef.current?.scrollToTop(animated);
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const RawNativeView = cachedNativeReviewDiffRawView;
|
||||
if (!RawNativeView) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return createElement(RawNativeView, { ...nativeProps, ref: nativeRef });
|
||||
}
|
||||
|
||||
export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
|
||||
if (cachedNativeReviewDiffView) {
|
||||
return cachedNativeReviewDiffView;
|
||||
if (cachedNativeReviewDiffRawView) {
|
||||
return NativeReviewDiffView;
|
||||
}
|
||||
|
||||
if (nativeReviewDiffViewResolutionFailed) {
|
||||
@@ -152,7 +277,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
|
||||
cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
|
||||
NATIVE_REVIEW_DIFF_MODULE_NAME,
|
||||
);
|
||||
} catch (cause) {
|
||||
@@ -166,5 +291,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedNativeReviewDiffView ?? null;
|
||||
return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -11,9 +11,25 @@ import {
|
||||
buildFileTree,
|
||||
defaultExpandedTreePaths,
|
||||
flattenFileTree,
|
||||
type FileTreeNode,
|
||||
type VisibleFileTreeNode,
|
||||
} from "./fileTree";
|
||||
|
||||
const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
|
||||
const FILE_TREE_INITIAL_RENDER_COUNT = 20;
|
||||
const FILE_TREE_RENDER_BATCH_SIZE = 12;
|
||||
const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;
|
||||
|
||||
function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
|
||||
const cached = fileTreeCache.get(entries);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
const tree = buildFileTree(entries);
|
||||
fileTreeCache.set(entries, tree);
|
||||
return tree;
|
||||
}
|
||||
|
||||
function ancestorPaths(path: string): ReadonlyArray<string> {
|
||||
const parts = path.split("/").filter(Boolean);
|
||||
const ancestors: string[] = [];
|
||||
@@ -25,19 +41,24 @@ function ancestorPaths(path: string): ReadonlyArray<string> {
|
||||
|
||||
const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
readonly item: VisibleFileTreeNode;
|
||||
readonly selectedPath: string | null;
|
||||
readonly selected: boolean;
|
||||
readonly expanded: boolean;
|
||||
readonly iconColor: string;
|
||||
readonly onPressDirectory: (path: string) => void;
|
||||
readonly onPreviewFile?: (path: string) => void;
|
||||
readonly onPressFile: (path: string) => void;
|
||||
}) {
|
||||
const { node, depth } = props.item;
|
||||
const selected = node.kind === "file" && node.path === props.selectedPath;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={node.path}
|
||||
onPressIn={() => {
|
||||
if (node.kind === "file") {
|
||||
props.onPreviewFile?.(node.path);
|
||||
}
|
||||
}}
|
||||
onPress={() => {
|
||||
if (node.kind === "directory") {
|
||||
props.onPressDirectory(node.path);
|
||||
@@ -47,7 +68,7 @@ const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
}}
|
||||
className={cn(
|
||||
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
|
||||
selected && "bg-subtle-strong",
|
||||
props.selected && "bg-subtle-strong",
|
||||
)}
|
||||
style={{ paddingLeft: 8 + depth * 18 }}
|
||||
>
|
||||
@@ -65,7 +86,9 @@ const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
<Text
|
||||
className={cn(
|
||||
"min-w-0 flex-1 text-sm leading-[19px]",
|
||||
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
|
||||
props.selected
|
||||
? "font-t3-bold text-foreground"
|
||||
: "font-t3-medium text-foreground-secondary",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -86,13 +109,26 @@ export function FileTreeBrowser(props: {
|
||||
readonly isPending: boolean;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedPath: string | null;
|
||||
readonly onPreviewFile?: (path: string) => void;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSelectFile: (path: string) => void;
|
||||
}) {
|
||||
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [pendingSelection, setPendingSelection] = useState<{
|
||||
readonly path: string;
|
||||
readonly selectedPathAtPress: string | null;
|
||||
} | null>(null);
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
|
||||
const controlledSelectedPathRef = useRef(controlledSelectedPath);
|
||||
const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
controlledSelectedPathRef.current = controlledSelectedPath;
|
||||
|
||||
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
|
||||
const selectedPath =
|
||||
pendingSelection?.selectedPathAtPress === controlledSelectedPath
|
||||
? pendingSelection.path
|
||||
: controlledSelectedPath;
|
||||
const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
|
||||
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
|
||||
const visibleNodes = useMemo(
|
||||
() =>
|
||||
@@ -114,17 +150,30 @@ export function FileTreeBrowser(props: {
|
||||
}, [defaultExpanded]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.selectedPath) {
|
||||
if (!controlledSelectedPath) {
|
||||
return;
|
||||
}
|
||||
setExpandedPaths((current) => {
|
||||
const ancestors = ancestorPaths(controlledSelectedPath);
|
||||
if (ancestors.every((ancestor) => current.has(ancestor))) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current);
|
||||
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
|
||||
for (const ancestor of ancestors) {
|
||||
next.add(ancestor);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [props.selectedPath]);
|
||||
}, [controlledSelectedPath]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (pendingSelectionTimeoutRef.current !== null) {
|
||||
clearTimeout(pendingSelectionTimeoutRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const toggleDirectory = useCallback((path: string) => {
|
||||
setExpandedPaths((current) => {
|
||||
@@ -137,6 +186,37 @@ export function FileTreeBrowser(props: {
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const handleSelectFile = useCallback(
|
||||
(path: string) => {
|
||||
if (pendingSelectionTimeoutRef.current !== null) {
|
||||
clearTimeout(pendingSelectionTimeoutRef.current);
|
||||
}
|
||||
setPendingSelection({
|
||||
path,
|
||||
selectedPathAtPress: controlledSelectedPathRef.current,
|
||||
});
|
||||
pendingSelectionTimeoutRef.current = setTimeout(() => {
|
||||
pendingSelectionTimeoutRef.current = null;
|
||||
setPendingSelection((current) => (current?.path === path ? null : current));
|
||||
}, OPTIMISTIC_SELECTION_TIMEOUT_MS);
|
||||
onSelectFile(path);
|
||||
},
|
||||
[onSelectFile],
|
||||
);
|
||||
const renderItem = useCallback(
|
||||
({ item }: { readonly item: VisibleFileTreeNode }) => (
|
||||
<FileTreeRow
|
||||
item={item}
|
||||
selected={item.node.kind === "file" && item.node.path === selectedPath}
|
||||
expanded={expandedPaths.has(item.node.path)}
|
||||
iconColor={iconColor}
|
||||
onPressDirectory={toggleDirectory}
|
||||
onPreviewFile={onPreviewFile}
|
||||
onPressFile={handleSelectFile}
|
||||
/>
|
||||
),
|
||||
[expandedPaths, handleSelectFile, iconColor, onPreviewFile, selectedPath, toggleDirectory],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
@@ -152,20 +232,15 @@ export function FileTreeBrowser(props: {
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
|
||||
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
|
||||
updateCellsBatchingPeriod={16}
|
||||
windowSize={5}
|
||||
contentContainerStyle={{ paddingVertical: 8 }}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
|
||||
}
|
||||
renderItem={({ item }) => (
|
||||
<FileTreeRow
|
||||
item={item}
|
||||
selectedPath={props.selectedPath}
|
||||
expanded={expandedPaths.has(item.node.path)}
|
||||
iconColor={iconColor}
|
||||
onPressDirectory={toggleDirectory}
|
||||
onPressFile={props.onSelectFile}
|
||||
/>
|
||||
)}
|
||||
renderItem={renderItem}
|
||||
ListEmptyComponent={
|
||||
<View className="px-4 py-5">
|
||||
{props.isPending ? (
|
||||
|
||||
@@ -20,13 +20,13 @@ import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
|
||||
import {
|
||||
buildNativeSourceRows,
|
||||
buildNativeSourceTokens,
|
||||
NATIVE_SOURCE_CONTENT_WIDTH,
|
||||
NATIVE_SOURCE_ROW_HEIGHT,
|
||||
NATIVE_SOURCE_STYLE,
|
||||
nativeSourceRowId,
|
||||
} from "./nativeSourceFileAdapter";
|
||||
import { prepareSourceFileDocument } from "./source-file-document";
|
||||
import { sourceHighlightAtom } from "./sourceHighlightingState";
|
||||
|
||||
const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
|
||||
@@ -41,10 +41,6 @@ interface SourceFileSurfaceProps {
|
||||
|
||||
type SourceHighlightStatus = "highlighting" | "ready" | "error";
|
||||
|
||||
function splitSourceLines(contents: string): ReadonlyArray<string> {
|
||||
return contents.replace(/\r\n?/g, "\n").split("\n");
|
||||
}
|
||||
|
||||
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
|
||||
readonly index: number;
|
||||
readonly line: string;
|
||||
@@ -119,11 +115,8 @@ const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
|
||||
function useSourceFileModel(props: SourceFileSurfaceProps) {
|
||||
const colorScheme = useColorScheme();
|
||||
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
|
||||
const normalizedContents = useMemo(
|
||||
() => props.contents.replace(/\r\n?/g, "\n"),
|
||||
[props.contents],
|
||||
);
|
||||
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
|
||||
const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]);
|
||||
const { contents: normalizedContents, lines, rowsJson } = document;
|
||||
const targetIndex =
|
||||
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
|
||||
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
|
||||
@@ -140,7 +133,7 @@ function useSourceFileModel(props: SourceFileSurfaceProps) {
|
||||
? "ready"
|
||||
: "highlighting";
|
||||
|
||||
return { lines, status, targetIndex, theme, tokens };
|
||||
return { lines, rowsJson, status, targetIndex, theme, tokens };
|
||||
}
|
||||
|
||||
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
|
||||
@@ -163,8 +156,7 @@ function NativeSourceFileSurface(
|
||||
},
|
||||
) {
|
||||
const { NativeView } = props;
|
||||
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
|
||||
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
|
||||
const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props);
|
||||
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
|
||||
const selectedRowIdsJson = useMemo(
|
||||
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
|
||||
@@ -176,11 +168,11 @@ function NativeSourceFileSurface(
|
||||
<View className="relative flex-1 bg-card">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<NativeView
|
||||
key={props.path}
|
||||
collapsable={false}
|
||||
testID="source-native-code-view"
|
||||
style={{ flex: 1 }}
|
||||
appearanceScheme={theme}
|
||||
contentResetKey={props.path}
|
||||
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
|
||||
initialRowIndex={targetIndex ?? -1}
|
||||
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import {
|
||||
NativeHeaderToolbar,
|
||||
NativeStackScreenOptions,
|
||||
} from "../../navigation/native-stack-header";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Text as RNText,
|
||||
useColorScheme,
|
||||
View,
|
||||
} from "react-native";
|
||||
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
|
||||
import {
|
||||
EnvironmentId,
|
||||
@@ -16,18 +27,30 @@ import { CopyTextButton } from "../../components/CopyTextButton";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { buildThreadFilesNavigation } from "../../lib/routes";
|
||||
import { buildThreadFilesNavigation, threadNavigation } from "../../lib/routes";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
import { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
|
||||
import {
|
||||
useAdaptiveWorkspaceLayout,
|
||||
useAdaptiveWorkspacePaneRole,
|
||||
} from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
|
||||
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
|
||||
import { FileMarkdownPreview } from "./FileMarkdownPreview";
|
||||
import { FileTreeBrowser } from "./FileTreeBrowser";
|
||||
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
|
||||
import { SourceFileSurface } from "./SourceFileSurface";
|
||||
import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
|
||||
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
|
||||
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
|
||||
import {
|
||||
@@ -41,6 +64,7 @@ import {
|
||||
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
|
||||
|
||||
type FileViewMode = "preview" | "source";
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
if (Array.isArray(value)) {
|
||||
@@ -334,7 +358,7 @@ function FileContent(props: {
|
||||
}
|
||||
|
||||
function useThreadFilesWorkspace() {
|
||||
const params = useLocalSearchParams<{
|
||||
const params = useRouteParams<{
|
||||
environmentId?: string | string[];
|
||||
threadId?: string | string[];
|
||||
}>();
|
||||
@@ -364,7 +388,7 @@ function useThreadFilesWorkspace() {
|
||||
function FilesUnavailable() {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-sheet px-6">
|
||||
<Stack.Screen options={{ title: "Files" }} />
|
||||
<NativeStackScreenOptions options={{ title: "Files" }} />
|
||||
<EmptyState
|
||||
title="Files unavailable"
|
||||
detail="This thread does not have an active workspace path."
|
||||
@@ -443,11 +467,17 @@ function FilesToolbarBottomFade() {
|
||||
}
|
||||
|
||||
export function ThreadFilesTreeScreen() {
|
||||
const router = useRouter();
|
||||
useAdaptiveWorkspacePaneRole("inspector");
|
||||
const navigation = useAppNavigation();
|
||||
const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
|
||||
useAdaptiveWorkspaceLayout();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const colorScheme = useColorScheme();
|
||||
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
|
||||
const revealedInspectorRef = useRef(false);
|
||||
const entriesQuery = useEnvironmentQuery(
|
||||
environmentId !== null && cwd !== null
|
||||
environmentId !== null && cwd !== null && !fileInspector.supported
|
||||
? projectEnvironment.listEntries({
|
||||
environmentId,
|
||||
input: { cwd },
|
||||
@@ -455,18 +485,81 @@ export function ThreadFilesTreeScreen() {
|
||||
: null,
|
||||
);
|
||||
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
|
||||
const handleReturnToThread = useCallback(() => {
|
||||
if (navigation.canGoBack()) {
|
||||
navigation.back();
|
||||
return;
|
||||
}
|
||||
if (environmentId !== null && threadId !== null) {
|
||||
navigation.replace(threadNavigation({ environmentId, threadId }));
|
||||
}
|
||||
}, [environmentId, navigation, threadId]);
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(path: string) => {
|
||||
if (environmentId === null || threadId === null) {
|
||||
return;
|
||||
}
|
||||
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
|
||||
const destination = buildThreadFilesNavigation({ environmentId, threadId }, path);
|
||||
const navigationAction = resolveFileSelectionNavigationAction({
|
||||
hasPersistentFileInspector: fileInspector.supported,
|
||||
});
|
||||
if (navigationAction === "replace") {
|
||||
navigation.replace(destination);
|
||||
return;
|
||||
}
|
||||
navigation.push(destination);
|
||||
},
|
||||
[environmentId, router, threadId],
|
||||
[environmentId, fileInspector.supported, navigation, threadId],
|
||||
);
|
||||
const renderInspector = useCallback(
|
||||
(headerInset: number) =>
|
||||
environmentId !== null && cwd !== null ? (
|
||||
<ThreadFileNavigatorPane
|
||||
cwd={cwd}
|
||||
environmentId={environmentId}
|
||||
headerInset={headerInset}
|
||||
projectName={projectName}
|
||||
selectedPath={null}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
) : null,
|
||||
[cwd, environmentId, handleSelectFile, projectName],
|
||||
);
|
||||
const handlePreviewFile = useCallback(
|
||||
(relativePath: string) => {
|
||||
if (environmentId === null || cwd === null) {
|
||||
return;
|
||||
}
|
||||
preloadWorkspaceFileContents({
|
||||
cwd,
|
||||
environmentId,
|
||||
relativePath,
|
||||
theme: highlightTheme,
|
||||
});
|
||||
},
|
||||
[cwd, environmentId, highlightTheme],
|
||||
);
|
||||
const renderHeaderTitle = useCallback(
|
||||
() => <FilesHeaderTitle projectName={projectName} />,
|
||||
[projectName],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
|
||||
revealedInspectorRef.current = true;
|
||||
showAuxiliaryPane("inspector");
|
||||
}
|
||||
}, [cwd, fileInspector.supported, showAuxiliaryPane]);
|
||||
|
||||
if (selectedThread === null || environmentId === null || threadId === null) {
|
||||
if (fileInspector.supported) {
|
||||
return (
|
||||
<ThreadRouteScreen
|
||||
onReturnToThread={handleReturnToThread}
|
||||
renderInspector={renderInspector}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
|
||||
}
|
||||
|
||||
@@ -474,46 +567,90 @@ export function ThreadFilesTreeScreen() {
|
||||
return <FilesUnavailable />;
|
||||
}
|
||||
|
||||
if (fileInspector.supported) {
|
||||
return (
|
||||
<ThreadRouteScreen
|
||||
onReturnToThread={handleReturnToThread}
|
||||
renderInspector={renderInspector}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
title: "Files",
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
|
||||
headerSearchBarOptions: {
|
||||
allowToolbarIntegration: true,
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
placeholder: "Search files",
|
||||
onChangeText: (event) => {
|
||||
setSearchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
setSearchQuery("");
|
||||
},
|
||||
},
|
||||
headerTitle: renderHeaderTitle,
|
||||
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
unstable_headerToolbarItems: usesCompactMailToolbar
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
composeButtonId: "files-refresh",
|
||||
composeSystemImageName: "arrow.clockwise",
|
||||
onComposePress: entriesQuery.refresh,
|
||||
onSearchTextChange: setSearchQuery,
|
||||
placeholder: "Search files",
|
||||
searchTextChangeId: "files-search-text",
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions: usesCompactMailToolbar
|
||||
? undefined
|
||||
: {
|
||||
allowToolbarIntegration: true,
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
placeholder: "Search files",
|
||||
onChangeText: (event) => {
|
||||
setSearchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
setSearchQuery("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
accessibilityLabel="Refresh files"
|
||||
icon="arrow.clockwise"
|
||||
onPress={entriesQuery.refresh}
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
</Stack.Toolbar>
|
||||
{layout.usesSplitView ? (
|
||||
<NativeHeaderToolbar placement="left">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel={panes.primarySidebarVisible ? "Maximize files" : "Show threads"}
|
||||
icon={
|
||||
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
|
||||
}
|
||||
onPress={togglePrimarySidebar}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
) : null}
|
||||
{!usesCompactMailToolbar ? (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Refresh files"
|
||||
icon="arrow.clockwise"
|
||||
onPress={entriesQuery.refresh}
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
) : null}
|
||||
{usesCompactMailToolbar ? null : (
|
||||
<NativeHeaderToolbar placement="bottom">
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
<FileTreeBrowser
|
||||
entries={entriesData?.entries ?? []}
|
||||
error={entriesQuery.error}
|
||||
isPending={entriesQuery.isPending}
|
||||
searchQuery={searchQuery}
|
||||
selectedPath={null}
|
||||
onPreviewFile={handlePreviewFile}
|
||||
onRefresh={entriesQuery.refresh}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
@@ -523,7 +660,11 @@ export function ThreadFilesTreeScreen() {
|
||||
}
|
||||
|
||||
export function ThreadFileScreen() {
|
||||
const params = useLocalSearchParams<{
|
||||
useAdaptiveWorkspacePaneRole("inspector");
|
||||
const navigation = useAppNavigation();
|
||||
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const params = useRouteParams<{
|
||||
line?: string | string[];
|
||||
path?: string | string[];
|
||||
}>();
|
||||
@@ -568,6 +709,33 @@ export function ThreadFileScreen() {
|
||||
);
|
||||
const fileData = fileQuery.data as ProjectReadFileResult | null;
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(path: string) => {
|
||||
// We are already on the catch-all file route. Updating its params keeps
|
||||
// the current native screen mounted while replacing the selected file in
|
||||
// place, avoiding an RNSScreen snapshot/unmount for every tree click.
|
||||
navigation.setParams({
|
||||
line: undefined,
|
||||
path: path.split("/").filter(Boolean),
|
||||
});
|
||||
},
|
||||
[navigation],
|
||||
);
|
||||
const renderInspector = useCallback(
|
||||
(headerInset: number) =>
|
||||
fileInspector.supported && environmentId !== null && cwd !== null ? (
|
||||
<ThreadFileNavigatorPane
|
||||
cwd={cwd}
|
||||
environmentId={environmentId}
|
||||
headerInset={headerInset}
|
||||
projectName={projectName}
|
||||
selectedPath={relativePath}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
) : undefined,
|
||||
[cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
|
||||
);
|
||||
|
||||
if (selectedThread === null || environmentId === null || threadId === null) {
|
||||
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
|
||||
}
|
||||
@@ -579,7 +747,7 @@ export function ThreadFileScreen() {
|
||||
if (relativePath === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-sheet px-6">
|
||||
<Stack.Screen options={{ title: "Files" }} />
|
||||
<NativeStackScreenOptions options={{ title: "Files" }} />
|
||||
<EmptyState title="File unavailable" detail="This file path is invalid." />
|
||||
</View>
|
||||
);
|
||||
@@ -588,9 +756,42 @@ export function ThreadFileScreen() {
|
||||
return (
|
||||
<ReviewHighlighterProvider>
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen options={{ title: basename(relativePath) }} />
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerTitle: basename(relativePath),
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerTintColor: iconColor,
|
||||
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
|
||||
title: basename(relativePath),
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
}}
|
||||
/>
|
||||
<WorkspaceSidebarToolbar>
|
||||
{fileInspector.supported ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Return to chat"
|
||||
icon="chevron.left"
|
||||
onPress={() => {
|
||||
navigation.replace(threadNavigation({ environmentId, threadId }));
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</WorkspaceSidebarToolbar>
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{fileInspector.supported ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel={
|
||||
panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
|
||||
}
|
||||
icon="sidebar.right"
|
||||
onPress={toggleAuxiliaryPane}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Refresh file"
|
||||
icon="arrow.clockwise"
|
||||
onPress={() => {
|
||||
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
|
||||
@@ -600,26 +801,30 @@ export function ThreadFileScreen() {
|
||||
fileQuery.refresh();
|
||||
}}
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
<FilePreviewHeader
|
||||
activeMode={resolvedActiveMode}
|
||||
showModeSelector={canPreview && !isImageFile}
|
||||
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
|
||||
projectName={projectName}
|
||||
relativePath={relativePath}
|
||||
onSetMode={(mode) => {
|
||||
setModeOverride({ path: relativePath, mode });
|
||||
}}
|
||||
/>
|
||||
<FileContent
|
||||
activeMode={resolvedActiveMode}
|
||||
previewUri={previewUri}
|
||||
fileContents={fileData?.contents ?? null}
|
||||
fileError={fileQuery.error}
|
||||
initialLine={targetLine}
|
||||
relativePath={relativePath}
|
||||
truncated={fileData?.truncated ?? false}
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
<AdaptiveInspectorLayout
|
||||
renderInspector={fileInspector.supported ? () => renderInspector(0) : undefined}
|
||||
>
|
||||
<FilePreviewHeader
|
||||
activeMode={resolvedActiveMode}
|
||||
showModeSelector={canPreview && !isImageFile}
|
||||
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
|
||||
projectName={projectName}
|
||||
relativePath={relativePath}
|
||||
onSetMode={(mode) => {
|
||||
setModeOverride({ path: relativePath, mode });
|
||||
}}
|
||||
/>
|
||||
<FileContent
|
||||
activeMode={resolvedActiveMode}
|
||||
previewUri={previewUri}
|
||||
fileContents={fileData?.contents ?? null}
|
||||
fileError={fileQuery.error}
|
||||
initialLine={targetLine}
|
||||
relativePath={relativePath}
|
||||
truncated={fileData?.truncated ?? false}
|
||||
/>
|
||||
</AdaptiveInspectorLayout>
|
||||
</View>
|
||||
</ReviewHighlighterProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
import { isBrowserPreviewFile, isImagePreviewFile } from "./filePath";
|
||||
import { prepareSourceFileDocument } from "./source-file-document";
|
||||
import { sourceHighlightAtom } from "./sourceHighlightingState";
|
||||
import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";
|
||||
|
||||
const inFlightPreloads = new Map<string, Promise<void>>();
|
||||
const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024;
|
||||
|
||||
function preloadKey(input: {
|
||||
readonly cwd: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly relativePath: string;
|
||||
}): string {
|
||||
return JSON.stringify([input.environmentId, input.cwd, input.relativePath]);
|
||||
}
|
||||
|
||||
export function preloadWorkspaceFileContents(input: {
|
||||
readonly cwd: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly relativePath: string;
|
||||
readonly theme: ReviewDiffTheme;
|
||||
}): void {
|
||||
if (isBrowserPreviewFile(input.relativePath) || isImagePreviewFile(input.relativePath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = preloadKey(input);
|
||||
if (inFlightPreloads.has(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preload = executeAtomQuery(
|
||||
appAtomRegistry,
|
||||
projectEnvironment.readFile({
|
||||
environmentId: input.environmentId,
|
||||
input: { cwd: input.cwd, relativePath: input.relativePath },
|
||||
}),
|
||||
{
|
||||
label: "workspace file preload",
|
||||
reportDefect: false,
|
||||
reportFailure: false,
|
||||
},
|
||||
)
|
||||
.then(async (result) => {
|
||||
if (result._tag === "Success") {
|
||||
const document = prepareSourceFileDocument(result.value.contents);
|
||||
if (document.contents.length <= MAX_HIGHLIGHT_PRELOAD_CHARACTERS) {
|
||||
await executeAtomQuery(
|
||||
appAtomRegistry,
|
||||
sourceHighlightAtom({
|
||||
path: input.relativePath,
|
||||
contents: document.contents,
|
||||
theme: input.theme,
|
||||
}),
|
||||
{
|
||||
label: "workspace source highlight preload",
|
||||
reportDefect: false,
|
||||
reportFailure: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightPreloads.delete(key);
|
||||
});
|
||||
|
||||
inFlightPreloads.set(key, preload);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { prepareSourceFileDocument } from "./source-file-document";
|
||||
|
||||
describe("prepareSourceFileDocument", () => {
|
||||
it("normalizes and serializes source rows once for repeated consumers", () => {
|
||||
const first = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r");
|
||||
const second = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r");
|
||||
const rows = JSON.parse(first.rowsJson) as ReadonlyArray<{ readonly content: string }>;
|
||||
|
||||
expect(first.contents).toBe("const value = 1;\n\tvalue;\n");
|
||||
expect(first.lines).toEqual(["const value = 1;", "\tvalue;", ""]);
|
||||
expect(rows.map((row) => row.content)).toEqual(["const value = 1;", " value;", ""]);
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { buildNativeSourceRows } from "./nativeSourceFileAdapter";
|
||||
|
||||
const MAX_CACHED_DOCUMENTS = 8;
|
||||
const MAX_CACHED_CHARACTERS = 4 * 1024 * 1024;
|
||||
|
||||
export interface SourceFileDocument {
|
||||
readonly contents: string;
|
||||
readonly lines: ReadonlyArray<string>;
|
||||
readonly rowsJson: string;
|
||||
}
|
||||
|
||||
const documentCache = new Map<string, SourceFileDocument>();
|
||||
let cachedCharacterCount = 0;
|
||||
|
||||
function removeOldestCachedDocument(): void {
|
||||
const oldestKey = documentCache.keys().next().value;
|
||||
if (typeof oldestKey !== "string") {
|
||||
return;
|
||||
}
|
||||
const document = documentCache.get(oldestKey);
|
||||
documentCache.delete(oldestKey);
|
||||
cachedCharacterCount -= (document?.contents.length ?? 0) + (document?.rowsJson.length ?? 0);
|
||||
}
|
||||
|
||||
export function prepareSourceFileDocument(contents: string): SourceFileDocument {
|
||||
const cached = documentCache.get(contents);
|
||||
if (cached !== undefined) {
|
||||
documentCache.delete(contents);
|
||||
documentCache.set(contents, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
const normalizedContents = contents.replace(/\r\n?/g, "\n");
|
||||
const lines = normalizedContents.split("\n");
|
||||
const document = {
|
||||
contents: normalizedContents,
|
||||
lines,
|
||||
rowsJson: JSON.stringify(buildNativeSourceRows(lines)),
|
||||
} satisfies SourceFileDocument;
|
||||
const characterCount = document.contents.length + document.rowsJson.length;
|
||||
|
||||
if (characterCount <= MAX_CACHED_CHARACTERS) {
|
||||
while (
|
||||
documentCache.size >= MAX_CACHED_DOCUMENTS ||
|
||||
cachedCharacterCount + characterCount > MAX_CACHED_CHARACTERS
|
||||
) {
|
||||
removeOldestCachedDocument();
|
||||
}
|
||||
documentCache.set(contents, document);
|
||||
cachedCharacterCount += characterCount;
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
@@ -88,7 +88,7 @@ describe("sourceHighlightingState", () => {
|
||||
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
|
||||
});
|
||||
firstUnmount();
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const secondUnmount = registry.mount(atom);
|
||||
await vi.waitFor(() => {
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import type { EnvironmentId, ProjectListEntriesResult } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useMemo, useState, type ComponentProps } from "react";
|
||||
import { Platform, Pressable, useColorScheme, View, type NativeSyntheticEvent } from "react-native";
|
||||
import {
|
||||
Screen,
|
||||
ScreenStack,
|
||||
ScreenStackHeaderConfig,
|
||||
ScreenStackHeaderSearchBarView,
|
||||
SearchBar,
|
||||
} from "react-native-screens";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { FileTreeBrowser } from "./FileTreeBrowser";
|
||||
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
|
||||
|
||||
export function ThreadFileNavigatorPane(props: {
|
||||
readonly cwd: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly headerInset: number;
|
||||
readonly projectName: string;
|
||||
readonly selectedPath: string | null;
|
||||
readonly onSelectFile: (path: string) => void;
|
||||
}) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const colorScheme = useColorScheme();
|
||||
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const foregroundColor = String(useThemeColor("--color-foreground"));
|
||||
const sheetColor = String(useThemeColor("--color-sheet"));
|
||||
const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
const entriesQuery = useEnvironmentQuery(
|
||||
projectEnvironment.listEntries({
|
||||
environmentId: props.environmentId,
|
||||
input: { cwd: props.cwd },
|
||||
}),
|
||||
);
|
||||
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
|
||||
const handlePreviewFile = useCallback(
|
||||
(relativePath: string) => {
|
||||
preloadWorkspaceFileContents({
|
||||
cwd: props.cwd,
|
||||
environmentId: props.environmentId,
|
||||
relativePath,
|
||||
theme: highlightTheme,
|
||||
});
|
||||
},
|
||||
[highlightTheme, props.cwd, props.environmentId],
|
||||
);
|
||||
const nativeHeaderRightBarButtonItems = useMemo(
|
||||
() =>
|
||||
[
|
||||
{
|
||||
accessibilityLabel: "Refresh files",
|
||||
icon: { name: "arrow.clockwise", type: "sfSymbol" as const },
|
||||
identifier: "thread-file-navigator-refresh",
|
||||
onPress: entriesQuery.refresh,
|
||||
sharesBackground: false,
|
||||
tintColor: foregroundColor,
|
||||
type: "button" as const,
|
||||
width: 44,
|
||||
},
|
||||
] as ComponentProps<typeof ScreenStackHeaderConfig>["headerRightBarButtonItems"],
|
||||
[entriesQuery.refresh, foregroundColor],
|
||||
);
|
||||
|
||||
const fileTree = (
|
||||
<FileTreeBrowser
|
||||
entries={entriesData?.entries ?? []}
|
||||
error={entriesQuery.error}
|
||||
isPending={entriesQuery.isPending}
|
||||
searchQuery={searchQuery}
|
||||
selectedPath={props.selectedPath}
|
||||
onPreviewFile={handlePreviewFile}
|
||||
onRefresh={entriesQuery.refresh}
|
||||
onSelectFile={props.onSelectFile}
|
||||
/>
|
||||
);
|
||||
|
||||
if (Platform.OS === "ios") {
|
||||
return (
|
||||
<View className="flex-1 border-l border-border bg-sheet">
|
||||
<ScreenStack style={{ flex: 1 }}>
|
||||
<Screen
|
||||
activityState={2}
|
||||
enabled
|
||||
isNativeStack
|
||||
screenId="thread-file-navigator-native"
|
||||
scrollEdgeEffects={headerScrollEdgeEffects}
|
||||
style={{ backgroundColor: sheetColor, flex: 1 }}
|
||||
>
|
||||
{fileTree}
|
||||
<ScreenStackHeaderConfig
|
||||
backgroundColor="rgba(0,0,0,0)"
|
||||
color={foregroundColor}
|
||||
headerRightBarButtonItems={nativeHeaderRightBarButtonItems}
|
||||
hideBackButton
|
||||
hideShadow={false}
|
||||
navigationItemStyle="editor"
|
||||
subtitle={props.projectName}
|
||||
title="Files"
|
||||
titleColor={foregroundColor}
|
||||
titleFontSize={17}
|
||||
titleFontWeight="700"
|
||||
translucent
|
||||
>
|
||||
<ScreenStackHeaderSearchBarView>
|
||||
<SearchBar
|
||||
allowToolbarIntegration
|
||||
autoCapitalize="none"
|
||||
barTintColor={sheetColor}
|
||||
hideNavigationBar={false}
|
||||
hideWhenScrolling={false}
|
||||
obscureBackground={false}
|
||||
onCancelButtonPress={() => {
|
||||
setSearchQuery("");
|
||||
}}
|
||||
onChangeText={(event: NativeSyntheticEvent<{ readonly text?: string }>) => {
|
||||
setSearchQuery(event.nativeEvent.text ?? "");
|
||||
}}
|
||||
placement="integratedButton"
|
||||
placeholder="Search files"
|
||||
textColor={foregroundColor}
|
||||
tintColor={foregroundColor}
|
||||
/>
|
||||
</ScreenStackHeaderSearchBarView>
|
||||
</ScreenStackHeaderConfig>
|
||||
</Screen>
|
||||
</ScreenStack>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 border-l border-border bg-sheet">
|
||||
<View className="border-b border-border" style={{ paddingTop: props.headerInset }}>
|
||||
<View className="h-12 flex-row items-center gap-2 px-3">
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-sm font-t3-bold text-foreground">Files</Text>
|
||||
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
|
||||
{props.projectName}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Refresh files"
|
||||
hitSlop={8}
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
onPress={entriesQuery.refresh}
|
||||
>
|
||||
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2 border-t border-border px-3 py-2">
|
||||
<SymbolView name="magnifyingglass" size={15} tintColor={iconColor} type="monochrome" />
|
||||
<TextInput
|
||||
accessibilityLabel="Search files"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
clearButtonMode="while-editing"
|
||||
className="min-h-10 flex-1 rounded-xl py-2 text-sm"
|
||||
placeholder="Search files"
|
||||
value={searchQuery}
|
||||
onChangeText={setSearchQuery}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{fileTree}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -4,59 +4,31 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import { Stack } from "expo-router";
|
||||
import { Text as RNText, View } from "react-native";
|
||||
NativeHeaderToolbar,
|
||||
NativeStackScreenOptions,
|
||||
} from "../../navigation/native-stack-header";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform } from "react-native";
|
||||
import type { SearchBarCommands } from "react-native-screens";
|
||||
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
buildHomeListFilterMenu,
|
||||
type HomeListFilterMenuEnvironment,
|
||||
} from "./home-list-filter-menu";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
|
||||
export interface HomeHeaderEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ value: "updated_at", label: "Last user message" },
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarThreadSortOrder;
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ value: "updated_at", label: "Last user message" },
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
export function HomeHeader(props: {
|
||||
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
|
||||
@@ -72,174 +44,185 @@ export function HomeHeader(props: {
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const hasCustomListOptions =
|
||||
props.selectedEnvironmentId !== null ||
|
||||
props.projectSortOrder !== DEFAULT_SIDEBAR_PROJECT_SORT_ORDER ||
|
||||
props.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
props.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE;
|
||||
const hasCustomListOptions = hasCustomHomeListOptions(props);
|
||||
const focusSearch = useCallback(() => {
|
||||
searchBarRef.current?.focus();
|
||||
return searchBarRef.current !== null;
|
||||
}, []);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const filterMenu = buildHomeListFilterMenu(props);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerLargeTitle: false,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
hideNavigationBar: false,
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
allowToolbarIntegration: true,
|
||||
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
headerBackVisible: false,
|
||||
headerBackTitle: "",
|
||||
headerTitle: "Threads",
|
||||
headerTitleStyle: {
|
||||
fontSize: 18,
|
||||
fontWeight: "800",
|
||||
},
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
unstable_headerRightItems:
|
||||
Platform.OS === "ios"
|
||||
? () => [
|
||||
{
|
||||
accessibilityLabel: "Open settings",
|
||||
glassEffect: false,
|
||||
icon: { name: "ellipsis", type: "sfSymbol" } as const,
|
||||
identifier: "home-settings",
|
||||
label: "",
|
||||
onPress: props.onOpenSettings,
|
||||
sharesBackground: false,
|
||||
type: "button",
|
||||
variant: "plain",
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
unstable_headerToolbarItems:
|
||||
Platform.OS === "ios"
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
composeButtonId: "home-new-task",
|
||||
composeSystemImageName: "square.and.pencil",
|
||||
filterMenu,
|
||||
filterButtonId: "home-filter",
|
||||
filterSystemImageName: hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease",
|
||||
onComposePress: props.onStartNewTask,
|
||||
onSearchTextChange: props.onSearchQueryChange,
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "home-search-text",
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
headerSearchBarOptions:
|
||||
Platform.OS === "ios"
|
||||
? undefined
|
||||
: {
|
||||
ref: searchBarRef,
|
||||
allowToolbarIntegration: true,
|
||||
hideNavigationBar: false,
|
||||
placeholder: "Search",
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="left">
|
||||
<Stack.Toolbar.View hidesSharedBackground>
|
||||
<View
|
||||
style={{
|
||||
width: 128,
|
||||
height: 32,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
}}
|
||||
{Platform.OS === "ios" ? null : (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
|
||||
{Platform.OS === "ios" ? null : (
|
||||
<NativeHeaderToolbar placement="bottom">
|
||||
<NativeHeaderToolbar.Menu
|
||||
accessibilityLabel="Filter and sort threads"
|
||||
icon={
|
||||
hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
title="Thread list options"
|
||||
separateBackground
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
color: iconColor,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
T3 Code
|
||||
</RNText>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 99,
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 3,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.micro.fontSize,
|
||||
color: mutedColor,
|
||||
letterSpacing: 1.1,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
<NativeHeaderToolbar.MenuAction onPress={props.onOpenSettings}>
|
||||
<NativeHeaderToolbar.Label>Settings</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
subtitle="Show threads from every environment"
|
||||
>
|
||||
Alpha
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
accessibilityLabel="Filter and sort threads"
|
||||
icon={
|
||||
hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Thread list options"
|
||||
>
|
||||
<Stack.Toolbar.Menu title="Environment">
|
||||
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
subtitle="Show threads from every environment"
|
||||
>
|
||||
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
<NativeHeaderToolbar.Menu title="Sort projects">
|
||||
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_SORT_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectSortOrder === option.value}
|
||||
onPress={() => props.onProjectSortOrderChange(option.value)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort projects">
|
||||
<Stack.Toolbar.Label>Sort projects</Stack.Toolbar.Label>
|
||||
{PROJECT_SORT_OPTIONS.map((option) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectSortOrder === option.value}
|
||||
onPress={() => props.onProjectSortOrderChange(option.value)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
<NativeHeaderToolbar.Menu title="Sort threads">
|
||||
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
|
||||
{THREAD_SORT_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.threadSortOrder === option.value}
|
||||
onPress={() => props.onThreadSortOrderChange(option.value)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort threads">
|
||||
<Stack.Toolbar.Label>Sort threads</Stack.Toolbar.Label>
|
||||
{THREAD_SORT_OPTIONS.map((option) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.threadSortOrder === option.value}
|
||||
onPress={() => props.onThreadSortOrderChange(option.value)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Group projects">
|
||||
<Stack.Toolbar.Label>Group projects</Stack.Toolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Button
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
|
||||
<Stack.Toolbar.Button
|
||||
accessibilityLabel="New task"
|
||||
icon="square.and.pencil"
|
||||
onPress={props.onStartNewTask}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
<NativeHeaderToolbar.Menu title="Group projects">
|
||||
<NativeHeaderToolbar.Label>Group projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.SearchBarSlot />
|
||||
<NativeHeaderToolbar.Spacer width={8} sharesBackground={false} />
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="New task"
|
||||
icon="square.and.pencil"
|
||||
onPress={props.onStartNewTask}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -7,13 +7,17 @@ import type {
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useCallback, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import Animated, {
|
||||
Easing,
|
||||
LinearTransition,
|
||||
@@ -31,12 +35,11 @@ import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { threadStatusTone } from "../threads/threadPresentation";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "./thread-swipe-actions";
|
||||
import { ThreadSwipeable } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
|
||||
/* ─── Types ──────────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -45,13 +48,21 @@ interface HomeScreenProps {
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly catalogState: WorkspaceState;
|
||||
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -62,19 +73,20 @@ interface HomeScreenProps {
|
||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
||||
switch (thread.session?.status) {
|
||||
case "running":
|
||||
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
|
||||
return { bg: "rgba(249,115,22,0.22)", fg: "#ff9f0a" };
|
||||
case "ready":
|
||||
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
|
||||
return { bg: "rgba(48,209,88,0.22)", fg: "#30d158" };
|
||||
case "starting":
|
||||
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
|
||||
return { bg: "rgba(10,132,255,0.22)", fg: "#0a84ff" };
|
||||
case "error":
|
||||
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
|
||||
return { bg: "rgba(255,69,58,0.22)", fg: "#ff453a" };
|
||||
default:
|
||||
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
|
||||
return { bg: "rgba(142,142,147,0.22)", fg: "#8e8e93" };
|
||||
}
|
||||
}
|
||||
|
||||
const COLLAPSED_THREAD_LIMIT = 6;
|
||||
const HOME_COMPACT_HEADER_THRESHOLD = 48;
|
||||
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
|
||||
|
||||
function threadRowExit(values: ExitAnimationsValues) {
|
||||
@@ -178,7 +190,7 @@ function ProjectGroupLabel(props: {
|
||||
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
|
||||
|
||||
return (
|
||||
<View className="flex-row items-center gap-2.5 px-1 pb-2">
|
||||
<View className="flex-row items-center gap-2.5 px-5 pb-2 pt-5">
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
size={18}
|
||||
@@ -186,7 +198,7 @@ function ProjectGroupLabel(props: {
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
<Text
|
||||
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
|
||||
className="flex-1 text-xs font-t3-bold text-foreground-muted"
|
||||
style={{ letterSpacing: 0.5 }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -207,6 +219,10 @@ function ProjectGroupLabel(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function HomeTopContentSpacer(props: { readonly topInset: number }) {
|
||||
return <View style={{ height: props.topInset + 78 }} />;
|
||||
}
|
||||
|
||||
/* ─── Thread row ─────────────────────────────────────────────────────── */
|
||||
|
||||
function ThreadRow(props: {
|
||||
@@ -217,15 +233,15 @@ function ThreadRow(props: {
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly simultaneousSwipeGesture?: ComponentProps<
|
||||
typeof ThreadSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
readonly isLast: boolean;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const cardColor = useThemeColor("--color-card");
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
const { bg, fg } = statusColors(props.thread);
|
||||
const tone = threadStatusTone(props.thread);
|
||||
const timestamp = relativeTime(
|
||||
@@ -235,213 +251,128 @@ function ThreadRow(props: {
|
||||
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
|
||||
Boolean(part),
|
||||
);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: cardColor }}
|
||||
containerStyle={{ backgroundColor: cardColor }}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose(swipeableRef.current);
|
||||
}
|
||||
<ThreadSwipeable
|
||||
backgroundColor={screenColor}
|
||||
fullSwipeWidth={windowWidth - 32}
|
||||
onDelete={props.onDelete}
|
||||
onSwipeableClose={props.onSwipeableClose}
|
||||
onSwipeableWillOpen={props.onSwipeableWillOpen}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Archive ${props.thread.title}`,
|
||||
icon: "archivebox",
|
||||
label: "Archive",
|
||||
onPress: props.onArchive,
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onSwipeableWillOpen(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Archive ${props.thread.title}`,
|
||||
icon: "archivebox",
|
||||
label: "Archive",
|
||||
onPress: props.onArchive,
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.thread.title}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
|
||||
threadTitle={props.thread.title}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityHint="Swipe left for archive and delete actions"
|
||||
accessibilityLabel={props.thread.title}
|
||||
accessibilityRole="button"
|
||||
className="bg-card"
|
||||
onPress={() => {
|
||||
swipeableRef.current?.close();
|
||||
props.onPress();
|
||||
}}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
paddingLeft: 16,
|
||||
paddingRight: 16,
|
||||
paddingVertical: 10,
|
||||
gap: 12,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
borderBottomColor: separatorColor,
|
||||
{(close) => (
|
||||
<Pressable
|
||||
accessibilityHint="Swipe left for archive and delete actions"
|
||||
accessibilityLabel={props.thread.title}
|
||||
accessibilityRole="button"
|
||||
className="bg-screen"
|
||||
onPress={() => {
|
||||
close();
|
||||
props.onPress();
|
||||
}}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderRadius: 9,
|
||||
backgroundColor: bg,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 2,
|
||||
flexDirection: "row",
|
||||
paddingLeft: 20,
|
||||
paddingRight: 18,
|
||||
paddingVertical: 11,
|
||||
gap: 12,
|
||||
minHeight: 78,
|
||||
}}
|
||||
>
|
||||
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
|
||||
</View>
|
||||
|
||||
<View style={{ flex: 1, gap: 3 }}>
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text
|
||||
className="flex-1 text-base font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View
|
||||
className={tone.pillClassName}
|
||||
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
|
||||
>
|
||||
<Text className={`text-3xs font-t3-bold ${tone.textClassName}`}>
|
||||
{tone.label}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
<View
|
||||
style={{
|
||||
width: 46,
|
||||
height: 46,
|
||||
borderRadius: 23,
|
||||
backgroundColor: bg,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 1,
|
||||
}}
|
||||
>
|
||||
<SymbolView name="arrow.triangle.branch" size={20} tintColor={fg} type="monochrome" />
|
||||
</View>
|
||||
|
||||
{subtitleParts.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
gap: 3,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
borderBottomColor: separatorColor,
|
||||
paddingBottom: 11,
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text
|
||||
className="text-2xs text-foreground-tertiary"
|
||||
className="flex-1 text-lg font-t3-bold leading-[22px] text-foreground"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitleParts.join(" · ")}
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View
|
||||
className={tone.pillClassName}
|
||||
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
|
||||
>
|
||||
<Text className={`text-3xs font-t3-bold ${tone.textClassName}`}>
|
||||
{tone.label}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className="text-base text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={13}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{subtitleParts.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
|
||||
{subtitleParts.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
</ReanimatedSwipeable>
|
||||
</Pressable>
|
||||
)}
|
||||
</ThreadSwipeable>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Main screen ────────────────────────────────────────────────────── */
|
||||
|
||||
function staleCatalogPillLabel(props: { readonly catalogState: WorkspaceState }): string {
|
||||
if (props.catalogState.networkStatus === "offline") {
|
||||
return "You are offline";
|
||||
}
|
||||
const connectingEnvironments = props.catalogState.connectingEnvironments;
|
||||
if (connectingEnvironments.length === 1) {
|
||||
return `Reconnecting to ${connectingEnvironments[0]!.environmentLabel}`;
|
||||
}
|
||||
if (connectingEnvironments.length > 1) {
|
||||
return `Reconnecting ${connectingEnvironments.length} environments`;
|
||||
}
|
||||
return "Not connected";
|
||||
}
|
||||
|
||||
function StaleCatalogStatusPill(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const label = staleCatalogPillLabel(props);
|
||||
const isReconnecting = props.catalogState.connectingEnvironments.length > 0;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
className="flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
|
||||
style={{
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: 10 },
|
||||
shadowOpacity: 0.12,
|
||||
shadowRadius: 24,
|
||||
}}
|
||||
>
|
||||
{isReconnecting ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="wifi.slash"
|
||||
size={15}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
)}
|
||||
<Text className="max-w-[260px] text-sm font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export function HomeScreen(props: HomeScreenProps) {
|
||||
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const { height: windowHeight } = useWindowDimensions();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
const toggleExpanded = useCallback((key: string) => {
|
||||
setExpandedProjects((prev) => {
|
||||
const next = new Set(prev);
|
||||
@@ -463,7 +394,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
openSwipeableRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
@@ -495,126 +425,148 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
|
||||
"this environment");
|
||||
const hasSearchQuery = props.searchQuery.trim().length > 0;
|
||||
const shouldShowConnectionStatus =
|
||||
props.catalogState.networkStatus === "offline" ||
|
||||
props.catalogState.hasConnectingEnvironment ||
|
||||
(props.catalogState.hasLoadedShellSnapshot && !props.catalogState.hasReadyEnvironment);
|
||||
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
|
||||
const emptyState = deriveEmptyState({
|
||||
catalogState: props.catalogState,
|
||||
projectCount: props.projects.length,
|
||||
});
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
className="flex-1"
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 8,
|
||||
paddingBottom: 24,
|
||||
gap: 20,
|
||||
}}
|
||||
>
|
||||
{!hasAnyThreads ? (
|
||||
<View>
|
||||
<EmptyState
|
||||
title={emptyState.title}
|
||||
detail={emptyState.detail}
|
||||
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
/>
|
||||
{emptyState.loading ? (
|
||||
<View className="absolute right-5 top-5">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : !hasResults && hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : !hasResults && selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
detail="Choose another environment or create a new task."
|
||||
/>
|
||||
) : !hasResults ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Create a task to start a new coding session."
|
||||
/>
|
||||
) : (
|
||||
projectGroups.map((group) => {
|
||||
const isExpanded = expandedProjects.has(group.key);
|
||||
const visibleThreads = isExpanded
|
||||
? group.threads
|
||||
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
|
||||
const listContent = (
|
||||
<>
|
||||
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
key={group.key}
|
||||
collapsable={false}
|
||||
exiting={threadRowExit}
|
||||
layout={THREAD_LAYOUT_TRANSITION}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<ProjectGroupLabel
|
||||
isExpanded={isExpanded}
|
||||
onToggleExpand={() => toggleExpanded(group.key)}
|
||||
project={group.representative}
|
||||
title={group.title}
|
||||
totalThreadCount={group.threads.length}
|
||||
/>
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{visibleThreads.map((thread, i) => {
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
return (
|
||||
<Animated.View
|
||||
key={threadKey}
|
||||
collapsable={false}
|
||||
exiting={threadRowExit}
|
||||
layout={THREAD_LAYOUT_TRANSITION}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<ThreadRow
|
||||
thread={thread}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[thread.environmentId]?.environmentLabel ??
|
||||
null
|
||||
}
|
||||
isLast={i === visibleThreads.length - 1}
|
||||
onArchive={() => props.onArchiveThread(thread)}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onPress={() => props.onSelectThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
{shouldShowConnectionStatus ? (
|
||||
<View
|
||||
className="absolute left-0 right-0 items-center"
|
||||
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
|
||||
>
|
||||
<StaleCatalogStatusPill
|
||||
catalogState={props.catalogState}
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View style={{ paddingBottom: 16 }}>
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{!hasAnyThreads ? (
|
||||
<View>
|
||||
<EmptyState
|
||||
title={emptyState.title}
|
||||
detail={emptyState.detail}
|
||||
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
/>
|
||||
{emptyState.loading ? (
|
||||
<View className="absolute right-5 top-5">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : !hasResults && hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : !hasResults && selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
detail="Choose another environment or create a new task."
|
||||
/>
|
||||
) : !hasResults ? (
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
) : (
|
||||
projectGroups.map((group) => {
|
||||
const isExpanded = expandedProjects.has(group.key);
|
||||
const visibleThreads = isExpanded
|
||||
? group.threads
|
||||
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
key={group.key}
|
||||
collapsable={false}
|
||||
exiting={threadRowExit}
|
||||
layout={THREAD_LAYOUT_TRANSITION}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<ProjectGroupLabel
|
||||
isExpanded={isExpanded}
|
||||
onToggleExpand={() => toggleExpanded(group.key)}
|
||||
project={group.representative}
|
||||
title={group.title}
|
||||
totalThreadCount={group.threads.length}
|
||||
/>
|
||||
<View className="bg-screen">
|
||||
{visibleThreads.map((thread, i) => {
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
return (
|
||||
<Animated.View
|
||||
key={threadKey}
|
||||
collapsable={false}
|
||||
exiting={threadRowExit}
|
||||
layout={THREAD_LAYOUT_TRANSITION}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<ThreadRow
|
||||
thread={thread}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
isLast={i === visibleThreads.length - 1}
|
||||
onArchive={() => props.onArchiveThread(thread)}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onPress={() => props.onSelectThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const scrollView = (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
scrollEventThrottle={16}
|
||||
className="flex-1 bg-screen"
|
||||
contentContainerStyle={{
|
||||
minHeight: windowHeight + HOME_COMPACT_HEADER_THRESHOLD + insets.top,
|
||||
paddingHorizontal: 0,
|
||||
paddingTop: Platform.OS === "ios" ? 18 : 0,
|
||||
paddingBottom: Platform.OS === "ios" ? Math.max(insets.bottom, 24) + 132 : 24,
|
||||
gap: 0,
|
||||
}}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios"
|
||||
? {
|
||||
bottom: Math.max(insets.bottom, 16) + 92,
|
||||
top: insets.top + 72,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{listContent}
|
||||
</ScrollView>
|
||||
);
|
||||
|
||||
const connectionStatus =
|
||||
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
|
||||
<View
|
||||
className="absolute left-0 right-0 items-center"
|
||||
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
|
||||
>
|
||||
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
|
||||
</View>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{scrollView}
|
||||
{connectionStatus}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import {
|
||||
shouldShowWorkspaceConnectionStatus,
|
||||
workspaceConnectionStatusLabel,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
|
||||
return {
|
||||
isLoadingConnections: false,
|
||||
hasConnections: true,
|
||||
hasLoadedShellSnapshot: true,
|
||||
hasPendingShellSnapshot: false,
|
||||
hasReadyEnvironment: true,
|
||||
hasConnectingEnvironment: false,
|
||||
connectingEnvironments: [],
|
||||
connectionState: "connected",
|
||||
connectionError: null,
|
||||
shellSnapshotError: null,
|
||||
latestCachedSnapshotReceivedAt: null,
|
||||
networkStatus: "online",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workspace connection status", () => {
|
||||
it("stays hidden while a ready environment is connected", () => {
|
||||
expect(shouldShowWorkspaceConnectionStatus(workspaceState())).toBe(false);
|
||||
});
|
||||
|
||||
it("surfaces offline snapshots", () => {
|
||||
const state = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
|
||||
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("You are offline");
|
||||
});
|
||||
|
||||
it("names the environment while reconnecting", () => {
|
||||
const state = workspaceState({
|
||||
hasConnectingEnvironment: true,
|
||||
hasReadyEnvironment: false,
|
||||
connectingEnvironments: [
|
||||
{
|
||||
environmentId: "environment-1" as never,
|
||||
environmentLabel: "Julius’s Mac mini",
|
||||
displayUrl: "",
|
||||
isRelayManaged: false,
|
||||
connectionState: "reconnecting",
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Reconnecting to Julius’s Mac mini");
|
||||
});
|
||||
|
||||
it("surfaces connection errors before the generic disconnected fallback", () => {
|
||||
const state = workspaceState({
|
||||
connectionError: "Could not reach Julius’s Mac mini",
|
||||
hasLoadedShellSnapshot: false,
|
||||
hasReadyEnvironment: false,
|
||||
});
|
||||
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Could not reach Julius’s Mac mini");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { ActivityIndicator, Pressable } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
|
||||
|
||||
export function WorkspaceConnectionStatus(props: {
|
||||
readonly state: WorkspaceState;
|
||||
readonly onPress: () => void;
|
||||
readonly variant?: "floating" | "sidebar";
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const isReconnecting = props.state.connectingEnvironments.length > 0;
|
||||
const variant = props.variant ?? "floating";
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint="Opens environment settings"
|
||||
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
className={
|
||||
variant === "sidebar"
|
||||
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
|
||||
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
|
||||
}
|
||||
style={
|
||||
variant === "floating"
|
||||
? {
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: 10 },
|
||||
shadowOpacity: 0.12,
|
||||
shadowRadius: 24,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isReconnecting ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
|
||||
)}
|
||||
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{workspaceConnectionStatusLabel(props.state)}
|
||||
</Text>
|
||||
{variant === "sidebar" ? (
|
||||
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
PROJECT_GROUPING_OPTIONS,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
|
||||
export interface HomeListFilterMenuEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
type HomeListFilterMenuAction = {
|
||||
readonly type: "action";
|
||||
readonly title: string;
|
||||
readonly subtitle?: string;
|
||||
readonly state?: "on" | "off";
|
||||
readonly onPress: () => void;
|
||||
};
|
||||
|
||||
type HomeListFilterMenuSubmenu = {
|
||||
readonly type: "submenu";
|
||||
readonly title: string;
|
||||
readonly items: HomeListFilterMenuAction[];
|
||||
};
|
||||
|
||||
export interface HomeListFilterMenu {
|
||||
readonly title: string;
|
||||
readonly items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu>;
|
||||
}
|
||||
|
||||
export function buildHomeListFilterMenu(props: {
|
||||
readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings?: () => void;
|
||||
}): HomeListFilterMenu {
|
||||
const items: Array<HomeListFilterMenuAction | HomeListFilterMenuSubmenu> = [];
|
||||
|
||||
if (props.onOpenSettings) {
|
||||
items.push({
|
||||
type: "action",
|
||||
title: "Settings",
|
||||
onPress: props.onOpenSettings,
|
||||
});
|
||||
}
|
||||
|
||||
items.push(
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Environment",
|
||||
items: [
|
||||
{
|
||||
type: "action",
|
||||
title: "All environments",
|
||||
subtitle: "Show threads from every environment",
|
||||
state: props.selectedEnvironmentId === null ? "on" : "off",
|
||||
onPress: () => props.onEnvironmentChange(null),
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
type: "action" as const,
|
||||
title: environment.label,
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: ("off" as const),
|
||||
onPress: () => props.onEnvironmentChange(environment.environmentId),
|
||||
})),
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort projects",
|
||||
items: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.projectSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Sort threads",
|
||||
items: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
state: props.threadSortOrder === option.value ? "on" : "off",
|
||||
onPress: () => props.onThreadSortOrderChange(option.value),
|
||||
})),
|
||||
},
|
||||
{
|
||||
type: "submenu",
|
||||
title: "Group projects",
|
||||
items: PROJECT_GROUPING_OPTIONS.map((option) => ({
|
||||
type: "action",
|
||||
title: option.label,
|
||||
subtitle: option.subtitle,
|
||||
state: props.projectGroupingMode === option.value ? "on" : "off",
|
||||
onPress: () => props.onProjectGroupingModeChange(option.value),
|
||||
})),
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
title: "Thread list options",
|
||||
items,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { hasCustomHomeListOptions, type HomeListOptions } from "./home-list-options";
|
||||
|
||||
const defaults: HomeListOptions = {
|
||||
selectedEnvironmentId: null,
|
||||
projectSortOrder:
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
|
||||
describe("home list options", () => {
|
||||
it("recognizes default options", () => {
|
||||
expect(hasCustomHomeListOptions(defaults)).toBe(false);
|
||||
});
|
||||
|
||||
it("marks environment filters and grouping changes as customized", () => {
|
||||
expect(
|
||||
hasCustomHomeListOptions({ ...defaults, selectedEnvironmentId: "environment-1" as never }),
|
||||
).toBe(true);
|
||||
expect(hasCustomHomeListOptions({ ...defaults, projectGroupingMode: "separate" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
createContext,
|
||||
createElement,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
type PropsWithChildren,
|
||||
type Dispatch,
|
||||
type SetStateAction,
|
||||
} from "react";
|
||||
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
|
||||
export interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ value: "updated_at", label: "Last user message" },
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
export const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarThreadSortOrder;
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ value: "updated_at", label: "Last user message" },
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
export const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
|
||||
function defaultHomeListOptions(): HomeListOptions {
|
||||
return {
|
||||
selectedEnvironmentId: null,
|
||||
projectSortOrder:
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
};
|
||||
}
|
||||
|
||||
interface HomeListOptionsContextValue {
|
||||
readonly options: HomeListOptions;
|
||||
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
|
||||
}
|
||||
|
||||
const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>(null);
|
||||
|
||||
/** Keeps list preferences stable while the app moves between compact and split shells. */
|
||||
export function HomeListOptionsProvider({ children }: PropsWithChildren) {
|
||||
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const value = useMemo(() => ({ options, setOptions }), [options]);
|
||||
return createElement(HomeListOptionsContext, { value }, children);
|
||||
}
|
||||
|
||||
export function hasCustomHomeListOptions(options: HomeListOptions): boolean {
|
||||
const defaultProjectSortOrder =
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER;
|
||||
return (
|
||||
options.selectedEnvironmentId !== null ||
|
||||
options.projectSortOrder !== defaultProjectSortOrder ||
|
||||
options.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
options.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE
|
||||
);
|
||||
}
|
||||
|
||||
export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<EnvironmentId>) {
|
||||
const shared = useContext(HomeListOptionsContext);
|
||||
const [localOptions, setLocalOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const options = shared?.options ?? localOptions;
|
||||
const setOptions = shared?.setOptions ?? setLocalOptions;
|
||||
const selectedEnvironmentId =
|
||||
options.selectedEnvironmentId !== null &&
|
||||
availableEnvironmentIds.has(options.selectedEnvironmentId)
|
||||
? options.selectedEnvironmentId
|
||||
: null;
|
||||
const resolvedOptions =
|
||||
selectedEnvironmentId === options.selectedEnvironmentId
|
||||
? options
|
||||
: { ...options, selectedEnvironmentId };
|
||||
|
||||
const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
|
||||
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
|
||||
}, []);
|
||||
const setProjectSortOrder = useCallback((value: HomeProjectSortOrder) => {
|
||||
setOptions((current) => ({ ...current, projectSortOrder: value }));
|
||||
}, []);
|
||||
const setThreadSortOrder = useCallback((value: SidebarThreadSortOrder) => {
|
||||
setOptions((current) => ({ ...current, threadSortOrder: value }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((value: SidebarProjectGroupingMode) => {
|
||||
setOptions((current) => ({ ...current, projectGroupingMode: value }));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
options: resolvedOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
setProjectGroupingMode,
|
||||
} as const;
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { ComponentProps } from "react";
|
||||
import type { ColorValue } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef, type ComponentProps, type ReactNode } from "react";
|
||||
import type { ColorValue, StyleProp, ViewStyle } from "react-native";
|
||||
import { Pressable, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import Animated, {
|
||||
Extrapolation,
|
||||
interpolate,
|
||||
@@ -26,6 +29,100 @@ export const THREAD_SWIPE_SPRING = {
|
||||
stiffness: 330,
|
||||
};
|
||||
|
||||
interface ThreadSwipePrimaryAction {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
}
|
||||
|
||||
export function ThreadSwipeable(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly children: (close: () => void) => ReactNode;
|
||||
readonly containerStyle?: StyleProp<ViewStyle>;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly simultaneousWithExternalGesture?: ComponentProps<
|
||||
typeof ReanimatedSwipeable
|
||||
>["simultaneousWithExternalGesture"];
|
||||
readonly threadTitle: string;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, props.fullSwipeWidth * 0.58);
|
||||
const close = useCallback(() => swipeableRef.current?.close(), []);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: props.backgroundColor }}
|
||||
containerStyle={[{ backgroundColor: props.backgroundColor }, props.containerStyle]}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture={props.enableTrackpadSwipe ?? true}
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose?.(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen?.(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onSwipeableWillOpen?.(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={props.backgroundColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
...props.primaryAction,
|
||||
onPress: () => {
|
||||
methods.close();
|
||||
props.primaryAction.onPress();
|
||||
},
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.threadTitle}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
simultaneousWithExternalGesture={props.simultaneousWithExternalGesture}
|
||||
>
|
||||
{props.children(close)}
|
||||
</ReanimatedSwipeable>
|
||||
);
|
||||
}
|
||||
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly backgroundColor: string;
|
||||
@@ -179,12 +276,7 @@ export function ThreadSwipeActions(props: {
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
readonly primaryAction: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
};
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
readonly swipeableMethods: SwipeableMethods;
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
|
||||
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
|
||||
return (
|
||||
state.networkStatus === "offline" ||
|
||||
state.connectionError !== null ||
|
||||
state.hasConnectingEnvironment ||
|
||||
(state.hasLoadedShellSnapshot && !state.hasReadyEnvironment)
|
||||
);
|
||||
}
|
||||
|
||||
export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
|
||||
if (state.networkStatus === "offline") return "You are offline";
|
||||
if (state.connectingEnvironments.length === 1) {
|
||||
return `Reconnecting to ${state.connectingEnvironments[0]!.environmentLabel}`;
|
||||
}
|
||||
if (state.connectingEnvironments.length > 1) {
|
||||
return `Reconnecting ${state.connectingEnvironments.length} environments`;
|
||||
}
|
||||
if (state.connectionError !== null) return state.connectionError;
|
||||
return "Not connected";
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useCurrentPathname, useAppNavigation } from "../../navigation/native-stack-header";
|
||||
import { useCallback, useMemo, useSyncExternalStore, type PropsWithChildren } from "react";
|
||||
|
||||
import {
|
||||
buildThreadFilesNavigation,
|
||||
buildThreadReviewNavigation,
|
||||
buildThreadTerminalNavigation,
|
||||
dismissRoute,
|
||||
newTaskNavigation,
|
||||
} from "../../lib/routes";
|
||||
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
|
||||
import {
|
||||
dispatchHardwareKeyboardCommand,
|
||||
getHardwareKeyboardCommandRegistrationVersion,
|
||||
getRegisteredHardwareKeyboardCommands,
|
||||
parseActiveThreadPath,
|
||||
subscribeToHardwareKeyboardCommandRegistrations,
|
||||
type HardwareKeyboardCommand,
|
||||
} from "./hardwareKeyboardCommands";
|
||||
|
||||
export function HardwareKeyboardCommandProvider({ children }: PropsWithChildren) {
|
||||
const pathname = useCurrentPathname();
|
||||
const navigation = useAppNavigation();
|
||||
const registrationVersion = useSyncExternalStore(
|
||||
subscribeToHardwareKeyboardCommandRegistrations,
|
||||
getHardwareKeyboardCommandRegistrationVersion,
|
||||
getHardwareKeyboardCommandRegistrationVersion,
|
||||
);
|
||||
const enabledCommands = useMemo(() => {
|
||||
const commands = new Set<HardwareKeyboardCommand>(getRegisteredHardwareKeyboardCommands());
|
||||
commands.add("newTask");
|
||||
if (pathname !== "/" || navigation.canGoBack()) commands.add("back");
|
||||
if (parseActiveThreadPath(pathname)) {
|
||||
commands.add("files");
|
||||
commands.add("terminal");
|
||||
commands.add("review");
|
||||
}
|
||||
return [...commands];
|
||||
}, [pathname, registrationVersion, navigation]);
|
||||
|
||||
const onCommand = useCallback(
|
||||
(command: HardwareKeyboardCommand) => {
|
||||
if (dispatchHardwareKeyboardCommand(command)) return;
|
||||
|
||||
if (command === "newTask") {
|
||||
navigation.push(newTaskNavigation());
|
||||
return;
|
||||
}
|
||||
if (command === "back") {
|
||||
dismissRoute(navigation);
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = parseActiveThreadPath(pathname);
|
||||
if (!thread) return;
|
||||
if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) {
|
||||
navigation.push(buildThreadFilesNavigation(thread));
|
||||
}
|
||||
if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) {
|
||||
navigation.push(buildThreadTerminalNavigation(thread));
|
||||
}
|
||||
if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) {
|
||||
navigation.push(buildThreadReviewNavigation(thread));
|
||||
}
|
||||
},
|
||||
[pathname, navigation],
|
||||
);
|
||||
|
||||
return (
|
||||
<T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
|
||||
{children}
|
||||
</T3KeyboardCommands>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { parseActiveThreadPath } from "./hardwareKeyboardCommands";
|
||||
|
||||
describe("parseActiveThreadPath", () => {
|
||||
it("extracts the active thread from thread subroutes", () => {
|
||||
expect(parseActiveThreadPath("/threads/environment-1/thread-1/files/src/index.ts")).toEqual({
|
||||
environmentId: "environment-1",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes route components", () => {
|
||||
expect(parseActiveThreadPath("/threads/local%20machine/thread%2Fone/review")).toEqual({
|
||||
environmentId: "local machine",
|
||||
threadId: "thread/one",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores non-thread routes", () => {
|
||||
expect(parseActiveThreadPath("/settings")).toBeNull();
|
||||
expect(parseActiveThreadPath("/threads/environment-only")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores malformed encoded route components", () => {
|
||||
expect(parseActiveThreadPath("/threads/%E0%A4%A/thread-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export type HardwareKeyboardCommand =
|
||||
| "newTask"
|
||||
| "focusSearch"
|
||||
| "back"
|
||||
| "files"
|
||||
| "terminal"
|
||||
| "review"
|
||||
| "toggleSidebar";
|
||||
|
||||
type CommandHandler = () => boolean | void;
|
||||
|
||||
const handlers = new Map<HardwareKeyboardCommand, Set<CommandHandler>>();
|
||||
const registrationListeners = new Set<() => void>();
|
||||
let registrationVersion = 0;
|
||||
|
||||
/**
|
||||
* Registers a context-specific hardware-keyboard action. The most recently mounted handler gets
|
||||
* the first chance to consume the command, allowing focused screens to override app defaults.
|
||||
*/
|
||||
export function useHardwareKeyboardCommand(
|
||||
command: HardwareKeyboardCommand,
|
||||
handler: CommandHandler,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const commandHandlers = handlers.get(command) ?? new Set<CommandHandler>();
|
||||
commandHandlers.add(handler);
|
||||
handlers.set(command, commandHandlers);
|
||||
registrationVersion += 1;
|
||||
registrationListeners.forEach((listener) => listener());
|
||||
return () => {
|
||||
commandHandlers.delete(handler);
|
||||
if (commandHandlers.size === 0) handlers.delete(command);
|
||||
registrationVersion += 1;
|
||||
registrationListeners.forEach((listener) => listener());
|
||||
};
|
||||
}, [command, handler]);
|
||||
}
|
||||
|
||||
export function getRegisteredHardwareKeyboardCommands(): ReadonlySet<HardwareKeyboardCommand> {
|
||||
return new Set(handlers.keys());
|
||||
}
|
||||
|
||||
export function getHardwareKeyboardCommandRegistrationVersion(): number {
|
||||
return registrationVersion;
|
||||
}
|
||||
|
||||
export function subscribeToHardwareKeyboardCommandRegistrations(listener: () => void): () => void {
|
||||
registrationListeners.add(listener);
|
||||
return () => registrationListeners.delete(listener);
|
||||
}
|
||||
|
||||
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
|
||||
const commandHandlers = handlers.get(command);
|
||||
if (!commandHandlers) return false;
|
||||
for (const handler of [...commandHandlers].toReversed()) {
|
||||
if (handler() !== false) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function parseActiveThreadPath(pathname: string): {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
} | null {
|
||||
const match = /^\/threads\/([^/]+)\/([^/]+)(?:\/|$)/.exec(pathname);
|
||||
if (!match?.[1] || !match[2]) return null;
|
||||
try {
|
||||
return {
|
||||
environmentId: EnvironmentId.make(decodeURIComponent(match[1])),
|
||||
threadId: ThreadId.make(decodeURIComponent(match[2])),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
useFocusEffect,
|
||||
useCurrentRouteParams,
|
||||
useCurrentPathname,
|
||||
useAppNavigation,
|
||||
} from "../../navigation/native-stack-header";
|
||||
import {
|
||||
createContext,
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useWindowDimensions, View } from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
ReduceMotion,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
import {
|
||||
deriveFileInspectorPaneLayout,
|
||||
deriveLayout,
|
||||
deriveWorkspacePaneLayout,
|
||||
type FileInspectorPaneLayout,
|
||||
type Layout,
|
||||
type WorkspaceAuxiliaryPaneRole,
|
||||
type WorkspacePaneLayout,
|
||||
} from "../../lib/layout";
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import {
|
||||
buildThreadFilesNavigation,
|
||||
newTaskNavigation,
|
||||
settingsNavigation,
|
||||
threadNavigation,
|
||||
} from "../../lib/routes";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
|
||||
interface AdaptiveWorkspaceContextValue {
|
||||
readonly layout: Layout;
|
||||
readonly panes: WorkspacePaneLayout;
|
||||
readonly fileInspector: FileInspectorPaneLayout;
|
||||
readonly primarySidebarSearchQuery: string;
|
||||
readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
|
||||
readonly setPrimarySidebarSearchQuery: (query: string) => void;
|
||||
readonly showAuxiliaryPane: (role: WorkspaceAuxiliaryPaneRole) => void;
|
||||
readonly toggleAuxiliaryPane: () => void;
|
||||
readonly togglePrimarySidebar: () => void;
|
||||
readonly setAuxiliaryPaneWidth: (width: number) => void;
|
||||
}
|
||||
|
||||
const compactLayout = deriveLayout({ width: 0, height: 0 });
|
||||
const compactPanes = deriveWorkspacePaneLayout({
|
||||
layout: compactLayout,
|
||||
viewportWidth: 0,
|
||||
primarySidebarPreferredVisible: true,
|
||||
auxiliaryPanePreferredVisible: true,
|
||||
});
|
||||
const compactFileInspector = deriveFileInspectorPaneLayout({
|
||||
layout: compactLayout,
|
||||
viewportWidth: 0,
|
||||
});
|
||||
const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextValue>({
|
||||
layout: compactLayout,
|
||||
panes: compactPanes,
|
||||
fileInspector: compactFileInspector,
|
||||
primarySidebarSearchQuery: "",
|
||||
activateAuxiliaryPaneRole: () => () => undefined,
|
||||
setPrimarySidebarSearchQuery: () => undefined,
|
||||
showAuxiliaryPane: () => undefined,
|
||||
toggleAuxiliaryPane: () => undefined,
|
||||
togglePrimarySidebar: () => undefined,
|
||||
setAuxiliaryPaneWidth: () => undefined,
|
||||
});
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
|
||||
}
|
||||
|
||||
export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue {
|
||||
return use(AdaptiveWorkspaceContext);
|
||||
}
|
||||
|
||||
export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {
|
||||
const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout();
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => activateAuxiliaryPaneRole(role), [activateAuxiliaryPaneRole, role]),
|
||||
);
|
||||
}
|
||||
|
||||
export function AdaptiveWorkspaceLayout(props: { readonly children: ReactNode }) {
|
||||
const { width, height } = useWindowDimensions();
|
||||
const pathname = useCurrentPathname();
|
||||
const navigation = useAppNavigation();
|
||||
const activeRoleOwner = useRef<symbol | null>(null);
|
||||
const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
|
||||
const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);
|
||||
const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true);
|
||||
const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState<number | null>(
|
||||
null,
|
||||
);
|
||||
const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
|
||||
const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
|
||||
useState<WorkspaceAuxiliaryPaneRole | null>(null);
|
||||
const params = useCurrentRouteParams<{
|
||||
environmentId?: string | string[];
|
||||
threadId?: string | string[];
|
||||
}>();
|
||||
const baseLayout = useMemo(() => deriveLayout({ width, height }), [height, width]);
|
||||
const layout = baseLayout;
|
||||
const fileInspector = useMemo(
|
||||
() =>
|
||||
deriveFileInspectorPaneLayout({
|
||||
layout,
|
||||
viewportWidth: width,
|
||||
preferredWidth: fileInspectorPreferredWidth ?? undefined,
|
||||
reservedLeadingWidth:
|
||||
layout.usesSplitView && primarySidebarPreferredVisible ? (layout.listPaneWidth ?? 0) : 0,
|
||||
}),
|
||||
[fileInspectorPreferredWidth, layout, primarySidebarPreferredVisible, width],
|
||||
);
|
||||
const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
|
||||
focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
|
||||
const auxiliaryPanePreferredVisible =
|
||||
auxiliaryPaneRole === "inspector"
|
||||
? fileInspectorPreferredVisible
|
||||
: supplementaryPanePreferredVisible;
|
||||
const auxiliaryPanePreferredWidth =
|
||||
auxiliaryPaneRole === "inspector"
|
||||
? fileInspectorPreferredWidth
|
||||
: supplementaryPanePreferredWidth;
|
||||
const panes = useMemo(
|
||||
() =>
|
||||
deriveWorkspacePaneLayout({
|
||||
layout,
|
||||
viewportWidth: width,
|
||||
primarySidebarPreferredVisible,
|
||||
auxiliaryPanePreferredVisible,
|
||||
auxiliaryPaneRole,
|
||||
auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
|
||||
}),
|
||||
[
|
||||
auxiliaryPanePreferredVisible,
|
||||
auxiliaryPaneRole,
|
||||
auxiliaryPanePreferredWidth,
|
||||
layout,
|
||||
primarySidebarPreferredVisible,
|
||||
width,
|
||||
],
|
||||
);
|
||||
const environmentId = firstRouteParam(params.environmentId);
|
||||
const threadId = firstRouteParam(params.threadId);
|
||||
const selectedThreadKey = useMemo(() => {
|
||||
if (environmentId === null || threadId === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [environmentId, threadId]);
|
||||
const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
|
||||
const owner = Symbol(role);
|
||||
activeRoleOwner.current = owner;
|
||||
setFocusedAuxiliaryPaneRole(role);
|
||||
|
||||
return () => {
|
||||
if (activeRoleOwner.current !== owner) {
|
||||
return;
|
||||
}
|
||||
activeRoleOwner.current = null;
|
||||
setFocusedAuxiliaryPaneRole(null);
|
||||
};
|
||||
}, []);
|
||||
const togglePrimarySidebar = useCallback(() => {
|
||||
if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
|
||||
setFileInspectorPreferredVisible(false);
|
||||
setPrimarySidebarPreferredVisible(true);
|
||||
return;
|
||||
}
|
||||
setPrimarySidebarPreferredVisible((current) => !current);
|
||||
}, [panes.primarySidebarSuppressedByAuxiliary, panes.primarySidebarVisible]);
|
||||
const revealPrimarySidebar = useCallback(() => {
|
||||
if (panes.primarySidebarSuppressedByAuxiliary) {
|
||||
setFileInspectorPreferredVisible(false);
|
||||
}
|
||||
setPrimarySidebarPreferredVisible(true);
|
||||
}, [panes.primarySidebarSuppressedByAuxiliary]);
|
||||
const handleToggleSidebarCommand = useCallback(() => {
|
||||
togglePrimarySidebar();
|
||||
return true;
|
||||
}, [togglePrimarySidebar]);
|
||||
useHardwareKeyboardCommand("toggleSidebar", handleToggleSidebarCommand);
|
||||
const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
|
||||
if (role === "inspector") {
|
||||
setFocusedAuxiliaryPaneRole("inspector");
|
||||
setFileInspectorPreferredVisible(true);
|
||||
return;
|
||||
}
|
||||
setFocusedAuxiliaryPaneRole("supplementary");
|
||||
setSupplementaryPanePreferredVisible(true);
|
||||
}, []);
|
||||
const handleOpenFilesCommand = useCallback(() => {
|
||||
const activeThread = parseActiveThreadPath(pathname);
|
||||
if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
|
||||
return false;
|
||||
}
|
||||
showAuxiliaryPane("inspector");
|
||||
if (/\/files(?:\/|$)/.test(pathname)) {
|
||||
return true;
|
||||
}
|
||||
navigation.replace(buildThreadFilesNavigation(activeThread));
|
||||
return true;
|
||||
}, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]);
|
||||
useHardwareKeyboardCommand("files", handleOpenFilesCommand);
|
||||
const toggleAuxiliaryPane = useCallback(() => {
|
||||
if (auxiliaryPaneRole === "inspector") {
|
||||
setFileInspectorPreferredVisible((current) => !current);
|
||||
return;
|
||||
}
|
||||
setSupplementaryPanePreferredVisible((current) => !current);
|
||||
}, [auxiliaryPaneRole]);
|
||||
const setAuxiliaryPaneWidth = useCallback(
|
||||
(nextWidth: number) => {
|
||||
if (auxiliaryPaneRole === "inspector") {
|
||||
setFileInspectorPreferredWidth(nextWidth);
|
||||
return;
|
||||
}
|
||||
setSupplementaryPanePreferredWidth(nextWidth);
|
||||
},
|
||||
[auxiliaryPaneRole],
|
||||
);
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
layout,
|
||||
panes,
|
||||
fileInspector,
|
||||
primarySidebarSearchQuery,
|
||||
activateAuxiliaryPaneRole,
|
||||
setPrimarySidebarSearchQuery,
|
||||
showAuxiliaryPane,
|
||||
toggleAuxiliaryPane,
|
||||
togglePrimarySidebar,
|
||||
setAuxiliaryPaneWidth,
|
||||
}),
|
||||
[
|
||||
activateAuxiliaryPaneRole,
|
||||
fileInspector,
|
||||
layout,
|
||||
panes,
|
||||
primarySidebarSearchQuery,
|
||||
showAuxiliaryPane,
|
||||
setPrimarySidebarSearchQuery,
|
||||
setAuxiliaryPaneWidth,
|
||||
toggleAuxiliaryPane,
|
||||
togglePrimarySidebar,
|
||||
],
|
||||
);
|
||||
|
||||
const handleOpenSettings = useCallback(() => {
|
||||
navigation.push(settingsNavigation());
|
||||
}, [navigation]);
|
||||
const handleStartNewTask = useCallback(() => {
|
||||
navigation.push(newTaskNavigation());
|
||||
}, [navigation]);
|
||||
|
||||
const renderedSidebarWidth = useSharedValue(
|
||||
panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
|
||||
);
|
||||
useEffect(() => {
|
||||
const targetWidth = panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0;
|
||||
renderedSidebarWidth.value = withTiming(targetWidth, {
|
||||
duration: panes.primarySidebarVisible ? 220 : 160,
|
||||
easing: panes.primarySidebarVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
|
||||
reduceMotion: ReduceMotion.System,
|
||||
});
|
||||
}, [layout.listPaneWidth, panes.primarySidebarVisible, renderedSidebarWidth]);
|
||||
const sidebarAnimatedStyle = useAnimatedStyle(() => ({
|
||||
opacity: Math.min(1, renderedSidebarWidth.value / 80),
|
||||
width: renderedSidebarWidth.value,
|
||||
}));
|
||||
|
||||
const handleSelectThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
const destination = threadNavigation(thread);
|
||||
const navigationAction = resolveThreadSelectionNavigationAction({
|
||||
usesSplitView: layout.usesSplitView,
|
||||
pathname,
|
||||
});
|
||||
if (navigationAction === "set-params") {
|
||||
const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (nextThreadKey === selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
setFileInspectorPreferredVisible(false);
|
||||
navigation.setParams({
|
||||
environmentId: String(thread.environmentId),
|
||||
threadId: String(thread.id),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (navigationAction === "replace") {
|
||||
setFileInspectorPreferredVisible(false);
|
||||
navigation.replace(destination);
|
||||
return;
|
||||
}
|
||||
navigation.push(destination);
|
||||
},
|
||||
[layout.usesSplitView, pathname, navigation, selectedThreadKey],
|
||||
);
|
||||
|
||||
return (
|
||||
<HomeListOptionsProvider>
|
||||
<AdaptiveWorkspaceContext.Provider value={contextValue}>
|
||||
<View testID="adaptive-workspace-layout" style={{ flex: 1, flexDirection: "row" }}>
|
||||
{layout.usesSplitView && layout.listPaneWidth !== null ? (
|
||||
<Animated.View
|
||||
accessibilityElementsHidden={!panes.primarySidebarVisible}
|
||||
collapsable={false}
|
||||
importantForAccessibility={
|
||||
panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
|
||||
}
|
||||
pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
|
||||
style={[{ alignSelf: "stretch", overflow: "hidden" }, sidebarAnimatedStyle]}
|
||||
>
|
||||
<ThreadNavigationSidebar
|
||||
width={layout.listPaneWidth}
|
||||
visible={panes.primarySidebarVisible}
|
||||
onRequestVisibility={revealPrimarySidebar}
|
||||
selectedThreadKey={selectedThreadKey}
|
||||
onOpenSettings={handleOpenSettings}
|
||||
onSelectThread={handleSelectThread}
|
||||
onSearchQueryChange={setPrimarySidebarSearchQuery}
|
||||
onStartNewTask={handleStartNewTask}
|
||||
searchQuery={primarySidebarSearchQuery}
|
||||
/>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<View collapsable={false} style={{ flex: 1 }}>
|
||||
{props.children}
|
||||
</View>
|
||||
</View>
|
||||
</AdaptiveWorkspaceContext.Provider>
|
||||
</HomeListOptionsProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export function WorkspaceEmptyDetail() {
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-screen px-10">
|
||||
<View className="max-w-[360px] items-center gap-3">
|
||||
<SymbolView name="sidebar.left" size={34} tintColor={iconColor} type="hierarchical" />
|
||||
<Text className="text-center text-xl font-t3-bold">Select a thread</Text>
|
||||
<Text className="text-center text-base text-foreground-muted">
|
||||
Choose a thread from the sidebar or start a new task.
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
ReduceMotion,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
import { constrainAuxiliaryPaneWidth } from "../../lib/layout";
|
||||
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
|
||||
import { WorkspacePaneDivider } from "./workspace-pane-divider";
|
||||
|
||||
export function AdaptiveInspectorLayout(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly renderInspector?: () => ReactNode;
|
||||
}) {
|
||||
const { panes, setAuxiliaryPaneWidth } = useAdaptiveWorkspaceLayout();
|
||||
const inspectorWidth = panes.auxiliaryPaneWidth;
|
||||
const inspectorSupported = props.renderInspector !== undefined && inspectorWidth !== null;
|
||||
const inspectorVisible = inspectorSupported && panes.auxiliaryPaneVisible;
|
||||
const resizeStartWidth = useRef(0);
|
||||
const [resizing, setResizing] = useState(false);
|
||||
|
||||
// A file-to-file replace remounts the route. Initialize an already-visible
|
||||
// inspector at its final position so route replacement never replays an
|
||||
// entering transition. Only visibility and explicit resizing change it.
|
||||
const inspectorProgress = useSharedValue(inspectorVisible ? 1 : 0);
|
||||
const renderedInspectorWidth = useSharedValue(inspectorVisible ? (inspectorWidth ?? 0) : 0);
|
||||
|
||||
useEffect(() => {
|
||||
inspectorProgress.value = withTiming(inspectorVisible ? 1 : 0, {
|
||||
duration: inspectorVisible ? 220 : 160,
|
||||
easing: inspectorVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
|
||||
reduceMotion: ReduceMotion.System,
|
||||
});
|
||||
const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0;
|
||||
renderedInspectorWidth.value = resizing
|
||||
? targetWidth
|
||||
: withTiming(targetWidth, {
|
||||
duration: inspectorVisible ? 220 : 160,
|
||||
easing: inspectorVisible ? Easing.out(Easing.cubic) : Easing.in(Easing.cubic),
|
||||
reduceMotion: ReduceMotion.System,
|
||||
});
|
||||
}, [inspectorProgress, inspectorVisible, inspectorWidth, renderedInspectorWidth, resizing]);
|
||||
|
||||
const inspectorStyle = useAnimatedStyle(
|
||||
() => ({
|
||||
opacity: inspectorProgress.value,
|
||||
transform: [{ translateX: (1 - inspectorProgress.value) * 24 }],
|
||||
width: renderedInspectorWidth.value,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
const beginResize = useCallback(() => {
|
||||
resizeStartWidth.current = inspectorWidth ?? 0;
|
||||
setResizing(true);
|
||||
}, [inspectorWidth]);
|
||||
const resizeBy = useCallback(
|
||||
(delta: number) => {
|
||||
setAuxiliaryPaneWidth(
|
||||
constrainAuxiliaryPaneWidth({
|
||||
preferredWidth: resizeStartWidth.current + delta,
|
||||
availableWidth: panes.contentPaneWidth,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[panes.contentPaneWidth, setAuxiliaryPaneWidth],
|
||||
);
|
||||
const endResize = useCallback(() => {
|
||||
setResizing(false);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<View className="flex-1 flex-row">
|
||||
<Animated.View collapsable={false} className="min-w-0 flex-1">
|
||||
{props.children}
|
||||
</Animated.View>
|
||||
{inspectorVisible ? (
|
||||
<WorkspacePaneDivider
|
||||
accessibilityLabel="Resize detail pane"
|
||||
currentWidth={inspectorWidth ?? 0}
|
||||
resizeDirection={-1}
|
||||
onResizeStart={beginResize}
|
||||
onResizeBy={resizeBy}
|
||||
onResizeEnd={endResize}
|
||||
/>
|
||||
) : null}
|
||||
{inspectorSupported ? (
|
||||
<Animated.View
|
||||
accessibilityElementsHidden={!inspectorVisible}
|
||||
collapsable={false}
|
||||
importantForAccessibility={inspectorVisible ? "auto" : "no-hide-descendants"}
|
||||
pointerEvents={inspectorVisible ? "auto" : "none"}
|
||||
style={[{ flexShrink: 0, overflow: "hidden" }, inspectorStyle]}
|
||||
>
|
||||
<View style={{ flex: 1, width: inspectorWidth }}>{props.renderInspector?.()}</View>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
type NativeGlassHeaderItem = {
|
||||
readonly type: "button" | "menu";
|
||||
readonly glassEffect?: boolean;
|
||||
readonly sharesBackground?: boolean;
|
||||
readonly variant?: "plain" | "done" | "prominent";
|
||||
readonly width?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* iOS 26/27 Mail-style header controls need the native glass button
|
||||
* configuration when they are not part of a larger toolbar. Keep this
|
||||
* centralized so native-stack screens and plain react-native-screens demos
|
||||
* don't drift apart.
|
||||
*/
|
||||
export function withNativeGlassHeaderItem<T extends NativeGlassHeaderItem>(
|
||||
item: T,
|
||||
options: {
|
||||
readonly sharesBackground?: boolean;
|
||||
readonly width?: number;
|
||||
} = {},
|
||||
): T {
|
||||
return {
|
||||
...item,
|
||||
glassEffect: item.glassEffect ?? true,
|
||||
sharesBackground: options.sharesBackground ?? item.sharesBackground ?? true,
|
||||
variant: item.variant ?? "prominent",
|
||||
...(options.width !== undefined || item.width !== undefined
|
||||
? { width: options.width ?? item.width }
|
||||
: {}),
|
||||
} as T;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { HeaderBarButtonMailSearchToolbarItem } from "react-native-screens";
|
||||
|
||||
type NativeMailSearchToolbarInput = Omit<
|
||||
HeaderBarButtonMailSearchToolbarItem,
|
||||
"type" | "useFallbackSearchField"
|
||||
>;
|
||||
|
||||
/**
|
||||
* Builds the patched react-native-screens Mail-style bottom search toolbar.
|
||||
*
|
||||
* Keeping this behind an app-level helper makes the iOS-only RNS patch an
|
||||
* explicit layout primitive instead of a per-screen object literal. Android can
|
||||
* keep using platform-specific header/search primitives without depending on
|
||||
* this helper.
|
||||
*/
|
||||
export function createNativeMailSearchToolbarItem(
|
||||
input: NativeMailSearchToolbarInput,
|
||||
): HeaderBarButtonMailSearchToolbarItem {
|
||||
return {
|
||||
placeholder: "Search",
|
||||
...input,
|
||||
type: "mailSearchToolbar",
|
||||
useFallbackSearchField: true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Platform,
|
||||
PlatformColor,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
View,
|
||||
type AccessibilityActionEvent,
|
||||
} from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { runOnJS } from "react-native-reanimated";
|
||||
|
||||
const ACCESSIBILITY_RESIZE_STEP = 24;
|
||||
|
||||
interface WorkspacePaneDividerProps {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly currentWidth: number;
|
||||
/** 1 when dragging right grows the pane, -1 when dragging left grows it. */
|
||||
readonly resizeDirection: 1 | -1;
|
||||
readonly onResizeStart?: () => void;
|
||||
readonly onResizeBy: (delta: number) => void;
|
||||
readonly onResizeEnd?: () => void;
|
||||
}
|
||||
|
||||
/** A forgiving divider target for touch, pointer, and VoiceOver users. */
|
||||
export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
|
||||
const latestProps = useRef(props);
|
||||
latestProps.current = props;
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const handleResizeStart = useCallback(() => {
|
||||
setDragging(true);
|
||||
latestProps.current.onResizeStart?.();
|
||||
}, []);
|
||||
const handleResize = useCallback((translationX: number) => {
|
||||
latestProps.current.onResizeBy(translationX * latestProps.current.resizeDirection);
|
||||
}, []);
|
||||
const handleResizeEnd = useCallback(() => {
|
||||
setDragging(false);
|
||||
latestProps.current.onResizeEnd?.();
|
||||
}, []);
|
||||
const resizeGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.activeOffsetX([-4, 4])
|
||||
.failOffsetY([-24, 24])
|
||||
.onStart(() => {
|
||||
runOnJS(handleResizeStart)();
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
runOnJS(handleResize)(event.translationX);
|
||||
})
|
||||
.onFinalize(() => {
|
||||
runOnJS(handleResizeEnd)();
|
||||
}),
|
||||
[handleResize, handleResizeEnd, handleResizeStart],
|
||||
);
|
||||
|
||||
const handleAccessibilityAction = (event: AccessibilityActionEvent) => {
|
||||
props.onResizeStart?.();
|
||||
if (event.nativeEvent.actionName === "increment") {
|
||||
props.onResizeBy(ACCESSIBILITY_RESIZE_STEP);
|
||||
} else if (event.nativeEvent.actionName === "decrement") {
|
||||
props.onResizeBy(-ACCESSIBILITY_RESIZE_STEP);
|
||||
}
|
||||
props.onResizeEnd?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<GestureDetector gesture={resizeGesture}>
|
||||
<Pressable
|
||||
accessibilityActions={[
|
||||
{ name: "increment", label: "Make pane wider" },
|
||||
{ name: "decrement", label: "Make pane narrower" },
|
||||
]}
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="adjustable"
|
||||
accessibilityValue={{
|
||||
now: Math.round(props.currentWidth),
|
||||
text: `${Math.round(props.currentWidth)} points wide`,
|
||||
}}
|
||||
onAccessibilityAction={handleAccessibilityAction}
|
||||
onHoverIn={() => setHovered(true)}
|
||||
onHoverOut={() => setHovered(false)}
|
||||
style={styles.hitTarget}
|
||||
>
|
||||
<View style={[styles.line, (hovered || dragging) && styles.activeLine]} />
|
||||
</Pressable>
|
||||
</GestureDetector>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
hitTarget: {
|
||||
alignSelf: "stretch",
|
||||
cursor: "pointer",
|
||||
justifyContent: "center",
|
||||
marginHorizontal: -22,
|
||||
position: "relative",
|
||||
width: 44,
|
||||
zIndex: 100,
|
||||
},
|
||||
line: {
|
||||
alignSelf: "center",
|
||||
backgroundColor:
|
||||
Platform.OS === "ios" ? PlatformColor("separator") : "rgba(120, 120, 128, 0.28)",
|
||||
height: "100%",
|
||||
opacity: 0.7,
|
||||
width: StyleSheet.hairlineWidth,
|
||||
},
|
||||
activeLine: {
|
||||
backgroundColor: Platform.OS === "ios" ? PlatformColor("systemBlueColor") : "#0a84ff",
|
||||
opacity: 1,
|
||||
width: 2,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NativeHeaderToolbar } from "../../navigation/native-stack-header";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
|
||||
|
||||
export function WorkspaceSidebarToolbar(
|
||||
props: {
|
||||
readonly children?: ReactNode;
|
||||
readonly afterSidebarButton?: ReactNode;
|
||||
} = {},
|
||||
) {
|
||||
const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
|
||||
|
||||
if (!layout.usesSplitView) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<NativeHeaderToolbar placement="left">
|
||||
{props.children}
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel={
|
||||
panes.primarySidebarVisible ? "Maximize content" : "Show thread sidebar"
|
||||
}
|
||||
icon={panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"}
|
||||
onPress={togglePrimarySidebar}
|
||||
/>
|
||||
{props.afterSidebarButton}
|
||||
</NativeHeaderToolbar>
|
||||
);
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
isFilesystemBrowseQuery,
|
||||
} from "@t3tools/client-runtime/state/projects";
|
||||
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
|
||||
@@ -40,6 +40,13 @@ import { sourceControlEnvironment } from "../../state/sourceControl";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ErrorBanner } from "../../components/ErrorBanner";
|
||||
import { SourceControlIcon } from "../../components/SourceControlIcon";
|
||||
import {
|
||||
addProjectDestinationNavigation,
|
||||
addProjectLocalNavigation,
|
||||
addProjectRepositoryNavigation,
|
||||
connectionsNewNavigation,
|
||||
newTaskDraftNavigation,
|
||||
} from "../../lib/routes";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
@@ -250,8 +257,8 @@ function useSelectedEnvironment(): {
|
||||
readonly selectedEnvironment: EnvironmentOption | null;
|
||||
readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
|
||||
} {
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{ environmentId?: string }>();
|
||||
const navigation = useAppNavigation();
|
||||
const params = useRouteParams<{ environmentId?: string }>();
|
||||
const environmentOptions = useEnvironmentOptions();
|
||||
const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null;
|
||||
const selectedEnvironment =
|
||||
@@ -264,12 +271,12 @@ function useSelectedEnvironment(): {
|
||||
return {
|
||||
environmentOptions,
|
||||
selectedEnvironment,
|
||||
setSelectedEnvironmentId: (environmentId) => router.setParams({ environmentId }),
|
||||
setSelectedEnvironmentId: (environmentId) => navigation.setParams({ environmentId }),
|
||||
};
|
||||
}
|
||||
|
||||
function EmptyEnvironmentState() {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
|
||||
return (
|
||||
<View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
|
||||
@@ -278,7 +285,7 @@ function EmptyEnvironmentState() {
|
||||
Add an environment before adding a project.
|
||||
</Text>
|
||||
<Pressable
|
||||
onPress={() => router.replace("/connections/new")}
|
||||
onPress={() => navigation.replace(connectionsNewNavigation())}
|
||||
className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
|
||||
@@ -294,7 +301,7 @@ function SourceControlRow(props: {
|
||||
readonly hint: string;
|
||||
readonly isFirst: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const title =
|
||||
props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
|
||||
@@ -322,20 +329,19 @@ function SourceControlRow(props: {
|
||||
icon={icon}
|
||||
isFirst={props.isFirst}
|
||||
onPress={() =>
|
||||
router.push({
|
||||
pathname: "/new/add-project/repository",
|
||||
params: {
|
||||
navigation.push(
|
||||
addProjectRepositoryNavigation({
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
source: props.source,
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddProjectSourceScreen() {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
|
||||
@@ -409,10 +415,11 @@ export function AddProjectSourceScreen() {
|
||||
}
|
||||
isFirst
|
||||
onPress={() =>
|
||||
router.push({
|
||||
pathname: "/new/add-project/local",
|
||||
params: { environmentId: selectedEnvironment.environmentId },
|
||||
})
|
||||
navigation.push(
|
||||
addProjectLocalNavigation({
|
||||
environmentId: selectedEnvironment.environmentId,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
|
||||
@@ -440,7 +447,7 @@ export function AddProjectSourceScreen() {
|
||||
}
|
||||
|
||||
function useCreateProject(environment: EnvironmentOption | null) {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
|
||||
const projects = useProjects();
|
||||
|
||||
@@ -455,14 +462,13 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
});
|
||||
if (existing) {
|
||||
Alert.alert("Project already exists", existing.title);
|
||||
router.replace({
|
||||
pathname: "/new/draft",
|
||||
params: {
|
||||
navigation.replace(
|
||||
newTaskDraftNavigation({
|
||||
environmentId: existing.environmentId,
|
||||
projectId: existing.id,
|
||||
title: existing.title,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -480,22 +486,21 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
if (AsyncResult.isFailure(result)) {
|
||||
return result;
|
||||
}
|
||||
router.replace({
|
||||
pathname: "/new/draft",
|
||||
params: {
|
||||
navigation.replace(
|
||||
newTaskDraftNavigation({
|
||||
environmentId: environment.environmentId,
|
||||
projectId,
|
||||
title: inferProjectTitleFromPath(workspaceRoot),
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
},
|
||||
[createProject, environment, projects, router],
|
||||
[createProject, environment, projects, navigation],
|
||||
);
|
||||
}
|
||||
|
||||
function useEnvironmentFromParam(): EnvironmentOption | null {
|
||||
const params = useLocalSearchParams<{ environmentId?: string }>();
|
||||
const params = useRouteParams<{ environmentId?: string }>();
|
||||
const environmentOptions = useEnvironmentOptions();
|
||||
const environmentId = stringParam(params.environmentId) as EnvironmentId | null;
|
||||
return (
|
||||
@@ -509,8 +514,8 @@ export function AddProjectRepositoryScreen() {
|
||||
const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
|
||||
const navigation = useAppNavigation();
|
||||
const params = useRouteParams<{ environmentId?: string; source?: string }>();
|
||||
const environment = useEnvironmentFromParam();
|
||||
const source = sourceFromParam(params.source);
|
||||
const [repositoryInput, setRepositoryInput] = useState("");
|
||||
@@ -524,15 +529,14 @@ export function AddProjectRepositoryScreen() {
|
||||
const provider = addProjectRemoteSourceProvider(source);
|
||||
if (!provider) {
|
||||
const remoteUrl = repositoryInput.trim();
|
||||
router.push({
|
||||
pathname: "/new/add-project/destination",
|
||||
params: {
|
||||
navigation.push(
|
||||
addProjectDestinationNavigation({
|
||||
environmentId: environment.environmentId,
|
||||
source,
|
||||
remoteUrl,
|
||||
repositoryTitle: remoteUrl,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
@@ -548,18 +552,17 @@ export function AddProjectRepositoryScreen() {
|
||||
setError(errorMessage(Cause.squash(result.cause)));
|
||||
} else {
|
||||
const repository = result.value;
|
||||
router.push({
|
||||
pathname: "/new/add-project/destination",
|
||||
params: {
|
||||
navigation.push(
|
||||
addProjectDestinationNavigation({
|
||||
environmentId: environment.environmentId,
|
||||
source,
|
||||
remoteUrl: repository.sshUrl,
|
||||
repositoryTitle: repository.nameWithOwner,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
setIsSubmitting(false);
|
||||
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, router, source]);
|
||||
}, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
|
||||
|
||||
return (
|
||||
<AddProjectShell>
|
||||
@@ -749,7 +752,7 @@ export function AddProjectDestinationScreen() {
|
||||
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const params = useLocalSearchParams<{
|
||||
const params = useRouteParams<{
|
||||
environmentId?: string;
|
||||
remoteUrl?: string;
|
||||
repositoryTitle?: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
@@ -41,13 +41,13 @@ import {
|
||||
const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
|
||||
|
||||
export function ReviewCommentComposerSheet() {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { width } = useWindowDimensions();
|
||||
const colorScheme = useColorScheme();
|
||||
const iconTint = String(useThemeColor("--color-icon"));
|
||||
const target = useReviewCommentTarget();
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
const { environmentId, threadId } = useRouteParams<{
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
}>();
|
||||
@@ -84,8 +84,8 @@ export function ReviewCommentComposerSheet() {
|
||||
const previewViewportWidth = Math.max(width - 40, 280);
|
||||
const dismissComposer = useCallback(() => {
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}, [router]);
|
||||
navigation.dismiss();
|
||||
}, [navigation]);
|
||||
const handleNativePaste = useNativePaste((uris) => {
|
||||
void (async () => {
|
||||
try {
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { useRouteParams } from "../../navigation/native-stack-header";
|
||||
import { useHeaderHeight } from "@react-navigation/elements";
|
||||
import {
|
||||
NativeHeaderToolbar,
|
||||
NativeStackScreenOptions,
|
||||
} from "../../navigation/native-stack-header";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, type ReactElement, useCallback, useMemo } from "react";
|
||||
import {
|
||||
memo,
|
||||
type Ref,
|
||||
type ReactElement,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
type NativeSyntheticEvent,
|
||||
@@ -19,24 +35,37 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
import { useEnvironmentPresentation } from "../../state/presentation";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
|
||||
import {
|
||||
useAdaptiveWorkspaceLayout,
|
||||
useAdaptiveWorkspacePaneRole,
|
||||
} from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useReviewCacheForThread } from "./reviewState";
|
||||
import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";
|
||||
import {
|
||||
type NativeReviewDiffViewHandle,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
import {
|
||||
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
|
||||
NATIVE_REVIEW_DIFF_ROW_HEIGHT,
|
||||
} from "./nativeReviewDiffAdapter";
|
||||
import { useReviewDiffData } from "./useReviewDiffData";
|
||||
import { useReviewDiffPrewarming } from "./useReviewDiffPrewarming";
|
||||
import { useReviewFileVisibility } from "./reviewFileVisibility";
|
||||
import { useReviewSections } from "./useReviewSections";
|
||||
import { useNativeReviewDiffBridge } from "./useNativeReviewDiffBridge";
|
||||
import { useReviewCommentSelectionController } from "./useReviewCommentSelectionController";
|
||||
import { resolveReviewAvailability } from "./reviewAvailability";
|
||||
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
|
||||
import { buildReviewSectionMenu } from "./review-section-menu";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
const IOS_NAV_BAR_HEIGHT = 44;
|
||||
const REVIEW_HEADER_SPACING = 0;
|
||||
|
||||
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
|
||||
@@ -110,13 +139,266 @@ function ReviewSelectionActionBar(props: {
|
||||
);
|
||||
}
|
||||
|
||||
interface ReviewNavigatorFile {
|
||||
readonly id: string;
|
||||
readonly path: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: {
|
||||
readonly file: ReviewNavigatorFile;
|
||||
readonly selected: boolean;
|
||||
readonly onSelectFile: (fileId: string | null) => void;
|
||||
}) {
|
||||
const { file, selected, onSelectFile } = props;
|
||||
const handlePress = useCallback(() => {
|
||||
onSelectFile(file.id);
|
||||
}, [file.id, onSelectFile]);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
className={
|
||||
selected
|
||||
? "mt-1 min-h-12 justify-center rounded-xl bg-subtle-strong px-3 py-2"
|
||||
: "mt-1 min-h-12 justify-center rounded-xl px-3 py-2 active:bg-subtle"
|
||||
}
|
||||
onPress={handlePress}
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
selected
|
||||
? "text-xs font-t3-bold text-foreground"
|
||||
: "text-xs font-t3-medium text-foreground-secondary"
|
||||
}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{file.path}
|
||||
</Text>
|
||||
<View className="mt-1 flex-row gap-2">
|
||||
<Text className="text-2xs font-t3-bold text-emerald-600">+{file.additions}</Text>
|
||||
<Text className="text-2xs font-t3-bold text-rose-600">-{file.deletions}</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
interface ReviewFileNavigatorHandle {
|
||||
readonly setVisibleFile: (fileId: string | null) => void;
|
||||
}
|
||||
|
||||
interface ReviewFileNavigatorProps {
|
||||
readonly files: ReadonlyArray<ReviewNavigatorFile>;
|
||||
readonly headerInset: number;
|
||||
readonly sectionId: string | null;
|
||||
readonly onSelectFile: (fileId: string | null) => void;
|
||||
readonly ref?: Ref<ReviewFileNavigatorHandle>;
|
||||
}
|
||||
|
||||
function ReviewFileNavigator({
|
||||
files,
|
||||
headerInset,
|
||||
sectionId,
|
||||
onSelectFile,
|
||||
ref,
|
||||
}: ReviewFileNavigatorProps) {
|
||||
const [fileSelection, setFileSelection] = useState<{
|
||||
readonly sectionId: string | null;
|
||||
readonly fileId: string | null;
|
||||
}>({ sectionId: null, fileId: null });
|
||||
const availableFileIds = useMemo(() => files.map((file) => file.id), [files]);
|
||||
const selectedFileId = resolveSelectedReviewFileId({
|
||||
selection: fileSelection,
|
||||
sectionId,
|
||||
availableFileIds,
|
||||
});
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
setVisibleFile: (fileId) => {
|
||||
if (fileId !== null && !availableFileIds.includes(fileId)) {
|
||||
return;
|
||||
}
|
||||
setFileSelection((current) => {
|
||||
if (current.sectionId === sectionId && current.fileId === fileId) {
|
||||
return current;
|
||||
}
|
||||
return { sectionId, fileId };
|
||||
});
|
||||
},
|
||||
}),
|
||||
[availableFileIds, sectionId],
|
||||
);
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(fileId: string | null) => {
|
||||
setFileSelection({ sectionId, fileId });
|
||||
onSelectFile(fileId);
|
||||
},
|
||||
[onSelectFile, sectionId],
|
||||
);
|
||||
|
||||
const renderFile = useCallback(
|
||||
({ item }: { readonly item: ReviewNavigatorFile }) => (
|
||||
<ReviewFileNavigatorRow
|
||||
file={item}
|
||||
selected={selectedFileId === item.id}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
),
|
||||
[handleSelectFile, selectedFileId],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1 border-l border-border bg-sheet">
|
||||
<View className="border-b border-border" style={{ paddingTop: headerInset }}>
|
||||
<View className="px-4 py-3">
|
||||
<Text className="text-sm font-t3-bold text-foreground">Changed files</Text>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{files.length} {files.length === 1 ? "file" : "files"}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<FlatList
|
||||
data={files}
|
||||
extraData={selectedFileId}
|
||||
keyExtractor={(file) => file.id}
|
||||
contentContainerStyle={{ paddingHorizontal: 8, paddingVertical: 8 }}
|
||||
ListHeaderComponent={
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: selectedFileId === null }}
|
||||
className={
|
||||
selectedFileId === null
|
||||
? "min-h-11 justify-center rounded-xl bg-subtle-strong px-3"
|
||||
: "min-h-11 justify-center rounded-xl px-3 active:bg-subtle"
|
||||
}
|
||||
onPress={() => handleSelectFile(null)}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-foreground">All files</Text>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{files.length} changed {files.length === 1 ? "file" : "files"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
}
|
||||
renderItem={renderFile}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewHeaderTitle(props: {
|
||||
readonly additions: string | null;
|
||||
readonly deletions: string | null;
|
||||
readonly foregroundColor: string;
|
||||
readonly mutedColor: string;
|
||||
readonly pendingCommentCount: number;
|
||||
readonly sectionTitle: string;
|
||||
}) {
|
||||
return (
|
||||
<View style={{ alignItems: "center" }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
fontWeight: "900",
|
||||
color: props.foregroundColor,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
Files Changed
|
||||
</NativeText>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 6,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
{props.additions && props.deletions ? (
|
||||
<>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#16a34a",
|
||||
}}
|
||||
>
|
||||
{props.additions}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#e11d48",
|
||||
}}
|
||||
>
|
||||
{props.deletions}
|
||||
</NativeText>
|
||||
{props.pendingCommentCount > 0 ? (
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#b45309",
|
||||
}}
|
||||
>
|
||||
{props.pendingCommentCount} pending
|
||||
</NativeText>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: props.mutedColor,
|
||||
}}
|
||||
>
|
||||
{props.sectionTitle}
|
||||
</NativeText>
|
||||
{props.pendingCommentCount > 0 ? (
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#b45309",
|
||||
}}
|
||||
>
|
||||
{props.pendingCommentCount} pending
|
||||
</NativeText>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReviewSheet() {
|
||||
useAdaptiveWorkspacePaneRole("inspector");
|
||||
const { layout, panes, showAuxiliaryPane, toggleAuxiliaryPane, togglePrimarySidebar } =
|
||||
useAdaptiveWorkspaceLayout();
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const colorScheme = useColorScheme();
|
||||
const headerForeground = String(useThemeColor("--color-foreground"));
|
||||
const headerMuted = String(useThemeColor("--color-foreground-muted"));
|
||||
const headerIcon = String(useThemeColor("--color-icon"));
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
const { environmentId, threadId } = useRouteParams<{
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
}>();
|
||||
@@ -126,7 +408,11 @@ export function ReviewSheet() {
|
||||
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
|
||||
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
|
||||
const selectedTheme = colorScheme === "dark" ? "dark" : "light";
|
||||
const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const topContentInset = headerHeight;
|
||||
|
||||
useEffect(() => {
|
||||
showAuxiliaryPane("inspector");
|
||||
}, [environmentId, showAuxiliaryPane, threadId]);
|
||||
const {
|
||||
error,
|
||||
loadingGitDiffs,
|
||||
@@ -141,6 +427,11 @@ export function ReviewSheet() {
|
||||
threadId,
|
||||
reviewCache,
|
||||
});
|
||||
useReviewDiffPrewarming({
|
||||
threadKey: reviewCache.threadKey,
|
||||
sections: reviewSections,
|
||||
selectedSectionId: selectedSection?.id ?? null,
|
||||
});
|
||||
const { headerDiffSummary, nativeReviewDiffData, parsedDiff, pendingReviewCommentCount } =
|
||||
useReviewDiffData({
|
||||
threadKey: reviewCache.threadKey,
|
||||
@@ -148,6 +439,8 @@ export function ReviewSheet() {
|
||||
draftMessage,
|
||||
});
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
|
||||
const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
|
||||
const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
|
||||
const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
|
||||
const fileVisibility = useReviewFileVisibility({
|
||||
threadKey: reviewCache.threadKey,
|
||||
@@ -179,6 +472,41 @@ export function ReviewSheet() {
|
||||
canHighlight: parsedDiff.kind === "files",
|
||||
});
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(fileId: string | null) => {
|
||||
commentSelection.clearSelection();
|
||||
if (fileId !== null && collapsedFileIds.includes(fileId)) {
|
||||
toggleExpandedFile(fileId);
|
||||
}
|
||||
const navigation =
|
||||
fileId === null
|
||||
? nativeReviewDiffViewRef.current?.scrollToTop(true)
|
||||
: nativeReviewDiffViewRef.current?.scrollToFile(fileId, true);
|
||||
void navigation?.catch((error: unknown) => {
|
||||
console.error("[review] Failed to navigate to diff file", error);
|
||||
});
|
||||
},
|
||||
[collapsedFileIds, commentSelection, toggleExpandedFile],
|
||||
);
|
||||
const handleVisibleFileChange = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => {
|
||||
reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const renderInspector = useCallback(
|
||||
() => (
|
||||
<ReviewFileNavigator
|
||||
ref={reviewFileNavigatorRef}
|
||||
files={nativeReviewDiffData.files}
|
||||
headerInset={headerHeight}
|
||||
sectionId={selectedSection?.id ?? null}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
),
|
||||
[handleSelectFile, headerHeight, nativeReviewDiffData.files, selectedSection?.id],
|
||||
);
|
||||
|
||||
const handleNativeToggleFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
@@ -203,6 +531,7 @@ export function ReviewSheet() {
|
||||
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
|
||||
const hasCachedSelectedDiff = selectedSection?.diff != null;
|
||||
const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
|
||||
const sectionMenu = useMemo(() => buildReviewSectionMenu(reviewSections), [reviewSections]);
|
||||
const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
|
||||
hasEnvironmentPresentation: environment.isReady,
|
||||
isEnvironmentConnected: isEnvironmentReady,
|
||||
@@ -235,10 +564,30 @@ export function ReviewSheet() {
|
||||
|
||||
return <>{children}</>;
|
||||
}, [error, parsedDiffNotice]);
|
||||
const renderHeaderTitle = useCallback(
|
||||
() => (
|
||||
<ReviewHeaderTitle
|
||||
additions={headerDiffSummary.additions}
|
||||
deletions={headerDiffSummary.deletions}
|
||||
foregroundColor={headerForeground}
|
||||
mutedColor={headerMuted}
|
||||
pendingCommentCount={pendingReviewCommentCount}
|
||||
sectionTitle={selectedSection?.title ?? "Review changes"}
|
||||
/>
|
||||
),
|
||||
[
|
||||
headerDiffSummary.additions,
|
||||
headerDiffSummary.deletions,
|
||||
headerForeground,
|
||||
headerMuted,
|
||||
pendingReviewCommentCount,
|
||||
selectedSection?.title,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
@@ -246,123 +595,102 @@ export function ReviewSheet() {
|
||||
headerStyle: {
|
||||
backgroundColor: "transparent",
|
||||
},
|
||||
headerTitle: () => (
|
||||
<View style={{ alignItems: "center" }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
fontWeight: "900",
|
||||
color: headerForeground,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
Files Changed
|
||||
</NativeText>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 6,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.additions && headerDiffSummary.deletions ? (
|
||||
<>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#16a34a",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.additions}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#e11d48",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.deletions}
|
||||
</NativeText>
|
||||
{pendingReviewCommentCount > 0 ? (
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#b45309",
|
||||
}}
|
||||
>
|
||||
{pendingReviewCommentCount} pending
|
||||
</NativeText>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: headerMuted,
|
||||
}}
|
||||
>
|
||||
{selectedSection?.title ?? "Review changes"}
|
||||
</NativeText>
|
||||
{pendingReviewCommentCount > 0 ? (
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "700",
|
||||
color: "#b45309",
|
||||
}}
|
||||
>
|
||||
{pendingReviewCommentCount} pending
|
||||
</NativeText>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
headerTitle: renderHeaderTitle,
|
||||
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
}}
|
||||
/>
|
||||
|
||||
{showSectionToolbar ? (
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
|
||||
{reviewSections.map((section) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={section.id}
|
||||
icon={section.id === selectedSection?.id ? "checkmark" : "circle"}
|
||||
onPress={() => selectSection(section.id)}
|
||||
subtitle={section.subtitle ?? undefined}
|
||||
>
|
||||
<Stack.Toolbar.Label>{section.title}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="arrow.clockwise"
|
||||
disabled={
|
||||
loadingGitDiffs ||
|
||||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
|
||||
{layout.usesSplitView ? (
|
||||
<NativeHeaderToolbar placement="left">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel={panes.primarySidebarVisible ? "Maximize review" : "Show threads"}
|
||||
icon={
|
||||
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
|
||||
}
|
||||
onPress={togglePrimarySidebar}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
) : null}
|
||||
|
||||
{showSectionToolbar || panes.supportsAuxiliaryPane ? (
|
||||
<NativeHeaderToolbar placement="right">
|
||||
{panes.supportsAuxiliaryPane ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel={
|
||||
panes.auxiliaryPaneVisible ? "Hide changed files" : "Show changed files"
|
||||
}
|
||||
onPress={() => void refreshSelectedSection()}
|
||||
subtitle="Reload current diff"
|
||||
>
|
||||
<Stack.Toolbar.Label>Refresh</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
icon="sidebar.right"
|
||||
onPress={toggleAuxiliaryPane}
|
||||
separateBackground
|
||||
/>
|
||||
) : null}
|
||||
{showSectionToolbar ? (
|
||||
<NativeHeaderToolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
|
||||
<NativeHeaderToolbar.Menu inline>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
disabled={sectionMenu.workingTree === null}
|
||||
isOn={selectedSection?.id === sectionMenu.workingTree?.id}
|
||||
onPress={() => {
|
||||
if (sectionMenu.workingTree) {
|
||||
selectSection(sectionMenu.workingTree.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Working tree</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
disabled={sectionMenu.branchChanges === null}
|
||||
isOn={selectedSection?.id === sectionMenu.branchChanges?.id}
|
||||
onPress={() => {
|
||||
if (sectionMenu.branchChanges) {
|
||||
selectSection(sectionMenu.branchChanges.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Branch changes</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
disabled={sectionMenu.latestTurn === null}
|
||||
isOn={selectedSection?.id === sectionMenu.latestTurn?.id}
|
||||
onPress={() => {
|
||||
if (sectionMenu.latestTurn) {
|
||||
selectSection(sectionMenu.latestTurn.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Latest turn</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{sectionMenu.turns.length > 0 ? (
|
||||
<NativeHeaderToolbar.Menu title="Turn">
|
||||
{sectionMenu.turns.map((section) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={section.id}
|
||||
isOn={section.id === selectedSection?.id}
|
||||
onPress={() => selectSection(section.id)}
|
||||
subtitle={section.subtitle ?? undefined}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{section.title}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="arrow.clockwise"
|
||||
disabled={
|
||||
loadingGitDiffs ||
|
||||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
|
||||
}
|
||||
onPress={() => void refreshSelectedSection()}
|
||||
subtitle="Reload current diff"
|
||||
>
|
||||
<NativeHeaderToolbar.Label>Refresh</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
</NativeHeaderToolbar>
|
||||
) : null}
|
||||
|
||||
<View className="flex-1 bg-sheet">
|
||||
@@ -386,35 +714,43 @@ export function ReviewSheet() {
|
||||
className="flex-1"
|
||||
style={{
|
||||
backgroundColor: nativeBridge.theme.background,
|
||||
paddingTop: topContentInset + REVIEW_HEADER_SPACING,
|
||||
}}
|
||||
>
|
||||
{listHeader}
|
||||
<View className="flex-1" collapsable={false}>
|
||||
<NativeReviewDiffView
|
||||
key={`${reviewCache.threadKey}:${selectedSection.id}`}
|
||||
collapsable={false}
|
||||
testID="review-native-diff-view"
|
||||
style={StyleSheet.absoluteFill}
|
||||
appearanceScheme={selectedTheme}
|
||||
collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
|
||||
collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
|
||||
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
||||
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
||||
rowsJson={nativeBridge.rowsJson}
|
||||
selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
|
||||
styleJson={nativeBridge.styleJson}
|
||||
themeJson={nativeBridge.themeJson}
|
||||
tokensPatchJson={nativeBridge.tokensPatchJson}
|
||||
tokensResetKey={nativeBridge.tokensResetKey}
|
||||
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
|
||||
onDebug={nativeBridge.onDebug}
|
||||
onPressLine={commentSelection.onPressLine}
|
||||
onToggleComment={nativeBridge.onToggleComment}
|
||||
onToggleFile={handleNativeToggleFile}
|
||||
onToggleViewedFile={handleNativeToggleViewedFile}
|
||||
/>
|
||||
</View>
|
||||
<AdaptiveInspectorLayout renderInspector={renderInspector}>
|
||||
<View
|
||||
className="min-w-0 flex-1"
|
||||
style={{ paddingTop: topContentInset + REVIEW_HEADER_SPACING }}
|
||||
>
|
||||
{listHeader}
|
||||
<View className="min-w-0 flex-1" collapsable={false}>
|
||||
<NativeReviewDiffView
|
||||
collapsable={false}
|
||||
testID="review-native-diff-view"
|
||||
style={StyleSheet.absoluteFill}
|
||||
appearanceScheme={selectedTheme}
|
||||
collapsedFileIdsJson={nativeBridge.collapsedFileIdsJson}
|
||||
collapsedCommentIdsJson={nativeBridge.collapsedCommentIdsJson}
|
||||
contentResetKey={`${reviewCache.threadKey}:${selectedSection.id}`}
|
||||
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
||||
nativeViewRef={nativeReviewDiffViewRef}
|
||||
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
||||
rowsJson={nativeBridge.rowsJson}
|
||||
selectedRowIdsJson={nativeBridge.selectedRowIdsJson}
|
||||
styleJson={nativeBridge.styleJson}
|
||||
themeJson={nativeBridge.themeJson}
|
||||
tokensPatchJson={nativeBridge.tokensPatchJson}
|
||||
tokensResetKey={nativeBridge.tokensResetKey}
|
||||
viewedFileIdsJson={nativeBridge.viewedFileIdsJson}
|
||||
onDebug={nativeBridge.onDebug}
|
||||
onPressLine={commentSelection.onPressLine}
|
||||
onVisibleFileChange={handleVisibleFileChange}
|
||||
onToggleComment={nativeBridge.onToggleComment}
|
||||
onToggleFile={handleNativeToggleFile}
|
||||
onToggleViewedFile={handleNativeToggleViewedFile}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</AdaptiveInspectorLayout>
|
||||
</View>
|
||||
) : (
|
||||
<ScrollView
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
getCachedNativeReviewDiffData,
|
||||
type BuildNativeReviewDiffDataInput,
|
||||
} from "./nativeReviewDiffAdapter";
|
||||
import type { ReviewInlineComment } from "./reviewCommentSelection";
|
||||
import { buildReviewParsedDiff } from "./reviewModel";
|
||||
|
||||
const parsedDiff = buildReviewParsedDiff(
|
||||
[
|
||||
"diff --git a/example.ts b/example.ts",
|
||||
"--- a/example.ts",
|
||||
"+++ b/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-const before = 1;",
|
||||
"+const after = 2;",
|
||||
].join("\n"),
|
||||
"native-review-cache-test",
|
||||
);
|
||||
|
||||
function makeComment(text: string): ReviewInlineComment {
|
||||
return {
|
||||
id: "comment-1",
|
||||
sectionId: "git:working-tree",
|
||||
sectionTitle: "Dirty worktree",
|
||||
filePath: "example.ts",
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
rangeLabel: "-1",
|
||||
text,
|
||||
diff: "@@ -1,1 +1,0 @@\n-const before = 1;",
|
||||
};
|
||||
}
|
||||
|
||||
function buildInput(comments: BuildNativeReviewDiffDataInput["comments"]) {
|
||||
return { parsedDiff, comments } satisfies BuildNativeReviewDiffDataInput;
|
||||
}
|
||||
|
||||
describe("getCachedNativeReviewDiffData", () => {
|
||||
it("reuses the row model for equivalent empty comment arrays", () => {
|
||||
const first = getCachedNativeReviewDiffData(buildInput([]));
|
||||
const second = getCachedNativeReviewDiffData(buildInput([]));
|
||||
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
it("reuses equivalent comment contents and invalidates changed comments", () => {
|
||||
const first = getCachedNativeReviewDiffData(buildInput([makeComment("First")]));
|
||||
const equivalent = getCachedNativeReviewDiffData(buildInput([makeComment("First")]));
|
||||
const changed = getCachedNativeReviewDiffData(buildInput([makeComment("Changed")]));
|
||||
|
||||
expect(equivalent).toBe(first);
|
||||
expect(changed).not.toBe(first);
|
||||
});
|
||||
});
|
||||
@@ -75,6 +75,33 @@ export interface BuildNativeReviewDiffDataInput {
|
||||
readonly comments?: ReadonlyArray<ReviewInlineComment>;
|
||||
}
|
||||
|
||||
interface CachedNativeReviewDiffData {
|
||||
readonly commentsKey: string;
|
||||
readonly data: NativeReviewDiffData;
|
||||
}
|
||||
|
||||
const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
|
||||
|
||||
function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
|
||||
if (comments.length === 0) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
return comments
|
||||
.map((comment) =>
|
||||
[
|
||||
comment.id,
|
||||
comment.sectionId,
|
||||
comment.filePath,
|
||||
comment.startIndex,
|
||||
comment.endIndex,
|
||||
comment.rangeLabel,
|
||||
comment.text,
|
||||
].join("\u001f"),
|
||||
)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
export function createNativeReviewDiffTheme(
|
||||
scheme: TerminalAppearanceScheme,
|
||||
): NativeReviewDiffTheme {
|
||||
@@ -430,3 +457,26 @@ export function buildNativeReviewDiffData(
|
||||
deletions: parsedDiff.deletions,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reuses the expensive flattened native row model across React development
|
||||
* render probes and unrelated draft updates. Only the latest comment version
|
||||
* is retained for each parsed diff so editing a comment cannot grow the cache.
|
||||
*/
|
||||
export function getCachedNativeReviewDiffData(
|
||||
input: BuildNativeReviewDiffDataInput,
|
||||
): NativeReviewDiffData {
|
||||
const comments = input.comments ?? [];
|
||||
const commentsKey = buildReviewCommentsCacheKey(comments);
|
||||
const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
|
||||
if (cached?.commentsKey === commentsKey) {
|
||||
return cached.data;
|
||||
}
|
||||
|
||||
const data = buildNativeReviewDiffData({
|
||||
parsedDiff: input.parsedDiff,
|
||||
comments,
|
||||
});
|
||||
nativeReviewDiffDataCache.set(input.parsedDiff, { commentsKey, data });
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { ReviewSectionItem, ReviewSectionKind } from "./reviewModel";
|
||||
import { buildReviewSectionMenu } from "./review-section-menu";
|
||||
|
||||
function section(id: string, kind: ReviewSectionKind): ReviewSectionItem {
|
||||
return {
|
||||
id,
|
||||
kind,
|
||||
title: id,
|
||||
subtitle: null,
|
||||
diff: null,
|
||||
isLoading: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildReviewSectionMenu", () => {
|
||||
it("exposes git scopes and the latest turn at the top level", () => {
|
||||
const turn28 = section("turn:28", "turn");
|
||||
const turn27 = section("turn:27", "turn");
|
||||
const workingTree = section("git:working-tree", "working-tree");
|
||||
const branchChanges = section("git:branch-range", "branch-range");
|
||||
|
||||
expect(buildReviewSectionMenu([turn28, turn27, workingTree, branchChanges])).toEqual({
|
||||
workingTree,
|
||||
branchChanges,
|
||||
latestTurn: turn28,
|
||||
turns: [turn28, turn27],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unavailable scopes empty while data loads", () => {
|
||||
expect(buildReviewSectionMenu([])).toEqual({
|
||||
workingTree: null,
|
||||
branchChanges: null,
|
||||
latestTurn: null,
|
||||
turns: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ReviewSectionItem } from "./reviewModel";
|
||||
|
||||
export interface ReviewSectionMenu {
|
||||
readonly workingTree: ReviewSectionItem | null;
|
||||
readonly branchChanges: ReviewSectionItem | null;
|
||||
readonly latestTurn: ReviewSectionItem | null;
|
||||
readonly turns: ReadonlyArray<ReviewSectionItem>;
|
||||
}
|
||||
|
||||
export function buildReviewSectionMenu(
|
||||
sections: ReadonlyArray<ReviewSectionItem>,
|
||||
): ReviewSectionMenu {
|
||||
const turns = sections.filter((section) => section.kind === "turn");
|
||||
|
||||
return {
|
||||
workingTree: sections.find((section) => section.kind === "working-tree") ?? null,
|
||||
branchChanges: sections.find((section) => section.kind === "branch-range") ?? null,
|
||||
latestTurn: turns[0] ?? null,
|
||||
turns,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
|
||||
|
||||
describe("resolveSelectedReviewFileId", () => {
|
||||
it("keeps a visible file selected within the active section", () => {
|
||||
expect(
|
||||
resolveSelectedReviewFileId({
|
||||
selection: { sectionId: "worktree", fileId: "second" },
|
||||
sectionId: "worktree",
|
||||
availableFileIds: ["first", "second"],
|
||||
}),
|
||||
).toBe("second");
|
||||
});
|
||||
|
||||
it("clears selection when the review section changes", () => {
|
||||
expect(
|
||||
resolveSelectedReviewFileId({
|
||||
selection: { sectionId: "turn-1", fileId: "first" },
|
||||
sectionId: "turn-2",
|
||||
availableFileIds: ["first"],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("clears a file that no longer exists in the diff", () => {
|
||||
expect(
|
||||
resolveSelectedReviewFileId({
|
||||
selection: { sectionId: "worktree", fileId: "removed" },
|
||||
sectionId: "worktree",
|
||||
availableFileIds: ["first", "second"],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface ReviewPaneFileSelection {
|
||||
readonly sectionId: string | null;
|
||||
readonly fileId: string | null;
|
||||
}
|
||||
|
||||
export function resolveSelectedReviewFileId(input: {
|
||||
readonly selection: ReviewPaneFileSelection;
|
||||
readonly sectionId: string | null;
|
||||
readonly availableFileIds: ReadonlyArray<string>;
|
||||
}): string | null {
|
||||
if (input.selection.sectionId !== input.sectionId || input.selection.fileId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return input.availableFileIds.includes(input.selection.fileId) ? input.selection.fileId : null;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { NativeSyntheticEvent } from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useAppNavigation } from "../../navigation/native-stack-header";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Result from "effect/Result";
|
||||
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { buildThreadReviewCommentNavigation } from "../../lib/routes";
|
||||
|
||||
import {
|
||||
buildReviewCommentTarget,
|
||||
@@ -34,7 +35,7 @@ export function useReviewCommentSelectionController(input: {
|
||||
readonly nativeReviewDiffData: NativeReviewDiffData;
|
||||
}) {
|
||||
const { environmentId, nativeReviewDiffData, selectedSection, threadId } = input;
|
||||
const { push } = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const activeCommentTarget = useReviewCommentTarget();
|
||||
const [pendingNativeCommentSelection, setPendingNativeCommentSelection] =
|
||||
useState<PendingNativeCommentSelection | null>(null);
|
||||
@@ -44,11 +45,8 @@ export function useReviewCommentSelectionController(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
push({
|
||||
pathname: "/threads/[environmentId]/[threadId]/review-comment",
|
||||
params: { environmentId, threadId },
|
||||
});
|
||||
}, [environmentId, push, threadId]);
|
||||
navigation.push(buildThreadReviewCommentNavigation({ environmentId, threadId }));
|
||||
}, [environmentId, navigation, threadId]);
|
||||
|
||||
const selectedRowIds = useMemo(() => {
|
||||
if (
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection";
|
||||
import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter";
|
||||
import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter";
|
||||
import { markReviewEvent, measureReviewWork } from "./reviewPerf";
|
||||
import { getCachedReviewParsedDiff } from "./reviewState";
|
||||
import type { ReviewParsedDiff, ReviewSectionItem } from "./reviewModel";
|
||||
|
||||
const EMPTY_INLINE_REVIEW_COMMENTS = Object.freeze([]);
|
||||
|
||||
function isReviewDiffDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
@@ -43,6 +45,7 @@ export function useReviewDiffData(input: {
|
||||
readonly draftMessage: string;
|
||||
}) {
|
||||
const { draftMessage, selectedSection, threadKey } = input;
|
||||
const selectedSectionId = selectedSection?.id ?? null;
|
||||
const parsedDiff = useMemo(
|
||||
() =>
|
||||
measureReviewWork("parse-diff", () =>
|
||||
@@ -59,17 +62,16 @@ export function useReviewDiffData(input: {
|
||||
() => parseReviewInlineComments(draftMessage),
|
||||
[draftMessage],
|
||||
);
|
||||
const selectedSectionInlineComments = useMemo(
|
||||
() =>
|
||||
selectedSection
|
||||
? inlineReviewComments.filter((comment) => comment.sectionId === selectedSection.id)
|
||||
: [],
|
||||
[inlineReviewComments, selectedSection],
|
||||
);
|
||||
const selectedSectionInlineComments = useMemo(() => {
|
||||
if (!selectedSectionId || inlineReviewComments.length === 0) {
|
||||
return EMPTY_INLINE_REVIEW_COMMENTS;
|
||||
}
|
||||
return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId);
|
||||
}, [inlineReviewComments, selectedSectionId]);
|
||||
const nativeReviewDiffData = useMemo(
|
||||
() =>
|
||||
measureReviewWork("build-native-diff-data", () =>
|
||||
buildNativeReviewDiffData({
|
||||
getCachedNativeReviewDiffData({
|
||||
parsedDiff,
|
||||
comments: selectedSectionInlineComments,
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter";
|
||||
import type { ReviewSectionItem } from "./reviewModel";
|
||||
import { getCachedReviewParsedDiff } from "./reviewState";
|
||||
|
||||
interface IdleDeadlineLike {
|
||||
readonly didTimeout: boolean;
|
||||
timeRemaining(): number;
|
||||
}
|
||||
|
||||
type IdleCallback = (deadline: IdleDeadlineLike) => void;
|
||||
|
||||
function scheduleIdle(callback: IdleCallback): number {
|
||||
if (typeof globalThis.requestIdleCallback === "function") {
|
||||
return globalThis.requestIdleCallback(callback, { timeout: 2_000 });
|
||||
}
|
||||
|
||||
return setTimeout(
|
||||
() => callback({ didTimeout: true, timeRemaining: () => 0 }),
|
||||
100,
|
||||
) as unknown as number;
|
||||
}
|
||||
|
||||
function cancelIdle(handle: number): void {
|
||||
if (typeof globalThis.cancelIdleCallback === "function") {
|
||||
globalThis.cancelIdleCallback(handle);
|
||||
return;
|
||||
}
|
||||
clearTimeout(handle);
|
||||
}
|
||||
|
||||
export function prewarmReviewDiffSection(input: {
|
||||
readonly threadKey: string;
|
||||
readonly section: ReviewSectionItem;
|
||||
}): void {
|
||||
const { section, threadKey } = input;
|
||||
if (section.diff === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedDiff = getCachedReviewParsedDiff({
|
||||
threadKey,
|
||||
sectionId: section.id,
|
||||
diff: section.diff,
|
||||
});
|
||||
getCachedNativeReviewDiffData({ parsedDiff, comments: [] });
|
||||
}
|
||||
|
||||
/** Warms one cached section per idle period, after navigation animations finish. */
|
||||
export function useReviewDiffPrewarming(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly sections: ReadonlyArray<ReviewSectionItem>;
|
||||
readonly selectedSectionId: string | null;
|
||||
}): void {
|
||||
const { sections, selectedSectionId, threadKey } = input;
|
||||
|
||||
useEffect(() => {
|
||||
if (!threadKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pendingSections = sections.filter(
|
||||
(section) => section.id !== selectedSectionId && section.diff !== null,
|
||||
);
|
||||
if (pendingSections.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let idleHandle: number | null = null;
|
||||
let nextSectionIndex = 0;
|
||||
|
||||
const scheduleNext = () => {
|
||||
idleHandle = scheduleIdle(() => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const section = pendingSections[nextSectionIndex];
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
nextSectionIndex += 1;
|
||||
prewarmReviewDiffSection({ threadKey, section });
|
||||
|
||||
if (nextSectionIndex < pendingSections.length) {
|
||||
scheduleNext();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
scheduleNext();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (idleHandle !== null) {
|
||||
cancelIdle(idleHandle);
|
||||
}
|
||||
};
|
||||
}, [sections, selectedSectionId, threadKey]);
|
||||
}
|
||||
@@ -179,7 +179,6 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
|
||||
|
||||
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
|
||||
const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
|
||||
const keyboardInputRef = useRef<TextInput>(null);
|
||||
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
|
||||
const { onInput, onResize } = props;
|
||||
@@ -196,9 +195,12 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
|
||||
}, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]);
|
||||
const handleNativeInput = useCallback(
|
||||
(event: NativeSyntheticEvent<TerminalInputEvent>) => {
|
||||
if (!props.isRunning) {
|
||||
return;
|
||||
}
|
||||
onInput(event.nativeEvent.data);
|
||||
},
|
||||
[onInput],
|
||||
[onInput, props.isRunning],
|
||||
);
|
||||
const handleNativeResize = useCallback(
|
||||
(event: NativeSyntheticEvent<TerminalResizeEvent>) => {
|
||||
@@ -210,33 +212,13 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
|
||||
[onResize],
|
||||
);
|
||||
|
||||
// Reopen focus through React and forward input normally; this avoids a native focus-command bridge.
|
||||
useEffect(() => {
|
||||
if (!NativeTerminalSurfaceView || (props.keyboardFocusRequest ?? 0) <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
keyboardInputRef.current?.blur();
|
||||
const focusFrame = requestAnimationFrame(() => keyboardInputRef.current?.focus());
|
||||
return () => cancelAnimationFrame(focusFrame);
|
||||
}, [NativeTerminalSurfaceView, props.keyboardFocusRequest]);
|
||||
|
||||
const handleKeyboardInput = useCallback(
|
||||
(data: string) => {
|
||||
if (data.length > 0) {
|
||||
onInput(data);
|
||||
keyboardInputRef.current?.clear();
|
||||
}
|
||||
},
|
||||
[onInput],
|
||||
);
|
||||
|
||||
if (NativeTerminalSurfaceView) {
|
||||
return (
|
||||
<View style={props.style}>
|
||||
<NativeTerminalSurfaceView
|
||||
appearanceScheme={appearanceScheme}
|
||||
backgroundColor={theme.background}
|
||||
focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
|
||||
foregroundColor={theme.foreground}
|
||||
mutedForegroundColor={theme.mutedForeground}
|
||||
terminalKey={props.terminalKey}
|
||||
@@ -247,23 +229,6 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
|
||||
onInput={handleNativeInput}
|
||||
onResize={handleNativeResize}
|
||||
/>
|
||||
<TextInput
|
||||
ref={keyboardInputRef}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
blurOnSubmit={false}
|
||||
caretHidden
|
||||
editable={props.isRunning}
|
||||
keyboardType="ascii-capable"
|
||||
style={{ bottom: 0, height: 1, left: 0, opacity: 0.01, position: "absolute", width: 1 }}
|
||||
onChangeText={handleKeyboardInput}
|
||||
onKeyPress={(event) => {
|
||||
if (event.nativeEvent.key === "Backspace") {
|
||||
onInput("\u007f");
|
||||
}
|
||||
}}
|
||||
onSubmitEditing={() => onInput("\n")}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import {
|
||||
NativeHeaderToolbar,
|
||||
NativeStackScreenOptions,
|
||||
useRouteParams,
|
||||
useAppNavigation,
|
||||
} from "../../navigation/native-stack-header";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { Platform, Pressable, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardEvents,
|
||||
@@ -25,6 +30,7 @@ import { terminalEnvironment } from "../../state/terminal";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { buildThreadTerminalNavigation } from "../../lib/routes";
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import {
|
||||
useAttachedTerminalSession,
|
||||
@@ -33,6 +39,7 @@ import {
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
import { getPierreTerminalTheme } from "./terminalTheme";
|
||||
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
|
||||
@@ -72,6 +79,7 @@ import {
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
const TERMINAL_ACCESSORY_HEIGHT = 52;
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
type PendingModifier = "ctrl" | "meta";
|
||||
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
|
||||
@@ -86,6 +94,47 @@ type TerminalToolbarAction =
|
||||
readonly modifier: PendingModifier;
|
||||
};
|
||||
|
||||
function TerminalHeaderTitle(props: {
|
||||
readonly topLine: string;
|
||||
readonly bottomLine: string;
|
||||
readonly foreground: string;
|
||||
readonly mutedForeground: string;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
maxWidth: 240,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: props.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.footnote.fontSize,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
{props.topLine}
|
||||
</RNText>
|
||||
<RNText
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: props.mutedForeground,
|
||||
fontFamily: "Menlo",
|
||||
fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
|
||||
lineHeight: 14,
|
||||
}}
|
||||
>
|
||||
{props.bottomLine}
|
||||
</RNText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] ?? null;
|
||||
@@ -154,14 +203,15 @@ function pickRunningTerminalSessionForBootstrap(
|
||||
}
|
||||
|
||||
export function ThreadTerminalRouteScreen() {
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
|
||||
const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
|
||||
const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
|
||||
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
|
||||
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const { state: workspaceState } = useWorkspaceState();
|
||||
const params = useLocalSearchParams<{
|
||||
const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
|
||||
const params = useRouteParams<{
|
||||
environmentId?: string | string[];
|
||||
threadId?: string | string[];
|
||||
terminalId?: string | string[];
|
||||
@@ -404,6 +454,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
);
|
||||
|
||||
const terminalTheme = getPierreTerminalTheme(appearanceScheme);
|
||||
const usesNativeHeaderGlass = Platform.OS === "ios";
|
||||
const pendingModifier =
|
||||
pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
|
||||
const headerTitle = useMemo(() => {
|
||||
@@ -422,6 +473,22 @@ export function ThreadTerminalRouteScreen() {
|
||||
selectedThreadProject?.title,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const renderTerminalHeaderTitle = useCallback(
|
||||
() => (
|
||||
<TerminalHeaderTitle
|
||||
topLine={headerTitle.topLine}
|
||||
bottomLine={headerTitle.bottomLine}
|
||||
foreground={terminalTheme.foreground}
|
||||
mutedForeground={terminalTheme.mutedForeground}
|
||||
/>
|
||||
),
|
||||
[
|
||||
headerTitle.bottomLine,
|
||||
headerTitle.topLine,
|
||||
terminalTheme.foreground,
|
||||
terminalTheme.mutedForeground,
|
||||
],
|
||||
);
|
||||
const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
|
||||
const modifierActions: ReadonlyArray<TerminalToolbarAction> =
|
||||
hostPlatform === "mac"
|
||||
@@ -546,8 +613,10 @@ export function ThreadTerminalRouteScreen() {
|
||||
if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
|
||||
return;
|
||||
}
|
||||
router.replace(buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId));
|
||||
}, [router, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
|
||||
navigation.replace(
|
||||
buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId),
|
||||
);
|
||||
}, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
|
||||
|
||||
useEffect(() => {
|
||||
const initialInput = pendingLaunch?.initialInput;
|
||||
@@ -772,9 +841,9 @@ export function ThreadTerminalRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
|
||||
navigation.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
|
||||
},
|
||||
[router, selectedThread, terminalId],
|
||||
[navigation, selectedThread, terminalId],
|
||||
);
|
||||
|
||||
const handleOpenNewTerminal = useCallback(() => {
|
||||
@@ -782,7 +851,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(
|
||||
navigation.replace(
|
||||
buildThreadTerminalNavigation(
|
||||
selectedThread,
|
||||
nextOpenTerminalId({
|
||||
@@ -791,7 +860,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
}),
|
||||
),
|
||||
);
|
||||
}, [router, selectedThread, terminalId, terminalMenuSessions]);
|
||||
}, [navigation, selectedThread, terminalId, terminalMenuSessions]);
|
||||
|
||||
const adjustFontSize = useCallback((delta: number) => {
|
||||
setTimeout(() => {
|
||||
@@ -898,80 +967,72 @@ export function ThreadTerminalRouteScreen() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerTransparent: usesNativeHeaderGlass,
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: terminalTheme.background },
|
||||
headerStyle: {
|
||||
backgroundColor: usesNativeHeaderGlass ? "transparent" : terminalTheme.background,
|
||||
},
|
||||
headerTintColor: terminalTheme.foreground,
|
||||
headerTitleAlign: "center",
|
||||
title: "",
|
||||
headerTitle: () => (
|
||||
<View
|
||||
style={{
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
maxWidth: 240,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: terminalTheme.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.footnote.fontSize,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
{headerTitle.topLine}
|
||||
</RNText>
|
||||
<RNText
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: terminalTheme.mutedForeground,
|
||||
fontFamily: "Menlo",
|
||||
fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
|
||||
lineHeight: 14,
|
||||
}}
|
||||
>
|
||||
{headerTitle.bottomLine}
|
||||
</RNText>
|
||||
</View>
|
||||
),
|
||||
headerTitle: usesNativeHeaderGlass ? headerTitle.topLine : renderTerminalHeaderTitle,
|
||||
headerTitleStyle: usesNativeHeaderGlass
|
||||
? {
|
||||
fontSize: 17,
|
||||
fontWeight: "800",
|
||||
}
|
||||
: undefined,
|
||||
scrollEdgeEffects: usesNativeHeaderGlass ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
title: headerTitle.topLine,
|
||||
unstable_navigationItemStyle: usesNativeHeaderGlass ? "editor" : undefined,
|
||||
}}
|
||||
/>
|
||||
|
||||
{layout.usesSplitView ? (
|
||||
<NativeHeaderToolbar placement="left">
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel={panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"}
|
||||
icon={
|
||||
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
|
||||
}
|
||||
onPress={togglePrimarySidebar}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
) : null}
|
||||
|
||||
{isEnvironmentReady ? (
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
|
||||
<Stack.Toolbar.Label>
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Menu icon="terminal" title="Terminal options" separateBackground>
|
||||
<NativeHeaderToolbar.Label>
|
||||
{getTerminalStatusLabel({
|
||||
status: terminal.status,
|
||||
hasRunningSubprocess: terminal.hasRunningSubprocess,
|
||||
})}
|
||||
</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
|
||||
<Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.Menu icon="textformat.size" inline title="Text size">
|
||||
<NativeHeaderToolbar.Label>Text size</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
|
||||
discoverabilityLabel="Decrease terminal text size"
|
||||
onPress={handleDecreaseFontSize}
|
||||
>
|
||||
<Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
<NativeHeaderToolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
|
||||
discoverabilityLabel="Increase terminal text size"
|
||||
onPress={handleIncreaseFontSize}
|
||||
>
|
||||
<Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
<NativeHeaderToolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
{terminalMenuSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={session.terminalId}
|
||||
icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
|
||||
onPress={() => handleSelectTerminal(session.terminalId)}
|
||||
@@ -982,18 +1043,18 @@ export function ThreadTerminalRouteScreen() {
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={handleOpenNewTerminal}
|
||||
subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
<NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar>
|
||||
) : null}
|
||||
|
||||
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
|
||||
|
||||
@@ -23,6 +23,7 @@ interface TerminalResizeEvent {
|
||||
|
||||
export interface NativeTerminalSurfaceProps extends ViewProps {
|
||||
readonly appearanceScheme?: "light" | "dark";
|
||||
readonly focusRequest?: number;
|
||||
readonly themeConfig?: string;
|
||||
readonly backgroundColor?: string;
|
||||
readonly foregroundColor?: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { NativeStackScreenOptions, useAppNavigation } from "../../navigation/native-stack-header";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { Alert, InteractionManager, View, useColorScheme } from "react-native";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
@@ -29,8 +29,10 @@ import {
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { newTaskNavigation, threadNavigation } from "../../lib/routes";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
@@ -56,13 +58,14 @@ export function NewTaskDraftScreen(props: {
|
||||
const projects = useProjects();
|
||||
const createProjectThread = useCreateProjectThread();
|
||||
const flow = useNewTaskFlow();
|
||||
const router = useRouter();
|
||||
const navigation = useAppNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
@@ -92,23 +101,29 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace("/new");
|
||||
navigation.replace(newTaskNavigation());
|
||||
}, [
|
||||
logicalProjects,
|
||||
projects,
|
||||
props.initialProjectRef?.environmentId,
|
||||
props.initialProjectRef?.projectId,
|
||||
router,
|
||||
navigation,
|
||||
selectedProject,
|
||||
setProject,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
loadedBranchesProjectKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
|
||||
if (loadedBranchesProjectKeyRef.current === projectKey) {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
}, [flow, selectedProject]);
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
// Defer state update so the native menu dismiss animation completes
|
||||
// before re-rendering the menu actions (prevents submenu jump).
|
||||
setTimeout(() => {
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}, 150);
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
flow.submitting ||
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
(workspaceMode === "worktree" && !selectedBranchName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
const result = await createProjectThread({
|
||||
project: flow.selectedProject,
|
||||
modelSelection: flow.selectedModel,
|
||||
envMode: flow.workspaceMode,
|
||||
branch: flow.selectedBranchName,
|
||||
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
initialMessageText: flow.prompt.trim(),
|
||||
initialAttachments: flow.attachments,
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
@@ -403,20 +429,20 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
flow.setPrompt("");
|
||||
flow.clearAttachments();
|
||||
router.replace(buildThreadRoutePath(result.value));
|
||||
navigation.replace(threadNavigation(result.value));
|
||||
}
|
||||
|
||||
if (!selectedProject) {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen options={{ title: "Loading task" }} />
|
||||
<NativeStackScreenOptions options={{ title: "Loading task" }} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen options={{ title: selectedProject.title }} />
|
||||
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
|
||||
<View style={{ flex: 1, minHeight: 0, paddingHorizontal: 20, paddingTop: 8 }}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
} from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
@@ -75,6 +77,7 @@ export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly placeholder: string;
|
||||
readonly contentMaxWidth?: number;
|
||||
readonly bottomInset?: number;
|
||||
readonly connectionState: RemoteClientConnectionState;
|
||||
readonly connectionError: string | null;
|
||||
@@ -91,7 +94,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -207,6 +210,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const inputRef = props.editorRef ?? fallbackInputRef;
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
const wasExpandedBeforePreviewRef = useRef(false);
|
||||
const inFlightThreadIdsRef = useRef(new Set<string>());
|
||||
const { onExpandedChange } = props;
|
||||
|
||||
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
|
||||
@@ -446,11 +450,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
// ── Handle command selection ──────────────────────────────
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
}, [onSendMessage]);
|
||||
const handleSend = useCallback(async () => {
|
||||
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
if (inFlightThreadIdsRef.current.has(threadKey)) return;
|
||||
inFlightThreadIdsRef.current.add(threadKey);
|
||||
try {
|
||||
await onSendMessage();
|
||||
} finally {
|
||||
inFlightThreadIdsRef.current.delete(threadKey);
|
||||
}
|
||||
}, [onSendMessage, props.environmentId, props.selectedThread.id]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
if (!composerTrigger) return;
|
||||
@@ -630,7 +639,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
|
||||
}}
|
||||
>
|
||||
<View className="w-full" style={{ position: "relative" }}>
|
||||
<View
|
||||
className="w-full"
|
||||
style={{ alignSelf: "center", maxWidth: props.contentMaxWidth, position: "relative" }}
|
||||
>
|
||||
{composerTrigger && composerMenuItems.length > 0 ? (
|
||||
<View
|
||||
style={{
|
||||
@@ -703,6 +715,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
placeholder={props.placeholder}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onSubmit={handleSend}
|
||||
scrollEnabled={isExpanded}
|
||||
contentInsetVertical={isExpanded ? 0 : 6}
|
||||
style={
|
||||
|
||||
Loaded 100 of 317 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user