Skip to content

Commit aaf10a1

Browse files
Merge remote-tracking branch 'origin/main' into t3/browser-search-engine-setting
# Conflicts: # apps/web/src/components/preview/PreviewView.tsx # packages/shared/src/preview.test.ts
2 parents adf7114 + 8ae53fd commit aaf10a1

141 files changed

Lines changed: 5006 additions & 1061 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/desktop/src/electron/ElectronProtocol.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,7 @@ describe("ElectronProtocol", () => {
322322
]);
323323
assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:", "http:", "https:"]);
324324
assert.deepEqual(directives["frame-src"], ["'self'", "blob:", "http:", "https:"]);
325+
assert.deepEqual(directives["object-src"], ["'self'", "blob:", "http:", "https:"]);
325326
assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]);
326327
});
327328
});

‎apps/desktop/src/electron/ElectronProtocol.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
9595
`font-src 'self' ${input.scheme}: data:`,
9696
"worker-src 'self' blob:",
9797
"frame-src 'self' blob: http: https:",
98+
"object-src 'self' blob: http: https:",
9899
"form-action 'self'",
99100
].join("; ");
100101
}

‎apps/desktop/src/preview/Manager.test.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1886,6 +1886,8 @@ describe("PreviewManager", () => {
18861886
const sendCommand = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(
18871887
async () => undefined,
18881888
);
1889+
const detachListeners = new Set<() => void>();
1890+
let chromiumDetaches = 0;
18891891
let destroyed = false;
18901892
const wc = {
18911893
id,
@@ -1914,19 +1916,30 @@ describe("PreviewManager", () => {
19141916
setIgnoreMenuShortcuts: vi.fn(),
19151917
setWindowOpenHandler: vi.fn(),
19161918
debugger: {
1917-
isAttached: () => attach.mock.calls.length > detach.mock.calls.length,
1919+
isAttached: () => attach.mock.calls.length > detach.mock.calls.length + chromiumDetaches,
19181920
attach,
19191921
detach,
19201922
sendCommand,
1921-
on: vi.fn(),
1922-
off: vi.fn(),
1923+
on: (event: string, listener: () => void) => {
1924+
if (event === "detach") detachListeners.add(listener);
1925+
},
1926+
off: (event: string, listener: () => void) => {
1927+
if (event === "detach") detachListeners.delete(listener);
1928+
},
19231929
},
19241930
};
1931+
/** Chromium dropping the debugger without a detach() call. */
1932+
const chromiumDetach = () => {
1933+
chromiumDetaches += 1;
1934+
// Snapshot like an EventEmitter, so a listener added during emit waits for the next one.
1935+
for (const listener of Array.from(detachListeners)) listener();
1936+
};
19251937
return {
19261938
wc: wc as unknown as Electron.WebContents,
19271939
attach,
19281940
detach,
19291941
sendCommand,
1942+
chromiumDetach,
19301943
destroy: () => {
19311944
destroyed = true;
19321945
listeners.get("destroyed")?.();
@@ -1965,6 +1978,24 @@ describe("PreviewManager", () => {
19651978
),
19661979
);
19671980

1981+
effectIt.effect("reattaches a debugger that Chromium dropped on its own", () =>
1982+
withManager((manager) =>
1983+
Effect.gen(function* () {
1984+
const guest = makeAttachingGuest(48);
1985+
fromId.mockReturnValue(guest.wc);
1986+
yield* manager.createTab("tab_detached");
1987+
yield* manager.registerWebview("tab_detached", 48);
1988+
yield* Effect.yieldNow;
1989+
expect(guest.attach).toHaveBeenCalledTimes(1);
1990+
1991+
guest.chromiumDetach();
1992+
yield* Effect.yieldNow;
1993+
yield* Effect.yieldNow;
1994+
expect(guest.attach).toHaveBeenCalledTimes(2);
1995+
}),
1996+
),
1997+
);
1998+
19681999
effectIt.effect("skips a guest destroyed while another guest's session opens", () =>
19692000
withManager((manager) =>
19702001
Effect.gen(function* () {

‎apps/desktop/src/preview/Manager.ts‎

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1023,13 +1023,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
10231023
copy.delete(webContentsId);
10241024
}),
10251025
]);
1026-
if (control) {
1027-
if (closedServerTab) browserHost.detach(closedServerTab);
1028-
for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) {
1029-
if (tab.webContentsId === webContentsId && tab.serverTab) browserHost.detach(tab.serverTab);
1026+
if (control) yield* releaseControlSession(control, closedServerTab);
1027+
});
1028+
1029+
// Closes a session already removed from `controlSessionsRef`. The server can
1030+
// only drive a tab while the desktop holds its debugger.
1031+
const releaseControlSession = Effect.fnUntraced(function* (
1032+
control: BrowserControlSession,
1033+
closedServerTab?: PreviewTabState["serverTab"],
1034+
) {
1035+
if (closedServerTab) browserHost.detach(closedServerTab);
1036+
for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) {
1037+
if (tab.webContentsId === control.webContentsId && tab.serverTab) {
1038+
browserHost.detach(tab.serverTab);
10301039
}
1031-
yield* Scope.close(control.scope, Exit.void).pipe(Effect.ignore);
10321040
}
1041+
yield* Scope.close(control.scope, Exit.void).pipe(Effect.ignore);
10331042
});
10341043

10351044
const ensureControlSession = Effect.fn("PreviewManager.ensureControlSession")(function* (
@@ -1141,23 +1150,36 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
11411150
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
11421151
runFork(handleDebuggerMessage(method, params));
11431152
};
1144-
yield* Scope.addFinalizer(
1145-
scope,
1146-
attempt({ operation: "detachControlSession", webContentsId: wc.id }, () => {
1147-
wcDebugger.off("message", onMessage);
1148-
if (wcDebugger.isAttached()) wcDebugger.detach();
1149-
}).pipe(Effect.ignore),
1150-
);
11511153
const control: BrowserControlSession = {
11521154
webContentsId: wc.id,
11531155
debugger: wcDebugger,
11541156
semaphore,
11551157
scope,
11561158
onMessage,
11571159
};
1160+
// Electron emits `detach` when Chromium closes the debugger session on its
1161+
// own. The cached session would then fail every command until the webview
1162+
// is replaced.
1163+
let dropped = false;
1164+
const onDetach = () => {
1165+
dropped = true;
1166+
runFork(recoverDetachedControlSession(wc, control));
1167+
};
1168+
// The listener comes off before detach() so a detach this manager requested
1169+
// never looks like a dropped one. A dropped session has nothing left to
1170+
// detach: `wc.debugger` is shared, so detaching here would hit a successor.
1171+
yield* Scope.addFinalizer(
1172+
scope,
1173+
attempt({ operation: "detachControlSession", webContentsId: wc.id }, () => {
1174+
wcDebugger.off("message", onMessage);
1175+
wcDebugger.off("detach", onDetach);
1176+
if (!dropped && wcDebugger.isAttached()) wcDebugger.detach();
1177+
}).pipe(Effect.ignore),
1178+
);
11581179
const initialize = Effect.fn("PreviewManager.initializeControlSession")(function* () {
11591180
yield* attempt({ operation: "attachDebuggerListeners", webContentsId: wc.id }, () => {
11601181
wcDebugger.on("message", onMessage);
1182+
wcDebugger.on("detach", onDetach);
11611183
wcDebugger.attach("1.3");
11621184
});
11631185
// Without this, dark-scheme pages with no background of their own (text/plain, e.g.
@@ -2356,6 +2378,30 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
23562378
}
23572379
}).pipe(Effect.ignore);
23582380

2381+
// Only the session that saw the detach is replaced: by the time the event is
2382+
// handled the guest may already hold a newer one, which must stay.
2383+
const recoverDetachedControlSession = Effect.fn("PreviewManager.recoverDetachedControlSession")(
2384+
function* (wc: Electron.WebContents, detached: BrowserControlSession) {
2385+
const removed = yield* SynchronizedRef.modify(controlSessionsRef, (sessions) =>
2386+
sessions.get(wc.id) === detached
2387+
? ([
2388+
true,
2389+
replaceMap(sessions, (copy) => {
2390+
copy.delete(wc.id);
2391+
}),
2392+
] as const)
2393+
: ([false, sessions] as const),
2394+
);
2395+
if (!removed) return;
2396+
yield* releaseControlSession(detached);
2397+
if (wc.isDestroyed()) return;
2398+
const tabId = yield* tabIdForWebContents(wc.id);
2399+
if (tabId === null) return;
2400+
yield* restoreControlSession(tabId, wc);
2401+
},
2402+
(recover) => Effect.ignore(recover),
2403+
);
2404+
23592405
const setColorScheme = Effect.fn("PreviewManager.setColorScheme")(function* (
23602406
tabId: string,
23612407
colorScheme: DesktopPreviewColorScheme,

‎apps/mobile/app.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ const config: ExpoConfig = {
317317
},
318318
plugins: [
319319
"expo-asset",
320+
"react-native-pdf-jsi",
320321
[
321322
"expo-font",
322323
{

‎apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,14 @@ public final class T3NativeControlsModule: Module {
5252
identifier: identifier, promise: promise)
5353
}.runOnQueue(.main)
5454

55-
AsyncFunction("presentFiles") { (urls: [URL], titles: [String], selectedIndex: Int, identifier: String, promise: Promise) in
56-
guard !urls.isEmpty, urls.count == titles.count, urls.indices.contains(selectedIndex) else {
55+
AsyncFunction("presentFiles") { (urls: [URL], titles: [String], selectedIndex: Int, sourceIdentifiers: [String], identifier: String, promise: Promise) in
56+
guard !urls.isEmpty, urls.count == titles.count, urls.count == sourceIdentifiers.count,
57+
urls.indices.contains(selectedIndex)
58+
else {
5759
throw URLError(.badURL)
5860
}
59-
let file = try self.makeFilePresentation(sourceIdentifier: "", identifier: identifier, promise: promise)
61+
let file = try self.makeFilePresentation(sourceIdentifiers: sourceIdentifiers, identifier: identifier,
62+
promise: promise)
6063
guard let presenter = self.appContext?.utilities?.currentViewController() else {
6164
file.dismiss()
6265
return
@@ -241,13 +244,13 @@ public final class T3NativeControlsModule: Module {
241244
if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
242245
}
243246

244-
private func makeFilePresentation(sourceIdentifier: String, identifier: String,
247+
private func makeFilePresentation(sourceIdentifiers: [String], identifier: String,
245248
promise: Promise) throws -> T3NativeFilePresentation {
246249
guard filePresentation == nil, videoPresentation == nil,
247250
appContext?.utilities?.currentViewController() != nil
248251
else { throw URLError(.cannotLoadFromNetwork) }
249252
let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
250-
sourceIdentifier: sourceIdentifier) { [weak self] error in
253+
sourceIdentifiers: sourceIdentifiers) { [weak self] error in
251254
self?.filePresentation = nil
252255
if let error { promise.reject(error) } else { promise.resolve(nil) }
253256
}
@@ -257,7 +260,7 @@ public final class T3NativeControlsModule: Module {
257260

258261
private func presentFile(url: URL, title: String, sourceIdentifier: String,
259262
identifier: String, promise: Promise) throws {
260-
let file = try makeFilePresentation(sourceIdentifier: sourceIdentifier, identifier: identifier, promise: promise)
263+
let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise)
261264
guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return }
262265
file.present(url: url, title: title, from: presenter)
263266
}

‎apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,17 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
2424
private var controller: UIViewController?
2525
private let completion: (Error?) -> Void
2626
private weak var sources: T3PresentationSources?
27-
private let sourceIdentifier: String
27+
private let sourceIdentifiers: [String]
2828
private var items: [FilePreviewItem] = []
2929
private var loading: Task<Void, Never>?
3030
private var dismissRequested = false
3131
private var finished = false
3232

33-
init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String, completion: @escaping (Error?) -> Void) {
33+
init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
34+
completion: @escaping (Error?) -> Void) {
3435
self.identifier = identifier
3536
self.sources = sources
36-
self.sourceIdentifier = sourceIdentifier
37+
self.sourceIdentifiers = sourceIdentifiers
3738
self.completion = completion
3839
super.init()
3940
}
@@ -107,14 +108,21 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
107108
items[index]
108109
}
109110

111+
private func sourceView(for item: QLPreviewItem) -> UIView? {
112+
guard !UIAccessibility.isReduceMotionEnabled,
113+
let index = items.firstIndex(where: { $0 === item }),
114+
sourceIdentifiers.indices.contains(index)
115+
else { return nil }
116+
return sources?.view(for: sourceIdentifiers[index])
117+
}
118+
110119
func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
111-
guard !UIAccessibility.isReduceMotionEnabled else { return nil }
112-
return sources?.view(for: sourceIdentifier)
120+
sourceView(for: item)
113121
}
114122

115123
func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem,
116124
inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect {
117-
guard !UIAccessibility.isReduceMotionEnabled, let source = sources?.view(for: sourceIdentifier) else { return .zero }
125+
guard let source = sourceView(for: item) else { return .zero }
118126
view.pointee = source
119127
return source.bounds
120128
}

‎apps/mobile/package.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
"@noble/curves": "catalog:",
5959
"@pierre/diffs": "catalog:",
6060
"@react-native-ai/apple": "0.12.0",
61+
"@react-native-async-storage/async-storage": "3.1.1",
6162
"@react-native-menu/menu": "^2.0.0",
6263
"@react-navigation/elements": "2.9.45",
6364
"@react-navigation/native": "7.5.1",
@@ -84,6 +85,7 @@
8485
"diff": "8.0.3",
8586
"effect": "catalog:",
8687
"expo": "58.0.14",
88+
"expo-application": "~58.1.2",
8789
"expo-asset": "~58.0.16",
8890
"expo-audio": "58.0.9",
8991
"expo-auth-session": "~58.0.13",
@@ -122,10 +124,13 @@
122124
"react": "catalog:",
123125
"react-dom": "catalog:",
124126
"react-native": "0.88.0",
127+
"react-native-blob-util": "0.25.1",
125128
"react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz",
126129
"react-native-gesture-handler": "~3.3.0",
127130
"react-native-image-viewing": "^0.2.2",
128131
"react-native-keyboard-controller": "1.22.7",
132+
"react-native-nitro-modules": "0.37.1",
133+
"react-native-pdf-jsi": "5.0.0",
129134
"react-native-reanimated": "4.7.1",
130135
"react-native-safe-area-context": "~5.10.1",
131136
"react-native-screens": "file:deps/react-native-screens-5.0.0-t3.27.tgz",

‎apps/mobile/src/components/FilePreview.ios.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const NativeControls = requireNativeModule<{
1515
uris: readonly string[],
1616
names: readonly string[],
1717
selectedIndex: number,
18+
sourceIdentifiers: readonly string[],
1819
identifier: string,
1920
): Promise<void>;
2021
dismissFile(identifier: string): Promise<void>;
@@ -44,6 +45,7 @@ function NativeFilePreview(props: {
4445
0,
4546
gallery.findIndex((item) => item.uri === uri),
4647
),
48+
gallery.map((item) => item.sourceIdentifier ?? ""),
4749
identifier,
4850
)
4951
: NativeControls.presentFile(uri, name ?? "Preview", sourceIdentifier ?? "", identifier);

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,43 @@ import * as Dialog from "./ui/Dialog";
22
import { useEffect, useEffectEvent } from "react";
33
import { Modal, Pressable, View } from "react-native";
44
import ImageViewing from "react-native-image-viewing";
5+
import { useSafeAreaInsets } from "react-native-safe-area-context";
56

67
import { openAttachmentInViewer } from "../lib/attachmentDownload";
78
import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
89
import { MediaImagePreview } from "./MediaImagePreview";
10+
import { PdfPreview } from "./PdfPreview";
11+
import { ControlPill } from "./ui/ControlPill";
912
import { AppText as Text } from "./ui/AppText";
1013

14+
function PdfDocumentPreview(props: {
15+
readonly source: ResolvedFilePreviewSource;
16+
readonly onRequestClose: () => void;
17+
}) {
18+
const insets = useSafeAreaInsets();
19+
return (
20+
<Modal
21+
animationType="slide"
22+
onRequestClose={props.onRequestClose}
23+
statusBarTranslucent
24+
navigationBarTranslucent
25+
>
26+
<View
27+
className="flex-1 bg-card"
28+
style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
29+
>
30+
<View className="flex-row items-center gap-3 border-b border-border px-4 py-2">
31+
<Text className="flex-1 font-t3-semibold text-foreground" numberOfLines={1}>
32+
{props.source.name ?? "PDF"}
33+
</Text>
34+
<ControlPill label="Close" variant="pill" onPress={props.onRequestClose} />
35+
</View>
36+
<PdfPreview uri={props.source.uri} />
37+
</View>
38+
</Modal>
39+
);
40+
}
41+
1142
function DocumentPreview(props: {
1243
readonly source: ResolvedFilePreviewSource;
1344
readonly onRequestClose: () => void;
@@ -71,6 +102,7 @@ export function FilePreview(props: {
71102
readonly onRequestClose: () => void;
72103
readonly onOpenError?: (error: unknown) => void;
73104
}) {
105+
if (props.source.kind === "pdf") return <PdfDocumentPreview {...props} />;
74106
if (props.source.kind !== "image") return <DocumentPreview {...props} />;
75107
if (props.source.actionsSource) return <MediaImagePreview {...props} />;
76108
return (

0 commit comments

Comments
 (0)