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!

15.2 KB
Raw Blame
import type { ComponentRef } from "react";
import type { Pressable } from "react-native";
import type { EnrichedTextInputInstance } from "react-native-enriched-html";
import { useLingui } from "@lingui/react/macro";
import { useRouter } from "expo-router";
import { useEffect, useRef, useState } from "react";
import { AccessibilityInfo, View } from "react-native";
import { EnrichedTextInput } from "react-native-enriched-html";
import { isValidSlug, MAX_SLUG_LENGTH, normalizeSlug } from "@reactive-resume/resume/sharing";
import { isolate } from "@reactive-resume/utils/string";
import { client } from "@/api/client";
import { resumeFieldFocus, useResumeStore } from "@/draft";
import { TranslateResume } from "@/features/assistant/translate-resume";
import { useNewDocuments } from "@/features/documents/new-documents";
import { useDocumentOperations } from "@/features/documents/queries";
import { useExistingTags } from "@/features/documents/tag-suggestions";
import { flushResume } from "@/features/share/document";
import { printResume } from "@/features/share/files";
import { setResumeLocked } from "@/features/share/revision";
import { confirmUndone } from "@/lib/undone";
import { routes } from "@/routes";
import { useBuilderChrome } from "@/shell/builder-chrome";
import { useKeyCommands } from "@/shell/key-commands";
import { useShortcutHelp } from "@/shell/shortcut-help";
import { Banner, Button, ChipInput, IconButton, ListRow, Sheet, Text, TextField, showToast, useTheme } from "@/ui";

