Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
refactor(pdf-export): move preview pane, settings rows, preview/settings hooks and dialog shell into the shared layer
Khuram Niazdb78f34dde80
diff --git a/src/components/pdf-export/PdfExportDialog.tsx b/src/components/pdf-export/PdfExportDialog.tsxnew file mode 100644index 0000000..76fbe37--- /dev/null+++ b/src/components/pdf-export/PdfExportDialog.tsx@@ -0,0 +1,110 @@+"use client";++import type { ReactNode } from "react";+import { FileDown } from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { PdfPreviewPane } from "./PdfPreviewPane";+import type { PreviewResult } from "./usePdfPreview";++type PdfExportDialogProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ title: string;+ description: string;+ previewLabel: string;+ emptyMessage: string;+ blob: Blob | null;+ filename: string | null;+ isGenerating: boolean;+ /** An input the generator needs has not arrived yet. */+ isPending?: boolean;+ hasError: boolean;+ canExport: boolean;+ settingsPanel: ReactNode;+ onExport: (prepared: PreviewResult | null) => void;+};++export function PdfExportDialog({+ open,+ onOpenChange,+ title,+ description,+ previewLabel,+ emptyMessage,+ blob,+ filename,+ isGenerating,+ isPending,+ hasError,+ canExport,+ settingsPanel,+ onExport,+}: PdfExportDialogProps) {+ // Exporting mid-generation would download the settings just switched away+ // from, since Export reuses the previewed blob. Exporting while pending+ // would take the null-prepared path and generate from inputs that have not+ // arrived — a letter with no letterhead, and no sign anything was wrong.+ const exportDisabled = !canExport || isGenerating || !!isPending;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ {/* A fixed height, not a max: the pane fits pages to its own height, so+ a content-driven one would feed back on itself. */}+ <DialogContent className="flex h-[90vh] flex-col sm:max-w-5xl">+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>++ <div className="flex min-h-0 flex-1 flex-col gap-4 md:flex-row">+ <div className="order-2 h-[45vh] min-h-0 md:order-1 md:h-auto md:min-w-0 md:flex-1">+ <PdfPreviewPane+ blob={blob}+ isGenerating={isGenerating || !!isPending}+ hasError={hasError}+ canExport={canExport}+ previewLabel={previewLabel}+ emptyMessage={emptyMessage}+ className="h-full"+ />+ </div>+ <div className="order-1 min-h-0 shrink-0 overflow-y-auto md:order-2 md:w-[34%]">+ {settingsPanel}+ </div>+ </div>++ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ disabled={exportDisabled}+ onClick={() => {+ // The blob on screen is the artifact; a null one tells the+ // caller to generate, which covers a failed preview.+ const prepared = blob && filename ? { blob, filename } : null;+ onOpenChange(false);+ onExport(prepared);+ }}+ >+ <FileDown className="h-4 w-4" />+ Export+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/profile/export-pdf-dialog/PdfPreviewPane.tsx b/src/components/pdf-export/PdfPreviewPane.tsxsimilarity index 97%rename from src/components/profile/export-pdf-dialog/PdfPreviewPane.tsxrename to src/components/pdf-export/PdfPreviewPane.tsxindex 627ab6d..d0adf71 100644--- a/src/components/profile/export-pdf-dialog/PdfPreviewPane.tsx+++ b/src/components/pdf-export/PdfPreviewPane.tsx@@ -12,8 +12,6 @@ import {const PREVIEW_RESIZE_DEBOUNCE_MS = 250;const MAX_CANVAS_SCALE = 2;-const EMPTY_MESSAGE =- "Add your contact info and at least one section to preview.";type FitMode = "page" | "width";@@ -22,6 +20,10 @@ type PdfPreviewPaneProps = {isGenerating: boolean;hasError: boolean;canExport: boolean;+ /** Names the scroll region, e.g. "Resume preview". */+ previewLabel: string;+ /** Shown when canExport is false. */+ emptyMessage: string;className?: string;};@@ -43,6 +45,8 @@ export function PdfPreviewPane({isGenerating,hasError,canExport,+ previewLabel,+ emptyMessage,className,}: PdfPreviewPaneProps) {const scrollRef = useRef<HTMLDivElement>(null);@@ -217,7 +221,7 @@ export function PdfPreviewPane({const showOverlaySpinner = canExport && !showError && hasPages && isGenerating;const status = showEmpty- ? EMPTY_MESSAGE+ ? emptyMessage: showError? "Preview unavailable": isGenerating@@ -262,7 +266,7 @@ export function PdfPreviewPane({<divref={scrollRef}aria-label={- hasPages ? `Resume preview, ${pageLabel(pageCount)}` : "Resume preview"+ hasPages ? `${previewLabel}, ${pageLabel(pageCount)}` : previewLabel}className="relative min-h-0 flex-1 overflow-y-auto rounded-md border bg-muted p-4">@@ -280,7 +284,7 @@ export function PdfPreviewPane({{(showEmpty || showError || showFirstSpinner) && (<div className="absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-muted-foreground">{showEmpty ? (- EMPTY_MESSAGE+ emptyMessage) : showError ? ("Preview unavailable") : (diff --git a/src/components/pdf-export/settings-rows.tsx b/src/components/pdf-export/settings-rows.tsxnew file mode 100644index 0000000..81c452a--- /dev/null+++ b/src/components/pdf-export/settings-rows.tsx@@ -0,0 +1,179 @@+"use client";++import { useEffect, useState } from "react";+import { ChevronDown, ChevronRight, Minus, Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ clampNumericField,+ PDF_NUMERIC_SETTINGS,+ type NumericSetting,+} from "@/models/pdfExport.model";++// Wraps rather than clips: the control drops below the label on a narrow+// settings column instead of overflowing it.+export const ROW =+ "flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-b px-4 py-2.5 last:border-b-0";++// A label element pointing at role="combobox" is named inconsistently across+// accname implementations, so the trigger carries its own aria-label.+export function SelectRow<T extends string>({+ id,+ label,+ value,+ labels,+ onSelect,+}: {+ id: string;+ label: string;+ value: T;+ labels: Record<T, string>;+ onSelect: (value: T) => void;+}) {+ return (+ <div className={ROW}>+ <Label htmlFor={id} className="cursor-pointer font-normal">+ {label}+ </Label>+ <Select value={value} onValueChange={(next) => onSelect(next as T)}>+ <SelectTrigger id={id} aria-label={label} className="ml-auto h-8 w-40">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(labels) as T[]).map((key) => (+ <SelectItem key={key} value={key}>+ {labels[key]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}++// The draft string is what is typed; only a parsed, in-range value is+// committed upward. Clamping on every keystroke would snap a cleared field+// to its minimum mid-edit.+export function StepperRow({+ idPrefix,+ field,+ value,+ onCommit,+}: {+ idPrefix: string;+ field: NumericSetting;+ value: number;+ onCommit: (value: number) => void;+}) {+ const spec = PDF_NUMERIC_SETTINGS[field];+ const id = `${idPrefix}-${field}`;+ const [draft, setDraft] = useState(() => String(value));++ // Resyncs when the value moves without the input being touched: Reset,+ // or the first read from storage.+ useEffect(() => {+ setDraft(String(value));+ }, [value]);++ const stepBy = (direction: 1 | -1) =>+ onCommit(clampNumericField(field, value + direction * spec.step));++ const onDraftChange = (next: string) => {+ setDraft(next);+ const parsed = Number(next);+ if (next.trim() === "" || !Number.isFinite(parsed)) return;+ if (parsed < spec.min || parsed > spec.max) return;+ onCommit(clampNumericField(field, parsed));+ };++ return (+ <div className={ROW}>+ <Label htmlFor={id} className="cursor-pointer font-normal">+ {spec.label}+ </Label>+ <div className="ml-auto flex items-center gap-1">+ <Button+ type="button"+ variant="outline"+ size="icon"+ className="h-7 w-7 shrink-0"+ aria-label={`Decrease ${spec.label}`}+ disabled={value <= spec.min}+ onClick={() => stepBy(-1)}+ >+ <Minus className="h-3 w-3" aria-hidden />+ </Button>+ <Input+ id={id}+ type="number"+ inputMode="decimal"+ min={spec.min}+ max={spec.max}+ step={spec.step}+ value={draft}+ onChange={(event) => onDraftChange(event.target.value)}+ onBlur={() => setDraft(String(value))}+ className="h-7 w-16 px-2 text-center text-sm"+ />+ {spec.unit && (+ <span className="w-4 text-xs text-muted-foreground">{spec.unit}</span>+ )}+ <Button+ type="button"+ variant="outline"+ size="icon"+ className="h-7 w-7 shrink-0"+ aria-label={`Increase ${spec.label}`}+ disabled={value >= spec.max}+ onClick={() => stepBy(1)}+ >+ <Plus className="h-3 w-3" aria-hidden />+ </Button>+ </div>+ </div>+ );+}++export function DisclosureGroup({+ title,+ summary,+ children,+}: {+ title: string;+ summary: string;+ children: React.ReactNode;+}) {+ const [open, setOpen] = useState(true);++ return (+ <Collapsible open={open} onOpenChange={setOpen}>+ <CollapsibleTrigger className="flex w-full items-center gap-1.5 text-sm font-semibold">+ {open ? (+ <ChevronDown className="h-4 w-4" aria-hidden />+ ) : (+ <ChevronRight className="h-4 w-4" aria-hidden />+ )}+ {title}+ </CollapsibleTrigger>+ {!open && (+ <p className="pl-[1.375rem] text-xs text-muted-foreground">{summary}</p>+ )}+ <CollapsibleContent className="mt-2 rounded-lg border bg-muted/40">+ {children}+ </CollapsibleContent>+ </Collapsible>+ );+}diff --git a/src/components/pdf-export/useExportSettings.ts b/src/components/pdf-export/useExportSettings.tsnew file mode 100644index 0000000..1c906cf--- /dev/null+++ b/src/components/pdf-export/useExportSettings.ts@@ -0,0 +1,59 @@+"use client";+import { useEffect, useState } from "react";+import {+ getFromLocalStorage,+ saveToLocalStorage,+} from "@/utils/localstorage.utils";++type Options<T> = {+ /** Module-level constant at every call site — it is an effect dependency. */+ defaults: T;+ /** Module-level function at every call site, for the same reason. */+ coerce: (stored: unknown) => T;+ storageKey: string;+ open: boolean;+};++// Reads on open rather than at mount: localStorage is unavailable during SSR,+// and `ready` holds the preview back one commit so it generates once, with+// the stored settings, instead of once with the defaults and again after.+export function useExportSettings<T>({+ defaults,+ coerce,+ storageKey,+ open,+}: Options<T>) {+ const [settings, setSettings] = useState<T>(defaults);+ const [ready, setReady] = useState(false);++ useEffect(() => {+ if (!open) {+ setReady(false);+ return;+ }+ let next: T;+ try {+ next = coerce(getFromLocalStorage(storageKey, null));+ } catch {+ // getFromLocalStorage calls JSON.parse unguarded.+ next = defaults;+ }+ setSettings(next);+ setReady(true);+ }, [open, storageKey, defaults, coerce]);++ const update = (next: T) => {+ setSettings(next);+ saveToLocalStorage(storageKey, next);+ };++ return {+ settings,+ setSettings: update,+ ready,+ // Passed through, not spread: spreading an unconstrained generic does+ // not reliably narrow back to T, and nothing here mutates settings in+ // place.+ reset: () => update(defaults),+ };+}diff --git a/src/components/pdf-export/usePdfPreview.ts b/src/components/pdf-export/usePdfPreview.tsnew file mode 100644index 0000000..772d7ff--- /dev/null+++ b/src/components/pdf-export/usePdfPreview.ts@@ -0,0 +1,95 @@+"use client";+import { useEffect, useRef, useState } from "react";+import { settingsKey } from "@/models/pdfExport.model";++const PREVIEW_DEBOUNCE_MS = 250;++export type PreviewResult = { blob: Blob; filename: string };++// Owns the preview artifact: debounce, cache, and blob generation. Deliberately+// touches no canvas and creates no object URL — PdfPreviewPane owns rendering.+// `generate` is held in a ref so an inline arrow at the call site does not+// re-trigger the effect on every render.+export function usePdfPreview<T extends object>(+ generate: (settings: T) => Promise<PreviewResult>,+ settings: T,+ active: boolean,+) {+ const [result, setResult] = useState<PreviewResult | null>(null);+ const [isGenerating, setIsGenerating] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const cacheRef = useRef(new Map<string, PreviewResult>());+ const hasRenderedRef = useRef(false);+ const runIdRef = useRef(0);++ // Read through refs so the effect can depend on primitives only.+ const generateRef = useRef(generate);+ generateRef.current = generate;+ const settingsRef = useRef(settings);+ settingsRef.current = settings;++ // Sorted, so a rebuilt settings object hits the same cache entry as a+ // spread one and key order carries no meaning.+ const key = settingsKey(settings);++ useEffect(() => {+ if (!active) {+ // A document edited between openings must never show a stale preview.+ cacheRef.current.clear();+ hasRenderedRef.current = false;+ runIdRef.current += 1;+ setResult(null);+ setIsGenerating(false);+ setError(null);+ return;+ }++ const cached = cacheRef.current.get(key);+ if (cached) {+ runIdRef.current += 1;+ hasRenderedRef.current = true;+ setResult(cached);+ setIsGenerating(false);+ setError(null);+ return;+ }++ const runId = ++runIdRef.current;+ setIsGenerating(true);+ setError(null);++ const run = async () => {+ try {+ const generated = await generateRef.current(settingsRef.current);+ if (runIdRef.current !== runId) return;+ cacheRef.current.set(key, generated);+ setResult(generated);+ setError(null);+ } catch (e) {+ if (runIdRef.current !== runId) return;+ setResult(null);+ setError(e instanceof Error ? e : new Error("Preview failed"));+ } finally {+ if (runIdRef.current === runId) setIsGenerating(false);+ }+ };++ // Opening the dialog must not wait out a debounce nobody triggered.+ if (!hasRenderedRef.current) {+ hasRenderedRef.current = true;+ void run();+ return;+ }++ const timer = setTimeout(() => void run(), PREVIEW_DEBOUNCE_MS);+ return () => clearTimeout(timer);+ }, [active, key]);++ return {+ blob: result?.blob ?? null,+ filename: result?.filename ?? null,+ isGenerating,+ error,+ };+}diff --git a/src/components/profile/ExportPdfDialog.tsx b/src/components/profile/ExportPdfDialog.tsxindex 6463ab0..9fb3a73 100644--- a/src/components/profile/ExportPdfDialog.tsx+++ b/src/components/profile/ExportPdfDialog.tsx@@ -1,26 +1,20 @@"use client";-import { FileDown } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "../ui/dialog";-import { Button } from "../ui/button";+import { PdfExportDialog } from "@/components/pdf-export/PdfExportDialog";import type { Resume } from "@/models/profile.model";+import { settingsKey } from "@/models/pdfExport.model";import {RESUME_TEMPLATE_DEFAULTS,type ResumeExportSettings,} from "@/models/resumeExport.model";import { ExportSettingsPanel } from "./export-pdf-dialog/ExportSettingsPanel";-import { PdfPreviewPane } from "./export-pdf-dialog/PdfPreviewPane";import { canExportResume } from "./resume-container/useResumePdfExport";import { useResumeExportSettings } from "./resume-container/useResumeExportSettings";import { useResumePdfPreview } from "./resume-container/useResumePdfPreview";+const EMPTY_MESSAGE =+ "Add your contact info and at least one section to preview.";+type ExportPdfDialogProps = {open: boolean;onOpenChange: (open: boolean) => void;@@ -39,8 +33,8 @@ export function ExportPdfDialog({}: ExportPdfDialogProps) {const { settings, setSettings, ready, reset } = useResumeExportSettings(open);const isDefault =- JSON.stringify(settings) ===- JSON.stringify(RESUME_TEMPLATE_DEFAULTS[settings.template]);+ settingsKey(settings) ===+ settingsKey(RESUME_TEMPLATE_DEFAULTS[settings.template]);const canExport = canExportResume(resume);const { blob, filename, isGenerating, error } = useResumePdfPreview(@@ -49,66 +43,28 @@ export function ExportPdfDialog({open && ready,);- // Exporting mid-generation would download the template just switched away- // from, since Export reuses the previewed blob.- const exportDisabled = !canExport || isGenerating;-return (- <Dialog open={open} onOpenChange={onOpenChange}>- {/* A fixed height, not a max: the pane fits pages to its own height, so- a content-driven one would feed back on itself. */}- <DialogContent className="flex h-[90vh] flex-col sm:max-w-5xl">- <DialogHeader>- <DialogTitle>Export to PDF</DialogTitle>- <DialogDescription>- Adjust the settings and preview the file before exporting.- </DialogDescription>- </DialogHeader>-- <div className="flex min-h-0 flex-1 flex-col gap-4 md:flex-row">- <div className="order-2 h-[45vh] min-h-0 md:order-1 md:h-auto md:min-w-0 md:flex-1">- <PdfPreviewPane- blob={blob}- isGenerating={isGenerating}- hasError={!!error}- canExport={canExport}- className="h-full"- />- </div>- <div className="order-1 min-h-0 shrink-0 overflow-y-auto md:order-2 md:w-[34%]">- <ExportSettingsPanel- settings={settings}- onChange={setSettings}- onReset={reset}- isDefault={isDefault}- />- </div>- </div>-- <DialogFooter>- <Button- type="button"- variant="outline"- onClick={() => onOpenChange(false)}- >- Cancel- </Button>- <Button- type="button"- disabled={exportDisabled}- onClick={() => {- // The blob on screen is the artifact; a null one makes the hook- // fall back to generating, which covers a failed preview.- const prepared = blob && filename ? { blob, filename } : null;- onOpenChange(false);- onExport(settings, prepared);- }}- >- <FileDown className="h-4 w-4" />- Export- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ <PdfExportDialog+ open={open}+ onOpenChange={onOpenChange}+ title="Export to PDF"+ description="Adjust the settings and preview the file before exporting."+ previewLabel="Resume preview"+ emptyMessage={EMPTY_MESSAGE}+ blob={blob}+ filename={filename}+ isGenerating={isGenerating}+ hasError={!!error}+ canExport={canExport}+ onExport={(prepared) => onExport(settings, prepared)}+ settingsPanel={+ <ExportSettingsPanel+ settings={settings}+ onChange={setSettings}+ onReset={reset}+ isDefault={isDefault}+ />+ }+ />);}diff --git a/src/components/profile/export-pdf-dialog/ExportSettingsPanel.tsx b/src/components/profile/export-pdf-dialog/ExportSettingsPanel.tsxindex 736cb4e..145b62b 100644--- a/src/components/profile/export-pdf-dialog/ExportSettingsPanel.tsx+++ b/src/components/profile/export-pdf-dialog/ExportSettingsPanel.tsx@@ -1,27 +1,14 @@"use client";-import { useEffect, useState } from "react";-import { ChevronDown, ChevronRight, Minus, Plus } from "lucide-react";import { Button } from "@/components/ui/button";import {- Collapsible,- CollapsibleContent,- CollapsibleTrigger,-} from "@/components/ui/collapsible";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";+ DisclosureGroup,+ SelectRow,+ StepperRow,+} from "@/components/pdf-export/settings-rows";import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import {- clampNumericField,formatSettingValue,PDF_FONT_LABELS,- PDF_NUMERIC_SETTINGS,} from "@/models/pdfExport.model";import {RESUME_LAYOUT_LABELS,@@ -36,158 +23,7 @@ type ExportSettingsPanelProps = {isDefault?: boolean;};-// Wraps rather than clips: the control drops below the label on a narrow-// settings column instead of overflowing it.-const ROW =- "flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-b px-4 py-2.5 last:border-b-0";--// A label element pointing at role="combobox" is named inconsistently across-// accname implementations, so the trigger carries its own aria-label.-function SelectRow<T extends string>({- id,- label,- value,- labels,- onSelect,-}: {- id: string;- label: string;- value: T;- labels: Record<T, string>;- onSelect: (value: T) => void;-}) {- return (- <div className={ROW}>- <Label htmlFor={id} className="cursor-pointer font-normal">- {label}- </Label>- <Select value={value} onValueChange={(next) => onSelect(next as T)}>- <SelectTrigger id={id} aria-label={label} className="ml-auto h-8 w-40">- <SelectValue />- </SelectTrigger>- <SelectContent>- {(Object.keys(labels) as T[]).map((key) => (- <SelectItem key={key} value={key}>- {labels[key]}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- );-}--// The draft string is what is typed; only a parsed, in-range value is-// committed upward. Clamping on every keystroke would snap a cleared field-// to its minimum mid-edit.-function StepperRow({- field,- value,- onCommit,-}: {- field: ResumeNumericSetting;- value: number;- onCommit: (value: number) => void;-}) {- const spec = PDF_NUMERIC_SETTINGS[field];- const id = `resume-export-${field}`;- const [draft, setDraft] = useState(() => String(value));-- // Resyncs when the value moves without the input being touched: Reset,- // or the first read from storage.- useEffect(() => {- setDraft(String(value));- }, [value]);-- const stepBy = (direction: 1 | -1) =>- onCommit(clampNumericField(field, value + direction * spec.step));-- const onDraftChange = (next: string) => {- setDraft(next);- const parsed = Number(next);- if (next.trim() === "" || !Number.isFinite(parsed)) return;- if (parsed < spec.min || parsed > spec.max) return;- onCommit(clampNumericField(field, parsed));- };-- return (- <div className={ROW}>- <Label htmlFor={id} className="cursor-pointer font-normal">- {spec.label}- </Label>- <div className="ml-auto flex items-center gap-1">- <Button- type="button"- variant="outline"- size="icon"- className="h-7 w-7 shrink-0"- aria-label={`Decrease ${spec.label}`}- disabled={value <= spec.min}- onClick={() => stepBy(-1)}- >- <Minus className="h-3 w-3" aria-hidden />- </Button>- <Input- id={id}- type="number"- inputMode="decimal"- min={spec.min}- max={spec.max}- step={spec.step}- value={draft}- onChange={(event) => onDraftChange(event.target.value)}- onBlur={() => setDraft(String(value))}- className="h-7 w-16 px-2 text-center text-sm"- />- {spec.unit && (- <span className="w-4 text-xs text-muted-foreground">{spec.unit}</span>- )}- <Button- type="button"- variant="outline"- size="icon"- className="h-7 w-7 shrink-0"- aria-label={`Increase ${spec.label}`}- disabled={value >= spec.max}- onClick={() => stepBy(1)}- >- <Plus className="h-3 w-3" aria-hidden />- </Button>- </div>- </div>- );-}--function DisclosureGroup({- title,- summary,- children,-}: {- title: string;- summary: string;- children: React.ReactNode;-}) {- const [open, setOpen] = useState(true);-- return (- <Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex w-full items-center gap-1.5 text-sm font-semibold">- {open ? (- <ChevronDown className="h-4 w-4" aria-hidden />- ) : (- <ChevronRight className="h-4 w-4" aria-hidden />- )}- {title}- </CollapsibleTrigger>- {!open && (- <p className="pl-[1.375rem] text-xs text-muted-foreground">{summary}</p>- )}- <CollapsibleContent className="mt-2 rounded-lg border bg-muted/40">- {children}- </CollapsibleContent>- </Collapsible>- );-}+const ID_PREFIX = "resume-export";export function ExportSettingsPanel({settings,@@ -214,7 +50,7 @@ export function ExportSettingsPanel({{/* Template reshapes everything below it, so it never folds away. */}<div className="rounded-lg border bg-muted/40"><SelectRow- id="resume-export-template"+ id={`${ID_PREFIX}-template`}label="Template"value={settings.template}labels={RESUME_LAYOUT_LABELS}@@ -224,18 +60,20 @@ export function ExportSettingsPanel({<DisclosureGroup title="Typography" summary={typographySummary}><SelectRow- id="resume-export-font"+ id={`${ID_PREFIX}-font`}label="Font"value={settings.font}labels={PDF_FONT_LABELS}onSelect={(font) => onChange({ ...settings, font })}/><StepperRow+ idPrefix={ID_PREFIX}field="fontSize"value={settings.fontSize}onCommit={setNumber("fontSize")}/><StepperRow+ idPrefix={ID_PREFIX}field="lineHeight"value={settings.lineHeight}onCommit={setNumber("lineHeight")}@@ -244,21 +82,25 @@ export function ExportSettingsPanel({<DisclosureGroup title="Layout" summary={layoutSummary}><StepperRow+ idPrefix={ID_PREFIX}field="marginVertical"value={settings.marginVertical}onCommit={setNumber("marginVertical")}/><StepperRow+ idPrefix={ID_PREFIX}field="marginHorizontal"value={settings.marginHorizontal}onCommit={setNumber("marginHorizontal")}/><StepperRow+ idPrefix={ID_PREFIX}field="sectionSpacing"value={settings.sectionSpacing}onCommit={setNumber("sectionSpacing")}/><StepperRow+ idPrefix={ID_PREFIX}field="entrySpacing"value={settings.entrySpacing}onCommit={setNumber("entrySpacing")}diff --git a/src/components/profile/resume-container/useResumeExportSettings.ts b/src/components/profile/resume-container/useResumeExportSettings.tsindex bca2372..393f9fc 100644--- a/src/components/profile/resume-container/useResumeExportSettings.ts+++ b/src/components/profile/resume-container/useResumeExportSettings.ts@@ -1,5 +1,5 @@"use client";-import { useEffect, useState } from "react";+import { useExportSettings } from "@/components/pdf-export/useExportSettings";import { APP_CONSTANTS } from "@/lib/constants";import {clampNumericField,@@ -14,10 +14,6 @@ import {type ResumeExportSettings,type ResumeLayout,} from "@/models/resumeExport.model";-import {- getFromLocalStorage,- saveToLocalStorage,-} from "@/utils/localstorage.utils";const KEY = APP_CONSTANTS.RESUME_EXPORT_SETTINGS_STORAGE_KEY;@@ -57,44 +53,25 @@ export function coerceResumeExportSettings(return next;}-function readStored(): ResumeExportSettings {- try {- return coerceResumeExportSettings(getFromLocalStorage(KEY, null));- } catch {- // getFromLocalStorage calls JSON.parse unguarded.- return { ...defaultResumeExportSettings };- }-}--// Reads on open rather than at mount: localStorage is unavailable during SSR,-// and `ready` holds the preview back one commit so it generates once, with-// the stored settings, instead of once with the defaults and again after.+// Reads on open, keeping the resume's own rule on top: picking a template+// re-seeds the rest, because each template's defaults are its own shipped+// literals and carrying the previous one's numbers across would silently+// restyle the template the user just chose. The letter has no template, so+// this rule stays here rather than moving into the shared hook.export function useResumeExportSettings(open: boolean) {- const [settings, setSettings] = useState<ResumeExportSettings>(- defaultResumeExportSettings,- );- const [ready, setReady] = useState(false);-- useEffect(() => {- if (!open) {- setReady(false);- return;- }- setSettings(readStored());- setReady(true);- }, [open]);+ const { settings, setSettings, ready } = useExportSettings({+ storageKey: KEY,+ defaults: defaultResumeExportSettings,+ coerce: coerceResumeExportSettings,+ open,+ });- // Picking a template re-seeds the rest: each template's defaults are its- // own shipped literals, so carrying the previous one's numbers across- // would silently restyle the template the user just chose.- const update = (next: ResumeExportSettings) => {- const applied =+ const update = (next: ResumeExportSettings) =>+ setSettings(next.template === settings.template? next- : { ...RESUME_TEMPLATE_DEFAULTS[next.template] };- setSettings(applied);- saveToLocalStorage(KEY, applied);- };+ : { ...RESUME_TEMPLATE_DEFAULTS[next.template] },+ );return {settings,diff --git a/src/components/profile/resume-container/useResumePdfPreview.ts b/src/components/profile/resume-container/useResumePdfPreview.tsindex ee4e397..aa14892 100644--- a/src/components/profile/resume-container/useResumePdfPreview.ts+++ b/src/components/profile/resume-container/useResumePdfPreview.ts@@ -1,108 +1,24 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useCallback } from "react";+import { usePdfPreview } from "@/components/pdf-export/usePdfPreview";import type { Resume } from "@/models/profile.model";import type { ResumeExportSettings } from "@/models/resumeExport.model";import { canExportResume } from "./useResumePdfExport";-const PREVIEW_DEBOUNCE_MS = 250;--type PreviewResult = { blob: Blob; filename: string };--// Owns the preview artifact: debounce, cache, and blob generation. Deliberately-// touches no canvas and creates no object URL — PdfPreviewPane owns rendering.export function useResumePdfPreview(resume: Resume,settings: ResumeExportSettings,open: boolean,) {- const [result, setResult] = useState<PreviewResult | null>(null);- const [isGenerating, setIsGenerating] = useState(false);- const [error, setError] = useState<Error | null>(null);-- const cacheRef = useRef(new Map<string, PreviewResult>());- const hasRenderedRef = useRef(false);- const runIdRef = useRef(0);-- // Read through refs so the effect can depend on primitives only.- const resumeRef = useRef(resume);- resumeRef.current = resume;- const settingsRef = useRef(settings);- settingsRef.current = settings;-- // Insertion-order sensitive. Fine while settings come from one literal;- // revisit the day a setting arrives by spread or merge.- const key = JSON.stringify(settings);- const canExport = canExportResume(resume);-- useEffect(() => {- if (!open) {- // A resume edited between openings must never show a stale preview.- cacheRef.current.clear();- hasRenderedRef.current = false;- runIdRef.current += 1;- setResult(null);- setIsGenerating(false);- setError(null);- return;- }-- if (!canExport) {- runIdRef.current += 1;- setResult(null);- setIsGenerating(false);- setError(null);- return;- }-- const cached = cacheRef.current.get(key);- if (cached) {- runIdRef.current += 1;- hasRenderedRef.current = true;- setResult(cached);- setIsGenerating(false);- setError(null);- return;- }-- const runId = ++runIdRef.current;- setIsGenerating(true);- setError(null);-- const generate = async () => {- try {- const { generateResumePdfBlob } = await import("../resume-pdf");- const generated = await generateResumePdfBlob(- resumeRef.current,- settingsRef.current,- );- if (runIdRef.current !== runId) return;- cacheRef.current.set(key, generated);- setResult(generated);- setError(null);- } catch (e) {- if (runIdRef.current !== runId) return;- setResult(null);- setError(e instanceof Error ? e : new Error("Preview failed"));- } finally {- if (runIdRef.current === runId) setIsGenerating(false);- }- };-- // Opening the dialog must not wait out a debounce nobody triggered.- if (!hasRenderedRef.current) {- hasRenderedRef.current = true;- void generate();- return;- }-- const timer = setTimeout(() => void generate(), PREVIEW_DEBOUNCE_MS);- return () => clearTimeout(timer);- }, [open, key, canExport]);-- return {- blob: result?.blob ?? null,- filename: result?.filename ?? null,- isGenerating,- error,- };+ // The dynamic import stays here, so the shared hook never pulls+ // @react-pdf/renderer into its own chunk.+ const generate = useCallback(+ async (next: ResumeExportSettings) => {+ const { generateResumePdfBlob } = await import("../resume-pdf");+ return generateResumePdfBlob(resume, next);+ },+ [resume],+ );++ return usePdfPreview(generate, settings, open && canExportResume(resume));}