Skip to content

Commit 5b3093c

Browse files
refactor(mobile): UI primitives and workspace screens drop sync effects
Adds the AppState and root navigation foundations, and moves the UI primitives, settings, media previews, files, home list, terminal, pull request and review screens off synced state and onto atoms, shared stores and ref callbacks. Effect categories removed: - AppState, keyboard and permission listeners moved to shared stores and atoms - fetches and polling moved to atoms (crash log, release checks, usage limits, file leases, file tree, pull request pages, review sections) - back handlers, announcements, video loads and favicons moved to ref callbacks - event logic in effects moved to handlers (slider drags, palette scroll, file jumps, reviewer search, close-on-blur) - props and queries mirrored into state derived in render (review selection, workspace tabs, filter menu, Live Activity status) - Reanimated prop copies moved to CSS transitions and animations - terminal lifecycle moved into a session store transition function - thread PR snapshots recorded from query answers Bugs fixed: - A dialog raised during Android activity replacement was lost, and late actions dismissed the wrong dialog. - Selections from the sidebar ignored Home's swipe-back dismissal. - The notifications screen re-read permissions on every render. - A release check timeout said "Aborted"; usage-limit reset times went stale between refreshes. - Project favicons showed before the new image had loaded. - iOS video previews could hand AVKit an expired signed URL. - Draft edits re-acquired file leases, and a failed gallery item leaked others' leases. - The reviewer list jumped to the top on refetch, and a late page load from an old filter clobbered the new one. - Review: a long-press range start was wiped, the wrong section showed first, a feed-opened turn was overwritten, and turn diff errors stuck. - Files opened with a hidden inspector for one frame. Kept effects: - Overlay portal publish: React Native has no createPortal. - Native header options and iOS search bar seeding: RefObject-only APIs. - Command palette list follows selection: results change from live data. - Native review diff and media presentations: imperative native views. - Settings auth route: Clerk reports sign-out only through its store. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 22bcb07 commit 5b3093c

138 files changed