type DocumentMenuProps = {
	id: string;
	/** Opens from the document name in the builder top bar instead of its own ⋯ button. */
	inChrome?: boolean;
};
/** BuilderChrome can mount this trigger; it owns no draft lifecycle. */
export function DocumentMenu({ id, inChrome = false }: DocumentMenuProps) {
	const router = useRouter();
	const { t, i18n } = useLingui();
	const { space } = useTheme();
	const draft = useResumeStore();
	const resume = draft.document?.id === id ? draft.document : null;
	const operations = useDocumentOperations();
	const [panel, setPanel] = useState<"menu" | "rename" | "duplicate" | "tags" | "notes" | "details" | null>(null);
	const [translating, setTranslating] = useState(false);
	const [name, setName] = useState("");
	const [tags, setTags] = useState<string[]>([]);
	const commitTags = useRef<(() => string[]) | null>(null);
	const tagSuggestions = useExistingTags(["resume"], panel === "tags");
	const [slug, setSlug] = useState("");
	const helpRequested = useRef(false);
	const menuTrigger = useRef<ComponentRef<typeof Pressable>>(null);
	const pending = useRef(Promise.resolve(false));
	const [printing, setPrinting] = useState(false);
	const printingRef = useRef(false);
	const close = () => {
		if (!operations.busy && !printing) setPanel(null);
	};
	const run = async (action: () => Promise<unknown>) => {
		const task = operations.run(action);
		pending.current = task;
		if (await task) setPanel(null);
	};
	const openMenu = () => {
		setName(resume?.name ?? "");
		setPanel("menu");
	};
	const print = () => {
		if (!resume || printingRef.current) return;
		printingRef.current = true;
		setPrinting(true);
		void printResume(resume.data, resume.name)
			.catch(() => showToast({ message: t`Couldn't print. Try again.` }))
			.finally(() => {
				printingRef.current = false;
				setPrinting(false);
			});
	};
	useBuilderChrome(inChrome ? { onMenu: resume ? openMenu : undefined, menuRef: menuTrigger } : {});
	useKeyCommands(inChrome ? [{ id: "print", input: "p", title: t`Print`, run: print }] : []);
	const titles = {
		menu: t`Document options`,
		rename: t`Rename`,
		duplicate: t`Duplicate resume`,
		tags: t`Tags`,
		notes: t`Notes`,
		details: t`Resume details`,
	};
	return (
		<>
			{translating && <TranslateResume resumeId={id} onClose={() => setTranslating(false)} />}
			{!inChrome && (
				<IconButton
					ref={menuTrigger}
					icon="dots-three"
					label={t`Document options`}
					disabled={!resume}
					onPress={openMenu}
				/>
			)}
			<Sheet
				onDismissed={() => {
					if (helpRequested.current) {
						helpRequested.current = false;
						useShortcutHelp.getState().show(() => {
							if (menuTrigger.current) AccessibilityInfo.sendAccessibilityEvent(menuTrigger.current, "focus");
						});
					}
				}}
				open={!!panel}
				title={panel ? titles[panel] : undefined}
				onClose={close}
				detents={[0.5, 0.9]}
			>
				{resume && (
					<View style={{ padding: space.s4, gap: space.s3 }}>
						{operations.error && <Banner tone="danger" message={operations.error} />}
						{panel === "menu" && (
							<>
								<Text variant="title">{resume.name}</Text>
								<ListRow
									title={t`Rename…`}
									leading="pencil-simple"
									disabled={resume.isLocked || operations.busy}
									onPress={() => setPanel("rename")}
								/>
								<ListRow
									title={t`Duplicate`}
									leading="copy"
									disabled={operations.busy || printing}
									onPress={() =>
										void operations.run(async () => {
											setName(await client.documents.suggestDuplicateName({ type: "resume", id }));
											setSlug("");
											setPanel("duplicate");
										})
									}
								/>
								{/* The library's job copy, from inside the editor (web's builder menu has it too). */}
								<ListRow
									title={t`Translate into…`}
									leading="translate"
									disabled={operations.busy || printing}
									onPress={() => {
										setPanel(null);
										setTranslating(true);
									}}
								/>
								<ListRow
									title={t`Copy for a job…`}
									leading="briefcase"
									disabled={operations.busy || printing}
									onPress={() =>
										void run(async () => {
											// The copy is made from the saved resume: save the open draft first, as Duplicate does.
											await flushResume(id);
											setPanel(null);
											router.push({ pathname: "/new", params: { step: "copy", sourceResumeId: id } });
										})
									}
								/>
								<ListRow
									title={t`Tags…`}
									leading="tag"
									disabled={resume.isLocked || operations.busy}
									onPress={() => {
										setTags(resume.tags);
										setPanel("tags");
									}}
								/>
								<ListRow
									title={resume.isLocked ? t`Unlock editing` : t`Lock editing`}
									leading={resume.isLocked ? "lock-open" : "lock"}
									disabled={operations.busy || printing}
									onPress={() =>
										void run(async () => {
											// Through the open draft's revision: Undo and the next autosave build on it.
											await setResumeLocked(id, !resume.isLocked);
										})
									}
								/>
								<ListRow
									title={t`Notes`}
									leading="note"
									disabled={operations.busy || printing}
									onPress={() => setPanel("notes")}
								/>
								<ListRow
									title={t`Details`}
									leading="info"
									disabled={operations.busy || printing}
									onPress={() => setPanel("details")}
								/>
								<ListRow
									title={t`History`}
									leading="clock-counter-clockwise"
									disabled={operations.busy || printing}
									onPress={() => {
										setPanel(null);
										router.push(routes.history(id));
									}}
								/>
								<ListRow
									title={t`Keyboard shortcuts`}
									leading="keyboard"
									onPress={() => {
										helpRequested.current = true;
										setPanel(null);
									}}
								/>
								<ListRow title={t`Print`} leading="printer" disabled={operations.busy || printing} onPress={print} />
								<ListRow
									title={t`Move to Trash`}
									leading="trash"
									destructive
									disabled={resume.isLocked || operations.busy}
									onPress={() =>
										void run(async () => {
											await flushResume(id);
											await client.documents.trash({ type: "resume", id });
											await useResumeStore.getState().close();
											router.replace(routes.documents());
											showToast({
												message: t`“${isolate(resume.name)}” moved to Trash`,
												action: {
													label: t`Undo`,
													onPress: () => {
														// Counted by the server: one already restored elsewhere, or deleted, isn't confirmed.
														let restored = 0;
														void pending.current
															.then(() =>
																operations.run(async () => {
																	restored = (
																		await client.documents.restoreMany({ documents: [{ type: "resume", id }] })
																	).restored;
																}),
															)
															.then((done) => {
																if (done && restored > 0) confirmUndone();
																else if (done)
																	showToast({ message: t`Nothing to undo: it was already restored or deleted.` });
															});
													},
												},
											});
										})
									}
								/>
							</>
						)}
						{panel === "rename" && (
							<>
								<TextField
									label={t`Name`}
									value={name}
									onChangeText={setName}
									maxLength={100}
									editable={!operations.busy && !resume.isLocked}
								/>
								<Button
									label={t`Save`}
									disabled={!name.trim() || resume.isLocked}
									loading={operations.busy}
									onPress={() =>
										void run(async () => {
											await flushResume(id);
											useResumeStore.getState().updateDocument((value) => {
												if (value.id !== id) return;
												value.name = name.trim();
											});
											await flushResume(id);
										})
									}
								/>
							</>
						)}
						{panel === "tags" && (
							<>
								<View pointerEvents={operations.busy || resume.isLocked ? "none" : "auto"}>
									<ChipInput
										commitRef={commitTags}
										label={t`Tags`}
										values={tags}
										onChange={setTags}
										suggestions={tagSuggestions}
										suggestionsLabel={t`Your tags`}
									/>
								</View>
								<Text variant="caption" color="ink3">{t`Up to 20 tags per document, 40 characters per tag.`}</Text>
								<Button
									label={t`Save`}
									loading={operations.busy}
									disabled={resume.isLocked || tags.length > 20 || tags.some((tag) => !tag.trim() || tag.length > 40)}
									onPress={() => {
										if (operations.busy || resume.isLocked) return;
										const next = commitTags.current?.() ?? tags;
										if (next.length > 20 || next.some((tag) => !tag.trim() || tag.length > 40)) return;
										void run(async () => {
											await flushResume(id);
											useResumeStore.getState().updateDocument((value) => {
												if (value.id !== id) return;
												value.tags = next;
											});
											await flushResume(id);
										});
									}}
								/>
							</>
						)}
						{panel === "duplicate" && (
							<>
								<TextField
									label={t`Name`}
									value={name}
									onChangeText={setName}
									maxLength={100}
									editable={!operations.busy}
								/>
								<TextField
									label={t`Slug`}
									value={slug}
									onChangeText={(value) => setSlug(normalizeSlug(value))}
									ltr
									editable={!operations.busy}
									autoCapitalize="none"
									autoCorrect={false}
									helper={t`Leave empty to generate an available address from the name.`}
									error={
										slug.length > MAX_SLUG_LENGTH
											? t`Use at most 64 characters.`
											: slug && !isValidSlug(slug)
												? t`Use Latin letters a–z, numbers and single dashes.`
												: undefined
									}
								/>
								<Button
									label={t`Duplicate`}
									loading={operations.busy}
									disabled={!name.trim() || (!!slug && !isValidSlug(slug))}
									onPress={() =>
										void run(async () => {
											const current = await flushResume(id);
											const copy = await client.resume.duplicate({
												id,
												name: name.trim(),
												tags: current.tags,
												...(slug ? { slug } : {}),
											});
											useNewDocuments.getState().markNew({ id: copy, type: "resume" });
											showToast({ message: t`Copy created` });
											router.replace(routes.builder(copy));
										})
									}
								/>
							</>
						)}
						{panel === "notes" && (
							<>
								<Text color="ink2">{t`Keep private notes about this resume here. Nobody else can see them.`}</Text>
								<NotesEditor id={id} value={resume.data.metadata.notes} locked={resume.isLocked} />
								<Text variant="caption" color="ink3">{t`Draft · not printed`}</Text>
							</>
						)}
						{panel === "details" && (
							<>
								<Text variant="title">{resume.name}</Text>
								<ListRow title={t`Created`} subtitle={resume.createdAt.toLocaleString(i18n.locale)} />
								<ListRow title={t`Last edited`} subtitle={resume.updatedAt.toLocaleString(i18n.locale)} />
								<ListRow title={t`Template`} subtitle={resume.data.metadata.template} />
								<ListRow title={t`Language`} subtitle={resume.data.metadata.page.locale} />
								<ListRow
									title={t`Sharing`}
									subtitle={
										resume.isPublic
											? resume.hasPassword
												? t`Public, with a password`
												: t`Public`
											: t`Private. Only you can see it.`
									}
								/>
								<Text selectable color="ink3">
									{resume.slug}
								</Text>
							</>
						)}
						{panel !== "menu" ? (
							<Button
								label={t`Back`}
								variant="ghost"
								disabled={operations.busy || printing}
								onPress={() => setPanel("menu")}
							/>
						) : null}
					</View>
				)}
			</Sheet>
		</>
	);
}

