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!

4.8 KB
Raw Blame
import { t } from "@lingui/core/macro";
import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, redirect, useBlocker } from "@tanstack/react-router";
import { useEffect } from "react";
import z from "zod";
import { toast } from "@reactive-resume/ui/components/toast";
import { LetterShell } from "./-components/letter-shell";
import { useLetterEditorStore } from "@/features/letters/store";
import { orpc } from "@/libs/orpc/client";
import { getPageTitle, createNoindexFollowMeta } from "@/libs/seo";

const searchSchema = z.object({
	// Write is the default and stays out of the URL. Letters have no Check.
	mode: z.enum(["write", "design"]).optional().catch(undefined),
	// Opens History on this version, read-only; Applications' "Open" on what was sent links here.
	version: z.string().optional().catch(undefined),
	// Opens the assistant on a conversation ("new" for a fresh one).
	assistant: z.string().optional().catch(undefined),
	// Fills the assistant's composer. Never sent without the user pressing Send: anyone can make a link.
	ask: z.string().max(2_000).optional().catch(undefined),
	applicationId: z.string().optional().catch(undefined),
});

export const Route = createFileRoute("/builder/letter/$coverLetterId")({
	component: RouteComponent,
	validateSearch: searchSchema,
	beforeLoad: ({ context, location }) => {
		if (!context.session) throw redirect({ to: "/auth/login", search: { callbackURL: location.href }, replace: true });
		return { session: context.session };
	},
	loader: async ({ params, context }) => {
		// The preview is a chunk of its own, otherwise fetched only once the page has rendered: start it with the letter.
		void import("@/features/resume/preview/preview.browser");

		// Letter wording pulls in the composer; loaded here so every other page's startup skips it.
		const compose = import("@/features/letters/compose");

		// Always fetched fresh: linked details come from the resume as it reads now.
		const letter = await context.queryClient.fetchQuery({
			...orpc.coverLetters.getById.queryOptions({ input: { id: params.coverLetterId } }),
			staleTime: 0,
		});
		const { letterWordsQueryOptions } = await compose;
		await context.queryClient.ensureQueryData(letterWordsQueryOptions(letter.style.metadata.page.locale));
		return { name: letter.name };
	},
	head: ({ loaderData }) => ({
		meta: loaderData
			? [{ title: getPageTitle(loaderData.name) }, createNoindexFollowMeta()]
			: [createNoindexFollowMeta()],
	}),
});

function RouteComponent() {
	const { coverLetterId } = Route.useParams();
	const queryClient = useQueryClient();
	const { data: letter } = useSuspenseQuery(orpc.coverLetters.getById.queryOptions({ input: { id: coverLetterId } }));
	const loaded = useLetterEditorStore((state) => state.letter?.id === coverLetterId);
	const name = useLetterEditorStore((state) =>
		state.letter?.id === coverLetterId ? (state.savedName ?? letter.name) : letter.name,
	);
	useEffect(() => {
		document.title = getPageTitle(name);
	}, [name]);

	useBlocker({
		shouldBlockFn: async ({ next }) => {
			if ("coverLetterId" in next.params && next.params.coverLetterId === coverLetterId) return false;
			const { draft } = useLetterEditorStore.getState();
			if (draft.phase === "streaming" || draft.phase === "ready") {
				toast.add({
					type: "warning",
					description: t`This letter has an unkept draft. Click Keep to save it, or Discard to leave without it.`,
				});
				return true;
			}
			let timeout: ReturnType<typeof setTimeout> | undefined;
			const saved = await Promise.race([
				useLetterEditorStore.getState().flush(),
				new Promise<boolean>((resolve) => {
					timeout = setTimeout(() => resolve(false), 10_000);
				}),
			]);
			clearTimeout(timeout);
			if (!saved)
				toast.add({ type: "error", description: t`Couldn't save your changes. Try again before continuing.` });
			return !saved;
		},
		enableBeforeUnload: false,
	});

	// The editor owns the letter from here; later refetches don't overwrite what's being typed.
	useEffect(() => {
		if (useLetterEditorStore.getState().letter?.id !== letter.id) useLetterEditorStore.getState().load(letter);
	}, [letter]);

	// Leaving saves what's pending, then lets lists (Documents, Applications) catch up.
	useEffect(
		() => () => {
			const sessionId = useLetterEditorStore.getState().sessionId;
			void useLetterEditorStore
				.getState()
				.flush()
				.then((saved) => {
					if (!saved) return;
					const state = useLetterEditorStore.getState();
					if (state.letter?.id === coverLetterId && state.sessionId === sessionId) state.reset();
					void queryClient.invalidateQueries({ queryKey: orpc.coverLetters.key() });
					void queryClient.invalidateQueries({ queryKey: orpc.documents.key() });
					void queryClient.invalidateQueries({ queryKey: orpc.applications.key() });
				});
		},
		[coverLetterId, queryClient],
	);

	if (!loaded) return null;

	return <LetterShell />;
}