Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c19a48626f | ||
|
|
b69c78cab0 | ||
|
|
86ab75e819 | ||
|
|
32e7844837 | ||
|
|
482d56233d | ||
|
|
6009720844 | ||
|
|
e26e55f389 | ||
|
|
4ac094fef6 | ||
|
|
a7e43b2281 | ||
|
|
cabc93bad3 | ||
|
|
5cda815626 | ||
|
|
32d17d3db5 | ||
|
|
6d35a87c5d |
No files matched your search
@@ -0,0 +1,110 @@
|
||||
name: Mobile EAS Production
|
||||
|
||||
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
|
||||
# Under the fingerprint runtime-version policy the fingerprint must be computed
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "build (+ auto-submit to TestFlight) or update (OTA)"
|
||||
required: true
|
||||
type: choice
|
||||
default: build
|
||||
options:
|
||||
- build
|
||||
- update
|
||||
platform:
|
||||
description: "Target platform"
|
||||
required: true
|
||||
type: choice
|
||||
default: ios
|
||||
options:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
packager: pnpm
|
||||
|
||||
- name: Pull production environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
vp staged
|
||||
@@ -358,10 +358,7 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
ensureElectronRuntime();
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
|
||||
if (hostPlatform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
@@ -378,13 +375,23 @@ export function resolveElectronLaunchCommand(args = []) {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveElectronBinaryPath({
|
||||
ensureRuntime = ensureElectronRuntime,
|
||||
createRequire = NodeModule.createRequire,
|
||||
moduleUrl = import.meta.url,
|
||||
} = {}) {
|
||||
ensureRuntime();
|
||||
|
||||
const require = createRequire(moduleUrl);
|
||||
return require("electron");
|
||||
}
|
||||
|
||||
export function resolveDevProtocolClient() {
|
||||
if (hostPlatform !== "darwin" || !isDevelopment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
const electronBinaryPath = resolveElectronBinaryPath();
|
||||
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
|
||||
return {
|
||||
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, describe, it } from "vite-plus/test";
|
||||
|
||||
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
|
||||
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
|
||||
|
||||
describe("electron development launcher", () => {
|
||||
it("uses captured values only as fallbacks for a live runner environment", () => {
|
||||
@@ -25,4 +25,24 @@ describe("electron development launcher", () => {
|
||||
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
|
||||
);
|
||||
});
|
||||
|
||||
it("repairs Electron before loading the package entrypoint", () => {
|
||||
const calls = [];
|
||||
const electronPath = resolveElectronBinaryPath({
|
||||
ensureRuntime: () => {
|
||||
calls.push("ensure");
|
||||
},
|
||||
createRequire: () => (specifier) => {
|
||||
calls.push(`require:${specifier}`);
|
||||
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
|
||||
},
|
||||
moduleUrl: import.meta.url,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
electronPath,
|
||||
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
|
||||
);
|
||||
assert.deepEqual(calls, ["ensure", "require:electron"]);
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -62,7 +66,11 @@ const config: ExpoConfig = {
|
||||
scheme: variant.scheme,
|
||||
version: "0.1.0",
|
||||
runtimeVersion: {
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
|
||||
// could land on a binary missing the native changes it needs and crash.
|
||||
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
|
||||
},
|
||||
orientation: "portrait",
|
||||
icon: "./assets/icon.png",
|
||||
@@ -77,6 +85,14 @@ const config: ExpoConfig = {
|
||||
icon: variant.iosIcon,
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
|
||||
// does not fall back to a personal team (which cannot sign app groups,
|
||||
// Sign in with Apple, or push notification entitlements).
|
||||
appleTeamId: "ARK85ZXQ4Z",
|
||||
associatedDomains: [
|
||||
`applinks:${variant.relyingParty}`,
|
||||
`webcredentials:${variant.relyingParty}`,
|
||||
],
|
||||
infoPlist: {
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
@@ -101,7 +117,6 @@ const config: ExpoConfig = {
|
||||
favicon: "./assets/favicon.png",
|
||||
},
|
||||
plugins: [
|
||||
"expo-router",
|
||||
"expo-font",
|
||||
"expo-secure-store",
|
||||
["@clerk/expo", { theme: "./clerk-theme.json" }],
|
||||
@@ -139,6 +154,7 @@ const config: ExpoConfig = {
|
||||
},
|
||||
},
|
||||
],
|
||||
"./plugins/withIosCocoaPodsUuidCache.cjs",
|
||||
[
|
||||
"expo-widgets",
|
||||
{
|
||||
@@ -155,6 +171,7 @@ const config: ExpoConfig = {
|
||||
],
|
||||
},
|
||||
],
|
||||
"./plugins/withIosSceneLifecycle.cjs",
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
],
|
||||
extra: {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "development"
|
||||
},
|
||||
@@ -14,6 +15,7 @@
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview"
|
||||
},
|
||||
@@ -22,6 +24,7 @@
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview:dev": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "preview",
|
||||
"MOBILE_VERSION_POLICY": "fingerprint"
|
||||
@@ -35,6 +38,7 @@
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"corepack": true,
|
||||
"env": {
|
||||
"APP_VARIANT": "production"
|
||||
},
|
||||
@@ -46,7 +50,10 @@
|
||||
"submit": {
|
||||
"production": {
|
||||
"ios": {
|
||||
"ascAppId": "6761315631"
|
||||
"ascAppId": "6787819824"
|
||||
},
|
||||
"android": {
|
||||
"track": "internal"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
-18
@@ -199,24 +199,24 @@
|
||||
--font-bold: "DMSans_700Bold";
|
||||
|
||||
/* Keep this scale aligned with src/lib/typography.ts for native style props. */
|
||||
--text-3xs: 10px;
|
||||
--text-3xs--line-height: 13px;
|
||||
--text-2xs: 11px;
|
||||
--text-2xs--line-height: 15px;
|
||||
--text-xs: 12px;
|
||||
--text-xs--line-height: 16px;
|
||||
--text-sm: 13px;
|
||||
--text-sm--line-height: 18px;
|
||||
--text-base: 15px;
|
||||
--text-base--line-height: 22px;
|
||||
--text-lg: 17px;
|
||||
--text-lg--line-height: 22px;
|
||||
--text-xl: 20px;
|
||||
--text-xl--line-height: 26px;
|
||||
--text-2xl: 24px;
|
||||
--text-2xl--line-height: 30px;
|
||||
--text-3xl: 28px;
|
||||
--text-3xl--line-height: 34px;
|
||||
--text-3xs: 11px;
|
||||
--text-3xs--line-height: 14px;
|
||||
--text-2xs: 12px;
|
||||
--text-2xs--line-height: 16px;
|
||||
--text-xs: 13px;
|
||||
--text-xs--line-height: 17px;
|
||||
--text-sm: 14px;
|
||||
--text-sm--line-height: 19px;
|
||||
--text-base: 16px;
|
||||
--text-base--line-height: 23px;
|
||||
--text-lg: 18px;
|
||||
--text-lg--line-height: 23px;
|
||||
--text-xl: 21px;
|
||||
--text-xl--line-height: 28px;
|
||||
--text-2xl: 26px;
|
||||
--text-2xl--line-height: 32px;
|
||||
--text-3xl: 30px;
|
||||
--text-3xl--line-height: 36px;
|
||||
}
|
||||
|
||||
/* ─── Custom utilities ──────────────────────────────────────────────── */
|
||||
|
||||
+10
-1
@@ -1,2 +1,11 @@
|
||||
import { registerRootComponent } from "expo";
|
||||
import "react-native-gesture-handler";
|
||||
import "expo-router/entry";
|
||||
import { featureFlags } from "react-native-screens";
|
||||
|
||||
import App from "./src/App";
|
||||
|
||||
// Required for react-native-screens' iOS FormSheet sizing fix when a nested
|
||||
// native stack is rendered inside a non-fitToContents formSheet.
|
||||
featureFlags.experiment.synchronousScreenUpdatesEnabled = true;
|
||||
|
||||
registerRootComponent(App);
|
||||
@@ -47,6 +47,7 @@ public class T3ComposerEditorModule: Module {
|
||||
"onComposerSelectionChange",
|
||||
"onComposerFocus",
|
||||
"onComposerBlur",
|
||||
"onComposerSubmit",
|
||||
"onComposerPasteImages",
|
||||
"onComposerContentSizeChange"
|
||||
)
|
||||
|
||||
@@ -63,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(_:)) {
|
||||
@@ -299,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()
|
||||
|
||||
@@ -320,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
|
||||
|
||||
@@ -26,6 +26,15 @@ function nodeKey(node: MarkdownNode, index: number): string {
|
||||
return `${node.type}:${node.beg ?? index}:${node.end ?? index}`;
|
||||
}
|
||||
|
||||
/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
|
||||
function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
|
||||
return Math.max(10, Math.round(textStyle.fontSize * 0.8));
|
||||
}
|
||||
|
||||
function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
|
||||
return codeBlockFontSize(textStyle) + 6;
|
||||
}
|
||||
|
||||
function nodeText(node: MarkdownNode): string {
|
||||
if (node.content !== undefined) {
|
||||
return node.content;
|
||||
@@ -161,8 +170,8 @@ function HighlightedCodeText(props: {
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
lineHeight: codeBlockLineHeight(props.textStyle),
|
||||
}}
|
||||
>
|
||||
{props.content}
|
||||
@@ -196,8 +205,8 @@ function HighlightedCodeText(props: {
|
||||
style={{
|
||||
color: props.textStyle.codeColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
lineHeight: codeBlockLineHeight(props.textStyle),
|
||||
}}
|
||||
>
|
||||
{keyedLines.map((line, lineIndex) => (
|
||||
@@ -264,7 +273,7 @@ function NativeCodeBlock(props: {
|
||||
flex: 1,
|
||||
color: props.textStyle.mutedColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
fontSize: codeBlockFontSize(props.textStyle),
|
||||
}}
|
||||
>
|
||||
{languageLabel}
|
||||
|
||||
@@ -32,11 +32,25 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
].join(":");
|
||||
}
|
||||
|
||||
const DEFAULT_BODY_FONT_SIZE = 15;
|
||||
const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
|
||||
|
||||
function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
|
||||
const index = Math.max(0, Math.min(5, headingLevel - 1));
|
||||
const configured = textStyle.headingFontSizes?.[index];
|
||||
if (typeof configured === "number" && Number.isFinite(configured)) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
|
||||
return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
|
||||
}
|
||||
|
||||
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
|
||||
const isFile = run.fileIcon != null;
|
||||
const isSkill = run.skillName != null;
|
||||
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
|
||||
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
|
||||
const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
|
||||
const isHeading = run.role === "heading";
|
||||
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
|
||||
const hasParagraphStyle = run.headIndent !== undefined;
|
||||
@@ -88,7 +102,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
: isHeading
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? 11
|
||||
? Math.max(10, Math.round(textStyle.fontSize * 0.73))
|
||||
: run.code || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
@@ -98,9 +112,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
: run.role === "list-break"
|
||||
? textStyle.lineHeight + (run.spacing ?? 0)
|
||||
: isHeading
|
||||
? Math.max(headingFontSize + 6, 20)
|
||||
? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
|
||||
: isCodeBlock
|
||||
? 18
|
||||
? Math.max(16, textStyle.lineHeight - 2)
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
|
||||
@@ -148,6 +162,9 @@ export function NativeMarkdownSelectableText(props: {
|
||||
// color-only child update can otherwise leave the previous appearance cached.
|
||||
const appearanceKey = [
|
||||
colorScheme ?? "unspecified",
|
||||
props.textStyle.fontSize,
|
||||
props.textStyle.lineHeight,
|
||||
props.textStyle.headingFontSizes?.join(","),
|
||||
props.textStyle.color,
|
||||
props.textStyle.strongColor,
|
||||
props.textStyle.mutedColor,
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface NativeMarkdownTextStyle {
|
||||
readonly fontFamily: string;
|
||||
readonly headingFontFamily: string;
|
||||
readonly boldFontFamily: string;
|
||||
readonly headingFontSizes?: ReadonlyArray<number>;
|
||||
}
|
||||
|
||||
export interface MarkdownHighlightedToken {
|
||||
|
||||
@@ -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,42 @@ public class T3ReviewDiffModule: Module {
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
|
||||
Prop("refreshing") { (view: T3ReviewDiffView, refreshing: Bool) in
|
||||
view.setRefreshing(refreshing)
|
||||
}
|
||||
|
||||
Events(
|
||||
"onDebug",
|
||||
"onVisibleFileChange",
|
||||
"onToggleFile",
|
||||
"onToggleViewedFile",
|
||||
"onPressLine",
|
||||
"onToggleComment",
|
||||
"onPullToRefresh"
|
||||
)
|
||||
|
||||
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,14 +327,25 @@ 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()
|
||||
let onToggleComment = EventDispatcher()
|
||||
let onPullToRefresh = EventDispatcher()
|
||||
|
||||
private let pullRefreshControl = UIRefreshControl()
|
||||
|
||||
public required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
@@ -345,6 +360,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
scrollView.showsVerticalScrollIndicator = true
|
||||
scrollView.showsHorizontalScrollIndicator = false
|
||||
scrollView.backgroundColor = contentView.theme.background
|
||||
pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
|
||||
scrollView.refreshControl = pullRefreshControl
|
||||
addSubview(scrollView)
|
||||
|
||||
contentView.backgroundColor = contentView.theme.background
|
||||
@@ -379,6 +396,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 +420,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 +554,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 +666,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 +691,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 +795,33 @@ 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)
|
||||
}
|
||||
|
||||
@objc private func handlePullToRefresh() {
|
||||
onPullToRefresh([:])
|
||||
}
|
||||
|
||||
/// Driven from JS: set to false once the reload completes to dismiss the spinner.
|
||||
func setRefreshing(_ refreshing: Bool) {
|
||||
if refreshing {
|
||||
if !pullRefreshControl.isRefreshing {
|
||||
pullRefreshControl.beginRefreshing()
|
||||
}
|
||||
} else if pullRefreshControl.isRefreshing {
|
||||
pullRefreshControl.endRefreshing()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyStyle() {
|
||||
contentView.style = ReviewDiffNativeStyle
|
||||
.resolve(stylePayload)
|
||||
@@ -686,6 +838,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 +1439,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
|
||||
|
||||
+10
@@ -7,6 +7,12 @@ class T3TerminalModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("T3TerminalSurface")
|
||||
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants(
|
||||
"hardwareKeyRevision" to 2,
|
||||
)
|
||||
|
||||
View(T3TerminalView::class) {
|
||||
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
|
||||
view.terminalKey = terminalKey
|
||||
@@ -20,6 +26,10 @@ class T3TerminalModule : Module() {
|
||||
view.fontSize = fontSize.toFloat()
|
||||
}
|
||||
|
||||
Prop("focusRequest") { view: T3TerminalView, focusRequest: Double ->
|
||||
view.focusRequest = focusRequest
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { view: T3TerminalView, appearanceScheme: String ->
|
||||
view.appearanceScheme = appearanceScheme
|
||||
}
|
||||
|
||||
+19
-2
@@ -62,6 +62,15 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
|
||||
var themeConfig: String = ""
|
||||
|
||||
var focusRequest: Double = 0.0
|
||||
set(value) {
|
||||
val previous = field
|
||||
field = value
|
||||
if (value != previous && value > 0) {
|
||||
requestKeyboardFocus()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColorHex: String = "#24292E"
|
||||
set(value) {
|
||||
field = value
|
||||
@@ -113,11 +122,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
}
|
||||
inputView.setOnKeyListener { _, keyCode, event ->
|
||||
if (event.action != android.view.KeyEvent.ACTION_DOWN) return@setOnKeyListener false
|
||||
when (keyCode) {
|
||||
android.view.KeyEvent.KEYCODE_DEL -> {
|
||||
when {
|
||||
keyCode == android.view.KeyEvent.KEYCODE_DEL -> {
|
||||
onInput(mapOf("data" to "\u007F"))
|
||||
true
|
||||
}
|
||||
// Hardware keyboard Ctrl+A..Z -> control bytes 0x01..0x1A (Ctrl+C, Ctrl+Z, ...).
|
||||
event.isCtrlPressed &&
|
||||
keyCode in android.view.KeyEvent.KEYCODE_A..android.view.KeyEvent.KEYCODE_Z -> {
|
||||
onInput(
|
||||
mapOf("data" to (keyCode - android.view.KeyEvent.KEYCODE_A + 1).toChar().toString()),
|
||||
)
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,12 @@ public class T3TerminalModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3TerminalSurface")
|
||||
|
||||
// Bumped when native hardware-keyboard handling changes; surfaced in the JS debug
|
||||
// logs so a stale native binary is distinguishable from a broken key pipeline.
|
||||
Constants([
|
||||
"hardwareKeyRevision": 2,
|
||||
])
|
||||
|
||||
View(T3TerminalView.self) {
|
||||
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
|
||||
view.terminalKey = terminalKey
|
||||
@@ -17,6 +23,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
|
||||
}
|
||||
|
||||
@@ -22,13 +22,129 @@ private enum GhosttyRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes hardware-keyboard combos that UITextField never surfaces through its
|
||||
/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte
|
||||
/// sequences a terminal expects.
|
||||
///
|
||||
/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than
|
||||
/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key
|
||||
/// events through the text-input system, which can consume presses before they reach
|
||||
/// responder press callbacks. Registered key commands are matched deterministically
|
||||
/// before that happens.
|
||||
private enum TerminalHardwareKeyEncoder {
|
||||
/// Characters that produce a control byte when combined with Ctrl.
|
||||
private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
|
||||
|
||||
static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
|
||||
var commands: [UIKeyCommand] = []
|
||||
|
||||
let specialInputs = [
|
||||
UIKeyCommand.inputEscape,
|
||||
UIKeyCommand.inputUpArrow,
|
||||
UIKeyCommand.inputDownArrow,
|
||||
UIKeyCommand.inputLeftArrow,
|
||||
UIKeyCommand.inputRightArrow,
|
||||
"\t",
|
||||
]
|
||||
for input in specialInputs {
|
||||
commands.append(makeCommand(input: input, modifierFlags: [], action: action))
|
||||
}
|
||||
commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
|
||||
|
||||
for character in controlInputs {
|
||||
commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action))
|
||||
commands.append(
|
||||
makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action)
|
||||
)
|
||||
}
|
||||
|
||||
return commands
|
||||
}
|
||||
|
||||
private static func makeCommand(
|
||||
input: String,
|
||||
modifierFlags: UIKeyModifierFlags,
|
||||
action: Selector
|
||||
) -> UIKeyCommand {
|
||||
let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
|
||||
command.wantsPriorityOverSystemBehavior = true
|
||||
return command
|
||||
}
|
||||
|
||||
static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? {
|
||||
switch input {
|
||||
case UIKeyCommand.inputEscape:
|
||||
return "\u{1B}"
|
||||
case UIKeyCommand.inputUpArrow:
|
||||
return "\u{1B}[A"
|
||||
case UIKeyCommand.inputDownArrow:
|
||||
return "\u{1B}[B"
|
||||
case UIKeyCommand.inputRightArrow:
|
||||
return "\u{1B}[C"
|
||||
case UIKeyCommand.inputLeftArrow:
|
||||
return "\u{1B}[D"
|
||||
case "\t":
|
||||
return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
guard modifiers.contains(.control) else { return nil }
|
||||
guard let scalar = input.lowercased().unicodeScalars.first else { return nil }
|
||||
return controlSequence(for: scalar)
|
||||
}
|
||||
|
||||
private static func controlSequence(for scalar: Unicode.Scalar) -> String? {
|
||||
switch scalar {
|
||||
case "a"..."z":
|
||||
// Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...).
|
||||
return UnicodeScalar(scalar.value - 96).map(String.init)
|
||||
case " ", "@":
|
||||
return "\u{00}"
|
||||
case "[":
|
||||
return "\u{1B}"
|
||||
case "\\":
|
||||
return "\u{1C}"
|
||||
case "]":
|
||||
return "\u{1D}"
|
||||
case "^":
|
||||
return "\u{1E}"
|
||||
case "_", "-":
|
||||
return "\u{1F}"
|
||||
case "?":
|
||||
return "\u{7F}"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class TerminalInputField: UITextField {
|
||||
var onDeleteBackward: (() -> Void)?
|
||||
var onInsert: ((String) -> Void)?
|
||||
|
||||
private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
|
||||
action: #selector(handleHardwareKeyCommand(_:))
|
||||
)
|
||||
|
||||
override var keyCommands: [UIKeyCommand]? {
|
||||
Self.hardwareKeyCommands
|
||||
}
|
||||
|
||||
override func deleteBackward() {
|
||||
onDeleteBackward?()
|
||||
super.deleteBackward()
|
||||
}
|
||||
|
||||
@objc
|
||||
private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
|
||||
guard let input = command.input else { return }
|
||||
guard let sequence = TerminalHardwareKeyEncoder.sequence(
|
||||
input: input,
|
||||
modifiers: command.modifierFlags
|
||||
) else { return }
|
||||
onInsert?(sequence)
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalAppearanceScheme: String {
|
||||
@@ -108,6 +224,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 +292,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)
|
||||
|
||||
+31
-20
@@ -5,7 +5,7 @@
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"dev": "expo start --clear",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --clear",
|
||||
"dev:client": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear",
|
||||
"start": "expo start",
|
||||
"start:dev": "APP_VARIANT=development expo start",
|
||||
"start:preview": "APP_VARIANT=preview expo start",
|
||||
@@ -43,12 +43,16 @@
|
||||
"@clerk/expo": "catalog:",
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@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,38 +66,37 @@
|
||||
"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",
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-keyboard-controller": "1.21.13",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
@@ -117,5 +120,13 @@
|
||||
},
|
||||
"overrides": {
|
||||
"react-native-nitro-markdown": "file:deps/react-native-nitro-markdown-0.5.0.tgz"
|
||||
},
|
||||
"expo": {
|
||||
"autolinking": {
|
||||
"buildFromSource": [
|
||||
"react-native-screens",
|
||||
"@react-native-menu/menu"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,72 @@
|
||||
import {
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
useFonts,
|
||||
} from "@expo-google-fonts/dm-sans";
|
||||
import * as Linking from "expo-linking";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
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 { createStaticNavigation, DarkTheme, DefaultTheme } from "@react-navigation/native";
|
||||
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { useEffect } from "react";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { AppearancePreferencesProvider } from "./features/settings/appearance/AppearancePreferencesProvider";
|
||||
import { RootStack } from "./Stack";
|
||||
import { appAtomRegistry } from "./state/atom-registry";
|
||||
import { useThemeColor } from "./lib/useThemeColor";
|
||||
|
||||
import "../global.css";
|
||||
|
||||
const appLinking = {
|
||||
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
|
||||
};
|
||||
|
||||
const Navigation = createStaticNavigation(RootStack);
|
||||
|
||||
export default function App() {
|
||||
const [fontsLoaded] = useFonts({
|
||||
DMSans_400Regular,
|
||||
DMSans_500Medium,
|
||||
DMSans_700Bold,
|
||||
});
|
||||
const colorScheme = useColorScheme();
|
||||
const statusBarBg = useThemeColor("--color-status-bar");
|
||||
|
||||
useEffect(() => {
|
||||
if (fontsLoaded) SplashScreen.hide();
|
||||
}, [fontsLoaded]);
|
||||
|
||||
return (
|
||||
<RegistryContext.Provider value={appAtomRegistry}>
|
||||
<CloudAuthProvider>
|
||||
<AppearancePreferencesProvider>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<KeyboardProvider statusBarTranslucent>
|
||||
<SafeAreaProvider>
|
||||
<StatusBar
|
||||
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
|
||||
backgroundColor={statusBarBg}
|
||||
translucent
|
||||
/>
|
||||
{/* The navigation theme drives the NATIVE header appearance: native-stack
|
||||
forwards `dark` as the nav bar's overrideUserInterfaceStyle. Without
|
||||
this, React Navigation defaults to its light theme and every native
|
||||
header (glass buttons, title, materials) is forced light even when
|
||||
the system is in dark mode. */}
|
||||
<Navigation
|
||||
linking={appLinking}
|
||||
theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
|
||||
/>
|
||||
</SafeAreaProvider>
|
||||
</KeyboardProvider>
|
||||
</GestureHandlerRootView>
|
||||
</AppearancePreferencesProvider>
|
||||
</CloudAuthProvider>
|
||||
</RegistryContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
import {
|
||||
createPathConfigForStaticNavigation,
|
||||
getPathFromState,
|
||||
NavigationState,
|
||||
StackActions,
|
||||
useNavigation,
|
||||
} from "@react-navigation/native";
|
||||
import {
|
||||
createNativeStackNavigator,
|
||||
createNativeStackScreen,
|
||||
type NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "./components/AppText";
|
||||
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
|
||||
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
|
||||
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
|
||||
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
|
||||
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
|
||||
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
|
||||
import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet";
|
||||
import { ReviewSheet } from "./features/review/ReviewSheet";
|
||||
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
|
||||
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
|
||||
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
|
||||
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
|
||||
import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";
|
||||
import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";
|
||||
import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen";
|
||||
import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen";
|
||||
import { HomeRouteScreen } from "./features/home/HomeRouteScreen";
|
||||
import { AddProjectDestinationRoute } from "./features/projects/AddProjectDestinationRoute";
|
||||
import { AddProjectLocalRoute } from "./features/projects/AddProjectLocalRoute";
|
||||
import { AddProjectRepositoryRoute } from "./features/projects/AddProjectRepositoryRoute";
|
||||
import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute";
|
||||
import { NewTaskDraftRouteScreen } from "./features/threads/NewTaskDraftRouteScreen";
|
||||
import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";
|
||||
import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";
|
||||
import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { SettingsWaitlistRouteScreen } from "./features/settings/SettingsWaitlistRouteScreen";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
// Matches --color-sheet in global.css (light/dark). DynamicColorIOS lets the header
|
||||
// background stay STATIC config while still adapting to appearance changes.
|
||||
const SHEET_BACKGROUND_COLOR =
|
||||
Platform.OS === "ios"
|
||||
? DynamicColorIOS({ light: "rgba(242, 242, 247, 0.98)", dark: "rgba(14, 14, 14, 0.98)" })
|
||||
: undefined;
|
||||
|
||||
type AppScreenOptions = NativeStackNavigationOptions & {
|
||||
readonly unstable_navigationItemStyle?: "editor";
|
||||
};
|
||||
|
||||
// Shared header presets. Screens only override genuinely dynamic values (titles,
|
||||
// subtitles, toolbar items, search callbacks) via NativeStackScreenOptions.
|
||||
//
|
||||
// GLASS: transparent header over the screen's primary scroll view, with the iOS 26
|
||||
// scroll-edge blur sampling the content (Home, Thread, Files tree, settings sheet).
|
||||
const GLASS_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle: Platform.OS === "ios" ? { backgroundColor: "transparent" } : undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: Platform.OS === "ios",
|
||||
scrollEdgeEffects: Platform.OS === "ios" ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
};
|
||||
|
||||
// SOLID: opaque sheet-colored header for surfaces whose content scrolls internally
|
||||
// (file viewer, terminal, review) — there is nothing for glass to sample there.
|
||||
const SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerLargeTitle: false,
|
||||
headerShadowVisible: false,
|
||||
headerShown: true,
|
||||
headerStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? // native-stack types this as `string`, but the native side accepts any
|
||||
// ColorValue including DynamicColorIOS.
|
||||
{ backgroundColor: SHEET_BACKGROUND_COLOR as unknown as string }
|
||||
: undefined,
|
||||
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
headerTransparent: false,
|
||||
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
|
||||
};
|
||||
|
||||
// Solid header variant for screens inside sheets (centered title, no editor style).
|
||||
const SHEET_SOLID_HEADER_OPTIONS: AppScreenOptions = {
|
||||
...SOLID_HEADER_OPTIONS,
|
||||
unstable_navigationItemStyle: undefined,
|
||||
};
|
||||
|
||||
const SettingsSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "Settings",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
},
|
||||
screens: {
|
||||
Settings: createNativeStackScreen({
|
||||
screen: SettingsRouteScreen,
|
||||
linking: "",
|
||||
options: {
|
||||
title: "Settings",
|
||||
},
|
||||
}),
|
||||
SettingsEnvironments: createNativeStackScreen({
|
||||
screen: SettingsEnvironmentsRouteScreen,
|
||||
linking: "environments",
|
||||
options: {
|
||||
title: "Environments",
|
||||
},
|
||||
}),
|
||||
SettingsEnvironmentNew: createNativeStackScreen({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "environment-new",
|
||||
options: {
|
||||
title: "Add Environment",
|
||||
},
|
||||
}),
|
||||
SettingsArchive: createNativeStackScreen({
|
||||
screen: ArchivedThreadsRouteScreen,
|
||||
linking: "archive",
|
||||
options: {
|
||||
title: "Archived Threads",
|
||||
},
|
||||
}),
|
||||
SettingsAppearance: createNativeStackScreen({
|
||||
screen: SettingsAppearanceRouteScreen,
|
||||
linking: "appearance",
|
||||
options: {
|
||||
title: "Appearance",
|
||||
},
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
options: {
|
||||
title: "Sign in",
|
||||
},
|
||||
}),
|
||||
SettingsWaitlist: createNativeStackScreen({
|
||||
screen: SettingsWaitlistRouteScreen,
|
||||
linking: "waitlist",
|
||||
options: {
|
||||
title: "Join the waitlist",
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Thread routes live FLAT in the root stack (not in a nested navigator). A nested
|
||||
// stack means a second UINavigationController with its own UINavigationBar, which
|
||||
// breaks iOS 26's shared-header morphing between Home and Thread (each pair inside
|
||||
// one bar morphs; across two bars the whole screen slides). Flat linking paths keep
|
||||
// the same deep-link URLs the nested config produced.
|
||||
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
|
||||
|
||||
// New-task / add-project flow: nested navigator inside the formSheet (Settings-sheet
|
||||
// pattern — a plain formSheet screen cannot render a stack header; the header and
|
||||
// in-sheet pushes come from this nested stack).
|
||||
const NewTaskSheetStack = createNativeStackNavigator({
|
||||
initialRouteName: "NewTask",
|
||||
screenOptions: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
// Sheets read better with the iOS-default centered title (no editor style).
|
||||
unstable_navigationItemStyle: undefined,
|
||||
},
|
||||
screens: {
|
||||
NewTask: createNativeStackScreen({
|
||||
screen: NewTaskRouteScreen,
|
||||
linking: "",
|
||||
options: {
|
||||
title: "Choose project",
|
||||
},
|
||||
}),
|
||||
NewTaskDraft: createNativeStackScreen({
|
||||
screen: NewTaskDraftRouteScreen,
|
||||
linking: "draft",
|
||||
// The draft composer has no scroll view for glass to sample; a solid
|
||||
// header also lays the content out below the bar (no manual inset).
|
||||
options: SHEET_SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
AddProject: createNativeStackScreen({
|
||||
screen: AddProjectSourceRoute,
|
||||
linking: "add-project",
|
||||
options: {
|
||||
title: "Add Project",
|
||||
},
|
||||
}),
|
||||
AddProjectRepository: createNativeStackScreen({
|
||||
screen: AddProjectRepositoryRoute,
|
||||
linking: "add-project/repository",
|
||||
}),
|
||||
AddProjectDestination: createNativeStackScreen({
|
||||
screen: AddProjectDestinationRoute,
|
||||
linking: "add-project/destination",
|
||||
}),
|
||||
AddProjectLocal: createNativeStackScreen({
|
||||
screen: AddProjectLocalRoute,
|
||||
linking: "add-project/local",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Routes presented as sheets/overlays ON TOP of the workspace. They must not
|
||||
// influence the adaptive workspace layout: opening Settings over Home should
|
||||
// not flip the sidebar in or change the active thread.
|
||||
const WORKSPACE_OVERLAY_ROUTES = new Set([
|
||||
"Connections",
|
||||
"ConnectionsNew",
|
||||
"GitBranches",
|
||||
"GitCommit",
|
||||
"GitConfirm",
|
||||
"GitOverview",
|
||||
"NewTaskSheet",
|
||||
"SettingsSheet",
|
||||
"ThreadReviewComment",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Pathname of the topmost NON-overlay route — the screen the workspace is
|
||||
* actually "on", regardless of any sheets floating above it.
|
||||
*/
|
||||
function workspacePathFromState(state: NavigationState): string {
|
||||
const routes = state.routes.filter((route) => !WORKSPACE_OVERLAY_ROUTES.has(route.name));
|
||||
const effectiveState =
|
||||
routes.length > 0 && routes.length !== state.routes.length
|
||||
? ({ ...state, routes, index: routes.length - 1 } as NavigationState)
|
||||
: state;
|
||||
const path = getPathFromState(effectiveState, navigationPathConfig);
|
||||
return path.startsWith("/") ? path : `/${path}`;
|
||||
}
|
||||
|
||||
function RootStackLayout(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly state: NavigationState;
|
||||
}) {
|
||||
useAgentNotificationNavigation();
|
||||
useThreadOutboxDrain();
|
||||
// Full pathname (sheets included) for keyboard-command scoping; the
|
||||
// workspace layout only reacts to the underlying non-overlay route.
|
||||
const path = getPathFromState(props.state, navigationPathConfig);
|
||||
const pathname = path.startsWith("/") ? path : `/${path}`;
|
||||
const workspacePathname = workspacePathFromState(props.state);
|
||||
|
||||
return (
|
||||
<HardwareKeyboardCommandProvider pathname={pathname}>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
|
||||
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
|
||||
{props.children}
|
||||
</AdaptiveWorkspaceLayout>
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
</HardwareKeyboardCommandProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function NotFoundScreen() {
|
||||
const navigation = useNavigation();
|
||||
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
|
||||
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
|
||||
const returnHomeButtonStyle = StyleSheet.flatten([
|
||||
{
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 20,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
primaryBgStyle,
|
||||
]);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{
|
||||
flexGrow: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 16,
|
||||
paddingHorizontal: 24,
|
||||
paddingVertical: 32,
|
||||
}}
|
||||
style={[{ flex: 1 }, screenBgStyle]}
|
||||
>
|
||||
<Text className="text-3xl font-t3-bold text-foreground" selectable>
|
||||
Route not found
|
||||
</Text>
|
||||
<Pressable
|
||||
style={returnHomeButtonStyle}
|
||||
onPress={() => navigation.dispatch(StackActions.replace("Home"))}
|
||||
>
|
||||
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
|
||||
</Pressable>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
export const RootStack = createNativeStackNavigator({
|
||||
initialRouteName: "Home",
|
||||
layout: RootStackLayout,
|
||||
screenOptions: {
|
||||
headerShown: false,
|
||||
},
|
||||
screens: {
|
||||
Home: createNativeStackScreen({
|
||||
screen: HomeRouteScreen,
|
||||
linking: "",
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle: { backgroundColor: "transparent" },
|
||||
headerBackVisible: false,
|
||||
title: "Threads",
|
||||
},
|
||||
}),
|
||||
Thread: createNativeStackScreen({
|
||||
screen: ThreadRouteScreen,
|
||||
linking: THREAD_LINKING_PREFIX,
|
||||
options: GLASS_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadTerminal: createNativeStackScreen({
|
||||
screen: ThreadTerminalRouteScreen,
|
||||
linking: `${THREAD_LINKING_PREFIX}/terminal`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadReview: createNativeStackScreen({
|
||||
screen: ReviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/review`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
ThreadReviewComment: createNativeStackScreen({
|
||||
screen: ReviewCommentComposerSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/review-comment`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
ThreadFiles: createNativeStackScreen({
|
||||
screen: ThreadFilesTreeScreen,
|
||||
linking: `${THREAD_LINKING_PREFIX}/files`,
|
||||
options: {
|
||||
...GLASS_HEADER_OPTIONS,
|
||||
contentStyle:
|
||||
SHEET_BACKGROUND_COLOR !== undefined
|
||||
? { backgroundColor: SHEET_BACKGROUND_COLOR }
|
||||
: undefined,
|
||||
title: "Files",
|
||||
},
|
||||
}),
|
||||
ThreadFile: createNativeStackScreen({
|
||||
screen: ThreadFileScreen,
|
||||
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
|
||||
options: SOLID_HEADER_OPTIONS,
|
||||
}),
|
||||
GitOverview: createNativeStackScreen({
|
||||
screen: GitOverviewSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
GitCommit: createNativeStackScreen({
|
||||
screen: GitCommitSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/commit`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
GitBranches: createNativeStackScreen({
|
||||
screen: GitBranchesSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git/branches`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
GitConfirm: createNativeStackScreen({
|
||||
screen: GitConfirmSheet,
|
||||
linking: `${THREAD_LINKING_PREFIX}/git-confirm`,
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.45, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
SettingsSheet: createNativeStackScreen({
|
||||
screen: SettingsSheetStack,
|
||||
linking: "settings",
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.7, 0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
Connections: createNativeStackScreen({
|
||||
screen: ConnectionsRouteScreen,
|
||||
linking: "connections",
|
||||
options: {
|
||||
title: "Environments",
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
ConnectionsNew: createNativeStackScreen({
|
||||
screen: ConnectionsNewRouteScreen,
|
||||
linking: "connections/new",
|
||||
options: {
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.55, 0.7],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
NewTaskSheet: createNativeStackScreen({
|
||||
screen: NewTaskSheetStack,
|
||||
linking: "new",
|
||||
// The whole new-task flow (choose project → draft → add project) shares
|
||||
// draft state via NewTaskFlowProvider. The expo-router era mounted it in
|
||||
// app/new/_layout.tsx; this layout wrapper is the native-stack equivalent.
|
||||
layout: ({ children }) => <NewTaskFlowProvider>{children}</NewTaskFlowProvider>,
|
||||
options: {
|
||||
gestureEnabled: true,
|
||||
headerShown: false,
|
||||
presentation: "formSheet",
|
||||
sheetAllowedDetents: [0.92],
|
||||
sheetGrabberVisible: true,
|
||||
},
|
||||
}),
|
||||
NotFound: createNativeStackScreen({
|
||||
screen: NotFoundScreen,
|
||||
linking: "*",
|
||||
}),
|
||||
},
|
||||
});
|
||||
type RootStackType = typeof RootStack;
|
||||
|
||||
const navigationPathConfig = {
|
||||
screens: createPathConfigForStaticNavigation(RootStack) ?? {},
|
||||
};
|
||||
|
||||
declare module "@react-navigation/native" {
|
||||
interface RootNavigator extends RootStackType {}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Link } from "expo-router";
|
||||
import { Pressable, ScrollView, StyleSheet } from "react-native";
|
||||
import { useResolveClassNames } from "uniwind";
|
||||
|
||||
import { AppText as Text } from "../components/AppText";
|
||||
|
||||
export default function NotFoundRoute() {
|
||||
const screenBgStyle = StyleSheet.flatten(useResolveClassNames("bg-screen"));
|
||||
const primaryBgStyle = StyleSheet.flatten(useResolveClassNames("bg-primary"));
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
contentContainerStyle={{
|
||||
flexGrow: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 16,
|
||||
paddingHorizontal: 24,
|
||||
paddingVertical: 32,
|
||||
}}
|
||||
style={[{ flex: 1 }, screenBgStyle]}
|
||||
>
|
||||
<Text className="text-3xl font-t3-bold text-foreground" selectable>
|
||||
Route not found
|
||||
</Text>
|
||||
<Link href="/" asChild>
|
||||
<Pressable
|
||||
style={[
|
||||
{
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 20,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
primaryBgStyle,
|
||||
]}
|
||||
>
|
||||
<Text className="text-base font-t3-bold text-primary-foreground">Return home</Text>
|
||||
</Pressable>
|
||||
</Link>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -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,120 +0,0 @@
|
||||
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 * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import { HomeHeader } from "../features/home/HomeHeader";
|
||||
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
|
||||
import { useThreadListActions } from "../features/home/useThreadListActions";
|
||||
|
||||
interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export default function HomeRouteScreen() {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [listOptions, setListOptions] = useState<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,
|
||||
});
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(
|
||||
Order.String,
|
||||
(environment: { readonly label: string }) => environment.label,
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const selectedEnvironmentId = environments.some(
|
||||
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
|
||||
)
|
||||
? listOptions.selectedEnvironmentId
|
||||
: null;
|
||||
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
|
||||
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
|
||||
}, []);
|
||||
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, projectSortOrder }));
|
||||
}, []);
|
||||
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, threadSortOrder }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
|
||||
setListOptions((current) => ({ ...current, projectGroupingMode }));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenSettings={() => router.push("/settings")}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => router.push("/new")}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
/>
|
||||
|
||||
<HomeScreen
|
||||
catalogState={catalogState}
|
||||
onAddConnection={() => router.push("/connections/new")}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onOpenEnvironments={() => router.push("/settings/environments")}
|
||||
onSelectThread={(thread) => {
|
||||
router.push(buildThreadRoutePath(thread));
|
||||
}}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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,5 +0,0 @@
|
||||
import { AddProjectDestinationScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectDestinationRoute() {
|
||||
return <AddProjectDestinationScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { AddProjectSourceScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectRoute() {
|
||||
return <AddProjectSourceScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { AddProjectLocalFolderScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectLocalRoute() {
|
||||
return <AddProjectLocalFolderScreen />;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Stack, useLocalSearchParams } from "expo-router";
|
||||
import { addProjectRemoteSourceLabel } from "@t3tools/client-runtime/operations/projects";
|
||||
|
||||
import { AddProjectRepositoryScreen } from "../../../features/projects/AddProjectScreen";
|
||||
|
||||
export default function AddProjectRepositoryRoute() {
|
||||
const params = useLocalSearchParams<{ source?: string | string[] }>();
|
||||
const source = Array.isArray(params.source) ? params.source[0] : params.source;
|
||||
const title =
|
||||
source === "github" ||
|
||||
source === "gitlab" ||
|
||||
source === "bitbucket" ||
|
||||
source === "azure-devops"
|
||||
? addProjectRemoteSourceLabel(source)
|
||||
: "Git URL";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ title }} />
|
||||
<AddProjectRepositoryScreen />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { Stack, useLocalSearchParams } from "expo-router";
|
||||
|
||||
import { NewTaskDraftScreen } from "../../features/threads/NewTaskDraftScreen";
|
||||
|
||||
export default function NewTaskDraftRoute() {
|
||||
const params = useLocalSearchParams<{
|
||||
environmentId?: string | string[];
|
||||
projectId?: string | string[];
|
||||
title?: string | string[];
|
||||
}>();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
|
||||
}}
|
||||
/>
|
||||
<NewTaskDraftScreen
|
||||
initialProjectRef={{
|
||||
environmentId: Array.isArray(params.environmentId)
|
||||
? params.environmentId[0]
|
||||
: params.environmentId,
|
||||
projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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,33 +0,0 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { Redirect, Stack } from "expo-router";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../../features/cloud/publicConfig";
|
||||
|
||||
export default function SettingsAuthRouteScreen() {
|
||||
return hasCloudPublicConfig() ? (
|
||||
<ConfiguredSettingsAuthRouteScreen />
|
||||
) : (
|
||||
<Redirect href="/settings" />
|
||||
);
|
||||
}
|
||||
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen options={{ title: isSignedIn ? "Account" : "Sign in" }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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 />;
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Ref } from "react";
|
||||
import {
|
||||
Text as RNText,
|
||||
TextInput as RNTextInput,
|
||||
@@ -21,7 +20,7 @@ export function AppText({ className, ...props }: AppTextProps) {
|
||||
|
||||
export type AppTextInputProps = RNTextInputProps & {
|
||||
readonly className?: string;
|
||||
readonly ref?: Ref<RNTextInput>;
|
||||
readonly ref?: React.Ref<RNTextInput>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -40,7 +39,7 @@ export function AppTextInput({
|
||||
<RNTextInput
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
|
||||
"min-h-13.5 rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground",
|
||||
className,
|
||||
)}
|
||||
placeholderTextColor={placeholderTextColor ?? placeholderColor}
|
||||
|
||||
@@ -75,7 +75,7 @@ export function ControlPill(props: {
|
||||
}
|
||||
|
||||
export function ControlPillMenu(
|
||||
props: Omit<ComponentProps<typeof MenuView>, "children" | "style" | "themeVariant"> & {
|
||||
props: Omit<ComponentProps<typeof MenuView>, "children" | "themeVariant"> & {
|
||||
readonly children: ReactNode;
|
||||
},
|
||||
) {
|
||||
|
||||
@@ -7,11 +7,33 @@ export function EmptyState(props: {
|
||||
readonly detail: string;
|
||||
readonly actionLabel?: string;
|
||||
readonly onAction?: () => void;
|
||||
readonly variant?: "card" | "plain";
|
||||
}) {
|
||||
if (props.variant === "plain") {
|
||||
return (
|
||||
<View className="items-center px-8 py-8">
|
||||
<Text className="text-center text-xl font-t3-bold text-foreground">{props.title}</Text>
|
||||
<Text className="mt-2 text-center font-sans text-base leading-normal text-foreground-muted">
|
||||
{props.detail}
|
||||
</Text>
|
||||
{props.actionLabel && props.onAction ? (
|
||||
<Pressable
|
||||
className="mt-5 rounded-full bg-primary px-5 py-3 active:opacity-70"
|
||||
onPress={props.onAction}
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
{props.actionLabel}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="rounded-[22px] border border-border bg-card p-5">
|
||||
<Text className="font-t3-bold text-lg text-foreground">{props.title}</Text>
|
||||
<Text className="mt-2 font-sans text-sm leading-[21px] text-foreground-muted">
|
||||
<Text className="mt-2 font-sans text-sm leading-relaxed text-foreground-muted">
|
||||
{props.detail}
|
||||
</Text>
|
||||
{props.actionLabel && props.onAction ? (
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AppText as Text } from "./AppText";
|
||||
export function ErrorBanner(props: { readonly message: string }) {
|
||||
return (
|
||||
<View className="rounded-2xl border border-rose-300/70 bg-rose-100/80 px-3.5 py-3 dark:border-rose-400/28 dark:bg-rose-500/12">
|
||||
<Text className="font-t3-medium text-sm leading-[18px] text-rose-700 dark:text-rose-300">
|
||||
<Text className="font-t3-medium text-sm text-rose-700 dark:text-rose-300">
|
||||
{props.message}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -9,12 +11,15 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
| typeof snapshotLoaderLayer
|
||||
| typeof runtimeContextLayer
|
||||
| typeof connectionPlatformLayer;
|
||||
|
||||
const connectionLayer = Connection.layer.pipe(
|
||||
const connectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
|
||||
Layer.provideMerge(Layer.mergeAll(runtimeContextLayer, providedConnectionPlatformLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -32,7 +32,10 @@ import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
// v2 stores the snapshot sequence alongside the thread so a warm cache can
|
||||
// resume via `afterSequence` instead of re-downloading the full thread body.
|
||||
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
@@ -45,7 +48,7 @@ const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
|
||||
const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
@@ -355,18 +358,18 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}),
|
||||
saveThread: (environmentId, thread) =>
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useLinkTo } from "@react-navigation/native";
|
||||
|
||||
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
|
||||
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
|
||||
|
||||
export function useAgentNotificationNavigation(): void {
|
||||
const router = useRouter();
|
||||
const linkTo = useLinkTo();
|
||||
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: linkTo,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -28,5 +28,5 @@ export function useAgentNotificationNavigation(): void {
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, [router]);
|
||||
}, [linkTo]);
|
||||
}
|
||||
@@ -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 "@react-navigation/native";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
|
||||
@@ -2,23 +2,22 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
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 "../../native/StackHeader";
|
||||
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";
|
||||
@@ -26,11 +25,8 @@ import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
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";
|
||||
|
||||
export interface ArchivedThreadsHeaderEnvironment {
|
||||
@@ -52,84 +48,185 @@ const THREAD_ACTIONS: MenuAction[] = [
|
||||
},
|
||||
];
|
||||
|
||||
type ArchivedThreadListItem =
|
||||
| {
|
||||
readonly kind: "project";
|
||||
readonly key: string;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly project: EnvironmentProject;
|
||||
}
|
||||
| {
|
||||
readonly kind: "thread";
|
||||
readonly key: string;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isFirst: boolean;
|
||||
readonly isLast: boolean;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
};
|
||||
|
||||
function ArchivedThreadsHeader(props: {
|
||||
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
|
||||
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
|
||||
{/* Static header config (glass preset + title) lives in Stack.tsx; only
|
||||
dynamic toolbar/search wiring is set here. */}
|
||||
<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("");
|
||||
},
|
||||
},
|
||||
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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -164,30 +261,25 @@ function ProjectGroupLabel(props: {
|
||||
|
||||
function ArchivedThreadRow(props: {
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isFirst: boolean;
|
||||
readonly isLast: boolean;
|
||||
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 +292,84 @@ 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,
|
||||
borderTopLeftRadius: props.isFirst ? 20 : 0,
|
||||
borderTopRightRadius: props.isFirst ? 20 : 0,
|
||||
borderBottomLeftRadius: props.isLast ? 20 : 0,
|
||||
borderBottomRightRadius: props.isLast ? 20 : 0,
|
||||
}}
|
||||
>
|
||||
<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-snug text-foreground"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"], minWidth: 30, textAlign: "right" }}
|
||||
>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -317,7 +379,7 @@ function ArchiveError(props: { readonly message: string; readonly onRetry: () =>
|
||||
<Text className="text-base font-t3-bold text-danger-foreground">
|
||||
Could not load every archive
|
||||
</Text>
|
||||
<Text className="mt-1 text-sm leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Text className="mt-1 text-sm text-foreground-muted">{props.message}</Text>
|
||||
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
|
||||
<Text className="text-sm font-t3-bold text-danger-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
@@ -340,8 +402,41 @@ export function ArchivedThreadsScreen(props: {
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
}) {
|
||||
const { onDeleteThread, onUnarchiveThread } = props;
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const refreshTint = useThemeColor("--color-icon");
|
||||
const environmentLabelsById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
props.environments.map((environment) => [environment.environmentId, environment.label]),
|
||||
),
|
||||
[props.environments],
|
||||
);
|
||||
const listItems = useMemo<ReadonlyArray<ArchivedThreadListItem>>(() => {
|
||||
const items: ArchivedThreadListItem[] = [];
|
||||
for (const group of props.groups) {
|
||||
const environmentLabel = environmentLabelsById.get(group.project.environmentId) ?? null;
|
||||
items.push({
|
||||
kind: "project",
|
||||
key: `${group.key}:project`,
|
||||
environmentLabel,
|
||||
project: group.project,
|
||||
});
|
||||
|
||||
group.threads.forEach((thread, index) => {
|
||||
items.push({
|
||||
kind: "thread",
|
||||
key: `${thread.environmentId}:${thread.id}`,
|
||||
environmentLabel,
|
||||
isFirst: index === 0,
|
||||
isLast: index === group.threads.length - 1,
|
||||
thread,
|
||||
});
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}, [environmentLabelsById, props.groups]);
|
||||
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
|
||||
openSwipeableRef.current.close();
|
||||
@@ -355,82 +450,103 @@ export function ArchivedThreadsScreen(props: {
|
||||
}, []);
|
||||
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
|
||||
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
|
||||
const renderListItem = useCallback(
|
||||
({ item }: { item: ArchivedThreadListItem }) => {
|
||||
if (item.kind === "project") {
|
||||
return (
|
||||
<View className="pt-4">
|
||||
<ProjectGroupLabel environmentLabel={item.environmentLabel} project={item.project} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ArchivedThreadRow
|
||||
environmentLabel={item.environmentLabel}
|
||||
isFirst={item.isFirst}
|
||||
isLast={item.isLast}
|
||||
onDelete={() => onDeleteThread(item.thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => onUnarchiveThread(item.thread)}
|
||||
simultaneousSwipeGesture={archiveScrollGesture}
|
||||
thread={item.thread}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
archiveScrollGesture,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
onDeleteThread,
|
||||
onUnarchiveThread,
|
||||
],
|
||||
);
|
||||
const listEmptyComponent = useMemo(() => {
|
||||
if (isInitialLoad) {
|
||||
return (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-sm text-foreground-muted">Loading archive...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
);
|
||||
}, [isFiltered, isInitialLoad, refreshTint]);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<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}
|
||||
|
||||
{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}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
<GestureDetector gesture={archiveScrollGesture}>
|
||||
<LegendList
|
||||
className="flex-1"
|
||||
contentContainerStyle={{
|
||||
paddingBottom: 32,
|
||||
paddingHorizontal: 16,
|
||||
paddingTop: 4,
|
||||
}}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
data={listItems}
|
||||
estimatedItemSize={62}
|
||||
getItemType={(item) => item.kind}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyExtractor={(item) => item.key}
|
||||
ListEmptyComponent={listEmptyComponent}
|
||||
ListHeaderComponent={
|
||||
props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null
|
||||
}
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
renderItem={renderListItem}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
</GestureDetector>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { useWaitlist } from "@clerk/expo";
|
||||
import { ActivityIndicator, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
|
||||
import { useState } from "react";
|
||||
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
|
||||
|
||||
@@ -36,8 +35,10 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
if (waitlist.id) {
|
||||
return (
|
||||
<View style={styles.content}>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>You are on the waitlist</Text>
|
||||
<Text style={[styles.body, styles.confirmationBody, { color: colors.secondaryForeground }]}>
|
||||
<Text className="text-center font-t3-bold text-xl text-foreground">
|
||||
You are on the waitlist
|
||||
</Text>
|
||||
<Text className="text-center font-sans text-base text-foreground-secondary">
|
||||
We will email you when your T3 Cloud access is ready.
|
||||
</Text>
|
||||
<SignInAction onPress={props.onSignIn} />
|
||||
@@ -47,17 +48,18 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
|
||||
return (
|
||||
<View style={styles.content}>
|
||||
<Text style={[styles.body, { color: colors.secondaryForeground }]}>
|
||||
<Text className="font-sans text-base text-foreground-secondary">
|
||||
Enter your email and we will let you know when access is ready.
|
||||
</Text>
|
||||
|
||||
<View style={styles.field}>
|
||||
<Text style={[styles.label, { color: colors.secondaryForeground }]}>Email address</Text>
|
||||
<Text className="font-t3-bold text-sm text-foreground-secondary">Email address</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Email address"
|
||||
autoCapitalize="none"
|
||||
autoComplete="email"
|
||||
autoCorrect={false}
|
||||
className="font-sans text-lg text-foreground"
|
||||
keyboardType="email-address"
|
||||
onChangeText={(value) => {
|
||||
setEmailAddress(value);
|
||||
@@ -73,7 +75,6 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
backgroundColor: colors.input,
|
||||
borderColor:
|
||||
fieldError || requestError ? colors.dangerForeground : colors.inputBorder,
|
||||
color: colors.foreground,
|
||||
},
|
||||
]}
|
||||
textContentType="emailAddress"
|
||||
@@ -82,7 +83,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
{fieldError || requestError ? (
|
||||
<Text
|
||||
accessibilityLiveRegion="polite"
|
||||
style={[styles.error, { color: colors.dangerForeground }]}
|
||||
className="font-sans text-sm text-danger-foreground"
|
||||
selectable
|
||||
>
|
||||
{fieldError ?? requestError}
|
||||
@@ -107,7 +108,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
]}
|
||||
>
|
||||
{isSubmitting ? <ActivityIndicator color={colors.primaryForeground} size="small" /> : null}
|
||||
<Text style={[styles.buttonText, { color: colors.primaryForeground }]}>
|
||||
<Text className="font-t3-bold text-base text-primary-foreground">
|
||||
{isSubmitting ? "Joining" : "Join the waitlist"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -118,12 +119,11 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
|
||||
}
|
||||
|
||||
function SignInAction(props: { readonly onPress: () => void }) {
|
||||
const colors = useCloudWaitlistColors();
|
||||
return (
|
||||
<View style={styles.signInRow}>
|
||||
<Text style={[styles.body, { color: colors.secondaryForeground }]}>Already have access?</Text>
|
||||
<Text className="font-sans text-base text-foreground-secondary">Already have access?</Text>
|
||||
<Pressable accessibilityRole="button" hitSlop={8} onPress={props.onPress}>
|
||||
<Text style={[styles.signInText, { color: colors.foreground }]}>Sign in</Text>
|
||||
<Text className="font-t3-bold text-base text-foreground">Sign in</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
@@ -132,35 +132,18 @@ function SignInAction(props: { readonly onPress: () => void }) {
|
||||
function useCloudWaitlistColors() {
|
||||
return {
|
||||
dangerForeground: String(useThemeColor("--color-danger-foreground")),
|
||||
foreground: String(useThemeColor("--color-foreground")),
|
||||
input: String(useThemeColor("--color-input")),
|
||||
inputBorder: String(useThemeColor("--color-input-border")),
|
||||
placeholder: String(useThemeColor("--color-placeholder")),
|
||||
primary: String(useThemeColor("--color-primary")),
|
||||
primaryForeground: String(useThemeColor("--color-primary-foreground")),
|
||||
secondaryForeground: String(useThemeColor("--color-foreground-secondary")),
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
body: {
|
||||
fontFamily: "DMSans_400Regular",
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
buttonText: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.body.fontSize,
|
||||
},
|
||||
content: {
|
||||
gap: 18,
|
||||
},
|
||||
confirmationBody: {
|
||||
textAlign: "center",
|
||||
},
|
||||
error: {
|
||||
fontFamily: "DMSans_400Regular",
|
||||
...MOBILE_TYPOGRAPHY.footnote,
|
||||
},
|
||||
field: {
|
||||
gap: 8,
|
||||
},
|
||||
@@ -168,16 +151,10 @@ const styles = StyleSheet.create({
|
||||
borderCurve: "continuous",
|
||||
borderRadius: 16,
|
||||
borderWidth: 1,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
minHeight: 54,
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
label: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
...MOBILE_TYPOGRAPHY.footnote,
|
||||
},
|
||||
primaryButton: {
|
||||
alignItems: "center",
|
||||
borderRadius: 999,
|
||||
@@ -195,13 +172,4 @@ const styles = StyleSheet.create({
|
||||
justifyContent: "center",
|
||||
paddingTop: 4,
|
||||
},
|
||||
signInText: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
},
|
||||
title: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
...MOBILE_TYPOGRAPHY.title,
|
||||
textAlign: "center",
|
||||
},
|
||||
});
|
||||
@@ -8,12 +8,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as ExpoCrypto from "expo-crypto";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import { p256 } from "@noble/curves/nist";
|
||||
import {
|
||||
computeDpopAccessTokenHash,
|
||||
computeDpopJwkThumbprint,
|
||||
DpopPublicJwk,
|
||||
normalizeDpopHtu,
|
||||
} from "@t3tools/shared/dpop";
|
||||
import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
|
||||
@@ -107,6 +102,40 @@ function sha256Digest(
|
||||
);
|
||||
}
|
||||
|
||||
function base64UrlSha256(
|
||||
data: Uint8Array,
|
||||
message: string,
|
||||
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
|
||||
return sha256Digest(data, message).pipe(Effect.map(Encoding.encodeBase64Url));
|
||||
}
|
||||
|
||||
function dpopThumbprintInput(jwk: DpopPublicJwk): string {
|
||||
return JSON.stringify({
|
||||
crv: jwk.crv,
|
||||
kty: jwk.kty,
|
||||
x: jwk.x,
|
||||
y: jwk.y,
|
||||
});
|
||||
}
|
||||
|
||||
function computeDpopJwkThumbprintEffect(
|
||||
jwk: DpopPublicJwk,
|
||||
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
|
||||
return base64UrlSha256(
|
||||
new TextEncoder().encode(dpopThumbprintInput(jwk)),
|
||||
"Could not hash the DPoP public key thumbprint.",
|
||||
);
|
||||
}
|
||||
|
||||
function computeDpopAccessTokenHashEffect(
|
||||
accessToken: string,
|
||||
): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
|
||||
return base64UrlSha256(
|
||||
new TextEncoder().encode(accessToken),
|
||||
"Could not hash the DPoP access token.",
|
||||
);
|
||||
}
|
||||
|
||||
function secureRandomBytes(
|
||||
byteCount: number,
|
||||
message: string,
|
||||
@@ -153,7 +182,7 @@ export function generateDpopProofKeyPair(): Effect.Effect<
|
||||
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
|
||||
catch: cloudDpopError("Generated DPoP public key is invalid."),
|
||||
});
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);
|
||||
return {
|
||||
privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
|
||||
publicJwk,
|
||||
@@ -189,9 +218,10 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
},
|
||||
catch: cloudDpopError("Stored DPoP proof key is invalid."),
|
||||
});
|
||||
const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
|
||||
return {
|
||||
...restored,
|
||||
thumbprint: computeDpopJwkThumbprint(restored.publicJwk),
|
||||
thumbprint,
|
||||
};
|
||||
}
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
@@ -243,7 +273,9 @@ export function createDpopProof(input: {
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
|
||||
);
|
||||
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
|
||||
const ath = input.accessToken
|
||||
? yield* computeDpopAccessTokenHashEffect(input.accessToken)
|
||||
: null;
|
||||
const payload = yield* encodeDpopJwtPayloadJson({
|
||||
htm: input.method.toUpperCase(),
|
||||
htu,
|
||||
|
||||
@@ -76,16 +76,16 @@ export function ConnectionEnvironmentRow(props: {
|
||||
/>
|
||||
|
||||
<View className="flex-1 gap-0.5">
|
||||
<Text className="text-base font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
|
||||
<Text className="text-base font-t3-bold leading-snug text-foreground" numberOfLines={1}>
|
||||
{props.environment.environmentLabel}
|
||||
</Text>
|
||||
<Text className="text-xs leading-[16px] text-foreground-muted" numberOfLines={1}>
|
||||
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
|
||||
{props.environment.displayUrl}
|
||||
</Text>
|
||||
{statusLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs leading-[16px]",
|
||||
"text-xs",
|
||||
hasConnectionFailure ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={props.expanded ? undefined : 1}
|
||||
@@ -134,7 +134,7 @@ export function ConnectionEnvironmentRow(props: {
|
||||
className="gap-3 px-4 pb-4"
|
||||
>
|
||||
{props.environment.isRelayManaged ? (
|
||||
<Text className="text-sm leading-[18px] text-foreground-muted">
|
||||
<Text className="text-sm text-foreground-muted">
|
||||
Managed by T3 Cloud. Tunnel details update automatically.
|
||||
</Text>
|
||||
) : (
|
||||
|
||||
+27
-15
@@ -1,5 +1,6 @@
|
||||
import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Alert, ScrollView, View } from "react-native";
|
||||
@@ -8,21 +9,26 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ErrorBanner } from "../../components/ErrorBanner";
|
||||
import { dismissRoute } from "../../lib/routes";
|
||||
import { ConnectionSheetButton } from "../../features/connection/ConnectionSheetButton";
|
||||
import { extractPairingUrlFromQrPayload } from "../../features/connection/pairing";
|
||||
import { ConnectionSheetButton } from "./ConnectionSheetButton";
|
||||
import { extractPairingUrlFromQrPayload } from "./pairing";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { buildPairingUrl, parsePairingUrl } from "../../features/connection/pairing";
|
||||
import { buildPairingUrl, parsePairingUrl } from "./pairing";
|
||||
|
||||
export default function ConnectionsNewRouteScreen() {
|
||||
type ConnectionsNewRouteParams = {
|
||||
readonly mode?: string;
|
||||
};
|
||||
|
||||
export function ConnectionsNewRouteScreen({
|
||||
route,
|
||||
}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
|
||||
const {
|
||||
connectionPairingUrl,
|
||||
onChangeConnectionPairingUrl,
|
||||
onConnectPress,
|
||||
pairingConnectionError,
|
||||
} = useRemoteConnections();
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{ mode?: string }>();
|
||||
const navigation = useNavigation();
|
||||
const params = route.params ?? {};
|
||||
const insets = useSafeAreaInsets();
|
||||
const [hostInput, setHostInput] = useState("");
|
||||
const [codeInput, setCodeInput] = useState("");
|
||||
@@ -31,6 +37,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
|
||||
const [scannerLocked, setScannerLocked] = useState(false);
|
||||
|
||||
const headerIconColor = useThemeColor("--color-icon");
|
||||
const placeholderColor = useThemeColor("--color-placeholder");
|
||||
|
||||
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
|
||||
@@ -116,21 +123,25 @@ export default function ConnectionsNewRouteScreen() {
|
||||
onChangeConnectionPairingUrl(pairingUrl);
|
||||
const result = await onConnectPress(pairingUrl);
|
||||
if (AsyncResult.isSuccess(result)) {
|
||||
dismissRoute(router);
|
||||
if (navigation.canGoBack()) {
|
||||
navigation.goBack();
|
||||
} else {
|
||||
navigation.dispatch(StackActions.replace("Home"));
|
||||
}
|
||||
} else {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, router]);
|
||||
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
title: showScanner ? "Scan QR Code" : "Add Environment",
|
||||
}}
|
||||
/>
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button
|
||||
icon={showScanner ? "xmark" : "qrcode.viewfinder"}
|
||||
onPress={() => {
|
||||
if (showScanner) {
|
||||
@@ -140,8 +151,9 @@ export default function ConnectionsNewRouteScreen() {
|
||||
}
|
||||
}}
|
||||
separateBackground
|
||||
tintColor={headerIconColor}
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
</NativeHeaderToolbar>
|
||||
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
@@ -171,7 +183,7 @@ export default function ConnectionsNewRouteScreen() {
|
||||
className="items-center gap-3 rounded-[24px] bg-card px-5 py-8"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
Camera permission is required to scan a QR code.
|
||||
</Text>
|
||||
<ConnectionSheetButton
|
||||
+10
-14
@@ -1,4 +1,5 @@
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { NativeHeaderToolbar } from "../../native/StackHeader";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
@@ -9,16 +10,16 @@ import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow";
|
||||
import { ConnectionEnvironmentRow } from "./ConnectionEnvironmentRow";
|
||||
|
||||
export default function ConnectionsRouteScreen() {
|
||||
export function ConnectionsRouteScreen() {
|
||||
const {
|
||||
connectedEnvironments,
|
||||
onReconnectEnvironment,
|
||||
onRemoveEnvironmentPress,
|
||||
onUpdateEnvironment,
|
||||
} = useRemoteConnections();
|
||||
const router = useRouter();
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const hasEnvironments = connectedEnvironments.length > 0;
|
||||
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
|
||||
@@ -31,18 +32,13 @@ export default function ConnectionsRouteScreen() {
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Environments",
|
||||
}}
|
||||
/>
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
<NativeHeaderToolbar placement="right">
|
||||
<NativeHeaderToolbar.Button
|
||||
icon="plus"
|
||||
onPress={() => router.push("/connections/new")}
|
||||
onPress={() => navigation.navigate("ConnectionsNew")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
</NativeHeaderToolbar>
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
@@ -85,7 +81,7 @@ export default function ConnectionsRouteScreen() {
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
No environments connected yet.{"\n"}Tap{" "}
|
||||
<Text className="font-t3-bold text-foreground">+</Text> to add one.
|
||||
</Text>
|
||||
@@ -73,10 +73,10 @@ export function EnvironmentConnectionNotice(props: {
|
||||
/>
|
||||
)}
|
||||
|
||||
<Text className="text-center text-lg font-t3-bold leading-[22px] text-foreground">
|
||||
<Text className="text-center text-lg font-t3-bold text-foreground">
|
||||
{noticeTitle(props.connection.phase, props.environmentLabel)}
|
||||
</Text>
|
||||
<Text className="text-center text-sm leading-[20px] text-foreground-muted">
|
||||
<Text className="text-center text-sm leading-normal text-foreground-muted">
|
||||
{noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
|
||||
{props.connection.traceId ? (
|
||||
<>
|
||||
|
||||
@@ -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,13 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly rowHeight: number;
|
||||
readonly contentWidth: number;
|
||||
readonly initialRowIndex?: number;
|
||||
readonly refreshing?: boolean;
|
||||
readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
|
||||
readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
|
||||
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 +144,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 +279,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
|
||||
cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
|
||||
NATIVE_REVIEW_DIFF_MODULE_NAME,
|
||||
);
|
||||
} catch (cause) {
|
||||
@@ -166,5 +293,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedNativeReviewDiffView ?? null;
|
||||
return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
|
||||
}
|
||||
@@ -1,15 +1,19 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
type NodeStyleOverrides,
|
||||
type PartialMarkdownTheme,
|
||||
} from "react-native-nitro-markdown";
|
||||
import { ScrollView, Text as NativeText, View } from "react-native";
|
||||
import { RefreshControl, ScrollView, Text as NativeText, View } from "react-native";
|
||||
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import {
|
||||
resolveMarkdownFontSizes,
|
||||
resolveNativeMarkdownTypography,
|
||||
} from "../../lib/appearancePreferences";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
@@ -24,6 +28,15 @@ interface MarkdownPreviewStyles {
|
||||
}
|
||||
|
||||
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const markdownFontSizes = useMemo(
|
||||
() => resolveMarkdownFontSizes(appearance.baseFontSize),
|
||||
[appearance.baseFontSize],
|
||||
);
|
||||
const nativeMarkdownTypography = useMemo(
|
||||
() => resolveNativeMarkdownTypography(appearance.baseFontSize),
|
||||
[appearance.baseFontSize],
|
||||
);
|
||||
const body = String(useThemeColor("--color-md-body"));
|
||||
const strong = String(useThemeColor("--color-md-strong"));
|
||||
const link = String(useThemeColor("--color-md-link"));
|
||||
@@ -74,7 +87,8 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
text: {
|
||||
color: body,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
fontSize: markdownFontSizes.m,
|
||||
lineHeight: markdownFontSizes.bodyLineHeight,
|
||||
},
|
||||
heading: {
|
||||
color: strong,
|
||||
@@ -124,7 +138,9 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
skillTextColor: codeText,
|
||||
quoteMarkerColor: blockquoteBorder,
|
||||
dividerColor: horizontalRule,
|
||||
...MOBILE_TYPOGRAPHY.body,
|
||||
fontSize: nativeMarkdownTypography.fontSize,
|
||||
lineHeight: nativeMarkdownTypography.lineHeight,
|
||||
headingFontSizes: nativeMarkdownTypography.headingFontSizes,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
headingFontFamily: "DMSans_700Bold",
|
||||
boldFontFamily: "DMSans_700Bold",
|
||||
@@ -138,18 +154,46 @@ function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
codeText,
|
||||
horizontalRule,
|
||||
link,
|
||||
markdownFontSizes,
|
||||
nativeMarkdownTypography,
|
||||
strong,
|
||||
]);
|
||||
}
|
||||
|
||||
export function FileMarkdownPreview(props: { readonly markdown: string }) {
|
||||
export function FileMarkdownPreview(props: {
|
||||
readonly markdown: string;
|
||||
readonly onRefresh?: () => Promise<void> | void;
|
||||
}) {
|
||||
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
|
||||
const handlePullToRefresh = useCallback(async () => {
|
||||
if (!props.onRefresh) {
|
||||
return;
|
||||
}
|
||||
setIsPullRefreshing(true);
|
||||
try {
|
||||
await props.onRefresh();
|
||||
} finally {
|
||||
setIsPullRefreshing(false);
|
||||
}
|
||||
}, [props.onRefresh]);
|
||||
const styles = useMarkdownPreviewStyles();
|
||||
const onLinkPress = useCallback((href: string) => {
|
||||
void tryOpenExternalUrl(href, "markdown-link");
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
|
||||
<ScrollView
|
||||
className="flex-1 bg-sheet"
|
||||
contentContainerStyle={{ padding: 18 }}
|
||||
refreshControl={
|
||||
props.onRefresh ? (
|
||||
<RefreshControl
|
||||
refreshing={isPullRefreshing}
|
||||
onRefresh={() => void handlePullToRefresh()}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<View className="mx-auto w-full max-w-[760px]">
|
||||
{hasNativeSelectableMarkdownText() ? (
|
||||
<SelectableMarkdownText
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
@@ -11,9 +19,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 +49,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 +76,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 }}
|
||||
>
|
||||
@@ -64,8 +93,10 @@ const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
|
||||
<Text
|
||||
className={cn(
|
||||
"min-w-0 flex-1 text-sm leading-[19px]",
|
||||
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
|
||||
"min-w-0 flex-1 text-sm leading-normal",
|
||||
props.selected
|
||||
? "font-t3-bold text-foreground"
|
||||
: "font-t3-medium text-foreground-secondary",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -86,13 +117,30 @@ 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 insets = useSafeAreaInsets();
|
||||
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
|
||||
// observed adjustedContentInset bottom (~102) seen in the native trace.
|
||||
const headerInset = Platform.OS === "ios" ? insets.top + 44 : 0;
|
||||
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 +162,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,53 +198,86 @@ 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],
|
||||
);
|
||||
|
||||
if (props.error && props.entries.length === 0) {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet px-4 py-5">
|
||||
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
|
||||
<Text className="mt-1 text-xs leading-normal text-foreground-muted">{props.error}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// SPIKE: render the FlatList as the screen's DIRECT content (no wrapping View), and
|
||||
// mirror the Home ScrollView exactly — `contentInsetAdjustmentBehavior: "automatic"`
|
||||
// with NO manual contentInset. iOS only applies the nav-bar top inset + scroll-edge
|
||||
// blur to a scroll view in the screen's primary position; a scroll view buried in
|
||||
// flex-1 Views is ignored, which is why the tree rendered under the header with no blur.
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
{props.error && props.entries.length === 0 ? (
|
||||
<FlatList
|
||||
style={{ flex: 1 }}
|
||||
data={visibleNodes}
|
||||
keyExtractor={(item) => item.node.path}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios" ? { top: headerInset, left: 0, right: 0, bottom: 0 } : undefined
|
||||
}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
|
||||
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
|
||||
updateCellsBatchingPeriod={16}
|
||||
windowSize={5}
|
||||
contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
|
||||
refreshControl={<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />}
|
||||
renderItem={renderItem}
|
||||
ListEmptyComponent={
|
||||
<View className="px-4 py-5">
|
||||
<Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
|
||||
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">{props.error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<FlatList
|
||||
data={visibleNodes}
|
||||
keyExtractor={(item) => item.node.path}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
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}
|
||||
/>
|
||||
{props.isPending ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<>
|
||||
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
|
||||
<Text className="mt-1 text-xs leading-normal text-foreground-muted">
|
||||
{props.searchQuery.trim().length > 0
|
||||
? "Try a different search."
|
||||
: "The workspace file index is empty."}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
ListEmptyComponent={
|
||||
<View className="px-4 py-5">
|
||||
{props.isPending ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<>
|
||||
<Text className="text-sm font-t3-bold text-foreground">No files found</Text>
|
||||
<Text className="mt-1 text-xs leading-[18px] text-foreground-muted">
|
||||
{props.searchQuery.trim().length > 0
|
||||
? "Try a different search."
|
||||
: "The workspace file index is empty."}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { ComponentType } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
FlatList,
|
||||
ScrollView,
|
||||
Text as NativeText,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { LoadingStrip } from "../../components/LoadingStrip";
|
||||
@@ -11,71 +18,62 @@ import {
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
|
||||
import {
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_MONO_FONT_FAMILY,
|
||||
renderVisibleWhitespace,
|
||||
} from "../review/reviewDiffRendering";
|
||||
import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering";
|
||||
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
|
||||
import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
|
||||
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
|
||||
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;
|
||||
const SOURCE_LINE_NUMBER_WIDTH = MOBILE_CODE_SURFACE.gutterWidth;
|
||||
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
|
||||
|
||||
interface SourceFileSurfaceProps {
|
||||
readonly contents: string;
|
||||
readonly path: string;
|
||||
readonly initialLine?: number | null;
|
||||
/** Enables native pull-to-refresh on the source surface. */
|
||||
readonly onRefresh?: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
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 codeSurface: ResolvedMobileCodeSurface;
|
||||
readonly index: number;
|
||||
readonly line: string;
|
||||
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
|
||||
readonly highlighted: boolean;
|
||||
readonly wordBreak: boolean;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
className={cn("flex-row", props.highlighted && "bg-primary/10")}
|
||||
style={{ minHeight: SOURCE_LINE_HEIGHT }}
|
||||
style={{ minHeight: props.codeSurface.rowHeight }}
|
||||
>
|
||||
<NativeText
|
||||
className="select-none pr-3 text-right text-foreground-tertiary"
|
||||
style={{
|
||||
width: SOURCE_LINE_NUMBER_WIDTH,
|
||||
width: props.codeSurface.gutterWidth,
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
|
||||
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
|
||||
fontSize: props.codeSurface.lineNumberFontSize,
|
||||
lineHeight: props.codeSurface.rowHeight,
|
||||
}}
|
||||
>
|
||||
{props.index + 1}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
selectable
|
||||
numberOfLines={1}
|
||||
className="font-normal text-foreground"
|
||||
numberOfLines={props.wordBreak ? undefined : 1}
|
||||
className="flex-1 font-normal text-foreground"
|
||||
style={{
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontSize: MOBILE_CODE_SURFACE.fontSize,
|
||||
lineHeight: MOBILE_CODE_SURFACE.rowHeight,
|
||||
minWidth: 320,
|
||||
fontSize: props.codeSurface.fontSize,
|
||||
lineHeight: props.codeSurface.rowHeight,
|
||||
minWidth: props.wordBreak ? undefined : 320,
|
||||
}}
|
||||
>
|
||||
{props.tokens && props.tokens.length > 0
|
||||
@@ -119,11 +117,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 +135,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 }) {
|
||||
@@ -162,39 +157,63 @@ function NativeSourceFileSurface(
|
||||
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
|
||||
},
|
||||
) {
|
||||
const { NativeView } = props;
|
||||
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
|
||||
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
|
||||
const { NativeView, onRefresh } = props;
|
||||
const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props);
|
||||
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
|
||||
const handlePullToRefresh = useCallback(async () => {
|
||||
if (!onRefresh) {
|
||||
return;
|
||||
}
|
||||
setIsPullRefreshing(true);
|
||||
try {
|
||||
await onRefresh();
|
||||
} finally {
|
||||
setIsPullRefreshing(false);
|
||||
}
|
||||
}, [onRefresh]);
|
||||
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
|
||||
const selectedRowIdsJson = useMemo(
|
||||
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
|
||||
[targetIndex],
|
||||
);
|
||||
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
|
||||
const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]);
|
||||
const contentWidth = codeWordBreak
|
||||
? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
|
||||
: NATIVE_SOURCE_CONTENT_WIDTH;
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
<View className="relative flex-1 bg-sheet">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<NativeView
|
||||
key={props.path}
|
||||
collapsable={false}
|
||||
testID="source-native-code-view"
|
||||
style={{ flex: 1 }}
|
||||
appearanceScheme={theme}
|
||||
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
|
||||
contentResetKey={props.path}
|
||||
contentWidth={contentWidth}
|
||||
initialRowIndex={targetIndex ?? -1}
|
||||
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
|
||||
rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
|
||||
rowsJson={rowsJson}
|
||||
selectedRowIdsJson={selectedRowIdsJson}
|
||||
styleJson={NATIVE_SOURCE_STYLE_JSON}
|
||||
styleJson={styleJson}
|
||||
themeJson={themeJson}
|
||||
tokensJson={tokensJson}
|
||||
{...(onRefresh
|
||||
? {
|
||||
refreshing: isPullRefreshing,
|
||||
onPullToRefresh: () => void handlePullToRefresh(),
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
|
||||
const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
|
||||
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
|
||||
const listRef = useRef<FlatList<string>>(null);
|
||||
|
||||
@@ -211,39 +230,53 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
|
||||
const renderLine = useCallback(
|
||||
({ item, index }: { item: string; index: number }) => (
|
||||
<HighlightedSourceLine
|
||||
codeSurface={codeSurface}
|
||||
index={index}
|
||||
line={item}
|
||||
tokens={tokens?.[index] ?? null}
|
||||
highlighted={index === targetIndex}
|
||||
wordBreak={codeWordBreak}
|
||||
/>
|
||||
),
|
||||
[targetIndex, tokens],
|
||||
[codeSurface, codeWordBreak, targetIndex, tokens],
|
||||
);
|
||||
|
||||
const list = (
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={lines}
|
||||
keyExtractor={(_line, index) => String(index)}
|
||||
initialNumToRender={80}
|
||||
maxToRenderPerBatch={80}
|
||||
windowSize={12}
|
||||
{...(codeWordBreak
|
||||
? {}
|
||||
: {
|
||||
getItemLayout: (_data, index) => ({
|
||||
length: codeSurface.rowHeight,
|
||||
offset: codeSurface.rowHeight * index,
|
||||
index,
|
||||
}),
|
||||
})}
|
||||
contentContainerStyle={{
|
||||
minWidth: codeWordBreak ? undefined : "100%",
|
||||
paddingBottom: codeSurface.rowHeight,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
renderItem={renderLine}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
<View className="relative flex-1 bg-sheet">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<ScrollView horizontal bounces={false} className="flex-1">
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={lines}
|
||||
keyExtractor={(_line, index) => String(index)}
|
||||
initialNumToRender={80}
|
||||
maxToRenderPerBatch={80}
|
||||
windowSize={12}
|
||||
getItemLayout={(_data, index) => ({
|
||||
length: SOURCE_LINE_HEIGHT,
|
||||
offset: SOURCE_LINE_HEIGHT * index,
|
||||
index,
|
||||
})}
|
||||
contentContainerStyle={{
|
||||
minWidth: "100%",
|
||||
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
renderItem={renderLine}
|
||||
/>
|
||||
</ScrollView>
|
||||
{codeWordBreak ? (
|
||||
list
|
||||
) : (
|
||||
<ScrollView horizontal bounces={false} className="flex-1">
|
||||
{list}
|
||||
</ScrollView>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import Stack from "expo-router/stack";
|
||||
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 { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
useColorScheme,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
|
||||
import {
|
||||
EnvironmentId,
|
||||
@@ -12,22 +19,31 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
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 { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { buildThreadFilesNavigation } 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 {
|
||||
useAdaptiveWorkspaceLayout,
|
||||
useAdaptiveWorkspacePaneRole,
|
||||
useRegisterWorkspaceInspector,
|
||||
} 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 {
|
||||
@@ -72,196 +88,6 @@ function defaultViewMode(path: string | null): FileViewMode {
|
||||
: "source";
|
||||
}
|
||||
|
||||
function ModeButton(props: {
|
||||
readonly active: boolean;
|
||||
readonly icon: "doc.text" | "eye";
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
const iconColor = String(
|
||||
useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: props.active }}
|
||||
className={cn(
|
||||
"h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
|
||||
props.active ? "bg-primary" : "bg-subtle",
|
||||
)}
|
||||
onPress={props.onPress}
|
||||
>
|
||||
<SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs font-t3-bold",
|
||||
props.active ? "text-primary-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
|
||||
const gradientId = `file-breadcrumb-${props.side}-fade`;
|
||||
const isLeft = props.side === "left";
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
|
||||
>
|
||||
<Svg width="100%" height="100%">
|
||||
<Defs>
|
||||
<LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
|
||||
<Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
|
||||
<Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
|
||||
</LinearGradient>
|
||||
</Defs>
|
||||
<Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
|
||||
</Svg>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const cardColor = String(useThemeColor("--color-card"));
|
||||
const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
|
||||
const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
|
||||
const breadcrumbs = useMemo(
|
||||
() => fileBreadcrumbs(props.projectName, props.relativePath),
|
||||
[props.projectName, props.relativePath],
|
||||
);
|
||||
const updateFadeVisibility = useCallback(
|
||||
(metrics: Partial<(typeof scrollMetrics)["current"]>) => {
|
||||
Object.assign(scrollMetrics.current, metrics);
|
||||
const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
|
||||
const maxOffset = Math.max(0, contentWidth - viewportWidth);
|
||||
const next = {
|
||||
left: maxOffset > 1 && offsetX > 1,
|
||||
right: maxOffset > 1 && offsetX < maxOffset - 1,
|
||||
};
|
||||
|
||||
setFadeVisibility((current) =>
|
||||
current.left === next.left && current.right === next.right ? current : next,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="min-w-0 flex-1">
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
onContentSizeChange={(contentWidth) => {
|
||||
updateFadeVisibility({ contentWidth });
|
||||
}}
|
||||
onLayout={(event) => {
|
||||
updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
|
||||
}}
|
||||
onScroll={(event) => {
|
||||
updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
|
||||
}}
|
||||
scrollEventThrottle={16}
|
||||
>
|
||||
<View className="h-8 flex-row items-center">
|
||||
{breadcrumbs.map((crumb, index) => (
|
||||
<View key={crumb.path || "project"} className="flex-row items-center">
|
||||
{index > 0 ? (
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"max-w-[180px] px-1 text-xs",
|
||||
crumb.kind === "file"
|
||||
? "font-t3-bold text-foreground"
|
||||
: "font-t3-medium text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{crumb.label}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
{fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
|
||||
{fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FilePreviewHeader(props: {
|
||||
readonly activeMode: FileViewMode;
|
||||
readonly showModeSelector: boolean;
|
||||
readonly externalPreviewUri?: string | null;
|
||||
readonly projectName: string;
|
||||
readonly relativePath: string;
|
||||
readonly onSetMode: (mode: FileViewMode) => void;
|
||||
}) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
|
||||
return (
|
||||
<View className="border-b border-border bg-card px-3 py-2">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
|
||||
<CopyTextButton
|
||||
accessibilityLabel="Copy file path"
|
||||
text={props.relativePath}
|
||||
tintColor={iconColor}
|
||||
buttonSize={32}
|
||||
iconSize={13}
|
||||
/>
|
||||
</View>
|
||||
{props.showModeSelector ? (
|
||||
<View className="mt-2 flex-row items-center gap-2">
|
||||
<ModeButton
|
||||
active={props.activeMode === "preview"}
|
||||
icon="eye"
|
||||
label="Preview"
|
||||
onPress={() => props.onSetMode("preview")}
|
||||
/>
|
||||
<ModeButton
|
||||
active={props.activeMode === "source"}
|
||||
icon="doc.text"
|
||||
label="Source"
|
||||
onPress={() => props.onSetMode("source")}
|
||||
/>
|
||||
{props.externalPreviewUri !== undefined ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Open preview in Safari"
|
||||
disabled={props.externalPreviewUri === null}
|
||||
hitSlop={8}
|
||||
className={cn(
|
||||
"ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
|
||||
props.externalPreviewUri === null && "opacity-40",
|
||||
)}
|
||||
onPress={() => {
|
||||
if (typeof props.externalPreviewUri === "string") {
|
||||
void tryOpenExternalUrl(props.externalPreviewUri, "file-preview");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FileContent(props: {
|
||||
readonly activeMode: FileViewMode;
|
||||
readonly previewUri: string | null;
|
||||
@@ -270,6 +96,7 @@ function FileContent(props: {
|
||||
readonly relativePath: string;
|
||||
readonly initialLine: number | null;
|
||||
readonly truncated: boolean;
|
||||
readonly onRefresh?: () => Promise<void> | void;
|
||||
}) {
|
||||
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
|
||||
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
|
||||
@@ -293,7 +120,7 @@ function FileContent(props: {
|
||||
|
||||
if (props.fileError && props.fileContents === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-card px-6">
|
||||
<View className="flex-1 items-center justify-center bg-sheet px-6">
|
||||
<EmptyState title="File unavailable" detail={props.fileError} />
|
||||
</View>
|
||||
);
|
||||
@@ -301,7 +128,7 @@ function FileContent(props: {
|
||||
|
||||
if (props.fileContents === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
|
||||
<View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
|
||||
<ActivityIndicator />
|
||||
<Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
|
||||
</View>
|
||||
@@ -309,35 +136,47 @@ function FileContent(props: {
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-card">
|
||||
<View className="flex-1 bg-sheet">
|
||||
{props.truncated ? (
|
||||
<View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
|
||||
<Text className="text-2xs font-t3-bold uppercase text-amber-700 dark:text-amber-300">
|
||||
Partial file
|
||||
</Text>
|
||||
<Text className="text-xs leading-[17px] text-amber-800 dark:text-amber-200">
|
||||
<Text className="text-xs leading-snug text-amber-800 dark:text-amber-200">
|
||||
Preview limited to the first 1 MB of a truncated file.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{props.activeMode === "preview" && isMarkdown ? (
|
||||
<FileMarkdownPreview markdown={props.fileContents} />
|
||||
<FileMarkdownPreview markdown={props.fileContents} onRefresh={props.onRefresh} />
|
||||
) : (
|
||||
<SourceFileSurface
|
||||
contents={props.fileContents}
|
||||
path={props.relativePath}
|
||||
initialLine={props.initialLine}
|
||||
onRefresh={props.onRefresh}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function useThreadFilesWorkspace() {
|
||||
const params = useLocalSearchParams<{
|
||||
environmentId?: string | string[];
|
||||
threadId?: string | string[];
|
||||
}>();
|
||||
type ThreadFilesRouteScreenProps = StaticScreenProps<{
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
}>;
|
||||
|
||||
type ThreadFileRouteScreenProps = StaticScreenProps<{
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly path: string[];
|
||||
readonly line?: string;
|
||||
}>;
|
||||
|
||||
function useThreadFilesWorkspace(params: {
|
||||
readonly environmentId?: string | string[];
|
||||
readonly threadId?: string | string[];
|
||||
}) {
|
||||
const routeEnvironmentId = firstRouteParam(params.environmentId);
|
||||
const routeThreadId = firstRouteParam(params.threadId);
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
@@ -364,7 +203,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."
|
||||
@@ -373,40 +212,6 @@ function FilesUnavailable() {
|
||||
);
|
||||
}
|
||||
|
||||
function FilesHeaderTitle(props: { readonly projectName: string }) {
|
||||
const foregroundColor = String(useThemeColor("--color-foreground"));
|
||||
const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
|
||||
|
||||
return (
|
||||
<View style={{ alignItems: "center", maxWidth: 220 }}>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: foregroundColor,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: MOBILE_TYPOGRAPHY.headline.fontSize,
|
||||
fontWeight: "900",
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
Files
|
||||
</RNText>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: secondaryForegroundColor,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
fontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
fontWeight: "500",
|
||||
letterSpacing: 0.2,
|
||||
}}
|
||||
>
|
||||
{props.projectName}
|
||||
</RNText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FilesToolbarBottomFade() {
|
||||
const sheetColor = String(useThemeColor("--color-sheet"));
|
||||
|
||||
@@ -442,12 +247,20 @@ function FilesToolbarBottomFade() {
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadFilesTreeScreen() {
|
||||
const router = useRouter();
|
||||
export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
|
||||
useAdaptiveWorkspacePaneRole("inspector");
|
||||
const navigation = useNavigation();
|
||||
const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
|
||||
useAdaptiveWorkspaceLayout();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
|
||||
const colorScheme = useColorScheme();
|
||||
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
|
||||
props.route.params,
|
||||
);
|
||||
const revealedInspectorRef = useRef(false);
|
||||
const entriesQuery = useEnvironmentQuery(
|
||||
environmentId !== null && cwd !== null
|
||||
environmentId !== null && cwd !== null && !fileInspector.supported
|
||||
? projectEnvironment.listEntries({
|
||||
environmentId,
|
||||
input: { cwd },
|
||||
@@ -455,18 +268,87 @@ export function ThreadFilesTreeScreen() {
|
||||
: null,
|
||||
);
|
||||
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
|
||||
const handleReturnToThread = useCallback(() => {
|
||||
if (navigation.canGoBack()) {
|
||||
navigation.goBack();
|
||||
return;
|
||||
}
|
||||
if (environmentId !== null && threadId !== null) {
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
environmentId: String(environmentId),
|
||||
threadId: String(threadId),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}, [environmentId, navigation, threadId]);
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(path: string) => {
|
||||
if (environmentId === null || threadId === null) {
|
||||
return;
|
||||
}
|
||||
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
|
||||
const params = {
|
||||
environmentId: String(environmentId),
|
||||
threadId: String(threadId),
|
||||
path: path.split("/").filter((segment) => segment.length > 0),
|
||||
};
|
||||
const navigationAction = resolveFileSelectionNavigationAction({
|
||||
hasPersistentFileInspector: fileInspector.supported,
|
||||
});
|
||||
if (navigationAction === "replace") {
|
||||
navigation.dispatch(StackActions.replace("ThreadFile", params));
|
||||
return;
|
||||
}
|
||||
navigation.navigate("ThreadFile", params);
|
||||
},
|
||||
[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],
|
||||
);
|
||||
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}
|
||||
route={props.route}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
|
||||
}
|
||||
|
||||
@@ -474,62 +356,95 @@ export function ThreadFilesTreeScreen() {
|
||||
return <FilesUnavailable />;
|
||||
}
|
||||
|
||||
if (fileInspector.supported) {
|
||||
return (
|
||||
<ThreadRouteScreen
|
||||
onReturnToThread={handleReturnToThread}
|
||||
renderInspector={renderInspector}
|
||||
route={props.route}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
<>
|
||||
{/* Static header config (glass preset, title, contentStyle) lives in Stack.tsx.
|
||||
Only genuinely dynamic options are set here. */}
|
||||
<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("");
|
||||
},
|
||||
},
|
||||
unstable_headerSubtitle:
|
||||
Platform.OS === "ios" && projectName.length > 0 ? projectName : undefined,
|
||||
// No refresh button: the list already supports pull-to-refresh.
|
||||
unstable_headerToolbarItems: usesCompactMailToolbar
|
||||
? () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
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 ? 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}
|
||||
/>
|
||||
<FilesToolbarBottomFade />
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadFileScreen() {
|
||||
const params = useLocalSearchParams<{
|
||||
line?: string | string[];
|
||||
path?: string | string[];
|
||||
}>();
|
||||
export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
|
||||
useAdaptiveWorkspacePaneRole("inspector");
|
||||
const navigation = useNavigation();
|
||||
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const params = props.route.params;
|
||||
const relativePath = normalizeRoutePath(params.path);
|
||||
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace(
|
||||
props.route.params,
|
||||
);
|
||||
const [modeOverride, setModeOverride] = useState<{
|
||||
readonly path: string;
|
||||
readonly mode: FileViewMode;
|
||||
@@ -568,6 +483,43 @@ export function ThreadFileScreen() {
|
||||
);
|
||||
const fileData = fileQuery.data as ProjectReadFileResult | null;
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(path: string) => {
|
||||
navigation.navigate("ThreadFile", {
|
||||
environmentId: String(environmentId),
|
||||
threadId: String(threadId),
|
||||
path: path.split("/").filter(Boolean),
|
||||
});
|
||||
},
|
||||
[environmentId, navigation, threadId],
|
||||
);
|
||||
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],
|
||||
);
|
||||
// The workspace inspector column spans the full window height. On iOS the
|
||||
// pane brings its own nested native header; elsewhere it pads itself below
|
||||
// the top inset.
|
||||
const safeAreaInsets = useSafeAreaInsets();
|
||||
const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
|
||||
// Hand the file navigator to the workspace so it renders beside the
|
||||
// navigator, outside this screen's native header.
|
||||
const renderWorkspaceInspector = useCallback(
|
||||
() => renderInspector(inspectorHeaderInset),
|
||||
[inspectorHeaderInset, renderInspector],
|
||||
);
|
||||
useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
|
||||
|
||||
if (selectedThread === null || environmentId === null || threadId === null) {
|
||||
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
|
||||
}
|
||||
@@ -579,38 +531,104 @@ 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>
|
||||
);
|
||||
}
|
||||
|
||||
const parentDir = relativePath.split("/").slice(0, -1).join("/");
|
||||
const headerSubtitle = [projectName, parentDir].filter(Boolean).join(" · ");
|
||||
|
||||
return (
|
||||
<ReviewHighlighterProvider>
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen options={{ title: basename(relativePath) }} />
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="arrow.clockwise"
|
||||
onPress={() => {
|
||||
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
|
||||
setPreviewRevision((current) => current + 1);
|
||||
return;
|
||||
}
|
||||
fileQuery.refresh();
|
||||
}}
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
<FilePreviewHeader
|
||||
activeMode={resolvedActiveMode}
|
||||
showModeSelector={canPreview && !isImageFile}
|
||||
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
|
||||
projectName={projectName}
|
||||
relativePath={relativePath}
|
||||
onSetMode={(mode) => {
|
||||
setModeOverride({ path: relativePath, mode });
|
||||
<NativeStackScreenOptions
|
||||
options={{
|
||||
// Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS: solid
|
||||
// sheet-colored header — this route's content scrolls internally, so
|
||||
// there is nothing for glass to sample). Only dynamic values here.
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: basename(relativePath),
|
||||
title: basename(relativePath),
|
||||
unstable_headerSubtitle:
|
||||
Platform.OS === "ios" && headerSubtitle.length > 0 ? headerSubtitle : undefined,
|
||||
}}
|
||||
/>
|
||||
<WorkspaceSidebarToolbar>
|
||||
{fileInspector.supported ? (
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="Return to chat"
|
||||
icon="chevron.left"
|
||||
onPress={() => {
|
||||
navigation.dispatch(
|
||||
StackActions.replace("Thread", {
|
||||
environmentId: String(environmentId),
|
||||
threadId: String(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.Menu accessibilityLabel="File actions" icon="ellipsis">
|
||||
{canPreview && !isImageFile ? (
|
||||
<NativeHeaderToolbar.Menu inline>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="eye"
|
||||
isOn={resolvedActiveMode === "preview"}
|
||||
onPress={() => setModeOverride({ path: relativePath, mode: "preview" })}
|
||||
>
|
||||
Preview
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="doc.text"
|
||||
isOn={resolvedActiveMode === "source"}
|
||||
onPress={() => setModeOverride({ path: relativePath, mode: "source" })}
|
||||
>
|
||||
Source
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="doc.on.doc"
|
||||
onPress={() => copyTextWithHaptic(relativePath)}
|
||||
>
|
||||
Copy path
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{isBrowserFile && typeof assetPreviewUri === "string" ? (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="safari"
|
||||
onPress={() => {
|
||||
void tryOpenExternalUrl(assetPreviewUri, "file-preview");
|
||||
}}
|
||||
>
|
||||
Open in Safari
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
) : null}
|
||||
{resolvedActiveMode === "preview" && (isBrowserFile || isImageFile) ? (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
icon="arrow.clockwise"
|
||||
onPress={() => {
|
||||
setPreviewRevision((current) => current + 1);
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
) : null}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
</NativeHeaderToolbar>
|
||||
<FileContent
|
||||
activeMode={resolvedActiveMode}
|
||||
previewUri={previewUri}
|
||||
@@ -619,6 +637,7 @@ export function ThreadFileScreen() {
|
||||
initialLine={targetLine}
|
||||
relativePath={relativePath}
|
||||
truncated={fileData?.truncated ?? false}
|
||||
onRefresh={() => fileQuery.refresh()}
|
||||
/>
|
||||
</View>
|
||||
</ReviewHighlighterProvider>
|
||||
|
||||
@@ -24,7 +24,7 @@ export function WorkspaceFileWebPreview(props: { readonly uri: string | null })
|
||||
{loadError ? (
|
||||
<View className="border-b border-border bg-card px-4 py-2">
|
||||
<Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
|
||||
<Text className="mt-0.5 text-xs leading-[17px] text-foreground-muted">{loadError}</Text>
|
||||
<Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<WebView
|
||||
|
||||
@@ -3,26 +3,38 @@ import type {
|
||||
NativeReviewDiffStyle,
|
||||
NativeReviewDiffToken,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
|
||||
import { resolveMobileCodeSurface } from "../../lib/appearancePreferences";
|
||||
import { MOBILE_CODE_SURFACE, MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import type { SourceHighlightTokens } from "./sourceHighlightingState";
|
||||
|
||||
export const NATIVE_SOURCE_ROW_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
|
||||
export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
|
||||
|
||||
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
|
||||
rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
|
||||
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
|
||||
changeBarWidth: 0,
|
||||
gutterWidth: MOBILE_CODE_SURFACE.gutterWidth,
|
||||
codePadding: MOBILE_CODE_SURFACE.codePadding,
|
||||
textVerticalInset: MOBILE_CODE_SURFACE.textVerticalInset,
|
||||
codeFontSize: MOBILE_CODE_SURFACE.fontSize,
|
||||
codeFontWeight: "regular",
|
||||
lineNumberFontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
|
||||
lineNumberFontWeight: "regular",
|
||||
emptyStateFontSize: MOBILE_TYPOGRAPHY.label.fontSize,
|
||||
emptyStateFontWeight: "medium",
|
||||
};
|
||||
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = createNativeSourceStyle(
|
||||
resolveMobileCodeSurface(MOBILE_CODE_SURFACE.fontSize),
|
||||
);
|
||||
|
||||
export function createNativeSourceStyle(
|
||||
codeSurface: ResolvedMobileCodeSurface,
|
||||
): NativeReviewDiffStyle {
|
||||
return {
|
||||
rowHeight: codeSurface.rowHeight,
|
||||
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
|
||||
changeBarWidth: 0,
|
||||
gutterWidth: codeSurface.gutterWidth,
|
||||
codePadding: codeSurface.codePadding,
|
||||
textVerticalInset: codeSurface.textVerticalInset,
|
||||
codeFontSize: codeSurface.fontSize,
|
||||
codeFontWeight: "regular",
|
||||
lineNumberFontSize: codeSurface.lineNumberFontSize,
|
||||
lineNumberFontWeight: "regular",
|
||||
emptyStateFontSize: Math.round(
|
||||
MOBILE_TYPOGRAPHY.label.fontSize * (codeSurface.fontSize / MOBILE_CODE_SURFACE.fontSize),
|
||||
),
|
||||
emptyStateFontWeight: "medium",
|
||||
};
|
||||
}
|
||||
|
||||
const SOURCE_FILE_ID = "source-file";
|
||||
|
||||
|
||||
@@ -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 "../../native/StackHeader";
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -3,60 +3,30 @@ import type {
|
||||
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 { Stack } from "expo-router";
|
||||
import { Text as RNText, View } from "react-native";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform } from "react-native";
|
||||
import type { SearchBarCommands } from "react-native-screens";
|
||||
|
||||
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
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 +42,170 @@ 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,
|
||||
// Static header config (glass, title, fonts) lives in Stack.tsx
|
||||
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
hideNavigationBar: false,
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
allowToolbarIntegration: true,
|
||||
},
|
||||
unstable_headerRightItems:
|
||||
Platform.OS === "ios"
|
||||
? () => [
|
||||
withNativeGlassHeaderItem({
|
||||
accessibilityLabel: "Open settings",
|
||||
icon: { name: "ellipsis", type: "sfSymbol" } as const,
|
||||
identifier: "home-settings",
|
||||
label: "",
|
||||
onPress: props.onOpenSettings,
|
||||
type: "button",
|
||||
}),
|
||||
]
|
||||
: 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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export function HomeRouteScreen() {
|
||||
const { layout } = useAdaptiveWorkspaceLayout();
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(
|
||||
Order.String,
|
||||
(environment: { readonly label: string }) => environment.label,
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const availableEnvironmentIds = useMemo(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
);
|
||||
const {
|
||||
options: listOptions,
|
||||
setSelectedEnvironmentId,
|
||||
setProjectGroupingMode,
|
||||
setProjectSortOrder,
|
||||
setThreadSortOrder,
|
||||
} = useHomeListOptions(availableEnvironmentIds);
|
||||
const selectedEnvironmentId = listOptions.selectedEnvironmentId;
|
||||
|
||||
// In split layouts the persistent sidebar IS the thread list — Home becomes
|
||||
// an empty detail pane so selecting a thread never transitions layouts.
|
||||
if (layout.usesSplitView) {
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ title: "", headerTitle: "" }} />
|
||||
<WorkspaceSidebarToolbar
|
||||
afterSidebarButton={
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="New task"
|
||||
icon="square.and.pencil"
|
||||
onPress={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<WorkspaceEmptyDetail
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Restore the compact title in case the split branch blanked it. */}
|
||||
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
/>
|
||||
|
||||
<HomeScreen
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
}}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
onNewThreadInProject={(project) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(project.environmentId),
|
||||
projectId: String(project.id),
|
||||
title: project.title,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
pendingTasks={pendingTasks}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
LegendList,
|
||||
type LegendListRef,
|
||||
type LegendListRenderItemProps,
|
||||
} from "@legendapp/list/react-native";
|
||||
import {
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
@@ -7,101 +12,74 @@ 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 Animated, {
|
||||
Easing,
|
||||
LinearTransition,
|
||||
type ExitAnimationsValues,
|
||||
withDelay,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { ActivityIndicator, Platform, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { threadStatusTone } from "../threads/threadPresentation";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "./thread-swipe-actions";
|
||||
PendingTaskListRow,
|
||||
ThreadListGroupHeader,
|
||||
ThreadListRow,
|
||||
ThreadListShowMoreRow,
|
||||
} from "../threads/thread-list-items";
|
||||
import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
|
||||
import {
|
||||
buildHomeListLayout,
|
||||
DEFAULT_GROUP_DISPLAY_STATE,
|
||||
homeListItemsAreEqual,
|
||||
nextGroupDisplayState,
|
||||
type HomeGroupDisplayAction,
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
|
||||
/* ─── Types ──────────────────────────────────────────────────────────── */
|
||||
|
||||
interface HomeScreenProps {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
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;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
}
|
||||
|
||||
/* ─── Status indicator colors ────────────────────────────────────────── */
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
||||
switch (thread.session?.status) {
|
||||
case "running":
|
||||
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
|
||||
case "ready":
|
||||
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
|
||||
case "starting":
|
||||
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
|
||||
case "error":
|
||||
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
|
||||
default:
|
||||
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
|
||||
}
|
||||
}
|
||||
|
||||
const COLLAPSED_THREAD_LIMIT = 6;
|
||||
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
|
||||
|
||||
function threadRowExit(values: ExitAnimationsValues) {
|
||||
"worklet";
|
||||
|
||||
return {
|
||||
initialValues: {
|
||||
height: values.currentHeight,
|
||||
opacity: 1,
|
||||
originX: values.currentOriginX,
|
||||
},
|
||||
animations: {
|
||||
height: withDelay(
|
||||
90,
|
||||
withTiming(0, {
|
||||
duration: 170,
|
||||
easing: Easing.inOut(Easing.cubic),
|
||||
}),
|
||||
),
|
||||
opacity: withDelay(80, withTiming(0, { duration: 100 })),
|
||||
originX: withTiming(values.currentOriginX - values.windowWidth, {
|
||||
duration: 190,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
/** Height of the floating custom header on non-iOS platforms. */
|
||||
const CUSTOM_HEADER_HEIGHT = 78;
|
||||
|
||||
function deriveEmptyState(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
@@ -166,287 +144,28 @@ function deriveEmptyState(props: {
|
||||
};
|
||||
}
|
||||
|
||||
/* ─── Project group header ───────────────────────────────────────────── */
|
||||
|
||||
function ProjectGroupLabel(props: {
|
||||
readonly project: EnvironmentProject;
|
||||
readonly title: string;
|
||||
readonly totalThreadCount: number;
|
||||
readonly isExpanded: boolean;
|
||||
readonly onToggleExpand: () => void;
|
||||
}) {
|
||||
const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
|
||||
|
||||
return (
|
||||
<View className="flex-row items-center gap-2.5 px-1 pb-2">
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
size={18}
|
||||
projectTitle={props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
<Text
|
||||
className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
|
||||
style={{ letterSpacing: 0.5 }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.title}
|
||||
</Text>
|
||||
|
||||
{hiddenCount > 0 ? (
|
||||
<Pressable onPress={props.onToggleExpand} hitSlop={8}>
|
||||
<Text
|
||||
className="text-xs font-t3-medium text-foreground-muted"
|
||||
style={{ letterSpacing: 0.4 }}
|
||||
>
|
||||
{props.isExpanded ? "Show less" : `${hiddenCount} more`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Thread row ─────────────────────────────────────────────────────── */
|
||||
|
||||
function ThreadRow(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly onPress: () => void;
|
||||
readonly onArchive: () => void;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
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 { bg, fg } = statusColors(props.thread);
|
||||
const tone = threadStatusTone(props.thread);
|
||||
const timestamp = relativeTime(
|
||||
props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
|
||||
);
|
||||
const branch = props.thread.branch;
|
||||
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);
|
||||
}
|
||||
}}
|
||||
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}
|
||||
>
|
||||
<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,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderRadius: 9,
|
||||
backgroundColor: bg,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 2,
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
|
||||
{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-2xs text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitleParts.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
</ReanimatedSwipeable>
|
||||
);
|
||||
function HomeTopContentSpacer(props: { readonly topInset: number }) {
|
||||
return <View style={{ height: props.topInset + CUSTOM_HEADER_HEIGHT }} />;
|
||||
}
|
||||
|
||||
/* ─── 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 [groupDisplayStates, setGroupDisplayStates] = useState<
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
const toggleExpanded = useCallback((key: string) => {
|
||||
setExpandedProjects((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
|
||||
setGroupDisplayStates((previous) => {
|
||||
const next = new Map(previous);
|
||||
next.set(
|
||||
key,
|
||||
nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
|
||||
);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
@@ -464,11 +183,19 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
openSwipeableRef.current?.close();
|
||||
}, []);
|
||||
const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
|
||||
onScrollBeginDrag: handleScrollBeginDrag,
|
||||
});
|
||||
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects: props.projects,
|
||||
threads: props.threads,
|
||||
pendingTasks: props.pendingTasks,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
@@ -476,6 +203,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
props.pendingTasks,
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
@@ -486,135 +214,241 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
],
|
||||
);
|
||||
|
||||
const hasSearchQuery = props.searchQuery.trim().length > 0;
|
||||
const listLayout = useMemo(
|
||||
() =>
|
||||
buildHomeListLayout({
|
||||
groups: projectGroups,
|
||||
displayStates: groupDisplayStates,
|
||||
showAllThreads: hasSearchQuery,
|
||||
}),
|
||||
[projectGroups, groupDisplayStates, hasSearchQuery],
|
||||
);
|
||||
|
||||
const projectCwdByKey = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
for (const project of props.projects) {
|
||||
map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
|
||||
}
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const extraData = useMemo(
|
||||
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
|
||||
[props.savedConnectionsById, projectCwdByKey],
|
||||
);
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item }: LegendListRenderItemProps<HomeListItem>) => {
|
||||
switch (item.type) {
|
||||
case "header":
|
||||
return (
|
||||
<ThreadListGroupHeader
|
||||
variant="compact"
|
||||
collapsed={item.collapsed}
|
||||
isFirst={item.isFirst}
|
||||
groupKey={item.group.key}
|
||||
onGroupAction={updateGroupDisplay}
|
||||
// Aggregated groups (same repo across machines) have no single
|
||||
// target project, and `pending-project:` groups hold a placeholder
|
||||
// built from queued-task metadata rather than a real project shell,
|
||||
// so the quick new-thread button is single-real-project only.
|
||||
newThreadTarget={item.group.newThreadTarget}
|
||||
onNewThread={props.onNewThreadInProject}
|
||||
project={item.group.representative}
|
||||
threadCount={item.group.threads.length + item.group.pendingTasks.length}
|
||||
title={item.group.title}
|
||||
/>
|
||||
);
|
||||
case "pending-task":
|
||||
return (
|
||||
<PendingTaskListRow
|
||||
variant="compact"
|
||||
pendingTask={item.pendingTask}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[item.pendingTask.message.environmentId]
|
||||
?.environmentLabel ?? null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
);
|
||||
case "thread": {
|
||||
const thread = item.thread;
|
||||
return (
|
||||
<ThreadListRow
|
||||
variant="compact"
|
||||
thread={thread}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
|
||||
null
|
||||
}
|
||||
isLast={item.isLast}
|
||||
onArchiveThread={props.onArchiveThread}
|
||||
onDeleteThread={props.onDeleteThread}
|
||||
onSelectThread={props.onSelectThread}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "show-more":
|
||||
return (
|
||||
<ThreadListShowMoreRow
|
||||
variant="compact"
|
||||
hiddenCount={item.hiddenCount}
|
||||
canShowLess={item.canShowLess}
|
||||
groupKey={item.groupKey}
|
||||
onGroupAction={updateGroupDisplay}
|
||||
/>
|
||||
);
|
||||
}
|
||||
},
|
||||
[
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
props.onDeletePendingTask,
|
||||
props.onDeleteThread,
|
||||
props.onNewThreadInProject,
|
||||
props.onSelectPendingTask,
|
||||
props.onSelectThread,
|
||||
props.savedConnectionsById,
|
||||
updateGroupDisplay,
|
||||
],
|
||||
);
|
||||
|
||||
const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
|
||||
|
||||
/* Empty states */
|
||||
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
|
||||
const hasAnyThreads =
|
||||
props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
|
||||
const hasResults = projectGroups.length > 0;
|
||||
const selectedEnvironmentLabel =
|
||||
props.selectedEnvironmentId === null
|
||||
? null
|
||||
: (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,
|
||||
});
|
||||
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 (
|
||||
<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,
|
||||
if (!hasAnyThreads) {
|
||||
return (
|
||||
<View
|
||||
className="flex-1 items-center justify-center bg-screen px-8"
|
||||
style={{
|
||||
paddingBottom: Math.max(insets.bottom, 24),
|
||||
paddingTop: Platform.OS === "ios" ? insets.top + 72 : insets.top,
|
||||
}}
|
||||
>
|
||||
{!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 ? (
|
||||
<View className="w-full max-w-[430px]">
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
detail="Choose another environment or create a new task."
|
||||
title={emptyState.title}
|
||||
detail={emptyState.detail}
|
||||
actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
) : !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);
|
||||
{emptyState.loading ? (
|
||||
<View className="mt-4 items-center">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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}
|
||||
const listHeader = (
|
||||
<>
|
||||
{Platform.OS === "ios" ? null : <HomeTopContentSpacer topInset={insets.top} />}
|
||||
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View style={{ paddingBottom: 16 }}>
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
detail="Choose another environment or create a new task."
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
)
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
|
||||
implementation mispositions pinned headers at mount under iOS
|
||||
automatic content insets (headers render one nav-inset too low until
|
||||
the first scroll event) and blanks non-pinned headers after
|
||||
collapse/expand data changes. The flattened layout still exposes
|
||||
`stickyHeaderIndices` if this gets revisited. */}
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<LegendList
|
||||
ref={listRef}
|
||||
data={listLayout.items}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={keyExtractor}
|
||||
itemsAreEqual={homeListItemsAreEqual}
|
||||
drawDistance={500}
|
||||
estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
|
||||
extraData={extraData}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={listEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
recycleItems
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom: Platform.OS === "ios" ? Math.max(insets.bottom, 24) + 24 : 24,
|
||||
}}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios"
|
||||
? {
|
||||
bottom: Math.max(insets.bottom, 16) + 24,
|
||||
top: 0,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildHomeListLayout,
|
||||
DEFAULT_GROUP_DISPLAY_STATE,
|
||||
HOME_INITIAL_VISIBLE_THREADS,
|
||||
HOME_SHOW_MORE_STEP,
|
||||
nextGroupDisplayState,
|
||||
type HomeGroupDisplayState,
|
||||
type HomeListItem,
|
||||
} from "./homeListItems";
|
||||
import type { HomeThreadGroup } from "./homeThreadList";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeProject(id: string, title: string): EnvironmentProject {
|
||||
return {
|
||||
environmentId,
|
||||
id: ProjectId.make(id),
|
||||
title,
|
||||
workspaceRoot: `/workspaces/${id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
id: ThreadId.make(id),
|
||||
projectId,
|
||||
title: `Thread ${id}`,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
}
|
||||
|
||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||
const project = makeProject(key, key);
|
||||
const threads = Array.from({ length: threadCount }, (_, index) =>
|
||||
makeThread(`${key}-thread-${index}`, project.id),
|
||||
);
|
||||
return {
|
||||
key,
|
||||
title: key,
|
||||
representative: project,
|
||||
projects: [project],
|
||||
pendingTasks: [],
|
||||
threads,
|
||||
// All threads inside the recency window, so the baseline stays at the
|
||||
// initial page size and the pagination expectations below hold.
|
||||
recentThreads: threads,
|
||||
newThreadTarget: project,
|
||||
};
|
||||
}
|
||||
|
||||
function itemTypes(items: ReadonlyArray<HomeListItem>): string[] {
|
||||
return items.map((item) => item.type);
|
||||
}
|
||||
|
||||
function displayStates(
|
||||
entries: Record<string, HomeGroupDisplayState>,
|
||||
): ReadonlyMap<string, HomeGroupDisplayState> {
|
||||
return new Map(Object.entries(entries));
|
||||
}
|
||||
|
||||
describe("buildHomeListLayout", () => {
|
||||
it("renders a header plus all threads for a small group without a show-more row", () => {
|
||||
const layout = buildHomeListLayout({
|
||||
groups: [makeGroup("alpha", 3)],
|
||||
displayStates: displayStates({}),
|
||||
});
|
||||
|
||||
expect(itemTypes(layout.items)).toEqual(["header", "thread", "thread", "thread"]);
|
||||
expect(layout.stickyHeaderIndices).toEqual([0]);
|
||||
expect(layout.items.at(-1)).toMatchObject({ type: "thread", isLast: true });
|
||||
});
|
||||
|
||||
it("limits large groups to the initial visible count with a show-more row", () => {
|
||||
const layout = buildHomeListLayout({
|
||||
groups: [makeGroup("alpha", 133)],
|
||||
displayStates: displayStates({}),
|
||||
});
|
||||
|
||||
const threadItems = layout.items.filter((item) => item.type === "thread");
|
||||
expect(threadItems).toHaveLength(HOME_INITIAL_VISIBLE_THREADS);
|
||||
expect(layout.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
groupKey: "alpha",
|
||||
hiddenCount: 133 - HOME_INITIAL_VISIBLE_THREADS,
|
||||
canShowLess: false,
|
||||
});
|
||||
// The show-more row takes over the last slot, so no thread is marked last.
|
||||
expect(threadItems.every((item) => item.type === "thread" && !item.isLast)).toBe(true);
|
||||
});
|
||||
|
||||
it("reveals more threads per show-more step and offers show-less when exhausted", () => {
|
||||
const group = makeGroup("alpha", 20);
|
||||
|
||||
const expandedOnce = buildHomeListLayout({
|
||||
groups: [group],
|
||||
displayStates: displayStates({
|
||||
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
|
||||
}),
|
||||
});
|
||||
expect(expandedOnce.items.filter((item) => item.type === "thread")).toHaveLength(
|
||||
HOME_INITIAL_VISIBLE_THREADS + HOME_SHOW_MORE_STEP,
|
||||
);
|
||||
expect(expandedOnce.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
hiddenCount: 4,
|
||||
canShowLess: true,
|
||||
});
|
||||
|
||||
const fullyExpanded = buildHomeListLayout({
|
||||
groups: [group],
|
||||
displayStates: displayStates({
|
||||
alpha: nextGroupDisplayState(
|
||||
nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
|
||||
"show-more",
|
||||
),
|
||||
}),
|
||||
});
|
||||
expect(fullyExpanded.items.filter((item) => item.type === "thread")).toHaveLength(20);
|
||||
expect(fullyExpanded.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
hiddenCount: 0,
|
||||
canShowLess: true,
|
||||
});
|
||||
|
||||
const reset = nextGroupDisplayState(
|
||||
nextGroupDisplayState(
|
||||
nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
|
||||
"show-more",
|
||||
),
|
||||
"show-less",
|
||||
);
|
||||
expect(reset.visibleCount).toBe(HOME_INITIAL_VISIBLE_THREADS);
|
||||
});
|
||||
|
||||
it("offers show-less after expanding a stale group whose baseline is below the page size", () => {
|
||||
// Stale project: 10 threads total but only 3 within the recency window.
|
||||
const project = makeProject("stale", "stale");
|
||||
const threads = Array.from({ length: 10 }, (_, index) =>
|
||||
makeThread(`stale-thread-${index}`, project.id),
|
||||
);
|
||||
const group: HomeThreadGroup = {
|
||||
key: "stale",
|
||||
title: "stale",
|
||||
representative: project,
|
||||
projects: [project],
|
||||
pendingTasks: [],
|
||||
threads,
|
||||
recentThreads: threads.slice(0, 3),
|
||||
newThreadTarget: project,
|
||||
};
|
||||
|
||||
const collapsedToRecent = buildHomeListLayout({
|
||||
groups: [group],
|
||||
displayStates: displayStates({}),
|
||||
});
|
||||
expect(collapsedToRecent.items.filter((item) => item.type === "thread")).toHaveLength(3);
|
||||
expect(collapsedToRecent.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
hiddenCount: 7,
|
||||
canShowLess: false,
|
||||
});
|
||||
|
||||
const expanded = buildHomeListLayout({
|
||||
groups: [group],
|
||||
displayStates: displayStates({
|
||||
stale: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "show-more"),
|
||||
}),
|
||||
});
|
||||
expect(expanded.items.filter((item) => item.type === "thread")).toHaveLength(10);
|
||||
expect(expanded.items.at(-1)).toMatchObject({
|
||||
type: "show-more",
|
||||
hiddenCount: 0,
|
||||
canShowLess: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("hides threads and the show-more row for collapsed groups", () => {
|
||||
const layout = buildHomeListLayout({
|
||||
groups: [makeGroup("alpha", 12), makeGroup("beta", 2)],
|
||||
displayStates: displayStates({
|
||||
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"),
|
||||
}),
|
||||
});
|
||||
|
||||
expect(itemTypes(layout.items)).toEqual(["header", "header", "thread", "thread"]);
|
||||
expect(layout.items[0]).toMatchObject({ type: "header", collapsed: true, isFirst: true });
|
||||
expect(layout.items[1]).toMatchObject({ type: "header", collapsed: false, isFirst: false });
|
||||
expect(layout.stickyHeaderIndices).toEqual([0, 1]);
|
||||
});
|
||||
|
||||
it("suspends collapse and pagination while searching", () => {
|
||||
const layout = buildHomeListLayout({
|
||||
groups: [makeGroup("alpha", 12)],
|
||||
displayStates: displayStates({
|
||||
alpha: nextGroupDisplayState(DEFAULT_GROUP_DISPLAY_STATE, "toggle-collapsed"),
|
||||
}),
|
||||
showAllThreads: true,
|
||||
});
|
||||
|
||||
expect(layout.items.filter((item) => item.type === "thread")).toHaveLength(12);
|
||||
expect(layout.items.some((item) => item.type === "show-more")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps sticky indices aligned across multiple expanded groups", () => {
|
||||
const layout = buildHomeListLayout({
|
||||
groups: [makeGroup("alpha", 8), makeGroup("beta", 1)],
|
||||
displayStates: displayStates({}),
|
||||
});
|
||||
|
||||
// header + 6 threads + show-more = 8 items, so beta's header is index 8.
|
||||
expect(layout.stickyHeaderIndices).toEqual([0, 8]);
|
||||
expect(layout.items[8]).toMatchObject({ type: "header", isFirst: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import type { HomeThreadGroup } from "./homeThreadList";
|
||||
|
||||
/** Threads shown per project before the "Show more" affordance appears. */
|
||||
export const HOME_INITIAL_VISIBLE_THREADS = 6;
|
||||
/** Additional threads revealed per "Show more" tap. */
|
||||
export const HOME_SHOW_MORE_STEP = 10;
|
||||
|
||||
export interface HomeGroupDisplayState {
|
||||
readonly collapsed: boolean;
|
||||
/** How many threads are currently revealed (clamped to the group size). */
|
||||
readonly visibleCount: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_GROUP_DISPLAY_STATE: HomeGroupDisplayState = {
|
||||
collapsed: false,
|
||||
visibleCount: HOME_INITIAL_VISIBLE_THREADS,
|
||||
};
|
||||
|
||||
export interface HomeHeaderListItem {
|
||||
readonly type: "header";
|
||||
readonly key: string;
|
||||
readonly group: HomeThreadGroup;
|
||||
readonly collapsed: boolean;
|
||||
readonly isFirst: boolean;
|
||||
}
|
||||
|
||||
export interface HomeThreadListItem {
|
||||
readonly type: "thread";
|
||||
readonly key: string;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface HomePendingTaskListItem {
|
||||
readonly type: "pending-task";
|
||||
readonly key: string;
|
||||
readonly pendingTask: PendingNewTask;
|
||||
readonly isLast: boolean;
|
||||
}
|
||||
|
||||
export interface HomeShowMoreListItem {
|
||||
readonly type: "show-more";
|
||||
readonly key: string;
|
||||
readonly groupKey: string;
|
||||
/** Threads still hidden. 0 means the group is fully expanded. */
|
||||
readonly hiddenCount: number;
|
||||
/** Whether more than the initial count is revealed, so "Show less" applies. */
|
||||
readonly canShowLess: boolean;
|
||||
}
|
||||
|
||||
export type HomeListItem =
|
||||
| HomeHeaderListItem
|
||||
| HomePendingTaskListItem
|
||||
| HomeThreadListItem
|
||||
| HomeShowMoreListItem;
|
||||
|
||||
export interface HomeListLayout {
|
||||
readonly items: ReadonlyArray<HomeListItem>;
|
||||
readonly stickyHeaderIndices: ReadonlyArray<number>;
|
||||
}
|
||||
|
||||
export type HomeGroupDisplayAction = "toggle-collapsed" | "show-more" | "show-less";
|
||||
|
||||
export function nextGroupDisplayState(
|
||||
current: HomeGroupDisplayState,
|
||||
action: HomeGroupDisplayAction,
|
||||
): HomeGroupDisplayState {
|
||||
switch (action) {
|
||||
case "toggle-collapsed":
|
||||
return { ...current, collapsed: !current.collapsed };
|
||||
case "show-more":
|
||||
return { ...current, visibleCount: current.visibleCount + HOME_SHOW_MORE_STEP };
|
||||
case "show-less":
|
||||
return { ...current, visibleCount: HOME_INITIAL_VISIBLE_THREADS };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural equality for list items. Item objects are rebuilt on every
|
||||
* collapse/show-more toggle; without this the lists would consider every
|
||||
* mounted row changed and re-render all of them (each carrying a swipeable +
|
||||
* a vcs-status subscription). Group/thread references are stable across
|
||||
* toggles.
|
||||
*/
|
||||
export function homeListItemsAreEqual(previous: HomeListItem, item: HomeListItem): boolean {
|
||||
switch (item.type) {
|
||||
case "header":
|
||||
return (
|
||||
previous.type === "header" &&
|
||||
previous.group === item.group &&
|
||||
previous.collapsed === item.collapsed &&
|
||||
previous.isFirst === item.isFirst
|
||||
);
|
||||
case "pending-task":
|
||||
return (
|
||||
previous.type === "pending-task" &&
|
||||
previous.pendingTask === item.pendingTask &&
|
||||
previous.isLast === item.isLast
|
||||
);
|
||||
case "thread":
|
||||
return (
|
||||
previous.type === "thread" &&
|
||||
previous.thread === item.thread &&
|
||||
previous.isLast === item.isLast
|
||||
);
|
||||
case "show-more":
|
||||
return (
|
||||
previous.type === "show-more" &&
|
||||
previous.groupKey === item.groupKey &&
|
||||
previous.hiddenCount === item.hiddenCount &&
|
||||
previous.canShowLess === item.canShowLess
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function buildHomeListLayout(input: {
|
||||
readonly groups: ReadonlyArray<HomeThreadGroup>;
|
||||
readonly displayStates: ReadonlyMap<string, HomeGroupDisplayState>;
|
||||
/**
|
||||
* When searching, pagination is suspended so every match stays visible.
|
||||
*/
|
||||
readonly showAllThreads?: boolean;
|
||||
}): HomeListLayout {
|
||||
const items: HomeListItem[] = [];
|
||||
const stickyHeaderIndices: number[] = [];
|
||||
|
||||
for (const [groupIndex, group] of input.groups.entries()) {
|
||||
const display = input.displayStates.get(group.key) ?? DEFAULT_GROUP_DISPLAY_STATE;
|
||||
const collapsed = display.collapsed && input.showAllThreads !== true;
|
||||
|
||||
stickyHeaderIndices.push(items.length);
|
||||
items.push({
|
||||
type: "header",
|
||||
key: `header:${group.key}`,
|
||||
group,
|
||||
collapsed,
|
||||
isFirst: groupIndex === 0,
|
||||
});
|
||||
|
||||
if (collapsed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const totalCount = group.threads.length;
|
||||
// Default to the group's recent-activity window (last few days, or a small
|
||||
// fallback for stale projects), capped at the initial page size. Until the
|
||||
// user taps "Show more", older threads stay hidden to save vertical space;
|
||||
// "Show less" resets visibleCount to the initial constant, which lands back
|
||||
// here at the recency baseline.
|
||||
const baselineCount = Math.min(
|
||||
group.recentThreads.length,
|
||||
HOME_INITIAL_VISIBLE_THREADS,
|
||||
totalCount,
|
||||
);
|
||||
const visibleCount = input.showAllThreads
|
||||
? totalCount
|
||||
: Math.min(
|
||||
display.visibleCount > HOME_INITIAL_VISIBLE_THREADS
|
||||
? display.visibleCount
|
||||
: baselineCount,
|
||||
totalCount,
|
||||
);
|
||||
const visibleThreads = group.threads.slice(0, visibleCount);
|
||||
const hiddenCount = totalCount - visibleCount;
|
||||
const hasShowMoreRow = !input.showAllThreads && totalCount > baselineCount;
|
||||
|
||||
// Pending (unsent) tasks lead the group and are never paginated away.
|
||||
for (const [pendingIndex, pendingTask] of group.pendingTasks.entries()) {
|
||||
items.push({
|
||||
type: "pending-task",
|
||||
key: `pending-task:${pendingTask.message.messageId}`,
|
||||
pendingTask,
|
||||
isLast:
|
||||
pendingIndex === group.pendingTasks.length - 1 &&
|
||||
visibleThreads.length === 0 &&
|
||||
!hasShowMoreRow,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [threadIndex, thread] of visibleThreads.entries()) {
|
||||
items.push({
|
||||
type: "thread",
|
||||
key: `thread:${thread.environmentId}:${thread.id}`,
|
||||
thread,
|
||||
isLast: threadIndex === visibleThreads.length - 1 && !hasShowMoreRow,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasShowMoreRow) {
|
||||
items.push({
|
||||
type: "show-more",
|
||||
key: `show-more:${group.key}`,
|
||||
groupKey: group.key,
|
||||
hiddenCount,
|
||||
// Compare against the group's own baseline, not the global page size:
|
||||
// stale projects start below HOME_INITIAL_VISIBLE_THREADS, and "Show
|
||||
// less" must be offered as soon as anything beyond the baseline shows.
|
||||
canShowLess: visibleCount > baselineCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { items, stickyHeaderIndices };
|
||||
}
|
||||
@@ -44,6 +44,8 @@ function makeThread(
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
function buildGroups(
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
threads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
@@ -57,6 +59,7 @@ function buildGroups(
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
projectGroupingMode: "repository",
|
||||
now: NOW,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
@@ -220,4 +223,144 @@ describe("buildHomeThreadGroups", () => {
|
||||
);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("default view shows only threads from the last 5 days", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("recent-1"),
|
||||
projectId: project.id,
|
||||
title: "Today",
|
||||
updatedAt: "2026-06-28T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("recent-2"),
|
||||
projectId: project.id,
|
||||
title: "Within window",
|
||||
updatedAt: "2026-06-25T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("old"),
|
||||
projectId: project.id,
|
||||
title: "Two weeks ago",
|
||||
updatedAt: "2026-06-14T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const group = buildGroups([project], threads)[0];
|
||||
// Default view trims to recent threads...
|
||||
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2"]);
|
||||
// ...while full history stays available for the expanded view.
|
||||
expect(group?.threads.map((thread) => thread.id)).toEqual(["recent-1", "recent-2", "old"]);
|
||||
});
|
||||
|
||||
it("falls back to the most recent 3 threads when none are within 5 days", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
|
||||
(day, index) =>
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make(`thread-${index}`),
|
||||
projectId: project.id,
|
||||
title: `Thread ${index}`,
|
||||
updatedAt: `${day}T00:00:00.000Z`,
|
||||
}),
|
||||
);
|
||||
|
||||
const group = buildGroups([project], threads)[0];
|
||||
expect(group?.recentThreads.map((thread) => thread.id)).toEqual([
|
||||
"thread-4",
|
||||
"thread-3",
|
||||
"thread-2",
|
||||
]);
|
||||
expect(group?.threads).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("does not apply the recency window while searching", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = ["2026-06-01", "2026-06-02", "2026-06-03", "2026-06-04", "2026-06-05"].map(
|
||||
(day, index) =>
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make(`thread-${index}`),
|
||||
projectId: project.id,
|
||||
title: `Thread ${index}`,
|
||||
updatedAt: `${day}T00:00:00.000Z`,
|
||||
}),
|
||||
);
|
||||
|
||||
const group = buildGroups([project], threads, { searchQuery: "T3 Code" })[0];
|
||||
// Search reaches the full history rather than the 3-thread fallback.
|
||||
expect(group?.recentThreads).toHaveLength(5);
|
||||
expect(group?.recentThreads.map((thread) => thread.id)).toEqual(
|
||||
group?.threads.map((thread) => thread.id),
|
||||
);
|
||||
});
|
||||
|
||||
it("targets quick new threads at the group member with the newest thread", () => {
|
||||
const laptopEnv = EnvironmentId.make("environment-laptop");
|
||||
const desktopEnv = EnvironmentId.make("environment-desktop");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
const laptopProject = makeProject({
|
||||
environmentId: laptopEnv,
|
||||
id: ProjectId.make("project-laptop"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const desktopProject = makeProject({
|
||||
environmentId: desktopEnv,
|
||||
id: ProjectId.make("project-desktop"),
|
||||
title: "t3code",
|
||||
repositoryIdentity,
|
||||
});
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId: laptopEnv,
|
||||
id: ThreadId.make("thread-laptop"),
|
||||
projectId: laptopProject.id,
|
||||
title: "Older laptop thread",
|
||||
updatedAt: "2026-06-27T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId: desktopEnv,
|
||||
id: ThreadId.make("thread-desktop"),
|
||||
projectId: desktopProject.id,
|
||||
title: "Newest desktop thread",
|
||||
updatedAt: "2026-06-28T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
// Aggregated into one group by repository; the quick new-thread target
|
||||
// must follow the newest thread (desktop), not the arbitrary first member.
|
||||
const groups = buildGroups([laptopProject, desktopProject], threads);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.projects).toHaveLength(2);
|
||||
expect(groups[0]?.newThreadTarget?.environmentId).toBe(desktopEnv);
|
||||
expect(groups[0]?.newThreadTarget?.id).toBe(desktopProject.id);
|
||||
});
|
||||
});
|
||||
@@ -14,42 +14,92 @@ import type {
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
/**
|
||||
* Default home view only surfaces threads active within this window, to keep the
|
||||
* screen compact while keeping recent work visible.
|
||||
*/
|
||||
const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
|
||||
/** Fallback when a project has no threads inside the recency window. */
|
||||
const RECENT_THREAD_FALLBACK_COUNT = 3;
|
||||
|
||||
export interface HomeThreadGroup {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly pendingTasks: ReadonlyArray<PendingNewTask>;
|
||||
/** Full sorted thread history for the group (revealed when expanded / searching). */
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
/** Subset shown by default: threads from the last few days, or the most recent few. */
|
||||
readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
/**
|
||||
* Where a quick "new thread in this project" should land. For aggregated
|
||||
* groups (same repo on several machines) this is the member that owns the
|
||||
* group's most recent thread — the machine the user last worked on — rather
|
||||
* than the arbitrary first member; the draft's computer picker covers
|
||||
* switching from there. Null only for synthetic pending-project groups,
|
||||
* whose single "project" is a placeholder built from queued-task metadata.
|
||||
*/
|
||||
readonly newThreadTarget: EnvironmentProject | null;
|
||||
}
|
||||
|
||||
interface MutableHomeThreadGroup {
|
||||
readonly key: string;
|
||||
readonly projects: EnvironmentProject[];
|
||||
readonly pendingTasks: PendingNewTask[];
|
||||
readonly threads: EnvironmentThreadShell[];
|
||||
}
|
||||
|
||||
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
|
||||
return group.threads.reduce(
|
||||
const latestThread = group.threads.reduce(
|
||||
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
return group.pendingTasks.reduce((latest, pendingTask) => {
|
||||
const timestamp = Date.parse(pendingTask.message.createdAt);
|
||||
return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
|
||||
}, latestThread);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trims a group's threads to recent activity for the default home view.
|
||||
* `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
|
||||
* Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
|
||||
* the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
|
||||
*/
|
||||
function selectRecentThreads(
|
||||
sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
threadSortOrder: SidebarThreadSortOrder,
|
||||
now: number,
|
||||
): ReadonlyArray<EnvironmentThreadShell> {
|
||||
const cutoff = now - RECENT_THREAD_WINDOW_MS;
|
||||
const recent = sortedThreads.filter(
|
||||
(thread) => getThreadSortTimestamp(thread, threadSortOrder) >= cutoff,
|
||||
);
|
||||
return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
|
||||
}
|
||||
|
||||
export function buildHomeThreadGroups(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly searchQuery: string;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
/** Current time used for the recency window; defaults to now. Injectable for tests. */
|
||||
readonly now?: number;
|
||||
}): ReadonlyArray<HomeThreadGroup> {
|
||||
const now = input.now ?? Date.now();
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
@@ -68,10 +118,49 @@ export function buildHomeThreadGroups(input: {
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], pendingTasks: [], threads: [] });
|
||||
}
|
||||
}
|
||||
|
||||
for (const pendingTask of input.pendingTasks ?? []) {
|
||||
if (input.environmentId !== null && pendingTask.message.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const physicalKey = scopedProjectKey(
|
||||
pendingTask.message.environmentId,
|
||||
pendingTask.creation.projectId,
|
||||
);
|
||||
let groupKey = groupKeyByProjectKey.get(physicalKey);
|
||||
if (!groupKey) {
|
||||
// The project shell is not loaded (environment offline / project gone).
|
||||
// A queued task must stay visible and deletable regardless, so build a
|
||||
// standalone group from the metadata snapshotted at enqueue time.
|
||||
groupKey = `pending-project:${physicalKey}`;
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
groups.set(groupKey, {
|
||||
key: groupKey,
|
||||
projects: [
|
||||
{
|
||||
environmentId: pendingTask.message.environmentId,
|
||||
id: pendingTask.creation.projectId,
|
||||
title: pendingTask.creation.projectTitle ?? "Unknown project",
|
||||
workspaceRoot:
|
||||
pendingTask.creation.projectCwd ?? String(pendingTask.creation.projectId),
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: pendingTask.message.createdAt,
|
||||
updatedAt: pendingTask.message.createdAt,
|
||||
},
|
||||
],
|
||||
pendingTasks: [],
|
||||
threads: [],
|
||||
});
|
||||
}
|
||||
groups.get(groupKey)?.pendingTasks.push(pendingTask);
|
||||
}
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) {
|
||||
continue;
|
||||
@@ -93,7 +182,7 @@ export function buildHomeThreadGroups(input: {
|
||||
|
||||
for (const group of groups.values()) {
|
||||
const representative = group.projects[0];
|
||||
if (!representative || group.threads.length === 0) {
|
||||
if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -108,17 +197,53 @@ export function buildHomeThreadGroups(input: {
|
||||
const matchingThreads = groupMatches
|
||||
? group.threads
|
||||
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
|
||||
const matchingPendingTasks = groupMatches
|
||||
? group.pendingTasks
|
||||
: group.pendingTasks.filter((pendingTask) =>
|
||||
pendingTask.title.toLocaleLowerCase().includes(query),
|
||||
);
|
||||
|
||||
if (matchingThreads.length === 0) {
|
||||
if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
|
||||
// An active search should reach the full history, so the recency window
|
||||
// only trims the default (no-query) view.
|
||||
const recentThreads =
|
||||
query.length === 0
|
||||
? selectRecentThreads(sortedThreads, input.threadSortOrder, now)
|
||||
: sortedThreads;
|
||||
|
||||
// Sorted newest-first, so the first thread whose project is a group member
|
||||
// marks the machine the user last worked on.
|
||||
const lastActiveProject = Arr.findFirst(sortedThreads, (thread) =>
|
||||
group.projects.some(
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
).pipe(
|
||||
Option.flatMap((thread) =>
|
||||
Arr.findFirst(
|
||||
group.projects,
|
||||
(project) =>
|
||||
project.environmentId === thread.environmentId && project.id === thread.projectId,
|
||||
),
|
||||
),
|
||||
Option.getOrNull,
|
||||
);
|
||||
|
||||
result.push({
|
||||
key: group.key,
|
||||
title,
|
||||
representative,
|
||||
projects: group.projects,
|
||||
threads: sortThreads(matchingThreads, input.threadSortOrder),
|
||||
pendingTasks: matchingPendingTasks,
|
||||
threads: sortedThreads,
|
||||
recentThreads,
|
||||
newThreadTarget: group.key.startsWith("pending-project:")
|
||||
? null
|
||||
: (lastActiveProject ?? representative),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,26 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { ComponentProps } from "react";
|
||||
import type { ColorValue } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
createContext,
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type {
|
||||
ColorValue,
|
||||
NativeScrollEvent,
|
||||
NativeSyntheticEvent,
|
||||
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 +44,231 @@ export const THREAD_SWIPE_SPRING = {
|
||||
stiffness: 330,
|
||||
};
|
||||
|
||||
interface ThreadSwipePrimaryAction {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers the scroll gate to swipeables via context so that flipping it does
|
||||
* NOT re-render whole rows: putting the flag in list extraData/renderItem deps
|
||||
* re-rendered every visible row (hooks, subscriptions and all) exactly at
|
||||
* scroll start — peak frame pressure. As a context value only the
|
||||
* ThreadSwipeable consumers re-render.
|
||||
*/
|
||||
const SwipeableScrollGateContext = createContext(true);
|
||||
|
||||
export function SwipeableScrollGateProvider(props: {
|
||||
readonly enabled: boolean;
|
||||
readonly children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<SwipeableScrollGateContext.Provider value={props.enabled}>
|
||||
{props.children}
|
||||
</SwipeableScrollGateContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gates row swipes on list scroll activity, mirroring UIKit's own swipe
|
||||
* actions (`!isDragging && !isDecelerating`). failOffsetY on the swipe pan
|
||||
* covers the first pan of a scroll, but trackpad scroll sessions spawn fresh
|
||||
* gesture sessions (momentum catch, direction changes) whose reset
|
||||
* translation can re-activate a swipe mid-scroll — so while the list has
|
||||
* moved vertically during an active drag/momentum phase, row swipes are
|
||||
* disabled entirely.
|
||||
*
|
||||
* Spread the returned handlers onto the list and pass `swipeEnabled` to rows.
|
||||
*/
|
||||
export function useSwipeableScrollGate(options?: {
|
||||
readonly onScroll?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
|
||||
readonly onScrollBeginDrag?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
|
||||
}) {
|
||||
const [gateActive, setGateActive] = useState(false);
|
||||
const gateActiveRef = useRef(false);
|
||||
const draggingRef = useRef(false);
|
||||
const dragStartYRef = useRef(0);
|
||||
const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const externalOnScroll = options?.onScroll;
|
||||
const externalOnScrollBeginDrag = options?.onScrollBeginDrag;
|
||||
|
||||
const update = useCallback((next: boolean) => {
|
||||
if (gateActiveRef.current !== next) {
|
||||
gateActiveRef.current = next;
|
||||
setGateActive(next);
|
||||
}
|
||||
}, []);
|
||||
const clearSettle = useCallback(() => {
|
||||
if (settleTimerRef.current !== null) {
|
||||
clearTimeout(settleTimerRef.current);
|
||||
settleTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => clearSettle, [clearSettle]);
|
||||
|
||||
const onScrollBeginDrag = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
draggingRef.current = true;
|
||||
dragStartYRef.current = event.nativeEvent.contentOffset.y;
|
||||
clearSettle();
|
||||
externalOnScrollBeginDrag?.(event);
|
||||
},
|
||||
[clearSettle, externalOnScrollBeginDrag],
|
||||
);
|
||||
const onScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
// Only vertical movement during a user drag arms the gate — a purely
|
||||
// horizontal row swipe never moves contentOffset.y, and inset-driven
|
||||
// offset changes at mount happen outside a drag.
|
||||
if (
|
||||
draggingRef.current &&
|
||||
!gateActiveRef.current &&
|
||||
Math.abs(event.nativeEvent.contentOffset.y - dragStartYRef.current) > 4
|
||||
) {
|
||||
update(true);
|
||||
}
|
||||
externalOnScroll?.(event);
|
||||
},
|
||||
[externalOnScroll, update],
|
||||
);
|
||||
const onScrollEndDrag = useCallback(() => {
|
||||
draggingRef.current = false;
|
||||
clearSettle();
|
||||
// If momentum follows, onMomentumScrollBegin cancels this and the gate
|
||||
// stays armed until the deceleration finishes.
|
||||
settleTimerRef.current = setTimeout(() => update(false), 160);
|
||||
}, [clearSettle, update]);
|
||||
const onMomentumScrollBegin = useCallback(() => {
|
||||
clearSettle();
|
||||
}, [clearSettle]);
|
||||
const onMomentumScrollEnd = useCallback(() => {
|
||||
update(false);
|
||||
}, [update]);
|
||||
|
||||
return {
|
||||
swipeEnabled: !gateActive,
|
||||
scrollGateHandlers: {
|
||||
onScroll,
|
||||
onScrollBeginDrag,
|
||||
onScrollEndDrag,
|
||||
onMomentumScrollBegin,
|
||||
onMomentumScrollEnd,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function ThreadSwipeable(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly children: (close: () => void) => ReactNode;
|
||||
readonly containerStyle?: StyleProp<ViewStyle>;
|
||||
/** Disables NEW swipe activations (e.g. while the list scrolls). */
|
||||
readonly enabled?: boolean;
|
||||
readonly enableTrackpadSwipe?: boolean;
|
||||
readonly fullSwipeWidth: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
|
||||
readonly primaryAction: ThreadSwipePrimaryAction;
|
||||
/**
|
||||
* Identity of the content being wrapped. When a recycled list reuses this
|
||||
* component for a different item, the swipeable snaps back to closed so an
|
||||
* open/mid-drag state can't leak onto another row.
|
||||
*/
|
||||
readonly resetKey?: string;
|
||||
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 gateEnabled = use(SwipeableScrollGateContext);
|
||||
const resetKey = props.resetKey;
|
||||
useEffect(() => {
|
||||
if (resetKey === undefined) {
|
||||
return;
|
||||
}
|
||||
fullSwipeArmedRef.current = false;
|
||||
swipeableRef.current?.reset();
|
||||
}, [resetKey]);
|
||||
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}
|
||||
enabled={props.enabled !== false && gateEnabled}
|
||||
enableTrackpadTwoFingerGesture={props.enableTrackpadSwipe ?? true}
|
||||
// Fail the swipe once the pan is vertically dominant (patched-in RNGH
|
||||
// prop) — otherwise trackpad scrolls with ~8px of horizontal drift
|
||||
// start opening rows because the swipe pan runs simultaneously with
|
||||
// the list scroll gesture and never gets disqualified by Y movement.
|
||||
failOffsetY={[-10, 10]}
|
||||
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 +422,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,57 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useCallback } from "react";
|
||||
import { Alert } from "react-native";
|
||||
|
||||
import { removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { releaseEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
|
||||
export function usePendingTaskListActions(): {
|
||||
readonly openPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
} {
|
||||
const navigation = useNavigation();
|
||||
|
||||
const openPendingTask = useCallback(
|
||||
(pendingTask: PendingNewTask) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(pendingTask.message.environmentId),
|
||||
projectId: String(pendingTask.creation.projectId),
|
||||
pendingTaskId: String(pendingTask.message.messageId),
|
||||
},
|
||||
});
|
||||
},
|
||||
[navigation],
|
||||
);
|
||||
|
||||
const confirmDeletePendingTask = useCallback((pendingTask: PendingNewTask) => {
|
||||
Alert.alert(
|
||||
"Delete pending task?",
|
||||
`“${pendingTask.title}” has not been sent yet and will be removed from the outbox.`,
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Delete",
|
||||
style: "destructive",
|
||||
onPress: () => {
|
||||
// Release the edit lock only after removal succeeds, and only if
|
||||
// it is held for THIS task — clearing it up front (or for another
|
||||
// task) would let the drain deliver a mid-edit payload.
|
||||
void removeThreadOutboxMessage(pendingTask.message)
|
||||
.then(() => releaseEditingQueuedMessage(pendingTask.message.messageId))
|
||||
.catch((error) => {
|
||||
Alert.alert(
|
||||
"Could not delete pending task",
|
||||
error instanceof Error ? error.message : "The pending task could not be removed.",
|
||||
);
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
}, []);
|
||||
|
||||
return { openPendingTask, confirmDeletePendingTask };
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user