type NotesEditorProps = { id: string; value: string; locked: boolean };
function NotesEditor({ id, value, locked }: NotesEditorProps) {
	const { t } = useLingui();
	const { space, colors, radius, type } = useTheme();
	const editor = useRef<EnrichedTextInputInstance>(null);
	const last = useRef(value);
	const focused = useRef(false);
	const [isFocused, setIsFocused] = useState(false);
	const border = isFocused ? 2 : 1;
	useEffect(
		() => () => {
			if (focused.current) {
				focused.current = false;
				resumeFieldFocus.onBlur();
			}
		},
		[],
	);
	useEffect(() => {
		if (!focused.current && value !== last.current) {
			last.current = value;
			editor.current?.setValue(value);
		}
	}, [value]);
	return (
		<View
			style={{
				borderWidth: border,
				borderRadius: radius.rMd,
				borderColor: isFocused ? colors.accent : colors.lineStrong,
				backgroundColor: locked ? colors.sunken : colors.raised,
				overflow: "hidden",
			}}
		>
			<EnrichedTextInput
				key={id}
				ref={editor}
				accessibilityLabel={t`Notes`}
				defaultValue={value}
				editable={!locked}
				onFocus={() => {
					focused.current = true;
					setIsFocused(true);
					resumeFieldFocus.onFocus();
				}}
				onBlur={() => {
					focused.current = false;
					setIsFocused(false);
					resumeFieldFocus.onBlur();
				}}
				style={{
					minHeight: space.s12 * 3 - border * 2,
					color: colors.ink,
					padding: space.s3 - (border - 1),
					fontFamily: type.body.fontFamily,
					fontSize: type.body.fontSize,
				}}
				onChangeHtml={(event) => {
					if (!focused.current) return;
					const html = event.nativeEvent.value;
					last.current = html;
					useResumeStore.getState().update(
						(data) => {
							data.metadata.notes = html;
						},
						{ coalesceKey: "metadata.notes" },
					);
				}}
			/>
		</View>
	);
}