Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

13.2 KB
Raw Blame
import type { EditorSelection } from "@/features/resume/editor/store";
import type { VersionSummary } from "@/features/resume/share/format";
import type { Template } from "@reactive-resume/schema/templates";
import { i18n } from "@lingui/core";
import { ph, t } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";
import { Plural, Trans } from "@lingui/react/macro";
import { useQuery } from "@tanstack/react-query";
import { lazyRouteComponent } from "@tanstack/react-router";
import { Suspense, useCallback, useLayoutEffect, useRef, useState } from "react";
import { measureOverflow } from "@reactive-resume/pdf/page-map";
import { spillingSections } from "@reactive-resume/resume/spill";
import { Icon } from "@reactive-resume/ui/components/icon";
import { useBreakpoint } from "@reactive-resume/ui/hooks/use-breakpoint";
import { cn } from "@reactive-resume/utils/style";
import { templates } from "@/dialogs/resume/template/data";
import { useCurrentBuilderResumeSelector, useResumeData, useResumeStore } from "@/features/resume/builder/draft";
import { CheckPageLayer, PageViewToggle } from "@/features/resume/editor/check/page-layer";
import { ParserView } from "@/features/resume/editor/check/parser-view";
import { CanvasStatusPill, usePageScale, ZoomBar } from "@/features/resume/editor/chrome";
import { addSpillPage, runFit } from "@/features/resume/editor/design/fit";
import { PageOverlay } from "@/features/resume/editor/page-overlay";
import { markProposals, pendingProposals } from "@/features/resume/editor/proposals/proposals";
import { useEditorStore } from "@/features/resume/editor/store";
import { useEditorMode } from "@/features/resume/editor/use-editor-mode";
import { revealSelectionInPanel } from "@/features/resume/editor/write/reveal";
import { ResumePreview } from "@/features/resume/preview/preview";
import { formatVersionTime, getVersionTitle } from "@/features/resume/share/format";
import { orpc } from "@/libs/orpc/client";

const NONE: readonly never[] = [];

const WebPagePreview = lazyRouteComponent(() => import("@/features/resume/share/web-page-preview"), "WebPagePreview");

/** Share shows the web page; every other mode, the PDF's pages. */

/** The Download & history sheet's width on desktop (the Sheet's `sm:max-w-[440px]`). */
const SHEET_WIDTH = 440;
export function PageCanvas() {
	const [mode] = useEditorMode();
	if (mode !== "share") return <ResumePageCanvas />;
	return (
		<Suspense>
			<WebPagePreview />
		</Suspense>
	);
}

/**
 * The page canvas: the live resume on the sunken desk, with a caption above the first page, a pointer layer
 * that links lines to entries, and the zoom bar.
 */