Lines changed: 5247 additions & 4199 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/components/ComposerContextAttachment.tsx‎

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,13 @@ import * as Dialog from "./ui/Dialog";
55
import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
66
import { Pressable, View } from "react-native";
77
import { Image } from "expo-image";
8-
import { useEffect, useId, useState } from "react";
8+
import { useId, useState } from "react";
99
import type { DraftComposerAttachment } from "../lib/composerImages";
1010
import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
11-
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
11+
import {
12+
loadLocalAttachmentPreview,
13+
useLocalAttachmentPreview,
14+
} from "../lib/localAttachmentPreview";
1215
import { downloadAndShareAttachment } from "../lib/attachmentDownload";
1316
import { assetImageSource } from "../lib/assetImageSource";
1417
import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
@@ -35,31 +38,13 @@ export function ComposerContextAttachment(props: {
3538
const remoteEnvironmentId = local || inlineUri ? null : (props.environmentId ?? null);
3639
const asset = useAssetUrlState(remoteEnvironmentId, resource);
3740
const refresh = useRefreshAssetUrl(remoteEnvironmentId, resource);
38-
const [localUri, setLocalUri] = useState<string | null>(null);
39-
const [error, setError] = useState<string | null>(null);
41+
const localPreview = useLocalAttachmentPreview(local ?? null);
42+
const error = localPreview.error ? "The local file is unavailable. Attach it again." : null;
4043
const [sharing, setSharing] = useState(false);
4144
const [previewOpen, setPreviewOpen] = useState(false);
42-
useEffect(() => {
43-
if (!local) return;
44-
const controller = new AbortController();
45-
let dispose: (() => void) | undefined;
46-
void loadLocalAttachmentPreview(local, controller.signal)
47-
.then((preview) => {
48-
if (!preview) return;
49-
if (controller.signal.aborted) return preview.dispose();
50-
dispose = preview.dispose;
51-
setLocalUri(preview.uri);
52-
setError(null);
53-
})
54-
.catch(() => {
55-
if (!controller.signal.aborted) setError("The local file is unavailable. Attach it again.");
56-
});
57-
return () => {
58-
controller.abort();
59-
dispose?.();
60-
};
61-
}, [local]);
62-
const uri = local ? localUri : (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
45+
const uri = local
46+
? localPreview.uri
47+
: (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
6348
const share = async () => {
6449
if (sharing) return;
6550
setSharing(true);

‎apps/mobile/src/components/FilePreviewModal.tsx‎

Lines changed: 96 additions & 147 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,9 @@
11
import * as Dialog from "./ui/Dialog";
2-
import { useNavigation } from "@react-navigation/native";
3-
import {
4-
useCallback,
5-
useContext,
6-
useEffect,
7-
useEffectEvent,
8-
useState,
9-
useSyncExternalStore,
10-
useMemo,
11-
} from "react";
12-
import { Keyboard } from "react-native";
2+
import { useContext, useEffect, useEffectEvent, useState } from "react";
133

144
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
15-
import { useRefreshAssetUrl } from "../state/assets";
5+
import { usePreviewPresentation } from "../lib/previewPresentation";
6+
import { refreshAssetUrl } from "../state/assets";
167
import { filePreviewGallery, filePreviewKey, filePreviewName } from "../lib/filePreviewGallery";
178
import { FilePreviewGallery } from "./FilePreviewGallery";
189
import { FilePreview } from "./FilePreview";
@@ -28,77 +19,47 @@ export type {
2819
ResolvedFilePreviewSource,
2920
} from "./FilePreviewModal.types";
3021

31-
function PreviewItemResolver(props: {
32-
readonly source: FilePreviewItem;
33-
readonly onResolved: (source: ResolvedFilePreviewSource) => void;
34-
readonly onRequestClose: () => void;
35-
readonly onOpenError?: (error: unknown) => void;
36-
}) {
37-
const { source } = props;
38-
const environmentId = "environmentId" in source ? source.environmentId : null;
39-
const refreshAssetUrl = useRefreshAssetUrl(
40-
environmentId,
41-
"resource" in source ? source.resource : null,
42-
);
43-
// Resolve once per presentation; background URL refreshes must not reopen the native viewer.
44-
const [uri, setUri] = useState<string | null>("uri" in source ? source.uri : null);
45-
const onRequestClose = useEffectEvent(props.onRequestClose);
46-
const onResolutionError = useEffectEvent((error: unknown, fallbackMessage: string) => {
47-
if (props.onOpenError) props.onOpenError(error);
48-
else Dialog.alert("Could not open preview", fallbackMessage);
49-
onRequestClose();
50-
});
51-
useEffect(() => Keyboard.dismiss(), []);
52-
useEffect(() => {
53-
if (environmentId === null || uri !== null) return;
54-
let cancelled = false;
55-
// Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
56-
void refreshAssetUrl()
57-
.then((url) => {
58-
if (cancelled) return;
59-
if (!url) throw new Error("Reconnect to this environment and try again.");
60-
setUri(url + (source.srcFragment ?? ""));
61-
})
62-
.catch((error: unknown) => {
63-
if (cancelled) return;
64-
onResolutionError(
65-
error,
66-
"Reconnect to this environment and try again. The file may have been moved or deleted.",
67-
);
68-
});
69-
return () => {
70-
cancelled = true;
71-
};
72-
}, [environmentId, uri, refreshAssetUrl, source.srcFragment]);
73-
useEffect(() => {
74-
if (!("attachment" in source)) return;
75-
const controller = new AbortController();
76-
let release: (() => void) | undefined;
77-
void loadLocalAttachmentPreview(source.attachment, controller.signal)
78-
.then((file) => {
79-
if (!file) return;
80-
if (controller.signal.aborted) {
81-
file.dispose();
82-
return;
83-
}
84-
release = file.dispose;
85-
setUri(file.uri);
86-
})
87-
.catch((error: unknown) => {
88-
if (controller.signal.aborted) return;
89-
onResolutionError(error, "Attach the file again and retry.");
90-
});
91-
return () => {
92-
controller.abort();
93-
release?.();
94-
};
95-
}, [source]);
22+
class PreviewResolutionError extends Error {
23+
constructor(
24+
override readonly cause: unknown,
25+
readonly fallbackMessage: string,
26+
) {
27+
super(fallbackMessage, { cause });
28+
}
29+
}
9630

97-
const onResolved = useEffectEvent(props.onResolved);
98-
useEffect(() => {
99-
if (uri !== null) onResolved({ ...source, name: filePreviewName(source), uri });
100-
}, [uri, source]);
101-
return null;
31+
interface ResolvedPreviewItem {
32+
readonly source: ResolvedFilePreviewSource;
33+
readonly dispose?: () => void;
34+
}
35+
36+
async function resolvePreviewItem(
37+
item: FilePreviewItem,
38+
signal: AbortSignal,
39+
): Promise<ResolvedPreviewItem | null> {
40+
const name = filePreviewName(item);
41+
if ("attachment" in item) {
42+
const file = await loadLocalAttachmentPreview(item.attachment, signal).catch(
43+
(error: unknown) => {
44+
throw new PreviewResolutionError(error, "Attach the file again and retry.");
45+
},
46+
);
47+
return file && { source: { ...item, name, uri: file.uri }, dispose: file.dispose };
48+
}
49+
if (!("environmentId" in item)) return { source: { ...item, name } };
50+
// Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
51+
const url = await refreshAssetUrl(item.environmentId, item.resource)
52+
.then((value) => {
53+
if (!value) throw new Error("Reconnect to this environment and try again.");
54+
return value;
55+
})
56+
.catch((error: unknown) => {
57+
throw new PreviewResolutionError(
58+
error,
59+
"Reconnect to this environment and try again. The file may have been moved or deleted.",
60+
);
61+
});
62+
return { source: { ...item, name, uri: url + (item.srcFragment ?? "") } };
10263
}
10364

10465
function ResolvedFilePreview(props: {
@@ -108,39 +69,55 @@ function ResolvedFilePreview(props: {
10869
}) {
10970
// Freeze the group at opening; streaming messages and URL refreshes must not reopen the viewer.
11071
const [items] = useState(() => filePreviewGallery(props.source, []));
111-
const [resolved, setResolved] = useState<Record<string, ResolvedFilePreviewSource>>({});
112-
const onResolved = useCallback((item: ResolvedFilePreviewSource, key: string) => {
113-
setResolved((current) => ({ ...current, [key]: item }));
114-
}, []);
115-
const selected = resolved[filePreviewKey(props.source)];
116-
const gallery = useMemo(
117-
() =>
118-
items.flatMap((item) => {
119-
const value = resolved[filePreviewKey(item)];
120-
return value ? [value] : [];
121-
}),
122-
[items, resolved],
72+
const selectedKey = filePreviewKey(props.source);
73+
const [gallery, setGallery] = useState<readonly ResolvedFilePreviewSource[] | null>(() =>
74+
items.every((item) => "uri" in item)
75+
? items.map((item) => ({ ...item, name: filePreviewName(item) }))
76+
: null,
12377
);
124-
const ready = selected && gallery.length === items.length;
78+
const onResolutionError = useEffectEvent((error: PreviewResolutionError) => {
79+
if (props.onOpenError) props.onOpenError(error.cause);
80+
else Dialog.alert("Could not open preview", error.fallbackMessage);
81+
props.onRequestClose();
82+
});
83+
// Resolves once per presentation and holds local file leases until it closes.
84+
useEffect(() => {
85+
if (items.every((item) => "uri" in item)) return;
86+
const controller = new AbortController();
87+
const resolving = Promise.allSettled(
88+
items.map((item) => resolvePreviewItem(item, controller.signal)),
89+
);
90+
void resolving.then((settled) => {
91+
if (controller.signal.aborted) return;
92+
const failure = settled.find((item) => item.status === "rejected");
93+
if (failure) {
94+
onResolutionError(
95+
failure.reason instanceof PreviewResolutionError
96+
? failure.reason
97+
: new PreviewResolutionError(failure.reason, "Try again."),
98+
);
99+
return;
100+
}
101+
const sources = settled.flatMap((item) =>
102+
item.status === "fulfilled" && item.value ? [item.value.source] : [],
103+
);
104+
if (sources.length === items.length) setGallery(sources);
105+
});
106+
return () => {
107+
controller.abort();
108+
void resolving.then((settled) => {
109+
for (const item of settled) if (item.status === "fulfilled") item.value?.dispose?.();
110+
});
111+
};
112+
}, [items]);
113+
const selected = gallery?.[items.findIndex((item) => filePreviewKey(item) === selectedKey)];
114+
if (!gallery || !selected) return null;
125115
return (
126-
<>
127-
{items.map((item) => (
128-
<PreviewItemResolver
129-
key={filePreviewKey(item)}
130-
source={item}
131-
onResolved={(value) => onResolved(value, filePreviewKey(item))}
132-
onRequestClose={props.onRequestClose}
133-
onOpenError={props.onOpenError}
134-
/>
135-
))}
136-
{ready ? (
137-
<FilePreview
138-
source={{ ...selected, gallery }}
139-
onRequestClose={props.onRequestClose}
140-
onOpenError={props.onOpenError}
141-
/>
142-
) : null}
143-
</>
116+
<FilePreview
117+
source={{ ...selected, gallery }}
118+
onRequestClose={props.onRequestClose}
119+
onOpenError={props.onOpenError}
120+
/>
144121
);
145122
}
146123

@@ -151,41 +128,13 @@ export function FilePreviewModal(props: {
151128
readonly onOpenError?: (error: unknown) => void;
152129
}) {
153130
const group = useContext(FilePreviewGallery);
154-
const source = useMemo(
155-
() =>
156-
props.source === null
157-
? null
158-
: {
159-
...props.source,
160-
gallery: filePreviewGallery(props.source, group),
161-
},
162-
[props.source, group],
163-
);
164-
const navigation = useNavigation();
165-
const subscribeToFocus = useCallback(
166-
(listener: () => void) => {
167-
const offFocus = navigation.addListener("focus", listener);
168-
const offBlur = navigation.addListener("blur", listener);
169-
return () => {
170-
offFocus();
171-
offBlur();
172-
};
173-
},
174-
[navigation],
175-
);
176-
// The legacy envelope's focus context may describe a different route than this v5 card.
177-
const isFocused = useSyncExternalStore(
178-
subscribeToFocus,
179-
navigation.isFocused,
180-
navigation.isFocused,
181-
);
182-
const hasSource = props.source !== null;
183-
const onRequestClose = useEffectEvent(props.onRequestClose);
184-
useEffect(() => {
185-
if (!isFocused && hasSource) onRequestClose();
186-
}, [isFocused, hasSource]);
131+
const source =
132+
props.source === null
133+
? null
134+
: { ...props.source, gallery: filePreviewGallery(props.source, group) };
135+
usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
187136

188-
if (!source || !isFocused) return null;
137+
if (!source) return null;
189138
return (
190139
<ResolvedFilePreview
191140
key={filePreviewKey(source)}

0 commit comments

Comments
 (0)