Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 | 'use client' import { css } from '@styled/css' import { useSuspenseQuery } from '@tanstack/react-query' import { Component, type ReactNode, Suspense, useEffect, useRef, useState } from 'react' import type { WorksheetFormState } from '@/app/create/worksheets/types' import { useTheme } from '@/contexts/ThemeContext' import { FloatingPageIndicator } from './FloatingPageIndicator' import { PagePlaceholder } from './PagePlaceholder' import { DuplicateWarningBanner } from './worksheet-preview/DuplicateWarningBanner' import { WorksheetPreviewProvider } from './worksheet-preview/WorksheetPreviewContext' interface WorksheetPreviewProps { formState: WorksheetFormState initialData?: string[] isScrolling?: boolean onPageDataReady?: (data: { currentPage: number totalPages: number jumpToPage: (pageIndex: number) => void }) => void } function getDefaultDate(): string { const now = new Date() return now.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', }) } interface FetchPreviewResponse { pages: string[] totalPages: number startPage?: number endPage?: number warnings?: string[] nextCursor?: number | null } async function fetchWorksheetPreview( formState: WorksheetFormState, startPage?: number, endPage?: number ): Promise<FetchPreviewResponse> { // Set current date for preview const configWithDate = { ...formState, date: getDefaultDate(), } console.log('[fetchWorksheetPreview] Fetching with config:', { mode: configWithDate.mode, operator: configWithDate.operator, displayRules: configWithDate.displayRules, additionDisplayRules: (configWithDate as any).additionDisplayRules, subtractionDisplayRules: (configWithDate as any).subtractionDisplayRules, startPage, endPage, }) // Use absolute URL for SSR compatibility const baseUrl = typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000' // Add pagination query parameters if provided const params = new URLSearchParams() if (startPage !== undefined) { params.set('startPage', startPage.toString()) } if (endPage !== undefined) { params.set('endPage', endPage.toString()) } const queryString = params.toString() const url = `${baseUrl}/api/create/worksheets/preview${queryString ? `?${queryString}` : ''}` console.log('[fetchWorksheetPreview] Sending POST to:', url) const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(configWithDate), }) if (!response.ok) { const errorData = await response.json().catch(() => ({})) const errorMsg = errorData.error || errorData.message || 'Failed to fetch preview' const details = errorData.details ? `\n\n${errorData.details}` : '' const errors = errorData.errors ? `\n\nErrors:\n${errorData.errors.join('\n')}` : '' throw new Error(errorMsg + details + errors) } const data = await response.json() return data } function PreviewContent({ formState, initialData, isScrolling = false, onPageDataReady, }: WorksheetPreviewProps) { const { resolvedTheme } = useTheme() const isDark = resolvedTheme === 'dark' const pageRefs = useRef<(HTMLDivElement | null)[]>([]) // Track if we've used the initial data (so we only use it once) const initialDataUsed = useRef(false) // Only use initialData on the very first query, not on subsequent fetches // Convert initial pages to response format const queryInitialData = !initialDataUsed.current && initialData ? { pages: initialData, totalPages: formState.pages || initialData.length, startPage: 0, endPage: initialData.length - 1, } : undefined if (queryInitialData) { initialDataUsed.current = true } // For initial query and refetches, only load first 3 pages const INITIAL_PAGE_COUNT = 3 // Use Suspense Query - will suspend during loading const { data: response } = useSuspenseQuery({ queryKey: [ 'worksheet-preview', // PRIMARY state formState.problemsPerPage, formState.cols, formState.pages, formState.orientation, // V4: Problem size (CRITICAL - affects column layout and problem generation) formState.digitRange?.min, formState.digitRange?.max, // V4: Operator selection (addition, subtraction, or mixed) formState.operator, // V4: Mode and conditional display settings formState.mode, formState.displayRules, // Custom mode: conditional scaffolding formState.difficultyProfile, // Custom mode: difficulty preset formState.manualPreset, // Manual mode: manual preset // Mastery mode: skill IDs (CRITICAL for mastery+mixed mode) formState.currentAdditionSkillId, formState.currentSubtractionSkillId, formState.currentStepId, // Other settings that affect appearance formState.name, formState.pAnyStart, formState.pAllStart, formState.interpolate, formState.seed, // Include seed to bust cache when problem set regenerates formState.includeQRCode, // Include QR code setting to regenerate preview when toggled formState.includeAnswerKey, // Include answer key setting to regenerate preview when toggled // Note: fontSize, date, rows, total intentionally excluded // (rows and total are derived from primary state) ], queryFn: () => { // Only fetch first INITIAL_PAGE_COUNT pages initially // The virtualization system will fetch remaining pages on-demand const totalPages = formState.pages || 1 const endPage = Math.min(INITIAL_PAGE_COUNT - 1, totalPages - 1) return fetchWorksheetPreview(formState, 0, endPage) }, initialData: queryInitialData, // Only use on first render }) const totalPages = response.totalPages const [loadedPages, setLoadedPages] = useState<Map<number, string>>(() => { // Initialize with pages from response const map = new Map<number, string>() response.pages.forEach((page, offsetIndex) => { const pageIndex = (response.startPage ?? 0) + offsetIndex map.set(pageIndex, page) }) return map }) // Virtualization decision based on page count, not config source // Always virtualize multi-page worksheets for performance const shouldVirtualize = totalPages > 1 // Initialize visible pages - start with first page only const [visiblePages, setVisiblePages] = useState<Set<number>>(() => new Set([0])) // Track which pages are currently being fetched const [fetchingPages, setFetchingPages] = useState<Set<number>>(new Set()) const [currentPage, setCurrentPage] = useState(0) // Track when refs are fully populated const [refsReady, setRefsReady] = useState(false) // Reset to first page when preview updates useEffect(() => { setCurrentPage(0) setVisiblePages(new Set([0])) setFetchingPages(new Set()) pageRefs.current = [] setRefsReady(false) // Update loaded pages with new pages from response const map = new Map<number, string>() response.pages.forEach((page, offsetIndex) => { const pageIndex = (response.startPage ?? 0) + offsetIndex map.set(pageIndex, page) }) setLoadedPages(map) }, [response]) // Fetch pages as they become visible useEffect(() => { if (!shouldVirtualize) { return } // Find pages that are visible but not loaded and not being fetched const pagesToFetch = Array.from(visiblePages).filter( (pageIndex) => !loadedPages.has(pageIndex) && !fetchingPages.has(pageIndex) ) if (pagesToFetch.length === 0) return // Group consecutive pages into ranges for batch fetching const ranges: { start: number; end: number }[] = [] let currentRange: { start: number; end: number } | null = null pagesToFetch .sort((a, b) => a - b) .forEach((pageIndex) => { if (currentRange === null) { currentRange = { start: pageIndex, end: pageIndex } } else if (pageIndex === currentRange.end + 1) { currentRange.end = pageIndex } else { ranges.push(currentRange) currentRange = { start: pageIndex, end: pageIndex } } }) if (currentRange !== null) { ranges.push(currentRange) } // Fetch each range ranges.forEach(({ start, end }) => { // Mark pages as being fetched setFetchingPages((prev) => { const next = new Set(prev) for (let i = start; i <= end; i++) { next.add(i) } return next }) console.log(`[Virtualization] Fetching pages ${start}-${end}...`) // Fetch the range with pagination parameters fetchWorksheetPreview(formState, start, end) .then((response) => { console.log( `[Virtualization] Received ${response.pages.length} pages for range ${start}-${end}` ) // Add fetched pages to loaded pages setLoadedPages((prev) => { const next = new Map(prev) // Pages are returned starting from 'start', so map them correctly response.pages.forEach((page, offsetIndex) => { next.set(start + offsetIndex, page) }) return next }) // Remove from fetching set setFetchingPages((prev) => { const next = new Set(prev) for (let i = start; i <= end; i++) { next.delete(i) } return next }) }) .catch((error) => { console.error(`[Virtualization] Failed to fetch pages ${start}-${end}:`, error) // Remove from fetching set on error setFetchingPages((prev) => { const next = new Set(prev) for (let i = start; i <= end; i++) { next.delete(i) } return next }) }) }) }, [visiblePages, loadedPages, fetchingPages, shouldVirtualize, formState]) // Check if all refs are populated after each render useEffect(() => { if (totalPages > 1 && pageRefs.current.length === totalPages) { const allPopulated = pageRefs.current.every((ref) => ref !== null) if (allPopulated && !refsReady) { setRefsReady(true) } } }) // Intersection Observer to track current page (works with or without virtualization) useEffect(() => { if (totalPages <= 1) { return // No need for page tracking with single page } // Wait for refs to be populated if (!refsReady) { return } const observer = new IntersectionObserver( (entries) => { // Find the most visible page among all entries let mostVisiblePage = 0 let maxRatio = 0 entries.forEach((entry) => { const pageIndex = Number(entry.target.getAttribute('data-page-index')) if (entry.intersectionRatio > maxRatio) { maxRatio = entry.intersectionRatio mostVisiblePage = pageIndex } }) // Update current page with hysteresis to prevent flickering // Only update if: // 1. New page has > 0 visibility // 2. New page is different from current // 3. New page is significantly more visible (>0.6 ratio) OR current page has very low visibility (<0.3) if (maxRatio > 0) { setCurrentPage((prev) => { const isDifferentPage = mostVisiblePage !== prev const isSignificantlyVisible = maxRatio > 0.6 const currentPageLowVisibility = maxRatio > 0.3 // If maxRatio is high, current page must be less visible if (isDifferentPage && (isSignificantlyVisible || !currentPageLowVisibility)) { return mostVisiblePage } return prev }) } // Update visible pages set (only when virtualizing) if (shouldVirtualize) { setVisiblePages((prev) => { const next = new Set<number>() // Only keep pages that are currently intersecting entries.forEach((entry) => { const pageIndex = Number(entry.target.getAttribute('data-page-index')) if (entry.isIntersecting) { // Add visible page next.add(pageIndex) // Preload adjacent pages for smooth scrolling if (pageIndex > 0) next.add(pageIndex - 1) if (pageIndex < totalPages - 1) next.add(pageIndex + 1) } }) // Keep any pages from prev that weren't in entries (not observed in this callback) prev.forEach((pageIndex) => { const wasObserved = entries.some( (entry) => Number(entry.target.getAttribute('data-page-index')) === pageIndex ) if (!wasObserved) { next.add(pageIndex) } }) return next }) } }, { root: null, // Use viewport as root (scrolling happens in parent) rootMargin: '50% 0px', // Start loading when page is 50% away from viewport threshold: [0, 0.5, 1], } ) // Observe all page containers pageRefs.current.forEach((ref) => { if (ref) { observer.observe(ref) } }) return () => { observer.disconnect() } }, [totalPages, refsReady, shouldVirtualize]) // Jump to page function for floating indicator const jumpToPage = (pageIndex: number) => { pageRefs.current[pageIndex]?.scrollIntoView({ behavior: 'smooth', block: 'start', }) } // Notify parent of page data for floating elements useEffect(() => { if (onPageDataReady) { onPageDataReady({ currentPage, totalPages, jumpToPage }) } }, [currentPage, totalPages, onPageDataReady]) return ( <div data-component="worksheet-preview" className={css({ bg: isDark ? 'gray.700' : 'white', rounded: 'lg', border: '1px solid', borderColor: isDark ? 'gray.600' : 'gray.200', minH: 'full', })} > {/* Floating elements moved to PreviewCenter */} {/* Page containers */} <div className={css({ display: 'flex', flexDirection: 'column', gap: '6', p: '4', })} > {Array.from({ length: totalPages }, (_, index) => { const isLoaded = loadedPages.has(index) const isFetching = fetchingPages.has(index) const isVisible = visiblePages.has(index) const page = loadedPages.get(index) // Calculate dimensions for consistent sizing between placeholder and loaded content const orientation = formState.orientation ?? 'portrait' const maxWidth = orientation === 'portrait' ? 816 : 1056 const aspectRatio = orientation === 'portrait' ? '8.5 / 11' : '11 / 8.5' return ( <div key={index} ref={(el) => { pageRefs.current[index] = el }} data-page-index={index} data-element="page-container" data-page-loaded={isLoaded ? 'true' : 'false'} data-page-fetching={isFetching ? 'true' : 'false'} className={css({ display: 'flex', justifyContent: 'center', alignItems: 'flex-start', })} > {isLoaded && page ? ( <div style={{ width: '100%', maxWidth: `${maxWidth}px`, aspectRatio: aspectRatio, }} className={css({ '& svg': { width: '100%', height: 'auto', }, })} dangerouslySetInnerHTML={{ __html: page }} /> ) : ( <PagePlaceholder pageNumber={index + 1} orientation={formState.orientation} rows={Math.ceil((formState.problemsPerPage ?? 20) / (formState.cols ?? 5))} cols={formState.cols} loading={isFetching} /> )} </div> ) })} </div> </div> ) } function PreviewFallback({ formState }: { formState?: WorksheetFormState }) { return ( <div data-component="worksheet-preview-loading" className={css({ bg: 'white', rounded: '2xl', p: '6', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '600px', })} > <PagePlaceholder pageNumber={1} orientation={formState?.orientation ?? 'portrait'} rows={Math.ceil((formState?.problemsPerPage ?? 20) / (formState?.cols ?? 5))} cols={formState?.cols ?? 5} loading={true} /> </div> ) } function PreviewErrorFallback({ error, onRetry }: { error: Error; onRetry: () => void }) { const { resolvedTheme } = useTheme() const isDark = resolvedTheme === 'dark' // Log full error details to console useEffect(() => { console.error('[WorksheetPreview] Preview generation failed:', { message: error.message, stack: error.stack, error, }) }, [error]) return ( <div data-component="worksheet-preview-error" className={css({ bg: isDark ? 'gray.800' : 'white', rounded: 'xl', p: '6', border: '2px solid', borderColor: 'red.300', display: 'flex', flexDirection: 'column', gap: '4', minHeight: '400px', })} > <div className={css({ display: 'flex', alignItems: 'flex-start', gap: '3', })} > <div className={css({ fontSize: '3xl', flexShrink: 0, })} > ⚠️ </div> <div className={css({ flex: 1 })}> <h3 className={css({ fontSize: 'lg', fontWeight: 'bold', color: isDark ? 'red.300' : 'red.600', mb: '2', })} > Preview Generation Failed </h3> <p className={css({ fontSize: 'sm', color: isDark ? 'gray.300' : 'gray.600', mb: '3', lineHeight: '1.6', })} > The worksheet preview could not be generated. This usually happens due to invalid settings or a temporary server issue. Your settings are still saved. </p> {/* Actionable suggestions */} <div className={css({ bg: isDark ? 'gray.900' : 'gray.50', p: '4', rounded: 'lg', fontSize: 'sm', mb: '3', })} > <h4 className={css({ fontWeight: 'semibold', color: isDark ? 'gray.200' : 'gray.800', mb: '2', })} > Try these steps: </h4> <ul className={css({ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: '2', color: isDark ? 'gray.300' : 'gray.700', })} > <li className={css({ display: 'flex', gap: '2' })}> <span>1.</span> <span>Click the "Retry Preview" button below to try generating again</span> </li> <li className={css({ display: 'flex', gap: '2' })}> <span>2.</span> <span> Try adjusting your worksheet settings (e.g., reduce problems per page or number of pages) </span> </li> <li className={css({ display: 'flex', gap: '2' })}> <span>3.</span> <span> Check if you have extreme values in difficulty settings that might be causing issues </span> </li> <li className={css({ display: 'flex', gap: '2' })}> <span>4.</span> <span> If the preview continues to fail, you can still try generating the full worksheet PDF </span> </li> </ul> </div> {/* Retry button */} <button onClick={onRetry} className={css({ px: '4', py: '2', bg: isDark ? 'blue.600' : 'blue.500', color: 'white', rounded: 'lg', fontWeight: 'medium', fontSize: 'sm', cursor: 'pointer', transition: 'all 0.2s', _hover: { bg: isDark ? 'blue.700' : 'blue.600', transform: 'translateY(-1px)', boxShadow: 'md', }, _active: { transform: 'translateY(0)', }, })} > 🔄 Retry Preview </button> </div> </div> {/* Technical details (collapsible) */} <details className={css({ bg: isDark ? 'gray.900' : 'gray.50', p: '3', rounded: 'md', fontSize: 'sm', borderTop: '1px solid', borderColor: isDark ? 'gray.700' : 'gray.200', })} > <summary className={css({ cursor: 'pointer', fontWeight: 'medium', color: isDark ? 'gray.400' : 'gray.600', _hover: { color: isDark ? 'gray.300' : 'gray.900', }, })} > Technical Details (for debugging) </summary> <div className={css({ mt: '3' })}> <div className={css({ mb: '2', fontSize: 'xs', color: isDark ? 'gray.400' : 'gray.600', })} > Error message: </div> <pre className={css({ p: '2', bg: isDark ? 'gray.950' : 'white', rounded: 'sm', fontSize: 'xs', overflow: 'auto', color: isDark ? 'red.300' : 'red.600', mb: '3', border: '1px solid', borderColor: isDark ? 'gray.800' : 'gray.200', })} > {error.message} </pre> {error.stack && ( <> <div className={css({ mb: '2', fontSize: 'xs', color: isDark ? 'gray.400' : 'gray.600', })} > Stack trace (also logged to browser console): </div> <pre className={css({ p: '2', bg: isDark ? 'gray.950' : 'white', rounded: 'sm', fontSize: 'xs', overflow: 'auto', maxHeight: '200px', color: isDark ? 'gray.400' : 'gray.600', border: '1px solid', borderColor: isDark ? 'gray.800' : 'gray.200', })} > {error.stack} </pre> </> )} </div> </details> </div> ) } class PreviewErrorBoundary extends Component< { children: ReactNode }, { hasError: boolean; error: Error | null } > { constructor(props: { children: ReactNode }) { super(props) this.state = { hasError: false, error: null } } static getDerivedStateFromError(error: Error) { return { hasError: true, error } } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { console.error('[WorksheetPreview] Error caught by boundary:', error, errorInfo) } handleRetry = () => { console.log('[WorksheetPreview] Retry requested - resetting error boundary') this.setState({ hasError: false, error: null }) } render() { if (this.state.hasError && this.state.error) { return <PreviewErrorFallback error={this.state.error} onRetry={this.handleRetry} /> } return this.props.children } } export function WorksheetPreview({ formState, initialData, isScrolling, onPageDataReady, }: WorksheetPreviewProps) { return ( <WorksheetPreviewProvider formState={formState}> <PreviewErrorBoundary> <Suspense fallback={<PreviewFallback formState={formState} />}> <PreviewContent formState={formState} initialData={initialData} isScrolling={isScrolling} onPageDataReady={onPageDataReady} /> </Suspense> </PreviewErrorBoundary> </WorksheetPreviewProvider> ) } |