function ResumePageCanvas() {
	const data = useResumeData();
	const format = useCurrentBuilderResumeSelector((resume) => resume.data.metadata.page.format);
	const previewTemplate = useEditorStore((state) => state.previewTemplate);
	const historyVersionId = useEditorStore((state) => state.historyVersionId);
	const pageView = useEditorStore((state) => state.pageView);
	const checkTab = useEditorStore((state) => state.checkTab);
	const proposals = useEditorStore((state) => state.proposals);
	const assistantProposals = useEditorStore((state) => (state.assistantOpen ? state.assistantProposals : NONE));
	const sheetOpen = useEditorStore((state) => state.sheetTab !== null);
	const resumeId = useCurrentBuilderResumeSelector((resume) => resume.id);
	const rendered = useEditorStore((state) => state.rendered);
	const setRendered = useEditorStore((state) => state.setRendered);
	const breakpoint = useBreakpoint();
	const [mode] = useEditorMode();
	// Desktop: the Download & history sheet covers the canvas's end; the page fits, and centres in, what's left.
	const shifted = sheetOpen && (breakpoint === "desktop" || breakpoint === "wide");
	const { canvasRef, fitScale, pageScale } = usePageScale(format, shifted ? SHEET_WIDTH : 0);
	const isPhone = breakpoint === "mobile";

	// History: the picked version is drawn on the page, read-only, until the user restores it or goes back to now.
	const { data: version } = useQuery({
		...orpc.resume.getVersion.queryOptions({ input: { resumeId, versionId: historyVersionId ?? "" } }),
		enabled: historyVersionId !== null,
	});
	const viewing = historyVersionId !== null && version?.id === historyVersionId ? version : null;

	// Check → Writing's and the assistant's proposed edits show on the page, the old text struck through and the new
	// highlighted.
	const markEdits = mode === "check" && checkTab === "writing" && pageView === "page" && proposals.length > 0;
	const marked = [...(markEdits ? proposals : []), ...assistantProposals];
	const applications = useResumeStore((state) => state.proposalApplications);
	const pendingOnPage = data ? pendingProposals(data, assistantProposals, undefined, applications).length : 0;
	const parser = mode === "check" && pageView === "parser" && !viewing;

	// Design: a hovered or focused template is drawn on the page until it's applied or the pointer leaves.
	const previewData = viewing
		? viewing.data
		: data && previewTemplate
			? { ...data, metadata: { ...data.metadata, template: previewTemplate } }
			: // Only undecided edits change the page: once every one is decided, it draws (and measures) as it is.
				data && pendingProposals(data, marked, undefined, applications).length > 0
				? markProposals(data, marked, applications)
				: undefined;
	// Fit is the resume's as it is: a render with edits marked (old and new text both shown) doesn't count. The callback
	// keeps one identity (the preview re-reports on every new one), reading whether this render is marked from a ref.
	const fitRendered = useEditorStore((state) => state.fitRendered);
	const markedRender = useRef(false);
	const marking = previewData !== undefined;
	// A layout effect, so it's current before the preview's own effect reports the render.
	useLayoutEffect(() => {
		markedRender.current = marking;
	}, [marking]);
	const onRender = useCallback(
		(render: Parameters<typeof setRendered>[0]) => setRendered(render, markedRender.current),
		[setRendered],
	);
	const overflow = data && !previewTemplate && !viewing ? measureOverflow(data, fitRendered) : null;

	const onSelect = (selection: EditorSelection) => {
		useEditorStore.setState({ selection });
		// Tablet: tapping a line opens the drawer on that entry.
		if (breakpoint === "tablet") useEditorStore.setState({ drawerOpen: true });
		// Phones show the page and the panel one at a time; the selection bar opens the entry instead.
		if (mode === "write" && !isPhone) revealSelectionInPanel(selection);
	};

	return (
		<div className="relative h-full min-h-0 bg-sunken">
			<section
				ref={canvasRef}
				// The scroll area takes focus so the page can be scrolled from the keyboard even before its lines load.
				// oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- a scrollable region must be reachable by keyboard.
				tabIndex={0}
				aria-label={t`Resume page`}
				// Tapping the page (not a line) closes the tablet drawer but keeps the selection; on phones it
				// dismisses the selection bar.
				onPointerDown={(event) => {
					if ((event.target as HTMLElement).closest("[data-kind]")) return;
					if (breakpoint === "tablet") useEditorStore.setState({ drawerOpen: false });
					if (isPhone) useEditorStore.setState({ selection: null });
				}}
				className={cn(
					// The region takes focus to scroll from the keyboard: it shows the ring, inset since it fills its container.
					"absolute inset-0 overflow-auto pb-24 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent",
					// Check keeps room above the page for the page-view toggle.
					mode === "check" && !viewing ? "pt-[68px]" : "pt-7",
					isPhone ? "px-4" : "px-10",
				)}
			>
				<ResumePreview
					data={previewData}
					pageLayout="vertical"
					pageGap={24}
					pageScale={pageScale}
					className={cn(
						"mx-auto w-fit transition-transform duration-emphasized ease-enter",
						shifted && "-translate-x-[220px] rtl:translate-x-[220px]",
						parser && "hidden",
					)}
					pageClassName={cn("rounded-none shadow-page", viewing && "outline-2 outline-offset-4 outline-ink")}
					onRender={onRender}
					renderPageCaption={({ pageNumber }) => (
						<ResumePageCaption
							pageNumber={pageNumber}
							viewing={viewing}
							previewTemplate={previewTemplate}
							pendingOnPage={pendingOnPage}
							mode={mode}
							format={format}
							overflow={overflow}
						/>
					)}
					renderPageOverlay={({ pageIndex, pageMap }) =>
						// A version from History is read-only: its lines don't open entries.
						viewing ? null : mode === "check" ? (
							<CheckPageLayer pageIndex={pageIndex} pageMap={pageMap} />
						) : (
							<PageOverlay pageIndex={pageIndex} pageMap={pageMap} onSelect={onSelect} />
						)
					}
				/>
				{parser && <ParserView />}
			</section>

			{mode === "check" && !viewing && <PageViewToggle />}
			{!parser && <ZoomBar fitScale={fitScale} pageCount={Math.max(1, rendered.pageCount)} />}
		</div>
	);
}

type ResumePageCaptionProps = {
	pageNumber: number;
	viewing: { createdAt: Date; kind: VersionSummary["kind"]; name: VersionSummary["name"] } | null;
	previewTemplate: Template | null;
	pendingOnPage: number;
	mode: string;
	format: "a4" | "letter" | "free-form";
	overflow: ReturnType<typeof measureOverflow>;
};

