javascript [code] Look through this page. What does it do?
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
javascript``` import React, { useState, useEffect, useRef } from 'react'; import { Document, Page } from 'react-pdf'; import ViewerChat from './ViewerChat'; import { getPdfUrl, addPdfSelectionToChat } from '../api'; import { pdfjs } from 'react-pdf'; import { useLocation, useNavigate } from 'react-router-dom'; import "react-pdf/dist/esm/Page/AnnotationLayer.css"; import "react-pdf/dist/esm/Page/TextLayer.css"; import { FaArrowLeft, FaDownload, FaRegSquare, FaComments } from 'react-icons/fa';
// Determine device type as early as possible (used in initial state) const isMobile = /Mobi|Android/i.test(navigator.userAgent);
pdfjs.GlobalWorkerOptions.workerSrc = //unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs;
export default function Viewer({ viewMode, setViewMode }) { const location = useLocation(); const navigate = useNavigate(); const [paperObj, setPaperObj] = useState(null); const [numPages, setNumPages] = useState(null); const [sidebarOpen, setSidebarOpen] = useState(() => !isMobile); const [chatExpanded, setChatExpanded] = useState(false); const [ocrTextQP, setOcrTextQP] = useState(''); const [ocrTextMS, setOcrTextMS] = useState(''); const [ocrTextIN, setOcrTextIN] = useState(''); const pdfViewerRef = useRef(null); const [pageWidth, setPageWidth] = useState(0); const [zoom, setZoom] = useState(() => { // Initialize zoom from localStorage or default to 0.9 const savedZoom = localStorage.getItem('viewer-zoom'); return savedZoom ? parseFloat(savedZoom) : 0.9; }); const initialDistanceRef = useRef(null); const initialZoomRef = useRef(zoom);
// Select tool states
const [selectToolActive, setSelectToolActive] = useState(false);
const [isSelecting, setIsSelecting] = useState(false);
const [selectionStart, setSelectionStart] = useState({ x: 0, y: 0 });
const [selectionEnd, setSelectionEnd] = useState({ x: 0, y: 0 });
const [showSelection, setShowSelection] = useState(false);
const selectionRef = useRef(null);
useEffect(() => {
const params = new URLSearchParams(location.search);
let paperFromSource = null;
let viewModeFromSource = null;
// Handle full paper object (preferred method)
if (location.state && location.state.paper) {
paperFromSource = location.state.paper;
viewModeFromSource = location.state.viewMode || 'qp';
console.log('Paper object from state:', paperFromSource); // Debug log
setPaperObj(paperFromSource);
setViewMode(viewModeFromSource);
// Don't auto-convert URL for now to avoid issues
}
// Handle legacy URL format with full paper object (for backward compatibility)
else if (params.get('paper')) {
try {
paperFromSource = JSON.parse(decodeURIComponent(params.get('paper')));
viewModeFromSource = params.get('viewMode') || 'qp';
console.log('Paper object from URL:', paperFromSource); // Debug log
setPaperObj(paperFromSource);
setViewMode(viewModeFromSource);
} catch (error) {
console.error('Error parsing paper from URL:', error);
navigate('/');
return;
}
}
// Handle legacy filename-only format (backward compatibility)
else if (location.state && location.state.filename) {
const filename = location.state.filename;
viewModeFromSource = location.state.viewMode || 'qp';
// Create a basic paper object
paperFromSource = {
qp: filename,
ms: filename.replace('_qp_', '_ms_').replace('_er_', '_ms_'),
in: filename.replace('_qp_', '_in_').replace('_er_', '_in_'),
code: filename.split('/').pop().replace('.pdf', ''),
name: filename.split('/').pop().replace('.pdf', '')
};
setPaperObj(paperFromSource);
setViewMode(viewModeFromSource);
}
// Handle legacy URL filename format
else if (params.get('filename')) {
const filename = params.get('filename');
viewModeFromSource = params.get('viewMode') || 'qp';
// Create a basic paper object
paperFromSource = {
qp: filename,
ms: filename.replace('_qp_', '_ms_').replace('_er_', '_ms_'),
in: filename.replace('_qp_', '_in_').replace('_er_', '_in_'),
code: filename.split('/').pop().replace('.pdf', ''),
name: filename.split('/').pop().replace('.pdf', '')
};
setPaperObj(paperFromSource);
setViewMode(viewModeFromSource);
}
if (!paperFromSource) {
navigate('/');
}
}, [location.state, location.search, navigate]);
// New function to extract OCR from a PDF and upload them to the backend, returning the OCR text.
async function extractOCRFromUrl(url) {
try {
const loadingTask = pdfjs.getDocument(url);
const pdf = await loadingTask.promise;
let ocrText = "";
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const textContent = await page.getTextContent();
const pageText = textContent.items.map(item => item.str).join(' ');
ocrText += `Page ${i}: ${pageText}\n`;
}
return ocrText;
} catch (error) {
console.error('Error extracting OCR from', url, error);
return 'OCR not available';
}
}
// useEffect to extract OCR text for all relevant documents
useEffect(() => {
if (paperObj) {
if (paperObj.qp) {
extractOCRFromUrl(getPdfUrl(paperObj.qp)).then(data => setOcrTextQP(data));
} else {
setOcrTextQP('Not available');
}
if (paperObj.ms) {
extractOCRFromUrl(getPdfUrl(paperObj.ms)).then(data => setOcrTextMS(data));
} else {
setOcrTextMS('Not available');
}
if (paperObj.in) {
extractOCRFromUrl(getPdfUrl(paperObj.in)).then(data => setOcrTextIN(data));
} else {
setOcrTextIN('Not available');
}
}
}, [paperObj]);
useEffect(() => {
if (pdfViewerRef.current) {
pdfViewerRef.current.scrollTop = 0;
}
}, [paperObj, viewMode]);
// Updated onDocumentLoadSuccess to recalc pageWidth immediately
function onDocumentLoadSuccess(pdf) {
setNumPages(pdf.numPages);
if (pdfViewerRef.current) {
setPageWidth(pdfViewerRef.current.clientWidth);
}
}
// Select tool functions
const handleSelectToolToggle = () => {
setSelectToolActive(!selectToolActive);
setShowSelection(false);
setIsSelecting(false);
};
const handleMouseDown = (e) => {
if (!selectToolActive) return;
const rect = pdfViewerRef.current.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
setSelectionStart({ x, y });
setSelectionEnd({ x, y });
setIsSelecting(true);
setShowSelection(true);
};
const handleMouseMove = (e) => {
if (!selectToolActive || !isSelecting) return;
const rect = pdfViewerRef.current.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
setSelectionEnd({ x, y });
};
const handleMouseUp = () => {
if (!selectToolActive || !isSelecting) return;
setIsSelecting(false);
};
const captureSelection = async () => {
if (!showSelection) return;
try {
// Get the selection rectangle dimensions
const rect = {
x: Math.min(selectionStart.x, selectionEnd.x),
y: Math.min(selectionStart.y, selectionEnd.y),
width: Math.abs(selectionEnd.x - selectionStart.x),
height: Math.abs(selectionEnd.y - selectionStart.y)
};
// Temporarily hide the selection overlay to exclude it from capture
const overlay = selectionRef.current;
const originalDisplay = overlay ? overlay.style.display : null;
if (overlay) {
overlay.style.display = 'none';
}
// Use html2canvas to capture the PDF viewer area
const html2canvas = await import('html2canvas');
const screenshot = await html2canvas.default(pdfViewerRef.current, {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
scale: 1,
useCORS: true,
allowTaint: true,
ignoreElements: (element) => {
// Ignore the selection overlay element
return element === overlay;
}
});
// Restore the overlay visibility
if (overlay && originalDisplay !== null) {
overlay.style.display = originalDisplay;
}
// Convert to blob and get data URL for chat
screenshot.toBlob(async (blob) => {
try {
// Convert blob to data URL
const reader = new FileReader();
reader.onload = async (e) => {
try {
// Add to chat context
await addPdfSelectionToChat(e.target.result);
alert('Selection added to chat context!');
// Clear the selection
clearSelection();
} catch (error) {
console.error('Failed to add selection to chat:', error);
// Fallback: copy to clipboard
try {
await navigator.clipboard.write([
new ClipboardItem({ 'image/png': blob })
]);
alert('Selection copied to clipboard!');
} catch (clipboardErr) {
console.error('Failed to copy to clipboard:', clipboardErr);
alert('Failed to capture selection');
}
}
};
reader.readAsDataURL(blob);
} catch (err) {
console.error('Failed to process selection:', err);
alert('Failed to capture selection');
}
});
} catch (error) {
console.error('Error capturing selection:', error);
alert('Failed to capture selection');
}
};
const clearSelection = () => {
setShowSelection(false);
setIsSelecting(false);
};
// Handle adding PDF selection to chat
const handleAddSelectionToChat = () => {
if (showSelection) {
captureSelection();
} else {
alert('Please make a selection first using the Select tool');
}
};
const getFilePath = (mode) => {
if (!paperObj || !paperObj[mode]) {
console.error(`Paper or paper file for mode ${mode} is undefined`);
return '';
}
return paperObj[mode];
};
useEffect(() => {
function handleResize() {
if (pdfViewerRef.current) {
setPageWidth(pdfViewerRef.current.clientWidth);
}
}
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
const handleZoomIn = () => setZoom(prev => Math.min(prev + 0.1, 3));
const handleZoomOut = () => setZoom(prev => Math.max(prev - 0.1, 0.5));
const handleResetZoom = () => setZoom(0.9);
const handleDownload = () => {
const fileUrl = getPdfUrl(getFilePath(viewMode));
const link = document.createElement('a');
link.href = fileUrl;
// Use paperObj.code if available, else default name
link.download = (paperObj && paperObj.code ? paperObj.code : 'document') + '_' + viewMode + '.pdf';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const handleBack = () => {
if (window.history.length > 1) {
navigate(-1);
} else if(window.opener) {
window.close();
} else {
navigate('/');
}
};
useEffect(() => {
const viewer = pdfViewerRef.current;
if (!viewer) return;
const getDistance = (touch1, touch2) => {
const dx = touch2.pageX - touch1.pageX;
const dy = touch2.pageY - touch1.pageY;
return Math.sqrt(dx * dx + dy * dy);
};
const handleTouchStart = (e) => {
if (e.touches.length === 2) {
initialDistanceRef.current = getDistance(e.touches[0], e.touches[1]);
initialZoomRef.current = zoom; // capture current zoom
}
};
const handleTouchMove = (e) => {
if (e.touches.length === 2 && initialDistanceRef.current) {
const currentDistance = getDistance(e.touches[0], e.touches[1]);
const scaleFactor = currentDistance / initialDistanceRef.current;
setZoom(Math.min(Math.max(initialZoomRef.current * scaleFactor, 0.5), 3));
}
};
const handleTouchEnd = (e) => {
if (e.touches.length < 2) {
initialDistanceRef.current = null;
}
};
viewer.addEventListener('touchstart', handleTouchStart);
viewer.addEventListener('touchmove', handleTouchMove);
viewer.addEventListener('touchend', handleTouchEnd);
viewer.addEventListener('touchcancel', handleTouchEnd);
return () => {
viewer.removeEventListener('touchstart', handleTouchStart);
viewer.removeEventListener('touchmove', handleTouchMove);
viewer.removeEventListener('touchend', handleTouchEnd);
viewer.removeEventListener('touchcancel', handleTouchEnd);
};
}, [zoom]);
// Save zoom level to localStorage whenever it changes
useEffect(() => {
localStorage.setItem('viewer-zoom', zoom.toString());
}, [zoom]);
return !paperObj ? null : (
<div className="viewer-wrapper" style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
<div className="viewer-navbar">
<select value={viewMode} onChange={(e) => {
const newMode = e.target.value;
// Check if the requested document type exists
if (!paperObj[newMode]) {
alert(`${newMode.toUpperCase()} document not available for this paper`);
return;
}
// Open new window with same paper object but different view mode
const params = new URLSearchParams();
params.set('paper', encodeURIComponent(JSON.stringify(paperObj)));
params.set('viewMode', newMode);
const newUrl = `${window.location.pathname}?${params.toString()}`;
window.open(newUrl, '_blank');
}}>
<option value="qp">Question Paper</option>
<option value="ms" disabled={!paperObj.ms}>Marking Scheme</option>
{paperObj.in && <option value="in">Reading Insert</option>}
</select>
<button onClick={handleBack} title="Back">
{isMobile ? <FaArrowLeft /> : 'Back'}
</button>
{!isMobile && (
<>
<button onClick={handleZoomOut}>-</button>
<button onClick={handleZoomIn}>+</button>
<button onClick={handleResetZoom}>Reset</button>
</>
)}
<button onClick={handleDownload} title="Download">
{isMobile ? <FaDownload /> : 'Download'}
</button>
<button
onClick={handleSelectToolToggle}
title="Select area"
style={{
backgroundColor: selectToolActive ? '#007bff' : 'transparent',
color: selectToolActive ? 'white' : 'inherit'
}}
>
{isMobile ? <FaRegSquare /> : 'Select'}
</button>
{showSelection && (
<>
<button onClick={captureSelection}>Add to Chat</button>
<button onClick={clearSelection}>Clear</button>
</>
)}
<button
onClick={() => setSidebarOpen(!sidebarOpen)}
title="Chat"
style={{
backgroundColor: sidebarOpen ? '#007bff' : 'transparent',
color: sidebarOpen ? 'white' : 'inherit'
}}
>
{isMobile ? <FaComments /> : 'Chat'}
</button>
</div>
<div className="viewer-body" style={{ display: 'flex', flex: 1 }}>
<div
className="pdf-viewer"
style={{
flex: 1,
overflowY: 'auto',
position: 'relative',
cursor: selectToolActive ? 'crosshair' : 'default'
}}
ref={pdfViewerRef}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Document
file={getPdfUrl(getFilePath(viewMode))}
onLoadSuccess={onDocumentLoadSuccess}
>
{Array.from(new Array(numPages), (el, index) => (
<Page
key={`page_${index + 1}`}
pageNumber={index + 1}
width={pageWidth * zoom}
renderTextLayer={!selectToolActive}
style={{
display: 'block',
marginBottom: 0,
userSelect: selectToolActive ? 'none' : 'auto',
WebkitUserSelect: selectToolActive ? 'none' : 'auto',
MozUserSelect: selectToolActive ? 'none' : 'auto'
}}
/>
))}
</Document>
</div>
{/* Selection overlay */}
{showSelection && (
<div
ref={selectionRef}
style={{
position: 'absolute',
left: Math.min(selectionStart.x, selectionEnd.x),
top: Math.min(selectionStart.y, selectionEnd.y),
width: Math.abs(selectionEnd.x - selectionStart.x),
height: Math.abs(selectionEnd.y - selectionStart.y),
border: '2px dashed #007bff',
backgroundColor: 'rgba(0, 123, 255, 0.1)',
pointerEvents: 'none',
zIndex: 1000
}}
/>
)}
</div>
{/* Chat Sidebar */}
{sidebarOpen && (
<ViewerChat
paperObj={paperObj}
ocrTexts={{
qp: ocrTextQP,
ms: ocrTextMS,
in: ocrTextIN
}}
onAddSelection={handleAddSelectionToChat}
isExpanded={chatExpanded}
onToggleExpanded={() => setChatExpanded(!chatExpanded)}
/>
)}
</div>
</div>
);
}
Look through this page. What does it do?
This is a React functional component named Viewer that serves as a PDF viewer application with advanced features. It's designed to display academic papers (question papers, marking schemes, and reading inserts) in a user-friendly interface. The component handles PDF rendering, navigation, zooming, selection tools, and integrates a chat functionality.
react-pdf library to render PDF documents.addPdfSelectionToChat API).ViewerChat component).pdfjs.ocrTextQP, ocrTextMS, ocrTextIN) for use in the chat.On mobile, the first 5-6 pages of the PDF in the viewer are cut off. I've scrolled all the way to the top, and I can only see page 7 and below. On Desktop, it works fine.
Identify where the issue is, and fix it please.
Again, it's not about being scrolled to the top, the issue is that once I've scrolled to the very top, the first few pages of the PDF are still cut off, even though I've scrolled to the very top.
The issue you're describing is a classic problem with sticky headers or overlays interfering with the scrollable content's top margin. In your case, it's likely caused by the navbar overlapping the PDF viewer. Here's a step-by-step breakdown:
.viewer-navbar has a fixed height (e.g., 50px, 60px, etc.)..pdf-viewer (or its parent .viewer-body) doesn't account for this navbar height when calculating its scrollable area.pdfViewerRef.current (the <div className="pdf-viewer">) is the scrollable element. When you scroll to the "top," React's scroll logic thinks it's at scrollTop: 0, but the navbar is visually covering the top part of the PDF.Inspect the mobile view in your browser's DevTools:
scrollTop === 0 via console.log(pdfViewerRef.current.scrollTop))..pdf-viewer:
overflow-y: auto is set (correct).height: 100% or flex: 1 (likely; this is the problem)..viewer-navbar position: fixed or absolute? If so, it's out of the document flow, meaning the PDF viewer doesn't "see" its height.You need to offset the PDF viewer's content by the navbar's height. Here's how:
Method 1: Add padding-top to .pdf-viewer (Simple)
.pdf-viewer {
padding-top: 60px; /* Match your navbar's height */
box-sizing: border-box; /* Ensure padding is included in height calc */
}
Method 2: Use calc() for .pdf-viewer height (Precise)
Update the inline style or CSS class:
The navbar height is too short to justify blocking the content of six whole pages... I'm not sure if that's it.
The navbar height being the culprit makes sense for a 1-2 page cutoff, but six pages sounds like a different issue. Let's dig deeper.
Here's what's likely happening:
onDocumentLoadSuccess triggers too early (or pageWidth is miscalculated).pageWidth is wrong because the container (pdfViewerRef.current) hasn't fully expanded/layout yet.width={pageWidth * zoom} on <Page /> is too small, causing the PDF pages to render narrower than they should be.flexDirection: 'column'), this narrower width means more pages fit "off-screen" above the visible area.<Page /> elements' computed width. Is it much smaller than the visible container width?pageWidth in onDocumentLoadSuccess:
function onDocumentLoadSuccess(pdf) { setNumPages(pdf.numPages); if (pdfViewerRef.current) { const width = pdfViewerRef.current.clientWidth; console.log('Initial pageWidth:', width); // Check this value! setPageWidth(width); } }
* Is the logged `pageWidth` **significantly smaller** (e.g., `300px`) than your mobile screen width (e.g., `400px` or more)?
**Fix: Force Correct `pageWidth` After Layout**
---------------------------------------------
We need to **recalculate `pageWidth` **after** the container has fully laid out**. Use `useLayoutEffect` for this:
```jsx
import { useLayoutEffect } from 'react';
// Add this alongside your existing effects
useLayoutEffect(() => {
if (pdfViewerRef.current && numPages) {
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const newWidth = entry.contentRect.width;
if (newWidth !== pageWidth) {
console.log('Updating pageWidth to:', newWidth);
setPageWidth(newWidth);
}
}
});
resizeObserver.observe(pdfViewerRef.current);
return () => resizeObserver.disconnect();
}
}, [numPages, pageWidth]); // Re-run when numPages changes (PDF loaded)
The component manages several states:
paperObj: The current paper object (contains file paths for QP, MS, IN).viewMode: Active document type (QP, MS, or IN).numPages: Total pages in the loaded PDF.sidebarOpen: Chat sidebar visibility.chatExpanded: Chat window expanded/collapsed state.ocrTextQP, ocrTextMS, ocrTextIN: Extracted text from PDFs.zoom: Current zoom level (persisted in localStorage).selectToolActive, isSelecting, selectionStart, selectionEnd: Selection tool states.paperObj from:
location.state (preferred, passed from React Router).?paper=<encoded JSON> or ?filename=<name>)./ if no valid paper object is found.paperObj changes.paperObj or viewMode changes.extractOCRFromUrl(url): Fetches a PDF and extracts text from all pages.captureSelection(): Uses html2canvas to capture the selected PDF area, converts it to a blob, and sends it to the chat API.handleSelectToolToggle(): Toggles the selection tool state.getFilePath(mode): Resolves the file path for the current viewMode (QP, MS, IN).react-pdf for PDF rendering.pdfjs-dist (via react-pdf) for PDF parsing and OCR.html2canvas for capturing selected areas as images.react-icons (FaArrowLeft, FaDownload, etc.) for button icons.useLocation, useNavigate) for routing./viewer with a paperObj in location.state or via URL params.This component is robust, handling legacy URL formats, mobile interactions, and feature-rich PDF manipulation. Its primary goal is to enhance the academic paper review experience with contextual chat support.
If you have any specific questions about parts of the code, feel free to ask!
<div
className="pdf-viewer"
style={{
flex: 1,
overflowY: 'auto',
height: 'calc(100vh - 60px)', /* Subtract navbar height */
position: 'relative',
cursor: selectToolActive ? 'crosshair' : 'default'
}}
ref={pdfViewerRef}
...
>
Method 3: Wrap PDF content with an inner container (Robust)
Modify your JSX structure:
<div
className="pdf-viewer"
style={{
flex: 1,
overflowY: 'auto',
position: 'relative',
}}
ref={pdfViewerRef}
>
<div style={{ paddingTop: '60px' }}> {/* Inner wrapper */}
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Document
file={getPdfUrl(getFilePath(viewMode))}
onLoadSuccess={onDocumentLoadSuccess}
>
{/* Pages rendering remains the same */}
</Document>
</div>
{/* Selection overlay */}
{showSelection && (
<div
ref={selectionRef}
style={{
position: 'absolute',
left: Math.min(selectionStart.x, selectionEnd.x),
top: Math.min(selectionStart.y, selectionEnd.y) + 60, // Offset selection too!
width: Math.abs(selectionEnd.x - selectionStart.x),
height: Math.abs(selectionEnd.y - selectionStart.y),
border: '2px dashed #007bff',
backgroundColor: 'rgba(0, 123, 255, 0.1)',
pointerEvents: 'none',
zIndex: 1000
}}
/>
)}
</div>
</div>
If your navbar's height changes (e.g., collapsible menu), use a ref and useLayoutEffect:
const navbarRef = useRef(null);
useLayoutEffect(() => {
if (navbarRef.current) {
const navbarHeight = navbarRef.current.offsetHeight;
pdfViewerRef.current.style.paddingTop = `${navbarHeight}px`;
}
}, []); // Run once on mount
// Assign the ref
<div className="viewer-navbar" ref={navbarRef}>
{/* Navbar content */}
</div>
For responsive navbar heights, combine useLayoutEffect with window.addEventListener('resize'):
useLayoutEffect(() => {
function updatePadding() {
if (navbarRef.current && pdfViewerRef.current) {
const navbarHeight = navbarRef.current.offsetHeight;
pdfViewerRef.current.style.paddingTop = `${navbarHeight}px`;
}
}
updatePadding();
window.addEventListener('resize', updatePadding);
return () => window.removeEventListener('resize', updatePadding);
}, []);
This ensures your fix adapts to screen rotations or navbar changes.
Pick Method 1 or 2 for a quick fix. If your navbar is dynamic, go with Method 3 + Bonus Tip.
Test thoroughly, and voilà! Your PDF viewer should now render page 1 correctly on mobile. Let me know if issues persist!
numPages to be set (PDF fully loaded).pdfViewerRef.current using ResizeObserver.pageWidth.<Page /> components with the correct width, fixing the "pushed-down" issue.Force a manual reflow after a tiny delay:
useEffect(() => {
if (numPages) {
setTimeout(() => {
if (pdfViewerRef.current) {
setPageWidth(pdfViewerRef.current.clientWidth);
}
}, 500); // Wait for 0.5s post-render
}
}, [numPages]);
useLayoutEffect isn't enough to catch async layout changes (e.g., fonts loading, CSS transitions).pageWidth for MobileIf all else fails, temporarily hardcode a sensible mobile width:
const [pageWidth, setPageWidth] = useState(() => {
const isMobile = /Mobi|Android/i.test(navigator.userAgent);
return isMobile ? window.innerWidth : 0; // Start with screen width on mobile
});
Then, refine it later with the ResizeObserver approach.
ResizeObserver fix.<Page /> widths matching the container?This should fix the six-pages-cut-off issue. Let me know if it works or if we need to debug further!