The best way to control Claude Code, Codex and more from any computer or phone
perf(mobile): files, review and remaining settings screens compile with the React Compiler (#21124)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 14:33 UTC
0ee07e32ab3532e2c59cd6720324b96a83c0df3d
14 files changed
+624
-809
apps/mobile/src/features/files/AttachmentFileScreen.tsx
+90
-113
@@ -6,7 +6,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
6
import type { MenuAction } from "@react-native-menu/menu";
7
import { EnvironmentId } from "@t3tools/contracts";
8
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
9
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
9
+import { useEffect, useRef, useState } from "react";
10
import { Platform, ScrollView, View } from "react-native";
11
12
import {
@@ -196,9 +196,9 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
196
);
197
const [nativeError, setNativeError] = useState<string | null>(null);
198
const pendingNativeError = useRef<string | null>(null);
199
- const handleBack = useCallback(() => {
199
+ const handleBack = () => {
200
if (navigation.canGoBack()) navigation.goBack();
201
- }, [navigation]);
201
+ };
202
const { uri, resource } = document;
203
useEffect(() => {
204
if (nativeViewer !== "pending" || !uri) return;
@@ -208,17 +208,17 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
208
}, [nativeViewer, uri]);
209
// The viewer mints its own fresh URL from the resource, so a link that expired while this
210
// screen sat in the background is never handed to Quick Look or ACTION_VIEW.
211
- const nativeSource = useMemo<FilePreviewSource | null>(() => {
211
+ const nativeSource = ((): FilePreviewSource | null => {
212
const kind = nativeKind ?? "document";
213
const base = { kind, name: params.name, mimeType: params.mimeType };
214
if (localAttachment) return { ...base, attachment: localAttachment };
215
if (environmentId) return { ...base, environmentId, resource };
216
return uri ? { ...base, uri } : null;
217
- }, [environmentId, localAttachment, nativeKind, params.mimeType, params.name, resource, uri]);
218
- const handleNativeOpenError = useCallback((error: unknown) => {
217
+ })();
218
+ const handleNativeOpenError = (error: unknown) => {
219
pendingNativeError.current = nativeViewerErrorMessage(error);
220
- }, []);
221
- const handleNativeClose = useCallback(() => {
220
+ };
221
+ const handleNativeClose = () => {
222
setNativeOpen(false);
223
const message = pendingNativeError.current;
224
pendingNativeError.current = null;
@@ -233,117 +233,94 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
233
return;
234
}
235
handleBack();
236
- }, [handleBack, nativeViewer]);
237
- const removeFromDraft = useCallback(() => {
236
+ };
237
+ const removeFromDraft = () => {
238
if (!draftKey) return;
239
removeComposerDraftAttachment(draftKey, params.attachmentId);
240
handleBack();
241
- }, [draftKey, handleBack, params.attachmentId]);
241
+ };
242
243
const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
244
- const menuActions = useMemo(
245
- () =>
246
- [
247
- renderedMode
248
- ? ({
249
- id: "preview",
250
- title: renderedMode === "table" ? "Table" : "Preview",
251
- icon: renderedMode === "table" ? "tablecells" : "eye",
252
- inline: true,
253
- onPress: () => setRendered(true),
254
- } as const)
255
- : null,
256
- renderedMode
257
- ? ({
258
- id: "source",
259
- title: "Source",
260
- icon: "doc.text",
261
- inline: true,
262
- onPress: () => setRendered(false),
263
- } as const)
264
- : null,
265
- content && activeMode === "source"
266
- ? ({
267
- id: "word-wrap",
268
- title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
269
- icon: "text.alignleft",
270
- inline: false,
271
- onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
272
- } as const)
273
- : null,
274
- content
275
- ? ({
276
- id: "copy",
277
- title: content.truncated ? "Copy preview" : "Copy contents",
278
- icon: "doc.on.doc",
279
- inline: false,
280
- onPress: () => copyTextWithHaptic(content.text),
281
- } as const)
282
- : null,
283
- uri
284
- ? ({
285
- id: "share",
286
- title: sharing ? "Opening share sheet…" : "Save or share",
287
- icon: "square.and.arrow.up",
288
- inline: false,
289
- onPress: () => void share(),
290
- } as const)
291
- : null,
292
- uri
293
- ? ({
294
- id: "open-viewer",
295
- title: "Open in file viewer",
296
- icon: "arrow.up.left.and.arrow.down.right",
297
- inline: false,
298
- onPress: () => {
299
- setNativeViewer((current) => (current === null ? null : "open"));
300
- setNativeOpen(true);
301
- },
302
- } as const)
303
- : null,
304
- draftKey
305
- ? ({
306
- id: "remove",
307
- title: "Remove from draft",
308
- icon: "trash",
309
- inline: false,
310
- destructive: true,
311
- onPress: removeFromDraft,
312
- } as const)
313
- : null,
314
- ].filter((action) => action !== null),
315
- [
316
- appearance.codeWordBreak,
317
- setCodeWordBreak,
318
- content,
319
- draftKey,
320
- removeFromDraft,
321
- activeMode,
322
- renderedMode,
323
- setRendered,
324
- share,
325
- sharing,
326
- uri,
327
- ],
328
- );
244
+ const menuActions = [
245
+ renderedMode
246
+ ? ({
247
+ id: "preview",
248
+ title: renderedMode === "table" ? "Table" : "Preview",
249
+ icon: renderedMode === "table" ? "tablecells" : "eye",
250
+ inline: true,
251
+ onPress: () => setRendered(true),
252
+ } as const)
253
+ : null,
254
+ renderedMode
255
+ ? ({
256
+ id: "source",
257
+ title: "Source",
258
+ icon: "doc.text",
259
+ inline: true,
260
+ onPress: () => setRendered(false),
261
+ } as const)
262
+ : null,
263
+ content && activeMode === "source"
264
+ ? ({
265
+ id: "word-wrap",
266
+ title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
267
+ icon: "text.alignleft",
268
+ inline: false,
269
+ onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
270
+ } as const)
271
+ : null,
272
+ content
273
+ ? ({
274
+ id: "copy",
275
+ title: content.truncated ? "Copy preview" : "Copy contents",
276
+ icon: "doc.on.doc",
277
+ inline: false,
278
+ onPress: () => copyTextWithHaptic(content.text),
279
+ } as const)
280
+ : null,
281
+ uri
282
+ ? ({
283
+ id: "share",
284
+ title: sharing ? "Opening share sheet…" : "Save or share",
285
+ icon: "square.and.arrow.up",
286
+ inline: false,
287
+ onPress: () => void share(),
288
+ } as const)
289
+ : null,
290
+ uri
291
+ ? ({
292
+ id: "open-viewer",
293
+ title: "Open in file viewer",
294
+ icon: "arrow.up.left.and.arrow.down.right",
295
+ inline: false,
296
+ onPress: () => {
297
+ setNativeViewer((current) => (current === null ? null : "open"));
298
+ setNativeOpen(true);
299
+ },
300
+ } as const)
301
+ : null,
302
+ draftKey
303
+ ? ({
304
+ id: "remove",
305
+ title: "Remove from draft",
306
+ icon: "trash",
307
+ inline: false,
308
+ destructive: true,
309
+ onPress: removeFromDraft,
310
+ } as const)
311
+ : null,
312
+ ].filter((action) => action !== null);
313
const selectedAction = activeMode === "source" ? "source" : "preview";
330
- const androidMenuActions = useMemo<MenuAction[]>(
331
- () =>
332
- menuActions.map((action) => ({
333
- id: action.id,
334
- title: action.title,
335
- image: action.icon,
336
- state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
337
- ...("destructive" in action ? { attributes: { destructive: true } } : {}),
338
- })),
339
- [selectedAction, menuActions],
340
- );
341
- const handleAndroidMenuAction = useCallback(
342
- (event: { nativeEvent: { event: string } }) => {
343
- menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
344
- },
345
- [menuActions],
346
- );
314
+ const androidMenuActions = menuActions.map((action) => ({
315
+ id: action.id,
316
+ title: action.title,
317
+ image: action.icon,
318
+ state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
319
+ ...("destructive" in action ? { attributes: { destructive: true } } : {}),
320
+ })) satisfies MenuAction[];
321
+ const handleAndroidMenuAction = (event: { nativeEvent: { event: string } }) => {
322
+ menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
323
+ };
324
const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;
325
326
return (
apps/mobile/src/features/files/FileMarkdownPreview.tsx
+102
-132
@@ -1,7 +1,8 @@
1
+import { settlePromise } from "@t3tools/client-runtime/state/runtime";
2
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3
import { resolveMobileMarkdownMediaSource } from "../../lib/markdownMediaSource";
4
import { getBrowseDirectoryPath } from "@t3tools/client-runtime/state/projects";
4
-import { useCallback, useMemo, useState } from "react";
5
+import { useState } from "react";
6
import { RefreshControl, ScrollView, View } from "react-native";
7
8
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
@@ -33,10 +34,7 @@ interface MarkdownPreviewStyles {
34
35
export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
36
const { appearance } = useAppearancePreferences();
36
- const nativeMarkdownTypography = useMemo(
37
- () => resolveNativeMarkdownTypography(appearance.baseFontSize),
38
- [appearance.baseFontSize],
39
- );
37
+ const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize);
38
const theme = useUniwindTheme();
39
const body = theme["--color-md-body"];
40
const strong = theme["--color-md-strong"];
@@ -48,41 +46,28 @@ export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
46
const regularFontFamily = FONT_FAMILIES.regular;
47
const boldFontFamily = FONT_FAMILIES.bold;
48
51
- return useMemo(() => {
52
- return {
53
- nativeTextStyle: {
54
- color: body,
55
- strongColor: strong,
56
- mutedColor: body,
57
- linkColor: link,
58
- inlineCodeColor: codeText,
59
- codeColor: codeText,
60
- codeBackgroundColor: codeBackground,
61
- codeBlockBackgroundColor: codeBackground,
62
- fileTextColor: codeText,
63
- skillTextColor: codeText,
64
- quoteMarkerColor: blockquoteBorder,
65
- dividerColor: horizontalRule,
66
- fontSize: nativeMarkdownTypography.fontSize,
67
- lineHeight: nativeMarkdownTypography.lineHeight,
68
- headingFontSizes: nativeMarkdownTypography.headingFontSizes,
69
- fontFamily: regularFontFamily,
70
- headingFontFamily: boldFontFamily,
71
- boldFontFamily,
72
- },
73
- };
74
- }, [
75
- blockquoteBorder,
76
- body,
77
- codeBackground,
78
- codeText,
79
- horizontalRule,
80
- link,
81
- nativeMarkdownTypography,
82
- regularFontFamily,
83
- strong,
84
- boldFontFamily,
85
- ]);
49
+ return {
50
+ nativeTextStyle: {
51
+ color: body,
52
+ strongColor: strong,
53
+ mutedColor: body,
54
+ linkColor: link,
55
+ inlineCodeColor: codeText,
56
+ codeColor: codeText,
57
+ codeBackgroundColor: codeBackground,
58
+ codeBlockBackgroundColor: codeBackground,
59
+ fileTextColor: codeText,
60
+ skillTextColor: codeText,
61
+ quoteMarkerColor: blockquoteBorder,
62
+ dividerColor: horizontalRule,
63
+ fontSize: nativeMarkdownTypography.fontSize,
64
+ lineHeight: nativeMarkdownTypography.lineHeight,
65
+ headingFontSizes: nativeMarkdownTypography.headingFontSizes,
66
+ fontFamily: regularFontFamily,
67
+ headingFontFamily: boldFontFamily,
68
+ boldFontFamily,
69
+ },
70
+ };
71
}
72
73
export function FileMarkdownPreview(props: {
@@ -97,85 +82,79 @@ export function FileMarkdownPreview(props: {
82
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
83
const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
84
const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
100
- const handlePullToRefresh = useCallback(async () => {
85
+ const handlePullToRefresh = async () => {
86
if (!props.onRefresh) {
87
return;
88
}
89
setIsPullRefreshing(true);
105
- try {
106
- await props.onRefresh();
107
- } finally {
108
- setIsPullRefreshing(false);
109
- }
110
- }, [props.onRefresh]);
111
- const markdownDirectory = useMemo(
112
- () => getBrowseDirectoryPath(resolveWorkspaceFilePath(props.cwd, props.relativePath)),
113
- [props.cwd, props.relativePath],
90
+ // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
91
+ await settlePromise(async () => props.onRefresh?.());
92
+ setIsPullRefreshing(false);
93
+ };
94
+ const markdownDirectory = getBrowseDirectoryPath(
95
+ resolveWorkspaceFilePath(props.cwd, props.relativePath),
96
);
115
- const renderImage = useCallback<MarkdownImageRenderer>(
116
- (image) => {
117
- const media = resolveMobileMarkdownMediaSource(image.href, {
118
- threadId: props.threadId ?? undefined,
119
- workspaceRoot: markdownDirectory,
120
- imageEmbed: true,
121
- });
122
- const preview = resolveMarkdownMediaPreview(image.href, {
123
- environmentId: props.environmentId,
124
- threadId: props.threadId ?? undefined,
125
- workspaceRoot: markdownDirectory,
126
- captured: props.captured,
127
- imageEmbed: true,
128
- });
129
- if (media?.access === "direct") {
130
- if (media.kind === "video") {
131
- return (
132
- <ThreadMarkdownVideo
133
- source={{
134
- type: "media",
135
- name: media.name,
136
- mimeType: media.mimeType,
137
- uri: normalizeNativeMarkdownUrl(media.uri),
138
- actionsSource: preview?.source.actionsSource,
139
- }}
140
- thumbnailVisible
141
- />
142
- );
143
- }
97
+ const renderImage: MarkdownImageRenderer = (image) => {
98
+ const media = resolveMobileMarkdownMediaSource(image.href, {
99
+ threadId: props.threadId ?? undefined,
100
+ workspaceRoot: markdownDirectory,
101
+ imageEmbed: true,
102
+ });
103
+ const preview = resolveMarkdownMediaPreview(image.href, {
104
+ environmentId: props.environmentId,
105
+ threadId: props.threadId ?? undefined,
106
+ workspaceRoot: markdownDirectory,
107
+ captured: props.captured,
108
+ imageEmbed: true,
109
+ });
110
+ if (media?.access === "direct") {
111
+ if (media.kind === "video") {
112
return (
145
- <ThreadMarkdownImageView
146
- uri={normalizeNativeMarkdownUrl(media.uri)}
147
- sourceKey={media.uri}
148
- unavailable={false}
149
- alt={image.alt}
150
- format={media.mimeType === "image/svg+xml" ? "svg" : undefined}
151
- actionsSource={preview?.source.actionsSource}
152
- onPressPreview={setExpandedFile}
113
+ <ThreadMarkdownVideo
114
+ source={{
115
+ type: "media",
116
+ name: media.name,
117
+ mimeType: media.mimeType,
118
+ uri: normalizeNativeMarkdownUrl(media.uri),
119
+ actionsSource: preview?.source.actionsSource,
120
+ }}
121
+ thumbnailVisible
122
/>
123
);
124
}
156
- if (props.captured || media === null || media.access === "unavailable") {
157
- return <ThreadMarkdownImageUnavailable alt={image.alt} />;
158
- }
159
- if (media.kind === "video") {
160
- return preview?.kind === "video" ? (
161
- <ThreadMarkdownVideo source={preview.source} thumbnailVisible />
162
- ) : (
163
- <ThreadMarkdownImageUnavailable alt={image.alt} />
164
- );
165
- }
125
return (
167
- <ThreadMarkdownImage
168
- environmentId={props.environmentId}
169
- resource={media.resource}
126
+ <ThreadMarkdownImageView
127
+ uri={normalizeNativeMarkdownUrl(media.uri)}
128
+ sourceKey={media.uri}
129
+ unavailable={false}
130
alt={image.alt}
171
- srcFragment={media.srcFragment}
131
+ format={media.mimeType === "image/svg+xml" ? "svg" : undefined}
132
actionsSource={preview?.source.actionsSource}
133
onPressPreview={setExpandedFile}
134
/>
135
);
176
- },
177
- [markdownDirectory, props.environmentId, props.threadId, props.captured],
178
- );
136
+ }
137
+ if (props.captured || media === null || media.access === "unavailable") {
138
+ return <ThreadMarkdownImageUnavailable alt={image.alt} />;
139
+ }
140
+ if (media.kind === "video") {
141
+ return preview?.kind === "video" ? (
142
+ <ThreadMarkdownVideo source={preview.source} thumbnailVisible />
143
+ ) : (
144
+ <ThreadMarkdownImageUnavailable alt={image.alt} />
145
+ );
146
+ }
147
+ return (
148
+ <ThreadMarkdownImage
149
+ environmentId={props.environmentId}
150
+ resource={media.resource}
151
+ alt={image.alt}
152
+ srcFragment={media.srcFragment}
153
+ actionsSource={preview?.source.actionsSource}
154
+ onPressPreview={setExpandedFile}
155
+ />
156
+ );
157
+ };
158
const styles = useMarkdownPreviewStyles();
159
const resolveImageSource = useMarkdownImageSource({
160
environmentId: props.environmentId,
@@ -183,34 +162,25 @@ export function FileMarkdownPreview(props: {
162
workspaceRoot: markdownDirectory,
163
captured: props.captured,
164
});
186
- const openMedia = useCallback(
187
- (href: string, imageEmbed = false) => {
188
- const media = resolveMarkdownMediaPreview(href, {
189
- environmentId: props.environmentId,
190
- threadId: props.threadId ?? undefined,
191
- workspaceRoot: markdownDirectory,
192
- captured: props.captured,
193
- imageEmbed,
194
- });
195
- if (!media) return false;
196
- if (media.kind === "video") setExpandedVideo(media.source);
197
- else setExpandedFile(media.source);
198
- return true;
199
- },
200
- [markdownDirectory, props.environmentId, props.threadId, props.captured],
201
- );
202
- const onImagePress = useCallback(
203
- (href: string) => {
204
- openMedia(href, true);
205
- },
206
- [openMedia],
207
- );
208
- const onLinkPress = useCallback(
209
- (href: string) => {
210
- if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link");
211
- },
212
- [openMedia],
213
- );
165
+ const openMedia = (href: string, imageEmbed = false) => {
166
+ const media = resolveMarkdownMediaPreview(href, {
167
+ environmentId: props.environmentId,
168
+ threadId: props.threadId ?? undefined,
169
+ workspaceRoot: markdownDirectory,
170
+ captured: props.captured,
171
+ imageEmbed,
172
+ });
173
+ if (!media) return false;
174
+ if (media.kind === "video") setExpandedVideo(media.source);
175
+ else setExpandedFile(media.source);
176
+ return true;
177
+ };
178
+ const onImagePress = (href: string) => {
179
+ openMedia(href, true);
180
+ };
181
+ const onLinkPress = (href: string) => {
182
+ if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link");
183
+ };
184
185
return (
186
<ScrollView
apps/mobile/src/features/files/FileTreeBrowser.tsx
+45
-70
@@ -2,7 +2,7 @@ import { LegendList } from "@legendapp/list/react-native";
2
import type { ProjectEntry } from "@t3tools/contracts";
3
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
4
import { SymbolView } from "../../components/ui/AppSymbol";
5
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+import { useEffect, useRef, useState } from "react";
6
import { Platform, Pressable, RefreshControl, View } from "react-native";
7
import { useSafeAreaInsets } from "react-native-safe-area-context";
8
@@ -39,7 +39,7 @@ function ancestorPaths(path: string): ReadonlyArray<string> {
39
return ancestors;
40
}
41
42
-const FileTreeRow = memo(function FileTreeRow(props: {
42
+const FileTreeRow = function FileTreeRow(props: {
43
readonly item: VisibleFileTreeNode;
44
readonly selected: boolean;
45
readonly expanded: boolean;
@@ -102,7 +102,7 @@ const FileTreeRow = memo(function FileTreeRow(props: {
102
) : null}
103
</Pressable>
104
);
105
-});
105
+};
106
107
export function FileTreeBrowser(props: {
108
readonly entries: ReadonlyArray<ProjectEntry>;
@@ -134,24 +134,18 @@ export function FileTreeBrowser(props: {
134
loadingDirectories,
135
selectedPath: controlledSelectedPath,
136
} = props;
137
- const controlledSelectedPathRef = useRef(controlledSelectedPath);
137
const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
139
- controlledSelectedPathRef.current = controlledSelectedPath;
138
139
const selectedPath =
140
pendingSelection?.selectedPathAtPress === controlledSelectedPath
141
? pendingSelection.path
142
: controlledSelectedPath;
145
- const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
146
- const visibleNodes = useMemo(
147
- () =>
148
- flattenFileTree({
149
- nodes: tree,
150
- expanded: expandedPaths,
151
- searchResultPaths: props.searchResultPaths,
152
- }),
153
- [expandedPaths, props.searchResultPaths, tree],
154
- );
143
+ const tree = cachedFileTree(props.entries);
144
+ const visibleNodes = flattenFileTree({
145
+ nodes: tree,
146
+ expanded: expandedPaths,
147
+ searchResultPaths: props.searchResultPaths,
148
+ });
149
150
useEffect(() => {
151
if (!controlledSelectedPath) {
@@ -183,64 +177,45 @@ export function FileTreeBrowser(props: {
177
[],
178
);
179
186
- const toggleDirectory = useCallback(
187
- (path: string, expand: boolean) => {
188
- if (expand) onLoadDirectory(path);
189
- setExpandedPaths((current) => {
190
- const next = new Set(current);
191
- if (next.has(path)) {
192
- next.delete(path);
193
- } else {
194
- next.add(path);
195
- }
196
- return next;
197
- });
198
- },
199
- [onLoadDirectory],
200
- );
201
- const handleSelectFile = useCallback(
202
- (path: string) => {
203
- if (pendingSelectionTimeoutRef.current !== null) {
204
- clearTimeout(pendingSelectionTimeoutRef.current);
180
+ const toggleDirectory = (path: string, expand: boolean) => {
181
+ if (expand) onLoadDirectory(path);
182
+ setExpandedPaths((current) => {
183
+ const next = new Set(current);
184
+ if (next.has(path)) {
185
+ next.delete(path);
186
+ } else {
187
+ next.add(path);
188
}
206
- setPendingSelection({
207
- path,
208
- selectedPathAtPress: controlledSelectedPathRef.current,
209
- });
210
- pendingSelectionTimeoutRef.current = setTimeout(() => {
211
- pendingSelectionTimeoutRef.current = null;
212
- setPendingSelection((current) => (current?.path === path ? null : current));
213
- }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
214
- onSelectFile(path);
215
- },
216
- [onSelectFile],
217
- );
218
- const renderItem = useCallback(
219
- ({ item }: { readonly item: VisibleFileTreeNode }) => (
220
- <FileTreeRow
221
- item={item}
222
- selected={item.node.kind === "file" && item.node.path === selectedPath}
223
- expanded={expandedPaths.has(item.node.path)}
224
- loading={loadingDirectories.has(item.node.path)}
225
- onPressDirectory={toggleDirectory}
226
- onPreviewFile={onPreviewFile}
227
- onPressFile={handleSelectFile}
228
- />
229
- ),
230
- [
231
- expandedPaths,
232
- handleSelectFile,
233
- onPreviewFile,
234
- loadingDirectories,
235
- selectedPath,
236
- toggleDirectory,
237
- ],
189
+ return next;
190
+ });
191
+ };
192
+ const handleSelectFile = (path: string) => {
193
+ if (pendingSelectionTimeoutRef.current !== null) {
194
+ clearTimeout(pendingSelectionTimeoutRef.current);
195
+ }
196
+ setPendingSelection({
197
+ path,
198
+ selectedPathAtPress: controlledSelectedPath,
199
+ });
200
+ pendingSelectionTimeoutRef.current = setTimeout(() => {
201
+ pendingSelectionTimeoutRef.current = null;
202
+ setPendingSelection((current) => (current?.path === path ? null : current));
203
+ }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
204
+ onSelectFile(path);
205
+ };
206
+ const renderItem = ({ item }: { readonly item: VisibleFileTreeNode }) => (
207
+ <FileTreeRow
208
+ item={item}
209
+ selected={item.node.kind === "file" && item.node.path === selectedPath}
210
+ expanded={expandedPaths.has(item.node.path)}
211
+ loading={loadingDirectories.has(item.node.path)}
212
+ onPressDirectory={toggleDirectory}
213
+ onPreviewFile={onPreviewFile}
214
+ onPressFile={handleSelectFile}
215
+ />
216
);
217
240
- const extraData = useMemo(
241
- () => ({ expandedPaths, loadingDirectories, selectedPath }),
242
- [expandedPaths, loadingDirectories, selectedPath],
243
- );
218
+ const extraData = { expandedPaths, loadingDirectories, selectedPath };
219
220
// UIKit owns the header inset on every supported iOS version. Keep the
221
// list as direct screen content so automatic inset adjustment can find it.
apps/mobile/src/features/files/SourceFileSurface.tsx
+30
-40
@@ -1,7 +1,8 @@
1
+import { settlePromise } from "@t3tools/client-runtime/state/runtime";
2
import { useAtomValue } from "@effect/atom-react";
3
import { AsyncResult } from "effect/reactivity";
4
import type { ComponentType } from "react";
4
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+import { useEffect, useRef, useState } from "react";
6
import {
7
FlatList,
8
Platform,
@@ -49,7 +50,7 @@ interface SourceFileSurfaceProps {
50
51
type SourceHighlightStatus = "highlighting" | "ready" | "error";
52
52
-const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
53
+const HighlightedSourceLine = function HighlightedSourceLine(props: {
54
readonly codeSurface: ResolvedMobileCodeSurface;
55
readonly index: number;
56
readonly line: string;
@@ -124,20 +125,21 @@ const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
125
</NativeText>
126
</View>
127
);
127
-});
128
+};
129
130
function useSourceFileModel(props: SourceFileSurfaceProps) {
131
const { themeAppearance: theme } = useAppearancePreferences();
131
- const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]);
132
+ const document = prepareSourceFileDocument(props.contents);
133
const { contents: normalizedContents, lines, rowsJson } = document;
134
const targetIndex =
135
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
136
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
137
: null;
137
- const highlightAtom = useMemo(
138
- () => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
139
- [normalizedContents, props.path, theme],
140
- );
138
+ const highlightAtom = sourceHighlightAtom({
139
+ path: props.path,
140
+ contents: normalizedContents,
141
+ theme,
142
+ });
143
const highlightResult = useAtomValue(highlightAtom);
144
const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
145
const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
@@ -165,17 +167,15 @@ function SourceHighlightStatusView(props: { readonly status: SourceHighlightStat
167
168
function useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {
169
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
168
- const handlePullToRefresh = useCallback(async () => {
170
+ const handlePullToRefresh = async () => {
171
if (!onRefresh) {
172
return;
173
}
174
setIsPullRefreshing(true);
173
- try {
174
- await onRefresh();
175
- } finally {
176
- setIsPullRefreshing(false);
177
- }
178
- }, [onRefresh]);
175
+ // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
176
+ await settlePromise(async () => onRefresh());
177
+ setIsPullRefreshing(false);
178
+ };
179
return { isPullRefreshing, handlePullToRefresh };
180
}
181
@@ -194,16 +194,12 @@ function NativeSourceFileSurface(
194
const { width: viewportWidth } = useWindowDimensions();
195
const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
196
const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(onRefresh);
197
- const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
198
- const selectedRowIdsJson = useMemo(
199
- () => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
200
- [targetIndex],
201
- );
202
- const themeJson = useMemo(
203
- () => JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme)),
204
- [appTheme, themeAppearance, themeId],
197
+ const tokensJson = JSON.stringify(buildNativeSourceTokens(tokens));
198
+ const selectedRowIdsJson = JSON.stringify(
199
+ targetIndex === null ? [] : [nativeSourceRowId(targetIndex)],
200
);
206
- const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]);
201
+ const themeJson = JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme));
202
+ const styleJson = JSON.stringify(nativeSourceStyle);
203
const contentWidth = codeWordBreak
204
? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
205
: NATIVE_SOURCE_CONTENT_WIDTH;
@@ -243,10 +239,7 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
239
const foreground = useUniwindTheme()["--color-foreground"];
240
const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
241
const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
246
- const selectableTokens = useMemo(
247
- () => (props.selectable ? boundedSelectableSourceTokens(tokens) : null),
248
- [props.selectable, tokens],
249
- );
242
+ const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;
243
const listRef = useRef<FlatList<string>>(null);
244
const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
245
const refreshControl = props.onRefresh ? (
@@ -263,18 +256,15 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
256
return () => cancelAnimationFrame(frame);
257
}, [props.path, targetIndex]);
258
266
- const renderLine = useCallback(
267
- ({ item, index }: { item: string; index: number }) => (
268
- <HighlightedSourceLine
269
- codeSurface={codeSurface}
270
- index={index}
271
- line={item}
272
- tokens={tokens?.[index] ?? null}
273
- highlighted={index === targetIndex}
274
- wordBreak={codeWordBreak}
275
- />
276
- ),
277
- [codeSurface, codeWordBreak, targetIndex, tokens],
259
+ const renderLine = ({ item, index }: { item: string; index: number }) => (
260
+ <HighlightedSourceLine
261
+ codeSurface={codeSurface}
262
+ index={index}
263
+ line={item}
264
+ tokens={tokens?.[index] ?? null}
265
+ highlighted={index === targetIndex}
266
+ wordBreak={codeWordBreak}
267
+ />
268
);
269
270
// On iOS `uiTextView` renders a real `UITextView`, which selects across every line,
apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+120
-161
@@ -2,7 +2,7 @@ import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/files
2
import { environmentSession } from "../../state/session";
3
import { NativeStackScreenOptions } from "../../native/StackHeader";
4
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5
-import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
5
+import { useEffect, useId, useRef, useState } from "react";
6
import { Platform, View } from "react-native";
7
import { useSafeAreaInsets } from "react-native-safe-area-context";
8
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
@@ -442,7 +442,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
442
cwd: !canReadFiles || fileInspector.supported ? null : cwd,
443
searchQuery,
444
});
445
- const handleReturnToThread = useCallback(() => {
445
+ const handleReturnToThread = () => {
446
if (navigation.canGoBack()) {
447
navigation.goBack();
448
return;
@@ -455,57 +455,48 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
455
}),
456
);
457
}
458
- }, [environmentId, navigation, threadId]);
458
+ };
459
460
- const handleSelectFile = useCallback(
461
- (path: string) => {
462
- if (environmentId === null || threadId === null) {
463
- return;
464
- }
465
- const params = {
466
- environmentId: String(environmentId),
467
- threadId: String(threadId),
468
- path: path.split("/").filter((segment) => segment.length > 0),
469
- };
470
- const navigationAction = resolveFileSelectionNavigationAction({
471
- hasPersistentFileInspector: fileInspector.supported,
472
- });
473
- if (navigationAction === "replace") {
474
- navigation.dispatch(StackActions.replace("ThreadFile", params));
475
- return;
476
- }
477
- navigation.navigate("ThreadFile", params);
478
- },
479
- [environmentId, fileInspector.supported, navigation, threadId],
480
- );
481
- const renderInspector = useCallback(
482
- (headerInset: number) =>
483
- environmentId !== null && cwd !== null ? (
484
- <ThreadFileNavigatorPane
485
- cwd={cwd}
486
- environmentId={environmentId}
487
- headerInset={headerInset}
488
- projectName={projectName}
489
- selectedPath={null}
490
- onSelectFile={handleSelectFile}
491
- />
492
- ) : null,
493
- [cwd, environmentId, handleSelectFile, projectName],
494
- );
495
- const handlePreviewFile = useCallback(
496
- (relativePath: string) => {
497
- if (environmentId === null || cwd === null) {
498
- return;
499
- }
500
- preloadWorkspaceFileContents({
501
- cwd,
502
- environmentId,
503
- relativePath,
504
- theme: highlightTheme,
505
- });
506
- },
507
- [cwd, environmentId, highlightTheme],
508
- );
460
+ const handleSelectFile = (path: string) => {
461
+ if (environmentId === null || threadId === null) {
462
+ return;
463
+ }
464
+ const params = {
465
+ environmentId: String(environmentId),
466
+ threadId: String(threadId),
467
+ path: path.split("/").filter((segment) => segment.length > 0),
468
+ };
469
+ const navigationAction = resolveFileSelectionNavigationAction({
470
+ hasPersistentFileInspector: fileInspector.supported,
471
+ });
472
+ if (navigationAction === "replace") {
473
+ navigation.dispatch(StackActions.replace("ThreadFile", params));
474
+ return;
475
+ }
476
+ navigation.navigate("ThreadFile", params);
477
+ };
478
+ const renderInspector = (headerInset: number) =>
479
+ environmentId !== null && cwd !== null ? (
480
+ <ThreadFileNavigatorPane
481
+ cwd={cwd}
482
+ environmentId={environmentId}
483
+ headerInset={headerInset}
484
+ projectName={projectName}
485
+ selectedPath={null}
486
+ onSelectFile={handleSelectFile}
487
+ />
488
+ ) : null;
489
+ const handlePreviewFile = (relativePath: string) => {
490
+ if (environmentId === null || cwd === null) {
491
+ return;
492
+ }
493
+ preloadWorkspaceFileContents({
494
+ cwd,
495
+ environmentId,
496
+ relativePath,
497
+ theme: highlightTheme,
498
+ });
499
+ };
500
useEffect(() => {
501
if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
502
revealedInspectorRef.current = true;
@@ -630,45 +621,39 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
621
draftCwd: threadId === null ? cwd : null,
622
});
623
const assetPreviewUri = assetPreview._tag === "Success" ? assetPreview.url : null;
633
- const mediaSource = useMemo<MediaActionsSource | undefined>(
634
- () =>
635
- environmentId !== null &&
636
- relativePath !== null &&
637
- assetPreview.resource !== null &&
638
- "path" in assetPreview.resource &&
639
- typeof assetPreview.resource.path === "string" &&
640
- (isImageFile || isVideoFile)
641
- ? {
642
- reference: mediaFileReference(assetPreview.resource.path, cwd),
643
- name: basename(relativePath),
644
- mimeType:
645
- mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
646
- "application/octet-stream",
647
- environmentId,
648
- ...(threadId === null ? {} : { threadId }),
649
- resource: assetPreview.resource,
650
- }
651
- : undefined,
652
- [assetPreview.resource, cwd, environmentId, isImageFile, isVideoFile, relativePath, threadId],
653
- );
624
+ const mediaSource: MediaActionsSource | undefined =
625
+ environmentId !== null &&
626
+ relativePath !== null &&
627
+ assetPreview.resource !== null &&
628
+ "path" in assetPreview.resource &&
629
+ typeof assetPreview.resource.path === "string" &&
630
+ (isImageFile || isVideoFile)
631
+ ? {
632
+ reference: mediaFileReference(assetPreview.resource.path, cwd),
633
+ name: basename(relativePath),
634
+ mimeType:
635
+ mediaMimeTypeFromExtension(relativePath.slice(relativePath.lastIndexOf("."))) ??
636
+ "application/octet-stream",
637
+ environmentId,
638
+ ...(threadId === null ? {} : { threadId }),
639
+ resource: assetPreview.resource,
640
+ }
641
+ : undefined;
642
const mediaActions = useMediaActions(mediaSource);
655
- const videoSource = useMemo<MediaVideoPreviewSource | null>(
656
- () =>
657
- environmentId !== null &&
658
- relativePath !== null &&
659
- (assetPreview.resource?._tag === "media-file" ||
660
- assetPreview.resource?._tag === "draft-workspace-file")
661
- ? {
662
- type: "media",
663
- environmentId,
664
- resource: assetPreview.resource,
665
- name: basename(relativePath),
666
- mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
667
- actionsSource: mediaSource,
668
- }
669
- : null,
670
- [assetPreview.resource, environmentId, relativePath, mediaSource],
671
- );
643
+ const videoSource: MediaVideoPreviewSource | null =
644
+ environmentId !== null &&
645
+ relativePath !== null &&
646
+ (assetPreview.resource?._tag === "media-file" ||
647
+ assetPreview.resource?._tag === "draft-workspace-file")
648
+ ? {
649
+ type: "media",
650
+ environmentId,
651
+ resource: assetPreview.resource,
652
+ name: basename(relativePath),
653
+ mimeType: videoMimeType({ name: relativePath, mimeType: "" }) ?? "video/mp4",
654
+ actionsSource: mediaSource,
655
+ }
656
+ : null;
657
const previewUri =
658
assetPreviewUri === null || previewRevision === 0
659
? assetPreviewUri
@@ -707,59 +692,50 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
692
);
693
const fileData = fileQuery.data as ProjectReadFileResult | null;
694
710
- const handleSelectFile = useCallback(
711
- (path: string) => {
712
- const segments = path.split("/").filter(Boolean);
713
- // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
714
- // thread to resolve, so a draft stays on its own route and carries its workspace along.
715
- if (threadId === null) {
716
- navigation.dispatch(
717
- StackActions.push("NewTaskFile", {
718
- environmentId: String(environmentId),
719
- ...(cwd === null ? {} : { cwd }),
720
- projectName,
721
- path: segments,
722
- }),
723
- );
724
- return;
725
- }
726
- navigation.navigate("ThreadFile", {
727
- environmentId: String(environmentId),
728
- threadId: String(threadId),
729
- path: segments,
730
- });
731
- },
732
- [cwd, environmentId, navigation, projectName, threadId],
733
- );
734
- const renderInspector = useCallback(
735
- (headerInset: number) =>
736
- fileInspector.supported && environmentId !== null && cwd !== null ? (
737
- <ThreadFileNavigatorPane
738
- cwd={cwd}
739
- environmentId={environmentId}
740
- headerInset={headerInset}
741
- projectName={projectName}
742
- selectedPath={relativePath}
743
- onSelectFile={handleSelectFile}
744
- />
745
- ) : undefined,
746
- [cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
747
- );
695
+ const handleSelectFile = (path: string) => {
696
+ const segments = path.split("/").filter(Boolean);
697
+ // A draft has no thread. `ThreadFile` would stringify null and then wait forever for a
698
+ // thread to resolve, so a draft stays on its own route and carries its workspace along.
699
+ if (threadId === null) {
700
+ navigation.dispatch(
701
+ StackActions.push("NewTaskFile", {
702
+ environmentId: String(environmentId),
703
+ ...(cwd === null ? {} : { cwd }),
704
+ projectName,
705
+ path: segments,
706
+ }),
707
+ );
708
+ return;
709
+ }
710
+ navigation.navigate("ThreadFile", {
711
+ environmentId: String(environmentId),
712
+ threadId: String(threadId),
713
+ path: segments,
714
+ });
715
+ };
716
+ const renderInspector = (headerInset: number) =>
717
+ fileInspector.supported && environmentId !== null && cwd !== null ? (
718
+ <ThreadFileNavigatorPane
719
+ cwd={cwd}
720
+ environmentId={environmentId}
721
+ headerInset={headerInset}
722
+ projectName={projectName}
723
+ selectedPath={relativePath}
724
+ onSelectFile={handleSelectFile}
725
+ />
726
+ ) : undefined;
727
const safeAreaInsets = useSafeAreaInsets();
728
const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
750
- const renderWorkspaceInspector = useCallback(
751
- () => (
752
- <ThreadInspectorContentStack
753
- mode="files"
754
- resetKeys={[threadId, cwd]}
755
- renderFiles={() => renderInspector(inspectorHeaderInset)}
756
- />
757
- ),
758
- [cwd, inspectorHeaderInset, renderInspector, threadId],
729
+ const renderWorkspaceInspector = () => (
730
+ <ThreadInspectorContentStack
731
+ mode="files"
732
+ resetKeys={[threadId, cwd]}
733
+ renderFiles={() => renderInspector(inspectorHeaderInset)}
734
+ />
735
);
736
useRegisterWorkspaceInspector(fileInspector.supported ? renderWorkspaceInspector : undefined);
737
762
- const fileMenuActions = useMemo(() => {
738
+ const fileMenuActions = (() => {
739
if (relativePath === null) return [];
740
const canToggleMode = canPreview && !isImageFile && !isVideoFile && !isAudioFile;
741
return [
@@ -856,26 +832,9 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
832
} as const)
833
: null,
834
].filter((action) => action !== null);
859
- }, [
860
- appearance.codeWordBreak,
861
- setCodeWordBreak,
862
- assetPreviewUri,
863
- assetPreview.refresh,
864
- previewUri,
865
- canPreview,
866
- isAudioFile,
867
- isBrowserFile,
868
- isImageFile,
869
- isVideoFile,
870
- relativePath,
871
- resolvedActiveMode,
872
- mediaSource,
873
- mediaActions.actions,
874
- fileData?.contents,
875
- fileData?.truncated,
876
- ]);
877
-
878
- const handleReturnToThread = useCallback(() => {
835
+ })();
836
+
837
+ const handleReturnToThread = () => {
838
if (environmentId !== null && threadId !== null) {
839
navigation.dispatch(
840
StackActions.replace("Thread", {
@@ -884,14 +843,14 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {
843
}),
844
);
845
}
887
- }, [environmentId, navigation, threadId]);
888
- const handleBack = useCallback(() => {
846
+ };
847
+ const handleBack = () => {
848
if (navigation.canGoBack()) {
849
navigation.goBack();
850
return;
851
}
852
handleReturnToThread();
894
- }, [handleReturnToThread, navigation]);
853
+ };
854
855
if (environmentId === null || (threadId !== null && selectedThread === null)) {
856
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
apps/mobile/src/features/files/useFileTreeEntries.ts
+53
-69
@@ -1,7 +1,7 @@
1
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
2
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
3
import * as Cause from "effect/Cause";
4
-import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
4
+import { useEffect, useReducer, useRef, useState } from "react";
5
6
import { appAtomRegistry } from "../../state/atom-registry";
7
import { projectEnvironment } from "../../state/projects";
@@ -33,17 +33,14 @@ export function useFileTreeEntries(input: {
33
const [, render] = useReducer((value: number) => value + 1, 0);
34
const [entriesRevision, entriesChanged] = useReducer((value: number) => value + 1, 0);
35
const refreshVersion = useRef(0);
36
- const directories = useMemo(
37
- () => ({
38
- cwd,
39
- environmentId,
40
- entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
41
- requested: new Set<string>(),
42
- pending: new Map<string, AbortController>(),
43
- errors: new Map<string, string>(),
44
- }),
45
- [cwd, environmentId],
46
- );
36
+ const directories = {
37
+ cwd,
38
+ environmentId,
39
+ entries: new Map<string, ReadonlyArray<ProjectEntry>>(),
40
+ requested: new Set<string>(),
41
+ pending: new Map<string, AbortController>(),
42
+ errors: new Map<string, string>(),
43
+ };
44
const [refreshingDirectories, setRefreshingDirectories] = useState<typeof directories | null>(
45
null,
46
);
@@ -55,54 +52,51 @@ export function useFileTreeEntries(input: {
52
},
53
[directories],
54
);
58
- const loadDirectory = useCallback(
59
- (directoryPath: string, refresh = false) => {
60
- if (
61
- cwd === null ||
62
- environmentId === null ||
63
- (!refresh && directories.entries.has(directoryPath)) ||
64
- directories.pending.has(directoryPath)
65
- ) {
66
- return;
55
+ const loadDirectory = (directoryPath: string, refresh = false) => {
56
+ if (
57
+ cwd === null ||
58
+ environmentId === null ||
59
+ (!refresh && directories.entries.has(directoryPath)) ||
60
+ directories.pending.has(directoryPath)
61
+ ) {
62
+ return;
63
+ }
64
+ const controller = new AbortController();
65
+ directories.requested.add(directoryPath);
66
+ directories.pending.set(directoryPath, controller);
67
+ directories.errors.delete(directoryPath);
68
+ render();
69
+ const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
70
+ appAtomRegistry.refresh(atom);
71
+ return executeAtomQuery(appAtomRegistry, atom, {
72
+ signal: controller.signal,
73
+ reportFailure: false,
74
+ reportDefect: false,
75
+ }).then((result) => {
76
+ if (controller.signal.aborted) return;
77
+ directories.pending.delete(directoryPath);
78
+ if (result._tag === "Success") {
79
+ directories.entries.set(
80
+ directoryPath,
81
+ result.value.entries.filter(
82
+ (entry) =>
83
+ entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
84
+ ),
85
+ );
86
+ entriesChanged();
87
+ } else {
88
+ const error = Cause.squash(result.cause);
89
+ directories.errors.set(
90
+ directoryPath,
91
+ error instanceof Error ? error.message : "Files unavailable",
92
+ );
93
}
68
- const controller = new AbortController();
69
- directories.requested.add(directoryPath);
70
- directories.pending.set(directoryPath, controller);
71
- directories.errors.delete(directoryPath);
94
render();
73
- const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
74
- appAtomRegistry.refresh(atom);
75
- return executeAtomQuery(appAtomRegistry, atom, {
76
- signal: controller.signal,
77
- reportFailure: false,
78
- reportDefect: false,
79
- }).then((result) => {
80
- if (controller.signal.aborted) return;
81
- directories.pending.delete(directoryPath);
82
- if (result._tag === "Success") {
83
- directories.entries.set(
84
- directoryPath,
85
- result.value.entries.filter(
86
- (entry) =>
87
- entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
88
- ),
89
- );
90
- entriesChanged();
91
- } else {
92
- const error = Cause.squash(result.cause);
93
- directories.errors.set(
94
- directoryPath,
95
- error instanceof Error ? error.message : "Files unavailable",
96
- );
97
- }
98
- render();
99
- });
100
- },
101
- [cwd, directories, environmentId],
102
- );
95
+ });
96
+ };
97
const { refresh: refreshRoot, data: rootData } = root;
98
const { refresh: refreshSearch, data: searchData } = search;
105
- const snapshot = useMemo(() => {
99
+ const snapshot = (() => {
100
const merged = new Map<string, ProjectEntry>();
101
if (searching) {
102
for (const entry of searchData?.entries ?? []) merged.set(entry.path, entry);
@@ -126,9 +120,9 @@ export function useFileTreeEntries(input: {
120
? new Set((searchData?.entries ?? []).map((entry) => entry.path))
121
: null,
122
};
129
- }, [directories, entriesRevision, rootData, searchData, searching]);
123
+ })();
124
131
- const refresh = useCallback(() => {
125
+ const refresh = () => {
126
refreshRoot();
127
if (searching) refreshSearch();
128
const paths = new Set(
@@ -171,17 +165,7 @@ export function useFileTreeEntries(input: {
165
return Promise.all(work).finally(() => {
166
if (version === refreshVersion.current) setRefreshingDirectories(null);
167
});
174
- }, [
175
- cwd,
176
- debouncedQuery,
177
- environmentId,
178
- directories,
179
- loadDirectory,
180
- refreshRoot,
181
- refreshSearch,
182
- searching,
183
- snapshot.reachableDirectories,
184
- ]);
168
+ };
169
170
return {
171
entries: snapshot.entries,
apps/mobile/src/features/review/ReviewSheet.tsx
+87
-110
@@ -1,3 +1,5 @@
1
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
+import { AsyncResult } from "effect/reactivity";
3
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
5
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
@@ -9,13 +11,10 @@ import type { ReviewSectionItem } from "./reviewModel";
11
import { useReviewHeaderPresentation } from "./useReviewHeaderPresentation";
12
import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
13
import {
12
- memo,
14
type Ref,
15
type ReactElement,
15
- useCallback,
16
useEffect,
17
useImperativeHandle,
18
- useMemo,
18
useRef,
19
useState,
20
} from "react";
@@ -157,7 +156,7 @@ function ReviewHeader(
156
157
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
158
160
-const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
159
+const ReviewNotice = function ReviewNotice(props: { readonly notice: string }) {
160
return (
161
<View
162
className={cn(
@@ -169,7 +168,7 @@ const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string
168
<Text className="text-xs leading-normal text-warning-foreground">{props.notice}</Text>
169
</View>
170
);
172
-});
171
+};
172
173
function ReviewSelectionActionBar(props: {
174
readonly bottomInset: number;
@@ -241,15 +240,15 @@ interface ReviewNavigatorFile {
240
readonly deletions: number;
241
}
242
244
-const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: {
243
+const ReviewFileNavigatorRow = function ReviewFileNavigatorRow(props: {
244
readonly file: ReviewNavigatorFile;
245
readonly selected: boolean;
246
readonly onSelectFile: (fileId: string | null) => void;
247
}) {
248
const { file, selected, onSelectFile } = props;
250
- const handlePress = useCallback(() => {
249
+ const handlePress = () => {
250
onSelectFile(selected ? null : file.id);
252
- }, [file.id, onSelectFile, selected]);
251
+ };
252
253
return (
254
<Pressable
@@ -287,7 +286,7 @@ const ReviewFileNavigatorRow = memo(function ReviewFileNavigatorRow(props: {
286
</View>
287
</Pressable>
288
);
290
-});
289
+};
290
291
interface ReviewFileNavigatorHandle {
292
readonly setVisibleFile: (fileId: string | null) => void;
@@ -317,7 +316,7 @@ function ReviewFileNavigator({
316
readonly sectionId: string | null;
317
readonly fileId: string | null;
318
}>({ sectionId: null, fileId: null });
320
- const availableFileIds = useMemo(() => files.map((file) => file.id), [files]);
319
+ const availableFileIds = files.map((file) => file.id);
320
const selectedFileId = resolveSelectedReviewFileId({
321
selection: fileSelection,
322
sectionId,
@@ -342,23 +341,17 @@ function ReviewFileNavigator({
341
[availableFileIds, sectionId],
342
);
343
345
- const handleSelectFile = useCallback(
346
- (fileId: string | null) => {
347
- setFileSelection({ sectionId, fileId });
348
- onSelectFile(fileId);
349
- },
350
- [onSelectFile, sectionId],
351
- );
344
+ const handleSelectFile = (fileId: string | null) => {
345
+ setFileSelection({ sectionId, fileId });
346
+ onSelectFile(fileId);
347
+ };
348
353
- const renderFile = useCallback(
354
- ({ item }: { readonly item: ReviewNavigatorFile }) => (
355
- <ReviewFileNavigatorRow
356
- file={item}
357
- selected={selectedFileId === item.id}
358
- onSelectFile={handleSelectFile}
359
- />
360
- ),
361
- [handleSelectFile, selectedFileId],
349
+ const renderFile = ({ item }: { readonly item: ReviewNavigatorFile }) => (
350
+ <ReviewFileNavigatorRow
351
+ file={item}
352
+ selected={selectedFileId === item.id}
353
+ onSelectFile={handleSelectFile}
354
+ />
355
);
356
357
const fileList = (
@@ -509,14 +502,11 @@ export function ReviewSheet(props: ReviewSheetProps) {
502
const nativeReviewDiffViewRef = useRef<NativeReviewDiffViewHandle>(null);
503
const showcasedReviewDrawRef = useRef<string | null>(null);
504
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
512
- const handlePullToRefresh = useCallback(async () => {
505
+ const handlePullToRefresh = async () => {
506
setIsPullRefreshing(true);
514
- try {
515
- await refreshSelectedSection();
516
- } finally {
517
- setIsPullRefreshing(false);
518
- }
519
- }, [refreshSelectedSection]);
507
+ await refreshSelectedSection();
508
+ setIsPullRefreshing(false);
509
+ };
510
const reviewFileNavigatorRef = useRef<ReviewFileNavigatorHandle>(null);
511
const reviewFiles = parsedDiff.kind === "files" ? parsedDiff.files : [];
512
const fileVisibility = useReviewFileVisibility({
@@ -551,95 +541,82 @@ export function ReviewSheet(props: ReviewSheetProps) {
541
SHOWCASE_ENABLED && parsedDiff.kind === "files" && selectedSection
542
? `${reviewCache.threadKey}:${selectedSection.id}:${nativeBridge.tokensResetKey}:${nativeBridge.themeId}`
543
: null;
554
- const handleNativeDebug = useCallback(
555
- (event: NativeSyntheticEvent<Record<string, unknown>>) => {
556
- nativeBridge.onDebug(event);
557
- if (
558
- showcaseReviewKey === null ||
559
- showcasedReviewDrawRef.current === showcaseReviewKey ||
560
- !isNativeReviewDiffDrawEvent(event.nativeEvent)
561
- ) {
562
- return;
563
- }
564
- showcasedReviewDrawRef.current = showcaseReviewKey;
565
- reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });
566
- },
567
- [nativeBridge.onDebug, nativeBridge.themeId, showcaseReviewKey],
544
+ const handleNativeDebug = (event: NativeSyntheticEvent<Record<string, unknown>>) => {
545
+ nativeBridge.onDebug(event);
546
+ if (
547
+ showcaseReviewKey === null ||
548
+ showcasedReviewDrawRef.current === showcaseReviewKey ||
549
+ !isNativeReviewDiffDrawEvent(event.nativeEvent)
550
+ ) {
551
+ return;
552
+ }
553
+ showcasedReviewDrawRef.current = showcaseReviewKey;
554
+ reportShowcaseSceneRendered({ scene: "review", themeId: nativeBridge.themeId });
555
+ };
556
+
557
+ const handleSelectFile = async (fileId: string | null) => {
558
+ loadVisibleFile(fileId, true);
559
+ commentSelection.clearSelection();
560
+ if (fileId !== null && collapsedFileIds.includes(fileId)) {
561
+ toggleExpandedFile(fileId);
562
+ }
563
+ const nativeView = nativeReviewDiffViewRef.current;
564
+ if (!nativeView) return;
565
+ const result = await settlePromise(() =>
566
+ fileId === null ? nativeView.scrollToTop(true) : nativeView.scrollToFile(fileId, true),
567
+ );
568
+ if (AsyncResult.isFailure(result)) {
569
+ console.error("[review] Failed to navigate to diff file", squashAtomCommandFailure(result));
570
+ }
571
+ };
572
+ const handleVisibleFileChange = (
573
+ event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
574
+ ) => {
575
+ loadVisibleFile(event.nativeEvent.fileId ?? null);
576
+ reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
577
+ };
578
+ const renderInspector = () => (
579
+ <ReviewFileNavigator
580
+ ref={reviewFileNavigatorRef}
581
+ files={nativeReviewDiffData.files}
582
+ headerInset={insets.top}
583
+ sectionId={selectedSection?.id ?? null}
584
+ onSelectFile={(fileId) => void handleSelectFile(fileId)}
585
+ />
586
);
587
570
- const handleSelectFile = useCallback(
571
- (fileId: string | null) => {
588
+ const handleNativeToggleFile = (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
589
+ const { fileId } = event.nativeEvent;
590
+ if (fileId) {
591
loadVisibleFile(fileId, true);
573
- commentSelection.clearSelection();
574
- if (fileId !== null && collapsedFileIds.includes(fileId)) {
575
- toggleExpandedFile(fileId);
576
- }
577
- const navigation =
578
- fileId === null
579
- ? nativeReviewDiffViewRef.current?.scrollToTop(true)
580
- : nativeReviewDiffViewRef.current?.scrollToFile(fileId, true);
581
- void navigation?.catch((error: unknown) => {
582
- console.error("[review] Failed to navigate to diff file", error);
583
- });
584
- },
585
- [collapsedFileIds, commentSelection, toggleExpandedFile, loadVisibleFile],
586
- );
587
- const handleVisibleFileChange = useCallback(
588
- (event: NativeSyntheticEvent<{ readonly fileId?: string | null }>) => {
589
- loadVisibleFile(event.nativeEvent.fileId ?? null);
590
- reviewFileNavigatorRef.current?.setVisibleFile(event.nativeEvent.fileId ?? null);
591
- },
592
- [loadVisibleFile],
593
- );
594
- const renderInspector = useCallback(
595
- () => (
596
- <ReviewFileNavigator
597
- ref={reviewFileNavigatorRef}
598
- files={nativeReviewDiffData.files}
599
- headerInset={insets.top}
600
- sectionId={selectedSection?.id ?? null}
601
- onSelectFile={handleSelectFile}
602
- />
603
- ),
604
- [handleSelectFile, insets.top, nativeReviewDiffData.files, selectedSection?.id],
605
- );
606
-
607
- const handleNativeToggleFile = useCallback(
608
- (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
609
- const { fileId } = event.nativeEvent;
610
- if (fileId) {
611
- loadVisibleFile(fileId, true);
612
- toggleExpandedFile(fileId);
613
- }
614
- },
615
- [toggleExpandedFile, loadVisibleFile],
616
- );
617
-
618
- const handleNativeToggleViewedFile = useCallback(
619
- (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
620
- const { fileId } = event.nativeEvent;
621
- if (fileId) {
622
- toggleViewedFile(fileId);
623
- }
624
- },
625
- [toggleViewedFile],
626
- );
592
+ toggleExpandedFile(fileId);
593
+ }
594
+ };
595
+
596
+ const handleNativeToggleViewedFile = (
597
+ event: NativeSyntheticEvent<{ readonly fileId?: string }>,
598
+ ) => {
599
+ const { fileId } = event.nativeEvent;
600
+ if (fileId) {
601
+ toggleViewedFile(fileId);
602
+ }
603
+ };
604
605
const parsedDiffNotice =
606
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
607
const hasCachedSelectedDiff = selectedSection?.diff != null;
608
const hasAnyCachedDiff = reviewSections.some((section) => section.diff != null);
632
- const sectionMenu = useMemo(() => buildReviewSectionMenu(reviewSections), [reviewSections]);
609
+ const sectionMenu = buildReviewSectionMenu(reviewSections);
610
const { showConnectionNotice, showSectionToolbar } = resolveReviewAvailability({
611
hasEnvironmentPresentation: environment.isReady,
612
isEnvironmentConnected: isEnvironmentReady,
613
hasCachedSelectedDiff,
614
hasAnyCachedDiff,
615
});
639
- const handleRetryEnvironment = useCallback(() => {
616
+ const handleRetryEnvironment = () => {
617
void retryEnvironment(environmentId);
641
- }, [environmentId, retryEnvironment]);
642
- const handleReturnToThread = useCallback(() => {
618
+ };
619
+ const handleReturnToThread = () => {
620
if (navigation.canGoBack()) {
621
navigation.goBack();
622
return;
@@ -648,7 +625,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
625
environmentId: String(environmentId),
626
threadId: String(threadId),
627
});
651
- }, [environmentId, navigation, threadId]);
628
+ };
629
const androidHeaderSubtitle = [
630
selectedSection?.title,
631
headerDiffSummary.additions,
@@ -665,7 +642,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
642
useRegisterWorkspaceInspector(showChangedFilesPane ? renderInspector : undefined);
643
const showChangedFilesToggle = panes.supportsAuxiliaryPane && showChangedFilesPane;
644
668
- const listHeader = useMemo(() => {
645
+ const listHeader = (() => {
646
const children: ReactElement[] = [];
647
648
if (error) {
@@ -692,7 +669,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
669
}
670
671
return <>{children}</>;
695
- }, [error, parsedDiffNotice]);
672
+ })();
673
const headerSubtitle = [
674
headerDiffSummary.additions,
675
headerDiffSummary.deletions,
apps/mobile/src/features/review/reviewDiffRendering.tsx
+13
-4
@@ -103,11 +103,10 @@ export function DiffTokenText(props: {
103
}}
104
>
105
{(() => {
106
- let offset = 0;
106
+ const starts = tokenStartOffsets(props.tokens);
107
108
- return props.tokens.map((token) => {
109
- const start = offset;
110
- offset += token.content.length;
108
+ return props.tokens.map((token, index) => {
109
+ const start = starts[index]!;
110
111
const fontWeight =
112
token.fontStyle !== null && (token.fontStyle & 2) === 2
@@ -142,3 +141,13 @@ export function DiffTokenText(props: {
141
</NativeText>
142
);
143
}
144
+
145
+function tokenStartOffsets(tokens: ReadonlyArray<{ readonly content: string }>): number[] {
146
+ const starts: number[] = [];
147
+ let offset = 0;
148
+ for (const token of tokens) {
149
+ starts.push(offset);
150
+ offset += token.content.length;
151
+ }
152
+ return starts;
153
+}
apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+35
-34
@@ -1,3 +1,5 @@
1
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
+import { AsyncResult } from "effect/reactivity";
3
import { useEffect, useRef, useState } from "react";
4
5
import {
@@ -70,8 +72,8 @@ export function useNativeReviewDiffHighlighting(input: {
72
const engine: NativeReviewDiffHighlightEngine = "native";
73
74
void (async () => {
73
- try {
74
- const result = await highlightNativeReviewDiffVisibleRows({
75
+ const settled = await settlePromise(() =>
76
+ highlightNativeReviewDiffVisibleRows({
77
files,
78
rows,
79
scheme,
@@ -80,41 +82,40 @@ export function useNativeReviewDiffHighlighting(input: {
82
lastRowIndex: requestRange.lastRowIndex,
83
alreadyHighlightedRowIds: highlightedRowIdsRef.current,
84
signal: abortController.signal,
85
+ }),
86
+ );
87
+ if (abortController.signal.aborted) return;
88
+ if (AsyncResult.isFailure(settled)) {
89
+ logReviewDiffDiagnostic("native visible highlight failed", {
90
+ error: squashAtomCommandFailure(settled),
91
+ resetKey,
92
+ scheme,
93
+ firstRowIndex: requestRange.firstRowIndex,
94
+ lastRowIndex: requestRange.lastRowIndex,
95
});
96
+ return;
97
+ }
98
+ const result = settled.value;
99
+ if (result.rowCount === 0) return;
100
85
- if (abortController.signal.aborted || result.rowCount === 0) {
86
- return;
87
- }
88
-
89
- for (const rowId of Object.keys(result.tokensByRowId)) {
90
- highlightedRowIdsRef.current.add(rowId);
91
- }
92
-
93
- const chunkIndex = visibleChunkIndexRef.current;
94
- visibleChunkIndexRef.current += 1;
95
- setTokensPatchJson(
96
- JSON.stringify({
97
- resetKey,
98
- chunkIndex,
99
- fileId: "visible",
100
- filePath: "visible rows",
101
- language: "diff",
102
- lineCount: result.rowCount,
103
- durationMs: result.durationMs,
104
- tokensByRowId: result.tokensByRowId,
105
- }),
106
- );
107
- } catch (error) {
108
- if (!abortController.signal.aborted) {
109
- logReviewDiffDiagnostic("native visible highlight failed", {
110
- error,
111
- resetKey,
112
- scheme,
113
- firstRowIndex: requestRange.firstRowIndex,
114
- lastRowIndex: requestRange.lastRowIndex,
115
- });
116
- }
101
+ for (const rowId of Object.keys(result.tokensByRowId)) {
102
+ highlightedRowIdsRef.current.add(rowId);
103
}
104
+
105
+ const chunkIndex = visibleChunkIndexRef.current;
106
+ visibleChunkIndexRef.current += 1;
107
+ setTokensPatchJson(
108
+ JSON.stringify({
109
+ resetKey,
110
+ chunkIndex,
111
+ fileId: "visible",
112
+ filePath: "visible rows",
113
+ language: "diff",
114
+ lineCount: result.rowCount,
115
+ durationMs: result.durationMs,
116
+ tokensByRowId: result.tokensByRowId,
117
+ }),
118
+ );
119
})();
120
121
return () => abortController.abort();
apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
+9
-12
@@ -5,7 +5,7 @@ import {
5
UserProfileView,
6
} from "@clerk/expo/native-components";
7
import { StackActions, useNavigation } from "@react-navigation/native";
8
-import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
8
+import { useEffect, useLayoutEffect, useState } from "react";
9
import { View } from "react-native";
10
11
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -35,25 +35,22 @@ export function SettingsAuthRouteScreen() {
35
function ConfiguredSettingsAuthRouteScreen() {
36
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
37
const navigation = useNavigation();
38
- const handleHostBack = useCallback(
39
- () => navigation.dispatch(StackActions.popTo("SettingsContent")),
40
- [navigation],
41
- );
42
- const hasBeenSignedIn = useRef(isSignedIn);
43
- if (isSignedIn) {
44
- hasBeenSignedIn.current = true;
45
- }
38
+ const handleHostBack = () => navigation.dispatch(StackActions.popTo("SettingsContent"));
39
+ // Once signed in, stay on the profile view so signing out pops back instead of
40
+ // flashing the sign-in form.
41
+ const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true);
42
+ if (isSignedIn && !hasBeenSignedIn) setHasBeenSignedIn(true);
43
44
useEffect(() => {
48
- if (hasBeenSignedIn.current && isLoaded && isSignedIn === false) {
45
+ if (hasBeenSignedIn && isLoaded && isSignedIn === false) {
46
navigation.dispatch(StackActions.popTo("SettingsContent"));
47
}
51
- }, [isLoaded, isSignedIn, navigation]);
48
+ }, [hasBeenSignedIn, isLoaded, isSignedIn, navigation]);
49
50
return (
51
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
52
{isLoaded ? (
56
- hasBeenSignedIn.current ? (
53
+ hasBeenSignedIn ? (
54
<UserProfileView
55
customPages={USER_PROFILE_CUSTOM_PAGES}
56
isDismissible={false}
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+16
-30
@@ -26,15 +26,7 @@ import {
26
DEFAULT_WEBHOOK_PROMPT,
27
parseMaxDeliveryAge,
28
} from "@t3tools/client-runtime/scheduled-task-webhook";
29
-import {
30
- useCallback,
31
- useEffect,
32
- useLayoutEffect,
33
- useMemo,
34
- useRef,
35
- useState,
36
- type ReactNode,
37
-} from "react";
29
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
30
import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
31
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
32
import { AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";
@@ -266,20 +258,18 @@ function PickerRow(props: {
258
259
export function SettingsScheduledTasksRouteScreen() {
260
const [now, setNow] = useState(Date.now);
269
- useFocusEffect(
270
- useCallback(() => {
271
- const updateNow = () => setNow(Date.now());
272
- updateNow();
273
- const timer = setInterval(updateNow, 60_000);
274
- const subscription = AppState.addEventListener("change", (state) => {
275
- if (state === "active") updateNow();
276
- });
277
- return () => {
278
- clearInterval(timer);
279
- subscription.remove();
280
- };
281
- }, []),
282
- );
261
+ useFocusEffect(() => {
262
+ const updateNow = () => setNow(Date.now());
263
+ updateNow();
264
+ const timer = setInterval(updateNow, 60_000);
265
+ const subscription = AppState.addEventListener("change", (state) => {
266
+ if (state === "active") updateNow();
267
+ });
268
+ return () => {
269
+ clearInterval(timer);
270
+ subscription.remove();
271
+ };
272
+ });
273
const { availableTargets, selectedTargets, selectedProjectKey, projectGroups } =
274
useSettingsEnvironmentFilter();
275
const selectedGroup = projectGroups.find((group) => group.key === selectedProjectKey);
@@ -435,9 +425,8 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }
425
selection,
426
readDraftMessage: () => {
427
const current = readEditor();
438
- return current?.environmentId === editor?.environmentId
439
- ? (current?.draft.prompt ?? null)
440
- : null;
428
+ if (current?.environmentId !== editor?.environmentId) return null;
429
+ return current?.draft.prompt ?? null;
430
},
431
onChangeSelection: setSelection,
432
onChangeDraftMessage: (text) => {
@@ -586,10 +575,7 @@ function TaskForm({
575
);
576
const projects = useProjects().filter((project) => project.environmentId === environmentId);
577
const config = useEnvironmentServerConfig(environmentId);
589
- const modelOptions = useMemo(
590
- () => buildModelOptions(config, null, undefined, draft.projectId),
591
- [config, draft.projectId],
592
- );
578
+ const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
579
const canOperate = useAtomValue(
580
serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
581
);
apps/mobile/src/features/settings/components/SettingsDragHandle.tsx
+23
-22
@@ -1,4 +1,4 @@
1
-import { useEffect, useMemo, useRef } from "react";
1
+import { useEffectEvent, useState } from "react";
2
import { View } from "react-native";
3
import { Gesture, GestureDetector } from "react-native-gesture-handler";
4
@@ -13,28 +13,29 @@ export function SettingsDragHandle(props: {
13
readonly onEnd: (translation: number, cancelled: boolean) => void;
14
readonly onStep: (direction: "up" | "down") => void;
15
}) {
16
- const latest = useRef(props);
17
- useEffect(() => {
18
- latest.current = props;
19
- });
20
- const translation = useRef(0);
21
- const gesture = useMemo(
22
- () =>
23
- Gesture.Pan()
24
- .minDistance(0)
25
- .shouldCancelWhenOutside(false)
26
- .runOnJS(true)
27
- .onStart(() => {
28
- translation.current = 0;
29
- latest.current.onStart();
30
- })
31
- .onUpdate((event) => {
32
- translation.current = event.translationY;
33
- latest.current.onMove(event.translationY);
34
- })
35
- .onFinalize((_, success) => latest.current.onEnd(translation.current, !success)),
36
- [],
16
+ // Gesture callbacks fire outside render, so effect events give them the
17
+ // latest props while the gesture object itself stays stable.
18
+ const onStart = useEffectEvent(() => props.onStart());
19
+ const onMove = useEffectEvent((translation: number) => props.onMove(translation));
20
+ const onEnd = useEffectEvent((translation: number, cancelled: boolean) =>
21
+ props.onEnd(translation, cancelled),
22
);
23
+ const [gesture] = useState(() => {
24
+ let translation = 0;
25
+ return Gesture.Pan()
26
+ .minDistance(0)
27
+ .shouldCancelWhenOutside(false)
28
+ .runOnJS(true)
29
+ .onStart(() => {
30
+ translation = 0;
31
+ onStart();
32
+ })
33
+ .onUpdate((event) => {
34
+ translation = event.translationY;
35
+ onMove(event.translationY);
36
+ })
37
+ .onFinalize((_, success) => onEnd(translation, !success));
38
+ });
39
return (
40
<GestureDetector gesture={gesture}>
41
<View
apps/mobile/src/reactCompilerCoverage.test.ts
-12
@@ -27,12 +27,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {
27
"src/components/ui/OverlayPortal.tsx": "unsupported syntax",
28
"src/features/connection/ConnectionsNewRouteScreen.tsx": "try without catch",
29
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
30
- "src/features/files/AttachmentFileScreen.tsx": "manual memo not preserved",
31
- "src/features/files/FileMarkdownPreview.tsx": "try without catch",
32
- "src/features/files/FileTreeBrowser.tsx": "ref read during render",
33
- "src/features/files/SourceFileSurface.tsx": "try without catch",
34
- "src/features/files/ThreadFilesRouteScreen.tsx": "manual memo not preserved",
35
- "src/features/files/useFileTreeEntries.ts": "manual memo not preserved",
30
"src/features/home/HomeScreen.tsx": "ref read during render",
31
"src/features/home/WorkspaceConnectionTitle.tsx": "ref read during render",
32
"src/features/home/home-list-options.ts": "manual memo not preserved",
@@ -55,12 +49,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {
49
"src/features/pull-requests/usePullRequestListActions.ts": "throw inside try, try/finally",
50
"src/features/pull-requests/usePullRequestListControls.ts": "unsupported syntax",
51
"src/features/pull-requests/usePullRequestThreads.ts": "throw inside try, try/finally",
58
- "src/features/review/ReviewSheet.tsx": "try without catch",
59
- "src/features/review/reviewDiffRendering.tsx": "mutates a frozen value",
60
- "src/features/review/useNativeReviewDiffHighlighting.ts": "conditional inside try",
61
- "src/features/settings/SettingsAuthRouteScreen.tsx": "ref read during render",
62
- "src/features/settings/SettingsScheduledTasksRouteScreen.tsx": "unsupported syntax",
63
- "src/features/settings/components/SettingsDragHandle.tsx": "ref read during render",
52
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
53
"src/features/threads/NewTaskContextPickerScreens.tsx":
54
"manual memo not preserved, try without catch",
apps/mobile/uniwind-types.d.ts
+1
@@ -1,3 +1,4 @@
1
+// NOTE: This file is generated by uniwind and it should not be edited manually.
2
/// <reference types="uniwind/types" />
3
4
declare module 'uniwind' {