/** Above the first page: the version or template being previewed, else the page label with proposals and overflow. */
function ResumePageCaption(props: ResumePageCaptionProps) {
	const { pageNumber, viewing, previewTemplate, pendingOnPage, mode, format, overflow } = props;
	const { i18n } = useLingui();
	const formatLabel = {
		a4: "A4",
		letter: t({ message: "Letter", context: "US Letter paper size (8.5 × 11 in), shown beside A4" }),
		"free-form": t`Free-form`,
	}[format];

	if (pageNumber === 1) {
		return (
			<figcaption className="mb-2.5 flex flex-wrap items-center justify-center gap-2.5 text-center text-xs font-medium text-ink-3">
				{viewing ? (
					<CanvasStatusPill icon="clock-counter-clockwise">
						<Trans>
							Viewing {formatVersionTime(viewing.createdAt, i18n.locale)} · {getVersionTitle(viewing)} · read-only
						</Trans>
					</CanvasStatusPill>
				) : previewTemplate ? (
					<CanvasStatusPill icon="eye">
						<Trans>Previewing {templates[previewTemplate].name} · click to apply</Trans>
					</CanvasStatusPill>
				) : (
					<>
						{pendingOnPage > 0 ? (
							<span className="text-accent-text">
								<Plural
									value={pendingOnPage}
									one="# proposed edit on this page · nothing changes until you accept"
									other="# proposed edits on this page · nothing changes until you accept"
								/>
							</span>
						) : mode === "check" ? (
							<Trans>Page 1 · {formatLabel}</Trans>
						) : (
							<Trans>Page 1</Trans>
						)}
						{overflow && <OverflowChip {...overflow} />}
					</>
				)}
			</figcaption>
		);
	}

	// Every continuation belongs to its authored page, even before the last authored page starts.
	if (overflow?.spills.some((spill) => spill.pages.includes(pageNumber))) {
		return (
			<figcaption className="relative mb-2.5 border-t-[1.5px] border-dashed border-warn">
				<span className="absolute end-0 -top-2.5 rounded bg-sunken px-1.5 text-xs font-semibold text-warn-text">
					<Trans>Page {ph({ pageNumber: i18n.number(pageNumber) })}</Trans>
				</span>
			</figcaption>
		);
	}

	return (
		<figcaption className="mb-2.5 text-center text-xs font-medium text-ink-3">
			<Trans>Page {ph({ pageNumber: i18n.number(pageNumber) })}</Trans>
		</figcaption>
	);
}

type OverflowChipProps = NonNullable<ReturnType<typeof measureOverflow>>;

/**
 * Names the first authored page that spills, with two ways out: Add page, which moves the sections that spill off
 * the last page onto a new one, and Fit, which tightens the design until it fits. Each is one undo step.
 */
function OverflowChip({ authored, spills, pageCount }: OverflowChipProps) {
	const [fitting, setFitting] = useState(false);
	const first = spills[0];
	const lines = first?.lines;
	const next = authored + 1;
	const data = useResumeData();
	const pageMap = useEditorStore((state) => state.rendered.pageMap);
	const canAddPage = !!data && spillingSections(data.metadata.layout.pages, pageMap?.nodes) !== null;
	const action =
		"h-6 rounded-md bg-surface px-2.5 text-xs font-semibold whitespace-nowrap text-ink shadow-e1 disabled:opacity-60";

	return (
		<span className="flex min-h-8 items-center gap-2 rounded-lg bg-warn-soft py-1 ps-3 pe-1.5 text-[13px] text-warn-text">
			<Icon name="square-split-horizontal" size={18} />
			{first && first.pages.length === 1 && lines ? (
				<Plural
					value={lines}
					one={`Page ${ph({ page: i18n.number(first.authoredPage) })} runs over by about # line`}
					other={`Page ${ph({ page: i18n.number(first.authoredPage) })} runs over by about # lines`}
				/>
			) : (
				<Plural value={pageCount} one="Runs to # page" other="Runs to # pages" />
			)}
			{canAddPage && (
				<button type="button" disabled={fitting} onClick={() => addSpillPage()} className={action}>
					<Trans>Add page {next}</Trans>
				</button>
			)}
			<button
				type="button"
				disabled={fitting}
				onClick={() => {
					setFitting(true);
					void runFit().finally(() => setFitting(false));
				}}
				className={action}
			>
				<Plural value={authored} _1="Fit to one page" other="Fit to # pages" />
			</button>
		</span>
	);
}