refactor: lint formatting and fixes #6
@@ -3,63 +3,58 @@ import logo from "../assets/logo.svg";
|
||||
import "@fontsource/knewave/400.css";
|
||||
|
||||
interface LogoProps {
|
||||
scale?: number;
|
||||
type?: "inline" | "mono" | "logo" | null;
|
||||
ul?: boolean;
|
||||
scale?: number;
|
||||
type?: "inline" | "mono" | "logo" | null;
|
||||
ul?: boolean;
|
||||
}
|
||||
|
||||
export default function Logo({
|
||||
scale = 1,
|
||||
type = null,
|
||||
ul = false,
|
||||
scale = 1,
|
||||
type = null,
|
||||
ul = false,
|
||||
}: LogoProps) {
|
||||
if (type === "inline") {
|
||||
return (
|
||||
<span className={"text-accent font-display italic "}>
|
||||
pi<span className="text-primary">.</span> ku
|
||||
<span className="text-primary">.</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "mono") {
|
||||
return (
|
||||
<span className="font-display italic font-bold border-b-3 border-dashed border-stone-800/50">
|
||||
pi. ku.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "logo") {
|
||||
return (
|
||||
<img
|
||||
src={logo}
|
||||
alt="Pi. Ku. logo"
|
||||
className="mx-4"
|
||||
width={scale * 100}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "inline") {
|
||||
return (
|
||||
<div
|
||||
role="img"
|
||||
aria-label="Pi. Ku. logo"
|
||||
className={`inline-flex items-baseline justify-center leading-none select-none ${ul ? "ul-wavy" : ""}`}
|
||||
style={{ fontFamily: "'Knewave', serif", scale }}
|
||||
>
|
||||
<span className="text-3xl font-light text-accent">Pi</span>
|
||||
<DotIcon
|
||||
weight="fill"
|
||||
size={12}
|
||||
className="text-primary translate-y-1 -mx-px"
|
||||
/>
|
||||
<span className="text-3xl font-light text-accent"> Ku</span>
|
||||
<DotIcon
|
||||
weight="fill"
|
||||
size={12}
|
||||
className="text-primary translate-y-1 -mx-px"
|
||||
/>
|
||||
</div>
|
||||
<span className={"text-accent font-display italic "}>
|
||||
pi<span className="text-primary">.</span> ku
|
||||
<span className="text-primary">.</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "mono") {
|
||||
return (
|
||||
<span className="font-display italic font-bold border-b-3 border-dashed border-stone-800/50">
|
||||
pi. ku.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "logo") {
|
||||
return (
|
||||
<img src={logo} alt="Pi. Ku. logo" className="mx-4" width={scale * 100} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="img"
|
||||
aria-label="Pi. Ku. logo"
|
||||
className={`inline-flex items-baseline justify-center leading-none select-none ${ul ? "ul-wavy" : ""}`}
|
||||
style={{ fontFamily: "'Knewave', serif", scale }}
|
||||
>
|
||||
<span className="text-3xl font-light text-accent">Pi</span>
|
||||
<DotIcon
|
||||
weight="fill"
|
||||
size={12}
|
||||
className="text-primary translate-y-1 -mx-px"
|
||||
/>
|
||||
<span className="text-3xl font-light text-accent"> Ku</span>
|
||||
<DotIcon
|
||||
weight="fill"
|
||||
size={12}
|
||||
className="text-primary translate-y-1 -mx-px"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,73 +6,73 @@ import { type CanvasTools, ComposeCanvas } from "../editor/ComposeCanvas";
|
||||
import { EnvelopeReveal } from "../reader/EnvelopeReveal";
|
||||
|
||||
export interface WelcomeLetterOverlayProps {
|
||||
onComplete: () => void;
|
||||
userName: string;
|
||||
onComplete: () => void;
|
||||
userName: string;
|
||||
}
|
||||
|
||||
export function WelcomeLetterOverlay({
|
||||
onComplete,
|
||||
userName,
|
||||
onComplete,
|
||||
userName,
|
||||
}: WelcomeLetterOverlayProps) {
|
||||
const [revealState, setRevealState] = useState<"SEALED" | "REVEALED">(
|
||||
"SEALED",
|
||||
);
|
||||
const canvasRef = useRef<CanvasTools>(null);
|
||||
const [revealState, setRevealState] = useState<"SEALED" | "REVEALED">(
|
||||
"SEALED",
|
||||
);
|
||||
const canvasRef = useRef<CanvasTools>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (revealState === "REVEALED" && canvasRef.current) {
|
||||
const welcomeContent = getWelcomeLetterContent(userName);
|
||||
canvasRef.current.loadData(welcomeContent);
|
||||
}
|
||||
}, [revealState, userName]);
|
||||
useEffect(() => {
|
||||
if (revealState === "REVEALED" && canvasRef.current) {
|
||||
const welcomeContent = getWelcomeLetterContent(userName);
|
||||
canvasRef.current.loadData(welcomeContent);
|
||||
}
|
||||
}, [revealState, userName]);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-30 backdrop-blur-3xl flex flex-col items-center justify-center p-4 md:p-8 overflow-x-hidden">
|
||||
<div className="fixed inset-0 bg-vig pointer-events-none z-0" />
|
||||
return (
|
||||
<div className="fixed inset-0 z-30 backdrop-blur-3xl flex flex-col items-center justify-center p-4 md:p-8 overflow-x-hidden">
|
||||
<div className="fixed inset-0 bg-vig pointer-events-none z-0" />
|
||||
|
||||
<div className="w-full max-w-4xl z-10 flex flex-col items-center">
|
||||
<AnimatePresence mode="wait">
|
||||
{revealState === "SEALED" && (
|
||||
<motion.div
|
||||
key="envelope"
|
||||
initial={{ scale: 0.5, opacity: 0 }}
|
||||
animate={{ scale: 0.8, opacity: 1 }}
|
||||
exit={{
|
||||
scale: 1,
|
||||
opacity: 0,
|
||||
transition: { duration: 0.5, ease: "easeOut" },
|
||||
}}
|
||||
transition={{ duration: 4, delay: 1 }}
|
||||
>
|
||||
<EnvelopeReveal
|
||||
recipient={userName}
|
||||
date={formatDate(new Date())}
|
||||
onRevealComplete={() => setRevealState("REVEALED")}
|
||||
ignite={false}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div
|
||||
className={`w-full space-y-8 py-12 ${revealState === "REVEALED" ? "block" : "hidden"}`}
|
||||
>
|
||||
<div className="bg-paper shadow-warm rounded-sm overflow-hidden mx-auto max-w-180">
|
||||
<div className="p-1 md:p-2 bg-base-content/5 opacity-10 pointer-events-none absolute inset-0 z-10" />
|
||||
<ComposeCanvas ref={canvasRef} readOnly />
|
||||
</div>
|
||||
<div className="w-full max-w-4xl z-10 flex flex-col items-center">
|
||||
<AnimatePresence mode="wait">
|
||||
{revealState === "SEALED" && (
|
||||
<motion.div
|
||||
key="envelope"
|
||||
initial={{ scale: 0.5, opacity: 0 }}
|
||||
animate={{ scale: 0.8, opacity: 1 }}
|
||||
exit={{
|
||||
scale: 1,
|
||||
opacity: 0,
|
||||
transition: { duration: 0.5, ease: "easeOut" },
|
||||
}}
|
||||
transition={{ duration: 4, delay: 1 }}
|
||||
>
|
||||
<EnvelopeReveal
|
||||
recipient={userName}
|
||||
date={formatDate(new Date())}
|
||||
onRevealComplete={() => setRevealState("REVEALED")}
|
||||
ignite={false}
|
||||
/>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div
|
||||
className={`w-full space-y-8 py-12 ${revealState === "REVEALED" ? "block" : "hidden"}`}
|
||||
>
|
||||
<div className="bg-paper shadow-warm rounded-sm overflow-hidden mx-auto max-w-180">
|
||||
<div className="p-1 md:p-2 bg-base-content/5 opacity-10 pointer-events-none absolute inset-0 z-10" />
|
||||
<ComposeCanvas ref={canvasRef} readOnly />
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center mt-12">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="dismiss-welcome-letter-btn"
|
||||
onClick={onComplete}
|
||||
className="btn btn-base btn-xs btn-wide opacity-80 shadow-lg font-light tracking-wider"
|
||||
>
|
||||
I'll see you
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-center mt-12">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="dismiss-welcome-letter-btn"
|
||||
onClick={onComplete}
|
||||
className="btn btn-base btn-xs btn-wide opacity-80 shadow-lg font-light tracking-wider"
|
||||
>
|
||||
I'll see you
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,39 +2,39 @@ import { XCircleIcon } from "@phosphor-icons/react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface ModalProps {
|
||||
isOpen: boolean;
|
||||
onClose?: () => void;
|
||||
children: ReactNode;
|
||||
"data-testid"?: string;
|
||||
isOpen: boolean;
|
||||
onClose?: () => void;
|
||||
children: ReactNode;
|
||||
"data-testid"?: string;
|
||||
}
|
||||
|
||||
export function Modal({
|
||||
isOpen,
|
||||
onClose,
|
||||
children,
|
||||
"data-testid": testId,
|
||||
isOpen,
|
||||
onClose,
|
||||
children,
|
||||
"data-testid": testId,
|
||||
}: ModalProps) {
|
||||
if (!isOpen) return null;
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid={testId}
|
||||
className="modal modal-open modal-middle backdrop-blur-md before:absolute before:top-0 before:left-0 before:w-full before:h-full before:content-[''] before:opacity-[0.03] before:z-10 before:pointer-events-none before:bg-[url('assets/textures/noise.gif')]"
|
||||
>
|
||||
<div className="modal-box relative bg-base-100/60 flex flex-col items-center text-center gap-6">
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="modal-close-btn"
|
||||
className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2 z-20"
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
>
|
||||
<XCircleIcon size={18} weight="bold" />
|
||||
</button>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
data-testid={testId}
|
||||
className="modal modal-open modal-middle backdrop-blur-md before:absolute before:top-0 before:left-0 before:w-full before:h-full before:content-[''] before:opacity-[0.03] before:z-10 before:pointer-events-none before:bg-[url('assets/textures/noise.gif')]"
|
||||
>
|
||||
<div className="modal-box relative bg-base-100/60 flex flex-col items-center text-center gap-6">
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="modal-close-btn"
|
||||
className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2 z-20"
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
>
|
||||
<XCircleIcon size={18} weight="bold" />
|
||||
</button>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { CanvasJSON } from "../components/editor/ComposeCanvas";
|
||||
import trainImage from "../assets/screenshots/train.png";
|
||||
import type { CanvasJSON } from "../components/editor/ComposeCanvas";
|
||||
|
||||
export function getWelcomeLetterContent(userName: string): CanvasJSON {
|
||||
return {
|
||||
|
||||
@@ -6,87 +6,87 @@ import { useKeyStore } from "../store/useKeyStore";
|
||||
import { CryptoUtils } from "../utils/crypto";
|
||||
|
||||
export interface ProcessedLetter extends LetterResponseData {
|
||||
metadata: LetterMetadata;
|
||||
metadata: LetterMetadata;
|
||||
}
|
||||
|
||||
async function decryptLettersMetadata(
|
||||
letters: LetterResponseData[],
|
||||
masterKey: CryptoKey,
|
||||
letters: LetterResponseData[],
|
||||
masterKey: CryptoKey,
|
||||
): Promise<ProcessedLetter[]> {
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
|
||||
return Promise.all(
|
||||
letters.map(async (letter) => {
|
||||
try {
|
||||
const metadata = (await cryptoUtils.decryptMetadata(
|
||||
{
|
||||
encrypted_content: letter.encrypted_metadata,
|
||||
encrypted_dek: letter.encrypted_dek,
|
||||
},
|
||||
masterKey,
|
||||
)) as LetterMetadata;
|
||||
return Promise.all(
|
||||
letters.map(async (letter) => {
|
||||
try {
|
||||
const metadata = (await cryptoUtils.decryptMetadata(
|
||||
{
|
||||
encrypted_content: letter.encrypted_metadata,
|
||||
encrypted_dek: letter.encrypted_dek,
|
||||
},
|
||||
masterKey,
|
||||
)) as LetterMetadata;
|
||||
|
||||
return { ...letter, metadata };
|
||||
} catch {
|
||||
return {
|
||||
...letter,
|
||||
metadata: { recipient: "Encrypted Letter" },
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
return { ...letter, metadata };
|
||||
} catch {
|
||||
return {
|
||||
...letter,
|
||||
metadata: { recipient: "Encrypted Letter" },
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function useLetters() {
|
||||
const [letters, setLetters] = useState<ProcessedLetter[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [isAuthRequired, setIsAuthRequired] = useState<boolean>(false);
|
||||
const { masterKey } = useKeyStore();
|
||||
const [letters, setLetters] = useState<ProcessedLetter[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [isAuthRequired, setIsAuthRequired] = useState<boolean>(false);
|
||||
const { masterKey } = useKeyStore();
|
||||
|
||||
// to fetch the letters and decryypt the metadata on load
|
||||
useEffect(() => {
|
||||
if (!masterKey) {
|
||||
setIsAuthRequired(true);
|
||||
return;
|
||||
}
|
||||
setIsAuthRequired(false);
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
api
|
||||
.get(endpoints.LETTERS)
|
||||
.then((res) => decryptLettersMetadata(res.data, masterKey))
|
||||
.then((decrypted) => {
|
||||
setLetters(
|
||||
decrypted.sort(
|
||||
(a, b) =>
|
||||
new Date(b.updated_at).getTime() -
|
||||
new Date(a.updated_at).getTime(),
|
||||
),
|
||||
);
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [masterKey]);
|
||||
|
||||
const drawerItems = useMemo(() => {
|
||||
return {
|
||||
drafts: letters.filter((l) => l.status === "DRAFT"),
|
||||
kept: letters.filter((l) => l.type === "KEPT" && l.status === "SEALED"),
|
||||
vault: letters.filter((l) => l.type === "VAULT" && l.status === "SEALED"),
|
||||
sent: letters.filter((l) => l.type === "SENT" && l.status === "SEALED"),
|
||||
};
|
||||
}, [letters]);
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
// to fetch the letters and decryypt the metadata on load
|
||||
useEffect(() => {
|
||||
if (!masterKey) {
|
||||
setIsAuthRequired(true);
|
||||
return;
|
||||
}
|
||||
setIsAuthRequired(false);
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
api
|
||||
.get(endpoints.LETTERS)
|
||||
.then((res) => decryptLettersMetadata(res.data, masterKey))
|
||||
.then((decrypted) => {
|
||||
setLetters(
|
||||
decrypted.sort(
|
||||
(a, b) =>
|
||||
new Date(b.updated_at).getTime() -
|
||||
new Date(a.updated_at).getTime(),
|
||||
),
|
||||
);
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [masterKey]);
|
||||
|
||||
const drawerItems = useMemo(() => {
|
||||
return {
|
||||
...drawerItems,
|
||||
loading,
|
||||
isAuthRequired,
|
||||
drafts: letters.filter((l) => l.status === "DRAFT"),
|
||||
kept: letters.filter((l) => l.type === "KEPT" && l.status === "SEALED"),
|
||||
vault: letters.filter((l) => l.type === "VAULT" && l.status === "SEALED"),
|
||||
sent: letters.filter((l) => l.type === "SENT" && l.status === "SEALED"),
|
||||
};
|
||||
}, [letters]);
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
...drawerItems,
|
||||
loading,
|
||||
isAuthRequired,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,99 +7,99 @@ import { endpoints, replacePathParams } from "../config/endpoints";
|
||||
import { ROUTES } from "../config/routes";
|
||||
|
||||
export default function Activate() {
|
||||
const { uidb64, token } = useParams();
|
||||
const [status, setStatus] = useState<"loading" | "success" | "error">(
|
||||
"loading",
|
||||
);
|
||||
const hasCalled = useRef(false);
|
||||
const navigate = useNavigate();
|
||||
const { uidb64, token } = useParams();
|
||||
const [status, setStatus] = useState<"loading" | "success" | "error">(
|
||||
"loading",
|
||||
);
|
||||
const hasCalled = useRef(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (!(uidb64 && token) || hasCalled.current) return;
|
||||
hasCalled.current = true;
|
||||
useEffect(() => {
|
||||
if (!(uidb64 && token) || hasCalled.current) return;
|
||||
hasCalled.current = true;
|
||||
|
||||
const activateAccount = async () => {
|
||||
try {
|
||||
const url = replacePathParams(endpoints.ACTIVATE, {
|
||||
uidb64,
|
||||
token,
|
||||
});
|
||||
await publicApi.get(url);
|
||||
setStatus("success");
|
||||
} catch {
|
||||
setStatus("error");
|
||||
}
|
||||
};
|
||||
const activateAccount = async () => {
|
||||
try {
|
||||
const url = replacePathParams(endpoints.ACTIVATE, {
|
||||
uidb64,
|
||||
token,
|
||||
});
|
||||
await publicApi.get(url);
|
||||
setStatus("success");
|
||||
} catch {
|
||||
setStatus("error");
|
||||
}
|
||||
};
|
||||
|
||||
activateAccount();
|
||||
}, [uidb64, token]);
|
||||
activateAccount();
|
||||
}, [uidb64, token]);
|
||||
|
||||
return (
|
||||
<div className="glass-card w-full max-w-sm p-8 text-center fade-zoom">
|
||||
{status === "loading" && (
|
||||
<div className="flex flex-col items-center gap-4 py-8">
|
||||
<span className="loading loading-spinner loading-lg text-primary" />
|
||||
<p className="text-sm opacity-70">Activating your account...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === "success" && (
|
||||
<div className="flex flex-col items-center gap-6 duration-500">
|
||||
<div className="bg-success/10 p-4 rounded-full">
|
||||
<CheckCircleIcon
|
||||
size={64}
|
||||
weight="duotone"
|
||||
className="text-success"
|
||||
/>
|
||||
</div>
|
||||
<h2
|
||||
data-testid="activation-success-header"
|
||||
className="font-display text-xl text-success"
|
||||
>
|
||||
You're in.
|
||||
</h2>
|
||||
<p className="opacity-70 leading-relaxed">
|
||||
Welcome to <Logo scale={1} />
|
||||
<br />
|
||||
Just one more step and you can start writing timeless letters.
|
||||
</p>
|
||||
<div className="divider opacity-10 my-0"></div>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="start-writing-btn"
|
||||
className="btn btn-primary w-full shadow-lg"
|
||||
onClick={() =>
|
||||
navigate(ROUTES.LOGIN, {
|
||||
state: { firstTime: true },
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
>
|
||||
I'm ready
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === "error" && (
|
||||
<div className="flex flex-col items-center gap-6 animate-in fade-in zoom-in duration-500">
|
||||
<div className="bg-error/10 p-4 rounded-full">
|
||||
<XCircleIcon size={64} weight="duotone" className="text-error" />
|
||||
</div>
|
||||
<h2 className="font-display text-xl text-error">Activation Failed</h2>
|
||||
<p className="opacity-70 leading-relaxed">
|
||||
The link might be expired or already used. Please try registering
|
||||
again.
|
||||
</p>
|
||||
<div className="divider opacity-10 my-0"></div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost w-full"
|
||||
onClick={() => navigate(ROUTES.ONBOARD)}
|
||||
>
|
||||
Register Again
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
return (
|
||||
<div className="glass-card w-full max-w-sm p-8 text-center fade-zoom">
|
||||
{status === "loading" && (
|
||||
<div className="flex flex-col items-center gap-4 py-8">
|
||||
<span className="loading loading-spinner loading-lg text-primary" />
|
||||
<p className="text-sm opacity-70">Activating your account...</p>
|
||||
</div>
|
||||
);
|
||||
)}
|
||||
|
||||
{status === "success" && (
|
||||
<div className="flex flex-col items-center gap-6 duration-500">
|
||||
<div className="bg-success/10 p-4 rounded-full">
|
||||
<CheckCircleIcon
|
||||
size={64}
|
||||
weight="duotone"
|
||||
className="text-success"
|
||||
/>
|
||||
</div>
|
||||
<h2
|
||||
data-testid="activation-success-header"
|
||||
className="font-display text-xl text-success"
|
||||
>
|
||||
You're in.
|
||||
</h2>
|
||||
<p className="opacity-70 leading-relaxed">
|
||||
Welcome to <Logo scale={1} />
|
||||
<br />
|
||||
Just one more step and you can start writing timeless letters.
|
||||
</p>
|
||||
<div className="divider opacity-10 my-0"></div>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="start-writing-btn"
|
||||
className="btn btn-primary w-full shadow-lg"
|
||||
onClick={() =>
|
||||
navigate(ROUTES.LOGIN, {
|
||||
state: { firstTime: true },
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
>
|
||||
I'm ready
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === "error" && (
|
||||
<div className="flex flex-col items-center gap-6 animate-in fade-in zoom-in duration-500">
|
||||
<div className="bg-error/10 p-4 rounded-full">
|
||||
<XCircleIcon size={64} weight="duotone" className="text-error" />
|
||||
</div>
|
||||
<h2 className="font-display text-xl text-error">Activation Failed</h2>
|
||||
<p className="opacity-70 leading-relaxed">
|
||||
The link might be expired or already used. Please try registering
|
||||
again.
|
||||
</p>
|
||||
<div className="divider opacity-10 my-0"></div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost w-full"
|
||||
onClick={() => navigate(ROUTES.ONBOARD)}
|
||||
>
|
||||
Register Again
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+465
-461
@@ -1,27 +1,27 @@
|
||||
import {
|
||||
ClockIcon,
|
||||
DownloadSimpleIcon,
|
||||
SpinnerGapIcon,
|
||||
XIcon,
|
||||
ClockIcon,
|
||||
DownloadSimpleIcon,
|
||||
SpinnerGapIcon,
|
||||
XIcon,
|
||||
} from "@phosphor-icons/react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
type NavigateFunction,
|
||||
useNavigate,
|
||||
useParams,
|
||||
type NavigateFunction,
|
||||
useNavigate,
|
||||
useParams,
|
||||
} from "react-router-dom";
|
||||
import { api } from "../api/apiClient";
|
||||
import type { LetterResponseData } from "../api/response";
|
||||
import {
|
||||
type CanvasStyle,
|
||||
type CanvasTools,
|
||||
ComposeCanvas,
|
||||
type CanvasStyle,
|
||||
type CanvasTools,
|
||||
ComposeCanvas,
|
||||
} from "../components/editor/ComposeCanvas";
|
||||
import { PostSealModal } from "../components/editor/PostSealModal";
|
||||
import {
|
||||
LetterHead,
|
||||
ToolBar,
|
||||
VaultConfirmModal,
|
||||
LetterHead,
|
||||
ToolBar,
|
||||
VaultConfirmModal,
|
||||
} from "../components/editor/ToolBar";
|
||||
import DateDisplay from "../components/ui/DateDisplay";
|
||||
import { LogModal } from "../components/ui/LogModal";
|
||||
@@ -42,482 +42,486 @@ const ERROR_VISIBLE_MS = 2400;
|
||||
const STOP_SAVE_DATE_PULSE_AFTER_MS = 10000;
|
||||
|
||||
const toPlaceholderList = [
|
||||
"Someone dear...",
|
||||
"Somewhere near...",
|
||||
"Something to bear...",
|
||||
"Someone dear...",
|
||||
"Somewhere near...",
|
||||
"Something to bear...",
|
||||
];
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||
export default function Editor() {
|
||||
const navigate = useNavigate();
|
||||
const navigateRef = useRef<NavigateFunction>(navigate);
|
||||
navigateRef.current = navigate;
|
||||
const navigate = useNavigate();
|
||||
const navigateRef = useRef<NavigateFunction>(navigate);
|
||||
navigateRef.current = navigate;
|
||||
|
||||
const { public_id } = useParams();
|
||||
const letterIdRef = useRef<string>(public_id ?? "");
|
||||
const justSavedRef = useRef<boolean>(false);
|
||||
const { public_id } = useParams();
|
||||
const letterIdRef = useRef<string>(public_id ?? "");
|
||||
const justSavedRef = useRef<boolean>(false);
|
||||
|
||||
const [decryptionStatus, setDecryptionStatus] = useState<{
|
||||
status: "SUCCESS" | "WARN" | "ERROR" | "RESET";
|
||||
message: string;
|
||||
log: string;
|
||||
}>({ status: "RESET", message: "", log: "" });
|
||||
const [decryptionStatus, setDecryptionStatus] = useState<{
|
||||
status: "SUCCESS" | "WARN" | "ERROR" | "RESET";
|
||||
message: string;
|
||||
log: string;
|
||||
}>({ status: "RESET", message: "", log: "" });
|
||||
|
||||
const [isInitialLoading, setIsInitialLoading] = useState(false);
|
||||
const [sealedTargetId, setSealedTargetId] = useState<string | null>(null);
|
||||
const [lastSaved, setLastSaved] = useState<string | null>(null);
|
||||
const [status, setLetterStatus] = useState<"DRAFT" | "SEALED" | "VAULT">(
|
||||
"DRAFT",
|
||||
);
|
||||
const [isSaveDatePulsing, setIsSaveDatePulsing] = useState(false);
|
||||
const [lastSavedPulseTick, setLastSavedPulseTick] = useState(0);
|
||||
const [sealBtnClicked, setSealBtnClicked] = useState<boolean>(false);
|
||||
const [isInitialLoading, setIsInitialLoading] = useState(false);
|
||||
const [sealedTargetId, setSealedTargetId] = useState<string | null>(null);
|
||||
const [lastSaved, setLastSaved] = useState<string | null>(null);
|
||||
const [status, setLetterStatus] = useState<"DRAFT" | "SEALED" | "VAULT">(
|
||||
"DRAFT",
|
||||
);
|
||||
const [isSaveDatePulsing, setIsSaveDatePulsing] = useState(false);
|
||||
const [lastSavedPulseTick, setLastSavedPulseTick] = useState(0);
|
||||
const [sealBtnClicked, setSealBtnClicked] = useState<boolean>(false);
|
||||
|
||||
const [saveOverlay, setSaveOverlay] = useState<SaveOverlay>("IDLE");
|
||||
const [logStatus, setLogStatus] = useState<{
|
||||
status: "WARN" | "ERROR" | "RESET";
|
||||
message: string;
|
||||
}>({
|
||||
status: "RESET",
|
||||
message: "",
|
||||
const [saveOverlay, setSaveOverlay] = useState<SaveOverlay>("IDLE");
|
||||
const [logStatus, setLogStatus] = useState<{
|
||||
status: "WARN" | "ERROR" | "RESET";
|
||||
message: string;
|
||||
}>({
|
||||
status: "RESET",
|
||||
message: "",
|
||||
});
|
||||
const [showSaveOverlay, setShowSaveOverlay] = useState(false);
|
||||
const [confirmModal, setConfirmModal] = useState<"VAULT" | "SEAL" | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const [recipient, setRecipient] = useState("");
|
||||
const [unlockDate, setUnlockDate] = useState<Date | null>(null);
|
||||
const [placeholderIndex, setPlaceholderIndex] = useState(0);
|
||||
const [canvasFontStyle, setCanvasFontStyle] = useState<CanvasStyle>({
|
||||
fontColor: "",
|
||||
fontFamily: "",
|
||||
});
|
||||
|
||||
const { masterKey } = useKeyStore();
|
||||
|
||||
const canvasRef = useRef<CanvasTools>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// to continuously rotate placeholder text of the recipient input
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setPlaceholderIndex((prev) => (prev + 1) % toPlaceholderList.length);
|
||||
}, 4000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// to load existing letter when public_id param and masterKey is available
|
||||
// NOTE: this has to trigger just once after each save
|
||||
useEffect(() => {
|
||||
if (!(public_id && masterKey)) return;
|
||||
if (justSavedRef.current) {
|
||||
justSavedRef.current = false;
|
||||
return;
|
||||
}
|
||||
const decryptAndLoadLetter = async (
|
||||
letterData: LetterResponseData,
|
||||
masterKey: CryptoKey,
|
||||
) => {
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
const metadata = await cryptoUtils.decryptMetadata(
|
||||
{
|
||||
encrypted_content: letterData.encrypted_metadata,
|
||||
encrypted_dek: letterData.encrypted_dek,
|
||||
},
|
||||
masterKey,
|
||||
);
|
||||
setRecipient(metadata.recipient || "");
|
||||
|
||||
const decryptedJsonStr = await cryptoUtils.decryptLetter(
|
||||
{
|
||||
encrypted_content: letterData.encrypted_content,
|
||||
encrypted_dek: letterData.encrypted_dek,
|
||||
},
|
||||
masterKey,
|
||||
);
|
||||
const canvasData = JSON.parse(decryptedJsonStr);
|
||||
|
||||
const { errors, isPartialFailure, canvasDataWithDecryptedImages } =
|
||||
await decryptCanvasImages(
|
||||
canvasData,
|
||||
letterData.images ?? [],
|
||||
letterData.encrypted_dek,
|
||||
masterKey,
|
||||
cryptoUtils,
|
||||
true,
|
||||
);
|
||||
|
||||
if (isPartialFailure) {
|
||||
setDecryptionStatus({
|
||||
status: "WARN",
|
||||
message: "Failed to decrypt some elements. Please check the render.",
|
||||
log: errors.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
if (canvasRef.current) {
|
||||
await canvasRef.current.loadData(canvasDataWithDecryptedImages);
|
||||
}
|
||||
};
|
||||
|
||||
const loadExistingLetter = async () => {
|
||||
setIsInitialLoading(true);
|
||||
try {
|
||||
const res = await api.get(`${endpoints.LETTERS}${public_id}/`);
|
||||
const letterData = res.data;
|
||||
|
||||
setLastSaved(formatRelativeDate(new Date(letterData.updated_at)));
|
||||
setLetterStatus(letterData.status);
|
||||
|
||||
if (letterData.status === "SEALED") {
|
||||
navigateRef.current(PATHS.read(public_id), { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (letterData.encrypted_dek && masterKey) {
|
||||
await decryptAndLoadLetter(letterData, masterKey);
|
||||
}
|
||||
} catch (err) {
|
||||
setDecryptionStatus({
|
||||
status: "ERROR",
|
||||
message: "Failed to decrypt letter. Please try again later.",
|
||||
log: err instanceof Error ? err.message : "Unknown error",
|
||||
});
|
||||
} finally {
|
||||
setIsInitialLoading(false);
|
||||
}
|
||||
};
|
||||
loadExistingLetter().then((_) => {
|
||||
if (canvasRef.current) {
|
||||
setCanvasFontStyle(canvasRef.current.getStyle());
|
||||
}
|
||||
});
|
||||
const [showSaveOverlay, setShowSaveOverlay] = useState(false);
|
||||
const [confirmModal, setConfirmModal] = useState<"VAULT" | "SEAL" | null>(
|
||||
null,
|
||||
}, [public_id, masterKey]);
|
||||
|
||||
// to trigger short pulse animation for Last Saved AT element
|
||||
useEffect(() => {
|
||||
if (lastSavedPulseTick === 0) return;
|
||||
setIsSaveDatePulsing(true);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
setIsSaveDatePulsing(false);
|
||||
}, STOP_SAVE_DATE_PULSE_AFTER_MS);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [lastSavedPulseTick]);
|
||||
|
||||
// to fade in and fade out the save status overlay after each save operation
|
||||
// Note: otherwise the fade efect is abrupt due to component's immediate unmount
|
||||
useEffect(() => {
|
||||
if (saveOverlay === "IDLE" || saveOverlay === "SAVING") return;
|
||||
const visibleTimer = setTimeout(
|
||||
() => {
|
||||
setShowSaveOverlay(false);
|
||||
},
|
||||
saveOverlay === "SAVED" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS,
|
||||
);
|
||||
const unmountTimer = setTimeout(
|
||||
() => {
|
||||
setSaveOverlay("IDLE");
|
||||
},
|
||||
(saveOverlay === "SAVED" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS) +
|
||||
OVERLAY_FADE_MS,
|
||||
);
|
||||
|
||||
const [recipient, setRecipient] = useState("");
|
||||
const [unlockDate, setUnlockDate] = useState<Date | null>(null);
|
||||
const [placeholderIndex, setPlaceholderIndex] = useState(0);
|
||||
const [canvasFontStyle, setCanvasFontStyle] = useState<CanvasStyle>({
|
||||
fontColor: "",
|
||||
fontFamily: "",
|
||||
return () => {
|
||||
clearTimeout(visibleTimer);
|
||||
clearTimeout(unmountTimer);
|
||||
};
|
||||
}, [saveOverlay]);
|
||||
|
||||
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file && file.size < MAX_FILE_SIZE) {
|
||||
const url = URL.createObjectURL(file);
|
||||
canvasRef.current?.addImage(url, file);
|
||||
} else {
|
||||
setLogStatus({
|
||||
status: "WARN",
|
||||
message: "Please upload images with size less than 10MB.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getRequestData = async (
|
||||
targetId: string,
|
||||
status: string,
|
||||
vaultDate?: Date,
|
||||
): Promise<FormData> => {
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
await cryptoUtils.initialize();
|
||||
|
||||
const canvasData = (await canvasRef.current?.getData()) || { objects: [] };
|
||||
const canvasImages = canvasRef.current?.getImages() || [];
|
||||
|
||||
const { encryptedImageFiles, encryptedCanvasData } =
|
||||
await encryptCanvasImages(
|
||||
canvasData,
|
||||
canvasImages,
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterkey can never be null here
|
||||
masterKey!,
|
||||
cryptoUtils,
|
||||
);
|
||||
|
||||
const encrypted_letter = await cryptoUtils.encryptLetter(
|
||||
JSON.stringify(encryptedCanvasData),
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterkey can never be null here
|
||||
masterKey!,
|
||||
);
|
||||
|
||||
const encrypted_metadata = await cryptoUtils.encryptMetadata(
|
||||
{ recipient, tags: [] },
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterkey can never be null here
|
||||
masterKey!,
|
||||
);
|
||||
|
||||
const formData = new FormData();
|
||||
if (status === "VAULT") {
|
||||
const finalDate = vaultDate || unlockDate;
|
||||
formData.append("type", "VAULT");
|
||||
if (finalDate) formData.append("unlock_at", finalDate.toISOString());
|
||||
formData.append("status", "SEALED");
|
||||
} else {
|
||||
formData.append("type", "KEPT");
|
||||
formData.append("status", status);
|
||||
}
|
||||
|
||||
formData.append("public_id", targetId);
|
||||
formData.append("encrypted_content", encrypted_letter.encrypted_content);
|
||||
formData.append("encrypted_dek", encrypted_letter.encrypted_dek);
|
||||
formData.append("encrypted_metadata", encrypted_metadata.encrypted_content);
|
||||
|
||||
encryptedImageFiles.forEach((blob, filename) => {
|
||||
formData.append("image_files", blob, filename);
|
||||
});
|
||||
|
||||
const { masterKey } = useKeyStore();
|
||||
return formData;
|
||||
};
|
||||
|
||||
const canvasRef = useRef<CanvasTools>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const handleSave = async (
|
||||
status: "SEALED" | "DRAFT" | "VAULT",
|
||||
vaultDate?: Date,
|
||||
): Promise<void> => {
|
||||
setSealBtnClicked(false);
|
||||
// use the letter's id if an existing letter or create a new id
|
||||
const targetId = public_id || letterIdRef.current || crypto.randomUUID();
|
||||
|
||||
// to continuously rotate placeholder text of the recipient input
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setPlaceholderIndex((prev) => (prev + 1) % toPlaceholderList.length);
|
||||
}, 4000);
|
||||
if (saveOverlay === "SAVING" || !masterKey) return;
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
setSaveOverlay("SAVING");
|
||||
setShowSaveOverlay(true);
|
||||
|
||||
// to load existing letter when public_id param and masterKey is available
|
||||
// NOTE: this has to trigger just once after each save
|
||||
useEffect(() => {
|
||||
if (!(public_id && masterKey)) return;
|
||||
if (justSavedRef.current) {
|
||||
justSavedRef.current = false;
|
||||
return;
|
||||
}
|
||||
const decryptAndLoadLetter = async (
|
||||
letterData: LetterResponseData,
|
||||
masterKey: CryptoKey,
|
||||
) => {
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
const metadata = await cryptoUtils.decryptMetadata(
|
||||
{
|
||||
encrypted_content: letterData.encrypted_metadata,
|
||||
encrypted_dek: letterData.encrypted_dek,
|
||||
},
|
||||
masterKey,
|
||||
);
|
||||
setRecipient(metadata.recipient || "");
|
||||
try {
|
||||
const formData = await getRequestData(targetId, status, vaultDate);
|
||||
await api.put(`${endpoints.LETTERS}${targetId}/`, formData);
|
||||
|
||||
const decryptedJsonStr = await cryptoUtils.decryptLetter(
|
||||
{
|
||||
encrypted_content: letterData.encrypted_content,
|
||||
encrypted_dek: letterData.encrypted_dek,
|
||||
},
|
||||
masterKey,
|
||||
);
|
||||
const canvasData = JSON.parse(decryptedJsonStr);
|
||||
justSavedRef.current = true;
|
||||
if (!public_id) {
|
||||
letterIdRef.current = targetId;
|
||||
navigate(PATHS.write(targetId), { replace: true });
|
||||
}
|
||||
|
||||
const { errors, isPartialFailure, canvasDataWithDecryptedImages } =
|
||||
await decryptCanvasImages(
|
||||
canvasData,
|
||||
letterData.images ?? [],
|
||||
letterData.encrypted_dek,
|
||||
masterKey,
|
||||
cryptoUtils,
|
||||
true,
|
||||
);
|
||||
setLastSaved(formatRelativeDate(new Date()));
|
||||
setLetterStatus(status);
|
||||
setLastSavedPulseTick((prev) => prev + 1);
|
||||
|
||||
if (isPartialFailure) {
|
||||
setDecryptionStatus({
|
||||
status: "WARN",
|
||||
message: "Failed to decrypt some elements. Please check the render.",
|
||||
log: errors.toString(),
|
||||
});
|
||||
}
|
||||
if (status === "SEALED" || status === "VAULT") {
|
||||
setSealedTargetId(targetId);
|
||||
}
|
||||
setSaveOverlay("SAVED");
|
||||
setShowSaveOverlay(true);
|
||||
} catch {
|
||||
setSaveOverlay("ERROR");
|
||||
setShowSaveOverlay(true);
|
||||
}
|
||||
};
|
||||
|
||||
if (canvasRef.current) {
|
||||
await canvasRef.current.loadData(canvasDataWithDecryptedImages);
|
||||
}
|
||||
};
|
||||
|
||||
const loadExistingLetter = async () => {
|
||||
setIsInitialLoading(true);
|
||||
try {
|
||||
const res = await api.get(`${endpoints.LETTERS}${public_id}/`);
|
||||
const letterData = res.data;
|
||||
|
||||
setLastSaved(formatRelativeDate(new Date(letterData.updated_at)));
|
||||
setLetterStatus(letterData.status);
|
||||
|
||||
if (letterData.status === "SEALED") {
|
||||
navigateRef.current(PATHS.read(public_id), { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (letterData.encrypted_dek && masterKey) {
|
||||
await decryptAndLoadLetter(letterData, masterKey);
|
||||
}
|
||||
} catch (err) {
|
||||
setDecryptionStatus({
|
||||
status: "ERROR",
|
||||
message: "Failed to decrypt letter. Please try again later.",
|
||||
log: err instanceof Error ? err.message : "Unknown error",
|
||||
});
|
||||
} finally {
|
||||
setIsInitialLoading(false);
|
||||
}
|
||||
};
|
||||
loadExistingLetter().then((_) => {
|
||||
if (canvasRef.current) {
|
||||
setCanvasFontStyle(canvasRef.current.getStyle());
|
||||
}
|
||||
});
|
||||
}, [public_id, masterKey]);
|
||||
|
||||
// to trigger short pulse animation for Last Saved AT element
|
||||
useEffect(() => {
|
||||
if (lastSavedPulseTick === 0) return;
|
||||
setIsSaveDatePulsing(true);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
setIsSaveDatePulsing(false);
|
||||
}, STOP_SAVE_DATE_PULSE_AFTER_MS);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [lastSavedPulseTick]);
|
||||
|
||||
// to fade in and fade out the save status overlay after each save operation
|
||||
// Note: otherwise the fade efect is abrupt due to component's immediate unmount
|
||||
useEffect(() => {
|
||||
if (saveOverlay === "IDLE" || saveOverlay === "SAVING") return;
|
||||
const visibleTimer = setTimeout(
|
||||
() => {
|
||||
setShowSaveOverlay(false);
|
||||
},
|
||||
saveOverlay === "SAVED" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS,
|
||||
);
|
||||
const unmountTimer = setTimeout(
|
||||
() => {
|
||||
setSaveOverlay("IDLE");
|
||||
},
|
||||
(saveOverlay === "SAVED" ? SAVED_VISIBLE_MS : ERROR_VISIBLE_MS) +
|
||||
OVERLAY_FADE_MS,
|
||||
);
|
||||
|
||||
return () => {
|
||||
clearTimeout(visibleTimer);
|
||||
clearTimeout(unmountTimer);
|
||||
};
|
||||
}, [saveOverlay]);
|
||||
|
||||
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file && file.size < MAX_FILE_SIZE) {
|
||||
const url = URL.createObjectURL(file);
|
||||
canvasRef.current?.addImage(url, file);
|
||||
} else {
|
||||
setLogStatus({
|
||||
status: "WARN",
|
||||
message: "Please upload images with size less than 10MB.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getRequestData = async (
|
||||
targetId: string,
|
||||
status: string,
|
||||
vaultDate?: Date,
|
||||
): Promise<FormData> => {
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
await cryptoUtils.initialize();
|
||||
|
||||
const canvasData = (await canvasRef.current?.getData()) || { objects: [] };
|
||||
const canvasImages = canvasRef.current?.getImages() || [];
|
||||
|
||||
const { encryptedImageFiles, encryptedCanvasData } =
|
||||
await encryptCanvasImages(
|
||||
canvasData,
|
||||
canvasImages,
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterkey can never be null here
|
||||
masterKey!,
|
||||
cryptoUtils,
|
||||
);
|
||||
|
||||
const encrypted_letter = await cryptoUtils.encryptLetter(
|
||||
JSON.stringify(encryptedCanvasData),
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterkey can never be null here
|
||||
masterKey!,
|
||||
);
|
||||
|
||||
const encrypted_metadata = await cryptoUtils.encryptMetadata(
|
||||
{ recipient, tags: [] },
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterkey can never be null here
|
||||
masterKey!,
|
||||
);
|
||||
|
||||
const formData = new FormData();
|
||||
if (status === "VAULT") {
|
||||
const finalDate = vaultDate || unlockDate;
|
||||
formData.append("type", "VAULT");
|
||||
if (finalDate) formData.append("unlock_at", finalDate.toISOString());
|
||||
formData.append("status", "SEALED");
|
||||
} else {
|
||||
formData.append("type", "KEPT");
|
||||
formData.append("status", status);
|
||||
}
|
||||
|
||||
formData.append("public_id", targetId);
|
||||
formData.append("encrypted_content", encrypted_letter.encrypted_content);
|
||||
formData.append("encrypted_dek", encrypted_letter.encrypted_dek);
|
||||
formData.append("encrypted_metadata", encrypted_metadata.encrypted_content);
|
||||
|
||||
encryptedImageFiles.forEach((blob, filename) => {
|
||||
formData.append("image_files", blob, filename);
|
||||
});
|
||||
|
||||
return formData;
|
||||
};
|
||||
|
||||
const handleSave = async (
|
||||
status: "SEALED" | "DRAFT" | "VAULT",
|
||||
vaultDate?: Date,
|
||||
): Promise<void> => {
|
||||
setSealBtnClicked(false);
|
||||
// use the letter's id if an existing letter or create a new id
|
||||
const targetId = public_id || letterIdRef.current || crypto.randomUUID();
|
||||
|
||||
if (saveOverlay === "SAVING" || !masterKey) return;
|
||||
|
||||
setSaveOverlay("SAVING");
|
||||
setShowSaveOverlay(true);
|
||||
|
||||
try {
|
||||
const formData = await getRequestData(targetId, status, vaultDate);
|
||||
await api.put(`${endpoints.LETTERS}${targetId}/`, formData);
|
||||
|
||||
justSavedRef.current = true;
|
||||
if (!public_id) {
|
||||
letterIdRef.current = targetId;
|
||||
navigate(PATHS.write(targetId), { replace: true });
|
||||
}
|
||||
|
||||
setLastSaved(formatRelativeDate(new Date()));
|
||||
setLetterStatus(status);
|
||||
setLastSavedPulseTick((prev) => prev + 1);
|
||||
|
||||
if (status === "SEALED" || status === "VAULT") {
|
||||
setSealedTargetId(targetId);
|
||||
}
|
||||
setSaveOverlay("SAVED");
|
||||
setShowSaveOverlay(true);
|
||||
} catch {
|
||||
setSaveOverlay("ERROR");
|
||||
setShowSaveOverlay(true);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Navbar
|
||||
child={
|
||||
<div
|
||||
className={`flex items-center gap-2 ${isSaveDatePulsing ? "animate-pulse" : ""
|
||||
}`}
|
||||
>
|
||||
<div className="text-xxs text-neutral-content/30 flex-col justify-end leading-none text-right">
|
||||
<span className="uppercase tracking-widest font-bold">
|
||||
Last Save
|
||||
</span>
|
||||
<br />
|
||||
<span className="italic">{lastSaved}</span>
|
||||
</div>
|
||||
<ClockIcon
|
||||
size={16}
|
||||
weight="bold"
|
||||
className="text-neutral-content/30"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Navbar
|
||||
child={
|
||||
<div
|
||||
className={`flex items-center gap-2 ${
|
||||
isSaveDatePulsing ? "animate-pulse" : ""
|
||||
}`}
|
||||
>
|
||||
<div className="text-xxs text-neutral-content/30 flex-col justify-end leading-none text-right">
|
||||
<span className="uppercase tracking-widest font-bold">
|
||||
Last Save
|
||||
</span>
|
||||
<br />
|
||||
<span className="italic">{lastSaved}</span>
|
||||
</div>
|
||||
<ClockIcon
|
||||
size={16}
|
||||
weight="bold"
|
||||
className="text-neutral-content/30"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<section className="flex-1 overflow-y-auto scrollbar-hide px-2 pt-32 pb-12 bg-base-300 relative">
|
||||
<LogModal
|
||||
status={decryptionStatus.status}
|
||||
message={decryptionStatus.message}
|
||||
log={decryptionStatus.log}
|
||||
onClose={() =>
|
||||
setDecryptionStatus({ status: "RESET", message: "", log: "" })
|
||||
}
|
||||
isOpen={decryptionStatus.status !== "RESET"}
|
||||
<section className="flex-1 overflow-y-auto scrollbar-hide px-2 pt-32 pb-12 bg-base-300 relative">
|
||||
<LogModal
|
||||
status={decryptionStatus.status}
|
||||
message={decryptionStatus.message}
|
||||
log={decryptionStatus.log}
|
||||
onClose={() =>
|
||||
setDecryptionStatus({ status: "RESET", message: "", log: "" })
|
||||
}
|
||||
isOpen={decryptionStatus.status !== "RESET"}
|
||||
/>
|
||||
|
||||
{isInitialLoading && (
|
||||
<div className="absolute inset-0 z-50 flex items-center justify-center bg-base-300/80 backdrop-blur-sm">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<SpinnerGapIcon
|
||||
size={48}
|
||||
weight="bold"
|
||||
className="animate-spin text-primary"
|
||||
/>
|
||||
<p
|
||||
data-testid="opening-draft-overlay"
|
||||
className="text-xxs uppercase tracking-widester font-bold text-base-content/40"
|
||||
>
|
||||
Opening your draft...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{saveOverlay !== "IDLE" && (
|
||||
<Modal isOpen={showSaveOverlay}>
|
||||
{saveOverlay === "SAVING" && (
|
||||
<div
|
||||
role="alert"
|
||||
className={`alert text-center alert-neutral shadow-lg transition-all ease-in-out duration-2000 ${
|
||||
showSaveOverlay
|
||||
? "opacity-100 scale-100 translate-y-0"
|
||||
: "opacity-0 scale-95 translate-y-1"
|
||||
}`}
|
||||
>
|
||||
<SpinnerGapIcon
|
||||
size={18}
|
||||
weight="bold"
|
||||
className="animate-spin"
|
||||
/>
|
||||
<span className="font-bold">Securing your letter...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isInitialLoading && (
|
||||
<div className="absolute inset-0 z-50 flex items-center justify-center bg-base-300/80 backdrop-blur-sm">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<SpinnerGapIcon
|
||||
size={48}
|
||||
weight="bold"
|
||||
className="animate-spin text-primary"
|
||||
/>
|
||||
<p
|
||||
data-testid="opening-draft-overlay"
|
||||
className="text-xxs uppercase tracking-widester font-bold text-base-content/40"
|
||||
>
|
||||
Opening your draft...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{saveOverlay === "SAVED" && (
|
||||
<div
|
||||
role="alert"
|
||||
data-testid="save-success-toast"
|
||||
className={`alert alert-success shadow-lg transition-all ease-in-out duration-2000 ${
|
||||
showSaveOverlay
|
||||
? "opacity-100 scale-100 translate-y-0"
|
||||
: "opacity-0 scale-95 translate-y-1"
|
||||
}`}
|
||||
>
|
||||
<DownloadSimpleIcon size={18} weight="bold" />
|
||||
<span className="font-bold">Your letter is saved!</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{saveOverlay !== "IDLE" && (
|
||||
<Modal isOpen={showSaveOverlay}>
|
||||
{saveOverlay === "SAVING" && (
|
||||
<div
|
||||
role="alert"
|
||||
className={`alert text-center alert-neutral shadow-lg transition-all ease-in-out duration-2000 ${showSaveOverlay
|
||||
? "opacity-100 scale-100 translate-y-0"
|
||||
: "opacity-0 scale-95 translate-y-1"
|
||||
}`}
|
||||
>
|
||||
<SpinnerGapIcon
|
||||
size={18}
|
||||
weight="bold"
|
||||
className="animate-spin"
|
||||
/>
|
||||
<span className="font-bold">Securing your letter...</span>
|
||||
</div>
|
||||
)}
|
||||
{saveOverlay === "ERROR" && (
|
||||
<div
|
||||
role="alert"
|
||||
className={`alert alert-error shadow-lg transition-all duration-300 ${
|
||||
showSaveOverlay
|
||||
? "opacity-100 scale-100 translate-y-0"
|
||||
: "opacity-0 scale-95 translate-y-1"
|
||||
}`}
|
||||
>
|
||||
<XIcon size={18} weight="bold" />
|
||||
<span className="font-bold">Failed to save letter</span>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{saveOverlay === "SAVED" && (
|
||||
<div
|
||||
role="alert"
|
||||
data-testid="save-success-toast"
|
||||
className={`alert alert-success shadow-lg transition-all ease-in-out duration-2000 ${showSaveOverlay
|
||||
? "opacity-100 scale-100 translate-y-0"
|
||||
: "opacity-0 scale-95 translate-y-1"
|
||||
}`}
|
||||
>
|
||||
<DownloadSimpleIcon size={18} weight="bold" />
|
||||
<span className="font-bold">Your letter is saved!</span>
|
||||
</div>
|
||||
)}
|
||||
{confirmModal === "VAULT" && (
|
||||
<VaultConfirmModal
|
||||
onSave={handleSave}
|
||||
setConfirmModal={setConfirmModal}
|
||||
setUnlockDate={setUnlockDate}
|
||||
/>
|
||||
)}
|
||||
{sealedTargetId && (
|
||||
<PostSealModal
|
||||
sealedTargetId={sealedTargetId}
|
||||
navigate={navigate}
|
||||
type={status === "VAULT" ? "VAULT" : "KEPT"}
|
||||
/>
|
||||
)}
|
||||
|
||||
{saveOverlay === "ERROR" && (
|
||||
<div
|
||||
role="alert"
|
||||
className={`alert alert-error shadow-lg transition-all duration-300 ${showSaveOverlay
|
||||
? "opacity-100 scale-100 translate-y-0"
|
||||
: "opacity-0 scale-95 translate-y-1"
|
||||
}`}
|
||||
>
|
||||
<XIcon size={18} weight="bold" />
|
||||
<span className="font-bold">Failed to save letter</span>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
)}
|
||||
<div className="max-w-180 mx-auto px-1 md:px-0">
|
||||
<div className="flex justify-between items-end mb-16 border-b border-base-content/5 pb-8 px-0">
|
||||
<div className="flex flex-col gap-2 flex-1">
|
||||
<label
|
||||
htmlFor="recipient"
|
||||
className="text-xxs uppercase tracking-widester text-secondary-content font-bold"
|
||||
>
|
||||
Recipient
|
||||
</label>
|
||||
<input
|
||||
id="recipient"
|
||||
data-testid="recipient-input"
|
||||
type="text"
|
||||
placeholder={toPlaceholderList[placeholderIndex]}
|
||||
value={recipient}
|
||||
disabled={status !== "DRAFT"}
|
||||
onChange={(e) => setRecipient(e.target.value)}
|
||||
className="bg-transparent border-none outline-none text-2xl md:text-3xl lg:text-4xl font-serif text-base-content placeholder:text-base-content/10 w-full disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<DateDisplay />
|
||||
</div>
|
||||
|
||||
{confirmModal === "VAULT" && (
|
||||
<VaultConfirmModal
|
||||
onSave={handleSave}
|
||||
setConfirmModal={setConfirmModal}
|
||||
setUnlockDate={setUnlockDate}
|
||||
/>
|
||||
)}
|
||||
{sealedTargetId && (
|
||||
<PostSealModal
|
||||
sealedTargetId={sealedTargetId}
|
||||
navigate={navigate}
|
||||
type={status === "VAULT" ? "VAULT" : "KEPT"}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="max-w-180 mx-auto px-1 md:px-0">
|
||||
<div className="flex justify-between items-end mb-16 border-b border-base-content/5 pb-8 px-0">
|
||||
<div className="flex flex-col gap-2 flex-1">
|
||||
<label
|
||||
htmlFor="recipient"
|
||||
className="text-xxs uppercase tracking-widester text-secondary-content font-bold"
|
||||
>
|
||||
Recipient
|
||||
</label>
|
||||
<input
|
||||
id="recipient"
|
||||
data-testid="recipient-input"
|
||||
type="text"
|
||||
placeholder={toPlaceholderList[placeholderIndex]}
|
||||
value={recipient}
|
||||
disabled={status !== "DRAFT"}
|
||||
onChange={(e) => setRecipient(e.target.value)}
|
||||
className="bg-transparent border-none outline-none text-2xl md:text-3xl lg:text-4xl font-serif text-base-content placeholder:text-base-content/10 w-full disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<DateDisplay />
|
||||
</div>
|
||||
|
||||
{status === "DRAFT" ? (
|
||||
<ToolBar
|
||||
onAddImage={() => fileInputRef.current?.click()}
|
||||
sealBtnClicked={sealBtnClicked}
|
||||
setSealBtnClicked={setSealBtnClicked}
|
||||
onSave={handleSave}
|
||||
setConfirmModal={setConfirmModal}
|
||||
onFontChange={setCanvasFontStyle}
|
||||
latestFontStyle={canvasFontStyle}
|
||||
/>
|
||||
) : (
|
||||
<LetterHead />
|
||||
)}
|
||||
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={handleImageUpload}
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
<ComposeCanvas
|
||||
ref={canvasRef}
|
||||
readOnly={status !== "DRAFT"}
|
||||
style={canvasFontStyle}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
<LogModal
|
||||
status={logStatus.status}
|
||||
message={logStatus.message}
|
||||
log={""}
|
||||
onClose={() =>
|
||||
setLogStatus({
|
||||
status: "RESET",
|
||||
message: "",
|
||||
})
|
||||
}
|
||||
isOpen={logStatus.status !== "RESET"}
|
||||
{status === "DRAFT" ? (
|
||||
<ToolBar
|
||||
onAddImage={() => fileInputRef.current?.click()}
|
||||
sealBtnClicked={sealBtnClicked}
|
||||
setSealBtnClicked={setSealBtnClicked}
|
||||
onSave={handleSave}
|
||||
setConfirmModal={setConfirmModal}
|
||||
onFontChange={setCanvasFontStyle}
|
||||
latestFontStyle={canvasFontStyle}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
) : (
|
||||
<LetterHead />
|
||||
)}
|
||||
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={handleImageUpload}
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
<ComposeCanvas
|
||||
ref={canvasRef}
|
||||
readOnly={status !== "DRAFT"}
|
||||
style={canvasFontStyle}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
<LogModal
|
||||
status={logStatus.status}
|
||||
message={logStatus.message}
|
||||
log={""}
|
||||
onClose={() =>
|
||||
setLogStatus({
|
||||
status: "RESET",
|
||||
message: "",
|
||||
})
|
||||
}
|
||||
isOpen={logStatus.status !== "RESET"}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
+320
-319
@@ -2,17 +2,17 @@ import { FlameIcon, PaperPlaneTiltIcon } from "@phosphor-icons/react";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
type NavigateFunction,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
useParams,
|
||||
type NavigateFunction,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
useParams,
|
||||
} from "react-router-dom";
|
||||
import { api } from "../api/apiClient";
|
||||
import type { LetterImageData, LetterResponseData } from "../api/response";
|
||||
import {
|
||||
type CanvasJSON,
|
||||
type CanvasTools,
|
||||
ComposeCanvas,
|
||||
type CanvasJSON,
|
||||
type CanvasTools,
|
||||
ComposeCanvas,
|
||||
} from "../components/editor/ComposeCanvas";
|
||||
import Logo from "../components/Logo";
|
||||
import { BurnModal } from "../components/reader/BurnModal";
|
||||
@@ -26,342 +26,343 @@ import { useKeyStore } from "../store/useKeyStore";
|
||||
import { CryptoUtils } from "../utils/crypto";
|
||||
import { formatDate } from "../utils/dateFormat";
|
||||
import {
|
||||
decryptCanvasImages,
|
||||
decryptCanvasImagesWithSharingKey,
|
||||
decryptCanvasImages,
|
||||
decryptCanvasImagesWithSharingKey,
|
||||
} from "../utils/letterLogic";
|
||||
|
||||
interface LetterMetadata {
|
||||
recipient?: string;
|
||||
updated_at?: string;
|
||||
recipient?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
const WAIT_FOR_BURN_MS = 18000;
|
||||
export default function Reader() {
|
||||
const { public_id } = useParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const sharingKey = location.hash.replace("#", "");
|
||||
const { public_id } = useParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const sharingKey = location.hash.replace("#", "");
|
||||
|
||||
const navigateRef = useRef<NavigateFunction>(navigate);
|
||||
const canvasRef = useRef<CanvasTools>(null);
|
||||
const navigateRef = useRef<NavigateFunction>(navigate);
|
||||
const canvasRef = useRef<CanvasTools>(null);
|
||||
|
||||
const [isDecrypting, setIsDecrypting] = useState(true);
|
||||
const [revealState, setRevealState] = useState<
|
||||
"SEALED" | "REVEALED" | "BURNED" | "BURNING"
|
||||
>("SEALED");
|
||||
const [logTrace, setLogTrace] = useState<{
|
||||
type: "WARN" | "ERROR";
|
||||
message: string;
|
||||
log: string;
|
||||
} | null>(null);
|
||||
const [metadata, setMetadata] = useState<LetterMetadata | null>(null);
|
||||
const [decryptedCanvasData, setDecryptedCanvasData] =
|
||||
useState<CanvasJSON | null>(null);
|
||||
const [showBurnModal, setShowBurnModal] = useState(false);
|
||||
const [isBurning, setIsBurning] = useState(false);
|
||||
const [ignite, setIgnite] = useState(false);
|
||||
const [encryptedDek, setEncryptedDek] = useState<string | null>(null);
|
||||
const [shareLink, setShareLink] = useState<string | null>(null);
|
||||
const [isDecrypting, setIsDecrypting] = useState(true);
|
||||
const [revealState, setRevealState] = useState<
|
||||
"SEALED" | "REVEALED" | "BURNED" | "BURNING"
|
||||
>("SEALED");
|
||||
const [logTrace, setLogTrace] = useState<{
|
||||
type: "WARN" | "ERROR";
|
||||
message: string;
|
||||
log: string;
|
||||
} | null>(null);
|
||||
const [metadata, setMetadata] = useState<LetterMetadata | null>(null);
|
||||
const [decryptedCanvasData, setDecryptedCanvasData] =
|
||||
useState<CanvasJSON | null>(null);
|
||||
const [showBurnModal, setShowBurnModal] = useState(false);
|
||||
const [isBurning, setIsBurning] = useState(false);
|
||||
const [ignite, setIgnite] = useState(false);
|
||||
const [encryptedDek, setEncryptedDek] = useState<string | null>(null);
|
||||
const [shareLink, setShareLink] = useState<string | null>(null);
|
||||
|
||||
const { masterKey } = useKeyStore();
|
||||
const { masterKey } = useKeyStore();
|
||||
|
||||
const isAuthor = !!masterKey && !sharingKey;
|
||||
const isAuthor = !!masterKey && !sharingKey;
|
||||
|
||||
const handleShare = async () => {
|
||||
if (!(encryptedDek && masterKey && public_id)) return;
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
const key = await cryptoUtils.extractSharingKey(encryptedDek, masterKey);
|
||||
try {
|
||||
await api.patch(`${endpoints.LETTERS}${public_id}/`, { type: "SENT" });
|
||||
} catch {
|
||||
// shouldn't obstruct share if api operation fails (since it's client side share)
|
||||
} finally {
|
||||
setShareLink(`${window.location.origin}${PATHS.read(public_id)}#${key}`);
|
||||
}
|
||||
};
|
||||
|
||||
const burnLetter = async () => {
|
||||
if (!public_id || isBurning) return;
|
||||
setIsBurning(true);
|
||||
try {
|
||||
await api.patch(`${endpoints.LETTERS}${public_id}/`, {
|
||||
status: "BURNED",
|
||||
});
|
||||
} catch {
|
||||
// should not obstruct burn if api operation fails
|
||||
// WHY?: it disconnects the UX. if you want to burn the letter, you should be able to burn the letter
|
||||
// TODO: maybe say something like: "the wind is strong today, let's try again"? or maybe something less stupid :3
|
||||
} finally {
|
||||
setIsBurning(false);
|
||||
setShowBurnModal(false);
|
||||
setIgnite(true);
|
||||
setTimeout(() => {
|
||||
setRevealState("BURNED");
|
||||
}, WAIT_FOR_BURN_MS);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!(sharingKey || masterKey)) {
|
||||
navigateRef.current("/login", {
|
||||
state: { redirectUrl: `/read/${public_id}` },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const decryptImages = async (
|
||||
canvasData: CanvasJSON,
|
||||
images: LetterImageData[],
|
||||
encrypted_dek: string,
|
||||
cryptoUtils: CryptoUtils,
|
||||
) => {
|
||||
if (!images?.length) return;
|
||||
const isShared = !!sharingKey;
|
||||
try {
|
||||
if (isShared) {
|
||||
await decryptCanvasImagesWithSharingKey(
|
||||
canvasData,
|
||||
images,
|
||||
sharingKey,
|
||||
cryptoUtils,
|
||||
);
|
||||
} else {
|
||||
await decryptCanvasImages(
|
||||
canvasData,
|
||||
images,
|
||||
encrypted_dek,
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterKey is guaranteed to be non-null here as isDecryptionKeyAvailable is true
|
||||
masterKey!,
|
||||
cryptoUtils,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
setLogTrace({
|
||||
message:
|
||||
"Failed to decrypt elements. Images might not render in the letter as intended.",
|
||||
log: err instanceof Error ? err.message : "Unknown error",
|
||||
type: "WARN",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const decryptLetterData = async (
|
||||
data: LetterResponseData,
|
||||
cryptoUtils: CryptoUtils,
|
||||
) => {
|
||||
const isShared = !!sharingKey;
|
||||
const {
|
||||
encrypted_content,
|
||||
encrypted_metadata,
|
||||
encrypted_dek,
|
||||
images,
|
||||
updated_at,
|
||||
} = data;
|
||||
|
||||
// Decrypt Metadata
|
||||
const decryptedMetadata = isShared
|
||||
? await cryptoUtils.decryptMetadataWithSharingKey(
|
||||
encrypted_metadata,
|
||||
sharingKey,
|
||||
)
|
||||
: await cryptoUtils.decryptMetadata(
|
||||
{ encrypted_content: encrypted_metadata, encrypted_dek },
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterKey is guaranteed to be non-null here as isDecryptionKeyAvailable is true
|
||||
masterKey!,
|
||||
);
|
||||
setMetadata({
|
||||
...(decryptedMetadata as LetterMetadata),
|
||||
updated_at,
|
||||
});
|
||||
|
||||
// Decrypt Content
|
||||
const decryptedContent = isShared
|
||||
? await cryptoUtils.decryptLetterWithSharingKey(
|
||||
encrypted_content,
|
||||
sharingKey,
|
||||
)
|
||||
: await cryptoUtils.decryptLetter(
|
||||
{ encrypted_content, encrypted_dek },
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterKey is guaranteed to be non-null here as isDecryptionKeyAvailable is true
|
||||
masterKey!,
|
||||
);
|
||||
|
||||
const canvasData: CanvasJSON = JSON.parse(decryptedContent);
|
||||
await decryptImages(canvasData, images, encrypted_dek, cryptoUtils);
|
||||
setDecryptedCanvasData(canvasData);
|
||||
};
|
||||
|
||||
const loadAndDecrypt = async () => {
|
||||
try {
|
||||
const response: AxiosResponse<LetterResponseData> = await api.get(
|
||||
`${endpoints.LETTERS}${public_id}/`,
|
||||
);
|
||||
const data = response.data;
|
||||
|
||||
if (data.status === "BURNED")
|
||||
throw new Error("This letter has been burned.");
|
||||
|
||||
if (data.encrypted_dek) setEncryptedDek(data.encrypted_dek);
|
||||
|
||||
const isDecryptionKeyAvailable = data.encrypted_dek && masterKey;
|
||||
if (!(!!sharingKey || isDecryptionKeyAvailable)) {
|
||||
throw new Error("Auth required: Decryption key is not available");
|
||||
}
|
||||
|
||||
const handleShare = async () => {
|
||||
if (!(encryptedDek && masterKey && public_id)) return;
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
const key = await cryptoUtils.extractSharingKey(encryptedDek, masterKey);
|
||||
try {
|
||||
await api.patch(`${endpoints.LETTERS}${public_id}/`, { type: "SENT" });
|
||||
} catch {
|
||||
// shouldn't obstruct share if api operation fails (since it's client side share)
|
||||
} finally {
|
||||
setShareLink(`${window.location.origin}${PATHS.read(public_id)}#${key}`);
|
||||
}
|
||||
await decryptLetterData(data, cryptoUtils);
|
||||
} catch (err) {
|
||||
setLogTrace({
|
||||
message: `Failed to load letter ☹`,
|
||||
log: err instanceof Error ? err.message : "Unknown error",
|
||||
type: "ERROR",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const burnLetter = async () => {
|
||||
if (!public_id || isBurning) return;
|
||||
setIsBurning(true);
|
||||
try {
|
||||
await api.patch(`${endpoints.LETTERS}${public_id}/`, {
|
||||
status: "BURNED",
|
||||
});
|
||||
} catch {
|
||||
// should not obstruct burn if api operation fails
|
||||
// WHY?: it disconnects the UX. if you want to burn the letter, you should be able to burn the letter
|
||||
// TODO: maybe say something like: "the wind is strong today, let's try again"? or maybe something less stupid :3
|
||||
} finally {
|
||||
setIsBurning(false);
|
||||
setShowBurnModal(false);
|
||||
setIgnite(true);
|
||||
setTimeout(() => {
|
||||
setRevealState("BURNED");
|
||||
}, WAIT_FOR_BURN_MS);
|
||||
}
|
||||
};
|
||||
loadAndDecrypt().then(() => setIsDecrypting(false));
|
||||
}, [public_id, sharingKey, masterKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!(sharingKey || masterKey)) {
|
||||
navigateRef.current("/login", {
|
||||
state: { redirectUrl: `/read/${public_id}` },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const decryptImages = async (
|
||||
canvasData: CanvasJSON,
|
||||
images: LetterImageData[],
|
||||
encrypted_dek: string,
|
||||
cryptoUtils: CryptoUtils,
|
||||
) => {
|
||||
if (!images?.length) return;
|
||||
const isShared = !!sharingKey;
|
||||
try {
|
||||
if (isShared) {
|
||||
await decryptCanvasImagesWithSharingKey(
|
||||
canvasData,
|
||||
images,
|
||||
sharingKey,
|
||||
cryptoUtils,
|
||||
);
|
||||
} else {
|
||||
await decryptCanvasImages(
|
||||
canvasData,
|
||||
images,
|
||||
encrypted_dek,
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterKey is guaranteed to be non-null here as isDecryptionKeyAvailable is true
|
||||
masterKey!,
|
||||
cryptoUtils,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
setLogTrace({
|
||||
message:
|
||||
"Failed to decrypt elements. Images might not render in the letter as intended.",
|
||||
log: err instanceof Error ? err.message : "Unknown error",
|
||||
type: "WARN",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const decryptLetterData = async (
|
||||
data: LetterResponseData,
|
||||
cryptoUtils: CryptoUtils,
|
||||
) => {
|
||||
const isShared = !!sharingKey;
|
||||
const {
|
||||
encrypted_content,
|
||||
encrypted_metadata,
|
||||
encrypted_dek,
|
||||
images,
|
||||
updated_at,
|
||||
} = data;
|
||||
|
||||
// Decrypt Metadata
|
||||
const decryptedMetadata = isShared
|
||||
? await cryptoUtils.decryptMetadataWithSharingKey(
|
||||
encrypted_metadata,
|
||||
sharingKey,
|
||||
)
|
||||
: await cryptoUtils.decryptMetadata(
|
||||
{ encrypted_content: encrypted_metadata, encrypted_dek },
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterKey is guaranteed to be non-null here as isDecryptionKeyAvailable is true
|
||||
masterKey!,
|
||||
);
|
||||
setMetadata({
|
||||
...(decryptedMetadata as LetterMetadata),
|
||||
updated_at,
|
||||
});
|
||||
|
||||
// Decrypt Content
|
||||
const decryptedContent = isShared
|
||||
? await cryptoUtils.decryptLetterWithSharingKey(
|
||||
encrypted_content,
|
||||
sharingKey,
|
||||
)
|
||||
: await cryptoUtils.decryptLetter(
|
||||
{ encrypted_content, encrypted_dek },
|
||||
// biome-ignore lint/style/noNonNullAssertion: masterKey is guaranteed to be non-null here as isDecryptionKeyAvailable is true
|
||||
masterKey!,
|
||||
);
|
||||
|
||||
const canvasData: CanvasJSON = JSON.parse(decryptedContent);
|
||||
await decryptImages(canvasData, images, encrypted_dek, cryptoUtils);
|
||||
setDecryptedCanvasData(canvasData);
|
||||
};
|
||||
|
||||
const loadAndDecrypt = async () => {
|
||||
try {
|
||||
const response: AxiosResponse<LetterResponseData> = await api.get(
|
||||
`${endpoints.LETTERS}${public_id}/`,
|
||||
);
|
||||
const data = response.data;
|
||||
|
||||
if (data.status === "BURNED")
|
||||
throw new Error("This letter has been burned.");
|
||||
|
||||
if (data.encrypted_dek) setEncryptedDek(data.encrypted_dek);
|
||||
|
||||
const isDecryptionKeyAvailable = data.encrypted_dek && masterKey;
|
||||
if (!(!!sharingKey || isDecryptionKeyAvailable)) {
|
||||
throw new Error("Auth required: Decryption key is not available");
|
||||
}
|
||||
|
||||
const cryptoUtils = new CryptoUtils();
|
||||
await decryptLetterData(data, cryptoUtils);
|
||||
} catch (err) {
|
||||
setLogTrace({
|
||||
message: `Failed to load letter ☹`,
|
||||
log: err instanceof Error ? err.message : "Unknown error",
|
||||
type: "ERROR",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
loadAndDecrypt().then(() => setIsDecrypting(false));
|
||||
}, [public_id, sharingKey, masterKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!isDecrypting &&
|
||||
revealState === "REVEALED" &&
|
||||
decryptedCanvasData &&
|
||||
canvasRef.current
|
||||
) {
|
||||
canvasRef.current.loadData(decryptedCanvasData);
|
||||
}
|
||||
}, [isDecrypting, revealState, decryptedCanvasData]);
|
||||
|
||||
if (isDecrypting) {
|
||||
return (
|
||||
<div className="flex items-center h-screen w-screen justify-center bg-base-100 font-sans">
|
||||
<div className="fixed inset-0 bg-vig pointer-events-none" />
|
||||
<div className="text-center space-y-6 z-10">
|
||||
<Logo />
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span className="loading loading-ring loading-md text-primary/40"></span>
|
||||
<p
|
||||
data-testid="decryption-overlay"
|
||||
className="text-xs uppercase tracking-widest text-base-content/20 animate-pulse"
|
||||
>
|
||||
Breaking the seal...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (logTrace) {
|
||||
return (
|
||||
<LogModal
|
||||
isOpen={!!logTrace}
|
||||
onClose={() => {
|
||||
if (logTrace.type === "ERROR") window.location.href = "/";
|
||||
setLogTrace(null);
|
||||
}}
|
||||
message={logTrace.message}
|
||||
log={logTrace.log}
|
||||
status={logTrace.type}
|
||||
/>
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
!isDecrypting &&
|
||||
revealState === "REVEALED" &&
|
||||
decryptedCanvasData &&
|
||||
canvasRef.current
|
||||
) {
|
||||
canvasRef.current.loadData(decryptedCanvasData);
|
||||
}
|
||||
}, [isDecrypting, revealState, decryptedCanvasData]);
|
||||
|
||||
if (isDecrypting) {
|
||||
return (
|
||||
<section className="min-h-fit w-full bg-base-100 px-4 py-8 md:py-16 font-serif relative overflow-hidden">
|
||||
<div className="fixed inset-0 bg-vig pointer-events-none z-0" />
|
||||
<div
|
||||
className={`transition-all delay-300 duration-1000 relative ${revealState === "REVEALED"
|
||||
? "opacity-0 w-0 h-0 overflow-hidden invisible"
|
||||
: "opacity-100"
|
||||
}`}
|
||||
<div className="flex items-center h-screen w-screen justify-center bg-base-100 font-sans">
|
||||
<div className="fixed inset-0 bg-vig pointer-events-none" />
|
||||
<div className="text-center space-y-6 z-10">
|
||||
<Logo />
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span className="loading loading-ring loading-md text-primary/40"></span>
|
||||
<p
|
||||
data-testid="decryption-overlay"
|
||||
className="text-xs uppercase tracking-widest text-base-content/20 animate-pulse"
|
||||
>
|
||||
{revealState === "SEALED" && (
|
||||
<div className="h-[80vh] mx-auto flex-col items-center flex justify-center">
|
||||
<div className="perspective-distant scale-80 duration-1000 transition-all animate-[pulse_2s_linear_1]">
|
||||
<EnvelopeReveal
|
||||
recipient={metadata?.recipient || "Someone dear"}
|
||||
date={
|
||||
metadata?.updated_at
|
||||
? formatDate(new Date(metadata.updated_at))
|
||||
: undefined
|
||||
}
|
||||
onRevealComplete={() => setRevealState("REVEALED")}
|
||||
ignite={ignite}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
Breaking the seal...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (logTrace) {
|
||||
return (
|
||||
<LogModal
|
||||
isOpen={!!logTrace}
|
||||
onClose={() => {
|
||||
if (logTrace.type === "ERROR") window.location.href = "/";
|
||||
setLogTrace(null);
|
||||
}}
|
||||
message={logTrace.message}
|
||||
log={logTrace.log}
|
||||
status={logTrace.type}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="min-h-fit w-full bg-base-100 px-4 py-8 md:py-16 font-serif relative overflow-hidden">
|
||||
<div className="fixed inset-0 bg-vig pointer-events-none z-0" />
|
||||
<div
|
||||
className={`transition-all delay-300 duration-1000 relative ${
|
||||
revealState === "REVEALED"
|
||||
? "opacity-0 w-0 h-0 overflow-hidden invisible"
|
||||
: "opacity-100"
|
||||
}`}
|
||||
>
|
||||
{revealState === "SEALED" && (
|
||||
<div className="h-[80vh] mx-auto flex-col items-center flex justify-center">
|
||||
<div className="perspective-distant scale-80 duration-1000 transition-all animate-[pulse_2s_linear_1]">
|
||||
<EnvelopeReveal
|
||||
recipient={metadata?.recipient || "Someone dear"}
|
||||
date={
|
||||
metadata?.updated_at
|
||||
? formatDate(new Date(metadata.updated_at))
|
||||
: undefined
|
||||
}
|
||||
onRevealComplete={() => setRevealState("REVEALED")}
|
||||
ignite={ignite}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ignite && <PostActionOverlay revealState={revealState} />}
|
||||
|
||||
{revealState === "REVEALED" && (
|
||||
<div className="max-w-180 m-8 mx-auto space-y-8 h-full relative inset-0 z-100">
|
||||
<div className="relative group perspective-1000">
|
||||
<div className="absolute inset-0 bg-primary/5 blur-3xl rounded-full scale-75 opacity-0 group-hover:opacity-100 transition-opacity duration-1000 pointer-events-none" />
|
||||
|
||||
<div className="bg-paper shadow-warm rounded-sm overflow-hidden animate-[opacity_1s_ease-in-out_1]">
|
||||
<div className="p-1 md:p-2 bg-base-content/5 opacity-10 pointer-events-none absolute inset-0 z-10" />
|
||||
<ComposeCanvas ref={canvasRef} readOnly />
|
||||
</div>
|
||||
|
||||
{ignite && <PostActionOverlay revealState={revealState} />}
|
||||
|
||||
{revealState === "REVEALED" && (
|
||||
<div className="max-w-180 m-8 mx-auto space-y-8 h-full relative inset-0 z-100">
|
||||
<div className="relative group perspective-1000">
|
||||
<div className="absolute inset-0 bg-primary/5 blur-3xl rounded-full scale-75 opacity-0 group-hover:opacity-100 transition-opacity duration-1000 pointer-events-none" />
|
||||
|
||||
<div className="bg-paper shadow-warm rounded-sm overflow-hidden animate-[opacity_1s_ease-in-out_1]">
|
||||
<div className="p-1 md:p-2 bg-base-content/5 opacity-10 pointer-events-none absolute inset-0 z-10" />
|
||||
<ComposeCanvas ref={canvasRef} readOnly />
|
||||
</div>
|
||||
|
||||
{metadata?.recipient && (
|
||||
<p className="text-center sm:hidden text-xxs uppercase tracking-widester text-base-content/20 mt-8">
|
||||
For {metadata.recipient}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{metadata?.recipient && (
|
||||
<p className="text-center sm:hidden text-xxs uppercase tracking-widester text-base-content/20 mt-8">
|
||||
For {metadata.recipient}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{shareLink && (
|
||||
<ShareModal shareLink={shareLink} setShareLink={setShareLink} />
|
||||
)}
|
||||
{showBurnModal && (
|
||||
<BurnModal
|
||||
burnLetter={burnLetter}
|
||||
isBurning={isBurning}
|
||||
setShowBurnModal={setShowBurnModal}
|
||||
setRevealState={setRevealState}
|
||||
/>
|
||||
)}
|
||||
{shareLink && (
|
||||
<ShareModal shareLink={shareLink} setShareLink={setShareLink} />
|
||||
)}
|
||||
{showBurnModal && (
|
||||
<BurnModal
|
||||
burnLetter={burnLetter}
|
||||
isBurning={isBurning}
|
||||
setShowBurnModal={setShowBurnModal}
|
||||
setRevealState={setRevealState}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isAuthor && revealState !== "BURNED" && (
|
||||
<div className="flex justify-center gap-2 mt-8 z-10 relative">
|
||||
<button
|
||||
id="share-letter-btn"
|
||||
data-testid="share-letter-btn"
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm text-base-content/30 hover:text-base-content hover:bg-base-content/10 gap-1.5"
|
||||
onClick={handleShare}
|
||||
>
|
||||
<PaperPlaneTiltIcon size={16} weight="duotone" />
|
||||
<span className="text-md uppercase font-sans tracking-widest">
|
||||
Send to someone
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
id="burn-letter-btn"
|
||||
data-testid="burn-letter-btn"
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm text-error/40 hover:text-error hover:bg-error/10 gap-1.5"
|
||||
onClick={() => setShowBurnModal(true)}
|
||||
>
|
||||
<FlameIcon size={16} weight="duotone" />
|
||||
<span className="text-md uppercase font-sans tracking-widest">
|
||||
Burn the letter
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isAuthor && revealState !== "BURNED" && (
|
||||
<div className="flex justify-center gap-2 mt-8 z-10 relative">
|
||||
<button
|
||||
id="share-letter-btn"
|
||||
data-testid="share-letter-btn"
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm text-base-content/30 hover:text-base-content hover:bg-base-content/10 gap-1.5"
|
||||
onClick={handleShare}
|
||||
>
|
||||
<PaperPlaneTiltIcon size={16} weight="duotone" />
|
||||
<span className="text-md uppercase font-sans tracking-widest">
|
||||
Send to someone
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
id="burn-letter-btn"
|
||||
data-testid="burn-letter-btn"
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm text-error/40 hover:text-error hover:bg-error/10 gap-1.5"
|
||||
onClick={() => setShowBurnModal(true)}
|
||||
>
|
||||
<FlameIcon size={16} weight="duotone" />
|
||||
<span className="text-md uppercase font-sans tracking-widest">
|
||||
Burn the letter
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<footer className="mt-16 text-center z-10 opacity-10 pointer-events-none">
|
||||
<p className="text-xs font-sans uppercase tracking-widester">
|
||||
Read. Remember. Release.
|
||||
</p>
|
||||
</footer>
|
||||
</section>
|
||||
);
|
||||
<footer className="mt-16 text-center z-10 opacity-10 pointer-events-none">
|
||||
<p className="text-xs font-sans uppercase tracking-widester">
|
||||
Read. Remember. Release.
|
||||
</p>
|
||||
</footer>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user