fix(files): load PDFs in browser previews #21095
MergedYash-Singh1(GitHub profile, opens in a new tab)merged 9 commits into
main fromrefs/pull/21095/headmerged by Yash-Singh1(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/mobile/src/components/PdfPreview.android.tsx line 53OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +33,21 @@33+ if (error) {34+ return (35+ <View className="flex-1 gap-4 bg-card">36+ <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>37+ <View className="items-center">38+ <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />39+ </View>40+ </View>41+ );42+ }43+ if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;44+45+ return (46+ <Pdf47+ source={{ uri: localUri }}48+ page={pdfInitialPage(props.uri)}49+ fitPolicy={0}50+ trustAllCerts={false}51+ enableAnnotationRendering52+ enableDoubleTapZoom53+ onError={() =>
- apps/web/src/pdfViewer/main.ts lines 30 to 31OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+const next = document.querySelector<HTMLButtonElement>("#next")!;12+const zoomOut = document.querySelector<HTMLButtonElement>("#zoom-out")!;13+const zoomIn = document.querySelector<HTMLButtonElement>("#zoom-in")!;14+const download = document.querySelector<HTMLAnchorElement>("#download")!;15+16+async function openPdf() {17+ const source = document.documentElement.hasAttribute("data-pdf-document")18+ ? location.href19+ : new URLSearchParams(location.search).get("file");20+ if (!source) throw new Error("No PDF was specified.");21+ const url = new URL(source, location.href);22+ // The client may be connected to another environment's signed asset URL.23+ if (!/^https?:$/.test(url.protocol) || !url.pathname.startsWith("/api/assets/")) {24+ throw new Error("This PDF URL is not an environment asset.");25+ }26+ download.href = url.href;27+ document.title = decodeURIComponent(url.pathname.split("/").at(-1) ?? "PDF viewer");28+ GlobalWorkerOptions.workerSrc = workerUrl;29+ const eventBus = new EventBus();30+ const linkService = new PDFLinkService({ eventBus });31+ const viewer = new PDFViewer({ container, eventBus, linkService });
github-actions[bot](GitHub profile, opens in a new tab) added labels📱 Native Change
- apps/server/src/preview/ServerBrowser.ts line 891Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -885,8 +887,6 @@885887 page.on("crash", () => dropTab(tab, true));886888 tabs.set(key, tab);887889 reportLiveTabs();888- // A popup is already loading its own URL, and the desktop loads its tab's.889- if (!adopted && !desktop && snapshot.navStatus._tag === "Loading") {890- tab.initialNavigation = page891- .goto(snapshot.navStatus.url, { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS })892- .then(constVoid);890+ // Desktop PDFs may start loading before interception attaches. Other desktop891+ // pages and popups keep their existing navigation.892+ if (apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx line 183Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -171,5 +174,10 @@171174 };172175173176 if (!snapshot) return null;177+ const pdfUrl =178+ snapshot.navStatus._tag === "Success"179+ ? previewPdfAssetUrl(snapshot.navStatus.url, httpBaseUrl)180+ : null;174181 const poppedOut = serverTab ? serverPictureInPicture : Boolean(desktopOverlay?.pictureInPicture);175- const canPopOut = serverTab ? supportsServerPictureInPicture() : true;182+ const canPopOut = serverTab183+ ? poppedOut || (pdfUrl === null && supportsServerPictureInPicture())patches/@react-navigation%2Fnative-stack@7.21.0.patch line 12OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1,10 +1,12 @@112-32435-6- function isFabric() {7- return 'nativeFabricUIManager' in global;4+5+ import { getDefaultHeaderHeight, getHeaderTitle, HeaderBackContext, HeaderHeightContext, HeaderShownContext, SafeAreaProviderCompat, useFrameSize } from '@react-navigation/elements';6+-import { NavigationProvider, StackActions, usePreventRemoveContext, useTheme } from '@react-navigation/native';7++import { NavigationContext, NavigationRouteContext, StackActions, usePreventRemoveContext, useTheme } from '@react-navigation/native';8+ import * as React from 'react';9+810 }911 +function SceneNavigationProvider({ presentationEnvelope, ...props }) {10-+ return presentationEnvelope ? props.children : /*#__PURE__*/_jsx(NavigationProvider, props);12++ return presentationEnvelope ? props.children : /*#__PURE__*/_jsx(NavigationContext.Provider, {
- apps/mobile/src/components/PdfPreview.android.tsx lines 50 to 61Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +36,21 @@36+ if (error) {37+ return (38+ <View className="flex-1 gap-4 bg-card">39+ <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>40+ <View className="items-center">41+ <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />42+ </View>43+ </View>44+ );45+ }46+ if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;47+48+ return (49+ <Pdf50+ source={{ uri: localUri }}51+ page={pdfInitialPage(props.uri)}52+ fitPolicy={0}53+ trustAllCerts={false}54+ enableAnnotationRendering55+ enableDoubleTapZoom56+ onError={() => {apps/server/src/preview/PdfDocumentNavigation.ts lines 51 to 53Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +18,21 @@18+ const { frameTree } = await cdp.send("Page.getFrameTree");19+ // The shell cannot open PDFs. Commit a document at the original URL so the20+ // client can embed its signed bytes while Back and Forward keep working.21+ cdp.on("Fetch.requestPaused", (event) => {22+ const { requestId, request, frameId } = event;23+ const proceed = () => cdp.send("Fetch.continueRequest", { requestId });24+ void (async () => {25+ if (26+ request.method !== "GET" ||27+ frameId !== frameTree.frame.id ||28+ !isPdfAssetUrl(request.url)29+ ) {30+ await proceed();31+ return;32+ }33+ const name = escapeHtml(34+ decodeURIComponent(new URL(request.url).pathname.split("/").at(-1) ?? "PDF"),35+ );36+ await cdp.send("Fetch.fulfillRequest", {37+ requestId,38+ responseCode: 200,packages/shared/src/preview.ts lines 8 to 34Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -4,2 +4,21 @@44 let nextPreviewTabSequence = 0;556+export function previewPdfAssetUrl(rawUrl: string, httpBaseUrl: string | null): string | null {7+ if (httpBaseUrl === null) return null;8+ try {9+ const url = new URL(rawUrl);10+ if (11+ (url.protocol !== "http:" && url.protocol !== "https:") ||12+ !url.pathname.startsWith("/api/assets/") ||13+ !/\.pdf$/i.test(url.pathname)14+ ) {15+ return null;16+ }17+ // The browser may run on the host's loopback address. Fetch signed bytes18+ // through this client's environment connection, including remote routes.19+ return new URL(`${url.pathname}${url.search}${url.hash}`, httpBaseUrl).href;20+ } catch {21+ return null;22+ }23+}24+
- packages/shared/src/preview.ts line 18OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3,3 +3,16 @@33 const TAB_ID_PREFIX = "tab_";44 let nextPreviewTabSequence = 0;556+export function previewPdfAssetUrl(rawUrl: string, httpBaseUrl: string | null): string | null {7+ if (httpBaseUrl === null) return null;8+ try {9+ const url = new URL(rawUrl);10+ const baseUrl = new URL(httpBaseUrl);11+ if (12+ (url.protocol !== "http:" && url.protocol !== "https:") ||13+ !url.pathname.startsWith("/api/assets/") ||14+ !/\.pdf$/i.test(url.pathname)15+ ) {16+ return null;17+ }18+ if (url.origin !== baseUrl.origin && !isLoopbackHost(url.hostname)) return url.href;
- apps/mobile/src/native/NativeHeaderToolbar.tsx line 256OutdatedResolvedby Yash-Singh1(GitHub profile, opens in a new tab)@@ -269,4 +251,6 @@269251 };270252 }, [navigation, props.placement, isTabActive]);271253272- return null;254+ return (255+ <NativeStackScreenOptions256+ optionsVersion={items}
Yash-Singh1(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed