Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: improve mobile viewer ux
Marc Seitzf872bac416f5
diff --git a/components/view/dataroom/dataroom-document-view.tsx b/components/view/dataroom/dataroom-document-view.tsxindex 236ec9d5..9fc26f0a 100644--- a/components/view/dataroom/dataroom-document-view.tsx+++ b/components/view/dataroom/dataroom-document-view.tsx@@ -21,6 +21,10 @@ import AccessForm, {import EmailVerificationMessage from "../access-form/email-verification-form";import ViewData, { TViewDocumentData } from "../view-data";+import {+ DEFAULT_VIEWER_BACKGROUND_COLOR,+ ViewerThemeColor,+} from "../viewer-theme-color";import { DownloadOtpVerification } from "./download-otp-verification";type RowData = { [key: string]: any };@@ -143,6 +147,8 @@ export default function DataroomDocumentView({const [code, setCode] = useState<string | null>(null);const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);+ const viewerBackgroundColor =+ brand?.accentColor || DEFAULT_VIEWER_BACKGROUND_COLOR;// Set when the server requires inline OTP re-auth before granting access.const [uploadReauth, setUploadReauth] = useState<{@@ -335,16 +341,19 @@ export default function DataroomDocumentView({// Components to render when email is submitted but verification is pendingif (verificationRequested) {return (- <EmailVerificationMessage- onSubmitHandler={handleSubmit}- data={data}- isLoading={isLoading}- code={code}- setCode={setCode}- isInvalidCode={isInvalidCode}- setIsInvalidCode={setIsInvalidCode}- brand={brand}- />+ <>+ <ViewerThemeColor color={brand?.accentColor} />+ <EmailVerificationMessage+ onSubmitHandler={handleSubmit}+ data={data}+ isLoading={isLoading}+ code={code}+ setCode={setCode}+ isInvalidCode={isInvalidCode}+ setIsInvalidCode={setIsInvalidCode}+ brand={brand}+ />+ </>);}@@ -352,117 +361,129 @@ export default function DataroomDocumentView({// `handleSubmission` retries cleanly.if (uploadReauth) {return (- <div className="flex min-h-screen items-center justify-center bg-background px-4">- <div className="w-full max-w-sm space-y-4 rounded-lg border bg-card p-6 shadow-sm">- <div className="space-y-1">- <h1 className="text-lg font-semibold">{t("reauth.title", "Verify it's you")}</h1>- <p className="text-sm text-muted-foreground">- <Trans- ns="access-form"- i18nKey="reauth.description"- values={{ email: uploadReauth.email }}- components={{ email: <strong /> }}- />- </p>- </div>- <DownloadOtpVerification- linkId={link.id}- email={uploadReauth.email}- sendOtpOnMount- description={+ <>+ <ViewerThemeColor color={brand?.accentColor} />+ <div className="flex min-h-screen items-center justify-center bg-background px-4">+ <div className="w-full max-w-sm space-y-4 rounded-lg border bg-card p-6 shadow-sm">+ <div className="space-y-1">+ <h1 className="text-lg font-semibold">+ {t("reauth.title", "Verify it's you")}+ </h1><p className="text-sm text-muted-foreground"><Transns="access-form"- i18nKey="reauth.otpDescription"+ i18nKey="reauth.description"values={{ email: uploadReauth.email }}components={{ email: <strong /> }}/></p>- }- onVerified={() => {- setUploadReauth(null);- void handleSubmission();- }}- />+ </div>+ <DownloadOtpVerification+ linkId={link.id}+ email={uploadReauth.email}+ sendOtpOnMount+ description={+ <p className="text-sm text-muted-foreground">+ <Trans+ ns="access-form"+ i18nKey="reauth.otpDescription"+ values={{ email: uploadReauth.email }}+ components={{ email: <strong /> }}+ />+ </p>+ }+ onVerified={() => {+ setUploadReauth(null);+ void handleSubmission();+ }}+ />+ </div></div>- </div>+ </>);}- // If link is not submitted and does not have email / password protection, show the access formif (!submitted && isProtected) {return (- <AccessForm- data={data}- email={userEmail}- password={urlPasscode}- setData={setData}- onSubmitHandler={handleSubmit}- requireEmail={emailProtected}- requirePassword={!!linkPassword}- requireAgreement={enableAgreement!}- agreementId={link.agreement?.id}- agreementName={link.agreement?.name}- agreementContent={link.agreement?.content}- agreementContentType={link.agreement?.contentType}- signingProvider={link.agreement?.signingProvider}- requireName={link.agreement?.requireName}- isLoading={isLoading}- linkId={link.id}- disableEditEmail={disableEditEmail}- disableEditPassword={disableEditPassword}- useCustomAccessForm={useCustomAccessForm}- brand={brand}- customFields={link.customFields}- logoOnAccessForm={logoOnAccessForm}- />+ <>+ <ViewerThemeColor color={brand?.accentColor} />+ <AccessForm+ data={data}+ email={userEmail}+ password={urlPasscode}+ setData={setData}+ onSubmitHandler={handleSubmit}+ requireEmail={emailProtected}+ requirePassword={!!linkPassword}+ requireAgreement={enableAgreement!}+ agreementId={link.agreement?.id}+ agreementName={link.agreement?.name}+ agreementContent={link.agreement?.content}+ agreementContentType={link.agreement?.contentType}+ signingProvider={link.agreement?.signingProvider}+ requireName={link.agreement?.requireName}+ isLoading={isLoading}+ linkId={link.id}+ disableEditEmail={disableEditEmail}+ disableEditPassword={disableEditPassword}+ useCustomAccessForm={useCustomAccessForm}+ brand={brand}+ customFields={link.customFields}+ logoOnAccessForm={logoOnAccessForm}+ />+ </>);}if (isLoading) {return (- <div className="flex h-screen items-center justify-center">- <LoadingSpinner className="h-20 w-20" />- </div>- );- }- return (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- {submitted ? (- <ViewData- dataroomId={link.dataroomId!}- link={link}- document={link.dataroomDocument.document as TViewDocumentData}- viewData={viewData}- notionData={notionData}- brand={brand}- showPoweredByBanner={false}- showAccountCreationSlide={false}- useAdvancedExcelViewer={- viewData.useAdvancedExcelViewer ?? useAdvancedExcelViewer- }- viewerEmail={- viewData.viewerEmail ??- data.email ??- verifiedEmail ??- userEmail ??- undefined- }- canDownload={viewData.canDownload}- textSelectionEnabled={textSelectionEnabled}- previewToken={previewToken}- />- ) : (+ <>+ <ViewerThemeColor color={brand?.accentColor} /><div className="flex h-screen items-center justify-center"><LoadingSpinner className="h-20 w-20" /></div>- )}- </div>+ </>+ );+ }+ return (+ <>+ <ViewerThemeColor color={viewerBackgroundColor} />+ <div+ className="bg-gray-950"+ style={{+ backgroundColor: viewerBackgroundColor,+ }}+ >+ {submitted ? (+ <ViewData+ dataroomId={link.dataroomId!}+ link={link}+ document={link.dataroomDocument.document as TViewDocumentData}+ viewData={viewData}+ notionData={notionData}+ brand={brand}+ showPoweredByBanner={false}+ showAccountCreationSlide={false}+ useAdvancedExcelViewer={+ viewData.useAdvancedExcelViewer ?? useAdvancedExcelViewer+ }+ viewerEmail={+ viewData.viewerEmail ??+ data.email ??+ verifiedEmail ??+ userEmail ??+ undefined+ }+ canDownload={viewData.canDownload}+ textSelectionEnabled={textSelectionEnabled}+ previewToken={previewToken}+ />+ ) : (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ )}+ </div>+ </>);}diff --git a/components/view/dataroom/document-card.tsx b/components/view/dataroom/document-card.tsxindex 2c504680..b9dfc877 100644--- a/components/view/dataroom/document-card.tsx+++ b/components/view/dataroom/document-card.tsx@@ -142,16 +142,26 @@ export default function DocumentCard({}e.preventDefault();- // Open in new tab- if (domain && slug) {- window.open(`/${slug}/d/${document.dataroomDocumentId}`, "_blank");++ const targetUrl =+ domain && slug+ ? `/${slug}/d/${document.dataroomDocumentId}`+ : `/view/${linkId}/d/${document.dataroomDocumentId}${+ previewToken ? `?previewToken=${previewToken}&preview=1` : ""+ }`;++ // On mobile, navigate in the same tab. Opening a new tab there forces the+ // visitor to re-run the access form and juggle tabs to get back. Same-tab+ // navigation reuses the existing dataroom session; the nav "Home"+ // breadcrumb returns them to the dataroom. Desktop keeps new-tab so+ // multiple documents can be compared side by side. Read the breakpoint on+ // demand instead of subscribing every card to window resizes (a dataroom+ // with N documents would otherwise install N resize listeners).+ const isMobile = window.matchMedia("(max-width: 640px)").matches;+ if (isMobile) {+ router.push(targetUrl);} else {- window.open(- `/view/${linkId}/d/${document.dataroomDocumentId}${- previewToken ? `?previewToken=${previewToken}&preview=1` : ""- }`,- "_blank",- );+ window.open(targetUrl, "_blank");}};diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex f5ba9069..f9fb3703 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -19,6 +19,10 @@ import AccessForm, {import EmailVerificationMessage from "./access-form/email-verification-form";import ViewData, { TViewDocumentData } from "./view-data";+import {+ DEFAULT_VIEWER_BACKGROUND_COLOR,+ ViewerThemeColor,+} from "./viewer-theme-color";type RowData = { [key: string]: any };type SheetData = {@@ -129,6 +133,8 @@ export default function DocumentView({);const [code, setCode] = useState<string | null>(null);const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);+ const viewerBackgroundColor =+ brand?.accentColor || DEFAULT_VIEWER_BACKGROUND_COLOR;const handleSubmission = async (): Promise<void> => {setIsLoading(true);@@ -266,86 +272,97 @@ export default function DocumentView({// Components to render when email is submitted but verification is pendingif (verificationRequested) {return (- <EmailVerificationMessage- onSubmitHandler={handleSubmit}- data={data}- isLoading={isLoading}- code={code}- setCode={setCode}- isInvalidCode={isInvalidCode}- setIsInvalidCode={setIsInvalidCode}- brand={brand}- />+ <>+ <ViewerThemeColor color={brand?.accentColor} />+ <EmailVerificationMessage+ onSubmitHandler={handleSubmit}+ data={data}+ isLoading={isLoading}+ code={code}+ setCode={setCode}+ isInvalidCode={isInvalidCode}+ setIsInvalidCode={setIsInvalidCode}+ brand={brand}+ />+ </>);}- // If link is not submitted and does not have email / password protection, show the access form+ // If link is not submitted and is protected by email / password, show the access formif (!submitted && isProtected) {return (- <AccessForm- data={data}- email={userEmail}- password={urlPasscode}- setData={setData}- onSubmitHandler={handleSubmit}- requireEmail={emailProtected}- requirePassword={!!linkPassword}- requireAgreement={enableAgreement!}- agreementId={link.agreement?.id}- agreementName={link.agreement?.name}- agreementContent={link.agreement?.content}- agreementContentType={link.agreement?.contentType}- signingProvider={link.agreement?.signingProvider}- requireName={link.agreement?.requireName}- isLoading={isLoading}- brand={brand}- linkId={link.id}- disableEditEmail={disableEditEmail}- disableEditPassword={disableEditPassword}- useCustomAccessForm={useCustomAccessForm}- customFields={link.customFields}- logoOnAccessForm={logoOnAccessForm}- linkWelcomeMessage={link.welcomeMessage}- />+ <>+ <ViewerThemeColor color={brand?.accentColor} />+ <AccessForm+ data={data}+ email={userEmail}+ password={urlPasscode}+ setData={setData}+ onSubmitHandler={handleSubmit}+ requireEmail={emailProtected}+ requirePassword={!!linkPassword}+ requireAgreement={enableAgreement!}+ agreementId={link.agreement?.id}+ agreementName={link.agreement?.name}+ agreementContent={link.agreement?.content}+ agreementContentType={link.agreement?.contentType}+ signingProvider={link.agreement?.signingProvider}+ requireName={link.agreement?.requireName}+ isLoading={isLoading}+ brand={brand}+ linkId={link.id}+ disableEditEmail={disableEditEmail}+ disableEditPassword={disableEditPassword}+ useCustomAccessForm={useCustomAccessForm}+ customFields={link.customFields}+ logoOnAccessForm={logoOnAccessForm}+ linkWelcomeMessage={link.welcomeMessage}+ />+ </>);}if (isLoading) {return (- <div className="flex h-screen items-center justify-center">- <LoadingSpinner className="h-20 w-20" />- </div>+ <>+ <ViewerThemeColor color={brand?.accentColor} />+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ </>);}return (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- {submitted ? (- <ViewData- link={link}- viewData={viewData}- document={document as unknown as TViewDocumentData}- notionData={notionData}- brand={brand}- showPoweredByBanner={showPoweredByBanner}- showAccountCreationSlide={showAccountCreationSlide}- useAdvancedExcelViewer={useAdvancedExcelViewer}- viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}- annotationsEnabled={annotationsEnabled}- textSelectionEnabled={textSelectionEnabled}- previewToken={previewToken}- />- ) : (- <div className="flex h-screen items-center justify-center">- <LoadingSpinner className="h-20 w-20" />- </div>- )}- </div>+ <>+ <ViewerThemeColor color={viewerBackgroundColor} />+ <div+ className="bg-gray-950"+ style={{+ backgroundColor: viewerBackgroundColor,+ }}+ >+ {submitted ? (+ <ViewData+ link={link}+ viewData={viewData}+ document={document as unknown as TViewDocumentData}+ notionData={notionData}+ brand={brand}+ showPoweredByBanner={showPoweredByBanner}+ showAccountCreationSlide={showAccountCreationSlide}+ useAdvancedExcelViewer={useAdvancedExcelViewer}+ viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}+ annotationsEnabled={annotationsEnabled}+ textSelectionEnabled={textSelectionEnabled}+ previewToken={previewToken}+ />+ ) : (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ )}+ </div>+ </>);}diff --git a/components/view/nav.tsx b/components/view/nav.tsxindex 132b3add..a62efea2 100644--- a/components/view/nav.tsx+++ b/components/view/nav.tsx@@ -11,7 +11,7 @@ import {BadgeInfoIcon,Download,Maximize,- MessageCircle,+ Minimize,Slash,ZoomInIcon,ZoomOutIcon,@@ -84,6 +84,8 @@ export default function Nav({handleZoomIn,handleZoomOut,handleFullscreen,+ isFullscreen,+ hidePageCount,}: {navData: TNavData;type?: "pdf" | "notion" | "sheet";@@ -94,6 +96,8 @@ export default function Nav({handleZoomIn?: () => void;handleZoomOut?: () => void;handleFullscreen?: () => void;+ isFullscreen?: boolean;+ hidePageCount?: boolean;}) {const router = useRouter();const asPath = router.asPath;@@ -134,7 +138,8 @@ export default function Nav({const { t } = useTranslation("viewer");const [showConversations, setShowConversations] = useState(false);- const navColorPalette = createAdaptiveSurfacePalette(brand?.brandColor);+ const brandColor = brand?.brandColor || "black";+ const navColorPalette = createAdaptiveSurfacePalette(brandColor);const ctaLabel = (brand as { ctaLabel?: string | null } | null | undefined)?.ctaLabel;@@ -229,9 +234,9 @@ export default function Nav({return (<navdata-viewer-top-bar- className="bg-black transition-[margin] duration-300 ease-in-out"+ className="transition-[margin] duration-300 ease-in-out"style={{- backgroundColor: brand && brand.brandColor ? brand.brandColor : "black",+ backgroundColor: brandColor,// The chat / Q&A panel shifts the content by padding the parent// (transition-all duration-300). We cancel that padding with a// matching-easing negative margin so the navbar stays full-width and@@ -240,6 +245,14 @@ export default function Nav({isChatOpen || isConversationSidebarOpen ? "-400px" : undefined,}}>+ <div+ aria-hidden="true"+ className="pointer-events-none fixed inset-x-0 top-0 z-[80]"+ style={{+ height: "env(safe-area-inset-top, 0px)",+ backgroundColor: brandColor,+ }}+ /><div className="mx-auto px-2 sm:px-6 lg:px-8"><div className="relative flex h-16 items-center justify-between"><div className="flex flex-1 items-center justify-start">@@ -257,7 +270,8 @@ export default function Nav({<Linkhref={`https://www.papermark.com?utm_campaign=navbar&utm_medium=navbar&utm_source=papermark-${linkId}`}target="_blank"- className="text-2xl font-bold tracking-tighter text-white"+ className="text-2xl font-bold tracking-tighter"+ style={{ color: navColorPalette.textColor }}>Papermark</Link>@@ -396,6 +410,33 @@ export default function Nav({</Button>) : null}+ {/* Mobile controls: pinch is the primary zoom gesture (pinch back+ out to fit), so the top bar exposes only a fullscreen toggle.+ Keeping the bar sparse avoids overflow on narrow screens. */}+ {isMobile && handleFullscreen && (+ <Button+ onClick={handleFullscreen}+ className="size-8 bg-gray-900 text-white hover:bg-gray-900/80"+ size="icon"+ title={+ isFullscreen+ ? t("nav.exitFullscreen", "Exit fullscreen")+ : t("nav.fullscreen", "Fullscreen")+ }+ aria-label={+ isFullscreen+ ? t("nav.exitFullscreen", "Exit fullscreen")+ : t("nav.fullscreen", "Fullscreen")+ }+ >+ {isFullscreen ? (+ <Minimize className="h-4 w-4" />+ ) : (+ <Maximize className="h-4 w-4" />+ )}+ </Button>+ )}+{!isMobile && handleZoomIn && handleZoomOut && (<div className="flex gap-1"><TooltipProvider delayDuration={50}>@@ -450,13 +491,24 @@ export default function Nav({onClick={handleFullscreen}className="bg-gray-900 text-white hover:bg-gray-900/80"size="icon"+ aria-label={+ isFullscreen+ ? t("nav.exitFullscreen", "Exit fullscreen")+ : t("nav.fullscreen", "Fullscreen")+ }>- <Maximize className="h-5 w-5" />+ {isFullscreen ? (+ <Minimize className="h-5 w-5" />+ ) : (+ <Maximize className="h-5 w-5" />+ )}</Button></TooltipTrigger><TooltipContent><span className="mr-2 text-xs">- {t("nav.fullscreen", "Fullscreen")}+ {isFullscreen+ ? t("nav.exitFullscreen", "Exit fullscreen")+ : t("nav.fullscreen", "Fullscreen")}</span><span className="ml-auto rounded-sm border bg-muted p-0.5 text-xs tracking-widest text-muted-foreground">F@@ -468,7 +520,7 @@ export default function Nav({</div>)}- {pageNumber && numPages && numPages > 1 ? (+ {!hidePageCount && pageNumber && numPages && numPages > 1 ? (<div className="flex h-8 items-center space-x-1 rounded-md bg-gray-900 px-3 py-1.5 text-xs font-medium text-white sm:h-10 sm:px-4 sm:py-2 sm:text-sm"><span style={{ fontVariantNumeric: "tabular-nums" }}>{pageNumber}diff --git a/components/view/viewer-theme-color.tsx b/components/view/viewer-theme-color.tsxnew file mode 100644index 00000000..0d409977--- /dev/null+++ b/components/view/viewer-theme-color.tsx@@ -0,0 +1,35 @@+import Head from "next/head";++import { useEffect } from "react";++export const DEFAULT_VIEWER_BACKGROUND_COLOR = "rgb(3, 7, 18)";++export function ViewerThemeColor({+ color,+}: {+ color?: string | null;+}) {+ const themeColor = color || DEFAULT_VIEWER_BACKGROUND_COLOR;++ useEffect(() => {+ const html = document.documentElement;+ const body = document.body;++ const prevHtmlBg = html.style.backgroundColor;+ const prevBodyBg = body.style.backgroundColor;++ html.style.backgroundColor = themeColor;+ body.style.backgroundColor = themeColor;++ return () => {+ html.style.backgroundColor = prevHtmlBg;+ body.style.backgroundColor = prevBodyBg;+ };+ }, [themeColor]);++ return (+ <Head>+ <meta name="theme-color" content={themeColor} key="theme-color" />+ </Head>+ );+}diff --git a/components/view/viewer/download-only-viewer.tsx b/components/view/viewer/download-only-viewer.tsxindex 13fe995d..9485161e 100644--- a/components/view/viewer/download-only-viewer.tsx+++ b/components/view/viewer/download-only-viewer.tsx@@ -68,10 +68,10 @@ export default function DownloadOnlyViewer({);};- if (router.query.token) {+ if (router.isReady && router.query.token) {removeQueryParams(["token", "email", "domain", "slug", "linkId"]);}- }, []);+ }, [router, router.isReady]);useEffect(() => {const handleVisibilityChange = () => {diff --git a/components/view/viewer/fullscreen-controls.tsx b/components/view/viewer/fullscreen-controls.tsxnew file mode 100644index 00000000..4f9b62f0--- /dev/null+++ b/components/view/viewer/fullscreen-controls.tsx@@ -0,0 +1,51 @@+import { Minimize, RotateCw } from "lucide-react";+import { useTranslation } from "react-i18next";++import { cn } from "@/lib/utils";++export function FullscreenControls({+ controlsVisible = true,+ showRotate = false,+ onRotate,+ onExit,+ className,+}: {+ controlsVisible?: boolean;+ showRotate?: boolean;+ onRotate?: () => void;+ onExit: () => void;+ className?: string;+}) {+ const { t } = useTranslation("viewer");++ return (+ <div+ className={cn(+ "absolute right-3 top-3 z-[70] flex items-center gap-2 transition-opacity duration-300",+ controlsVisible ? "opacity-100" : "pointer-events-none opacity-0",+ className,+ )}+ >+ {showRotate && onRotate ? (+ <button+ type="button"+ onClick={onRotate}+ aria-label={t("fullscreenControls.rotate")}+ title={t("fullscreenControls.rotate")}+ className="rounded-full bg-gray-950/50 p-2 text-white shadow-lg backdrop-blur"+ >+ <RotateCw className="size-5" />+ </button>+ ) : null}+ <button+ type="button"+ onClick={onExit}+ aria-label={t("fullscreenControls.exitFullscreen")}+ title={t("fullscreenControls.exitFullscreen")}+ className="rounded-full bg-gray-950/50 p-2 text-white shadow-lg backdrop-blur"+ >+ <Minimize className="size-5" />+ </button>+ </div>+ );+}diff --git a/components/view/viewer/horizontal-page-content.tsx b/components/view/viewer/horizontal-page-content.tsxnew file mode 100644index 00000000..04cfed6d--- /dev/null+++ b/components/view/viewer/horizontal-page-content.tsx@@ -0,0 +1,205 @@+import type { MouseEvent, MutableRefObject } from "react";++import { getContainedImageRect } from "@/lib/hooks/use-fullscreen";+import { WatermarkConfig } from "@/lib/types";+import { getSafeLinkHref } from "@/lib/utils/sanitize-link-href";++import { SVGWatermark } from "../watermark-svg";++export type HorizontalViewerPage = {+ file: string | null;+ pageNumber: string;+ embeddedLinks: string[];+ pageLinks: {+ href: string;+ coords: string;+ isInternal?: boolean;+ targetPage?: number;+ }[];+ metadata: { width: number; height: number; scaleFactor: number };+};++type PageDimensions = Record<number, { width: number; height: number }>;++const scaleCoordinates = (coords: string, scaleFactor: number) => {+ return coords+ .split(",")+ .map((coord) => parseFloat(coord) * scaleFactor)+ .join(",");+};++export function HorizontalPageContent({+ page,+ index,+ imgHeight,+ imgMaxHeight,+ imgMaxWidth,+ watermarkConfig,+ viewerEmail,+ linkName,+ ipAddress,+ imageDimensions,+ imageRefs,+ getScaleFactor,+ onImageDimensionsChange,+ onLinkClick,+}: {+ page: HorizontalViewerPage;+ index: number;+ imgHeight?: string;+ imgMaxHeight: string;+ imgMaxWidth?: string;+ watermarkConfig?: WatermarkConfig | null;+ viewerEmail?: string;+ linkName?: string;+ ipAddress?: string;+ imageDimensions: PageDimensions;+ imageRefs: MutableRefObject<(HTMLImageElement | null)[]>;+ getScaleFactor: ({+ naturalHeight,+ scaleFactor,+ }: {+ naturalHeight: number;+ scaleFactor: number;+ }) => number;+ onImageDimensionsChange: (+ index: number,+ dimensions: { width: number; height: number },+ ) => void;+ onLinkClick: (href: string, event: MouseEvent<HTMLAreaElement>) => void;+}) {+ const watermarkBox = imageDimensions[index];+ const watermarkRect =+ watermarkConfig && watermarkBox+ ? getContainedImageRect(+ watermarkBox.width,+ watermarkBox.height,+ page.metadata.height > 0+ ? page.metadata.width / page.metadata.height+ : 0,+ )+ : null;++ return (+ <div className="relative w-fit">+ <img+ className="viewer-image-mobile !pointer-events-auto object-contain"+ style={{+ height: imgHeight,+ maxHeight: imgMaxHeight,+ maxWidth: imgMaxWidth,+ }}+ onContextMenu={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ ref={(ref) => {+ imageRefs.current[index] = ref;+ if (ref) {+ ref.onload = () =>+ onImageDimensionsChange(index, {+ width: ref.clientWidth,+ height: ref.clientHeight,+ });+ }+ }}+ useMap={`#page-map-${index + 1}`}+ src={page.file || "https://www.papermark.com/_static/blank.gif"}+ alt={`Page ${index + 1}`}+ />++ {watermarkConfig && watermarkRect ? (+ <div+ className="pointer-events-none absolute"+ style={{ left: watermarkRect.left, top: watermarkRect.top }}+ >+ <SVGWatermark+ config={watermarkConfig}+ viewerData={{+ email: viewerEmail,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ link: linkName,+ ipAddress,+ }}+ documentDimensions={{+ width: watermarkRect.width,+ height: watermarkRect.height,+ }}+ pageIndex={index}+ />+ </div>+ ) : null}++ {page.pageLinks ? (+ <map name={`page-map-${index + 1}`}>+ {page.pageLinks+ .filter((link) => !link.href.endsWith(".gif"))+ .map((link, linkIndex) => {+ const safeHref = getSafeLinkHref(link.href);+ if (!safeHref) {+ return null;+ }+ const isInternal = safeHref.startsWith("#");+ return (+ <area+ key={linkIndex}+ shape="rect"+ coords={scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ }),+ )}+ href={safeHref}+ onClick={(event) => onLinkClick(safeHref, event)}+ target={isInternal ? "_self" : "_blank"}+ rel={isInternal ? undefined : "noopener noreferrer"}+ />+ );+ })}+ </map>+ ) : null}++ {page.pageLinks && imageDimensions[index]+ ? page.pageLinks+ .filter((link) => link.href.endsWith(".gif"))+ .map((link, linkIndex) => {+ const [x1, y1, x2, y2] = scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ }),+ )+ .split(",")+ .map(Number);++ const overlayWidth = x2 - x1;+ const overlayHeight = y2 - y1;+ const containerWidth =+ imageRefs.current[index]?.parentElement?.clientWidth || 0;+ const imageWidth = imageDimensions[index].width;+ const leftOffset = (containerWidth - imageWidth) / 2;++ return (+ <img+ key={`overlay-${index}-${linkIndex}`}+ src={link.href}+ alt={`Overlay ${index + 1}`}+ style={{+ position: "absolute",+ top: y1,+ left: x1 + leftOffset,+ width: `${overlayWidth}px`,+ height: `${overlayHeight}px`,+ pointerEvents: "none",+ }}+ />+ );+ })+ : null}+ </div>+ );+}diff --git a/components/view/viewer/image-viewer.tsx b/components/view/viewer/image-viewer.tsxindex 2cfb6878..f15530da 100644--- a/components/view/viewer/image-viewer.tsx+++ b/components/view/viewer/image-viewer.tsx@@ -1,10 +1,22 @@import { useRouter } from "next/router";import { useEffect, useRef, useState } from "react";-import React from "react";import { ConfidentialViewOverlay } from "@/ee/features/permissions/components/confidential-view/confidential-view-overlay";-+import {+ ReactZoomPanPinchRef,+ TransformComponent,+ TransformWrapper,+} from "react-zoom-pan-pinch";++import { useAutoHideControls } from "@/lib/hooks/use-auto-hide-controls";+import { useDisablePullToRefresh } from "@/lib/hooks/use-disable-pull-to-refresh";+import {+ getContainedImageRect,+ getRotationLayerStyle,+ useFullscreen,+} from "@/lib/hooks/use-fullscreen";+import { useViewerKeyboardShortcuts } from "@/lib/hooks/use-viewer-keyboard-shortcuts";import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { WatermarkConfig } from "@/lib/types";@@ -13,8 +25,10 @@ import { cn } from "@/lib/utils";import { ScreenProtector } from "../ScreenProtection";import Nav, { TNavData } from "../nav";import { PoweredBy } from "../powered-by";+import { ViewerThemeColor } from "../viewer-theme-color";import { SVGWatermark } from "../watermark-svg";import { AwayPoster } from "./away-poster";+import { FullscreenControls } from "./fullscreen-controls";import "@/styles/custom-viewer-styles.css";@@ -43,19 +57,43 @@ export default function ImageViewer({}) {const router = useRouter();- const { isMobile, isPreview, linkId, documentId, viewId, dataroomId } =+ const { isMobile, isPreview, linkId, documentId, viewId, dataroomId, brand } =navData;+ // Viewer's chosen background color; fills the fullscreen letterbox and tints+ // the browser chrome instead of a hard black.+ const viewerBackgroundColor = brand?.accentColor || "rgb(3, 7, 18)";++ const {+ isFullscreen,+ isPseudoFullscreen,+ toggleFullscreen,+ rotation,+ rotate,+ } = useFullscreen();++ useDisablePullToRefresh(!!isMobile);++ // In fullscreen the overlay controls fade after a few seconds; a tap anywhere+ // reveals them again.+ const { visible: controlsVisible, reveal: revealControls } =+ useAutoHideControls({ active: isFullscreen });+const numPages = 1;const pageNumber = 1;const [scale, setScale] = useState<number>(1);+ const [isZoomed, setIsZoomed] = useState<boolean>(false);const [isWindowFocused, setIsWindowFocused] = useState(true);const startTimeRef = useRef(Date.now());- const visibilityRef = useRef<boolean>(true);const containerRef = useRef<HTMLDivElement>(null);+ const scrollContainerRef = useRef<HTMLDivElement>(null);+ const transformRef = useRef<ReactZoomPanPinchRef | null>(null);const imageRefs = useRef<HTMLImageElement | null>(null);+ // Natural aspect ratio of the loaded image, used to size the watermark to the+ // visible (object-contain) image rather than the letterboxed element box.+ const imageAspectRef = useRef<number>(0);const trackingOptions = getTrackingOptions();const {@@ -76,59 +114,46 @@ export default function ImageViewer({height: number;} | null>(null);- // Add zoom handlers+ // Desktop drives the CSS `scale`; mobile delegates to react-zoom-pan-pinch+ // for focal-point-correct pinch and pan.const handleZoomIn = () => {- setScale((prev) => Math.min(prev + 0.25, 3)); // Max zoom 3x+ if (isMobile) {+ transformRef.current?.zoomIn();+ return;+ }+ setScale((prev) => Math.min(prev + 0.25, 3));};const handleZoomOut = () => {- setScale((prev) => Math.max(prev - 0.25, 0.5)); // Min zoom 0.5x+ if (isMobile) {+ transformRef.current?.zoomOut();+ return;+ }+ setScale((prev) => Math.max(prev - 0.25, 0.5));};- // Add fullscreen handler- const handleFullscreen = () => {- if (!document.fullscreenElement) {- document.documentElement.requestFullscreen().catch((err) => {- console.error("Error attempting to enable fullscreen:", err);- });- } else {- document.exitFullscreen();+ const handleResetZoom = () => {+ if (isMobile) {+ transformRef.current?.resetTransform();+ return;}+ setScale(1);};- // Add keyboard shortcuts for zooming and fullscreen- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- // Don't trigger shortcuts when typing in inputs or textareas- const target = e.target as HTMLElement;- if (- target.tagName === "INPUT" ||- target.tagName === "TEXTAREA" ||- target.isContentEditable- ) {- return;- }-- if (e.metaKey || e.ctrlKey) {- if (e.key === "=" || e.key === "+") {- e.preventDefault();- handleZoomIn();- } else if (e.key === "-") {- e.preventDefault();- handleZoomOut();- } else if (e.key === "0") {- e.preventDefault();- setScale(1);- }- } else if (e.key === "f" || e.key === "F") {- e.preventDefault();- handleFullscreen();- }- };+ const handleTransform = (+ _ref: ReactZoomPanPinchRef,+ state: { scale: number },+ ) => {+ const zoomed = state.scale > 1.05;+ setIsZoomed((prev) => (prev === zoomed ? prev : zoomed));+ };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [containerRef.current, imageDimensions]);+ useViewerKeyboardShortcuts({+ onZoomIn: handleZoomIn,+ onZoomOut: handleZoomOut,+ onResetZoom: handleResetZoom,+ onToggleFullscreen: toggleFullscreen,+ });useEffect(() => {const updateImageDimensions = () => {@@ -144,17 +169,26 @@ export default function ImageViewer({};updateImageDimensions();+ // Fullscreen toggles resize the image box via the fill styles, but the new+ // layout isn't ready on the same tick; re-measure next frame so the zoom+ // scroll area (`imageDimensions.width * scale`) matches the rendered width+ // and `transformOrigin: center top` doesn't clip the image's left edge.+ const raf = requestAnimationFrame(updateImageDimensions);window.addEventListener("resize", updateImageDimensions);return () => {+ cancelAnimationFrame(raf);window.removeEventListener("resize", updateImageDimensions);};- }, [scale]);+ // `rotation` re-measures after a quarter turn resizes the image box so the+ // watermark stays locked to the rotated image.+ // `isFullscreen`/`isPseudoFullscreen` re-measure when the fill styles change+ // the image box so scaled zoom bounds stay correct.+ }, [scale, rotation, isFullscreen, isPseudoFullscreen]);useEffect(() => {const handleVisibilityChange = () => {if (document.visibilityState === "visible") {- visibilityRef.current = true;resetTrackingState();const trackingData = {linkId,@@ -167,7 +201,6 @@ export default function ImageViewer({};startIntervalTracking(trackingData);} else {- visibilityRef.current = false;stopIntervalTracking();const duration = getActiveDuration();trackPageViewSafely(@@ -262,7 +295,7 @@ export default function ImageViewer({const removeQueryParams = (queries: string[]) => {const currentQuery = { ...router.query };const currentPath = router.asPath.split("?")[0];- queries.map((query) => delete currentQuery[query]);+ queries.forEach((query) => delete currentQuery[query]);router.replace({@@ -274,10 +307,10 @@ export default function ImageViewer({);};- if (!dataroomId && router.query.token) {+ if (router.isReady && !dataroomId && router.query.token) {removeQueryParams(["token", "email", "domain", "slug", "linkId"]);}- }, []); // Run once on mount+ }, [dataroomId, router, router.isReady]);// Start interval tracking when component mountsuseEffect(() => {@@ -306,20 +339,150 @@ export default function ImageViewer({stopIntervalTracking,]);+ // Image fit caps. After a quarter turn the image's height axis maps to the+ // physical width, so bound height by `dvw` (and width by `dvh`) to keep it+ // fully visible instead of clipped. Non-rotated behavior is unchanged.+ const rotated = isFullscreen && rotation !== 0;+ const quarterTurn = rotation === 90 || rotation === 270;+ const imgMaxHeight = rotated+ ? quarterTurn+ ? "100dvw"+ : "100dvh"+ : isPseudoFullscreen+ ? "100dvh"+ : "calc(100dvh - 64px)";+ // In fullscreen (no rotation) drive the image off an explicit height so a+ // smaller-than-screen image scales *up* to fill it, instead of only being+ // capped by max-height. `object-contain` plus a `100dvw` width bound keep the+ // aspect ratio and stop a wide image from overflowing sideways.+ const imgHeight = isFullscreen && !rotated ? imgMaxHeight : undefined;+ const imgMaxWidth = rotated+ ? quarterTurn+ ? "100dvh"+ : undefined+ : isFullscreen+ ? "100dvw"+ : undefined;++ const watermarkRect =+ watermarkConfig && imageDimensions+ ? getContainedImageRect(+ imageDimensions.width,+ imageDimensions.height,+ imageAspectRef.current,+ )+ : null;++ const imageContent = (+ <div className="viewer-container relative mx-auto flex w-full justify-center">+ {/* Shrink-wrap the image so the absolutely-positioned watermark anchors+ to the image box, not the letterboxed viewport corner. */}+ <div className="relative w-fit">+ <img+ className="viewer-image-mobile !pointer-events-auto object-contain"+ style={{+ height: imgHeight,+ maxHeight: imgMaxHeight,+ maxWidth: imgMaxWidth,+ }}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ ref={(ref) => {+ imageRefs.current = ref;+ if (ref) {+ ref.onload = () => {+ if (ref.naturalWidth && ref.naturalHeight) {+ imageAspectRef.current = ref.naturalWidth / ref.naturalHeight;+ }+ setImageDimensions({+ width: ref.clientWidth,+ height: ref.clientHeight,+ });+ };+ }+ }}+ src={file}+ alt="Image 1"+ />++ {watermarkConfig && watermarkRect ? (+ <div+ className="pointer-events-none absolute"+ style={{ left: watermarkRect.left, top: watermarkRect.top }}+ >+ <SVGWatermark+ config={watermarkConfig}+ viewerData={{+ email: viewerEmail,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ link: linkName,+ ipAddress: ipAddress,+ }}+ documentDimensions={{+ width: watermarkRect.width,+ height: watermarkRect.height,+ }}+ pageIndex={0}+ />+ </div>+ ) : null}+ </div>+ </div>+ );++ // In fullscreen a non-zero rotation turns the viewport into a fixed, rotated+ // full-viewport layer; otherwise it just sizes to the available height.+ const viewportStyle = (isFullscreen &&+ getRotationLayerStyle(rotation, viewerBackgroundColor)) || {+ height: isPseudoFullscreen ? "100dvh" : "calc(100dvh - 64px)",+ };++ // Pseudo-fullscreen (iPhone, no native Fullscreen API) hides the navbar, so+ // this overlay is the only way to rotate or exit and must stay regardless of+ // the viewport breakpoint — an iPhone rotated to landscape reports > 640px,+ // which flips `isMobile` to false and would otherwise strand the viewer.+ // Desktop native fullscreen keeps the navbar's exit toggle, so the overlay+ // stays mobile-only there to avoid a duplicate exit button.+ const showFullscreenOverlay = isFullscreen && (isMobile || isPseudoFullscreen);+return (- <>- <Nav- pageNumber={pageNumber}- numPages={numPages}- hasWatermark={!!watermarkConfig}- handleZoomIn={handleZoomIn}- handleZoomOut={handleZoomOut}- handleFullscreen={handleFullscreen}- navData={navData}- />+ <div+ className={cn(isPseudoFullscreen && "fixed inset-0 z-[60]")}+ style={+ isPseudoFullscreen+ ? { backgroundColor: viewerBackgroundColor }+ : undefined+ }+ >+ {/* While presenting, tint the browser chrome to the viewer background+ (accent) so iOS Safari's status-bar/safe-area matches the immersive+ document instead of the brand-colored top bar. Rendering it here (a+ deeper next/head entry than the base brand ViewerThemeColor) makes the+ accent win, and it reverts on exit. */}+ {isFullscreen && <ViewerThemeColor color={viewerBackgroundColor} />}+ {!isPseudoFullscreen && (+ <Nav+ pageNumber={pageNumber}+ numPages={numPages}+ hasWatermark={!!watermarkConfig}+ handleZoomIn={handleZoomIn}+ handleZoomOut={handleZoomOut}+ handleFullscreen={toggleFullscreen}+ isFullscreen={isFullscreen}+ navData={navData}+ />+ )}<div- style={{ height: "calc(100dvh - 64px)" }}+ style={viewportStyle}className="relative flex items-center overflow-hidden"+ onClick={(e) => {+ if (!isFullscreen) return;+ if ((e.target as HTMLElement).closest("a, area")) return;+ revealControls();+ }}><divclassName={cn(@@ -330,86 +493,86 @@ export default function ImageViewer({)}ref={containerRef}>- {/* Scroll Container */}- <div className="h-full w-full overflow-auto">- {/* Sizer defines scrollable dimensions at current scale.- On mobile at default zoom we vertically center the image so- it sits at the visual center of the viewport (landscape or- short images would otherwise be pinned to the top with a big- empty band underneath). */}+ {isMobile ? (+ <TransformWrapper+ ref={transformRef}+ initialScale={1}+ minScale={1}+ maxScale={3}+ centerOnInit+ limitToBounds+ doubleClick={{ disabled: true }}+ wheel={{ disabled: true }}+ pinch={{ disabled: false }}+ panning={{ disabled: !isZoomed }}+ onTransform={handleTransform}+ >+ <TransformComponent+ wrapperStyle={{ width: "100%", height: "100%" }}+ contentStyle={{+ width: "100%",+ height: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ {imageContent}+ </TransformComponent>+ </TransformWrapper>+ ) : (<div- className={cn(- "mx-auto",- isMobile &&- scale <= 1 &&- "flex min-h-full items-center justify-center",- )}- style={{- width:- imageDimensions && scale > 1- ? `${imageDimensions.width * scale}px`- : "100%",- height:- imageDimensions && scale > 1- ? `${imageDimensions.height * scale}px`- : "auto",- }}+ ref={scrollContainerRef}+ className="h-full w-full overflow-auto">- {/* Scaled content */}+ {/* Sizer defines scrollable dimensions at current scale. */}<div+ className="mx-auto"style={{- transition: "transform 0.2s ease-out",- transformOrigin: "center top",- transform: `scale(${scale})`,- }}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();+ width:+ imageDimensions && scale > 1+ ? `${imageDimensions.width * scale}px`+ : "100%",+ height:+ imageDimensions && scale > 1+ ? `${imageDimensions.height * scale}px`+ : "auto",}}>- <div className="viewer-container relative mx-auto flex w-full justify-center">- <img- className="viewer-image-mobile !pointer-events-auto max-h-[calc(100dvh-64px)] object-contain"- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- ref={(ref) => {- imageRefs.current = ref;- if (ref) {- ref.onload = () =>- setImageDimensions({- width: ref.clientWidth,- height: ref.clientHeight,- });- }- }}- src={file}- alt="Image 1"- />-- {watermarkConfig ? (- <SVGWatermark- config={watermarkConfig}- viewerData={{- email: viewerEmail,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- link: linkName,- ipAddress: ipAddress,- }}- documentDimensions={- imageDimensions ?? { width: 0, height: 0 }- }- pageIndex={0}- />- ) : null}+ {/* Scaled content */}+ <div+ style={{+ transition: "transform 0.2s ease-out",+ transformOrigin: "center top",+ transform: `scale(${scale})`,+ }}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ >+ {imageContent}</div></div></div>- </div>+ )}</div>+ {/* Fullscreen controls, inside the viewport so they rotate with the+ content and land at the presentation's top-right after a turn. They+ fade after a few seconds; a tap anywhere reveals them again. Shown+ for handheld/pseudo-fullscreen presentations (see+ `showFullscreenOverlay`); desktop native fullscreen relies on the+ navbar's exit toggle instead. */}+ {showFullscreenOverlay ? (+ <FullscreenControls+ controlsVisible={controlsVisible}+ showRotate+ onRotate={rotate}+ onExit={toggleFullscreen}+ />+ ) : null}+{screenshotProtectionEnabled ? <ScreenProtector /> : null}{confidentialViewEnabled ? <ConfidentialViewOverlay /> : null}{showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}@@ -419,6 +582,6 @@ export default function ImageViewer({inactivityThreshold={trackingOptions.inactivityThreshold || 60000}onDismiss={updateActivity}/>- </>+ </div>);}diff --git a/components/view/viewer/mobile-page-controls.tsx b/components/view/viewer/mobile-page-controls.tsxnew file mode 100644index 00000000..aab1fdef--- /dev/null+++ b/components/view/viewer/mobile-page-controls.tsx@@ -0,0 +1,52 @@+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";++import { cn } from "@/lib/utils";++export function MobilePageControls({+ pageNumber,+ numPages,+ isFullscreen,+ controlsVisible,+ onPreviousPage,+ onNextPage,+}: {+ pageNumber: number;+ numPages: number;+ isFullscreen: boolean;+ controlsVisible: boolean;+ onPreviousPage: () => void;+ onNextPage: () => void;+}) {+ if (numPages <= 1) return null;++ return (+ <div+ className={cn(+ "absolute bottom-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-full bg-gray-950/50 px-1.5 py-1 text-white shadow-lg backdrop-blur transition-opacity duration-300",+ !isFullscreen || controlsVisible+ ? "opacity-100"+ : "pointer-events-none opacity-0",+ )}+ >+ <button+ onClick={onPreviousPage}+ disabled={pageNumber <= 1}+ aria-label="Previous page"+ className="rounded-full p-1.5 transition-opacity disabled:opacity-30"+ >+ <ChevronLeftIcon className="size-6" />+ </button>+ <span className="min-w-[3.5ch] text-center text-xs font-medium tabular-nums">+ {pageNumber} / {numPages}+ </span>+ <button+ onClick={onNextPage}+ disabled={pageNumber >= numPages}+ aria-label="Next page"+ className="rounded-full p-1.5 transition-opacity disabled:opacity-30"+ >+ <ChevronRightIcon className="size-6" />+ </button>+ </div>+ );+}diff --git a/components/view/viewer/pages-horizontal-viewer.tsx b/components/view/viewer/pages-horizontal-viewer.tsxindex a539b48f..fcbe6f19 100644--- a/components/view/viewer/pages-horizontal-viewer.tsx+++ b/components/view/viewer/pages-horizontal-viewer.tsx@@ -1,37 +1,49 @@import { useRouter } from "next/router";-import { useEffect, useRef, useState } from "react";-import React from "react";+import React, { useEffect, useRef, useState } from "react";import { ConfidentialViewOverlay } from "@/ee/features/permissions/components/confidential-view/confidential-view-overlay";import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";import { useSession } from "next-auth/react";-+import {+ ReactZoomPanPinchRef,+ TransformComponent,+ TransformWrapper,+} from "react-zoom-pan-pinch";++import { useAutoHideControls } from "@/lib/hooks/use-auto-hide-controls";+import { useDisablePullToRefresh } from "@/lib/hooks/use-disable-pull-to-refresh";+import {+ getRotationLayerStyle,+ unrotateDelta,+ useFullscreen,+} from "@/lib/hooks/use-fullscreen";+import {+ useViewerKeyboardShortcuts,+ useViewerPageKeyboardShortcuts,+} from "@/lib/hooks/use-viewer-keyboard-shortcuts";import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { WatermarkConfig } from "@/lib/types";import { cn } from "@/lib/utils";-import { ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";-import { ScreenProtector } from "../ScreenProtection";import Nav, { TNavData } from "../nav";import { PoweredBy } from "../powered-by";import Question from "../question";import Toolbar from "../toolbar";+import { ViewerThemeColor } from "../viewer-theme-color";import ViewDurationSummary from "../visitor-graph";-import { SVGWatermark } from "../watermark-svg";import { AwayPoster } from "./away-poster";+import { FullscreenControls } from "./fullscreen-controls";+import {+ HorizontalPageContent,+ type HorizontalViewerPage,+} from "./horizontal-page-content";+import { MobilePageControls } from "./mobile-page-controls";import "@/styles/custom-viewer-styles.css";-const scaleCoordinates = (coords: string, scaleFactor: number) => {- return coords- .split(",")- .map((coord) => parseFloat(coord) * scaleFactor)- .join(",");-};-export default function PagesHorizontalViewer({pages,feedbackEnabled,@@ -49,18 +61,7 @@ export default function PagesHorizontalViewer({navData,ensurePagesLoaded,}: {- pages: {- file: string | null;- pageNumber: string;- embeddedLinks: string[];- pageLinks: {- href: string;- coords: string;- isInternal?: boolean;- targetPage?: number;- }[];- metadata: { width: number; height: number; scaleFactor: number };- }[];+ pages: HorizontalViewerPage[];feedbackEnabled: boolean;screenshotProtectionEnabled: boolean;confidentialViewEnabled?: boolean;@@ -82,8 +83,22 @@ export default function PagesHorizontalViewer({const { isMobile, isPreview, linkId, documentId, viewId, dataroomId, brand } =navData;+ // The viewer's chosen background color (matches the surrounding viewer chrome+ // in document-view). Used to fill the fullscreen letterbox and tint the+ // browser chrome instead of a hard black.+ const viewerBackgroundColor = brand?.accentColor || "rgb(3, 7, 18)";+const router = useRouter();const { status: sessionStatus } = useSession();+ const {+ isFullscreen,+ isPseudoFullscreen,+ toggleFullscreen,+ rotation,+ rotate,+ } = useFullscreen();++ useDisablePullToRefresh(!!isMobile);const showStatsSlideWithAccountCreation =showAccountCreationSlide && // if showAccountCreationSlide is enabled@@ -104,9 +119,17 @@ export default function PagesHorizontalViewer({pageQuery >= 1 && pageQuery <= numPages ? pageQuery : 1,); // start on first page+ // In fullscreen the overlay controls fade after a few seconds (and on each+ // new page) so the slide is unobstructed; a tap anywhere reveals them again.+ const { visible: controlsVisible, reveal: revealControls } =+ useAutoHideControls({ active: isFullscreen, resetKey: pageNumber });+const [submittedFeedback, setSubmittedFeedback] = useState<boolean>(false);const [accountCreated, setAccountCreated] = useState<boolean>(false);const [scale, setScale] = useState<number>(1);+ // Mobile pinch/pan runs through react-zoom-pan-pinch; `isZoomed` mirrors its+ // scale so the swipe handler and the "fit" control can react to it.+ const [isZoomed, setIsZoomed] = useState<boolean>(false);const [viewedPages, setViewedPages] = useState<{ pageNumber: number; duration: number }[]@@ -120,11 +143,12 @@ export default function PagesHorizontalViewer({const [isWindowFocused, setIsWindowFocused] = useState(true);const startTimeRef = useRef(Date.now());- const pageNumberRef = useRef<number>(pageNumber);- const visibilityRef = useRef<boolean>(true);const containerRef = useRef<HTMLDivElement>(null);- const hasTrackedDownRef = useRef<boolean>(false);- const hasTrackedUpRef = useRef<boolean>(false);+ const scrollContainerRef = useRef<HTMLDivElement>(null);+ const transformRef = useRef<ReactZoomPanPinchRef | null>(null);+ const scaleRef = useRef<number>(1);+ const mobileViewportRef = useRef<HTMLDivElement>(null);+ const swipeRef = useRef<{ x: number; y: number; time: number } | null>(null);const imageRefs = useRef<(HTMLImageElement | null)[]>([]);const [imageDimensions, setImageDimensions] = useState<@@ -179,19 +203,23 @@ export default function PagesHorizontalViewer({};updateImageDimensions();+ // Entering/leaving fullscreen resizes the image box via the fill styles, but+ // the new layout isn't ready on the same tick; re-measure next frame so the+ // zoom scroll area (`scaledWidthPx`) matches the rendered width. A stale+ // smaller width makes `transformOrigin: center top` push the slide's left+ // edge past the scroll origin, clipping it when zoomed.+ const raf = requestAnimationFrame(updateImageDimensions);window.addEventListener("resize", updateImageDimensions);return () => {+ cancelAnimationFrame(raf);window.removeEventListener("resize", updateImageDimensions);};- }, [pageNumber]);-- // Update the previous page number after the effect hook has run- useEffect(() => {- pageNumberRef.current = pageNumber;- hasTrackedDownRef.current = false; // Reset tracking status on page number change- hasTrackedUpRef.current = false; // Reset tracking status on page number change- }, [pageNumber]);+ // `rotation` re-measures after a quarter turn resizes the image box so the+ // watermark and link overlays stay locked to the rotated image.+ // `isFullscreen`/`isPseudoFullscreen` re-measure when the fill styles change+ // the image box so scaled zoom bounds stay correct.+ }, [pageNumber, rotation, isFullscreen, isPseudoFullscreen]);// Start interval tracking when component mounts or page changesuseEffect(() => {@@ -231,7 +259,6 @@ export default function PagesHorizontalViewer({if (pageNumber > numPages) return;if (document.visibilityState === "visible") {- visibilityRef.current = true;resetTrackingState();// Restart interval tracking@@ -249,7 +276,6 @@ export default function PagesHorizontalViewer({startIntervalTracking(trackingData);}} else {- visibilityRef.current = false;stopIntervalTracking();if (pageNumber <= numPages) {const duration = getActiveDuration();@@ -358,7 +384,7 @@ export default function PagesHorizontalViewer({const removeQueryParams = (queries: string[]) => {const currentQuery = { ...router.query };const currentPath = router.asPath.split("?")[0];- queries.map((query) => delete currentQuery[query]);+ queries.forEach((query) => delete currentQuery[query]);router.replace({@@ -370,10 +396,10 @@ export default function PagesHorizontalViewer({);};- if (!dataroomId && router.query.token) {+ if (router.isReady && !dataroomId && router.query.token) {removeQueryParams(["token", "email", "domain", "slug", "linkId"]);}- }, []); // Run once on mount+ }, [dataroomId, router, router.isReady]);const goToPreviousPage = () => {if (pageNumber <= 1) return;@@ -432,22 +458,11 @@ export default function PagesHorizontalViewer({startTimeRef.current = Date.now();};- const handleKeyDown = (event: KeyboardEvent) => {- switch (event.key) {- case "ArrowRight":- event.preventDefault(); // Prevent default behavior- event.stopPropagation(); // Stop propagation- goToNextPage();- break;- case "ArrowLeft":- event.preventDefault(); // Prevent default behavior- event.stopPropagation(); // Stop propagation- goToPreviousPage();- break;- default:- break;- }- };+ useViewerPageKeyboardShortcuts({+ orientation: "horizontal",+ onPreviousPage: goToPreviousPage,+ onNextPage: goToNextPage,+ });const handleLinkClick = (href: string, event: React.MouseEvent) => {// Check if it's an internal page link or external link@@ -471,7 +486,6 @@ export default function PagesHorizontalViewer({});setPageNumber(targetPage);- pageNumberRef.current = targetPage;// Reset the start time for the new pagestartTimeRef.current = Date.now();@@ -500,401 +514,525 @@ export default function PagesHorizontalViewer({}};- useEffect(() => {- document.addEventListener("keydown", handleKeyDown);-- return () => {- document.removeEventListener("keydown", handleKeyDown);- };- }, [handleKeyDown, goToNextPage, goToPreviousPage]);-- // Add zoom handlers+ // Zoom handlers. Desktop drives the CSS `scale` state directly; mobile+ // delegates to react-zoom-pan-pinch so pinch and pan stay focal-point+ // correct (the page no longer jumps out from under the fingers).const handleZoomIn = () => {- setScale((prev) => Math.min(prev + 0.25, 3)); // Max zoom 3x+ if (isMobile) {+ transformRef.current?.zoomIn();+ return;+ }+ setScale((prev) => Math.min(prev + 0.25, 3));};const handleZoomOut = () => {- setScale((prev) => Math.max(prev - 0.25, 0.5)); // Min zoom 0.5x+ if (isMobile) {+ transformRef.current?.zoomOut();+ return;+ }+ setScale((prev) => Math.max(prev - 0.25, 0.5));};- // Add fullscreen handler- const handleFullscreen = () => {- if (!document.fullscreenElement) {- document.documentElement.requestFullscreen().catch((err) => {- console.error("Error attempting to enable fullscreen:", err);- });- } else {- document.exitFullscreen();+ const handleResetZoom = () => {+ if (isMobile) {+ transformRef.current?.resetTransform();+ return;}+ setScale(1);+ };++ const handleTransform = (+ _ref: ReactZoomPanPinchRef,+ state: { scale: number },+ ) => {+ scaleRef.current = state.scale;+ const zoomed = state.scale > 1.05;+ setIsZoomed((prev) => (prev === zoomed ? prev : zoomed));};- // Add keyboard shortcuts for zooming and fullscreen+ useViewerKeyboardShortcuts({+ onZoomIn: handleZoomIn,+ onZoomOut: handleZoomOut,+ onResetZoom: handleResetZoom,+ onToggleFullscreen: toggleFullscreen,+ });++ // Keep the latest navigation callbacks for the imperative swipe handler,+ // which is bound once and must not close over a stale `pageNumber`.+ const goToNextPageRef = useRef(goToNextPage);+ const goToPreviousPageRef = useRef(goToPreviousPage);++ // Read inside the once-bound swipe handler so a rotate doesn't re-subscribe.+ const rotationRef = useRef(rotation);++ // Sync after commit so the swipe handler only ever reads committed callbacks+ // and rotation (mutating refs during render is unsafe under concurrent React).useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- // Don't trigger shortcuts when typing in inputs or textareas- const target = e.target as HTMLElement;+ goToNextPageRef.current = goToNextPage;+ goToPreviousPageRef.current = goToPreviousPage;+ rotationRef.current = rotation;+ }, [goToNextPage, goToPreviousPage, rotation]);++ // Each slide starts unzoomed. The wrapper is NOT keyed by page (keying it+ // remounted react-zoom-pan-pinch and its <img> on every navigation, which+ // painted a blank frame — the flash). Instead we keep it mounted and reset+ // its transform imperatively (0ms so there's no zoom-out animation).+ useEffect(() => {+ scaleRef.current = 1;+ setIsZoomed(false);+ transformRef.current?.resetTransform(0);+ }, [pageNumber]);++ // Swipe left/right to change slides — only while not zoomed, so panning a+ // zoomed page never flips the page. Listeners are attached natively in the+ // capture phase so they observe touches regardless of the zoom layer.+ useEffect(() => {+ if (!isMobile) return;+ const el = mobileViewportRef.current;+ if (!el) return;++ const onStart = (e: TouchEvent) => {+ if (e.touches.length === 1 && scaleRef.current <= 1.05) {+ const touch = e.touches[0];+ swipeRef.current = {+ x: touch.clientX,+ y: touch.clientY,+ time: Date.now(),+ };+ } else {+ swipeRef.current = null;+ }+ };+ const onMove = (e: TouchEvent) => {+ if (swipeRef.current && e.touches.length !== 1) swipeRef.current = null;+ };+ const onEnd = (e: TouchEvent) => {+ const start = swipeRef.current;+ swipeRef.current = null;+ if (!start || scaleRef.current > 1.05) return;+ const touch = e.changedTouches[0];+ if (!touch) return;+ // Remap the physical swipe into the (possibly rotated) content frame so a+ // left/right swipe relative to the presentation always flips the page.+ const { dx, dy } = unrotateDelta(+ touch.clientX - start.x,+ touch.clientY - start.y,+ rotationRef.current,+ );+ const elapsed = Date.now() - start.time;if (- target.tagName === "INPUT" ||- target.tagName === "TEXTAREA" ||- target.isContentEditable+ elapsed < 700 &&+ Math.abs(dx) > 48 &&+ Math.abs(dx) > Math.abs(dy) * 1.4) {- return;- }-- if (e.metaKey || e.ctrlKey) {- if (e.key === "=" || e.key === "+") {- e.preventDefault();- handleZoomIn();- } else if (e.key === "-") {- e.preventDefault();- handleZoomOut();- } else if (e.key === "0") {- e.preventDefault();- setScale(1);- }- } else if (e.key === "f" || e.key === "F") {- e.preventDefault();- handleFullscreen();+ if (dx < 0) goToNextPageRef.current();+ else goToPreviousPageRef.current();}};- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [containerRef.current, pageNumber, imageDimensions]);+ const opts: AddEventListenerOptions = { passive: true, capture: true };+ el.addEventListener("touchstart", onStart, opts);+ el.addEventListener("touchmove", onMove, opts);+ el.addEventListener("touchend", onEnd, opts);+ return () => {+ el.removeEventListener("touchstart", onStart, opts);+ el.removeEventListener("touchmove", onMove, opts);+ el.removeEventListener("touchend", onEnd, opts);+ };+ }, [isMobile]);// Compute scaled sizer dimensions for accurate scroll areaconst currentDims = imageDimensions[pageNumber - 1];const scaledWidthPx = currentDims ? currentDims.width * scale : undefined;const scaledHeightPx = currentDims ? currentDims.height * scale : undefined;+ const isQuestionSlide =+ !!enableQuestion && !!feedback && pageNumber === numPagesWithFeedback;+ const isAccountSlide =+ showStatsSlideWithAccountCreation &&+ pageNumber === numPagesWithAccountCreation;++ // In fullscreen a non-zero rotation turns the viewport into a fixed, rotated+ // full-viewport layer (see getRotationLayerStyle); otherwise it just sizes to+ // the available height. `getRotationLayerStyle` returns null at rotation 0.+ const viewportStyle = (isFullscreen &&+ getRotationLayerStyle(rotation, viewerBackgroundColor)) || {+ height: isPseudoFullscreen ? "100dvh" : "calc(100dvh - 64px)",+ };++ // Image fit caps. After a quarter turn the slide's height axis maps to the+ // physical width, so bound height by `dvw` (and width by `dvh`) to keep a+ // landscape slide fully visible instead of clipped. Non-rotated behavior is+ // unchanged.+ const rotated = isFullscreen && rotation !== 0;+ const quarterTurn = rotation === 90 || rotation === 270;+ const imgMaxHeight = rotated+ ? quarterTurn+ ? "100dvw"+ : "100dvh"+ : isPseudoFullscreen+ ? "100dvh"+ : "calc(100dvh - 64px)";+ // In fullscreen (no rotation) drive the slide off an explicit height so a+ // page render smaller than the screen scales *up* to fill it, instead of only+ // being capped by max-height. `object-contain` plus a `100dvw` width bound+ // keep the aspect ratio and stop a wide slide from overflowing sideways.+ const imgHeight = isFullscreen && !rotated ? imgMaxHeight : undefined;+ const imgMaxWidth = rotated+ ? quarterTurn+ ? "100dvh"+ : undefined+ : isFullscreen+ ? "100dvw"+ : undefined;++ // Pseudo-fullscreen (iPhone, no native Fullscreen API) hides the navbar, so+ // this overlay is the only way to rotate or exit and must stay regardless of+ // the viewport breakpoint — an iPhone rotated to landscape reports > 640px,+ // which flips `isMobile` to false and would otherwise strand the viewer.+ // Desktop native fullscreen keeps the navbar's exit toggle, so the overlay+ // stays mobile-only there to avoid a duplicate exit button.+ const showFullscreenOverlay = isFullscreen && (isMobile || isPseudoFullscreen);++ const handleImageDimensionsChange = (+ index: number,+ dimensions: { width: number; height: number },+ ) => {+ setImageDimensions((prev) => ({+ ...prev,+ [index]: dimensions,+ }));+ };++ const renderPageContent = (page: HorizontalViewerPage, index: number) => (+ <HorizontalPageContent+ page={page}+ index={index}+ imgHeight={imgHeight}+ imgMaxHeight={imgMaxHeight}+ imgMaxWidth={imgMaxWidth}+ watermarkConfig={watermarkConfig}+ viewerEmail={viewerEmail}+ linkName={linkName}+ ipAddress={ipAddress}+ imageDimensions={imageDimensions}+ imageRefs={imageRefs}+ getScaleFactor={getScaleFactor}+ onImageDimensionsChange={handleImageDimensionsChange}+ onLinkClick={handleLinkClick}+ />+ );++ const renderPage = (page: HorizontalViewerPage, index: number, active: boolean) => (+ <div+ key={index}+ className={cn(+ "viewer-container relative mx-auto w-full",+ active ? "flex justify-center" : "hidden",+ )}+ >+ {renderPageContent(page, index)}+ </div>+ );+return (- <>- <Nav- pageNumber={pageNumber}- numPages={numPagesWithAccountCreation}- embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}- hasWatermark={!!watermarkConfig}- handleZoomIn={handleZoomIn}- handleZoomOut={handleZoomOut}- handleFullscreen={handleFullscreen}- navData={navData}- />+ <div+ className={cn(isPseudoFullscreen && "fixed inset-0 z-[60]")}+ style={+ isPseudoFullscreen+ ? { backgroundColor: viewerBackgroundColor }+ : undefined+ }+ >+ {/* While presenting, tint the browser chrome to the viewer background+ (accent) so iOS Safari's status-bar/safe-area matches the immersive+ document instead of the brand-colored top bar. Rendering it here (a+ deeper next/head entry than the base brand ViewerThemeColor) makes the+ accent win, and it reverts on exit. */}+ {isFullscreen && <ViewerThemeColor color={viewerBackgroundColor} />}+ {!isPseudoFullscreen && (+ <Nav+ pageNumber={pageNumber}+ numPages={numPagesWithAccountCreation}+ embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}+ hasWatermark={!!watermarkConfig}+ handleZoomIn={handleZoomIn}+ handleZoomOut={handleZoomOut}+ handleFullscreen={toggleFullscreen}+ isFullscreen={isFullscreen}+ hidePageCount={isMobile}+ navData={navData}+ />+ )}<div- style={{ height: "calc(100dvh - 64px)" }}+ ref={mobileViewportRef}+ style={viewportStyle}className="relative overflow-hidden"+ onClick={(e) => {+ if (!isFullscreen) return;+ // A tap on a document link follows the link; any other tap brings the+ // faded overlay controls back.+ if ((e.target as HTMLElement).closest("a, area")) return;+ revealControls();+ }}>- <ResizablePanelGroup orientation="horizontal">- {/* Document Content */}- <ResizablePanel defaultSize="100%">- <div className="flex h-full w-full items-center">+ <div className="flex h-full w-full items-center">+ {isMobile ? (+ <div+ className={cn(+ "relative h-full w-full",+ !isWindowFocused &&+ screenshotProtectionEnabled &&+ "blur-xl transition-all duration-300",+ )}+ ref={containerRef}+ >+ {pageNumber <= numPages ? (+ <TransformWrapper+ ref={transformRef}+ initialScale={1}+ minScale={1}+ maxScale={3}+ centerOnInit+ limitToBounds+ doubleClick={{ disabled: true }}+ wheel={{ disabled: true }}+ pinch={{ disabled: false }}+ panning={{ disabled: !isZoomed }}+ onTransform={handleTransform}+ >+ <TransformComponent+ wrapperStyle={{ width: "100%", height: "100%" }}+ contentStyle={{ width: "100%", height: "100%" }}+ >+ {/* Persistent stack: the current page plus its immediate+ neighbors stay mounted and decoded, so a swipe/next+ reveals an already-painted page instead of a blank+ frame. Only the active page is visible. */}+ <div className="relative h-full w-full">+ {pages.map((page, index) => {+ if (Math.abs(index - (pageNumber - 1)) > 1) return null;+ const active = index === pageNumber - 1;+ return (+ <div+ key={index}+ aria-hidden={!active}+ className={cn(+ "absolute inset-0 flex items-center justify-center",+ active+ ? "visible"+ : "pointer-events-none invisible",+ )}+ >+ {renderPageContent(page, index)}+ </div>+ );+ })}+ </div>+ </TransformComponent>+ </TransformWrapper>+ ) : isQuestionSlide ? (+ <div className="flex h-full w-full items-center justify-center">+ <Question+ accentColor={brand?.accentColor}+ feedback={feedback!}+ viewId={viewId}+ submittedFeedback={submittedFeedback}+ setSubmittedFeedback={setSubmittedFeedback}+ isPreview={isPreview}+ />+ </div>+ ) : isAccountSlide ? (+ <div className="flex h-full w-full items-center justify-center">+ <ViewDurationSummary+ linkId={linkId}+ viewedPages={viewedPages}+ viewerEmail={viewerEmail}+ accountCreated={accountCreated}+ setAccountCreated={setAccountCreated}+ />+ </div>+ ) : null}+ </div>+ ) : (+ <div+ className={cn(+ "relative h-full w-full",+ !isWindowFocused &&+ screenshotProtectionEnabled &&+ "blur-xl transition-all duration-300",+ )}+ ref={containerRef}+ ><div- className={cn(- "relative h-full w-full",- !isWindowFocused &&- screenshotProtectionEnabled &&- "blur-xl transition-all duration-300",- )}- ref={containerRef}+ ref={scrollContainerRef}+ className="h-full w-full overflow-auto"+ // Let one-finger drags scroll/pan while our pinch handler+ // owns two-finger zoom. Without this the browser's own+ // pinch-zoom fights the scroll container on mobile.+ style={isMobile ? { touchAction: "pan-x pan-y" } : undefined}>- <div className="h-full w-full overflow-auto">- {/* Sizer defines the scrollable layout size at current scale.+ {/* Sizer defines the scrollable layout size at current scale.On mobile at default zoom we vertically center the pageso it aligns with the next/prev controls (which sit atvertical-center of the viewport) instead of being pinnedto the top — short/landscape pages would otherwise leavea large empty band underneath. */}+ <div+ className={cn(+ "mx-auto",+ isMobile &&+ scale <= 1 &&+ "flex min-h-full items-center justify-center",+ )}+ style={{+ // Keep default zoom responsive to viewport changes.+ // Only lock dimensions when zoomed in to preserve a stable scroll area.+ width:+ scale > 1 && scaledWidthPx+ ? `${scaledWidthPx}px`+ : "100%",+ height:+ scale > 1 && scaledHeightPx+ ? `${scaledHeightPx}px`+ : "auto",+ }}+ >+ {/* Content is scaled; origin set to top-left so it grows into the sizer */}<div- className={cn(- "mx-auto",- isMobile &&- scale <= 1 &&- "flex min-h-full items-center justify-center",- )}style={{- // Keep default zoom responsive to viewport changes.- // Only lock dimensions when zoomed in to preserve a stable scroll area.- width:- scale > 1 && scaledWidthPx- ? `${scaledWidthPx}px`- : "100%",- height:- scale > 1 && scaledHeightPx- ? `${scaledHeightPx}px`- : "auto",+ transition: "transform 0.2s ease-out",+ transformOrigin: "center top",+ transform: `scale(${scale})`,+ }}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();}}>- {/* Content is scaled; origin set to top-left so it grows into the sizer */}- <div- style={{- transition: "transform 0.2s ease-out",- transformOrigin: "center top",- transform: `scale(${scale})`,- }}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- >- {pageNumber <= numPagesWithAccountCreation && pages- ? pages.map((page, index) => (- <div- key={index}- className={cn(- "viewer-container relative mx-auto w-full",- pageNumber - 1 === index- ? "flex justify-center"- : "hidden",- )}- >- <img- className={cn(- "viewer-image-mobile !pointer-events-auto max-h-[calc(100dvh-64px)] object-contain",- )}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- ref={(ref) => {- imageRefs.current[index] = ref;- if (ref) {- ref.onload = () =>- setImageDimensions((prev) => ({- ...prev,- [index]: {- width: ref.clientWidth,- height: ref.clientHeight,- },- }));- }- }}- useMap={`#page-map-${index + 1}`}- src={- page.file ||- "https://www.papermark.com/_static/blank.gif"- }- alt={`Page ${index + 1}`}- />-- {/* Add Watermark Component */}- {watermarkConfig ? (- <SVGWatermark- config={watermarkConfig}- viewerData={{- email: viewerEmail,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- link: linkName,- ipAddress: ipAddress,- }}- documentDimensions={- imageDimensions[index] || {- width: 0,- height: 0,- }- }- pageIndex={index}- />- ) : null}-- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter(- (link) => !link.href.endsWith(".gif"),- )- .map((link, index) => (- <area- key={index}- shape="rect"- coords={scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor:- page.metadata.scaleFactor,- }),- )}- href={link.href}- onClick={(e) =>- handleLinkClick(link.href, e)- }- target={- link.href.startsWith("#")- ? "_self"- : "_blank"- }- rel={- link.href.startsWith("#")- ? undefined- : "noopener noreferrer"- }- />- ))}- </map>- ) : null}-- {/** Automatically Render Overlays **/}- {page.pageLinks && imageDimensions[index]- ? page.pageLinks- .filter((link) =>- link.href.endsWith(".gif"),- )- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor:- page.metadata.scaleFactor,- }),- )- .split(",")- .map(Number);-- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;-- // Calculate the offset to center-align with the image- const containerWidth =- imageRefs.current[index]?.parentElement- ?.clientWidth || 0;- const imageWidth =- imageDimensions[index].width;- const leftOffset =- (containerWidth - imageWidth) / 2;-- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href}- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1 + leftOffset,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none",- }}- />- );- })- : null}- </div>- ))- : null}-- {enableQuestion &&- feedback &&- pageNumber === numPagesWithFeedback ? (- <div- className={cn("relative block h-dvh w-full")}- style={{ height: "calc(100dvh - 64px)" }}- >- <Question- accentColor={brand?.accentColor}- feedback={feedback}- viewId={viewId}- submittedFeedback={submittedFeedback}- setSubmittedFeedback={setSubmittedFeedback}- isPreview={isPreview}- />- </div>- ) : null}-- {showStatsSlideWithAccountCreation &&- pageNumber === numPagesWithAccountCreation ? (- <div- className={cn("relative block h-dvh w-full")}- style={{ height: "calc(100dvh - 64px)" }}- >- <ViewDurationSummary- linkId={linkId}- viewedPages={viewedPages}- viewerEmail={viewerEmail}- accountCreated={accountCreated}- setAccountCreated={setAccountCreated}- />- </div>- ) : null}- </div>+ {pageNumber <= numPagesWithAccountCreation && pages+ ? pages.map((page, index) =>+ renderPage(page, index, pageNumber - 1 === index),+ )+ : null}</div></div>- </div>- {/* Navigation arrows with hover zones.- Stacked at z-50 so they sit ABOVE the confidential-view- overlay (z-40) and its slice-handle. Without this, the- slice-handle on touch devices intercepts taps inside the- visible window and the user can't reach the chevrons.- Visually this also keeps the chevrons readable when the- fence sweeps over them. */}- {pageNumber > 1 && (- <div- className={cn(- "group absolute left-0 top-0 z-50 flex h-full items-center",- isMobile ? "w-1/6" : "w-32",- isMobile ? "justify-start pl-1" : "justify-start pl-4",- )}- onClick={isMobile ? goToPreviousPage : undefined}- >- <button- onClick={!isMobile ? goToPreviousPage : undefined}- className={cn(- "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",- "opacity-50 group-hover:opacity-100",- )}+ {enableQuestion &&+ feedback &&+ pageNumber === numPagesWithFeedback ? (+ <div+ className={cn("relative block h-dvh w-full")}+ style={{ height: "calc(100dvh - 64px)" }}>- <ChevronLeftIcon- className={cn("size-10 text-white", isMobile && "size-8")}+ <Question+ accentColor={brand?.accentColor}+ feedback={feedback}+ viewId={viewId}+ submittedFeedback={submittedFeedback}+ setSubmittedFeedback={setSubmittedFeedback}+ isPreview={isPreview}/>- </button>- </div>- )}+ </div>+ ) : null}- {pageNumber < numPagesWithAccountCreation && (- <div- className={cn(- "group absolute right-0 top-0 z-50 flex h-full items-center",- isMobile ? "w-1/6" : "w-32",- isMobile ? "justify-end pr-1" : "justify-end pr-4",- )}- onClick={isMobile ? goToNextPage : undefined}- >- <button- onClick={!isMobile ? goToNextPage : undefined}- className={cn(- "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",- "opacity-50 group-hover:opacity-100",- )}+ {showStatsSlideWithAccountCreation &&+ pageNumber === numPagesWithAccountCreation ? (+ <div+ className={cn("relative block h-dvh w-full")}+ style={{ height: "calc(100dvh - 64px)" }}>- <ChevronRightIcon- className={cn("size-10 text-white", isMobile && "size-8")}+ <ViewDurationSummary+ linkId={linkId}+ viewedPages={viewedPages}+ viewerEmail={viewerEmail}+ accountCreated={accountCreated}+ setAccountCreated={setAccountCreated}/>- </button>- </div>- )}+ </div>+ ) : null}+ </div>+ </div>+ )}- {feedbackEnabled && pageNumber <= numPages ? (- <Toolbar- viewId={viewId}- pageNumber={pageNumber}- isPreview={isPreview}- />- ) : null}+ {!isMobile && pageNumber > 1 && (+ <div className="group absolute left-0 top-0 z-50 flex h-full w-32 items-center justify-start pl-4">+ <button+ onClick={goToPreviousPage}+ className={cn(+ "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",+ "opacity-50 group-hover:opacity-100",+ )}+ >+ <ChevronLeftIcon className="size-10 text-white" />+ </button>+ </div>+ )}- {screenshotProtectionEnabled ? <ScreenProtector /> : null}- {confidentialViewEnabled ? <ConfidentialViewOverlay /> : null}- {showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}- <AwayPoster- isVisible={isInactive}- inactivityThreshold={getTrackingOptions().inactivityThreshold}- onDismiss={updateActivity}- />+ {!isMobile && pageNumber < numPagesWithAccountCreation && (+ <div className="group absolute right-0 top-0 z-50 flex h-full w-32 items-center justify-end pr-4">+ <button+ onClick={goToNextPage}+ className={cn(+ "rounded-full bg-gray-950/50 p-1 transition-opacity duration-200 hover:bg-gray-950/75",+ "opacity-50 group-hover:opacity-100",+ )}+ >+ <ChevronRightIcon className="size-10 text-white" />+ </button></div>- </ResizablePanel>- </ResizablePanelGroup>+ )}++ {isMobile ? (+ <MobilePageControls+ pageNumber={pageNumber}+ numPages={numPagesWithAccountCreation}+ isFullscreen={isFullscreen}+ controlsVisible={controlsVisible}+ onPreviousPage={goToPreviousPage}+ onNextPage={goToNextPage}+ />+ ) : null}++ {/* Fullscreen controls. Placed inside the viewport so they+ rotate with the presentation and land at the presentation's+ top-right (not the physical screen's) after a quarter turn.+ They fade with the rest of the overlay after a few seconds.+ Shown for handheld/pseudo-fullscreen presentations (see+ `showFullscreenOverlay`); desktop native fullscreen relies on+ the navbar's exit toggle instead. */}+ {showFullscreenOverlay ? (+ <FullscreenControls+ controlsVisible={controlsVisible}+ showRotate+ onRotate={rotate}+ onExit={toggleFullscreen}+ />+ ) : null}++ {feedbackEnabled && pageNumber <= numPages ? (+ <Toolbar+ viewId={viewId}+ pageNumber={pageNumber}+ isPreview={isPreview}+ />+ ) : null}++ {screenshotProtectionEnabled ? <ScreenProtector /> : null}+ {confidentialViewEnabled ? (+ <ConfidentialViewOverlay+ navbarAbove={!isPseudoFullscreen && rotation === 0}+ rotation={rotation}+ />+ ) : null}+ {showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}+ <AwayPoster+ isVisible={isInactive}+ inactivityThreshold={getTrackingOptions().inactivityThreshold}+ onDismiss={updateActivity}+ />+ </div></div>- </>+ </div>);}diff --git a/components/view/viewer/pages-vertical-viewer.tsx b/components/view/viewer/pages-vertical-viewer.tsxindex 50d2c055..f0556737 100644--- a/components/view/viewer/pages-vertical-viewer.tsx+++ b/components/view/viewer/pages-vertical-viewer.tsx@@ -1,26 +1,36 @@import { useRouter } from "next/router";-import { useEffect, useRef, useState } from "react";-import React from "react";+import React, { useEffect, useRef, useState } from "react";import { ConfidentialViewOverlay } from "@/ee/features/permissions/components/confidential-view/confidential-view-overlay";import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";+import { useDisablePullToRefresh } from "@/lib/hooks/use-disable-pull-to-refresh";+import {+ getRotationLayerStyle,+ useFullscreen,+} from "@/lib/hooks/use-fullscreen";+import { useTouchZoom } from "@/lib/hooks/use-touch-zoom";+import {+ useViewerKeyboardShortcuts,+ useViewerPageKeyboardShortcuts,+} from "@/lib/hooks/use-viewer-keyboard-shortcuts";import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { WatermarkConfig } from "@/lib/types";import { cn } from "@/lib/utils";+import { getSafeLinkHref } from "@/lib/utils/sanitize-link-href";import { useMediaQuery } from "@/lib/utils/use-media-query";-import { ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";-import { ScreenProtector } from "../ScreenProtection";import Nav, { TNavData } from "../nav";import { PoweredBy } from "../powered-by";import Question from "../question";import Toolbar from "../toolbar";+import { ViewerThemeColor } from "../viewer-theme-color";import { SVGWatermark } from "../watermark-svg";import { AwayPoster } from "./away-poster";+import { FullscreenControls } from "./fullscreen-controls";import "@/styles/custom-viewer-styles.css";@@ -104,15 +114,27 @@ export default function PagesVerticalViewer({ensurePagesLoaded?: (currentPage: number) => void;}) {const { linkId, documentId, viewId, isPreview, dataroomId, brand } = navData;+ const { isMobile, isTablet } = useMediaQuery();++ // Viewer's chosen background color; fills the fullscreen background and tints+ // the browser chrome instead of a hard black.+ const viewerBackgroundColor = brand?.accentColor || "rgb(3, 7, 18)";const router = useRouter();+ const {+ isFullscreen,+ isPseudoFullscreen,+ toggleFullscreen,+ rotation,+ rotate,+ } = useFullscreen();++ useDisablePullToRefresh(isMobile);const numPages = pages.length;const numPagesWithFeedback =enableQuestion && feedback ? numPages + 1 : numPages;- const numPagesWithAccountCreation = numPagesWithFeedback;-const pageQuery = router.query.p ? Number(router.query.p) : 1;const [pageNumber, setPageNumber] = useState<number>(() =>@@ -120,8 +142,15 @@ export default function PagesVerticalViewer({); // start on first pageconst [submittedFeedback, setSubmittedFeedback] = useState<boolean>(false);- const [accountCreated, setAccountCreated] = useState<boolean>(false);const [scale, setScale] = useState<number>(1);+ // Unscaled layout size of the zoom content, used to reserve the scaled+ // scroll area (a sizer) so pinch-zoom can pan in both axes. `offsetWidth`+ // and `offsetHeight` are layout metrics unaffected by the CSS transform, so+ // this stays the base size regardless of the current scale.+ const [baseSize, setBaseSize] = useState<{+ width: number;+ height: number;+ } | null>(null);const [viewedPages, setViewedPages] = useState<{ pageNumber: number; duration: number }[]@@ -135,32 +164,28 @@ export default function PagesVerticalViewer({const [isWindowFocused, setIsWindowFocused] = useState(true);const startTimeRef = useRef(Date.now());- const pageNumberRef = useRef<number>(pageNumber);- const visibilityRef = useRef<boolean>(true);const containerRef = useRef<HTMLDivElement>(null);+ const zoomContentRef = useRef<HTMLDivElement>(null);const scrollActionRef = useRef<boolean>(false);const scrollEndTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null,);- const hasTrackedDownRef = useRef<boolean>(false);- const hasTrackedUpRef = useRef<boolean>(false);const imageRefs = useRef<(HTMLImageElement | null)[]>([]);const [imageDimensions, setImageDimensions] = useState<Record<number, { width: number; height: number }>>({});-- const { isMobile, isTablet } = useMediaQuery();-const getScaleFactor = ({naturalHeight,scaleFactor,+ pageIndex,}: {naturalHeight: number;scaleFactor: number;+ pageIndex: number;}) => {- const containerHeight = imageDimensions[pageNumber - 1]- ? imageDimensions[pageNumber - 1]!.height+ const containerHeight = imageDimensions[pageIndex]+ ? imageDimensions[pageIndex]!.height: window.innerHeight - 64;// Add a safety check to prevent division by zero@@ -194,13 +219,6 @@ export default function PagesVerticalViewer({};}, [pageNumber]);- // Update the previous page number after the effect hook has run- useEffect(() => {- pageNumberRef.current = pageNumber;- hasTrackedDownRef.current = false; // Reset tracking status on page number change- hasTrackedUpRef.current = false; // Reset tracking status on page number change- }, [pageNumber]);-const {trackPageViewSafely,resetTrackingState,@@ -251,7 +269,6 @@ export default function PagesVerticalViewer({if (pageNumber > numPages) return;if (document.visibilityState === "visible") {- visibilityRef.current = true;resetTrackingState();if (pageNumber <= numPages) {@@ -268,7 +285,6 @@ export default function PagesVerticalViewer({startIntervalTracking(trackingData);}} else {- visibilityRef.current = false;stopIntervalTracking();// Track final duration using activity-aware calculation@@ -379,7 +395,7 @@ export default function PagesVerticalViewer({const removeQueryParams = (queries: string[]) => {const currentQuery = { ...router.query };const currentPath = router.asPath.split("?")[0];- queries.map((query) => delete currentQuery[query]);+ queries.forEach((query) => delete currentQuery[query]);router.replace({@@ -391,10 +407,10 @@ export default function PagesVerticalViewer({);};- if (!dataroomId && router.query.token) {+ if (router.isReady && !dataroomId && router.query.token) {removeQueryParams(["token", "email", "domain", "slug", "linkId"]);}- }, []); // Run once on mount+ }, [dataroomId, router, router.isReady]);const handleScroll = () => {const container = containerRef.current;@@ -432,7 +448,6 @@ export default function PagesVerticalViewer({if (isFeedbackVisible) {setPageNumber(numPagesWithFeedback);- pageNumberRef.current = numPagesWithFeedback;startTimeRef.current = Date.now();return;}@@ -455,7 +470,6 @@ export default function PagesVerticalViewer({}setPageNumber(maxVisiblePage);- pageNumberRef.current = maxVisiblePage;startTimeRef.current = Date.now();}};@@ -504,7 +518,7 @@ export default function PagesVerticalViewer({};const goToNextPage = () => {- if (pageNumber >= numPagesWithAccountCreation) return;+ if (pageNumber >= numPagesWithFeedback) return;if (pageNumber === numPages && enableQuestion && feedback) {const feedbackElement = document.getElementById("feedback-question");@@ -547,32 +561,11 @@ export default function PagesVerticalViewer({}};- const handleKeyDown = (event: KeyboardEvent) => {- switch (event.key) {- case "ArrowDown":- event.preventDefault(); // Prevent default behavior- event.stopPropagation(); // Stop propagation- goToNextPage();- break;- case "ArrowUp":- event.preventDefault(); // Prevent default behavior- event.stopPropagation(); // Stop propagation- goToPreviousPage();- break;- case "ArrowRight":- event.preventDefault(); // Prevent default behavior- event.stopPropagation(); // Stop propagation- goToNextPage();- break;- case "ArrowLeft":- event.preventDefault(); // Prevent default behavior- event.stopPropagation(); // Stop propagation- goToPreviousPage();- break;- default:- break;- }- };+ useViewerPageKeyboardShortcuts({+ orientation: "vertical",+ onPreviousPage: goToPreviousPage,+ onNextPage: goToNextPage,+ });const handleLinkClick = (href: string, event: React.MouseEvent) => {// Check if it's an internal page link or external link@@ -596,7 +589,6 @@ export default function PagesVerticalViewer({});setPageNumber(targetPage);- pageNumberRef.current = targetPage;// Wait for images to load before scrollingconst waitForImageAndScroll = () => {@@ -668,14 +660,6 @@ export default function PagesVerticalViewer({}};- useEffect(() => {- document.addEventListener("keydown", handleKeyDown);-- return () => {- document.removeEventListener("keydown", handleKeyDown);- };- }, [handleKeyDown, goToNextPage, goToPreviousPage]);-const handleScrollRef = useRef(handleScroll);handleScrollRef.current = handleScroll;@@ -704,14 +688,16 @@ export default function PagesVerticalViewer({}, []);const [containerWidth, setContainerWidth] = useState<number>(0);+ const [containerHeight, setContainerHeight] = useState<number>(0);- // Add resize observer to track container width+ // Add resize observer to track container width and heightuseEffect(() => {if (!containerRef.current) return;const resizeObserver = new ResizeObserver((entries) => {for (const entry of entries) {setContainerWidth(entry.contentRect.width);+ setContainerHeight(entry.contentRect.height);}});@@ -722,6 +708,41 @@ export default function PagesVerticalViewer({};}, []);+ // Rotating the viewport (and the container resize it triggers) changes each+ // page's rendered size, but per-page dimensions are otherwise only captured on+ // `img.onload`. Re-measure once the post-rotation layout has committed so the+ // dynamic watermark and link overlays — both sized from `imageDimensions` —+ // keep covering the rotated pages instead of using stale upright dimensions.+ useEffect(() => {+ if (typeof window === "undefined") return;++ const measure = () => {+ setImageDimensions((prev) => {+ let changed = false;+ const next = { ...prev };+ imageRefs.current.forEach((img, index) => {+ if (!img) return;+ const width = img.clientWidth;+ const height = img.clientHeight;+ if (!width || !height) return;+ const existing = next[index];+ if (+ !existing ||+ existing.width !== width ||+ existing.height !== height+ ) {+ next[index] = { width, height };+ changed = true;+ }+ });+ return changed ? next : prev;+ });+ };++ const raf = requestAnimationFrame(measure);+ return () => cancelAnimationFrame(raf);+ }, [rotation, isFullscreen, isPseudoFullscreen, containerWidth, containerHeight]);+const handleZoomIn = () => {setScale((prev) => Math.min(prev + 0.25, 3)); // Max zoom 3x};@@ -730,139 +751,166 @@ export default function PagesVerticalViewer({setScale((prev) => Math.max(prev - 0.25, 0.5)); // Min zoom 0.5x};- // Add fullscreen handler- const handleFullscreen = () => {- if (!document.fullscreenElement) {- document.documentElement.requestFullscreen().catch((err) => {- console.error("Error attempting to enable fullscreen:", err);- });- } else {- document.exitFullscreen();- }- };+ useViewerKeyboardShortcuts({+ onZoomIn: handleZoomIn,+ onZoomOut: handleZoomOut,+ onResetZoom: () => setScale(1),+ onToggleFullscreen: toggleFullscreen,+ });++ const { isPinching } = useTouchZoom({+ containerRef,+ scale,+ setScale,+ minScale: 1,+ maxScale: 3,+ enabled: isMobile,+ });- // Add keyboard shortcuts for zooming and fullscreen+ // Measure the unscaled content size so the sizer can reserve the scaled+ // scroll area. Re-measures as pages load (height grows) or the viewport+ // resizes (width changes); the transform never changes these layout metrics,+ // so observing the content element does not feed back into itself.useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- // Don't trigger shortcuts when typing in inputs or textareas- const target = e.target as HTMLElement;- if (- target.tagName === "INPUT" ||- target.tagName === "TEXTAREA" ||- target.isContentEditable- ) {- return;- }+ const el = zoomContentRef.current;+ if (!el) return;+ const measure = () =>+ setBaseSize({ width: el.offsetWidth, height: el.offsetHeight });+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);- if (e.metaKey || e.ctrlKey) {- if (e.key === "=" || e.key === "+") {- e.preventDefault();- handleZoomIn();- } else if (e.key === "-") {- e.preventDefault();- handleZoomOut();- } else if (e.key === "0") {- e.preventDefault();- setScale(1);- }- } else if (e.key === "f" || e.key === "F") {- e.preventDefault();- handleFullscreen();- }- };+ // In fullscreen a non-zero rotation turns the viewport into a fixed, rotated+ // full-viewport layer (see getRotationLayerStyle); otherwise it just sizes to+ // the available height. The scroll container fills the swapped box, so the+ // ResizeObserver reports the rotated width/height and the per-page fullscreen+ // sizing below scales each page to the physical viewport height automatically.+ const viewportStyle = (isFullscreen &&+ getRotationLayerStyle(rotation, viewerBackgroundColor)) || {+ height: isPseudoFullscreen ? "100dvh" : "calc(100dvh - 64px)",+ };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, []);+ // Pseudo-fullscreen (iPhone, no native Fullscreen API) hides the navbar, so+ // this overlay is the only way to rotate or exit and must stay regardless of+ // the viewport breakpoint — an iPhone rotated to landscape reports > 640px,+ // which flips `isMobile` to false and would otherwise strand the viewer.+ const showFullscreenOverlay = isFullscreen && (isMobile || isPseudoFullscreen);return (- <>- <Nav- pageNumber={pageNumber}- numPages={numPagesWithAccountCreation}- embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}- hasWatermark={watermarkConfig ? true : false}- handleZoomIn={handleZoomIn}- handleZoomOut={handleZoomOut}- handleFullscreen={handleFullscreen}- navData={navData}- />- <div- style={{ height: "calc(100dvh - 64px)" }}- className="relative overflow-hidden"- >- <ResizablePanelGroup orientation="horizontal">+ <div+ className={cn(isPseudoFullscreen && "fixed inset-0 z-[60]")}+ style={+ isPseudoFullscreen+ ? { backgroundColor: viewerBackgroundColor }+ : undefined+ }+ >+ {/* While presenting, tint the browser chrome to the viewer background+ (accent) so iOS Safari's status-bar/safe-area matches the immersive+ document instead of the brand-colored top bar. Rendering it here (a+ deeper next/head entry than the base brand ViewerThemeColor) makes the+ accent win, and it reverts on exit. */}+ {isFullscreen && <ViewerThemeColor color={viewerBackgroundColor} />}+ {!isPseudoFullscreen && (+ <Nav+ pageNumber={pageNumber}+ numPages={numPagesWithFeedback}+ embeddedLinks={pages[pageNumber - 1]?.embeddedLinks}+ hasWatermark={watermarkConfig ? true : false}+ handleZoomIn={handleZoomIn}+ handleZoomOut={handleZoomOut}+ handleFullscreen={toggleFullscreen}+ isFullscreen={isFullscreen}+ navData={navData}+ />+ )}+ <div style={viewportStyle} className="relative overflow-hidden">+ <div className="h-full w-full">{/* Document Content */}- <ResizablePanel defaultSize="100%">+ <div className="h-full w-full"><divclassName={cn("h-full w-full",- "overflow-auto scroll-smooth",+ "overflow-auto",+ // Disable smooth scrolling while pinching so the focal-point+ // scroll compensation lands instantly instead of animating and+ // drifting out from under the fingers.+ !isPinching && "scroll-smooth",!isWindowFocused &&screenshotProtectionEnabled &&"blur-xl transition-all duration-300",)}+ style={isMobile ? { touchAction: "pan-x pan-y" } : undefined}ref={containerRef}>- <div className="flex min-h-full min-w-full justify-center">+ {/* Sizer: `margin: 0 auto` centers the content when it fits and+ left-aligns it (scrollable from the left edge) once it grows+ wider than the viewport — unlike flex centering, which clips+ the overflowing start. Locks to the scaled dimensions only+ when zoomed so default layout stays responsive. */}+ <div+ className="mx-auto"+ style={+ scale > 1 && baseSize+ ? {+ width: `${baseSize.width * scale}px`,+ height: `${baseSize.height * scale}px`,+ }+ : { width: "fit-content" }+ }+ ><div- className="flex w-full max-w-[1400px] justify-center"+ ref={zoomContentRef}+ className="transform-container"style={{- minWidth: scale > 1 ? `${100 * scale}%` : "100%",+ width: "fit-content",+ transform: `scale(${scale})`,+ transition: isPinching ? "none" : "transform 0.2s ease-out",+ transformOrigin: "0 0",}}><div- className="transform-container w-full"- style={{- transform: `scale(${scale})`,- transition: "transform 0.2s ease-out",- transformOrigin: "center top",+ className="flex flex-col items-center gap-2"+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();}}>- <div- className="flex flex-col items-center gap-2"- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- >- {pages.map((page, index) => {- const optimalWidth = containerWidth- ? calculateOptimalWidth(+ {pages.map((page, index) => {+ const aspectRatio =+ page.metadata && page.metadata.height > 0+ ? page.metadata.width / page.metadata.height+ : 0;+ // In fullscreen scale each page up to fill the viewport+ // height (bounded by the container width) so a render+ // smaller than the screen still fills it, instead of+ // sitting at the default max width.+ const optimalWidth =+ isFullscreen && containerHeight && aspectRatio+ ? Math.min(containerWidth,- page.metadata,- isMobile,- isTablet,+ containerHeight * aspectRatio,)- : 800;-- // Calculate placeholder height from metadata aspect ratio- const placeholderHeight =- page.metadata && page.metadata.width > 0- ? (optimalWidth * page.metadata.height) /- page.metadata.width- : 600; // fallback height-- if (!page.file) {- // Render a placeholder div with correct dimensions to preserve scroll height- return (- <div- key={index}- className="relative w-full px-4 md:px-8"- style={{- width: `${optimalWidth}px`,- }}- >- <div- className="viewer-container relative border-b border-t border-gray-100 bg-gray-50"- style={{- height: `${placeholderHeight}px`,- }}- />- </div>- );- }-+ : containerWidth+ ? calculateOptimalWidth(+ containerWidth,+ page.metadata,+ isMobile,+ isTablet,+ )+ : 800;++ // Calculate placeholder height from metadata aspect ratio+ const placeholderHeight =+ page.metadata && page.metadata.width > 0+ ? (optimalWidth * page.metadata.height) /+ page.metadata.width+ : 600; // fallback height++ if (!page.file) {+ // Render a placeholder div with correct dimensions to preserve scroll heightreturn (<divkey={index}@@ -871,86 +919,110 @@ export default function PagesVerticalViewer({width: `${optimalWidth}px`,}}>- <div className="viewer-container relative border-b border-t border-gray-100">- <div- className="pointer-events-none absolute bottom-0 left-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to top, #f3f4f6, transparent)",- }}- />- <div- className="pointer-events-none absolute bottom-0 right-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to top, #f3f4f6, transparent)",- }}- />- <div- className="pointer-events-none absolute left-0 top-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to bottom, #f3f4f6, transparent)",- }}- />- <div- className="pointer-events-none absolute right-0 top-0 w-px"- style={{- height: "10%",- background:- "linear-gradient(to bottom, #f3f4f6, transparent)",- }}- />- <img- className="viewer-image-mobile h-auto w-full object-contain"- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- }}- ref={(ref) => {- imageRefs.current[index] = ref;- if (ref) {- ref.onload = () =>- setImageDimensions((prev) => ({- ...prev,- [index]: {- width: ref.clientWidth,- height: ref.clientHeight,- },- }));+ <div+ className="viewer-container relative border-b border-t border-gray-100 bg-gray-50"+ style={{+ height: `${placeholderHeight}px`,+ }}+ />+ </div>+ );+ }++ return (+ <div+ key={index}+ className="relative w-full px-4 md:px-8"+ style={{+ width: `${optimalWidth}px`,+ }}+ >+ <div className="viewer-container relative border-b border-t border-gray-100">+ <div+ className="pointer-events-none absolute bottom-0 left-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to top, #f3f4f6, transparent)",+ }}+ />+ <div+ className="pointer-events-none absolute bottom-0 right-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to top, #f3f4f6, transparent)",+ }}+ />+ <div+ className="pointer-events-none absolute left-0 top-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to bottom, #f3f4f6, transparent)",+ }}+ />+ <div+ className="pointer-events-none absolute right-0 top-0 w-px"+ style={{+ height: "10%",+ background:+ "linear-gradient(to bottom, #f3f4f6, transparent)",+ }}+ />+ <img+ className="viewer-image-mobile h-auto w-full object-contain"+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ ref={(ref) => {+ imageRefs.current[index] = ref;+ if (ref) {+ ref.onload = () =>+ setImageDimensions((prev) => ({+ ...prev,+ [index]: {+ width: ref.clientWidth,+ height: ref.clientHeight,+ },+ }));+ }+ }}+ useMap={`#page-map-${index + 1}`}+ src={page.file}+ alt={`Page ${index + 1}`}+ />++ {watermarkConfig && imageDimensions[index] ? (+ <div className="absolute left-0 top-0">+ <SVGWatermark+ config={watermarkConfig}+ viewerData={{+ email: viewerEmail,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ link: linkName,+ ipAddress: ipAddress,+ }}+ documentDimensions={imageDimensions[index]}+ pageIndex={index}+ />+ </div>+ ) : null}+ </div>++ {page.pageLinks ? (+ <map name={`page-map-${index + 1}`}>+ {page.pageLinks+ .filter((link) => !link.href.endsWith(".gif"))+ .map((link, linkIndex) => {+ const safeHref = getSafeLinkHref(link.href);+ if (!safeHref) {+ return null;}- }}- useMap={`#page-map-${index + 1}`}- src={page.file}- alt={`Page ${index + 1}`}- />-- {watermarkConfig && imageDimensions[index] ? (- <div className="absolute left-0 top-0">- <SVGWatermark- config={watermarkConfig}- viewerData={{- email: viewerEmail,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- link: linkName,- ipAddress: ipAddress,- }}- documentDimensions={imageDimensions[index]}- pageIndex={index}- />- </div>- ) : null}- </div>-- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter((link) => !link.href.endsWith(".gif"))- .map((link, linkIndex) => (+ const isInternal = safeHref.startsWith("#");+ return (<areakey={linkIndex}shape="rect"@@ -958,89 +1030,86 @@ export default function PagesVerticalViewer({link.coords,getScaleFactor({naturalHeight: page.metadata.height,- scaleFactor:- page.metadata.scaleFactor,+ scaleFactor: page.metadata.scaleFactor,+ pageIndex: index,}),)}- href={link.href}+ href={safeHref}onClick={(e) =>- handleLinkClick(link.href, e)- }- target={- link.href.startsWith("#")- ? "_self"- : "_blank"+ handleLinkClick(safeHref, e)}+ target={isInternal ? "_self" : "_blank"}rel={- link.href.startsWith("#")+ isInternal? undefined: "noopener noreferrer"}/>- ))}- </map>- ) : null}-- {page.pageLinks && imageDimensions[index]- ? page.pageLinks- .filter((link) => link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )- .split(",")- .map(Number);-- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;-- // Account for the padding on the outer container (px-4 md:px-8)- const padding = isMobile ? 16 : 32; // 1rem = 16px (px-4), 2rem = 32px (px-8)-- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href}- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1 + padding,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none",- }}- />- );- })- : null}- </div>- );- })}-- {enableQuestion &&- feedback &&- pageNumber >= numPagesWithFeedback - 1 && (- <div- id="feedback-question"- className={cn("relative block h-dvh w-full")}- style={{ height: "calc(100dvh - 64px)" }}- >- <Question- accentColor={brand?.accentColor}- feedback={feedback}- viewId={viewId}- submittedFeedback={submittedFeedback}- setSubmittedFeedback={setSubmittedFeedback}- isPreview={isPreview}- />- </div>- )}- </div>+ );+ })}+ </map>+ ) : null}++ {page.pageLinks && imageDimensions[index]+ ? page.pageLinks+ .filter((link) => link.href.endsWith(".gif"))+ .map((link, linkIndex) => {+ const [x1, y1, x2, y2] = scaleCoordinates(+ link.coords,+ getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ pageIndex: index,+ }),+ )+ .split(",")+ .map(Number);++ const overlayWidth = x2 - x1;+ const overlayHeight = y2 - y1;++ // Account for the padding on the outer container (px-4 md:px-8)+ const padding = isMobile ? 16 : 32; // 1rem = 16px (px-4), 2rem = 32px (px-8)++ return (+ <img+ key={`overlay-${index}-${linkIndex}`}+ src={link.href}+ alt={`Overlay ${index + 1}`}+ style={{+ position: "absolute",+ top: y1,+ left: x1 + padding,+ width: `${overlayWidth}px`,+ height: `${overlayHeight}px`,+ pointerEvents: "none",+ }}+ />+ );+ })+ : null}+ </div>+ );+ })}++ {enableQuestion &&+ feedback &&+ pageNumber >= numPagesWithFeedback - 1 && (+ <div+ id="feedback-question"+ className={cn("relative block h-dvh w-full")}+ style={{ height: "calc(100dvh - 64px)" }}+ >+ <Question+ accentColor={brand?.accentColor}+ feedback={feedback}+ viewId={viewId}+ submittedFeedback={submittedFeedback}+ setSubmittedFeedback={setSubmittedFeedback}+ isPreview={isPreview}+ />+ </div>+ )}</div></div></div>@@ -1075,14 +1144,14 @@ export default function PagesVerticalViewer({<divclassName={cn("absolute bottom-0 left-0 right-0 flex h-24 items-end justify-center pb-4 transition-opacity duration-200",- pageNumber >= numPagesWithAccountCreation+ pageNumber >= numPagesWithFeedback? "hidden": "opacity-0 hover:opacity-100",)}onClick={goToNextPage}><button- disabled={pageNumber >= numPagesWithAccountCreation}+ disabled={pageNumber >= numPagesWithFeedback}className="rounded-full bg-gray-950/50 p-1 hover:bg-gray-950/75"><ChevronDownIcon className="h-10 w-10 text-white" />@@ -1100,7 +1169,12 @@ export default function PagesVerticalViewer({) : null}{screenshotProtectionEnabled ? <ScreenProtector /> : null}- {confidentialViewEnabled ? <ConfidentialViewOverlay /> : null}+ {confidentialViewEnabled ? (+ <ConfidentialViewOverlay+ navbarAbove={!isPseudoFullscreen && rotation === 0}+ rotation={rotation}+ />+ ) : null}{showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}<AwayPosterisVisible={isInactive}@@ -1109,11 +1183,20 @@ export default function PagesVerticalViewer({}onDismiss={updateActivity}/>- {/* </div> */}- {/* </div> */}- </ResizablePanel>- </ResizablePanelGroup>+ </div>+ </div>+ {/* Placed inside the viewport so the rotate/exit buttons rotate with+ the presentation and land at the presentation's top-right (not the+ physical screen's) after a quarter turn, matching the horizontal+ viewer. */}+ {showFullscreenOverlay ? (+ <FullscreenControls+ showRotate+ onRotate={rotate}+ onExit={toggleFullscreen}+ />+ ) : null}</div>- </>+ </div>);}diff --git a/components/view/watermark-svg.tsx b/components/view/watermark-svg.tsxindex bc696de4..c3ba1e48 100644--- a/components/view/watermark-svg.tsx+++ b/components/view/watermark-svg.tsx@@ -20,10 +20,14 @@ export const SVGWatermark = ({const { width, height } = documentDimensions;- // Calculate a responsive font size+ // Font size stays proportional to the rendered document at every size, so the+ // watermark (and the tiled pattern derived from it) scales uniformly with the+ // page instead of freezing once the page grows past ~1000px. config.fontSize+ // is the proportionality coefficient, not a hard ceiling. Keep a small floor+ // for legibility on thumbnails.const calculateFontSize = () => {const baseFontSize = Math.min(width, height) * (config.fontSize / 1000);- return Math.max(8, Math.min(baseFontSize, config.fontSize)); // Clamp between 8px and config.fontSize+ return Math.max(8, baseFontSize);};const fontSize = calculateFontSize();diff --git a/lib/hooks/use-auto-hide-controls.ts b/lib/hooks/use-auto-hide-controls.tsnew file mode 100644index 00000000..31d24b67--- /dev/null+++ b/lib/hooks/use-auto-hide-controls.ts@@ -0,0 +1,48 @@+import { useCallback, useEffect, useRef, useState } from "react";++type UseAutoHideControlsOptions = {+ /** Auto-hiding is only active while this is true (e.g. in fullscreen). */+ active: boolean;+ /** Changing this re-shows the controls then restarts the hide timer (e.g. page number). */+ resetKey?: unknown;+ delayMs?: number;+};++/**+ * Shows a set of overlay controls, then fades them after `delayMs` so the+ * content is unobstructed. `reveal()` brings them back and restarts the timer.+ * While `active` is false the controls stay permanently visible.+ */+export function useAutoHideControls({+ active,+ resetKey,+ delayMs = 3000,+}: UseAutoHideControlsOptions) {+ const [visible, setVisible] = useState(true);+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const scheduleHide = useCallback(() => {+ if (timerRef.current) clearTimeout(timerRef.current);+ timerRef.current = setTimeout(() => setVisible(false), delayMs);+ }, [delayMs]);++ const reveal = useCallback(() => {+ setVisible(true);+ if (active) scheduleHide();+ }, [active, scheduleHide]);++ useEffect(() => {+ if (!active) {+ if (timerRef.current) clearTimeout(timerRef.current);+ setVisible(true);+ return;+ }+ setVisible(true);+ scheduleHide();+ return () => {+ if (timerRef.current) clearTimeout(timerRef.current);+ };+ }, [active, resetKey, scheduleHide]);++ return { visible, reveal };+}diff --git a/lib/hooks/use-disable-pull-to-refresh.ts b/lib/hooks/use-disable-pull-to-refresh.tsnew file mode 100644index 00000000..0d1ef4f2--- /dev/null+++ b/lib/hooks/use-disable-pull-to-refresh.ts@@ -0,0 +1,93 @@+import { useEffect } from "react";++type SavedStyles = {+ htmlOverflow: string;+ htmlOverscroll: string;+ bodyOverflow: string;+ bodyOverscroll: string;+ bodyPosition: string;+ bodyTop: string;+ bodyLeft: string;+ bodyRight: string;+ bodyWidth: string;+};++let lockCount = 0;+let saved: SavedStyles | null = null;+let savedScrollY = 0;++const isTouchDevice = () =>+ typeof window !== "undefined" &&+ ("ontouchstart" in window ||+ (navigator.maxTouchPoints ?? 0) > 0 ||+ (typeof window.matchMedia === "function" &&+ window.matchMedia("(pointer: coarse)").matches));++const applyLock = () => {+ const html = document.documentElement;+ const body = document.body;+ saved = {+ htmlOverflow: html.style.overflow,+ htmlOverscroll: html.style.overscrollBehaviorY,+ bodyOverflow: body.style.overflow,+ bodyOverscroll: body.style.overscrollBehaviorY,+ bodyPosition: body.style.position,+ bodyTop: body.style.top,+ bodyLeft: body.style.left,+ bodyRight: body.style.right,+ bodyWidth: body.style.width,+ };+ savedScrollY = window.scrollY;+ // overscroll-behavior alone does not defeat iOS Safari's pull-to-refresh+ // when the body is not the scroll container (the document lives inside an+ // inner overflow-auto div). Making the body structurally non-scrollable via+ // position:fixed leaves pull-to-refresh nothing to pull on. The scroll+ // position is preserved and restored on release.+ html.style.overflow = "hidden";+ html.style.overscrollBehaviorY = "none";+ body.style.overflow = "hidden";+ body.style.overscrollBehaviorY = "none";+ body.style.position = "fixed";+ body.style.top = `-${savedScrollY}px`;+ body.style.left = "0";+ body.style.right = "0";+ body.style.width = "100%";+};++const releaseLock = () => {+ if (!saved) return;+ const html = document.documentElement;+ const body = document.body;+ html.style.overflow = saved.htmlOverflow;+ html.style.overscrollBehaviorY = saved.htmlOverscroll;+ body.style.overflow = saved.bodyOverflow;+ body.style.overscrollBehaviorY = saved.bodyOverscroll;+ body.style.position = saved.bodyPosition;+ body.style.top = saved.bodyTop;+ body.style.left = saved.bodyLeft;+ body.style.right = saved.bodyRight;+ body.style.width = saved.bodyWidth;+ window.scrollTo(0, savedScrollY);+ saved = null;+};++/**+ * Structurally locks `<body>` scroll while mounted so iOS Safari's+ * pull-to-refresh has nothing to pull on. No-op on non-touch devices, where+ * `position: fixed` on the body would break native scrolling.+ *+ * Reference-counted so overlapping callers (e.g. a viewer plus the+ * confidential-view overlay it renders) share one lock; the body is restored+ * only after the last caller unmounts.+ */+export function useDisablePullToRefresh(enabled = true) {+ useEffect(() => {+ if (!enabled || !isTouchDevice()) return;+ lockCount += 1;+ if (lockCount === 1) applyLock();+ return () => {+ lockCount -= 1;+ if (lockCount === 0) releaseLock();+ };+ }, [enabled]);+}diff --git a/lib/hooks/use-fullscreen.ts b/lib/hooks/use-fullscreen.tsnew file mode 100644index 00000000..2c182fdc--- /dev/null+++ b/lib/hooks/use-fullscreen.ts@@ -0,0 +1,204 @@+import { CSSProperties, useCallback, useEffect, useState } from "react";++type FullscreenElement = HTMLElement & {+ webkitRequestFullscreen?: () => Promise<void> | void;+};++type FullscreenDocument = Document & {+ webkitFullscreenElement?: Element | null;+ webkitExitFullscreen?: () => Promise<void> | void;+};++const getNativeFullscreenElement = () => {+ if (typeof document === "undefined") return null;+ const doc = document as FullscreenDocument;+ return document.fullscreenElement ?? doc.webkitFullscreenElement ?? null;+};++const supportsNativeFullscreen = () => {+ if (typeof document === "undefined") return false;+ const el = document.documentElement as FullscreenElement;+ return (+ typeof el.requestFullscreen === "function" ||+ typeof el.webkitRequestFullscreen === "function"+ );+};++/**+ * Cross-platform viewer fullscreen.+ *+ * Desktop, Android Chrome and iPadOS support the native Fullscreen API, so we+ * use it there. iPhone Safari/Chrome (all iOS browsers are WebKit) do not+ * implement the API for non-video elements — `requestFullscreen` is undefined —+ * so the button previously did nothing. There we fall back to a CSS+ * "pseudo-fullscreen": the caller expands the viewer to fill the viewport+ * (`position: fixed`, `100dvh`) and hides its own chrome. `isFullscreen`+ * reflects either mode so the UI can render a single toggle.+ */+/** Quarter-turn rotation applied to the content while presenting fullscreen. */+export type Rotation = 0 | 90 | 180 | 270;++/**+ * Fixed, full-viewport layer style for a rotated presentation. Rotating the+ * *content* (rather than relying on the device) lets a viewer hold the phone+ * upright with orientation lock on and still see a slide landscape, without the+ * browser chrome that appears when the device itself is turned.+ *+ * For quarter turns the width/height are swapped (`100dvh` x `100dvw`) so the+ * rotated box fills the physical viewport; the black background covers the+ * letterbox bands.+ */+export function getRotationLayerStyle(+ rotation: Rotation,+ backgroundColor = "black",+): CSSProperties | null {+ if (rotation === 0) return null;+ const quarter = rotation === 90 || rotation === 270;+ return {+ position: "fixed",+ top: "50%",+ left: "50%",+ width: quarter ? "100dvh" : "100dvw",+ height: quarter ? "100dvw" : "100dvh",+ transform: `translate(-50%, -50%) rotate(${rotation}deg)`,+ transformOrigin: "center center",+ backgroundColor,+ zIndex: 60,+ };+}++/**+ * Map a physical (screen-space) swipe delta into the rotated content's own+ * coordinate frame so horizontal navigation keeps working after a quarter turn.+ * CSS `rotate(r)` maps content -> screen by R(r); the inverse R(-r) recovers the+ * content-space delta from the observed screen delta.+ */+export function unrotateDelta(+ dx: number,+ dy: number,+ rotation: Rotation,+): { dx: number; dy: number } {+ switch (rotation) {+ case 0:+ return { dx, dy };+ case 90:+ return { dx: dy, dy: -dx };+ case 180:+ return { dx: -dx, dy: -dy };+ case 270:+ return { dx: -dy, dy: dx };+ default: {+ const _exhaustive: never = rotation;+ return { dx, dy };+ }+ }+}++/**+ * `object-contain` keeps an image's aspect ratio and centers it inside its+ * element box. In fullscreen the box is stretched taller/wider than the visible+ * image by the fill-height and max-width caps, so the measured `clientWidth`/+ * `clientHeight` overstates the document. Given the element box and the image's+ * aspect ratio, return the visible image rect and its centering offset so+ * overlays (e.g. the watermark) cover the document exactly and scale uniformly+ * with it instead of drifting into the letterbox bands.+ */+export function getContainedImageRect(+ boxWidth: number,+ boxHeight: number,+ aspectRatio: number,+): { width: number; height: number; left: number; top: number } {+ if (!boxWidth || !boxHeight || !aspectRatio) {+ return { width: boxWidth, height: boxHeight, left: 0, top: 0 };+ }+ const boxAspect = boxWidth / boxHeight;+ let width = boxWidth;+ let height = boxHeight;+ if (aspectRatio > boxAspect) {+ height = boxWidth / aspectRatio;+ } else {+ width = boxHeight * aspectRatio;+ }+ return {+ width,+ height,+ left: (boxWidth - width) / 2,+ top: (boxHeight - height) / 2,+ };+}++export function useFullscreen() {+ const [isNativeFullscreen, setIsNativeFullscreen] = useState(false);+ const [isPseudoFullscreen, setIsPseudoFullscreen] = useState(false);+ const [rotation, setRotation] = useState<Rotation>(0);++ useEffect(() => {+ const sync = () => setIsNativeFullscreen(!!getNativeFullscreenElement());+ document.addEventListener("fullscreenchange", sync);+ document.addEventListener("webkitfullscreenchange", sync);+ return () => {+ document.removeEventListener("fullscreenchange", sync);+ document.removeEventListener("webkitfullscreenchange", sync);+ };+ }, []);++ // Escape exits pseudo-fullscreen (native fullscreen handles Escape itself).+ useEffect(() => {+ if (!isPseudoFullscreen) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") setIsPseudoFullscreen(false);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [isPseudoFullscreen]);++ const isFullscreen = isNativeFullscreen || isPseudoFullscreen;++ // Rotation is a fullscreen-only presentation affordance; drop it whenever we+ // leave fullscreen so re-entering always starts upright.+ useEffect(() => {+ if (!isFullscreen) setRotation(0);+ }, [isFullscreen]);++ // A single control that toggles the presentation between upright and one+ // quarter turn. The geometry helpers stay general (any multiple of 90) so a+ // future multi-step control needs no rework here.+ const rotate = useCallback(() => {+ setRotation((prev) => (prev === 0 ? 90 : 0));+ }, []);++ const toggleFullscreen = useCallback(() => {+ if (isPseudoFullscreen) {+ setIsPseudoFullscreen(false);+ return;+ }++ if (!supportsNativeFullscreen()) {+ setIsPseudoFullscreen(true);+ return;+ }++ const doc = document as FullscreenDocument;+ if (getNativeFullscreenElement()) {+ (doc.exitFullscreen ?? doc.webkitExitFullscreen)?.call(document);+ return;+ }++ const el = document.documentElement as FullscreenElement;+ const request = el.requestFullscreen ?? el.webkitRequestFullscreen;+ const result = request?.call(el);+ // Some browsers reject the promise when the gesture is not trusted; fall+ // back to pseudo-fullscreen so the button always does something.+ if (result && typeof (result as Promise<void>).catch === "function") {+ (result as Promise<void>).catch(() => setIsPseudoFullscreen(true));+ }+ }, [isPseudoFullscreen]);++ return {+ isFullscreen,+ isPseudoFullscreen,+ toggleFullscreen,+ rotation,+ rotate,+ };+}diff --git a/lib/hooks/use-touch-zoom.ts b/lib/hooks/use-touch-zoom.tsnew file mode 100644index 00000000..81c0136d--- /dev/null+++ b/lib/hooks/use-touch-zoom.ts@@ -0,0 +1,133 @@+import { RefObject, useEffect, useLayoutEffect, useRef, useState } from "react";++type UseTouchZoomOptions = {+ /** Element that receives the touch gestures (the scroll/zoom container). */+ containerRef: RefObject<HTMLElement>;+ /** Current zoom scale. */+ scale: number;+ /** Setter for the zoom scale (functional updates supported). */+ setScale: (updater: (prev: number) => number) => void;+ minScale?: number;+ maxScale?: number;+ enabled?: boolean;+};++const distance = (a: Touch, b: Touch) =>+ Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);++/**+ * Focal-point-aware two-finger pinch-to-zoom for the continuous vertical viewer.+ *+ * The browser's native pinch-zoom operates on the visual viewport and fights+ * the viewer's own scroll container, so we drive the existing `scale` state+ * directly. Listeners are attached natively with `passive: false` because+ * React's synthetic touch handlers are passive and cannot `preventDefault()`+ * the browser gesture.+ *+ * Position awareness: the content is scaled with `transform-origin: 0 0` inside+ * a sizer that reserves the scaled dimensions, so the scroll area grows in both+ * axes. On each pinch move we record the content point under the finger midpoint+ * and, once the new scale has reflowed (layout effect), we set `scrollLeft` /+ * `scrollTop` so that point stays under the fingers. Without this the page+ * scaled from a fixed origin and snapped back to the top.+ */+export function useTouchZoom({+ containerRef,+ scale,+ setScale,+ minScale = 1,+ maxScale = 3,+ enabled = true,+}: UseTouchZoomOptions) {+ const scaleRef = useRef(scale);+ scaleRef.current = scale;++ const pinchRef = useRef<{ startDistance: number; startScale: number } | null>(+ null,+ );+ // The content point (in unscaled content coordinates) that must stay under+ // the finger midpoint, plus that midpoint relative to the scroll viewport.+ // Captured each move, consumed once by the layout effect after the new scale+ // has reflowed, then cleared so later (button) zoom changes don't reuse it.+ const focalRef = useRef<{+ ux: number;+ uy: number;+ fx: number;+ fy: number;+ } | null>(null);++ const [isPinching, setIsPinching] = useState(false);++ useLayoutEffect(() => {+ const el = containerRef.current;+ const focal = focalRef.current;+ if (!el || !focal) return;+ const maxLeft = el.scrollWidth - el.clientWidth;+ const maxTop = el.scrollHeight - el.clientHeight;+ el.scrollLeft = Math.max(0, Math.min(maxLeft, focal.ux * scale - focal.fx));+ el.scrollTop = Math.max(0, Math.min(maxTop, focal.uy * scale - focal.fy));+ focalRef.current = null;+ }, [scale, containerRef]);++ useEffect(() => {+ const el = containerRef.current;+ if (!el || !enabled) return;++ const clamp = (value: number) =>+ Math.min(maxScale, Math.max(minScale, value));++ const onTouchStart = (e: TouchEvent) => {+ if (e.touches.length === 2) {+ pinchRef.current = {+ startDistance: distance(e.touches[0], e.touches[1]),+ startScale: scaleRef.current,+ };+ setIsPinching(true);+ e.preventDefault();+ }+ };++ const onTouchMove = (e: TouchEvent) => {+ if (e.touches.length === 2 && pinchRef.current) {+ e.preventDefault();+ const a = e.touches[0];+ const b = e.touches[1];+ const rect = el.getBoundingClientRect();+ const fx = (a.clientX + b.clientX) / 2 - rect.left;+ const fy = (a.clientY + b.clientY) / 2 - rect.top;+ const current = scaleRef.current;+ focalRef.current = {+ ux: (el.scrollLeft + fx) / current,+ uy: (el.scrollTop + fy) / current,+ fx,+ fy,+ };+ const ratio = distance(a, b) / pinchRef.current.startDistance;+ const next = clamp(pinchRef.current.startScale * ratio);+ scaleRef.current = next;+ setScale(() => next);+ }+ };++ const onTouchEnd = (e: TouchEvent) => {+ if (e.touches.length < 2) {+ pinchRef.current = null;+ setIsPinching(false);+ }+ };++ el.addEventListener("touchstart", onTouchStart, { passive: false });+ el.addEventListener("touchmove", onTouchMove, { passive: false });+ el.addEventListener("touchend", onTouchEnd, { passive: false });+ el.addEventListener("touchcancel", onTouchEnd, { passive: false });++ return () => {+ el.removeEventListener("touchstart", onTouchStart);+ el.removeEventListener("touchmove", onTouchMove);+ el.removeEventListener("touchend", onTouchEnd);+ el.removeEventListener("touchcancel", onTouchEnd);+ };+ }, [containerRef, enabled, minScale, maxScale, setScale]);++ return { isPinching };+}diff --git a/lib/hooks/use-viewer-keyboard-shortcuts.ts b/lib/hooks/use-viewer-keyboard-shortcuts.tsnew file mode 100644index 00000000..dd6ffc08--- /dev/null+++ b/lib/hooks/use-viewer-keyboard-shortcuts.ts@@ -0,0 +1,159 @@+import { useEffect, useRef } from "react";++type ViewerKeyboardShortcutsOptions = {+ enabled?: boolean;+ onZoomIn?: () => void;+ onZoomOut?: () => void;+ onResetZoom?: () => void;+ onToggleFullscreen?: () => void;+};++type ViewerPageKeyboardShortcutsOptions = {+ enabled?: boolean;+ orientation: "horizontal" | "vertical";+ onPreviousPage: () => void;+ onNextPage: () => void;+};++const isTextInputTarget = (target: EventTarget | null) => {+ if (!(target instanceof HTMLElement)) return false;+ return (+ target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.tagName === "SELECT" ||+ target.isContentEditable+ );+};++const hasModifierKey = (event: KeyboardEvent) =>+ event.altKey || event.metaKey || event.ctrlKey || event.shiftKey;++export function useViewerKeyboardShortcuts({+ enabled = true,+ onZoomIn,+ onZoomOut,+ onResetZoom,+ onToggleFullscreen,+}: ViewerKeyboardShortcutsOptions) {+ const callbacksRef = useRef({+ onZoomIn,+ onZoomOut,+ onResetZoom,+ onToggleFullscreen,+ });++ callbacksRef.current = {+ onZoomIn,+ onZoomOut,+ onResetZoom,+ onToggleFullscreen,+ };++ useEffect(() => {+ if (!enabled) return;++ const handleKeyDown = (event: KeyboardEvent) => {+ if (isTextInputTarget(event.target)) return;++ const {+ onZoomIn,+ onZoomOut,+ onResetZoom,+ onToggleFullscreen,+ } = callbacksRef.current;++ if (event.metaKey || event.ctrlKey) {+ if (event.key === "=" || event.key === "+") {+ if (!onZoomIn) return;+ event.preventDefault();+ onZoomIn();+ return;+ }++ if (event.key === "-") {+ if (!onZoomOut) return;+ event.preventDefault();+ onZoomOut();+ return;+ }++ if (event.key === "0") {+ if (!onResetZoom) return;+ event.preventDefault();+ onResetZoom();+ }+ return;+ }++ if (event.key === "f" || event.key === "F") {+ if (!onToggleFullscreen) return;+ event.preventDefault();+ onToggleFullscreen();+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [enabled]);+}++export function useViewerPageKeyboardShortcuts({+ enabled = true,+ orientation,+ onPreviousPage,+ onNextPage,+}: ViewerPageKeyboardShortcutsOptions) {+ const callbacksRef = useRef({+ onPreviousPage,+ onNextPage,+ });++ callbacksRef.current = {+ onPreviousPage,+ onNextPage,+ };++ useEffect(() => {+ if (!enabled) return;++ const handleKeyDown = (event: KeyboardEvent) => {+ // A nested widget (e.g. a Radix menu) may have already consumed the arrow+ // key for its own navigation; don't also page the document.+ if (event.defaultPrevented) return;+ if (isTextInputTarget(event.target)) return;+ if (hasModifierKey(event)) return;++ if (event.key === "ArrowLeft") {+ event.preventDefault();+ event.stopPropagation();+ callbacksRef.current.onPreviousPage();+ return;+ }++ if (event.key === "ArrowRight") {+ event.preventDefault();+ event.stopPropagation();+ callbacksRef.current.onNextPage();+ return;+ }++ if (orientation !== "vertical") return;++ if (event.key === "ArrowUp") {+ event.preventDefault();+ event.stopPropagation();+ callbacksRef.current.onPreviousPage();+ return;+ }++ if (event.key === "ArrowDown") {+ event.preventDefault();+ event.stopPropagation();+ callbacksRef.current.onNextPage();+ }+ };++ document.addEventListener("keydown", handleKeyDown);+ return () => document.removeEventListener("keydown", handleKeyDown);+ }, [enabled, orientation]);+}diff --git a/lib/utils/sanitize-link-href.ts b/lib/utils/sanitize-link-href.tsnew file mode 100644index 00000000..68e604cf--- /dev/null+++ b/lib/utils/sanitize-link-href.ts@@ -0,0 +1,27 @@+/**+ * Page links come from document content and are rendered as clickable overlays.+ * Only allow same-page anchors and http(s)/mailto/tel URLs so unsafe schemes+ * (e.g. javascript:) can never be wired up to a click target. Returns the+ * original href when safe, or null when it should not be rendered.+ */+export const getSafeLinkHref = (href: string): string | null => {+ if (href.startsWith("#")) {+ return href;+ }+ try {+ const base =+ typeof window !== "undefined" ? window.location.href : "http://localhost";+ const url = new URL(href, base);+ if (+ url.protocol === "http:" ||+ url.protocol === "https:" ||+ url.protocol === "mailto:" ||+ url.protocol === "tel:"+ ) {+ return href;+ }+ } catch {+ return null;+ }+ return null;+};diff --git a/locales/de/viewer.json b/locales/de/viewer.jsonindex e9ff487b..8d682ba7 100644--- a/locales/de/viewer.json+++ b/locales/de/viewer.json@@ -11,6 +11,10 @@"teamMemberTooltip": "Verifizierung übersprungen, da Sie Teammitglied sind; es werden keine Analysen erfasst","changeLanguage": "Sprache ändern"},+ "fullscreenControls": {+ "rotate": "Drehen",+ "exitFullscreen": "Vollbild beenden"+ },"toasts": {"preparingDownload": "Download wird vorbereitet ...","preparingDownloadWatermark": "Download mit Wasserzeichen wird vorbereitet ...",diff --git a/locales/en/viewer.json b/locales/en/viewer.jsonindex b50571cb..162247ca 100644--- a/locales/en/viewer.json+++ b/locales/en/viewer.json@@ -6,11 +6,17 @@"linksOnCurrentPage": "Links on current page","zoomIn": "Zoom in","zoomOut": "Zoom out",+ "resetZoom": "Fit to screen","fullscreen": "Fullscreen",+ "exitFullscreen": "Exit fullscreen","downloadDocument": "Download document","teamMemberTooltip": "Skipped verification because you are a team member; no analytics will be collected","changeLanguage": "Change language"},+ "fullscreenControls": {+ "rotate": "Rotate",+ "exitFullscreen": "Exit fullscreen"+ },"toasts": {"preparingDownload": "Preparing download...","preparingDownloadWatermark": "Preparing download with watermark...",diff --git a/locales/es/viewer.json b/locales/es/viewer.jsonindex 15aa5736..323c5b15 100644--- a/locales/es/viewer.json+++ b/locales/es/viewer.json@@ -11,6 +11,10 @@"teamMemberTooltip": "Verificación omitida porque es miembro del equipo; no se recopilarán datos analíticos","changeLanguage": "Cambiar idioma"},+ "fullscreenControls": {+ "rotate": "Girar",+ "exitFullscreen": "Salir de pantalla completa"+ },"toasts": {"preparingDownload": "Preparando la descarga...","preparingDownloadWatermark": "Preparando la descarga con marca de agua...",diff --git a/locales/fr/viewer.json b/locales/fr/viewer.jsonindex a0f795c2..f50a3d2b 100644--- a/locales/fr/viewer.json+++ b/locales/fr/viewer.json@@ -11,6 +11,10 @@"teamMemberTooltip": "Vérification ignorée car vous êtes membre de l'équipe ; aucune analyse ne sera collectée","changeLanguage": "Changer de langue"},+ "fullscreenControls": {+ "rotate": "Pivoter",+ "exitFullscreen": "Quitter le plein écran"+ },"toasts": {"preparingDownload": "Préparation du téléchargement...","preparingDownloadWatermark": "Préparation du téléchargement avec filigrane...",diff --git a/locales/it/viewer.json b/locales/it/viewer.jsonindex c6454c48..ec41b5b9 100644--- a/locales/it/viewer.json+++ b/locales/it/viewer.json@@ -11,6 +11,10 @@"teamMemberTooltip": "Verifica saltata perché sei un membro del team; non verranno raccolti dati analitici","changeLanguage": "Cambia lingua"},+ "fullscreenControls": {+ "rotate": "Ruota",+ "exitFullscreen": "Esci dallo schermo intero"+ },"toasts": {"preparingDownload": "Preparazione del download...","preparingDownloadWatermark": "Preparazione del download con filigrana...",diff --git a/locales/ja/viewer.json b/locales/ja/viewer.jsonindex 975ee8db..5ae1eb44 100644--- a/locales/ja/viewer.json+++ b/locales/ja/viewer.json@@ -11,6 +11,10 @@"teamMemberTooltip": "あなたはチームメンバーのため認証をスキップしました。分析データは収集されません","changeLanguage": "言語を変更"},+ "fullscreenControls": {+ "rotate": "回転",+ "exitFullscreen": "全画面表示を終了"+ },"toasts": {"preparingDownload": "ダウンロードを準備中...","preparingDownloadWatermark": "ウォーターマーク付きダウンロードを準備中...",diff --git a/locales/pt-BR/viewer.json b/locales/pt-BR/viewer.jsonindex 7e031340..375e9d05 100644--- a/locales/pt-BR/viewer.json+++ b/locales/pt-BR/viewer.json@@ -11,6 +11,10 @@"teamMemberTooltip": "Verificação ignorada porque você é membro da equipe; nenhuma análise será coletada","changeLanguage": "Alterar idioma"},+ "fullscreenControls": {+ "rotate": "Girar",+ "exitFullscreen": "Sair da tela cheia"+ },"toasts": {"preparingDownload": "Preparando download...","preparingDownloadWatermark": "Preparando download com marca d'água...",diff --git a/pages/_app.tsx b/pages/_app.tsxindex 8061e952..fcee6e33 100644--- a/pages/_app.tsx+++ b/pages/_app.tsx@@ -35,7 +35,7 @@ export default function App({<><Head><title>Papermark | The Open Source DocSend Alternative</title>- <meta name="theme-color" content="#000000" />+ <meta name="theme-color" content="#000000" key="theme-color" /><metaname="description"content="Papermark is an open-source document sharing alternative to DocSend with built-in analytics."