Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[photobook] Migration (#14170)

Anandd8a032e0f64a
diff --git a/.github/scripts/ci/paths.json b/.github/scripts/ci/paths.json
index b5a79ae0e1..363fa3f523 100644
--- a/.github/scripts/ci/paths.json
+++ b/.github/scripts/ci/paths.json
@@ -158,6 +158,7 @@
"rust/crates/location/**",
"rust/crates/locker/**",
"rust/crates/paste/**",
+ "rust/crates/photobook/**",
"rust/crates/space/**",
"web/**"
]
diff --git a/.github/workflows/web-deploy.yml b/.github/workflows/web-deploy.yml
index d91310130f..f523090cd8 100644
--- a/.github/workflows/web-deploy.yml
+++ b/.github/workflows/web-deploy.yml
@@ -132,3 +132,10 @@ jobs:
app: ensu
account-id: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
api-token: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+
+ - name: Deploy photobook
+ uses: ./.github/actions/deploy-web-app
+ with:
+ app: photobook
+ account-id: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+ api-token: ${{ secrets.CLOUDFLARE_API_TOKEN }}
diff --git a/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts b/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts
index 1c68bcc5a7..8277c2a8d6 100644
--- a/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts
+++ b/web/apps/albums/src/public-album/access/services/verify-public-album-password.ts
@@ -1,33 +1,8 @@
-import { deriveKey } from "ente-base/crypto";
-import {
- authenticatedPublicAlbumsRequestHeaders,
- ensureOk,
-} from "ente-base/http";
-import { apiURL } from "ente-base/origins";
import type { PublicURL } from "ente-media/collection";
-import { z } from "zod";
+import { verifyPublicCollectionPassword } from "ente-media/public-albums";
export const verifyPublicAlbumPassword = async (
publicURL: PublicURL,
password: string,
accessToken: string,
-) => {
- const passwordHash = await deriveKey(
- password,
- // TODO: Fix the types to not require the bang.
- publicURL.nonce!,
- publicURL.opsLimit!,
- publicURL.memLimit!,
- );
-
- const res = await fetch(
- await apiURL("/public-collection/verify-password"),
- {
- method: "POST",
- headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
- body: JSON.stringify({ passHash: passwordHash }),
- },
- );
- ensureOk(res);
- return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;
-};
+) => verifyPublicCollectionPassword({ accessToken }, publicURL, password);
diff --git a/web/apps/albums/src/public-album/data/api/public-collection.ts b/web/apps/albums/src/public-album/data/api/public-collection.ts
index fad0ba5b62..e34ba6cd15 100644
--- a/web/apps/albums/src/public-album/data/api/public-collection.ts
+++ b/web/apps/albums/src/public-album/data/api/public-collection.ts
@@ -1,25 +1,13 @@
-import { deriveKey } from "ente-base/crypto";
-import {
- authenticatedPublicAlbumsDeviceLimitRequestHeaders,
- authenticatedPublicAlbumsInfoRequestHeaders,
- authenticatedPublicAlbumsRequestHeaders,
- ensureOk,
- linkDeviceTokenFromResponse,
- type PublicAlbumsCredentials,
-} from "ente-base/http";
-import { apiURL } from "ente-base/origins";
+import type { PublicAlbumsCredentials } from "ente-base/http";
import {
decryptRemoteCollection,
- RemoteCollection,
type Collection,
- type PublicURL,
} from "ente-media/collection";
+import { decryptRemoteFile, type EnteFile } from "ente-media/file";
import {
- decryptRemoteFile,
- FileDiffResponse,
- type EnteFile,
-} from "ente-media/file";
-import { z } from "zod";
+ getPublicCollectionDiff,
+ getPublicCollectionInfo,
+} from "ente-media/public-albums";
import {
removePublicCollectionAccessTokenJWT,
removePublicCollectionFiles,
@@ -32,31 +20,6 @@ import {
savePublicCollectionLastSyncTime,
} from "../storage/public-albums-fdb";
-export const verifyPublicAlbumPassword = async (
- publicURL: PublicURL,
- password: string,
- accessToken: string,
-) => {
- const passwordHash = await deriveKey(
- password,
- // TODO: Fix the types to not require the bang.
- publicURL.nonce!,
- publicURL.opsLimit!,
- publicURL.memLimit!,
- );
-
- const res = await fetch(
- await apiURL("/public-collection/verify-password"),
- {
- method: "POST",
- headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
- body: JSON.stringify({ passHash: passwordHash }),
- },
- );
- ensureOk(res);
- return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;
-};
-
export const pullCollection = async (
credentials: PublicAlbumsCredentials,
collectionKey: string,
@@ -83,22 +46,6 @@ export const pullCollection = async (
return { collection, referralCode, linkDeviceToken };
};
-const PublicCollectionInfo = z.object({
- collection: RemoteCollection,
- referralCode: z.string(),
-});
-
-const getPublicCollectionInfo = async (
- credentials: PublicAlbumsCredentials,
-) => {
- const res = await fetch(await apiURL("/public-collection/info"), {
- headers: authenticatedPublicAlbumsInfoRequestHeaders(credentials),
- });
- ensureOk(res);
- const info = PublicCollectionInfo.parse(await res.json());
- return { ...info, linkDeviceToken: linkDeviceTokenFromResponse(res) };
-};
-
export const pullPublicCollectionFiles = async (
credentials: PublicAlbumsCredentials,
collection: Collection,
@@ -150,21 +97,6 @@ export const pullPublicCollectionFiles = async (
}
};
-const getPublicCollectionDiff = async (
- credentials: PublicAlbumsCredentials,
- sinceTime: number,
-) => {
- const res = await fetch(
- await apiURL("/public-collection/diff", { sinceTime }),
- {
- headers:
- authenticatedPublicAlbumsDeviceLimitRequestHeaders(credentials),
- },
- );
- ensureOk(res);
- return FileDiffResponse.parse(await res.json());
-};
-
export const removePublicCollectionFileData = async (accessToken: string) => {
await Promise.all([
removePublicCollectionAccessTokenJWT(accessToken),
diff --git a/web/apps/photobook/eslint.config.mjs b/web/apps/photobook/eslint.config.mjs
new file mode 100644
index 0000000000..38d1479f25
--- /dev/null
+++ b/web/apps/photobook/eslint.config.mjs
@@ -0,0 +1,3 @@
+import baseConfig from "ente-build-config/eslintrc-next-app.mjs";
+
+export default [...baseConfig];
diff --git a/web/apps/photobook/next.config.js b/web/apps/photobook/next.config.js
new file mode 100644
index 0000000000..5a52794ab2
--- /dev/null
+++ b/web/apps/photobook/next.config.js
@@ -0,0 +1 @@
+module.exports = require("ente-base/next.config.base.js");
diff --git a/web/apps/photobook/package.json b/web/apps/photobook/package.json
new file mode 100644
index 0000000000..1315aa4155
--- /dev/null
+++ b/web/apps/photobook/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "photobook",
+ "version": "0.0.0",
+ "private": true,
+ "scripts": {
+ "test": "vitest --run"
+ },
+ "dependencies": {
+ "@fontsource/gochi-hand": "5.3.0",
+ "@hugeicons/core-free-icons": "4.3.5",
+ "@hugeicons/react": "1.1.10",
+ "bs58": "6.0.0",
+ "ente-base": "*",
+ "ente-gallery": "*",
+ "ente-media": "*",
+ "ente-photobook-wasm": "*",
+ "jszip": "3.10.2",
+ "konva": "9.3.22",
+ "page-flip": "2.0.7",
+ "react-konva": "19.2.3"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "vitest": "5.0.4"
+ }
+}
diff --git a/web/apps/photobook/public/ente-branding.svg b/web/apps/photobook/public/ente-branding.svg
new file mode 100644
index 0000000000..3d53fc3866
--- /dev/null
+++ b/web/apps/photobook/public/ente-branding.svg
@@ -0,0 +1,6 @@
+<svg width="844" height="264" viewBox="0 0 844 264" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M225.65 175.02H75.0694C82.344 192.768 98.6376 201.649 123.957 201.649C139.382 201.649 152.621 196.554 163.674 186.369L216.051 223.039C194.807 250.103 163.53 263.632 122.213 263.632C85.2607 263.632 55.5763 252.861 33.1734 231.327C11.0601 209.503 0 181.998 0 148.824C0 115.651 10.9084 88.442 32.7321 66.3218C54.5558 44.2085 82.344 33.1484 116.097 33.1484C149.849 33.1484 175.603 44.0637 196.841 65.8874C218.085 87.4215 228.704 114.775 228.704 147.949C228.704 158.133 227.684 167.152 225.65 175.013V175.02ZM74.1937 124.822H157.993C152.463 104.453 138.789 94.2686 116.965 94.2686C95.1417 94.2686 80.3029 104.453 74.1937 124.822Z" fill="black" style="fill:black;fill-opacity:1;"/>
+<path d="M372.127 33.1613C396.281 33.1613 415.63 41.4564 430.179 58.0397C445.018 74.3333 452.437 97.3223 452.437 127.007V257.521H379.981V136.171C379.981 125.11 377.071 116.671 371.251 110.851C365.432 104.742 357.426 101.687 347.242 101.687C335.892 101.687 327.018 105.176 320.619 112.161C314.51 118.856 311.448 128.606 311.448 141.404V257.515H238.992V39.2568H311.448V61.0805C324.542 42.4562 344.767 33.1406 372.12 33.1406L372.127 33.1613Z" fill="black" style="fill:black;fill-opacity:1;"/>
+<path d="M611.041 39.2689V108.677H565.649V171.969C565.649 181.285 568.849 187.249 575.247 189.87C581.943 192.2 593.872 192.924 611.041 192.056V257.534C567.98 262.774 537.42 258.844 519.381 245.749C501.922 232.069 493.193 208.066 493.193 173.728V108.691H460.461V39.2827H493.193V0H565.649V39.2827H611.041V39.2689Z" fill="black" style="fill:black;fill-opacity:1;"/>
+<path d="M840.438 175.02H689.858C697.132 192.768 713.426 201.649 738.739 201.649C754.163 201.649 767.402 196.554 778.456 186.369L830.833 223.039C809.588 250.103 778.311 263.632 736.994 263.632C700.035 263.632 670.358 252.861 647.955 231.327C625.841 209.503 614.781 181.998 614.781 148.824C614.781 115.651 625.69 88.442 647.52 66.3218C669.344 44.2085 697.132 33.1484 730.885 33.1484C764.637 33.1484 790.391 44.0637 811.629 65.8874C832.873 87.4215 843.492 114.775 843.492 147.949C843.492 158.133 842.472 167.152 840.438 175.013V175.02ZM688.982 124.822H772.781C767.258 104.453 753.577 94.2686 731.754 94.2686C709.93 94.2686 695.091 104.453 688.982 124.822Z" fill="black" style="fill:black;fill-opacity:1;"/>
+</svg>
diff --git a/web/apps/photobook/public/hero-photo.jpg b/web/apps/photobook/public/hero-photo.jpg
new file mode 100644
index 0000000000..c7d66274fb
Binary files /dev/null and b/web/apps/photobook/public/hero-photo.jpg differ
diff --git a/web/apps/photobook/public/icon-192x192.png b/web/apps/photobook/public/icon-192x192.png
new file mode 100644
index 0000000000..291c6c5eee
Binary files /dev/null and b/web/apps/photobook/public/icon-192x192.png differ
diff --git a/web/apps/photobook/public/images/favicon.png b/web/apps/photobook/public/images/favicon.png
new file mode 100644
index 0000000000..deb25a1c3b
Binary files /dev/null and b/web/apps/photobook/public/images/favicon.png differ
diff --git a/web/apps/photobook/public/pdfx/FOGRA39L_coated.icc b/web/apps/photobook/public/pdfx/FOGRA39L_coated.icc
new file mode 100644
index 0000000000..4bd9bbb467
Binary files /dev/null and b/web/apps/photobook/public/pdfx/FOGRA39L_coated.icc differ
diff --git a/web/apps/photobook/src/components/AddPageDialog.tsx b/web/apps/photobook/src/components/AddPageDialog.tsx
new file mode 100644
index 0000000000..208588a3f5
--- /dev/null
+++ b/web/apps/photobook/src/components/AddPageDialog.tsx
@@ -0,0 +1,243 @@
+import type { BookPage } from "@/lib/types";
+import { accentGreen, accentGreenHover } from "@/theme/buttons";
+import {
+ dialogActionSx,
+ dialogCloseButtonSx,
+ dialogDescriptionSx,
+ dialogHeaderSx,
+ dialogPaperSx,
+ dialogSelectMenuProps,
+ dialogSelectSx,
+ dialogTitleSx,
+} from "@/theme/dialogs";
+import {
+ Box,
+ Button,
+ Dialog,
+ IconButton,
+ MenuItem,
+ Select,
+ Typography,
+} from "@mui/material";
+import { useId, useState } from "react";
+import { AddPageIcon, CloseIcon } from "./icons";
+import type { PageInsertPosition } from "./PageMenu";
+
+interface AddPageDialogProps {
+ pages: BookPage[];
+ initialPageId?: string;
+ disabled: boolean;
+ onClose: () => void;
+ onInsert: (pageIndex: number, position: PageInsertPosition) => void;
+}
+
+export default function AddPageDialog({
+ pages,
+ initialPageId,
+ disabled,
+ onClose,
+ onInsert,
+}: AddPageDialogProps) {
+ const id = useId();
+ const [open, setOpen] = useState(true);
+ const [insertion, setInsertion] = useState<{
+ pageIndex: number;
+ position: PageInsertPosition;
+ } | null>(null);
+ const [pageId, setPageId] = useState(
+ initialPageId ?? pages.at(0)?.id ?? "",
+ );
+ const [position, setPosition] = useState<PageInsertPosition>(() =>
+ pages.length >= 2 && initialPageId === pages.at(-1)?.id
+ ? "before"
+ : "after",
+ );
+ const lastIndex = pages.length - 1;
+ const firstAllowedIndex = position === "before" ? 1 : 0;
+ const lastAllowedIndex = position === "after" ? lastIndex - 1 : lastIndex;
+ const pageIndex = Math.min(
+ lastAllowedIndex,
+ Math.max(
+ firstAllowedIndex,
+ pages.findIndex((page) => page.id === pageId),
+ ),
+ );
+ const targetPage = pages.at(pageIndex);
+ const canInsert = !disabled && pages.length >= 2 && !!targetPage;
+
+ return (
+ <Dialog
+ open={open}
+ onClose={() => setOpen(false)}
+ maxWidth={false}
+ aria-labelledby={`${id}-title`}
+ aria-describedby={`${id}-description`}
+ slotProps={{
+ paper: { sx: dialogPaperSx },
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.5)" } },
+ transition: {
+ onExited: () => {
+ onClose();
+ if (insertion)
+ onInsert(insertion.pageIndex, insertion.position);
+ },
+ },
+ }}
+ >
+ <Box
+ component="form"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (!open || !canInsert) return;
+ setInsertion({ pageIndex, position });
+ setOpen(false);
+ }}
+ sx={{ position: "relative", p: "48px 16px 16px" }}
+ >
+ <IconButton
+ type="button"
+ aria-label="Close"
+ onClick={() => setOpen(false)}
+ sx={dialogCloseButtonSx}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "16px",
+ }}
+ >
+ <Box
+ aria-hidden="true"
+ sx={{
+ width: 126,
+ height: 121,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ mb: "8px",
+ color: accentGreen,
+ }}
+ >
+ <AddPageIcon sx={{ fontSize: 72 }} />
+ </Box>
+ <Box sx={dialogHeaderSx}>
+ <Typography
+ component="h2"
+ id={`${id}-title`}
+ sx={dialogTitleSx}
+ >
+ Add page
+ </Typography>
+ <Typography
+ id={`${id}-description`}
+ sx={dialogDescriptionSx}
+ >
+ Choose where to add a blank page.
+ </Typography>
+ </Box>
+ <Box
+ sx={{
+ display: "grid",
+ gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
+ gap: "12px",
+ width: "100%",
+ }}
+ >
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: "8px",
+ minWidth: 0,
+ }}
+ >
+ <Select
+ autoFocus
+ inputProps={{ "aria-label": "Insert position" }}
+ value={position}
+ onChange={(event) => {
+ const nextPosition = event.target.value;
+ const nextIndex =
+ nextPosition === "before"
+ ? Math.max(1, pageIndex)
+ : Math.min(
+ lastIndex - 1,
+ pageIndex,
+ );
+ setPosition(nextPosition);
+ setPageId(pages[nextIndex]?.id ?? "");
+ }}
+ disabled={!canInsert}
+ sx={dialogSelectSx}
+ MenuProps={dialogSelectMenuProps}
+ >
+ <MenuItem value="before">Before</MenuItem>
+ <MenuItem value="after">After</MenuItem>
+ </Select>
+ </Box>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: "8px",
+ minWidth: 0,
+ }}
+ >
+ <Select
+ inputProps={{ "aria-label": "Page" }}
+ value={targetPage?.id ?? ""}
+ onChange={(event) =>
+ setPageId(event.target.value)
+ }
+ disabled={!canInsert}
+ sx={dialogSelectSx}
+ MenuProps={dialogSelectMenuProps}
+ >
+ {pages.map((page, index) =>
+ index < firstAllowedIndex ||
+ index > lastAllowedIndex ? null : (
+ <MenuItem key={page.id} value={page.id}>
+ {index === 0
+ ? "Front cover"
+ : index === lastIndex
+ ? "Back cover"
+ : `Page ${index}`}
+ </MenuItem>
+ ),
+ )}
+ </Select>
+ </Box>
+ </Box>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: "12px",
+ width: "100%",
+ }}
+ >
+ <Button
+ type="submit"
+ variant="contained"
+ fullWidth
+ disableElevation
+ disabled={!canInsert}
+ sx={{
+ ...dialogActionSx,
+ color: "#FFFFFF",
+ bgcolor: accentGreen,
+ "&:hover": { bgcolor: accentGreenHover },
+ }}
+ >
+ Add page
+ </Button>
+ </Box>
+ </Box>
+ </Box>
+ </Dialog>
+ );
+}
diff --git a/web/apps/photobook/src/components/AddPhotosDialog.tsx b/web/apps/photobook/src/components/AddPhotosDialog.tsx
new file mode 100644
index 0000000000..ed75cf0e9e
--- /dev/null
+++ b/web/apps/photobook/src/components/AddPhotosDialog.tsx
@@ -0,0 +1,216 @@
+import {
+ MAX_PAGE_PHOTOS,
+ photoDestinationError,
+ type PhotoDestination,
+} from "@/lib/photoPlacement";
+import type { BookPage } from "@/lib/types";
+import { accentGreen, accentGreenHover } from "@/theme/buttons";
+import { uiColors } from "@/theme/colors";
+import {
+ dialogActionSx,
+ dialogCloseButtonSx,
+ dialogHeaderSx,
+ dialogPaperSx,
+ dialogSelectMenuProps,
+ dialogSelectSx,
+ dialogTitleSx,
+} from "@/theme/dialogs";
+import {
+ Box,
+ Button,
+ Dialog,
+ IconButton,
+ MenuItem,
+ Select,
+ Typography,
+} from "@mui/material";
+import { useId, useState } from "react";
+import { AddPhotosIcon, CloseIcon } from "./icons";
+
+interface AddPhotosDialogProps {
+ pages: BookPage[];
+ photoCount: number;
+ busy: boolean;
+ progress: number;
+ onClose: () => void;
+ onAdd: (destination: PhotoDestination) => Promise<void>;
+}
+
+export default function AddPhotosDialog({
+ pages,
+ photoCount,
+ busy,
+ progress,
+ onClose,
+ onAdd,
+}: AddPhotosDialogProps) {
+ const id = useId();
+ const [open, setOpen] = useState(true);
+ const [submitting, setSubmitting] = useState(false);
+ const [target, setTarget] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const destination: PhotoDestination | null = !target
+ ? null
+ : target === "end"
+ ? { kind: "end" }
+ : { kind: "page", pageId: target };
+ const validationError =
+ destination && !submitting
+ ? photoDestinationError(pages, destination, photoCount)
+ : null;
+ const isCover = target === pages[0]?.id;
+ const newPageCount = Math.ceil(photoCount / MAX_PAGE_PHOTOS);
+ const loading = busy || submitting;
+ const close = () => {
+ if (!loading) setOpen(false);
+ };
+
+ return (
+ <Dialog
+ open={open}
+ onClose={close}
+ maxWidth={false}
+ aria-labelledby={`${id}-title`}
+ aria-busy={loading}
+ slotProps={{
+ paper: { sx: dialogPaperSx },
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.5)" } },
+ transition: { onExited: onClose },
+ }}
+ >
+ <Box
+ component="form"
+ sx={{ position: "relative", p: "48px 16px 16px" }}
+ onSubmit={async (event) => {
+ event.preventDefault();
+ if (!open || loading || !destination || validationError)
+ return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await onAdd(destination);
+ setOpen(false);
+ } catch (cause) {
+ setSubmitting(false);
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : "Couldn't add these photos. Please try again.",
+ );
+ }
+ }}
+ >
+ <IconButton
+ type="button"
+ aria-label="Close"
+ onClick={close}
+ disabled={loading}
+ sx={dialogCloseButtonSx}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "16px",
+ }}
+ >
+ <Box
+ aria-hidden="true"
+ sx={{
+ width: 126,
+ height: 121,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ mb: "8px",
+ color: accentGreen,
+ }}
+ >
+ <AddPhotosIcon sx={{ fontSize: 72 }} />
+ </Box>
+ <Box sx={dialogHeaderSx}>
+ <Typography
+ component="h2"
+ id={`${id}-title`}
+ sx={dialogTitleSx}
+ >
+ {isCover ? "Cover image" : "Add photos"}
+ </Typography>
+ </Box>
+ <Select
+ autoFocus
+ fullWidth
+ displayEmpty
+ inputProps={{ "aria-label": "Add photos to" }}
+ value={target}
+ disabled={loading}
+ renderValue={
+ target === "" ? () => "Choose page" : undefined
+ }
+ onChange={(event) => {
+ setTarget(event.target.value);
+ setError(null);
+ }}
+ sx={dialogSelectSx}
+ MenuProps={dialogSelectMenuProps}
+ >
+ <MenuItem value="end">
+ {newPageCount === 1
+ ? "New page at end"
+ : "New pages at end"}
+ </MenuItem>
+ {pages.slice(0, -1).map((page, index) => (
+ <MenuItem
+ key={page.id}
+ value={page.id}
+ disabled={
+ !!photoDestinationError(
+ pages,
+ { kind: "page", pageId: page.id },
+ photoCount,
+ )
+ }
+ >
+ {index === 0 ? "Front cover" : `Page ${index}`}
+ </MenuItem>
+ ))}
+ </Select>
+ {(error || validationError) && (
+ <Typography
+ role="alert"
+ sx={{
+ color: uiColors.danger,
+ fontSize: 13,
+ textAlign: "center",
+ }}
+ >
+ {error || validationError}
+ </Typography>
+ )}
+ <Button
+ type="submit"
+ variant="contained"
+ fullWidth
+ disableElevation
+ disabled={loading || !destination || !!validationError}
+ sx={{
+ ...dialogActionSx,
+ color: "#FFFFFF",
+ bgcolor: accentGreen,
+ "&:hover": { bgcolor: accentGreenHover },
+ }}
+ >
+ {loading
+ ? `Adding photos… ${progress}%`
+ : isCover
+ ? "Use as cover"
+ : `Add ${photoCount} photo${photoCount === 1 ? "" : "s"}`}
+ </Button>
+ </Box>
+ </Box>
+ </Dialog>
+ );
+}
diff --git a/web/apps/photobook/src/components/AppShell.tsx b/web/apps/photobook/src/components/AppShell.tsx
new file mode 100644
index 0000000000..15b6a86ce5
--- /dev/null
+++ b/web/apps/photobook/src/components/AppShell.tsx
@@ -0,0 +1,194 @@
+import EditPage from "@/components/EditPage";
+import ResultsPage from "@/components/ResultsPage";
+import { useBook } from "@/context/book";
+import { usePhotoImport } from "@/hooks/usePhotoImport";
+import type { AppView } from "@/lib/types";
+import { popupShadow, uiColors } from "@/theme/colors";
+import {
+ Alert,
+ Box,
+ CircularProgress,
+ Dialog,
+ DialogContent,
+ Fade,
+ IconButton,
+ Snackbar,
+ Typography,
+ useMediaQuery,
+} from "@mui/material";
+import { useEffect, useState } from "react";
+import EntePasswordDialog from "./EntePasswordDialog";
+import { CloseIcon } from "./icons";
+import ImportProgress from "./ImportProgress";
+
+function BookWorkspace({ view }: { view: AppView }) {
+ const [displayedView, setDisplayedView] = useState(view);
+ const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
+ const visible = displayedView === view;
+
+ return (
+ <Fade
+ in={visible}
+ appear={false}
+ timeout={reduceMotion ? 0 : { exit: 120, enter: 220 }}
+ easing={{ exit: "ease-in", enter: "ease-out" }}
+ onExited={() => setDisplayedView(view)}
+ >
+ <Box inert={!visible} data-workspace-view={displayedView}>
+ {displayedView === "results" ? <ResultsPage /> : <EditPage />}
+ </Box>
+ </Fade>
+ );
+}
+
+export default function AppShell() {
+ const { appView, loading, book, importNotice, clearImportNotice } =
+ useBook();
+ const {
+ importActive,
+ enteStage,
+ entePassword,
+ setEntePassword,
+ handleSubmitPassword,
+ handleCancelPassword,
+ } = usePhotoImport();
+ const [showMobileHint, setShowMobileHint] = useState(false);
+
+ useEffect(() => {
+ if (
+ !importActive &&
+ book.pages.length > 0 &&
+ appView === "edit" &&
+ typeof window !== "undefined" &&
+ window.matchMedia("(max-width: 640px)").matches
+ ) {
+ const dismissed = sessionStorage.getItem("mobile-hint-dismissed");
+ if (!dismissed) setShowMobileHint(true);
+ }
+ }, [appView, importActive, book.pages.length]);
+
+ if (loading) {
+ return (
+ <Box
+ sx={{
+ minHeight: "100vh",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <CircularProgress sx={{ color: "#08C225" }} />
+ </Box>
+ );
+ }
+
+ return (
+ <>
+ {importActive ? (
+ <ImportProgress />
+ ) : (
+ <BookWorkspace view={appView} />
+ )}
+ <EntePasswordDialog
+ open={enteStage === "password"}
+ password={entePassword}
+ onPasswordChange={setEntePassword}
+ onSubmit={handleSubmitPassword}
+ onCancel={handleCancelPassword}
+ />
+
+ <Snackbar
+ open={Boolean(importNotice)}
+ autoHideDuration={10000}
+ onClose={clearImportNotice}
+ anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
+ >
+ <Alert
+ severity="info"
+ onClose={clearImportNotice}
+ sx={{
+ bgcolor: uiColors.surface,
+ color: uiColors.text,
+ boxShadow: popupShadow,
+ "& .MuiAlert-icon": { color: "#08C225" },
+ }}
+ >
+ {importNotice}
+ </Alert>
+ </Snackbar>
+
+ <Dialog
+ open={showMobileHint}
+ onClose={() => {
+ setShowMobileHint(false);
+ sessionStorage.setItem("mobile-hint-dismissed", "1");
+ }}
+ slotProps={{
+ paper: {
+ sx: {
+ borderRadius: 4,
+ maxWidth: 300,
+ mx: 2,
+ p: 0,
+ bgcolor: uiColors.surface,
+ boxShadow: popupShadow,
+ },
+ },
+ }}
+ >
+ <DialogContent
+ sx={{
+ textAlign: "center",
+ py: 3.5,
+ px: 3,
+ position: "relative",
+ }}
+ >
+ <IconButton
+ onClick={() => {
+ setShowMobileHint(false);
+ sessionStorage.setItem(
+ "mobile-hint-dismissed",
+ "1",
+ );
+ }}
+ size="small"
+ sx={{
+ position: "absolute",
+ top: 6,
+ right: 6,
+ color: uiColors.muted,
+ "&:hover": { color: uiColors.text },
+ }}
+ >
+ <CloseIcon sx={{ fontSize: 18 }} />
+ </IconButton>
+ <Typography
+ variant="body"
+ sx={{
+ fontFamily: "var(--font-inter)",
+ fontWeight: 700,
+ mb: 0.5,
+ color: uiColors.text,
+ fontSize: "1rem",
+ }}
+ >
+ Best on desktop
+ </Typography>
+ <Typography
+ variant="small"
+ sx={{
+ fontFamily: "var(--font-inter)",
+ color: uiColors.muted,
+ lineHeight: 1.55,
+ fontSize: "0.835rem",
+ }}
+ >
+ The photobook editor works best on a larger screen. For
+ the full experience, try it on a desktop or laptop.
+ </Typography>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/web/apps/photobook/src/components/BookBindingSelect.tsx b/web/apps/photobook/src/components/BookBindingSelect.tsx
new file mode 100644
index 0000000000..ec1f761470
--- /dev/null
+++ b/web/apps/photobook/src/components/BookBindingSelect.tsx
@@ -0,0 +1,67 @@
+import { useBook } from "@/context/book";
+import { getBindingPrintSelection, getPrintBinding } from "@/lib/printProducts";
+import { accentGreen } from "@/theme/buttons";
+import { dialogSelectMenuProps, dialogSelectSx } from "@/theme/dialogs";
+import { MenuItem, Select } from "@mui/material";
+import { ChevronDownIcon } from "./icons";
+
+export default function BookBindingSelect({
+ disabled = false,
+}: {
+ disabled?: boolean;
+}) {
+ const { book, setBook, processingPhotos } = useBook();
+ const binding = getPrintBinding(book.printSelection);
+ return (
+ <Select
+ value={binding}
+ disabled={disabled || processingPhotos}
+ inputProps={{ "aria-label": "Cover type" }}
+ IconComponent={ChevronDownIcon}
+ MenuProps={dialogSelectMenuProps}
+ onChange={(event) => {
+ const next = event.target.value;
+ if (!book.printSelection || next !== binding)
+ setBook((previous) => ({
+ ...previous,
+ printSelection: getBindingPrintSelection(next),
+ }));
+ }}
+ sx={{
+ ...dialogSelectSx,
+ bgcolor: "transparent",
+ width: "auto",
+ mr: "14px",
+ height: { xs: 38, sm: 40 },
+ flexShrink: 0,
+ borderRadius: { xs: "12px", sm: "14px" },
+ fontSize: 13,
+ fontWeight: 600,
+ "&& .MuiSelect-select.MuiSelect-outlined": {
+ pl: "8px",
+ pr: "28px",
+ },
+ "& .MuiSelect-icon": {
+ fontSize: 16,
+ right: 8,
+ top: "calc(50% - 8px)",
+ },
+ "& .MuiSelect-select:focus": { bgcolor: "transparent" },
+ "&:hover .MuiOutlinedInput-notchedOutline": {
+ borderColor: "transparent",
+ },
+ "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
+ borderColor: "transparent",
+ },
+ "& .MuiSelect-select:focus-visible": {
+ outline: `2px solid ${accentGreen}`,
+ outlineOffset: -2,
+ borderRadius: "12px",
+ },
+ }}
+ >
+ <MenuItem value="Hardcover">Hardcover</MenuItem>
+ <MenuItem value="Softcover">Softcover</MenuItem>
+ </Select>
+ );
+}
diff --git a/web/apps/photobook/src/components/BookHeader.tsx b/web/apps/photobook/src/components/BookHeader.tsx
new file mode 100644
index 0000000000..ab9aa18154
--- /dev/null
+++ b/web/apps/photobook/src/components/BookHeader.tsx
@@ -0,0 +1,83 @@
+import { Box, Typography } from "@mui/material";
+import type { ReactNode } from "react";
+import BookTitleInput from "./BookTitleInput";
+import { EDITOR_HEADER_HEIGHT } from "./editorLayout";
+
+export default function BookHeader({
+ children,
+ showBookControls = true,
+}: {
+ children: ReactNode;
+ showBookControls?: boolean;
+}) {
+ return (
+ <Box
+ component="header"
+ sx={{
+ display: "grid",
+ gridTemplateColumns: {
+ xs: "minmax(0, 1fr) minmax(0, max-content)",
+ md: "minmax(max-content, 1fr) minmax(0, max-content) minmax(max-content, 1fr)",
+ },
+ alignItems: "center",
+ minHeight: showBookControls
+ ? { xs: 104, sm: 116, md: 76 }
+ : EDITOR_HEADER_HEIGHT,
+ gap: 1,
+ px: 1,
+ flexShrink: 0,
+ }}
+ >
+ <Box
+ sx={{
+ gridColumn: 1,
+ gridRow: 1,
+ justifySelf: "start",
+ display: "flex",
+ alignItems: "center",
+ gap: 1,
+ }}
+ >
+ <Box
+ component="img"
+ src="/ente-branding.svg"
+ alt="Ente"
+ sx={{
+ display: "block",
+ height: { xs: 16, sm: 20 },
+ width: "auto",
+ filter: "invert(1)",
+ "@media (max-width: 359px)": { height: 13 },
+ }}
+ />
+ <Typography
+ sx={{
+ fontFamily: '"Gochi Hand", cursive',
+ fontSize: { xs: 24, sm: 32 },
+ lineHeight: 1.2,
+ fontWeight: 400,
+ color: "#F2C14E",
+ transform: "translateY(1px)",
+ whiteSpace: "nowrap",
+ "@media (max-width: 359px)": { fontSize: 21 },
+ }}
+ >
+ photobook
+ </Typography>
+ </Box>
+ {showBookControls && <BookTitleInput />}
+ <Box
+ sx={{
+ gridColumn: { xs: "1 / -1", md: 3 },
+ gridRow: { xs: 2, md: 1 },
+ justifySelf: "end",
+ display: showBookControls ? "flex" : "none",
+ alignItems: "center",
+ gap: 1,
+ }}
+ >
+ {children}
+ </Box>
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/BookPageNavigation.tsx b/web/apps/photobook/src/components/BookPageNavigation.tsx
new file mode 100644
index 0000000000..116ee0fd98
--- /dev/null
+++ b/web/apps/photobook/src/components/BookPageNavigation.tsx
@@ -0,0 +1,73 @@
+import {
+ getSpreadLabel,
+ getSpreadPageIndices,
+ type Spread,
+} from "@/lib/spreads";
+import { dialogSelectMenuProps, dialogSelectSx } from "@/theme/dialogs";
+import { MenuItem, Select } from "@mui/material";
+import { ChevronDownIcon } from "./icons";
+
+interface BookPageNavigationProps {
+ pageCount: number;
+ spreads: Spread[];
+ spreadIndex: number;
+ disabled: boolean;
+ turning: boolean;
+ onGoToSpread: (spreadIndex: number) => void;
+}
+
+export default function BookPageNavigation({
+ pageCount,
+ spreads,
+ spreadIndex,
+ disabled,
+ turning,
+ onGoToSpread,
+}: BookPageNavigationProps) {
+ if (pageCount === 0) return null;
+
+ const options = spreads.map((item, index) => {
+ const pageIndex = getSpreadPageIndices(item).at(0);
+ const label = getSpreadLabel(item, pageCount);
+ const isCover = pageIndex === 0 || pageIndex === pageCount - 1;
+ return {
+ index,
+ label:
+ pageIndex === undefined
+ ? index < spreads.length / 2
+ ? "Front blanks"
+ : "Back blanks"
+ : isCover
+ ? label
+ : `${label.includes("–") ? "Pages" : "Page"} ${label}`,
+ };
+ });
+
+ return (
+ <Select
+ value={Math.min(spreadIndex, spreads.length - 1)}
+ disabled={disabled}
+ readOnly={turning}
+ SelectDisplayProps={{ "aria-readonly": turning || undefined }}
+ onChange={(event) => onGoToSpread(event.target.value)}
+ inputProps={{ "aria-label": "Current page" }}
+ IconComponent={ChevronDownIcon}
+ MenuProps={dialogSelectMenuProps}
+ sx={{
+ ...dialogSelectSx,
+ width: 136,
+ maxWidth: "calc(100vw - 48px)",
+ height: 42,
+ borderRadius: "14px",
+ fontSize: 13,
+ "& .MuiSelect-select": { pl: "12px", pr: "32px" },
+ }}
+ >
+ {options.map(({ index, label }) => (
+ <MenuItem key={index} value={index}>
+ {label}
+ </MenuItem>
+ ))}
+ </Select>
+ );
+}
diff --git a/web/apps/photobook/src/components/BookTitleInput.tsx b/web/apps/photobook/src/components/BookTitleInput.tsx
new file mode 100644
index 0000000000..c90a08c71e
--- /dev/null
+++ b/web/apps/photobook/src/components/BookTitleInput.tsx
@@ -0,0 +1,88 @@
+import { useBook } from "@/context/book";
+import { headerButtonSx } from "@/theme/buttons";
+import { uiColors } from "@/theme/colors";
+import { Box } from "@mui/material";
+import { useEffect, useState } from "react";
+
+export default function BookTitleInput() {
+ const { book, setBook } = useBook();
+ const [title, setTitle] = useState(book.title ?? "");
+ const [focused, setFocused] = useState(false);
+ const placeholder = focused ? "" : "Book title (on spine)";
+
+ useEffect(() => {
+ if (!focused) setTitle(book.title ?? "");
+ }, [book.title, focused]);
+
+ return (
+ <Box
+ sx={{
+ position: "relative",
+ gridColumn: 2,
+ gridRow: 1,
+ justifySelf: "center",
+ width: "max-content",
+ maxWidth: { xs: "min(38vw, 160px)", md: "min(360px, 100%)" },
+ minWidth: 0,
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: 14,
+ fontWeight: 600,
+ lineHeight: "20px",
+ }}
+ >
+ <Box
+ component="span"
+ aria-hidden="true"
+ sx={{
+ display: "block",
+ visibility: "hidden",
+ whiteSpace: "pre",
+ overflow: "hidden",
+ minWidth: "calc(1ch + 34px)",
+ p: { xs: "8px 12px", sm: "9px 16px" },
+ border: "1px solid transparent",
+ }}
+ >
+ {title || placeholder || " "}
+ </Box>
+ <Box
+ component="input"
+ aria-label="Photobook title"
+ value={title}
+ placeholder={placeholder}
+ autoComplete="off"
+ onChange={(event) => setTitle(event.target.value)}
+ onFocus={() => setFocused(true)}
+ onBlur={() => {
+ setFocused(false);
+ if (title !== (book.title ?? "")) {
+ setBook((previous) => ({ ...previous, title }));
+ }
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") event.currentTarget.blur();
+ }}
+ sx={{
+ position: "absolute",
+ inset: 0,
+ width: "100%",
+ height: "100%",
+ minWidth: 0,
+ p: { xs: "8px 12px", sm: "9px 16px" },
+ font: "inherit",
+ color: uiColors.text,
+ textAlign: "center",
+ bgcolor: "#262626",
+ border: "1px solid transparent",
+ borderRadius: headerButtonSx.borderRadius,
+ outline: "none",
+ transition:
+ "background-color 120ms ease, border-color 120ms ease",
+ "&::placeholder": { color: uiColors.muted, opacity: 1 },
+ "&:hover": { bgcolor: "#2E2E2E", borderColor: "#484848" },
+ "&:focus": { bgcolor: "#2E2E2E", borderColor: "#707070" },
+ }}
+ />
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/BookViewer.tsx b/web/apps/photobook/src/components/BookViewer.tsx
new file mode 100644
index 0000000000..983601594d
--- /dev/null
+++ b/web/apps/photobook/src/components/BookViewer.tsx
@@ -0,0 +1,412 @@
+import { useBook } from "@/context/book";
+import { getPrintBinding } from "@/lib/printProducts";
+import { clipSoftcoverInsidePages } from "@/lib/softcoverPreview";
+import {
+ getFlipPageIndex,
+ getFlipPages,
+ getSpreadPageIndices,
+ getSpreads,
+} from "@/lib/spreads";
+import type { BookPage } from "@/lib/types";
+import { uiColors } from "@/theme/colors";
+import { Box, IconButton } from "@mui/material";
+import { PageFlip } from "page-flip";
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { createPortal } from "react-dom";
+import { Layer, Stage } from "react-konva";
+import BookPageNavigation from "./BookPageNavigation";
+import { ChevronLeftIcon, ChevronRightIcon } from "./icons";
+import PageCanvas from "./PageCanvas";
+
+const PAGE_NAVIGATION_SPACE = 72;
+
+const navigationButtonSx = {
+ position: "absolute",
+ top: 0,
+ transform: "translateY(-50%)",
+ pointerEvents: "auto",
+ width: { xs: 40, sm: 48 },
+ height: { xs: 40, sm: 48 },
+ color: uiColors.text,
+ bgcolor: uiColors.control,
+ "&:hover": { bgcolor: uiColors.controlHover },
+ "&.Mui-disabled": { opacity: 0.3 },
+} as const;
+
+export interface BookViewerHandle {
+ flipNext: () => void;
+ flipPrev: () => void;
+}
+
+interface BookViewerProps {
+ pages: BookPage[];
+ onSpreadChange: (spreadIndex: number) => void;
+}
+
+const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
+ function BookViewer({ pages, onSpreadChange }, ref) {
+ const { book: bookState, photoUrls, loadPreviews } = useBook();
+ const binding = getPrintBinding(bookState.printSelection);
+ const flipPages = useMemo(
+ () => getFlipPages(pages.length, binding),
+ [pages.length, binding],
+ );
+ const spreads = useMemo(
+ () => getSpreads(pages.length, binding),
+ [pages.length, binding],
+ );
+ const containerRef = useRef<HTMLDivElement>(null);
+ const mountRef = useRef<HTMLDivElement>(null);
+ const pageFlipRef = useRef<PageFlip | null>(null);
+ const [pageElements, setPageElements] = useState<HTMLElement[]>([]);
+ const [pageSize, setPageSize] = useState(1);
+ const [currentPage, setCurrentPage] = useState(0);
+ const [turning, setTurning] = useState(false);
+ const onSpreadChangeRef = useRef(onSpreadChange);
+ onSpreadChangeRef.current = onSpreadChange;
+ const startPageRef = useRef(0);
+
+ const allPhotoIds = useMemo(
+ () => [
+ ...new Set(
+ pages.flatMap((page) =>
+ page.slots.flatMap((slot) =>
+ slot.photoId ? [slot.photoId] : [],
+ ),
+ ),
+ ),
+ ],
+ [pages],
+ );
+ useEffect(() => {
+ if (allPhotoIds.length > 0)
+ void loadPreviews(allPhotoIds).catch((error: unknown) =>
+ console.error("Failed to load previews", error),
+ );
+ }, [allPhotoIds, loadPreviews]);
+
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ const measure = () => {
+ const { width, height } = container.getBoundingClientRect();
+ setPageSize(
+ Math.max(
+ 1,
+ Math.floor(
+ Math.min(
+ width / 2,
+ Math.max(1, height - PAGE_NAVIGATION_SPACE),
+ 1200,
+ ) * 0.768,
+ ),
+ ),
+ );
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, []);
+
+ const flipNext = useCallback(() => {
+ const book = pageFlipRef.current;
+ if (book?.getState() === "read") book.flipNext("bottom");
+ }, []);
+ const flipPrev = useCallback(() => {
+ const book = pageFlipRef.current;
+ if (book?.getState() === "read") book.flipPrev("bottom");
+ }, []);
+ useImperativeHandle(ref, () => ({ flipNext, flipPrev }), [
+ flipNext,
+ flipPrev,
+ ]);
+
+ const goToSpread = useCallback(
+ (spreadIndex: number) => {
+ const book = pageFlipRef.current;
+ const physicalIndex = flipPages.findIndex(
+ (page) => page.spreadIndex === spreadIndex,
+ );
+ if (book?.getState() === "read" && physicalIndex >= 0)
+ book.turnToPage(physicalIndex);
+ },
+ [flipPages],
+ );
+
+ useEffect(() => {
+ const mount = mountRef.current;
+ if (!mount || flipPages.length === 0) return;
+
+ const root = document.createElement("div");
+ root.className = "book-preview-root";
+ const elements = flipPages.map(({ pageIndex }, index) => {
+ const element = document.createElement("div");
+ element.className = "book-preview-page";
+ if (index > 0 && index < flipPages.length - 1) {
+ element.dataset.spineEdge =
+ index % 2 === 0 ? "left" : "right";
+ }
+ element.dataset.density =
+ binding === "Hardcover" &&
+ (index < 2 || index >= flipPages.length - 2)
+ ? "hard"
+ : "soft";
+ if (pageIndex === null)
+ element.setAttribute("aria-label", "Blank page (required)");
+ root.appendChild(element);
+ return element;
+ });
+ mount.appendChild(root);
+
+ const book = new PageFlip(root, {
+ width: 600,
+ height: 600,
+ size: "stretch",
+ minWidth: 1,
+ minHeight: 1,
+ maxWidth: 1200,
+ maxHeight: 1200,
+ autoSize: false,
+ showCover: true,
+ mobileScrollSupport: true,
+ flippingTime: 450,
+ useMouseEvents: true,
+ swipeDistance: 30,
+ startPage:
+ getFlipPageIndex(
+ pages.length,
+ Math.min(startPageRef.current, pages.length - 1),
+ binding,
+ ) ?? 0,
+ drawShadow: false,
+ showPageCorners: false,
+ usePortrait: false,
+ });
+ book.on("flip", (event: { data: number }) => {
+ startPageRef.current =
+ getSpreadPageIndices(
+ spreads[flipPages[event.data]?.spreadIndex ?? 0]!,
+ )[0] ??
+ (event.data < flipPages.length / 2 ? 0 : pages.length - 1);
+ setCurrentPage(event.data);
+ onSpreadChangeRef.current(
+ flipPages[event.data]?.spreadIndex ?? 0,
+ );
+ });
+ book.on("changeState", (event: { data: string }) => {
+ setTurning(event.data !== "read");
+ });
+ book.loadFromHTML(elements);
+ elements.forEach((element, index) =>
+ book
+ .getPage(index)
+ .setDensity(element.dataset.density as "hard" | "soft"),
+ );
+ const restoreCoverDrawing =
+ binding === "Softcover"
+ ? clipSoftcoverInsidePages(book)
+ : undefined;
+ book.update();
+ pageFlipRef.current = book;
+ setPageElements(elements);
+ setCurrentPage(book.getCurrentPageIndex());
+ setTurning(false);
+
+ return () => {
+ const index = book.getCurrentPageIndex();
+ startPageRef.current =
+ getSpreadPageIndices(
+ spreads[flipPages[index]?.spreadIndex ?? 0]!,
+ )[0] ??
+ (index < flipPages.length / 2 ? 0 : pages.length - 1);
+ pageFlipRef.current = null;
+ restoreCoverDrawing?.();
+ book.destroy();
+ };
+ }, [flipPages, spreads, binding, pages.length]);
+
+ useLayoutEffect(() => {
+ pageFlipRef.current?.update();
+ }, [pageSize]);
+
+ const frontCover = currentPage === 0 && flipPages.length > 1;
+ const backCover = currentPage === flipPages.length - 1;
+ const closed = frontCover || backCover;
+ const showSpread = !closed || turning;
+ const shift = turning ? 0 : frontCover ? "-25%" : backCover ? "25%" : 0;
+
+ return (
+ <Box
+ ref={containerRef}
+ data-binding={binding}
+ sx={{
+ flex: 1,
+ minWidth: 0,
+ minHeight: 0,
+ position: "relative",
+ mx: { xs: 0, sm: 7 },
+ my: 3,
+ "& .book-preview-root, & .book-preview-mount": {
+ width: "100%",
+ height: "100%",
+ },
+ "& .book-preview-page": {
+ backgroundColor: uiColors.paper,
+ overflow: "hidden",
+ "&[data-spine-edge]::after": {
+ content: '""',
+ position: "absolute",
+ top: 0,
+ bottom: 0,
+ width: 6,
+ zIndex: 1,
+ pointerEvents: "none",
+ },
+ '&[data-spine-edge="left"]::after': {
+ left: 0,
+ background:
+ "linear-gradient(to right, rgba(0, 0, 0, 0.09), transparent)",
+ },
+ '&[data-spine-edge="right"]::after': {
+ right: 0,
+ background:
+ "linear-gradient(to left, rgba(0, 0, 0, 0.09), transparent)",
+ },
+ },
+ }}
+ >
+ <Box
+ sx={{
+ position: "absolute",
+ left: "50%",
+ top: "50%",
+ width: pageSize * 2,
+ height: pageSize + PAGE_NAVIGATION_SPACE,
+ transform: "translate(-50%, -50%)",
+ }}
+ >
+ <Box
+ sx={{
+ width: "100%",
+ height: pageSize,
+ transform: `translateX(${shift})`,
+ transition: "transform 300ms ease",
+ "@media (prefers-reduced-motion: reduce)": {
+ transition: "none",
+ },
+ }}
+ >
+ <div ref={mountRef} className="book-preview-mount" />
+ </Box>
+ <Box
+ sx={{
+ position: "absolute",
+ left: "50%",
+ top: pageSize / 2,
+ width: showSpread ? "100%" : "50%",
+ height: 0,
+ transform: "translate(-50%, -50%)",
+ transition: "width 300ms ease",
+ "@media (prefers-reduced-motion: reduce)": {
+ transition: "none",
+ },
+ zIndex: 20,
+ pointerEvents: "none",
+ }}
+ >
+ <IconButton
+ aria-label="Previous pages"
+ onClick={flipPrev}
+ disabled={
+ currentPage === 0 ||
+ turning ||
+ flipPages.length === 0
+ }
+ sx={{
+ ...navigationButtonSx,
+ right: "100%",
+ mr: { xs: 1, sm: 3 },
+ }}
+ >
+ <ChevronLeftIcon
+ sx={{ fontSize: { xs: 28, sm: 32 } }}
+ />
+ </IconButton>
+ <IconButton
+ aria-label="Next pages"
+ onClick={flipNext}
+ disabled={
+ currentPage >= flipPages.length - 1 || turning
+ }
+ sx={{
+ ...navigationButtonSx,
+ left: "100%",
+ ml: { xs: 1, sm: 3 },
+ }}
+ >
+ <ChevronRightIcon
+ sx={{ fontSize: { xs: 28, sm: 32 } }}
+ />
+ </IconButton>
+ </Box>
+ <Box
+ sx={{
+ position: "absolute",
+ top: pageSize + 24,
+ left: "50%",
+ transform: "translateX(-50%)",
+ }}
+ >
+ <BookPageNavigation
+ pageCount={pages.length}
+ spreads={spreads}
+ spreadIndex={
+ flipPages[currentPage]?.spreadIndex ?? 0
+ }
+ disabled={pageElements.length === 0}
+ turning={turning}
+ onGoToSpread={goToSpread}
+ />
+ </Box>
+ </Box>
+ {flipPages.map(({ pageIndex, spreadIndex }, index) => {
+ const element = pageElements.at(index);
+ const page = pageIndex === null ? null : pages[pageIndex];
+ if (!element || !page) return null;
+ return createPortal(
+ <Stage
+ width={pageSize}
+ height={pageSize}
+ listening={false}
+ >
+ <Layer>
+ <PageCanvas
+ page={page}
+ photoUrls={photoUrls}
+ pageWidth={pageSize}
+ pageHeight={pageSize}
+ isBackCover={pageIndex === pages.length - 1}
+ isFrontCover={pageIndex === 0}
+ />
+ </Layer>
+ </Stage>,
+ element,
+ `${page.id}-${spreadIndex}`,
+ );
+ })}
+ </Box>
+ );
+ },
+);
+
+export default BookViewer;
diff --git a/web/apps/photobook/src/components/EditPage.tsx b/web/apps/photobook/src/components/EditPage.tsx
new file mode 100644
index 0000000000..2d2e0f1662
--- /dev/null
+++ b/web/apps/photobook/src/components/EditPage.tsx
@@ -0,0 +1,915 @@
+import { useBook } from "@/context/book";
+import { useAutoScroll } from "@/hooks/useAutoScroll";
+import { usePageDrag } from "@/hooks/usePageDrag";
+import { usePhotoDrag } from "@/hooks/usePhotoDrag";
+import { useSpreads } from "@/hooks/useSpreads";
+import type { PhotoDestination } from "@/lib/photoPlacement";
+import { getSpreadPageIndices } from "@/lib/spreads";
+import type { TextBlock } from "@/lib/types";
+import { toolbarColors, uiColors } from "@/theme/colors";
+import {
+ Alert,
+ Backdrop,
+ Box,
+ CircularProgress,
+ Snackbar,
+ Typography,
+} from "@mui/material";
+import React, {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type RefCallback,
+} from "react";
+import AddPageDialog from "./AddPageDialog";
+import AddPhotosDialog from "./AddPhotosDialog";
+import BookBindingSelect from "./BookBindingSelect";
+import BookHeader from "./BookHeader";
+import EditorActions, { EditorPreviewButton } from "./EditorActions";
+import EmptyBookState from "./EmptyBookState";
+import type { PageInsertPosition } from "./PageMenu";
+import PageStrip from "./PageStrip";
+import PrinterBlankPage from "./PrinterBlankPage";
+import SpreadPage, { PICKER_WIDTH } from "./SpreadPage";
+import {
+ EDITOR_CANVAS_PADDING,
+ EDITOR_PANEL_BOTTOM_INSET,
+ EDITOR_PANEL_INSET,
+ EDITOR_PANEL_SX,
+ EDITOR_SCROLLBAR_SX,
+ EDITOR_SIDEBAR_WIDTH,
+} from "./editorLayout";
+
+const PAGE_GAP = 2;
+const NEIGHBORHOOD_RADIUS = 4;
+
+export default function EditPage() {
+ const {
+ book,
+ currentSpreadIndex,
+ setCurrentSpreadIndex,
+ addPage,
+ addPhotos,
+ removeSlot,
+ updateTextBlock,
+ removeTextBlock,
+ undo,
+ redo,
+ processingPhotos,
+ processingProgress,
+ } = useBook();
+
+ const [selectedSlotId, setSelectedSlotId] = useState<string | null>(null);
+ const [selectedPageId, setSelectedPageId] = useState<string | null>(null);
+ const [selectedTextId, setSelectedTextId] = useState<string | null>(null);
+
+ const [editingTextId, setEditingTextId] = useState<string | null>(null);
+ const [insertedPageId, setInsertedPageId] = useState<string | null>(null);
+ const [addPageDialogOpen, setAddPageDialogOpen] = useState(false);
+ const [pendingFiles, setPendingFiles] = useState<File[] | null>(null);
+ const [photoImportError, setPhotoImportError] = useState<string | null>(
+ null,
+ );
+ const [showPhotoImportProgress, setShowPhotoImportProgress] =
+ useState(false);
+ const pagePhotoImportBusy =
+ processingPhotos && !pendingFiles && book.pages.length > 0;
+
+ useEffect(() => {
+ if (!pagePhotoImportBusy) {
+ setShowPhotoImportProgress(false);
+ return;
+ }
+ const timeout = window.setTimeout(
+ () => setShowPhotoImportProgress(true),
+ 300,
+ );
+ return () => window.clearTimeout(timeout);
+ }, [pagePhotoImportBusy]);
+
+ const containerRef = useRef<HTMLDivElement>(null);
+ const photoInputRef = useRef<HTMLInputElement>(null);
+ const photoDestinationRef = useRef<string | undefined>(undefined);
+
+ const [containerWidth, setContainerWidth] = useState(0);
+
+ const pages = book.pages;
+ const totalPages = pages.length;
+
+ const autoScroll = useAutoScroll(containerRef);
+ const photoDrag = usePhotoDrag(containerRef, autoScroll);
+ const pageDrag = usePageDrag();
+
+ const spreads = useSpreads(pages.length);
+
+ const currentSpreadRow = useMemo(() => {
+ const idx = spreads.findIndex(
+ (s) =>
+ s.left === currentSpreadIndex || s.right === currentSpreadIndex,
+ );
+ return idx >= 0 ? idx : 0;
+ }, [spreads, currentSpreadIndex]);
+
+ const [visibleSpreads, setVisibleSpreads] = useState<Set<number>>(
+ () => new Set([0, 1, 2]),
+ );
+ const spreadElsRef = useRef<Map<number, Element>>(new Map());
+ const observerRef = useRef<IntersectionObserver | null>(null);
+
+ useEffect(() => {
+ const root = containerRef.current;
+ if (!root) return;
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ setVisibleSpreads((prev) => {
+ const next = new Set(prev);
+ for (const entry of entries) {
+ const idx = Number(
+ (entry.target as HTMLElement).dataset.spreadIndex,
+ );
+ if (!isNaN(idx)) {
+ if (entry.isIntersecting) next.add(idx);
+ else next.delete(idx);
+ }
+ }
+ if (
+ next.size === prev.size &&
+ [...next].every((v) => prev.has(v))
+ )
+ return prev;
+ return next;
+ });
+ },
+ { root, rootMargin: "2000px 0px" },
+ );
+ observerRef.current = observer;
+
+ spreadElsRef.current.forEach((el) => observer.observe(el));
+
+ return () => {
+ observer.disconnect();
+ observerRef.current = null;
+ };
+ }, [spreads.length]);
+
+ const spreadRefCallback = useCallback(
+ (idx: number): RefCallback<HTMLDivElement> =>
+ (el) => {
+ const prev = spreadElsRef.current.get(idx);
+ if (prev && observerRef.current)
+ observerRef.current.unobserve(prev);
+
+ if (el) {
+ spreadElsRef.current.set(idx, el);
+ if (observerRef.current) observerRef.current.observe(el);
+ } else {
+ spreadElsRef.current.delete(idx);
+ }
+ },
+ [],
+ );
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const target = e.target;
+ if (
+ e.defaultPrevented ||
+ e.isComposing ||
+ processingPhotos ||
+ (target instanceof HTMLElement &&
+ (target.isContentEditable ||
+ target.closest(
+ 'input, textarea, select, [role="textbox"], [role="dialog"], [role="menu"], [role="listbox"], [role="combobox"]',
+ )))
+ )
+ return;
+ if (
+ (e.key === "Delete" || e.key === "Backspace") &&
+ !e.metaKey &&
+ !e.ctrlKey &&
+ !e.altKey &&
+ !e.shiftKey &&
+ !e.repeat
+ ) {
+ const slot = pages
+ .find((page) => page.id === selectedPageId)
+ ?.slots.find((slot) => slot.id === selectedSlotId);
+ if (selectedPageId && slot?.photoId) {
+ e.preventDefault();
+ removeSlot(selectedPageId, slot.id);
+ setSelectedSlotId(null);
+ setSelectedPageId(null);
+ setSelectedTextId(null);
+ setEditingTextId(null);
+ }
+ return;
+ }
+ if ((e.metaKey || e.ctrlKey) && e.key === "z") {
+ e.preventDefault();
+ if (e.shiftKey) {
+ redo();
+ } else {
+ undo();
+ }
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [
+ undo,
+ redo,
+ processingPhotos,
+ pages,
+ selectedPageId,
+ selectedSlotId,
+ removeSlot,
+ ]);
+
+ useLayoutEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const measureWidth = () => setContainerWidth(el.clientWidth);
+ measureWidth();
+ const observer = new ResizeObserver(measureWidth);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ const { pageWidth, pageHeight } = useMemo(() => {
+ const availW =
+ containerWidth -
+ EDITOR_CANVAS_PADDING * 2 -
+ PAGE_GAP -
+ PICKER_WIDTH * 2;
+ const size = Math.round(Math.max(200, Math.min(availW / 2, 500)));
+
+ return { pageWidth: size, pageHeight: size };
+ }, [containerWidth]);
+
+ const scrollRafRef = useRef<number | null>(null);
+ const handleMainScroll = useCallback(() => {
+ if (scrollRafRef.current !== null) return;
+ scrollRafRef.current = requestAnimationFrame(() => {
+ scrollRafRef.current = null;
+ const main = containerRef.current;
+ if (!main) return;
+
+ const maxMainScroll = main.scrollHeight - main.clientHeight;
+ if (maxMainScroll <= 0) return;
+
+ const fraction = main.scrollTop / maxMainScroll;
+
+ const visibleIdx = Math.round(
+ fraction * Math.max(0, spreads.length - 1),
+ );
+ const spread = spreads.at(visibleIdx);
+ if (spread) {
+ const newIndex =
+ getSpreadPageIndices(spread)[0] ??
+ (visibleIdx < spreads.length / 2 ? 0 : pages.length - 1);
+ if (newIndex !== currentSpreadIndex) {
+ setCurrentSpreadIndex(newIndex);
+ }
+ }
+ });
+ }, [spreads, currentSpreadIndex, setCurrentSpreadIndex, pages.length]);
+
+ useEffect(() => {
+ return () => {
+ if (scrollRafRef.current !== null) {
+ cancelAnimationFrame(scrollRafRef.current);
+ scrollRafRef.current = null;
+ }
+ };
+ }, []);
+
+ const handleSidebarSpreadClick = useCallback((spreadIdx: number) => {
+ const main = containerRef.current;
+ if (!main) return;
+ const spreadEl = main.querySelector(
+ `[data-spread-index="${spreadIdx}"]`,
+ );
+ if (spreadEl) {
+ spreadEl.scrollIntoView({ behavior: "smooth", block: "center" });
+ }
+ }, []);
+
+ const handleSlotClick = useCallback((pageId: string, slotId: string) => {
+ setSelectedSlotId(slotId);
+ setSelectedPageId(pageId);
+ setSelectedTextId(null);
+ }, []);
+
+ const handleTextClick = useCallback((pageId: string, textId: string) => {
+ setSelectedTextId(textId);
+ setSelectedPageId(pageId);
+ setSelectedSlotId(null);
+ }, []);
+
+ const handleTextDblClick = useCallback((pageId: string, textId: string) => {
+ setEditingTextId(textId);
+ setSelectedTextId(textId);
+ setSelectedPageId(pageId);
+ }, []);
+
+ const clearSelection = useCallback(() => {
+ setSelectedSlotId(null);
+ setSelectedPageId(null);
+ setSelectedTextId(null);
+ setEditingTextId(null);
+ }, []);
+
+ const handleWorkspaceClick = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!(e.target as Element).closest("[data-book-page]"))
+ clearSelection();
+ },
+ [clearSelection],
+ );
+
+ const handleInsertPage = useCallback(
+ (pageIndex: number, position: PageInsertPosition) => {
+ clearSelection();
+ const pageId = addPage(
+ position === "before" ? pageIndex - 1 : pageIndex,
+ );
+ setInsertedPageId(pageId);
+ },
+ [addPage, clearSelection],
+ );
+
+ const handleAddPhotos = useCallback(
+ (pageId?: string) => {
+ const input = photoInputRef.current;
+ if (!input || processingPhotos) return;
+ setPhotoImportError(null);
+ photoDestinationRef.current = pageId;
+ input.multiple = !pageId || pageId !== pages[0]?.id;
+ input.click();
+ },
+ [pages, processingPhotos],
+ );
+
+ const importPhotos = useCallback(
+ async (files: File[], destination: PhotoDestination) => {
+ const pageId = await addPhotos(files, {
+ replace: pages.length === 0,
+ destination,
+ });
+ clearSelection();
+ if (pageId) setInsertedPageId(pageId);
+ },
+ [addPhotos, pages.length, clearSelection],
+ );
+
+ useEffect(() => {
+ if (!insertedPageId) return;
+ const pageIndex = pages.findIndex((page) => page.id === insertedPageId);
+ if (pageIndex < 0) return;
+ const spreadIndex = spreads.findIndex(
+ (spread) => spread.left === pageIndex || spread.right === pageIndex,
+ );
+ const row = containerRef.current?.querySelector(
+ `[data-spread-index="${spreadIndex}"]`,
+ );
+ if (!row) return;
+ setCurrentSpreadIndex(pageIndex);
+ row.scrollIntoView({ behavior: "smooth", block: "center" });
+ setInsertedPageId(null);
+ }, [insertedPageId, pages, spreads, setCurrentSpreadIndex]);
+
+ const handleTextUpdate = useCallback(
+ (pageId: string, blockId: string, updates: Partial<TextBlock>) => {
+ updateTextBlock(pageId, blockId, updates);
+ },
+ [updateTextBlock],
+ );
+
+ const handleTextDelete = useCallback(
+ (pageId: string, blockId: string) => {
+ removeTextBlock(pageId, blockId);
+ setSelectedTextId(null);
+ setEditingTextId(null);
+ },
+ [removeTextBlock],
+ );
+
+ const handleTextEditEnd = useCallback(() => {
+ setEditingTextId(null);
+ }, []);
+
+ return (
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ height: "100dvh",
+ px: EDITOR_PANEL_INSET,
+ bgcolor: uiColors.background,
+ }}
+ >
+ <BookHeader showBookControls={pages.length > 0}>
+ <BookBindingSelect />
+ <EditorPreviewButton />
+ </BookHeader>
+
+ <Box
+ sx={{
+ display: "flex",
+ flex: 1,
+ minHeight: 0,
+ gap: EDITOR_PANEL_INSET,
+ mb: EDITOR_PANEL_BOTTOM_INSET,
+ }}
+ >
+ <Box
+ component="aside"
+ id="book-pages-sidebar"
+ aria-label="Book pages"
+ sx={{
+ ...EDITOR_PANEL_SX,
+ borderRadius: "20px",
+ width: EDITOR_SIDEBAR_WIDTH,
+ display: pages.length > 0 ? "flex" : "none",
+ flexDirection: "column",
+ flexShrink: 0,
+ overflow: "hidden",
+ }}
+ >
+ <PageStrip onSpreadClick={handleSidebarSpreadClick} />
+ </Box>
+
+ <Box
+ component="main"
+ aria-label="Photobook editor"
+ sx={{
+ ...EDITOR_PANEL_SX,
+ bgcolor:
+ pages.length > 0
+ ? EDITOR_PANEL_SX.bgcolor
+ : "transparent",
+ borderRadius: "20px",
+ flex: 1,
+ minWidth: 0,
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ }}
+ >
+ <Box
+ ref={containerRef}
+ onScroll={handleMainScroll}
+ onClick={handleWorkspaceClick}
+ onDragOver={
+ pages.length > 0
+ ? photoDrag.handleContainerDragOver
+ : undefined
+ }
+ onDragEnd={photoDrag.handleDragEnd}
+ sx={{
+ flex: 1,
+ minWidth: 0,
+ minHeight: 0,
+ display: "flex",
+ flexDirection: "column",
+ overflow: "auto",
+ scrollbarGutter:
+ pages.length > 0 ? "stable" : "auto",
+ ...EDITOR_SCROLLBAR_SX,
+ }}
+ >
+ {pages.length === 0 ? (
+ <EmptyBookState />
+ ) : (
+ containerWidth > 0 && (
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ px: `${EDITOR_CANVAS_PADDING}px`,
+ pt: 4,
+ pb: {
+ xs: "calc(144px + env(safe-area-inset-bottom))",
+ sm: "calc(96px + env(safe-area-inset-bottom))",
+ },
+ gap: 3,
+ }}
+ >
+ {spreads.map((spread, spreadIdx) => {
+ const isVisible =
+ visibleSpreads.has(spreadIdx) ||
+ Math.abs(
+ spreadIdx - currentSpreadRow,
+ ) <= NEIGHBORHOOD_RADIUS;
+ const leftIndex =
+ typeof spread.left === "number"
+ ? spread.left
+ : null;
+ const rightIndex =
+ typeof spread.right === "number"
+ ? spread.right
+ : null;
+ const lp =
+ leftIndex !== null
+ ? pages[leftIndex]
+ : null;
+ const rp =
+ rightIndex !== null
+ ? pages[rightIndex]
+ : null;
+
+ return (
+ <Box
+ key={spreadIdx}
+ ref={spreadRefCallback(
+ spreadIdx,
+ )}
+ data-spread-index={spreadIdx}
+ sx={{
+ display: "flex",
+ gap: `${PAGE_GAP}px`,
+ alignItems: "start",
+ width:
+ PICKER_WIDTH +
+ pageWidth * 2 +
+ PAGE_GAP +
+ PICKER_WIDTH,
+ justifyContent:
+ spread.left !== null
+ ? "flex-start"
+ : "flex-end",
+ minHeight: pageHeight,
+ }}
+ >
+ {isVisible &&
+ spread.left ===
+ "printer-blank" && (
+ <Box
+ sx={{
+ pl: `${PICKER_WIDTH}px`,
+ }}
+ >
+ <PrinterBlankPage
+ width={
+ pageWidth
+ }
+ height={
+ pageHeight
+ }
+ showLabel
+ />
+ </Box>
+ )}
+ {isVisible && lp && (
+ <SpreadPage
+ page={lp}
+ pageIndex={leftIndex!}
+ pickerSide="left"
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ totalPages={totalPages}
+ selectedSlotId={
+ selectedSlotId
+ }
+ selectedPageId={
+ selectedPageId
+ }
+ selectedTextId={
+ selectedTextId
+ }
+ editingTextId={
+ editingTextId
+ }
+ onSlotClick={
+ handleSlotClick
+ }
+ onTextClick={
+ handleTextClick
+ }
+ onTextDblClick={
+ handleTextDblClick
+ }
+ onTextUpdate={
+ handleTextUpdate
+ }
+ onTextDelete={
+ handleTextDelete
+ }
+ onTextEditEnd={
+ handleTextEditEnd
+ }
+ onClearSelection={
+ clearSelection
+ }
+ onInsertPage={
+ handleInsertPage
+ }
+ onAddPhotos={
+ handleAddPhotos
+ }
+ dragSourceInfo={
+ photoDrag.dragSourceInfo
+ }
+ dragOverInfo={
+ photoDrag.dragOverInfo
+ }
+ dragOverPageId={
+ photoDrag.dragOverPageId
+ }
+ onPhotoDragStart={
+ photoDrag.handleDragStart
+ }
+ onSlotDragOver={
+ photoDrag.handleSlotDragOver
+ }
+ onPhotoDrop={
+ photoDrag.handleDrop
+ }
+ onPhotoDragEnd={
+ photoDrag.handleDragEnd
+ }
+ onPageDragOver={
+ photoDrag.handlePageDragOver
+ }
+ onPageDrop={
+ photoDrag.handlePageDrop
+ }
+ pageDragSource={
+ pageDrag.pageDragSource
+ }
+ pageDragTarget={
+ pageDrag.pageDragTarget
+ }
+ pageDragSourceRef={
+ pageDrag.pageDragSourceRef
+ }
+ onPageDragStart={
+ pageDrag.handlePageDragStart
+ }
+ onPageDragOverPage={
+ pageDrag.handlePageDragOverPage
+ }
+ onPageDropOnPage={
+ pageDrag.handlePageDropOnPage
+ }
+ onPageDragEndCleanup={
+ pageDrag.handlePageDragEndCleanup
+ }
+ />
+ )}
+ {isVisible && rp && (
+ <SpreadPage
+ page={rp}
+ pageIndex={rightIndex!}
+ pickerSide="right"
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ totalPages={totalPages}
+ selectedSlotId={
+ selectedSlotId
+ }
+ selectedPageId={
+ selectedPageId
+ }
+ selectedTextId={
+ selectedTextId
+ }
+ editingTextId={
+ editingTextId
+ }
+ onSlotClick={
+ handleSlotClick
+ }
+ onTextClick={
+ handleTextClick
+ }
+ onTextDblClick={
+ handleTextDblClick
+ }
+ onTextUpdate={
+ handleTextUpdate
+ }
+ onTextDelete={
+ handleTextDelete
+ }
+ onTextEditEnd={
+ handleTextEditEnd
+ }
+ onClearSelection={
+ clearSelection
+ }
+ onInsertPage={
+ handleInsertPage
+ }
+ onAddPhotos={
+ handleAddPhotos
+ }
+ dragSourceInfo={
+ photoDrag.dragSourceInfo
+ }
+ dragOverInfo={
+ photoDrag.dragOverInfo
+ }
+ dragOverPageId={
+ photoDrag.dragOverPageId
+ }
+ onPhotoDragStart={
+ photoDrag.handleDragStart
+ }
+ onSlotDragOver={
+ photoDrag.handleSlotDragOver
+ }
+ onPhotoDrop={
+ photoDrag.handleDrop
+ }
+ onPhotoDragEnd={
+ photoDrag.handleDragEnd
+ }
+ onPageDragOver={
+ photoDrag.handlePageDragOver
+ }
+ onPageDrop={
+ photoDrag.handlePageDrop
+ }
+ pageDragSource={
+ pageDrag.pageDragSource
+ }
+ pageDragTarget={
+ pageDrag.pageDragTarget
+ }
+ pageDragSourceRef={
+ pageDrag.pageDragSourceRef
+ }
+ onPageDragStart={
+ pageDrag.handlePageDragStart
+ }
+ onPageDragOverPage={
+ pageDrag.handlePageDragOverPage
+ }
+ onPageDropOnPage={
+ pageDrag.handlePageDropOnPage
+ }
+ onPageDragEndCleanup={
+ pageDrag.handlePageDragEndCleanup
+ }
+ />
+ )}
+ {isVisible &&
+ spread.right ===
+ "printer-blank" && (
+ <Box
+ sx={{
+ pr: `${PICKER_WIDTH}px`,
+ }}
+ >
+ <PrinterBlankPage
+ width={
+ pageWidth
+ }
+ height={
+ pageHeight
+ }
+ showLabel
+ />
+ </Box>
+ )}
+ </Box>
+ );
+ })}
+ </Box>
+ )
+ )}
+ </Box>
+ </Box>
+ </Box>
+
+ <Box
+ component="nav"
+ aria-label="Photobook tools"
+ sx={{
+ ...EDITOR_PANEL_SX,
+ "--toolbar-radius": "20px",
+ "--toolbar-inset": "6px",
+ bgcolor: toolbarColors.background,
+ display: pages.length > 0 ? "block" : "none",
+ position: "fixed",
+ left: "50%",
+ bottom: "calc(20px + env(safe-area-inset-bottom))",
+ transform: "translateX(-50%)",
+ width: "max-content",
+ maxWidth: "calc(100% - 32px)",
+ p: "var(--toolbar-inset)",
+ borderRadius: "var(--toolbar-radius)",
+ zIndex: 1200,
+ boxShadow: `inset 0 0 0 1px ${toolbarColors.border}, 0 8px 24px rgba(0,0,0,0.3)`,
+ }}
+ >
+ <EditorActions
+ onAddPage={() => setAddPageDialogOpen(true)}
+ onAddPhotos={() => handleAddPhotos()}
+ />
+ </Box>
+
+ <input
+ ref={photoInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/heic,image/heif,.heic,.heif"
+ multiple
+ style={{ display: "none" }}
+ onChange={async (event) => {
+ const files = Array.from(event.currentTarget.files ?? []);
+ const pageId = photoDestinationRef.current;
+ event.currentTarget.value = "";
+ if (files.length === 0) return;
+ if (!pageId) {
+ setPendingFiles(files);
+ return;
+ }
+ try {
+ await importPhotos(files, { kind: "page", pageId });
+ } catch (error) {
+ setPhotoImportError(
+ error instanceof Error
+ ? error.message
+ : "Couldn't add these photos. Please try again.",
+ );
+ }
+ }}
+ />
+ {pendingFiles && (
+ <AddPhotosDialog
+ pages={pages}
+ photoCount={pendingFiles.length}
+ busy={processingPhotos}
+ progress={processingProgress}
+ onClose={() => setPendingFiles(null)}
+ onAdd={(destination) =>
+ importPhotos(pendingFiles, destination)
+ }
+ />
+ )}
+ <Backdrop
+ open={pagePhotoImportBusy}
+ invisible={!showPhotoImportProgress}
+ transitionDuration={0}
+ sx={{ zIndex: (theme) => theme.zIndex.modal + 1 }}
+ >
+ {pagePhotoImportBusy && showPhotoImportProgress && (
+ <Box
+ role="status"
+ aria-live="polite"
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ gap: 2,
+ bgcolor: uiColors.surface,
+ color: uiColors.text,
+ p: 3,
+ borderRadius: 3,
+ }}
+ >
+ <CircularProgress size={24} sx={{ color: "#08C225" }} />
+ <Typography>
+ {"Adding photos… "}
+ {processingProgress}%
+ </Typography>
+ </Box>
+ )}
+ </Backdrop>
+ <Snackbar
+ open={!!photoImportError}
+ onClose={() => setPhotoImportError(null)}
+ anchorOrigin={{ vertical: "top", horizontal: "center" }}
+ >
+ <Alert
+ severity="error"
+ onClose={() => setPhotoImportError(null)}
+ >
+ {photoImportError}
+ </Alert>
+ </Snackbar>
+
+ {addPageDialogOpen && (
+ <AddPageDialog
+ pages={pages}
+ initialPageId={
+ selectedPageId ?? pages[currentSpreadIndex]?.id
+ }
+ disabled={processingPhotos}
+ onClose={() => setAddPageDialogOpen(false)}
+ onInsert={handleInsertPage}
+ />
+ )}
+
+ <canvas
+ ref={photoDrag.dragGhostRef}
+ style={{ position: "fixed", left: -9999 }}
+ />
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/EditorActions.tsx b/web/apps/photobook/src/components/EditorActions.tsx
new file mode 100644
index 0000000000..adbfe600e6
--- /dev/null
+++ b/web/apps/photobook/src/components/EditorActions.tsx
@@ -0,0 +1,260 @@
+import { useBook } from "@/context/book";
+import { normalizeBookPages } from "@/lib/bookPages";
+import {
+ getBindingPrintSelection,
+ getPrintBinding,
+ getPrintExportError,
+ getPrintProduct,
+} from "@/lib/printProducts";
+import {
+ accentGreen,
+ accentGreenHover,
+ editorToolbarButtonSx,
+ headerButtonSx,
+} from "@/theme/buttons";
+import { toolbarColors, uiColors } from "@/theme/colors";
+import {
+ dialogActionSx,
+ dialogCloseButtonSx,
+ dialogDescriptionSx,
+ dialogHeaderSx,
+ dialogPaperSx,
+ dialogTitleSx,
+} from "@/theme/dialogs";
+import { Box, Button, Dialog, IconButton, Typography } from "@mui/material";
+import { useId, useState } from "react";
+import EditorIconButton from "./EditorIconButton";
+import {
+ AddPageIcon,
+ AddPhotosIcon,
+ CloseIcon,
+ InfoIcon,
+ PreviewIcon,
+ RedoIcon,
+ UndoIcon,
+} from "./icons";
+import ResetBookButton from "./ResetBookButton";
+
+export default function EditorActions({
+ onAddPage,
+ onAddPhotos,
+}: {
+ onAddPage: () => void;
+ onAddPhotos: () => void;
+}) {
+ const { book, processingPhotos, undo, redo, canUndo, canRedo } = useBook();
+
+ return (
+ <Box
+ role="group"
+ aria-label="Editing tools"
+ sx={{
+ display: "flex",
+ flexWrap: "wrap",
+ minWidth: 0,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: "var(--toolbar-inset)",
+ "& .MuiButton-root, & .MuiIconButton-root": {
+ height: 40,
+ borderRadius:
+ "calc(var(--toolbar-radius) - var(--toolbar-inset))",
+ },
+ "& .MuiButton-root": {
+ px: "16px",
+ "& .MuiButton-startIcon": { mr: "8px" },
+ },
+ "& .MuiIconButton-root": { width: 40, minWidth: 40 },
+ }}
+ >
+ <Button
+ startIcon={<AddPhotosIcon />}
+ onClick={onAddPhotos}
+ disabled={processingPhotos}
+ sx={editorToolbarButtonSx}
+ >
+ Add photos
+ </Button>
+ <Button
+ startIcon={<AddPageIcon />}
+ onClick={onAddPage}
+ disabled={processingPhotos || book.pages.length < 2}
+ sx={editorToolbarButtonSx}
+ >
+ Add page
+ </Button>
+ <Box
+ role="group"
+ aria-label="Edit history"
+ sx={{
+ display: "flex",
+ gap: "var(--toolbar-inset)",
+ pl: "var(--toolbar-inset)",
+ borderLeft: `1px solid ${toolbarColors.border}`,
+ }}
+ >
+ <EditorIconButton
+ label="Undo"
+ onClick={undo}
+ disabled={!canUndo || processingPhotos}
+ >
+ <UndoIcon />
+ </EditorIconButton>
+ <EditorIconButton
+ label="Redo"
+ onClick={redo}
+ disabled={!canRedo || processingPhotos}
+ >
+ <RedoIcon />
+ </EditorIconButton>
+ </Box>
+ <Box
+ sx={{
+ pl: "var(--toolbar-inset)",
+ borderLeft: `1px solid ${toolbarColors.border}`,
+ }}
+ >
+ <ResetBookButton />
+ </Box>
+ </Box>
+ );
+}
+
+export function EditorPreviewButton() {
+ const { book, setAppView, processingPhotos } = useBook();
+ const [validationError, setValidationError] = useState<{
+ title: string;
+ description: string;
+ } | null>(null);
+ const [validationOpen, setValidationOpen] = useState(false);
+ const id = useId();
+ const closeValidation = () => setValidationOpen(false);
+
+ const handlePreview = () => {
+ const selection = getBindingPrintSelection(
+ getPrintBinding(book.printSelection),
+ );
+ const pageCount = normalizeBookPages(book.pages).length;
+ const error = getPrintExportError(selection, pageCount);
+ if (error) {
+ const { minPages, maxPages } = getPrintProduct(
+ selection.productId,
+ )!;
+ if (pageCount < minPages) {
+ const missing = minPages - pageCount;
+ setValidationError({
+ title: `Add ${missing} more ${missing === 1 ? "page" : "pages"}`,
+ description: `Printed books need at least ${minPages} pages, including the covers.`,
+ });
+ } else if (pageCount > maxPages) {
+ const extra = pageCount - maxPages;
+ setValidationError({
+ title: `Remove ${extra} ${extra === 1 ? "page" : "pages"}`,
+ description: `Printed books can have up to ${maxPages} pages, including the covers.`,
+ });
+ } else {
+ setValidationError({
+ title: "Update your book",
+ description: error,
+ });
+ }
+ setValidationOpen(true);
+ return;
+ }
+ setAppView("results");
+ };
+
+ return (
+ <>
+ <Button
+ variant="contained"
+ aria-label="Preview"
+ startIcon={<PreviewIcon strokeWidth={2.2} />}
+ onClick={handlePreview}
+ disabled={processingPhotos || book.pages.length === 0}
+ sx={{ ...headerButtonSx, fontWeight: 700 }}
+ >
+ <Box
+ component="span"
+ sx={{ display: { xs: "none", sm: "inline" } }}
+ >
+ Preview
+ </Box>
+ </Button>
+ <Dialog
+ open={validationOpen}
+ onClose={closeValidation}
+ maxWidth={false}
+ aria-labelledby={`${id}-title`}
+ aria-describedby={`${id}-description`}
+ slotProps={{
+ paper: { sx: dialogPaperSx },
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.5)" } },
+ }}
+ >
+ <Box sx={{ position: "relative", p: "48px 16px 16px" }}>
+ <IconButton
+ aria-label="Close"
+ onClick={closeValidation}
+ sx={dialogCloseButtonSx}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "16px",
+ }}
+ >
+ <Box
+ aria-hidden="true"
+ sx={{
+ width: 126,
+ height: 121,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ mb: "8px",
+ color: uiColors.muted,
+ }}
+ >
+ <InfoIcon sx={{ fontSize: 72 }} />
+ </Box>
+ <Box sx={dialogHeaderSx}>
+ <Typography
+ component="h2"
+ id={`${id}-title`}
+ sx={dialogTitleSx}
+ >
+ {validationError?.title}
+ </Typography>
+ <Typography
+ id={`${id}-description`}
+ sx={{ ...dialogDescriptionSx, px: 4 }}
+ >
+ {validationError?.description}
+ </Typography>
+ </Box>
+ <Button
+ variant="contained"
+ fullWidth
+ disableElevation
+ autoFocus
+ onClick={closeValidation}
+ sx={{
+ ...dialogActionSx,
+ color: "#FFFFFF",
+ bgcolor: accentGreen,
+ "&:hover": { bgcolor: accentGreenHover },
+ }}
+ >
+ Back to editing
+ </Button>
+ </Box>
+ </Box>
+ </Dialog>
+ </>
+ );
+}
diff --git a/web/apps/photobook/src/components/EditorIconButton.tsx b/web/apps/photobook/src/components/EditorIconButton.tsx
new file mode 100644
index 0000000000..ddd2af2143
--- /dev/null
+++ b/web/apps/photobook/src/components/EditorIconButton.tsx
@@ -0,0 +1,35 @@
+import { editorToolbarButtonSx } from "@/theme/buttons";
+import { Box, IconButton, Tooltip } from "@mui/material";
+import type { ReactNode } from "react";
+
+export default function EditorIconButton({
+ label,
+ onClick,
+ disabled = false,
+ children,
+}: {
+ label: string;
+ onClick: () => void;
+ disabled?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <Tooltip title={label} enterDelay={400}>
+ <Box component="span" sx={{ display: "inline-flex" }}>
+ <IconButton
+ aria-label={label}
+ onClick={onClick}
+ disabled={disabled}
+ sx={{
+ ...editorToolbarButtonSx,
+ width: 44,
+ p: 0,
+ "& .MuiSvgIcon-root": { fontSize: 20 },
+ }}
+ >
+ {children}
+ </IconButton>
+ </Box>
+ </Tooltip>
+ );
+}
diff --git a/web/apps/photobook/src/components/EmptyBookState.tsx b/web/apps/photobook/src/components/EmptyBookState.tsx
new file mode 100644
index 0000000000..fda730f5ca
--- /dev/null
+++ b/web/apps/photobook/src/components/EmptyBookState.tsx
@@ -0,0 +1,269 @@
+import { usePhotoImport } from "@/hooks/usePhotoImport";
+import {
+ accentGreen,
+ editorButtonSx,
+ editorToolbarButtonSx,
+} from "@/theme/buttons";
+import { uiColors } from "@/theme/colors";
+import {
+ Alert,
+ Box,
+ Button,
+ InputBase,
+ LinearProgress,
+ Typography,
+} from "@mui/material";
+import { AddPhotosIcon, LinkIcon } from "./icons";
+
+export default function EmptyBookState() {
+ const {
+ fileInputRef,
+ dragOver,
+ enteUrl,
+ setEnteUrl,
+ enteError,
+ importError,
+ processingPhotos,
+ processingProgress,
+ processingMessage,
+ handleImportEnte,
+ handleFiles,
+ handleDrop,
+ handleDragOver,
+ handleDragLeave,
+ } = usePhotoImport();
+
+ return (
+ <Box
+ onDrop={processingPhotos ? undefined : handleDrop}
+ onDragOver={processingPhotos ? undefined : handleDragOver}
+ onDragLeave={(event) => {
+ if (
+ !event.currentTarget.contains(
+ event.relatedTarget as Node | null,
+ )
+ )
+ handleDragLeave();
+ }}
+ sx={{
+ flex: 1,
+ minHeight: "min-content",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ px: 2,
+ py: 5,
+ }}
+ >
+ <Box sx={{ width: "100%", maxWidth: 480 }}>
+ {processingPhotos ? (
+ <Box
+ role="status"
+ aria-live="polite"
+ sx={{ py: 5, textAlign: "center" }}
+ >
+ <Typography
+ sx={{ fontSize: 18, fontWeight: 600, mb: 3 }}
+ >
+ {processingMessage}
+ </Typography>
+ <LinearProgress
+ variant="determinate"
+ value={processingProgress}
+ aria-label="Import progress"
+ sx={{
+ height: 5,
+ borderRadius: 3,
+ bgcolor: uiColors.control,
+ "& .MuiLinearProgress-bar": { borderRadius: 3 },
+ }}
+ />
+ <Typography
+ sx={{ fontSize: 13, color: uiColors.muted, mt: 2 }}
+ >
+ {processingProgress}%
+ </Typography>
+ </Box>
+ ) : (
+ <>
+ <Typography
+ component="h1"
+ sx={{
+ fontSize: { xs: 28, sm: 32 },
+ lineHeight: 1.25,
+ fontWeight: 600,
+ letterSpacing: "-0.8px",
+ mb: 4,
+ textAlign: "center",
+ }}
+ >
+ Create your photobook
+ </Typography>
+ <Box
+ component="form"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (enteUrl.trim()) void handleImportEnte();
+ }}
+ >
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ gap: { xs: 1, sm: 1.5 },
+ p: "6px",
+ pl: { xs: "12px", sm: "18px" },
+ borderRadius: "20px",
+ border: `1px solid ${enteError ? uiColors.danger : "#414141"}`,
+ bgcolor: "#242424",
+ transition:
+ "border-color 120ms ease, background-color 120ms ease",
+ "&:hover": { borderColor: "#626262" },
+ "&:focus-within": {
+ borderColor: accentGreen,
+ },
+ }}
+ >
+ <LinkIcon
+ aria-hidden="true"
+ sx={{
+ fontSize: 22,
+ color: uiColors.muted,
+ flexShrink: 0,
+ }}
+ />
+ <InputBase
+ id="empty-book-album-url"
+ placeholder="Paste an Ente Photos album link"
+ value={enteUrl}
+ onChange={(event) =>
+ setEnteUrl(event.target.value)
+ }
+ error={Boolean(enteError)}
+ autoComplete="off"
+ inputProps={{
+ "aria-label": "Ente Photos album link",
+ inputMode: "url",
+ spellCheck: false,
+ "aria-describedby": enteError
+ ? "empty-book-import-error"
+ : undefined,
+ }}
+ sx={{
+ flex: 1,
+ minWidth: 0,
+ fontSize: { xs: 14, sm: 15 },
+ "& input": { py: 1.5 },
+ "& input::placeholder": {
+ color: uiColors.muted,
+ opacity: 1,
+ },
+ }}
+ />
+ <Button
+ type="submit"
+ variant="contained"
+ disabled={!enteUrl.trim()}
+ sx={{
+ ...editorButtonSx,
+ height: 46,
+ px: { xs: 2, sm: 3 },
+ fontWeight: 700,
+ flexShrink: 0,
+ borderRadius: "13px",
+ }}
+ >
+ Import
+ </Button>
+ </Box>
+ {enteError && (
+ <Alert
+ id="empty-book-import-error"
+ severity="error"
+ sx={{ mt: 2, borderRadius: "14px" }}
+ >
+ {enteError}
+ </Alert>
+ )}
+ </Box>
+ <Typography
+ sx={{
+ my: 2.5,
+ fontSize: 12,
+ lineHeight: "18px",
+ color: "#808080",
+ textAlign: "center",
+ }}
+ >
+ or
+ </Typography>
+ <Box
+ role="group"
+ aria-label="Add or drop photos"
+ sx={{
+ textAlign: "center",
+ p: 3,
+ borderRadius: "20px",
+ minHeight: 300,
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ border: `1px dashed ${dragOver ? accentGreen : "#484848"}`,
+ bgcolor: dragOver ? "#1B2A1D" : "transparent",
+ transition:
+ "border-color 120ms ease, background-color 120ms ease",
+ }}
+ >
+ <Button
+ startIcon={
+ <AddPhotosIcon sx={{ fontSize: 20 }} />
+ }
+ onClick={() => fileInputRef.current?.click()}
+ sx={{
+ ...editorToolbarButtonSx,
+ borderRadius: "14px",
+ px: 2,
+ }}
+ >
+ Add photos
+ </Button>
+ <Typography
+ sx={{
+ mt: 1.5,
+ fontSize: 12,
+ lineHeight: "18px",
+ color: dragOver ? uiColors.text : "#898989",
+ }}
+ >
+ {dragOver
+ ? "Drop photos here"
+ : "or drop photos here"}
+ </Typography>
+ </Box>
+ {importError && (
+ <Alert
+ severity="error"
+ sx={{ mt: 2, borderRadius: "14px" }}
+ >
+ {importError}
+ </Alert>
+ )}
+ </>
+ )}
+ </Box>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/heic,image/heif,.heic,.heif"
+ multiple
+ style={{ display: "none" }}
+ onChange={(event) => {
+ if (event.currentTarget.files)
+ void handleFiles(event.currentTarget.files);
+ event.currentTarget.value = "";
+ }}
+ />
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/EntePasswordDialog.tsx b/web/apps/photobook/src/components/EntePasswordDialog.tsx
new file mode 100644
index 0000000000..efc702a467
--- /dev/null
+++ b/web/apps/photobook/src/components/EntePasswordDialog.tsx
@@ -0,0 +1,77 @@
+import {
+ Button,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogTitle,
+ TextField,
+ Typography,
+} from "@mui/material";
+
+interface EntePasswordDialogProps {
+ open: boolean;
+ password: string;
+ onPasswordChange: (v: string) => void;
+ onSubmit: () => void;
+ onCancel: () => void;
+}
+
+export default function EntePasswordDialog({
+ open,
+ password,
+ onPasswordChange,
+ onSubmit,
+ onCancel,
+}: EntePasswordDialogProps) {
+ return (
+ <Dialog open={open} onClose={onCancel} maxWidth="xs" fullWidth>
+ <DialogTitle
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ fontWeight: 700,
+ }}
+ >
+ Album password
+ </DialogTitle>
+ <DialogContent>
+ <Typography
+ sx={{ color: "text.secondary", mb: 2, fontSize: "0.95rem" }}
+ >
+ This album is password-protected. Enter the password shared
+ with you.
+ </Typography>
+ <TextField
+ autoFocus
+ fullWidth
+ variant="outlined"
+ type="password"
+ placeholder="Password"
+ value={password}
+ onChange={(e) => onPasswordChange(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ onSubmit();
+ }
+ }}
+ />
+ </DialogContent>
+ <DialogActions sx={{ px: 3, pb: 2 }}>
+ <Button onClick={onCancel} sx={{ color: "text.secondary" }}>
+ Cancel
+ </Button>
+ <Button
+ onClick={onSubmit}
+ variant="contained"
+ sx={{
+ background: "#08C225",
+ fontWeight: 700,
+ "&:hover": { background: "#07AE22" },
+ }}
+ >
+ Unlock
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
+}
diff --git a/web/apps/photobook/src/components/ImportProgress.tsx b/web/apps/photobook/src/components/ImportProgress.tsx
new file mode 100644
index 0000000000..e31107e124
--- /dev/null
+++ b/web/apps/photobook/src/components/ImportProgress.tsx
@@ -0,0 +1,137 @@
+import { usePhotoImport } from "@/hooks/usePhotoImport";
+import { editorButtonSx, secondaryButtonSx } from "@/theme/buttons";
+import { uiColors } from "@/theme/colors";
+import {
+ Alert,
+ Box,
+ Button,
+ LinearProgress,
+ TextField,
+ Typography,
+} from "@mui/material";
+import BookHeader from "./BookHeader";
+import { EDITOR_PANEL_INSET } from "./editorLayout";
+
+export default function ImportProgress() {
+ const {
+ importing,
+ processingProgress,
+ processingMessage,
+ enteUrl,
+ setEnteUrl,
+ enteError,
+ importError,
+ retryImport,
+ dismissImport,
+ } = usePhotoImport();
+
+ return (
+ <Box
+ sx={{
+ minHeight: "100dvh",
+ display: "flex",
+ flexDirection: "column",
+ px: EDITOR_PANEL_INSET,
+ pb: EDITOR_PANEL_INSET,
+ bgcolor: uiColors.background,
+ }}
+ >
+ <BookHeader showBookControls={false}>{null}</BookHeader>
+ <Box
+ sx={{
+ flex: 1,
+ display: "grid",
+ placeItems: "center",
+ px: 2,
+ py: 5,
+ }}
+ >
+ <Box sx={{ width: "100%", maxWidth: 400, textAlign: "center" }}>
+ {importing ? (
+ <>
+ <Typography
+ component="h1"
+ sx={{ fontSize: 22, fontWeight: 600, mb: 3 }}
+ >
+ {processingMessage}
+ </Typography>
+ <LinearProgress
+ variant="determinate"
+ value={processingProgress}
+ aria-label="Import progress"
+ sx={{
+ height: 6,
+ borderRadius: 3,
+ bgcolor: "#303030",
+ "& .MuiLinearProgress-bar": {
+ borderRadius: 3,
+ },
+ }}
+ />
+ <Typography
+ sx={{
+ color: uiColors.muted,
+ fontSize: 14,
+ fontVariantNumeric: "tabular-nums",
+ mt: 1.5,
+ }}
+ >
+ {processingProgress}%
+ </Typography>
+ </>
+ ) : (
+ <>
+ <Typography
+ component="h1"
+ sx={{ fontSize: 24, fontWeight: 600, mb: 2 }}
+ >
+ Couldn’t import your photos
+ </Typography>
+ <Alert
+ severity="error"
+ sx={{
+ textAlign: "left",
+ borderRadius: "14px",
+ mb: 2,
+ }}
+ >
+ {enteError || importError}
+ </Alert>
+ {enteError && (
+ <TextField
+ fullWidth
+ label="Ente album link"
+ value={enteUrl}
+ onChange={(event) =>
+ setEnteUrl(event.target.value)
+ }
+ sx={{ mb: 2 }}
+ />
+ )}
+ <Box sx={{ display: "flex", gap: 1 }}>
+ <Button
+ fullWidth
+ onClick={dismissImport}
+ sx={secondaryButtonSx}
+ >
+ Back
+ </Button>
+ <Button
+ fullWidth
+ variant="contained"
+ onClick={() => {
+ void retryImport();
+ }}
+ disabled={!!enteError && !enteUrl.trim()}
+ sx={editorButtonSx}
+ >
+ Try again
+ </Button>
+ </Box>
+ </>
+ )}
+ </Box>
+ </Box>
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/LayoutPicker.tsx b/web/apps/photobook/src/components/LayoutPicker.tsx
new file mode 100644
index 0000000000..c9bf39c56c
--- /dev/null
+++ b/web/apps/photobook/src/components/LayoutPicker.tsx
@@ -0,0 +1,155 @@
+import {
+ getMirrorVariant,
+ getVariantPreview,
+ getVariantsForCount,
+ type LayoutVariant,
+} from "@/lib/layouts";
+import { thumbnailShadow, uiColors } from "@/theme/colors";
+import { Box } from "@mui/material";
+import { useMemo } from "react";
+
+const THUMB_W = 44;
+
+interface LayoutPickerProps {
+ photoCount: number;
+ currentVariant?: string;
+ thumbnailUrls: string[];
+ onSelect: (variantKey: string) => void;
+ isFrontCover?: boolean;
+}
+
+function VariantThumbnail({
+ variant,
+ isActive,
+ thumbnailUrls,
+ onClick,
+}: {
+ variant: LayoutVariant;
+ isActive: boolean;
+ thumbnailUrls: string[];
+ onClick: () => void;
+}) {
+ const slots = useMemo(() => getVariantPreview(variant.key), [variant.key]);
+ const isFullBleed = variant.key === "1-full";
+
+ return (
+ <Box
+ onClick={(e) => {
+ e.stopPropagation();
+ onClick();
+ }}
+ sx={{
+ width: THUMB_W,
+ height: THUMB_W,
+ bgcolor: uiColors.paper,
+ borderRadius: 0.5,
+ position: "relative",
+ overflow: "hidden",
+ cursor: "pointer",
+ flexShrink: 0,
+ boxShadow: thumbnailShadow,
+ outline: isActive
+ ? "2px solid #08C225"
+ : "2px solid transparent",
+ transition: "outline-color 0.15s",
+ "&:hover": {
+ outline: isActive
+ ? "2px solid #08C225"
+ : `2px solid ${uiColors.muted}`,
+ },
+ }}
+ >
+ {slots.map((slot, i) => {
+ const url = thumbnailUrls[i];
+ const GAP = isFullBleed ? 0 : 1.5;
+ const left = (slot.x / 100) * THUMB_W + GAP;
+ const top = (slot.y / 100) * THUMB_W + GAP;
+ const width = (slot.width / 100) * THUMB_W - GAP * 2;
+ const height = (slot.height / 100) * THUMB_W - GAP * 2;
+ return (
+ <Box
+ key={i}
+ sx={{
+ position: "absolute",
+ left: `${left}px`,
+ top: `${top}px`,
+ width: `${width}px`,
+ height: `${height}px`,
+ bgcolor: url ? undefined : "#b0b0b0",
+ borderRadius: isFullBleed ? 0 : "1px",
+ overflow: "hidden",
+ }}
+ >
+ {url && (
+ <img
+ src={url}
+ alt=""
+ style={{
+ width: "100%",
+ height: "100%",
+ objectFit: "cover",
+ display: "block",
+ }}
+ />
+ )}
+ </Box>
+ );
+ })}
+ </Box>
+ );
+}
+
+export default function LayoutPicker({
+ photoCount,
+ currentVariant,
+ thumbnailUrls,
+ onSelect,
+ isFrontCover = false,
+}: LayoutPickerProps) {
+ const variants = useMemo(
+ () =>
+ getVariantsForCount(photoCount, isFrontCover).filter(
+ (variant) => !isFrontCover || variant.key !== "1-moderate",
+ ),
+ [photoCount, isFrontCover],
+ );
+
+ if (variants.length === 0) return null;
+
+ return (
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: 1,
+ alignItems: "center",
+ }}
+ >
+ {variants.map((v) => {
+ const mirrorOfCurrent = currentVariant
+ ? getMirrorVariant(currentVariant)
+ : undefined;
+ const isActive =
+ v.key === currentVariant || v.key === mirrorOfCurrent;
+ return (
+ <VariantThumbnail
+ key={v.key}
+ variant={v}
+ isActive={isActive}
+ thumbnailUrls={thumbnailUrls}
+ onClick={() => {
+ if (isActive) {
+ const mirror = getMirrorVariant(
+ currentVariant!,
+ );
+ if (mirror) onSelect(mirror);
+ } else {
+ onSelect(v.key);
+ }
+ }}
+ />
+ );
+ })}
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/NavBar.tsx b/web/apps/photobook/src/components/NavBar.tsx
new file mode 100644
index 0000000000..d4d593f7a1
--- /dev/null
+++ b/web/apps/photobook/src/components/NavBar.tsx
@@ -0,0 +1,227 @@
+import { Box } from "@mui/material";
+import { useEffect, useState } from "react";
+import { CloseIcon, MenuIcon } from "./icons";
+
+const mobileNavQuery = "(max-width: 640px)";
+
+interface NavItem {
+ label: string;
+ href: string;
+}
+
+const navItems: NavItem[] = [
+ { label: "Home", href: "https://ente.com/" },
+ { label: "About", href: "https://ente.com/about" },
+ { label: "Blog", href: "https://ente.com/blog" },
+ { label: "Download", href: "https://ente.com/download" },
+];
+
+export default function NavBar() {
+ const [isMobileNav, setIsMobileNav] = useState(
+ () =>
+ typeof window !== "undefined" &&
+ window.matchMedia(mobileNavQuery).matches,
+ );
+ const [isNavOpen, setIsNavOpen] = useState(false);
+
+ useEffect(() => {
+ const mql = window.matchMedia(mobileNavQuery);
+ const handler = (e: MediaQueryListEvent) => setIsMobileNav(e.matches);
+ setIsMobileNav(mql.matches);
+ mql.addEventListener("change", handler);
+ return () => mql.removeEventListener("change", handler);
+ }, []);
+
+ useEffect(() => {
+ if (!isMobileNav) setIsNavOpen(false);
+ }, [isMobileNav]);
+
+ useEffect(() => {
+ if (!isNavOpen) return;
+ const handler = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setIsNavOpen(false);
+ };
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, [isNavOpen]);
+
+ const closeNav = () => {
+ if (isMobileNav) setIsNavOpen(false);
+ };
+
+ return (
+ <Box
+ component="header"
+ sx={{
+ position: "fixed",
+ top: 0,
+ left: 0,
+ right: 0,
+ zIndex: 50,
+ p: { xs: "16px", sm: "28px 24px" },
+ }}
+ >
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: isNavOpen ? "stretch" : "center",
+ flexDirection: isNavOpen ? "column" : "row",
+ justifyContent: "space-between",
+ gap: isNavOpen ? "14px" : "18px",
+ padding: isNavOpen ? "18px" : "14px 18px",
+ border: "1px solid rgba(21, 21, 21, 0.08)",
+ borderRadius: isNavOpen ? "28px" : "999px",
+ background: "rgba(255, 255, 255, 0.76)",
+ backdropFilter: "blur(28px)",
+ boxShadow: "0 20px 48px rgba(18, 18, 18, 0.07)",
+ maxWidth: 1100,
+ mx: "auto",
+ animation:
+ "navSlideIn 0.45s cubic-bezier(0.22, 1, 0.36, 1)",
+ "@keyframes navSlideIn": {
+ from: { opacity: 0, transform: "translateY(-16px)" },
+ to: { opacity: 1, transform: "translateY(0)" },
+ },
+ }}
+ >
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: isMobileNav
+ ? "space-between"
+ : "flex-start",
+ width: isMobileNav ? "100%" : "auto",
+ gap: "12px",
+ }}
+ >
+ <Box
+ component="a"
+ href="https://ente.com/"
+ target="_blank"
+ rel="noopener"
+ onClick={closeNav}
+ sx={{
+ display: "inline-flex",
+ alignItems: "center",
+ ml: isMobileNav ? 0 : "10px",
+ minHeight: isMobileNav ? 40 : "auto",
+ cursor: "pointer",
+ textDecoration: "none",
+ }}
+ >
+ <Box
+ component="img"
+ alt="Ente"
+ src="/ente-branding.svg"
+ sx={{
+ display: "block",
+ width: "auto",
+ height: { xs: "21.6px", sm: "25.2px" },
+ }}
+ />
+ </Box>
+
+ {isMobileNav && (
+ <Box
+ component="button"
+ onClick={() => setIsNavOpen((c) => !c)}
+ aria-label={
+ isNavOpen
+ ? "Close navigation menu"
+ : "Open navigation menu"
+ }
+ aria-expanded={isNavOpen}
+ sx={{
+ display: "inline-flex",
+ width: 44,
+ minHeight: 44,
+ p: 0,
+ border: "1px solid rgba(21, 21, 21, 0.08)",
+ borderRadius: "14px",
+ background: "rgba(255, 255, 255, 0.62)",
+ color: "rgba(21, 21, 21, 0.84)",
+ alignItems: "center",
+ justifyContent: "center",
+ cursor: "pointer",
+ transition:
+ "transform 220ms ease, border-color 220ms ease, background 220ms ease",
+ "&:hover": {
+ transform: "translateY(-1px)",
+ borderColor: "rgba(21, 21, 21, 0.14)",
+ background: "rgba(255, 255, 255, 0.78)",
+ },
+ }}
+ >
+ {isNavOpen ? <CloseIcon /> : <MenuIcon />}
+ </Box>
+ )}
+ </Box>
+
+ {(!isMobileNav || isNavOpen) && (
+ <Box
+ component="nav"
+ aria-label="Primary"
+ sx={{
+ display: isMobileNav ? "grid" : "flex",
+ gridTemplateColumns: isMobileNav
+ ? "1fr"
+ : undefined,
+ flexWrap: "wrap",
+ justifyContent: isMobileNav
+ ? undefined
+ : "flex-end",
+ gap: isMobileNav ? "8px" : "10px",
+ width: isMobileNav ? "100%" : "auto",
+ }}
+ >
+ {navItems.map((item) => (
+ <Box
+ key={item.label}
+ component="a"
+ href={item.href}
+ target="_blank"
+ rel="noopener"
+ onClick={closeNav}
+ sx={{
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: isMobileNav
+ ? "flex-start"
+ : "center",
+ minHeight: isMobileNav ? 44 : 42,
+ px: isMobileNav ? "16px" : "18px",
+ borderRadius: "999px",
+ border: "1px solid",
+ borderColor: isMobileNav
+ ? "rgba(21, 21, 21, 0.06)"
+ : "transparent",
+ background: isMobileNav
+ ? "rgba(255, 255, 255, 0.52)"
+ : "transparent",
+ color: "rgba(21, 21, 21, 0.76)",
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: "0.92rem",
+ fontWeight: 500,
+ letterSpacing: 0,
+ textDecoration: "none",
+ textAlign: isMobileNav ? "left" : "center",
+ transition:
+ "transform 220ms ease, border-color 220ms ease, background 220ms ease, color 220ms ease",
+ "&:hover": {
+ transform: "translateY(-1px)",
+ borderColor: "rgba(21, 21, 21, 0.08)",
+ background: "rgba(255, 255, 255, 0.65)",
+ color: "#151515",
+ },
+ }}
+ >
+ {item.label}
+ </Box>
+ ))}
+ </Box>
+ )}
+ </Box>
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/PageCanvas.tsx b/web/apps/photobook/src/components/PageCanvas.tsx
new file mode 100644
index 0000000000..58f994b83b
--- /dev/null
+++ b/web/apps/photobook/src/components/PageCanvas.tsx
@@ -0,0 +1,481 @@
+import { useBook } from "@/context/book";
+import {
+ getCachedImage,
+ getCachedUrl,
+ loadImageCached,
+} from "@/lib/imageCache";
+import {
+ CAPTION_FONT_WEIGHT,
+ CENTER_TEXT_FONT_WEIGHT,
+ getBrandingLayout,
+ getCaptionLayout,
+ getCenterTextLayout,
+ getInterFont,
+ getOutfitFont,
+ getTextBlockLayout,
+ SAFE_AREA,
+ TEXT_LINE_HEIGHT,
+ type CaptionLayout,
+} from "@/lib/printLayout";
+import type { BookPage, PhotoSlot, TextBlock } from "@/lib/types";
+import Konva from "konva";
+import { useEffect, useMemo, useState } from "react";
+import { Group, Image as KonvaImage, Rect, Text } from "react-konva";
+
+export type CaptionPosition = "top" | "bottom";
+
+interface PageCanvasProps {
+ page: BookPage;
+ pageWidth: number;
+ pageHeight: number;
+ isBackCover?: boolean;
+ isFrontCover?: boolean;
+ photoUrls?: Map<string, string>;
+ onSlotClick?: (slotId: string) => void;
+ selectedSlotId?: string | null;
+ selectedTextId?: string | null;
+ editingTextId?: string | null;
+ editingCaption?: CaptionPosition | null;
+ hideCaptions?: boolean;
+ hideCenterText?: boolean;
+ dragOverSlotId?: string | null;
+ dragSourceSlotId?: string | null;
+}
+
+function PhotoSlotRenderer({
+ slot,
+ pageWidth,
+ pageHeight,
+ photoUrl,
+ isSelected,
+ isDragOver,
+ isDragSource,
+ onClick,
+}: {
+ slot: PhotoSlot;
+ pageWidth: number;
+ pageHeight: number;
+ photoUrl?: string;
+ isSelected: boolean;
+ isDragOver: boolean;
+ isDragSource: boolean;
+ onClick: () => void;
+}) {
+ const photoId = slot.photoId;
+ const [image, setImage] = useState<HTMLImageElement | null>(() =>
+ photoId ? getCachedImage(photoId) : null,
+ );
+
+ const sx = (slot.x / 100) * pageWidth;
+ const sy = (slot.y / 100) * pageHeight;
+ const sw = (slot.width / 100) * pageWidth;
+ const sh = (slot.height / 100) * pageHeight;
+
+ useEffect(() => {
+ if (!photoId || !photoUrl) {
+ setImage(null);
+ return;
+ }
+ const cached = getCachedImage(photoId);
+ if (cached) setImage(cached);
+
+ if (cached && getCachedUrl(photoId) === photoUrl) return;
+
+ let cancelled = false;
+ loadImageCached(photoId, photoUrl)
+ .then((img) => {
+ if (!cancelled) setImage(img);
+ })
+ .catch(() => {
+ if (!cancelled && !cached) setImage(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [photoId, photoUrl]);
+
+ const clipFunc = (ctx: Konva.Context) => {
+ ctx.rect(sx, sy, sw, sh);
+ };
+
+ const drawProps = useMemo(() => {
+ if (!image) return null;
+ const imgAspect = image.naturalWidth / image.naturalHeight;
+ const slotAspect = sw / sh;
+
+ let drawW: number, drawH: number;
+ if (imgAspect > slotAspect) {
+ drawH = sh * slot.cropZoom;
+ drawW = drawH * imgAspect;
+ } else {
+ drawW = sw * slot.cropZoom;
+ drawH = drawW / imgAspect;
+ }
+
+ const drawX = sx + (sw - drawW) * slot.cropX;
+ const drawY = sy + (sh - drawH) * slot.cropY;
+
+ return { x: drawX, y: drawY, width: drawW, height: drawH };
+ }, [image, sx, sy, sw, sh, slot.cropX, slot.cropY, slot.cropZoom]);
+
+ return (
+ <Group clipFunc={clipFunc}>
+ <Rect
+ x={sx}
+ y={sy}
+ width={sw}
+ height={sh}
+ fill="#EEEEF0"
+ onClick={onClick}
+ onTap={onClick}
+ />
+ {image && drawProps && (
+ <KonvaImage
+ image={image}
+ x={drawProps.x}
+ y={drawProps.y}
+ width={drawProps.width}
+ height={drawProps.height}
+ listening={false}
+ />
+ )}
+ {isDragSource && (
+ <Rect
+ x={sx}
+ y={sy}
+ width={sw}
+ height={sh}
+ fill="rgba(255, 255, 255, 0.5)"
+ listening={false}
+ />
+ )}
+ {isDragOver && !isDragSource && (
+ <Rect
+ x={sx}
+ y={sy}
+ width={sw}
+ height={sh}
+ stroke="#08C225"
+ strokeWidth={2}
+ dash={[6, 3]}
+ fill="rgba(8, 194, 37, 0.1)"
+ listening={false}
+ />
+ )}
+ {isSelected && !isDragSource && (
+ <Rect
+ x={sx}
+ y={sy}
+ width={sw}
+ height={sh}
+ stroke="#08C225"
+ strokeWidth={4}
+ listening={false}
+ />
+ )}
+ {!image && !slot.photoId && (
+ <Text
+ x={sx}
+ y={sy + sh / 2 - 8}
+ width={sw}
+ text={isDragOver ? "Drop here" : "Empty slot"}
+ fontSize={12}
+ fontFamily={getInterFont()}
+ fill={isDragOver ? "#08C225" : "#999"}
+ fontStyle={isDragOver ? "bold" : "normal"}
+ align="center"
+ />
+ )}
+ </Group>
+ );
+}
+
+function TextBlockRenderer({
+ block,
+ pageWidth,
+ pageHeight,
+ isSelected,
+ isEditing,
+}: {
+ block: TextBlock;
+ pageWidth: number;
+ pageHeight: number;
+ isSelected: boolean;
+ isEditing: boolean;
+}) {
+ const layout = getTextBlockLayout(block);
+ const bx = (layout.x / 100) * pageWidth;
+ const by = (layout.y / 100) * pageHeight;
+ const bw = (layout.width / 100) * pageWidth;
+ const bh = (layout.height / 100) * pageHeight;
+
+ const fontSize = pageHeight * (layout.fontSize / 100);
+ const color = block.color ?? "#555555";
+ const rotation = layout.rotation;
+
+ if (isEditing) return null;
+
+ const displayText = block.text || (isSelected ? "" : "Type here");
+ const displayColor = block.text ? color : "#bbb";
+
+ return (
+ <Group x={bx} y={by} rotation={rotation}>
+ <Text
+ x={(layout.padding / 100) * pageWidth}
+ y={0}
+ text={displayText}
+ fontSize={fontSize}
+ fontFamily={getInterFont()}
+ fontStyle="bold"
+ fill={displayColor}
+ lineHeight={TEXT_LINE_HEIGHT}
+ verticalAlign="middle"
+ wrap="none"
+ listening={false}
+ />
+ {isSelected && (
+ <Rect
+ x={-3}
+ y={-3}
+ width={bw + 6}
+ height={bh + 6}
+ stroke="#08C225"
+ strokeWidth={3}
+ listening={false}
+ />
+ )}
+ </Group>
+ );
+}
+
+function EnteBranding({
+ pageWidth,
+ pageHeight,
+}: {
+ pageWidth: number;
+ pageHeight: number;
+}) {
+ const [logo, setLogo] = useState<HTMLCanvasElement | null>(null);
+
+ useEffect(() => {
+ const img = new window.Image();
+ img.onload = () => {
+ const targetH = Math.round(
+ pageHeight * 0.031 * (window.devicePixelRatio || 1),
+ );
+ const targetW = Math.round(
+ (img.naturalWidth / img.naturalHeight) * targetH,
+ );
+ const offscreen = document.createElement("canvas");
+ offscreen.width = targetW;
+ offscreen.height = targetH;
+ const ctx = offscreen.getContext("2d")!;
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(img, 0, 0, targetW, targetH);
+ setLogo(offscreen);
+ };
+ img.src = "/ente-branding.svg";
+ }, [pageHeight]);
+
+ const layout = getBrandingLayout();
+
+ return (
+ <>
+ {logo && (
+ <KonvaImage
+ image={logo}
+ x={(layout.x / 100) * pageWidth}
+ y={(layout.y / 100) * pageHeight}
+ width={(layout.width / 100) * pageWidth}
+ height={(layout.height / 100) * pageHeight}
+ listening={false}
+ />
+ )}
+ </>
+ );
+}
+
+function CaptionText({
+ text,
+ layout,
+ pageWidth,
+ pageHeight,
+ isEditing,
+ lineHeight = TEXT_LINE_HEIGHT,
+ fontFamily = getInterFont(),
+ fontWeight = CAPTION_FONT_WEIGHT,
+}: {
+ text: string;
+ layout: CaptionLayout | null;
+ pageWidth: number;
+ pageHeight: number;
+ isEditing?: boolean;
+ lineHeight?: number;
+ fontFamily?: string;
+ fontWeight?: number;
+}) {
+ if (isEditing) return null;
+ if (!text) return null;
+ if (!layout) return null;
+ const x = (layout.x / 100) * pageWidth;
+ const y = (layout.y / 100) * pageHeight;
+ const width = (layout.width / 100) * pageWidth;
+ const height = (layout.height / 100) * pageHeight;
+ return (
+ <Group clipX={x} clipY={y} clipWidth={width} clipHeight={height}>
+ <Text
+ x={x}
+ y={y}
+ width={width}
+ height={height}
+ text={text}
+ fontSize={(layout.fontSize / 100) * pageHeight}
+ lineHeight={lineHeight}
+ wrap="none"
+ fontFamily={fontFamily}
+ fontStyle={String(fontWeight)}
+ fill="#2a2a2a"
+ align="center"
+ verticalAlign="middle"
+ />
+ </Group>
+ );
+}
+
+export default function PageCanvas({
+ page,
+ pageWidth,
+ pageHeight,
+ isBackCover = false,
+ isFrontCover = false,
+ selectedSlotId,
+ selectedTextId,
+ dragOverSlotId,
+ dragSourceSlotId,
+ onSlotClick,
+ editingTextId,
+ editingCaption,
+ hideCaptions = false,
+ hideCenterText = false,
+ photoUrls: photoUrlsProp,
+}: PageCanvasProps) {
+ const { thumbnailUrls } = useBook();
+ const urls = photoUrlsProp ?? thumbnailUrls;
+
+ const [, setFontsReady] = useState(false);
+ useEffect(() => {
+ let active = true;
+ void document.fonts.ready.then(() => {
+ if (active) setFontsReady(true);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+ const topCaption = getCaptionLayout(page, "top", isFrontCover);
+ const bottomCaption = getCaptionLayout(page, "bottom", isFrontCover);
+ const centerText = getCenterTextLayout(page);
+
+ return (
+ <>
+ <Rect
+ x={0}
+ y={0}
+ width={pageWidth}
+ height={pageHeight}
+ fill="#ffffff"
+ listening={false}
+ />
+
+ {page.slots.map((slot) => (
+ <PhotoSlotRenderer
+ key={slot.id}
+ slot={slot}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ photoUrl={slot.photoId ? urls.get(slot.photoId) : undefined}
+ isSelected={selectedSlotId === slot.id}
+ isDragOver={dragOverSlotId === slot.id}
+ isDragSource={dragSourceSlotId === slot.id}
+ onClick={() => onSlotClick?.(slot.id)}
+ />
+ ))}
+
+ {!hideCenterText && page.centerText && (
+ <CaptionText
+ text={centerText?.lines.join("\n") ?? ""}
+ layout={centerText}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ lineHeight={centerText?.lineHeight}
+ fontFamily={getOutfitFont()}
+ fontWeight={CENTER_TEXT_FONT_WEIGHT}
+ />
+ )}
+ {!hideCaptions && (
+ <CaptionText
+ text={page.topCaption}
+ layout={topCaption}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ isEditing={editingCaption === "top"}
+ fontFamily={isFrontCover ? getOutfitFont() : getInterFont()}
+ fontWeight={
+ isFrontCover
+ ? CENTER_TEXT_FONT_WEIGHT
+ : CAPTION_FONT_WEIGHT
+ }
+ />
+ )}
+ {isBackCover ? (
+ <EnteBranding pageWidth={pageWidth} pageHeight={pageHeight} />
+ ) : (
+ !hideCaptions && (
+ <CaptionText
+ text={page.bottomCaption}
+ layout={bottomCaption}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ isEditing={editingCaption === "bottom"}
+ fontFamily={
+ isFrontCover ? getOutfitFont() : getInterFont()
+ }
+ fontWeight={
+ isFrontCover
+ ? CENTER_TEXT_FONT_WEIGHT
+ : CAPTION_FONT_WEIGHT
+ }
+ />
+ )
+ )}
+
+ <Group
+ clipX={(SAFE_AREA.x / 100) * pageWidth}
+ clipY={(SAFE_AREA.y / 100) * pageHeight}
+ clipWidth={(SAFE_AREA.width / 100) * pageWidth}
+ clipHeight={(SAFE_AREA.height / 100) * pageHeight}
+ >
+ {page.textBlocks.map((block) => (
+ <TextBlockRenderer
+ key={block.id}
+ block={block}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ isSelected={selectedTextId === block.id}
+ isEditing={editingTextId === block.id}
+ />
+ ))}
+ </Group>
+
+ <Text
+ x={pageWidth - 30}
+ y={pageHeight - 18}
+ text=""
+ fontSize={8}
+ fill="#ccc"
+ fontFamily={getInterFont()}
+ />
+ </>
+ );
+}
diff --git a/web/apps/photobook/src/components/PageMenu.tsx b/web/apps/photobook/src/components/PageMenu.tsx
new file mode 100644
index 0000000000..69c914a78a
--- /dev/null
+++ b/web/apps/photobook/src/components/PageMenu.tsx
@@ -0,0 +1,226 @@
+import { MAX_PAGE_PHOTOS } from "@/lib/photoPlacement";
+import { pageMenuColors, popupShadow, uiColors } from "@/theme/colors";
+import { IconButton, Menu, MenuItem } from "@mui/material";
+import { useState } from "react";
+import {
+ AddPageIcon,
+ AddPhotosIcon,
+ DeleteIcon,
+ EditPhotoIcon,
+ MoreIcon,
+} from "./icons";
+import RequiredPageDialog from "./RequiredPageDialog";
+
+export type PageInsertPosition = "before" | "after";
+
+const menuItemSx = {
+ alignItems: "center",
+ borderRadius: "10px",
+ color: pageMenuColors.text,
+ display: "flex",
+ gap: "8px",
+ minHeight: 36,
+ px: "9px",
+ py: "4px",
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ whiteSpace: "nowrap",
+ transition: "background-color 120ms ease, color 120ms ease",
+ "& .MuiSvgIcon-root": { color: pageMenuColors.icon },
+ "&:hover, &.Mui-focusVisible": {
+ bgcolor: pageMenuColors.hover,
+ "& .MuiSvgIcon-root": { color: pageMenuColors.text },
+ },
+ "&:active": { bgcolor: pageMenuColors.active },
+};
+
+interface PageMenuProps {
+ pageId: string;
+ pageIndex: number;
+ totalPages: number;
+ side: "left" | "right";
+ photoCount: number;
+ requiredBlank: boolean;
+ onAddPhotos: () => void;
+ onInsert: (position: PageInsertPosition) => void;
+ onDelete: () => void;
+}
+
+export default function PageMenu({
+ pageId,
+ pageIndex,
+ totalPages,
+ side,
+ photoCount,
+ requiredBlank,
+ onAddPhotos,
+ onInsert,
+ onDelete,
+}: PageMenuProps) {
+ const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
+ const [restoreFocus, setRestoreFocus] = useState(true);
+ const [requiredPageDialogOpen, setRequiredPageDialogOpen] = useState(false);
+ const isFrontCover = pageIndex === 0;
+ const isBackCover = pageIndex === totalPages - 1;
+ const isInterior = !isFrontCover && !isBackCover;
+ const label = isFrontCover
+ ? "Front cover"
+ : isBackCover
+ ? "Back cover"
+ : `Page ${pageIndex}`;
+ const buttonId = `page-menu-button-${pageId}`;
+ const menuId = `page-menu-${pageId}`;
+ const open = Boolean(anchorEl);
+
+ const runAction = (action: () => void) => {
+ setRestoreFocus(false);
+ setAnchorEl(null);
+ action();
+ };
+
+ return (
+ <>
+ <IconButton
+ id={buttonId}
+ data-page-control
+ data-open={open ? "true" : undefined}
+ aria-label={`${label} options`}
+ aria-haspopup="menu"
+ aria-controls={open ? menuId : undefined}
+ aria-expanded={open ? true : undefined}
+ onClick={(event) => {
+ event.stopPropagation();
+ setRestoreFocus(true);
+ setAnchorEl(event.currentTarget);
+ }}
+ sx={{
+ bgcolor: open
+ ? pageMenuColors.active
+ : pageMenuColors.hover,
+ borderRadius: "14px",
+ color: open ? pageMenuColors.text : uiColors.muted,
+ width: 44,
+ height: 44,
+ flexShrink: 0,
+ mt: "auto",
+ p: 0,
+ "&:hover": {
+ bgcolor: pageMenuColors.active,
+ color: pageMenuColors.text,
+ },
+ "&.Mui-focusVisible": { opacity: 1, pointerEvents: "auto" },
+ }}
+ >
+ <MoreIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ <Menu
+ id={menuId}
+ anchorEl={anchorEl}
+ open={open}
+ onClose={() => setAnchorEl(null)}
+ onClick={(event) => event.stopPropagation()}
+ disableRestoreFocus={!restoreFocus}
+ anchorOrigin={{ vertical: "bottom", horizontal: side }}
+ transformOrigin={{ vertical: "top", horizontal: side }}
+ slotProps={{
+ paper: {
+ sx: {
+ bgcolor: pageMenuColors.background,
+ backgroundImage: "none",
+ borderRadius: "14px",
+ boxShadow: popupShadow,
+ mt: "6px",
+ minWidth: 0,
+ p: "4px",
+ width: "max-content",
+ },
+ },
+ list: { "aria-labelledby": buttonId, sx: { p: 0 } },
+ }}
+ >
+ {isFrontCover && (
+ <MenuItem
+ dense
+ disableRipple
+ onClick={() => runAction(onAddPhotos)}
+ sx={menuItemSx}
+ >
+ <EditPhotoIcon sx={{ fontSize: 18, flexShrink: 0 }} />
+ Change cover image
+ </MenuItem>
+ )}
+ {isInterior && photoCount < MAX_PAGE_PHOTOS && (
+ <MenuItem
+ dense
+ disableRipple
+ onClick={() => runAction(onAddPhotos)}
+ sx={menuItemSx}
+ >
+ <AddPhotosIcon sx={{ fontSize: 18, flexShrink: 0 }} />
+ Add photos
+ </MenuItem>
+ )}
+ {!isFrontCover && (
+ <MenuItem
+ dense
+ disableRipple
+ onClick={() => runAction(() => onInsert("before"))}
+ sx={menuItemSx}
+ >
+ <AddPageIcon sx={{ fontSize: 18, flexShrink: 0 }} />
+ Insert page before
+ </MenuItem>
+ )}
+ {!isBackCover && (
+ <MenuItem
+ dense
+ disableRipple
+ onClick={() => runAction(() => onInsert("after"))}
+ sx={menuItemSx}
+ >
+ <AddPageIcon sx={{ fontSize: 18, flexShrink: 0 }} />
+ Insert page after
+ </MenuItem>
+ )}
+ {isInterior && (
+ <MenuItem
+ dense
+ disableRipple
+ onClick={() =>
+ runAction(() => {
+ if (requiredBlank)
+ setRequiredPageDialogOpen(true);
+ else onDelete();
+ })
+ }
+ sx={{
+ ...menuItemSx,
+ color: pageMenuColors.danger,
+ "& .MuiSvgIcon-root": {
+ color: pageMenuColors.danger,
+ },
+ "&:hover, &.Mui-focusVisible": {
+ bgcolor: pageMenuColors.dangerHover,
+ "& .MuiSvgIcon-root": {
+ color: pageMenuColors.danger,
+ },
+ },
+ "&:active": {
+ bgcolor: pageMenuColors.dangerActive,
+ },
+ }}
+ >
+ <DeleteIcon sx={{ fontSize: 18, flexShrink: 0 }} />
+ Delete page
+ </MenuItem>
+ )}
+ </Menu>
+ {requiredPageDialogOpen && (
+ <RequiredPageDialog
+ onClose={() => setRequiredPageDialogOpen(false)}
+ />
+ )}
+ </>
+ );
+}
diff --git a/web/apps/photobook/src/components/PageStrip.tsx b/web/apps/photobook/src/components/PageStrip.tsx
new file mode 100644
index 0000000000..414e7d8d82
--- /dev/null
+++ b/web/apps/photobook/src/components/PageStrip.tsx
@@ -0,0 +1,307 @@
+import { useBook } from "@/context/book";
+import { usePageDrag } from "@/hooks/usePageDrag";
+import { useSpreads } from "@/hooks/useSpreads";
+import { thumbnailShadow, toolbarColors, uiColors } from "@/theme/colors";
+import { Box, Typography, useMediaQuery } from "@mui/material";
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type RefCallback,
+} from "react";
+import { Layer, Stage } from "react-konva";
+import PageCanvas from "./PageCanvas";
+import PrinterBlankPage from "./PrinterBlankPage";
+import { EDITOR_SCROLLBAR_SX } from "./editorLayout";
+
+interface PageStripProps {
+ onSpreadClick?: (spreadIdx: number) => void;
+}
+
+export default function PageStrip({ onSpreadClick }: PageStripProps) {
+ const { book } = useBook();
+ const isCompact = useMediaQuery("(max-width: 599px)");
+ const thumbnailWidth = isCompact ? 52 : 136;
+ const rowPadding = isCompact ? 8 : 12;
+ const labelLineHeight = isCompact ? 16 : 18;
+ const pages = book.pages;
+ const pageDrag = usePageDrag();
+ const stripContainerRef = useRef<HTMLDivElement | null>(null);
+
+ const spreads = useSpreads(pages.length);
+
+ const [visibleSpreads, setVisibleSpreads] = useState<Set<number>>(
+ () => new Set([0, 1, 2, 3, 4, 5, 6, 7]),
+ );
+ const stripElsRef = useRef<Map<number, Element>>(new Map());
+ const stripObserverRef = useRef<IntersectionObserver | null>(null);
+
+ useEffect(() => {
+ const root = stripContainerRef.current;
+ if (!root) return;
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ setVisibleSpreads((prev) => {
+ const next = new Set(prev);
+ for (const entry of entries) {
+ const idx = Number(
+ (entry.target as HTMLElement).dataset
+ .stripSpreadIndex,
+ );
+ if (!isNaN(idx)) {
+ if (entry.isIntersecting) next.add(idx);
+ else next.delete(idx);
+ }
+ }
+ if (
+ next.size === prev.size &&
+ [...next].every((v) => prev.has(v))
+ )
+ return prev;
+ return next;
+ });
+ },
+ { root, rootMargin: "300px 0px" },
+ );
+ stripObserverRef.current = observer;
+
+ stripElsRef.current.forEach((el) => observer.observe(el));
+
+ return () => {
+ observer.disconnect();
+ stripObserverRef.current = null;
+ };
+ }, [spreads.length]);
+
+ const stripSpreadRefCallback = useCallback(
+ (idx: number): RefCallback<HTMLDivElement> =>
+ (el) => {
+ const prev = stripElsRef.current.get(idx);
+ if (prev && stripObserverRef.current)
+ stripObserverRef.current.unobserve(prev);
+
+ if (el) {
+ stripElsRef.current.set(idx, el);
+ if (stripObserverRef.current)
+ stripObserverRef.current.observe(el);
+ } else {
+ stripElsRef.current.delete(idx);
+ }
+ },
+ [],
+ );
+
+ return (
+ <Box
+ ref={stripContainerRef}
+ sx={{
+ width: "100%",
+ display: "flex",
+ flexDirection: "column",
+ px: { xs: 1, sm: 2 },
+ py: 3,
+ flex: 1,
+ minHeight: 0,
+ overflowX: "hidden",
+ overflowY: "auto",
+ scrollbarGutter: "stable both-edges",
+ ...EDITOR_SCROLLBAR_SX,
+ }}
+ >
+ {pages.length === 0 && (
+ <Typography
+ sx={{
+ px: 1,
+ pt: 3,
+ fontSize: 12,
+ lineHeight: 1.5,
+ color: uiColors.muted,
+ textAlign: "center",
+ }}
+ >
+ Your pages will appear here
+ </Typography>
+ )}
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: { xs: 1, sm: 1.5 },
+ }}
+ >
+ {spreads.map((spread, spreadIdx) => (
+ <Box
+ key={spreadIdx}
+ ref={stripSpreadRefCallback(spreadIdx)}
+ data-strip-spread-index={spreadIdx}
+ onClick={() => onSpreadClick?.(spreadIdx)}
+ sx={{
+ cursor: "pointer",
+ borderRadius: `${rowPadding + 4}px`,
+ p: `${rowPadding}px`,
+ width:
+ (spread.left !== null && spread.right !== null
+ ? thumbnailWidth * 2 + 2
+ : thumbnailWidth) +
+ rowPadding * 2,
+ ml:
+ spread.left === null
+ ? `${thumbnailWidth + 2}px`
+ : 0,
+ mr:
+ spread.right === null
+ ? `${thumbnailWidth + 2}px`
+ : 0,
+ display: "flex",
+ gap: "2px",
+ minHeight:
+ thumbnailWidth +
+ rowPadding * 2 +
+ labelLineHeight +
+ 4,
+ "&:hover": { bgcolor: toolbarColors.control },
+ transition: "background-color 120ms ease",
+ }}
+ >
+ {visibleSpreads.has(spreadIdx) &&
+ (["left", "right"] as const).map((side) => {
+ const entry = spread[side];
+ if (entry === null) return null;
+ const pageIndex =
+ typeof entry === "number" ? entry : null;
+ const page =
+ pageIndex !== null
+ ? pages[pageIndex]
+ : null;
+ const canDrag =
+ pageIndex !== null &&
+ pageIndex > 0 &&
+ pageIndex < pages.length - 1;
+ const label =
+ entry === "printer-blank"
+ ? "Blank"
+ : pageIndex === null
+ ? ""
+ : pageIndex === 0
+ ? "Cover"
+ : pageIndex === pages.length - 1
+ ? "Back cover"
+ : pageIndex;
+
+ return (
+ <Box
+ key={side}
+ sx={{
+ width: thumbnailWidth,
+ flexShrink: 0,
+ }}
+ >
+ {entry === "printer-blank" ? (
+ <PrinterBlankPage
+ width={thumbnailWidth}
+ height={thumbnailWidth}
+ />
+ ) : page && pageIndex !== null ? (
+ <Box
+ draggable={canDrag}
+ onDragStart={(e) =>
+ pageDrag.handlePageDragStart(
+ e,
+ pageIndex,
+ )
+ }
+ onDragOver={(e) =>
+ pageDrag.handlePageDragOverPage(
+ e,
+ pageIndex,
+ )
+ }
+ onDrop={(e) =>
+ pageDrag.handlePageDropOnPage(
+ e,
+ pageIndex,
+ )
+ }
+ onDragEnd={
+ pageDrag.handlePageDragEndCleanup
+ }
+ sx={{
+ width: thumbnailWidth,
+ height: thumbnailWidth,
+ bgcolor: uiColors.paper,
+ boxShadow: thumbnailShadow,
+ borderRadius: 0.5,
+ overflow: "hidden",
+ cursor: canDrag
+ ? "grab"
+ : "pointer",
+ outline:
+ pageDrag.pageDragTarget ===
+ pageIndex
+ ? "2px solid #08C225"
+ : undefined,
+ opacity:
+ pageDrag.pageDragSource ===
+ pageIndex
+ ? 0.4
+ : 1,
+ }}
+ >
+ <Stage
+ width={thumbnailWidth}
+ height={thumbnailWidth}
+ listening={false}
+ style={{
+ pointerEvents: "none",
+ }}
+ >
+ <Layer>
+ <PageCanvas
+ page={page}
+ pageWidth={
+ thumbnailWidth
+ }
+ pageHeight={
+ thumbnailWidth
+ }
+ isFrontCover={
+ pageIndex === 0
+ }
+ isBackCover={
+ pageIndex ===
+ pages.length - 1
+ }
+ />
+ </Layer>
+ </Stage>
+ </Box>
+ ) : null}
+ <Typography
+ title={
+ entry === "printer-blank"
+ ? "Blank page (required)"
+ : undefined
+ }
+ sx={{
+ mt: 0.5,
+ fontSize: isCompact ? 12 : 14,
+ lineHeight: `${labelLineHeight}px`,
+ fontWeight: 600,
+ color: uiColors.muted,
+ textAlign: "center",
+ }}
+ >
+ {label}
+ </Typography>
+ </Box>
+ );
+ })}
+ </Box>
+ ))}
+ </Box>
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/PrinterBlankPage.tsx b/web/apps/photobook/src/components/PrinterBlankPage.tsx
new file mode 100644
index 0000000000..a7704c15cf
--- /dev/null
+++ b/web/apps/photobook/src/components/PrinterBlankPage.tsx
@@ -0,0 +1,41 @@
+import { bookPageShadow, thumbnailShadow, uiColors } from "@/theme/colors";
+import { Box, Typography } from "@mui/material";
+
+export default function PrinterBlankPage({
+ width,
+ height,
+ showLabel = false,
+}: {
+ width: number;
+ height: number;
+ showLabel?: boolean;
+}) {
+ return (
+ <Box title="Blank page (required)" sx={{ width, flexShrink: 0 }}>
+ <Box
+ aria-label="Blank page (required)"
+ sx={{
+ width,
+ height,
+ bgcolor: uiColors.paper,
+ borderRadius: 0.5,
+ boxShadow: showLabel ? bookPageShadow : thumbnailShadow,
+ }}
+ />
+ {showLabel && (
+ <Typography
+ sx={{
+ fontSize: { xs: 12, sm: 14 },
+ lineHeight: { xs: "16px", sm: "18px" },
+ color: uiColors.muted,
+ fontWeight: 600,
+ textAlign: "center",
+ mt: 0.5,
+ }}
+ >
+ Blank page (required)
+ </Typography>
+ )}
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/RequiredPageDialog.tsx b/web/apps/photobook/src/components/RequiredPageDialog.tsx
new file mode 100644
index 0000000000..dd8df11c8b
--- /dev/null
+++ b/web/apps/photobook/src/components/RequiredPageDialog.tsx
@@ -0,0 +1,155 @@
+import { accentGreen, accentGreenHover } from "@/theme/buttons";
+import { uiColors } from "@/theme/colors";
+import {
+ dialogActionSx,
+ dialogCloseButtonSx,
+ dialogDescriptionSx,
+ dialogHeaderSx,
+ dialogPaperSx,
+ dialogTitleSx,
+} from "@/theme/dialogs";
+import { Box, Button, Dialog, IconButton, Typography } from "@mui/material";
+import { useId, useState } from "react";
+import { CloseIcon, InfoIcon } from "./icons";
+
+export default function RequiredPageDialog({
+ onClose,
+}: {
+ onClose: () => void;
+}) {
+ const id = useId();
+ const [open, setOpen] = useState(true);
+ const close = () => setOpen(false);
+
+ return (
+ <Dialog
+ open={open}
+ onClose={close}
+ maxWidth={false}
+ aria-labelledby={`${id}-title`}
+ aria-describedby={`${id}-description ${id}-tips`}
+ slotProps={{
+ paper: { sx: dialogPaperSx },
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.5)" } },
+ transition: { onExited: onClose },
+ }}
+ >
+ <Box sx={{ position: "relative", p: "48px 16px 16px" }}>
+ <IconButton
+ aria-label="Close"
+ onClick={close}
+ sx={dialogCloseButtonSx}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "16px",
+ }}
+ >
+ <Box
+ aria-hidden="true"
+ sx={{
+ width: 126,
+ height: 121,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ mb: "8px",
+ color: uiColors.muted,
+ }}
+ >
+ <InfoIcon sx={{ fontSize: 72 }} />
+ </Box>
+ <Box sx={dialogHeaderSx}>
+ <Typography
+ component="h2"
+ id={`${id}-title`}
+ sx={dialogTitleSx}
+ >
+ Page required for printing
+ </Typography>
+ <Typography
+ id={`${id}-description`}
+ sx={dialogDescriptionSx}
+ >
+ Printed books need an even page count.
+ </Typography>
+ </Box>
+ <Box
+ component="ul"
+ id={`${id}-tips`}
+ sx={{
+ width: "100%",
+ boxSizing: "border-box",
+ m: 0,
+ p: "16px",
+ listStyle: "none",
+ borderRadius: "16px",
+ bgcolor: "rgba(255,255,255,0.04)",
+ display: "flex",
+ flexDirection: "column",
+ gap: "16px",
+ textAlign: "left",
+ }}
+ >
+ <Box component="li">
+ <Typography
+ sx={{
+ ...dialogDescriptionSx,
+ color: "#FFFFFF",
+ fontWeight: 600,
+ mb: "4px",
+ }}
+ >
+ It doesn’t have to stay blank
+ </Typography>
+ <Typography sx={dialogDescriptionSx}>
+ You can add photos or text here.
+ </Typography>
+ </Box>
+ <Box
+ component="li"
+ sx={{
+ borderTop: "1px solid rgba(255,255,255,0.08)",
+ pt: "16px",
+ }}
+ >
+ <Typography
+ sx={{
+ ...dialogDescriptionSx,
+ color: "#FFFFFF",
+ fontWeight: 600,
+ mb: "4px",
+ }}
+ >
+ Want to remove it?
+ </Typography>
+ <Typography sx={dialogDescriptionSx}>
+ Delete another page to remove both.
+ </Typography>
+ </Box>
+ </Box>
+ <Button
+ variant="contained"
+ fullWidth
+ disableElevation
+ autoFocus
+ onClick={close}
+ sx={{
+ ...dialogActionSx,
+ color: "#FFFFFF",
+ bgcolor: accentGreen,
+ "&:hover": { bgcolor: accentGreenHover },
+ }}
+ >
+ Got it
+ </Button>
+ </Box>
+ </Box>
+ </Dialog>
+ );
+}
diff --git a/web/apps/photobook/src/components/ResetBookButton.tsx b/web/apps/photobook/src/components/ResetBookButton.tsx
new file mode 100644
index 0000000000..cd5b9d3562
--- /dev/null
+++ b/web/apps/photobook/src/components/ResetBookButton.tsx
@@ -0,0 +1,186 @@
+import { useBook } from "@/context/book";
+import { editorButtonSx } from "@/theme/buttons";
+import { pageMenuColors, toolbarColors, uiColors } from "@/theme/colors";
+import {
+ dialogActionSx,
+ dialogCancelButtonSx,
+ dialogCloseButtonSx,
+ dialogDescriptionSx,
+ dialogHeaderSx,
+ dialogPaperSx,
+ dialogTitleSx,
+} from "@/theme/dialogs";
+import { Box, Button, Dialog, IconButton, Typography } from "@mui/material";
+import { useState } from "react";
+import { CloseIcon, DeleteIcon } from "./icons";
+
+export default function ResetBookButton() {
+ const { startOver, processingPhotos, book } = useBook();
+ const [open, setOpen] = useState(false);
+ const [resetting, setResetting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const close = () => {
+ if (!resetting) setOpen(false);
+ };
+
+ const handleReset = async () => {
+ if (resetting || !open) return;
+ setResetting(true);
+ setError(null);
+ try {
+ await startOver();
+ setOpen(false);
+ } catch {
+ setError("Couldn't reset the photobook. Please try again.");
+ setResetting(false);
+ }
+ };
+
+ return (
+ <>
+ <Button
+ variant="text"
+ onClick={() => {
+ setError(null);
+ setOpen(true);
+ }}
+ disabled={
+ processingPhotos || resetting || book.pages.length === 0
+ }
+ sx={{
+ ...editorButtonSx,
+ color: toolbarColors.muted,
+ bgcolor: "transparent",
+ outline: "none",
+ transition: "color 120ms ease, background-color 120ms ease",
+ "&:hover": {
+ color: uiColors.danger,
+ bgcolor: pageMenuColors.dangerHover,
+ },
+ "&:focus-visible": {
+ color: uiColors.danger,
+ bgcolor: pageMenuColors.dangerHover,
+ outline: "none",
+ },
+ "&:active": {
+ color: uiColors.danger,
+ bgcolor: pageMenuColors.dangerActive,
+ },
+ }}
+ >
+ Reset
+ </Button>
+ <Dialog
+ open={open}
+ onClose={close}
+ aria-labelledby="reset-book-title"
+ aria-describedby="reset-book-description"
+ aria-busy={resetting}
+ maxWidth={false}
+ sx={{ zIndex: 1500 }}
+ slotProps={{
+ paper: { sx: dialogPaperSx },
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.5)" } },
+ transition: { onExited: () => setResetting(false) },
+ }}
+ >
+ <Box sx={{ position: "relative", p: "48px 16px 16px" }}>
+ <IconButton
+ aria-label="Close"
+ onClick={close}
+ aria-disabled={resetting}
+ sx={dialogCloseButtonSx}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "16px",
+ }}
+ >
+ <Box
+ aria-hidden="true"
+ sx={{
+ width: 126,
+ height: 121,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ mb: "8px",
+ color: uiColors.danger,
+ }}
+ >
+ <DeleteIcon sx={{ fontSize: 72 }} />
+ </Box>
+ <Box sx={dialogHeaderSx}>
+ <Typography
+ component="h2"
+ id="reset-book-title"
+ sx={dialogTitleSx}
+ >
+ Reset this photobook
+ </Typography>
+ <Typography
+ id="reset-book-description"
+ sx={dialogDescriptionSx}
+ >
+ Remove all photos and edits from this photobook?
+ Your original photos will stay untouched.
+ </Typography>
+ </Box>
+ {error && (
+ <Typography
+ role="alert"
+ sx={{
+ color: uiColors.danger,
+ fontSize: 13,
+ lineHeight: "18px",
+ textAlign: "center",
+ }}
+ >
+ {error}
+ </Typography>
+ )}
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ gap: "12px",
+ width: "100%",
+ }}
+ >
+ <Button
+ variant="contained"
+ fullWidth
+ disableElevation
+ onClick={handleReset}
+ aria-disabled={resetting}
+ sx={{
+ ...dialogActionSx,
+ color: "#FFFFFF",
+ bgcolor: "#F63A3A",
+ "&:hover": { bgcolor: "#DD3434" },
+ }}
+ >
+ Reset
+ </Button>
+ <Button
+ variant="outlined"
+ fullWidth
+ autoFocus
+ onClick={close}
+ aria-disabled={resetting}
+ sx={dialogCancelButtonSx}
+ >
+ Cancel
+ </Button>
+ </Box>
+ </Box>
+ </Box>
+ </Dialog>
+ </>
+ );
+}
diff --git a/web/apps/photobook/src/components/ResultsPage.tsx b/web/apps/photobook/src/components/ResultsPage.tsx
new file mode 100644
index 0000000000..a8f3fda2b0
--- /dev/null
+++ b/web/apps/photobook/src/components/ResultsPage.tsx
@@ -0,0 +1,428 @@
+import { useBook } from "@/context/book";
+import { useSpreads } from "@/hooks/useSpreads";
+import { normalizeBookPages } from "@/lib/bookPages";
+import { exportPdfX4Pages } from "@/lib/export";
+import {
+ getBindingPrintSelection,
+ getPrintBinding,
+ getPrintExportError,
+ PrintExportValidationError,
+} from "@/lib/printProducts";
+import { getSpreadLabel } from "@/lib/spreads";
+import { headerButtonSx } from "@/theme/buttons";
+import { popupShadow, toolbarColors, uiColors } from "@/theme/colors";
+import {
+ Alert,
+ Box,
+ Button,
+ CircularProgress,
+ Dialog,
+ LinearProgress,
+ Snackbar,
+ Typography,
+} from "@mui/material";
+import { saveAsFileAndRevokeObjectURL } from "ente-base/utils/web";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import BookBindingSelect from "./BookBindingSelect";
+import BookHeader from "./BookHeader";
+import BookViewer, { type BookViewerHandle } from "./BookViewer";
+import {
+ EDITOR_PANEL_BOTTOM_INSET,
+ EDITOR_PANEL_INSET,
+ EDITOR_PANEL_SX,
+} from "./editorLayout";
+import { DownloadIcon, EditIcon } from "./icons";
+
+export default function ResultsPage() {
+ const { book, photos, setAppView, waitForEnteOriginals } = useBook();
+ const viewerRef = useRef<BookViewerHandle>(null);
+ const [spreadIndex, setSpreadIndex] = useState(0);
+ const [downloadPhase, setDownloadPhase] = useState<
+ "idle" | "originals" | "exporting"
+ >("idle");
+ const downloadInProgress = useRef(false);
+ const [exportProgress, setExportProgress] = useState(0);
+ const [exportError, setExportError] = useState<string | null>(null);
+ const waitingForOriginals = downloadPhase === "originals";
+ const [originalsProgress, setOriginalsProgress] = useState({
+ done: 0,
+ total: 0,
+ });
+ const pages = book.pages;
+ const binding = getPrintBinding(book.printSelection);
+ const printSelection = useMemo(
+ () => getBindingPrintSelection(binding),
+ [binding],
+ );
+ const exportPages = useMemo(() => normalizeBookPages(pages), [pages]);
+ const busy = downloadPhase !== "idle";
+ const totalPages = pages.length;
+ const spreads = useSpreads(totalPages);
+ const photosRef = useRef(photos);
+ photosRef.current = photos;
+
+ const pageLabel = getSpreadLabel(spreads[spreadIndex], totalPages);
+ const isAtStart = spreadIndex === 0;
+ const isAtEnd = spreadIndex >= spreads.length - 1;
+
+ const usedPhotoIds = useMemo(() => {
+ const ids = new Set<string>();
+ for (const page of pages) {
+ for (const slot of page.slots) {
+ if (slot.photoId) {
+ ids.add(slot.photoId);
+ }
+ }
+ }
+ return ids;
+ }, [pages]);
+
+ const handleSpreadChange = useCallback((idx: number) => {
+ setSpreadIndex(idx);
+ }, []);
+
+ const getBlockedEntePhotos = useCallback(() => {
+ return photosRef.current.filter(
+ (photo) =>
+ usedPhotoIds.has(photo.id) &&
+ photo.source === "ente" &&
+ photo.originalStatus !== "ready",
+ );
+ }, [usedPhotoIds]);
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented) return;
+ const target = e.target as HTMLElement | null;
+ if (
+ target &&
+ (target.tagName === "INPUT" ||
+ target.tagName === "TEXTAREA" ||
+ target.isContentEditable ||
+ target.closest(
+ '[role="combobox"], [role="listbox"], [role="option"]',
+ ))
+ ) {
+ return;
+ }
+ if (e.key === "ArrowLeft" && !isAtStart) {
+ e.preventDefault();
+ viewerRef.current?.flipPrev();
+ } else if (e.key === "ArrowRight" && !isAtEnd) {
+ e.preventDefault();
+ viewerRef.current?.flipNext();
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [isAtStart, isAtEnd]);
+
+ const handleExport = useCallback(async () => {
+ if (downloadInProgress.current) return;
+ const validationError = getPrintExportError(
+ printSelection,
+ exportPages.length,
+ );
+ if (validationError) {
+ setExportError(validationError);
+ return;
+ }
+
+ const initiallyBlocked = getBlockedEntePhotos();
+ const pendingIds = initiallyBlocked
+ .filter((photo) => photo.originalStatus === "pending")
+ .map((photo) => photo.id);
+
+ downloadInProgress.current = true;
+ setExportError(null);
+ setExportProgress(0);
+ setDownloadPhase(pendingIds.length > 0 ? "originals" : "exporting");
+ const preparationShare = pendingIds.length > 0 ? 10 : 0;
+
+ try {
+ if (pendingIds.length > 0) {
+ setOriginalsProgress({ done: 0, total: pendingIds.length });
+ await waitForEnteOriginals(pendingIds, (done, total) => {
+ setOriginalsProgress({ done, total });
+ setExportProgress(
+ total
+ ? Math.round((done / total) * preparationShare)
+ : 0,
+ );
+ });
+ }
+
+ const remainingBlocked = getBlockedEntePhotos();
+ if (remainingBlocked.length > 0) {
+ const failedCount = remainingBlocked.filter(
+ (photo) => photo.originalStatus === "failed",
+ ).length;
+ setExportError(
+ failedCount > 0
+ ? "Some Ente photos failed to prepare. Re-import the album before exporting."
+ : "Ente originals are still being prepared. Please wait a moment and try again.",
+ );
+ return;
+ }
+
+ setDownloadPhase("exporting");
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => setTimeout(resolve, 0)),
+ );
+ const blob = await exportPdfX4Pages(
+ exportPages,
+ printSelection,
+ (progress) => {
+ setExportProgress(
+ preparationShare +
+ Math.round(
+ (progress * (100 - preparationShare)) / 100,
+ ),
+ );
+ },
+ );
+ const filename = `photobook-${printSelection.sizeMm}mm.pdf`;
+
+ saveAsFileAndRevokeObjectURL(URL.createObjectURL(blob), filename);
+ } catch (e) {
+ console.error("Export failed:", e);
+ setExportError(
+ e instanceof PrintExportValidationError
+ ? e.message
+ : "Export failed. Please try again.",
+ );
+ } finally {
+ downloadInProgress.current = false;
+ setDownloadPhase("idle");
+ }
+ }, [
+ getBlockedEntePhotos,
+ exportPages,
+ printSelection,
+ waitForEnteOriginals,
+ ]);
+
+ return (
+ <Box
+ sx={{
+ height: "100dvh",
+ display: "flex",
+ flexDirection: "column",
+ px: EDITOR_PANEL_INSET,
+ bgcolor: uiColors.background,
+ }}
+ >
+ <BookHeader>
+ <BookBindingSelect disabled={busy} />
+ <Button
+ aria-label="Edit"
+ startIcon={<EditIcon />}
+ onClick={() => setAppView("edit")}
+ disabled={busy}
+ sx={{
+ ...headerButtonSx,
+ color: toolbarColors.text,
+ bgcolor: toolbarColors.control,
+ "&:hover": { bgcolor: toolbarColors.hover },
+ "&:active": { bgcolor: toolbarColors.active },
+ }}
+ >
+ <Box
+ component="span"
+ sx={{ display: { xs: "none", sm: "inline" } }}
+ >
+ Edit
+ </Box>
+ </Button>
+ <Button
+ id="download-button"
+ variant="contained"
+ aria-label={
+ busy ? `Downloading, ${exportProgress}%` : "Download"
+ }
+ aria-busy={busy}
+ startIcon={
+ <Box
+ component="span"
+ sx={{
+ display: "grid",
+ width: 18,
+ height: 18,
+ flexShrink: 0,
+ }}
+ >
+ <DownloadIcon
+ strokeWidth={2.2}
+ sx={{
+ gridArea: "1 / 1",
+ visibility: busy ? "hidden" : "visible",
+ }}
+ />
+ <CircularProgress
+ disableShrink
+ size={18}
+ thickness={4}
+ color="inherit"
+ aria-hidden="true"
+ sx={{
+ gridArea: "1 / 1",
+ visibility: busy ? "visible" : "hidden",
+ willChange: "transform",
+ "& circle": { strokeLinecap: "round" },
+ }}
+ />
+ </Box>
+ }
+ disabled={busy || pages.length === 0}
+ onClick={handleExport}
+ sx={{
+ ...headerButtonSx,
+ fontWeight: 700,
+ gap: { xs: busy ? "6px" : 0, sm: "8px" },
+ ...(busy && { "&.Mui-disabled": { opacity: 1 } }),
+ }}
+ >
+ <Box
+ component="span"
+ sx={{ display: { xs: "none", sm: "inline" } }}
+ >
+ {busy ? "Downloading" : "Download"}
+ </Box>
+ {busy && (
+ <Box
+ component="span"
+ sx={{
+ display: "inline-flex",
+ justifyContent: "center",
+ alignItems: "center",
+ flexShrink: 0,
+ width: "4.5ch",
+ py: 0.5,
+ borderRadius: "7px",
+ bgcolor: "rgba(0,0,0,0.12)",
+ fontSize: 12,
+ lineHeight: "16px",
+ fontWeight: 600,
+ fontVariantNumeric: "tabular-nums",
+ }}
+ >
+ {exportProgress}%
+ </Box>
+ )}
+ </Button>
+ </BookHeader>
+
+ <Box
+ component="main"
+ aria-label={`Photobook preview: ${pageLabel}`}
+ sx={{
+ ...EDITOR_PANEL_SX,
+ flex: 1,
+ minHeight: 0,
+ mb: EDITOR_PANEL_BOTTOM_INSET,
+ borderRadius: "20px",
+ display: "flex",
+ position: "relative",
+ overflow: "hidden",
+ px: { xs: 1, sm: 4 },
+ }}
+ >
+ <BookViewer
+ ref={viewerRef}
+ pages={pages}
+ onSpreadChange={handleSpreadChange}
+ />
+ </Box>
+
+ <Dialog
+ open={waitingForOriginals}
+ slotProps={{
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.25)" } },
+ paper: {
+ sx: {
+ borderRadius: 3,
+ bgcolor: uiColors.surface,
+ minWidth: 360,
+ boxShadow: popupShadow,
+ },
+ },
+ }}
+ >
+ <Box sx={{ textAlign: "center", px: 3.5, py: 3.5 }}>
+ <CircularProgress
+ sx={{ color: "#08C225", mb: 2 }}
+ size={36}
+ />
+ <Typography
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ fontWeight: 700,
+ fontSize: "1.05rem",
+ color: uiColors.text,
+ mb: 0.5,
+ }}
+ >
+ Finishing your album download
+ </Typography>
+ <Typography
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ color: uiColors.muted,
+ fontSize: "0.8rem",
+ lineHeight: 1.6,
+ mb: 2.5,
+ }}
+ >
+ We need the full-resolution photos before we can build a
+ print-ready file.
+ </Typography>
+ <LinearProgress
+ variant="determinate"
+ value={
+ originalsProgress.total
+ ? (originalsProgress.done /
+ originalsProgress.total) *
+ 100
+ : 0
+ }
+ sx={{
+ height: 6,
+ borderRadius: 3,
+ mb: 1,
+ bgcolor: uiColors.control,
+ "& .MuiLinearProgress-bar": {
+ background: "#08C225",
+ borderRadius: 3,
+ },
+ }}
+ />
+ <Typography
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ color: uiColors.muted,
+ fontSize: "0.8rem",
+ }}
+ >
+ {originalsProgress.done} / {originalsProgress.total}{" "}
+ photos
+ </Typography>
+ </Box>
+ </Dialog>
+
+ <Snackbar
+ open={Boolean(exportError)}
+ autoHideDuration={6000}
+ onClose={() => setExportError(null)}
+ anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
+ >
+ <Alert
+ onClose={() => setExportError(null)}
+ severity="error"
+ variant="filled"
+ >
+ {exportError}
+ </Alert>
+ </Snackbar>
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/SpreadPage.tsx b/web/apps/photobook/src/components/SpreadPage.tsx
new file mode 100644
index 0000000000..f8d543b437
--- /dev/null
+++ b/web/apps/photobook/src/components/SpreadPage.tsx
@@ -0,0 +1,1174 @@
+import { useBook } from "@/context/book";
+import type { DragInfo } from "@/hooks/usePhotoDrag";
+import { isRequiredBlankPage } from "@/lib/bookPages";
+import {
+ CAPTION_FONT_WEIGHT,
+ CENTER_TEXT_FONT_WEIGHT,
+ getCaptionLayout,
+ getCenterTextLayout,
+ getTextBlockLayout,
+ TEXT_LINE_HEIGHT,
+} from "@/lib/printLayout";
+import type { BookPage, TextBlock } from "@/lib/types";
+import { bookPageShadow, uiColors } from "@/theme/colors";
+import { Box, Button, Typography } from "@mui/material";
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import { Layer, Stage } from "react-konva";
+import { AddPhotosIcon, DeleteIcon, ZoomInIcon, ZoomOutIcon } from "./icons";
+import LayoutPicker from "./LayoutPicker";
+import type { CaptionPosition } from "./PageCanvas";
+import PageCanvas from "./PageCanvas";
+import PageMenu, { type PageInsertPosition } from "./PageMenu";
+import TextToolbar from "./TextToolbar";
+
+function SlotControls({
+ pageId,
+ slotId,
+ slot,
+ pageWidth,
+ pageHeight,
+}: {
+ pageId: string;
+ slotId: string;
+ slot: {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ cropZoom: number;
+ };
+ pageWidth: number;
+ pageHeight: number;
+}) {
+ const { updateSlot, removeSlot } = useBook();
+
+ const handleZoomIn = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ updateSlot(pageId, slotId, {
+ cropZoom: Math.min(slot.cropZoom + 0.2, 3),
+ });
+ };
+
+ const handleZoomOut = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ updateSlot(pageId, slotId, {
+ cropZoom: Math.max(slot.cropZoom - 0.2, 1),
+ });
+ };
+
+ const handleDelete = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ removeSlot(pageId, slotId);
+ };
+
+ const btnSize = Math.max(22, Math.min(28, pageWidth * 0.06));
+ const iconSize = btnSize * 0.58;
+ const padding = Math.max(4, pageWidth * 0.012);
+
+ return (
+ <div
+ style={{
+ position: "absolute",
+ left: (slot.x / 100) * pageWidth,
+ top: (slot.y / 100) * pageHeight,
+ width: (slot.width / 100) * pageWidth,
+ height: (slot.height / 100) * pageHeight,
+ zIndex: 3,
+ pointerEvents: "none",
+ }}
+ >
+ <div
+ data-page-control
+ onClick={handleDelete}
+ style={{
+ position: "absolute",
+ top: padding,
+ right: padding,
+ width: btnSize,
+ height: btnSize,
+ borderRadius: btnSize / 2,
+ background: "rgba(0,0,0,0.45)",
+ backdropFilter: "blur(8px)",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ cursor: "pointer",
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background = "rgba(186,26,26,0.7)";
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = "rgba(0,0,0,0.45)";
+ }}
+ >
+ <DeleteIcon
+ sx={{ fontSize: iconSize, color: "rgba(255,255,255,0.9)" }}
+ />
+ </div>
+
+ <div
+ data-page-control
+ style={{
+ position: "absolute",
+ bottom: padding,
+ right: padding,
+ display: "flex",
+ gap: 2,
+ borderRadius: btnSize / 2,
+ background: "rgba(0,0,0,0.45)",
+ backdropFilter: "blur(8px)",
+ padding: 2,
+ }}
+ >
+ <div
+ onClick={handleZoomOut}
+ style={{
+ width: btnSize,
+ height: btnSize,
+ borderRadius: btnSize / 2,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ cursor: "pointer",
+ transition: "background 0.15s",
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background =
+ "rgba(255,255,255,0.15)";
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = "transparent";
+ }}
+ >
+ <ZoomOutIcon
+ sx={{
+ fontSize: iconSize,
+ color: "rgba(255,255,255,0.9)",
+ }}
+ />
+ </div>
+ <div
+ onClick={handleZoomIn}
+ style={{
+ width: btnSize,
+ height: btnSize,
+ borderRadius: btnSize / 2,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ cursor: "pointer",
+ transition: "background 0.15s",
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background =
+ "rgba(255,255,255,0.15)";
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = "transparent";
+ }}
+ >
+ <ZoomInIcon
+ sx={{
+ fontSize: iconSize,
+ color: "rgba(255,255,255,0.9)",
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export const PICKER_WIDTH = 60;
+
+interface SpreadPageProps {
+ page: BookPage;
+ pageIndex: number;
+ pickerSide: "left" | "right";
+ pageWidth: number;
+ pageHeight: number;
+ totalPages: number;
+ selectedSlotId: string | null;
+ selectedPageId: string | null;
+ selectedTextId: string | null;
+ editingTextId: string | null;
+ onSlotClick: (pageId: string, slotId: string) => void;
+ onTextClick: (pageId: string, textId: string) => void;
+ onTextDblClick: (pageId: string, textId: string) => void;
+ onTextUpdate: (
+ pageId: string,
+ blockId: string,
+ updates: Partial<TextBlock>,
+ ) => void;
+ onTextDelete: (pageId: string, blockId: string) => void;
+ onTextEditEnd: () => void;
+ onClearSelection: () => void;
+ onInsertPage: (pageIndex: number, position: PageInsertPosition) => void;
+ onAddPhotos: (pageId: string) => void;
+ dragSourceInfo: DragInfo | null;
+ dragOverInfo: DragInfo | null;
+ dragOverPageId: string | null;
+ onPhotoDragStart: (
+ e: React.DragEvent,
+ pageId: string,
+ slotId: string,
+ photoId: string,
+ ) => void;
+ onSlotDragOver: (
+ e: React.DragEvent,
+ pageId: string,
+ slotId: string,
+ ) => void;
+ onPhotoDrop: (e: React.DragEvent, pageId: string, slotId: string) => void;
+ onPhotoDragEnd: () => void;
+ onPageDragOver: (e: React.DragEvent, pageId: string) => void;
+ onPageDrop: (e: React.DragEvent, pageId: string) => void;
+ pageDragSource: number | null;
+ pageDragTarget: number | null;
+ pageDragSourceRef: React.RefObject<number | null>;
+ onPageDragStart: (e: React.DragEvent, pageIndex: number) => void;
+ onPageDragOverPage: (e: React.DragEvent, pageIndex: number) => void;
+ onPageDropOnPage: (e: React.DragEvent, pageIndex: number) => void;
+ onPageDragEndCleanup: () => void;
+}
+
+export default function SpreadPage({
+ page,
+ pageIndex,
+ pickerSide,
+ pageWidth,
+ pageHeight,
+ totalPages,
+ selectedSlotId,
+ selectedPageId,
+ selectedTextId,
+ editingTextId,
+ onSlotClick,
+ onTextClick,
+ onTextDblClick,
+ onTextUpdate,
+ onTextDelete,
+ onTextEditEnd,
+ onClearSelection,
+ onInsertPage,
+ onAddPhotos,
+ dragSourceInfo,
+ dragOverInfo,
+ dragOverPageId,
+ onPhotoDragStart,
+ onSlotDragOver,
+ onPhotoDrop,
+ onPhotoDragEnd,
+ onPageDragOver,
+ onPageDrop,
+ pageDragSource,
+ pageDragTarget,
+ pageDragSourceRef,
+ onPageDragStart,
+ onPageDragOverPage,
+ onPageDropOnPage,
+ onPageDragEndCleanup,
+}: SpreadPageProps) {
+ const {
+ book,
+ thumbnailUrls,
+ photoUrls,
+ loadPreviews,
+ removePage,
+ setPageLayout,
+ updatePage,
+ updateSlot,
+ photos,
+ processingPhotos,
+ } = useBook();
+
+ const pagePhotoIds = useMemo(
+ () => page.slots.filter((s) => s.photoId).map((s) => s.photoId!),
+ [page.slots],
+ );
+ useEffect(() => {
+ if (pagePhotoIds.length > 0)
+ void loadPreviews(pagePhotoIds).catch((error: unknown) =>
+ console.error("Failed to load previews", error),
+ );
+ }, [pagePhotoIds, loadPreviews]);
+
+ const [editingCaption, setEditingCaption] =
+ useState<CaptionPosition | null>(null);
+ const [captionValue, setCaptionValue] = useState("");
+ const captionInputRef = useRef<HTMLInputElement>(null);
+ const [editingCenterText, setEditingCenterText] = useState(false);
+ const [centerTextDraft, setCenterTextDraft] = useState("");
+ const [textDraft, setTextDraft] = useState<{
+ id: string;
+ value: string;
+ } | null>(null);
+
+ useEffect(() => {
+ if (!editingTextId) setTextDraft(null);
+ }, [editingTextId]);
+
+ const isBackCover = pageIndex === totalPages - 1;
+ const isFrontCover = pageIndex === 0;
+
+ const handleCaptionClick = (position: CaptionPosition) => {
+ onClearSelection();
+ const val = position === "top" ? page.topCaption : page.bottomCaption;
+ setCaptionValue(val);
+ setEditingCaption(position);
+ };
+
+ const handleCaptionSave = () => {
+ if (editingCaption) {
+ const key =
+ editingCaption === "top" ? "topCaption" : "bottomCaption";
+ updatePage(page.id, { [key]: captionValue });
+ setEditingCaption(null);
+ }
+ };
+
+ const handleCaptionCancel = () => {
+ handleCaptionSave();
+ };
+
+ useEffect(() => {
+ if (editingCaption && captionInputRef.current) {
+ captionInputRef.current.focus();
+ captionInputRef.current.select();
+ }
+ }, [editingCaption]);
+
+ const isInterior = pageIndex > 0 && !isBackCover;
+ const isDragTarget =
+ pageDragTarget === pageIndex && pageDragSource !== null;
+ const isDragSource = pageDragSource === pageIndex;
+ const photoCount = page.slots.filter((s) => s.photoId !== null).length;
+ const showEmptyPageAddPhotos =
+ isInterior &&
+ photoCount === 0 &&
+ page.textBlocks.length === 0 &&
+ !(editingCenterText ? centerTextDraft : (page.centerText ?? "")).trim();
+ useEffect(() => {
+ if (photoCount > 0) setEditingCenterText(false);
+ else setEditingCaption(null);
+ }, [photoCount]);
+ const hideLayoutPicker = isBackCover;
+ const hasSelectedSlotOnPage =
+ selectedPageId === page.id && selectedSlotId !== null;
+
+ const pageBlock = (
+ <Box>
+ <Box
+ data-book-page={page.id}
+ sx={{
+ position: "relative",
+ bgcolor: uiColors.paper,
+ boxShadow: isDragTarget
+ ? `0 0 0 3px #08C225, ${bookPageShadow}`
+ : bookPageShadow,
+ borderRadius: 0.5,
+ overflow: "hidden",
+ opacity: isDragSource ? 0.4 : 1,
+ transition: "box-shadow 0.15s, opacity 0.15s",
+ }}
+ >
+ <Stage
+ width={pageWidth}
+ height={pageHeight}
+ onClick={(e) => {
+ if (e.target === e.target.getStage())
+ onClearSelection();
+ }}
+ onTap={(e) => {
+ if (e.target === e.target.getStage())
+ onClearSelection();
+ }}
+ >
+ <Layer>
+ <PageCanvas
+ page={page}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ photoUrls={photoUrls}
+ isBackCover={isBackCover}
+ isFrontCover={isFrontCover}
+ selectedSlotId={
+ selectedPageId === page.id
+ ? selectedSlotId
+ : null
+ }
+ selectedTextId={
+ selectedPageId === page.id
+ ? selectedTextId
+ : null
+ }
+ editingTextId={
+ selectedPageId === page.id
+ ? editingTextId
+ : null
+ }
+ editingCaption={editingCaption}
+ hideCaptions
+ hideCenterText
+ dragOverSlotId={
+ dragOverInfo?.pageId === page.id
+ ? dragOverInfo.slotId
+ : null
+ }
+ dragSourceSlotId={
+ dragSourceInfo?.pageId === page.id
+ ? dragSourceInfo.slotId
+ : null
+ }
+ onSlotClick={(slotId) =>
+ onSlotClick(page.id, slotId)
+ }
+ />
+ </Layer>
+ </Stage>
+ <div
+ draggable={isInterior}
+ onClick={onClearSelection}
+ onDragStart={(e) => {
+ if (!isInterior) {
+ e.preventDefault();
+ return;
+ }
+ onPageDragStart(e, pageIndex);
+ }}
+ onDragOver={(e) => {
+ if (pageDragSourceRef.current !== null) {
+ onPageDragOverPage(e, pageIndex);
+ } else {
+ onPageDragOver(e, page.id);
+ }
+ }}
+ onDrop={(e) => {
+ if (pageDragSourceRef.current !== null) {
+ onPageDropOnPage(e, pageIndex);
+ } else {
+ onPageDrop(e, page.id);
+ }
+ }}
+ onDragEnd={() => {
+ onPageDragEndCleanup();
+ onPhotoDragEnd();
+ }}
+ style={{
+ position: "absolute",
+ inset: 0,
+ zIndex: 1,
+ cursor: isInterior ? "grab" : "default",
+ pointerEvents:
+ hasSelectedSlotOnPage &&
+ pageDragSource === null &&
+ !dragSourceInfo
+ ? "none"
+ : "auto",
+ }}
+ />
+ {dragOverPageId === page.id &&
+ dragSourceInfo &&
+ dragSourceInfo.pageId !== page.id && (
+ <div
+ style={{
+ position: "absolute",
+ inset: 0,
+ zIndex: 3,
+ background: "rgba(8, 194, 37, 0.1)",
+ border: "2px dashed #08C225",
+ borderRadius: 2,
+ pointerEvents: "none",
+ }}
+ />
+ )}
+ {page.slots.map((slot) => {
+ const isSelected =
+ selectedPageId === page.id &&
+ selectedSlotId === slot.id;
+ const canPanCrop =
+ isSelected && !!slot.photoId && !dragSourceInfo;
+ return (
+ <div
+ key={slot.id}
+ tabIndex={-1}
+ draggable={!!slot.photoId && !isSelected}
+ onDragStart={(e) => {
+ if (slot.photoId) {
+ e.stopPropagation();
+ onPhotoDragStart(
+ e,
+ page.id,
+ slot.id,
+ slot.photoId,
+ );
+ } else {
+ e.preventDefault();
+ }
+ }}
+ onDragOver={(e) =>
+ onSlotDragOver(e, page.id, slot.id)
+ }
+ onDrop={(e) => onPhotoDrop(e, page.id, slot.id)}
+ onDragEnd={onPhotoDragEnd}
+ onClick={(event) => {
+ event.currentTarget.focus({
+ preventScroll: true,
+ });
+ onSlotClick(page.id, slot.id);
+ }}
+ onMouseDown={
+ canPanCrop
+ ? (e) => {
+ if (e.button !== 0) return;
+ const photo = photos.find(
+ (p) => p.id === slot.photoId,
+ );
+ if (!photo) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const origCropX = slot.cropX;
+ const origCropY = slot.cropY;
+ const sw =
+ (slot.width / 100) * pageWidth;
+ const sh =
+ (slot.height / 100) * pageHeight;
+ const imgAspect =
+ photo.width / photo.height;
+ const slotAspect = sw / sh;
+ let drawW: number, drawH: number;
+ if (imgAspect > slotAspect) {
+ drawH = sh * slot.cropZoom;
+ drawW = drawH * imgAspect;
+ } else {
+ drawW = sw * slot.cropZoom;
+ drawH = drawW / imgAspect;
+ }
+ const slackX = sw - drawW;
+ const slackY = sh - drawH;
+ const onMove = (ev: MouseEvent) => {
+ const dx = ev.clientX - startX;
+ const dy = ev.clientY - startY;
+ const newCropX =
+ slackX !== 0
+ ? Math.max(
+ 0,
+ Math.min(
+ 1,
+ origCropX +
+ dx / slackX,
+ ),
+ )
+ : origCropX;
+ const newCropY =
+ slackY !== 0
+ ? Math.max(
+ 0,
+ Math.min(
+ 1,
+ origCropY +
+ dy / slackY,
+ ),
+ )
+ : origCropY;
+ if (
+ newCropX !== slot.cropX ||
+ newCropY !== slot.cropY
+ ) {
+ updateSlot(page.id, slot.id, {
+ cropX: newCropX,
+ cropY: newCropY,
+ });
+ }
+ };
+ const onUp = () => {
+ document.removeEventListener(
+ "mousemove",
+ onMove,
+ );
+ document.removeEventListener(
+ "mouseup",
+ onUp,
+ );
+ };
+ document.addEventListener(
+ "mousemove",
+ onMove,
+ );
+ document.addEventListener(
+ "mouseup",
+ onUp,
+ );
+ }
+ : undefined
+ }
+ style={{
+ position: "absolute",
+ left: (slot.x / 100) * pageWidth,
+ top: (slot.y / 100) * pageHeight,
+ width: (slot.width / 100) * pageWidth,
+ height: (slot.height / 100) * pageHeight,
+ cursor: slot.photoId
+ ? isSelected
+ ? "move"
+ : "grab"
+ : "default",
+ pointerEvents:
+ pageDragSource !== null ? "none" : "auto",
+ zIndex: 2,
+ }}
+ />
+ );
+ })}
+ {page.textBlocks.map((block) => {
+ const isTextEditing =
+ selectedPageId === page.id &&
+ editingTextId === block.id;
+ if (isTextEditing) return null;
+ const isTextSelected =
+ selectedPageId === page.id &&
+ selectedTextId === block.id;
+ const layout = getTextBlockLayout(block);
+ const bx = (layout.x / 100) * pageWidth;
+ const by = (layout.y / 100) * pageHeight;
+ const bw = (layout.width / 100) * pageWidth;
+ const bh = (layout.height / 100) * pageHeight;
+ const rotation = layout.rotation;
+ return (
+ <div
+ key={`text-overlay-${block.id}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ onTextClick(page.id, block.id);
+ }}
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ onTextDblClick(page.id, block.id);
+ }}
+ onMouseDown={
+ isTextSelected
+ ? (e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const origX = layout.x;
+ const origY = layout.y;
+ const onMove = (ev: MouseEvent) => {
+ const dx =
+ ((ev.clientX - startX) /
+ pageWidth) *
+ 100;
+ const dy =
+ ((ev.clientY - startY) /
+ pageHeight) *
+ 100;
+ onTextUpdate(page.id, block.id, {
+ x: origX + dx,
+ y: origY + dy,
+ });
+ };
+ const onUp = () => {
+ document.removeEventListener(
+ "mousemove",
+ onMove,
+ );
+ document.removeEventListener(
+ "mouseup",
+ onUp,
+ );
+ };
+ document.addEventListener(
+ "mousemove",
+ onMove,
+ );
+ document.addEventListener(
+ "mouseup",
+ onUp,
+ );
+ }
+ : undefined
+ }
+ style={{
+ position: "absolute",
+ left: bx - 4,
+ top: by - 4,
+ width: bw + 8,
+ height: bh + 8,
+ zIndex: 6,
+ cursor: isTextSelected ? "grab" : "pointer",
+ transform: rotation
+ ? `rotate(${rotation}deg)`
+ : undefined,
+ transformOrigin: "top left",
+ pointerEvents: dragSourceInfo ? "none" : "auto",
+ }}
+ />
+ );
+ })}
+ {page.slots.map((slot) => {
+ const isSelected =
+ selectedPageId === page.id &&
+ selectedSlotId === slot.id;
+ if (!isSelected || !slot.photoId) return null;
+ return (
+ <SlotControls
+ key={`ctrl-${slot.id}`}
+ pageId={page.id}
+ slotId={slot.id}
+ slot={slot}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ />
+ );
+ })}
+ {selectedPageId === page.id &&
+ editingTextId &&
+ (() => {
+ const block = page.textBlocks.find(
+ (t) => t.id === editingTextId,
+ );
+ if (!block) return null;
+ const value =
+ textDraft?.id === block.id
+ ? textDraft.value
+ : block.text;
+ const layout = getTextBlockLayout({
+ ...block,
+ text: value,
+ });
+ const bx = (layout.x / 100) * pageWidth;
+ const by = (layout.y / 100) * pageHeight;
+ const bw = (layout.width / 100) * pageWidth;
+ const fontSize = pageHeight * (layout.fontSize / 100);
+ const color = block.color ?? "#555555";
+ const rotation = block.rotation ?? 0;
+ return (
+ <input
+ key={`edit-${block.id}`}
+ type="text"
+ autoFocus
+ value={value}
+ onChange={(e) =>
+ setTextDraft({
+ id: block.id,
+ value: e.target.value,
+ })
+ }
+ placeholder="Type here"
+ onBlur={(e) => {
+ onTextUpdate(page.id, block.id, {
+ text: e.currentTarget.value,
+ });
+ onTextEditEnd();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ onTextUpdate(page.id, block.id, {
+ text: e.currentTarget.value,
+ });
+ onTextEditEnd();
+ }
+ if (e.key === "Enter") {
+ onTextUpdate(page.id, block.id, {
+ text: e.currentTarget.value,
+ });
+ onTextEditEnd();
+ }
+ }}
+ style={{
+ position: "absolute",
+ left: bx,
+ top: by,
+ transform: rotation
+ ? `rotate(${rotation}deg)`
+ : undefined,
+ transformOrigin: "top left",
+ width: bw,
+ boxSizing: "border-box",
+ zIndex: 15,
+ border: "none",
+ borderBottom:
+ "1.5px solid rgba(8, 194, 37, 0.5)",
+ outline: "none",
+ borderRadius: 4,
+ background: "rgba(255,255,255,0.85)",
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: fontSize,
+ fontWeight: 700,
+ color: color,
+ textAlign: "left" as const,
+ padding: `0 ${(layout.padding / 100) * pageWidth}px`,
+ lineHeight: TEXT_LINE_HEIGHT,
+ caretColor: "#08C225",
+ }}
+ />
+ );
+ })()}
+ {selectedPageId === page.id &&
+ selectedTextId &&
+ !editingTextId &&
+ (() => {
+ const block = page.textBlocks.find(
+ (t) => t.id === selectedTextId,
+ );
+ if (!block) return null;
+ return (
+ <TextToolbar
+ block={getTextBlockLayout(block)}
+ pageWidth={pageWidth}
+ pageHeight={pageHeight}
+ onUpdate={(updates) =>
+ onTextUpdate(page.id, block.id, updates)
+ }
+ onDelete={() => onTextDelete(page.id, block.id)}
+ onEdit={() => onTextDblClick(page.id, block.id)}
+ />
+ );
+ })()}
+ {photoCount === 0 &&
+ (page.centerText ||
+ (!isBackCover && page.textBlocks.length === 0)) &&
+ (() => {
+ const value = editingCenterText
+ ? centerTextDraft
+ : (page.centerText ?? "");
+ const layout = getCenterTextLayout({
+ ...page,
+ centerText: value,
+ });
+ if (!layout) return null;
+ const style: React.CSSProperties = {
+ position: "absolute",
+ left: (layout.x / 100) * pageWidth,
+ top: (layout.y / 100) * pageHeight,
+ width: (layout.width / 100) * pageWidth,
+ height: (layout.height / 100) * pageHeight,
+ boxSizing: "border-box",
+ zIndex: 4,
+ padding: `0 ${(layout.padding / 100) * pageWidth}px`,
+ border: "none",
+ background: "transparent",
+ fontFamily: "var(--font-outfit), sans-serif",
+ fontSize: (layout.fontSize / 100) * pageHeight,
+ fontWeight: CENTER_TEXT_FONT_WEIGHT,
+ lineHeight: layout.lineHeight,
+ textAlign: "center",
+ color: page.centerText ? "#2a2a2a" : "#aaa",
+ pointerEvents:
+ dragSourceInfo || pageDragSource !== null
+ ? "none"
+ : "auto",
+ };
+ return editingCenterText ? (
+ <textarea
+ autoFocus
+ aria-label="Page text"
+ placeholder="Add text..."
+ value={value}
+ wrap="soft"
+ onChange={(event) =>
+ setCenterTextDraft(event.target.value)
+ }
+ onBlur={(event) => {
+ if (
+ event.currentTarget.value !==
+ (page.centerText ?? "")
+ ) {
+ updatePage(page.id, {
+ centerText:
+ event.currentTarget.value,
+ });
+ }
+ setEditingCenterText(false);
+ }}
+ onKeyDown={(event) => {
+ if (
+ !event.nativeEvent.isComposing &&
+ (event.key === "Escape" ||
+ (event.key === "Enter" &&
+ (event.metaKey ||
+ event.ctrlKey)))
+ ) {
+ event.preventDefault();
+ event.currentTarget.blur();
+ }
+ }}
+ style={{
+ ...style,
+ color: "#2a2a2a",
+ outline: "none",
+ resize: "none",
+ overflow: "hidden",
+ whiteSpace: "pre-wrap",
+ overflowWrap: "anywhere",
+ }}
+ />
+ ) : (
+ <button
+ type="button"
+ aria-label={
+ page.centerText
+ ? "Edit page text"
+ : "Add text..."
+ }
+ onClick={(event) => {
+ event.stopPropagation();
+ onClearSelection();
+ setCenterTextDraft(page.centerText ?? "");
+ setEditingCenterText(true);
+ }}
+ style={{
+ ...style,
+ cursor: "text",
+ whiteSpace: "pre",
+ overflow: "hidden",
+ }}
+ >
+ {layout.lines.join("\n")}
+ </button>
+ );
+ })()}
+ {showEmptyPageAddPhotos && (
+ <Button
+ type="button"
+ aria-label={`Add photos to page ${pageIndex}`}
+ startIcon={<AddPhotosIcon />}
+ disabled={processingPhotos}
+ disableRipple
+ onClick={(event) => {
+ event.stopPropagation();
+ onClearSelection();
+ onAddPhotos(page.id);
+ }}
+ sx={{
+ position: "absolute",
+ left: "50%",
+ bottom: Math.max(16, pageHeight * 0.07),
+ transform: "translateX(-50%)",
+ zIndex: 4,
+ minWidth: 0,
+ maxWidth: "calc(100% - 24px)",
+ height: 36,
+ px: "14px",
+ borderRadius: "999px",
+ bgcolor: "#F1F3F2",
+ color: "#59635D",
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: 13,
+ fontWeight: 500,
+ textTransform: "none",
+ whiteSpace: "nowrap",
+ boxShadow: "none",
+ pointerEvents:
+ dragSourceInfo || pageDragSource !== null
+ ? "none"
+ : "auto",
+ transition:
+ "background-color 120ms ease, color 120ms ease",
+ "& .MuiButton-startIcon": { ml: 0, mr: "6px" },
+ "& .MuiSvgIcon-root": { fontSize: 17 },
+ "&:hover": { bgcolor: "#E4F1E7", color: "#246B37" },
+ "&:focus-visible": {
+ bgcolor: "#E4F1E7",
+ color: "#246B37",
+ outline: "2px solid #08C225",
+ outlineOffset: 2,
+ },
+ }}
+ >
+ Add photos
+ </Button>
+ )}
+ {(["top", "bottom"] as const).map((position) => {
+ if (position === "bottom" && isBackCover) return null;
+ const key =
+ position === "top" ? "topCaption" : "bottomCaption";
+ const isEditing = editingCaption === position;
+ const captionPage = isEditing
+ ? { ...page, [key]: captionValue }
+ : page;
+ const layout = getCaptionLayout(
+ captionPage,
+ position,
+ isFrontCover,
+ );
+ if (!layout) return null;
+ const style: React.CSSProperties = {
+ position: "absolute",
+ left: (layout.x / 100) * pageWidth,
+ top: (layout.y / 100) * pageHeight,
+ width: (layout.width / 100) * pageWidth,
+ height: (layout.height / 100) * pageHeight,
+ fontFamily: isFrontCover
+ ? "var(--font-outfit), sans-serif"
+ : "var(--font-inter), sans-serif",
+ fontSize: (layout.fontSize / 100) * pageHeight,
+ fontWeight: isFrontCover
+ ? CENTER_TEXT_FONT_WEIGHT
+ : CAPTION_FONT_WEIGHT,
+ lineHeight: TEXT_LINE_HEIGHT,
+ color: "#2a2a2a",
+ textAlign: "center",
+ boxSizing: "border-box",
+ };
+ return isEditing ? (
+ <input
+ key={position}
+ ref={captionInputRef}
+ value={captionValue}
+ onChange={(e) => setCaptionValue(e.target.value)}
+ onBlur={handleCaptionSave}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") handleCaptionSave();
+ if (e.key === "Escape") handleCaptionCancel();
+ }}
+ style={{
+ ...style,
+ zIndex: 5,
+ border: "none",
+ outline: "none",
+ background: "white",
+ padding: 0,
+ }}
+ />
+ ) : (
+ <div
+ key={position}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleCaptionClick(position);
+ }}
+ style={{
+ ...style,
+ zIndex: 4,
+ cursor: "text",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ overflow: "hidden",
+ whiteSpace: "nowrap",
+ pointerEvents: dragSourceInfo ? "none" : "auto",
+ }}
+ >
+ <span
+ style={{
+ color: page[key] ? "#2a2a2a" : "#aaa",
+ pointerEvents: "none",
+ }}
+ >
+ {page[key] ||
+ (isFrontCover
+ ? "Add title..."
+ : "Add caption...")}
+ </span>
+ </div>
+ );
+ })}
+ </Box>
+ <Typography
+ sx={{
+ fontSize: { xs: 12, sm: 14 },
+ lineHeight: { xs: "16px", sm: "18px" },
+ color: uiColors.muted,
+ fontWeight: 600,
+ textAlign: "center",
+ mt: 0.5,
+ }}
+ >
+ {pageIndex === 0
+ ? "Cover"
+ : pageIndex === totalPages - 1
+ ? "Back cover"
+ : pageIndex}
+ </Typography>
+ </Box>
+ );
+
+ const slotThumbnails = page.slots
+ .filter((s) => s.photoId !== null)
+ .map((s) => thumbnailUrls.get(s.photoId!) ?? "");
+
+ const showPicker = photoCount > 0 && !hideLayoutPicker;
+ const pickerContainer = (
+ <Box
+ sx={{
+ width: PICKER_WIDTH,
+ height: pageHeight,
+ flexShrink: 0,
+ display: "flex",
+ flexDirection: "column",
+ alignItems: pickerSide === "left" ? "flex-end" : "flex-start",
+ ...(pickerSide === "left" ? { pr: 1 } : { pl: 1 }),
+ gap: 1,
+ }}
+ >
+ {showPicker && (
+ <Box
+ data-page-control
+ sx={{
+ minHeight: 0,
+ overflowY: "auto",
+ p: "2px",
+ m: "-2px",
+ }}
+ >
+ <LayoutPicker
+ photoCount={photoCount}
+ currentVariant={page.layoutVariant}
+ thumbnailUrls={slotThumbnails}
+ onSelect={(key) => setPageLayout(page.id, key)}
+ isFrontCover={isFrontCover}
+ />
+ </Box>
+ )}
+ <PageMenu
+ key={page.id}
+ pageId={page.id}
+ pageIndex={pageIndex}
+ totalPages={totalPages}
+ side={pickerSide}
+ photoCount={photoCount}
+ requiredBlank={isRequiredBlankPage(book.pages, page.id)}
+ onAddPhotos={() => onAddPhotos(page.id)}
+ onInsert={(position) => onInsertPage(pageIndex, position)}
+ onDelete={() => {
+ onClearSelection();
+ removePage(page.id);
+ }}
+ />
+ </Box>
+ );
+
+ return (
+ <Box
+ sx={{
+ display: "flex",
+ flexDirection: "row",
+ alignItems: "start",
+ "& [data-page-control]": {
+ opacity: 0,
+ pointerEvents: "none",
+ transition: "opacity 120ms ease-out",
+ },
+ '&:hover [data-page-control], &:focus-within [data-page-control], &:has([data-page-control][data-open="true"]) [data-page-control], & [data-page-control][data-open="true"]':
+ { opacity: 1, pointerEvents: "auto" },
+ "@media (hover: none)": {
+ "& [data-page-control]": {
+ opacity: 1,
+ pointerEvents: "auto",
+ },
+ },
+ "@media (prefers-reduced-motion: reduce)": {
+ "& [data-page-control]": { transition: "none" },
+ },
+ }}
+ >
+ {pickerSide === "left" && pickerContainer}
+ {pageBlock}
+ {pickerSide === "right" && pickerContainer}
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/StartPage.tsx b/web/apps/photobook/src/components/StartPage.tsx
new file mode 100644
index 0000000000..70b2276f72
--- /dev/null
+++ b/web/apps/photobook/src/components/StartPage.tsx
@@ -0,0 +1,302 @@
+import { useBook } from "@/context/book";
+import { usePhotoImport } from "@/hooks/usePhotoImport";
+import { Alert, Box, Button, TextField, Typography } from "@mui/material";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
+import NavBar from "./NavBar";
+
+export default function StartPage() {
+ const router = useRouter();
+ const { loading } = useBook();
+ useEffect(() => {
+ void router.prefetch("/app");
+ }, [router]);
+ const {
+ fileInputRef,
+ dragOver,
+ enteUrl,
+ setEnteUrl,
+ enteError,
+ importError,
+ importing,
+ handleImportEnte,
+ handleFiles,
+ handleDrop,
+ handleDragOver,
+ handleDragLeave,
+ } = usePhotoImport();
+ const busy = loading || importing;
+
+ return (
+ <Box
+ sx={{
+ minHeight: "100vh",
+ bgcolor: "#fff",
+ color: "#1A1C1D",
+ display: "flex",
+ flexDirection: "column",
+ position: "relative",
+ overflow: "hidden",
+ }}
+ >
+ <NavBar />
+ <Box
+ component="main"
+ onDrop={busy ? undefined : handleDrop}
+ onDragOver={busy ? undefined : handleDragOver}
+ onDragLeave={handleDragLeave}
+ sx={{
+ flex: 1,
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ position: "relative",
+ px: 3,
+ pt: { xs: "128px", sm: "170px" },
+ pb: 8,
+ }}
+ >
+ {dragOver && (
+ <Box
+ sx={{
+ position: "absolute",
+ inset: 0,
+ zIndex: 30,
+ bgcolor: "rgba(8,194,37,0.08)",
+ border: "3px dashed #08C225",
+ borderRadius: 2,
+ display: "grid",
+ placeItems: "center",
+ pointerEvents: "none",
+ }}
+ >
+ <Typography
+ sx={{
+ fontSize: "1.5rem",
+ fontWeight: 700,
+ color: "#08C225",
+ }}
+ >
+ Drop your photos here
+ </Typography>
+ </Box>
+ )}
+ <Box
+ sx={{
+ position: "relative",
+ zIndex: 10,
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ textAlign: "center",
+ maxWidth: 1100,
+ width: "100%",
+ }}
+ >
+ <Typography
+ component="h1"
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: { xs: "2.5rem", md: "4rem" },
+ fontWeight: 800,
+ letterSpacing: "-0.02em",
+ mb: 2,
+ lineHeight: 1.1,
+ color: "#1A1C1D",
+ }}
+ >
+ Your memories deserve a book
+ </Typography>
+ <Typography
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: "1.15rem",
+ color: "#666",
+ maxWidth: 560,
+ lineHeight: 1.7,
+ mb: 6,
+ }}
+ >
+ Drop in your photos and get a print-ready photobook.
+ <br />
+ Beautifully arranged, completely private, and free.
+ </Typography>
+ <Box
+ sx={{
+ mb: 8,
+ position: "relative",
+ "& .card": { transition: "transform 0.5s ease" },
+ "&:hover .card": {
+ transform: "rotate(0deg) !important",
+ },
+ }}
+ >
+ <Box
+ className="card"
+ component="img"
+ src="/hero-photo.jpg"
+ alt="A photobook page with photos from Delhi"
+ draggable={false}
+ sx={{
+ width: { xs: 260, md: 380 },
+ maxWidth: "100%",
+ height: "auto",
+ borderRadius: 2,
+ boxShadow:
+ "0px 16px 40px rgba(0,0,0,0.15), 0px 4px 12px rgba(0,0,0,0.08)",
+ transform: "rotate(-3deg)",
+ position: "relative",
+ zIndex: 20,
+ userSelect: "none",
+ pointerEvents: "none",
+ }}
+ />
+ </Box>
+ <Button
+ variant="contained"
+ size="large"
+ disabled={busy}
+ onClick={() => fileInputRef.current?.click()}
+ sx={{
+ bgcolor: "#08C225",
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: "1.15rem",
+ fontWeight: 700,
+ px: 6,
+ py: 2,
+ boxShadow: "none",
+ "&:hover": {
+ transform: "scale(1.02)",
+ bgcolor: "#07AE22",
+ },
+ "&:active": { transform: "scale(0.95)" },
+ transition:
+ "transform 0.3s ease, background-color 0.3s ease",
+ }}
+ >
+ Add photos
+ </Button>
+ {importError && (
+ <Alert severity="error" sx={{ mt: 2, maxWidth: 480 }}>
+ {importError}
+ </Alert>
+ )}
+ <Box
+ component="form"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (!busy && enteUrl.trim())
+ void handleImportEnte();
+ }}
+ sx={{ mt: 3, mb: 3, width: "100%", maxWidth: 480 }}
+ >
+ <Typography
+ component="label"
+ htmlFor="landing-album-url"
+ sx={{
+ display: "block",
+ mb: 1.5,
+ color: "#777",
+ fontSize: 14,
+ }}
+ >
+ or import an Ente album
+ </Typography>
+ <Box sx={{ display: "flex", gap: 1 }}>
+ <TextField
+ id="landing-album-url"
+ fullWidth
+ placeholder="Paste an album link"
+ value={enteUrl}
+ onChange={(event) =>
+ setEnteUrl(event.target.value)
+ }
+ error={Boolean(enteError)}
+ autoComplete="off"
+ disabled={busy}
+ slotProps={{
+ htmlInput: {
+ inputMode: "url",
+ spellCheck: false,
+ "aria-describedby": enteError
+ ? "landing-import-error"
+ : undefined,
+ },
+ }}
+ sx={{
+ "& .MuiOutlinedInput-root": {
+ height: 48,
+ borderRadius: "14px",
+ color: "#333",
+ bgcolor: "#FFF",
+ fontSize: 14,
+ "& fieldset": { borderColor: "#DDD" },
+ "&:hover fieldset": {
+ borderColor: "#BBB",
+ },
+ "&.Mui-focused fieldset": {
+ borderColor: "#08C225",
+ },
+ },
+ }}
+ />
+ <Button
+ type="submit"
+ disabled={busy || !enteUrl.trim()}
+ sx={{
+ height: 48,
+ px: 2.5,
+ borderRadius: "14px",
+ color: "#006E0F",
+ bgcolor: "#EEF8EF",
+ "&:hover": { bgcolor: "#E1F2E3" },
+ "&.Mui-disabled": {
+ color: "#999",
+ bgcolor: "#F2F2F2",
+ },
+ }}
+ >
+ Import
+ </Button>
+ </Box>
+ {enteError && (
+ <Alert
+ id="landing-import-error"
+ severity="error"
+ sx={{
+ mt: 2,
+ borderRadius: 2,
+ textAlign: "left",
+ }}
+ >
+ {enteError}
+ </Alert>
+ )}
+ </Box>
+ <Typography
+ sx={{
+ fontFamily: "var(--font-inter), sans-serif",
+ fontSize: "0.85rem",
+ color: "#999",
+ letterSpacing: "0.04em",
+ }}
+ >
+ Print-ready. Auto-arranged. 100% in your browser.
+ </Typography>
+ </Box>
+ </Box>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/heic,image/heif,.heic,.heif"
+ multiple
+ style={{ display: "none" }}
+ onChange={(event) => {
+ if (event.currentTarget.files)
+ void handleFiles(event.currentTarget.files);
+ event.currentTarget.value = "";
+ }}
+ />
+ </Box>
+ );
+}
diff --git a/web/apps/photobook/src/components/TextToolbar.tsx b/web/apps/photobook/src/components/TextToolbar.tsx
new file mode 100644
index 0000000000..a993c605bb
--- /dev/null
+++ b/web/apps/photobook/src/components/TextToolbar.tsx
@@ -0,0 +1,350 @@
+import type { TextBlock } from "@/lib/types";
+import { popupShadow, uiColors } from "@/theme/colors";
+import React, { useEffect, useRef, useState } from "react";
+import { CloseIcon, DeleteIcon, EditIcon, RotateIcon } from "./icons";
+
+const PRESET_COLORS = [
+ "#555555",
+ "#ffffff",
+ "#08C225",
+ "#3B82F6",
+ "#EF4444",
+ "#F59E0B",
+ "#8B5CF6",
+ "#EC4899",
+];
+
+const FONT_SIZES = [
+ { label: "S", value: 2 },
+ { label: "M", value: 3 },
+ { label: "L", value: 4.5 },
+ { label: "XL", value: 6 },
+];
+
+interface TextToolbarProps {
+ block: TextBlock;
+ pageWidth: number;
+ pageHeight: number;
+ onUpdate: (updates: Partial<TextBlock>) => void;
+ onDelete: () => void;
+ onEdit: () => void;
+}
+
+export default function TextToolbar({
+ block,
+ pageWidth,
+ pageHeight,
+ onUpdate,
+ onDelete,
+ onEdit,
+}: TextToolbarProps) {
+ const [showColors, setShowColors] = useState(false);
+ const [showRotation, setShowRotation] = useState(false);
+ const colorRef = useRef<HTMLDivElement>(null);
+ const rotationRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!showColors && !showRotation) return;
+ const handler = (e: MouseEvent) => {
+ if (
+ showColors &&
+ colorRef.current &&
+ !colorRef.current.contains(e.target as Node)
+ ) {
+ setShowColors(false);
+ }
+ if (
+ showRotation &&
+ rotationRef.current &&
+ !rotationRef.current.contains(e.target as Node)
+ ) {
+ setShowRotation(false);
+ }
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [showColors, showRotation]);
+
+ const bx = (block.x / 100) * pageWidth;
+ const by = (block.y / 100) * pageHeight;
+ const bw = (block.width / 100) * pageWidth;
+
+ const toolbarLeft = bx + bw / 2;
+ const toolbarTop = by - 44;
+
+ const currentSize = FONT_SIZES.find(
+ (s) => Math.abs(s.value - (block.fontSize ?? 2.5)) < 0.3,
+ );
+
+ const btnStyle: React.CSSProperties = {
+ width: 28,
+ height: 28,
+ border: "none",
+ background: "transparent",
+ color: uiColors.text,
+ cursor: "pointer",
+ borderRadius: 4,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ fontSize: 13,
+ fontFamily: "var(--font-inter), sans-serif",
+ padding: 0,
+ transition: "background 0.15s",
+ };
+
+ const activeBtnStyle: React.CSSProperties = {
+ ...btnStyle,
+ background: uiColors.control,
+ color: uiColors.text,
+ };
+
+ const handleSizeChange = () => {
+ const currentIdx = FONT_SIZES.findIndex(
+ (s) => Math.abs(s.value - (block.fontSize ?? 2.5)) < 0.3,
+ );
+ const nextIdx = (currentIdx + 1) % FONT_SIZES.length;
+ onUpdate({
+ fontSize: FONT_SIZES[nextIdx]!.value,
+ style: FONT_SIZES[nextIdx]!.value >= 4 ? "title" : "body",
+ });
+ };
+
+ const rotation = block.rotation ?? 0;
+
+ return (
+ <div
+ style={{
+ position: "absolute",
+ left: toolbarLeft,
+ top: toolbarTop,
+ transform: "translateX(-50%)",
+ zIndex: 20,
+ display: "flex",
+ alignItems: "center",
+ gap: 2,
+ background: uiColors.surface,
+ backdropFilter: "blur(12px)",
+ borderRadius: 8,
+ padding: "3px 4px",
+ boxShadow: popupShadow,
+ }}
+ onMouseDown={(e) => e.stopPropagation()}
+ >
+ <button
+ style={btnStyle}
+ onClick={onEdit}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.background = uiColors.background)
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.background = "transparent")
+ }
+ title="Edit text"
+ >
+ <EditIcon sx={{ fontSize: 14 }} />
+ </button>
+
+ <div
+ style={{ width: 1, height: 18, background: uiColors.border }}
+ />
+
+ <button
+ style={{
+ ...btnStyle,
+ fontWeight: 700,
+ fontSize: 12,
+ width: 32,
+ }}
+ onClick={handleSizeChange}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.background = uiColors.background)
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.background = "transparent")
+ }
+ title="Font size"
+ >
+ {currentSize?.label ?? "M"}
+ </button>
+
+ <div ref={colorRef} style={{ position: "relative" }}>
+ <button
+ style={btnStyle}
+ onClick={() => {
+ setShowColors(!showColors);
+ setShowRotation(false);
+ }}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.background = uiColors.background)
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.background = "transparent")
+ }
+ title="Text color"
+ >
+ <div
+ style={{
+ width: 16,
+ height: 16,
+ borderRadius: 3,
+ background: block.color ?? "#555555",
+ border: `2px solid ${uiColors.border}`,
+ }}
+ />
+ </button>
+ {showColors && (
+ <div
+ style={{
+ position: "absolute",
+ top: "calc(100% + 6px)",
+ left: "50%",
+ transform: "translateX(-50%)",
+ background: uiColors.surface,
+ backdropFilter: "blur(12px)",
+ borderRadius: 8,
+ padding: 6,
+ display: "grid",
+ gridTemplateColumns: "repeat(4, 1fr)",
+ gap: 4,
+ boxShadow: popupShadow,
+ }}
+ >
+ {PRESET_COLORS.map((c) => (
+ <button
+ key={c}
+ onClick={() => {
+ onUpdate({ color: c });
+ setShowColors(false);
+ }}
+ style={{
+ width: 24,
+ height: 24,
+ borderRadius: 4,
+ background: c,
+ border:
+ (block.color ?? "#555555") === c
+ ? "2px solid #08C225"
+ : c === "#ffffff"
+ ? `1px solid ${uiColors.muted}`
+ : `1px solid ${uiColors.border}`,
+ cursor: "pointer",
+ padding: 0,
+ }}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div ref={rotationRef} style={{ position: "relative" }}>
+ <button
+ style={rotation !== 0 ? activeBtnStyle : btnStyle}
+ onClick={() => {
+ setShowRotation(!showRotation);
+ setShowColors(false);
+ }}
+ onMouseEnter={(e) => {
+ if (rotation === 0)
+ e.currentTarget.style.background =
+ uiColors.background;
+ }}
+ onMouseLeave={(e) => {
+ if (rotation === 0)
+ e.currentTarget.style.background = "transparent";
+ }}
+ title={`Rotate (${Math.round(rotation)}Β°)`}
+ >
+ <RotateIcon sx={{ fontSize: 14 }} />
+ </button>
+ {showRotation && (
+ <div
+ style={{
+ position: "absolute",
+ top: "calc(100% + 6px)",
+ left: "50%",
+ transform: "translateX(-50%)",
+ background: uiColors.surface,
+ backdropFilter: "blur(12px)",
+ borderRadius: 8,
+ padding: "8px 12px",
+ boxShadow: popupShadow,
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ whiteSpace: "nowrap",
+ }}
+ >
+ <input
+ type="range"
+ min={-180}
+ max={180}
+ step={1}
+ value={rotation}
+ onChange={(e) =>
+ onUpdate({ rotation: Number(e.target.value) })
+ }
+ style={{
+ width: 120,
+ accentColor: "#08C225",
+ cursor: "pointer",
+ }}
+ />
+ <span
+ style={{
+ color: uiColors.muted,
+ fontSize: 11,
+ fontFamily: "var(--font-inter), sans-serif",
+ minWidth: 32,
+ textAlign: "right",
+ }}
+ >
+ {Math.round(rotation)}Β°
+ </span>
+ {rotation !== 0 && (
+ <button
+ onClick={() => onUpdate({ rotation: 0 })}
+ style={{
+ ...btnStyle,
+ width: 20,
+ height: 20,
+ fontSize: 11,
+ color: uiColors.muted,
+ }}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.background =
+ uiColors.background)
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.background =
+ "transparent")
+ }
+ title="Reset rotation"
+ >
+ <CloseIcon sx={{ fontSize: 12 }} />
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div
+ style={{ width: 1, height: 18, background: uiColors.border }}
+ />
+
+ <button
+ style={{ ...btnStyle, color: uiColors.danger }}
+ onClick={onDelete}
+ onMouseEnter={(e) =>
+ (e.currentTarget.style.background = "rgba(255,80,80,0.15)")
+ }
+ onMouseLeave={(e) =>
+ (e.currentTarget.style.background = "transparent")
+ }
+ title="Delete text"
+ >
+ <DeleteIcon sx={{ fontSize: 14 }} />
+ </button>
+ </div>
+ );
+}
diff --git a/web/apps/photobook/src/components/editorLayout.ts b/web/apps/photobook/src/components/editorLayout.ts
new file mode 100644
index 0000000000..123694035f
--- /dev/null
+++ b/web/apps/photobook/src/components/editorLayout.ts
@@ -0,0 +1,22 @@
+import { uiColors } from "@/theme/colors";
+
+export const EDITOR_SIDEBAR_WIDTH = { xs: 156, sm: 366 };
+export const EDITOR_CANVAS_PADDING = 16;
+export const EDITOR_HEADER_HEIGHT = { xs: 60, sm: 76 };
+export const EDITOR_PANEL_INSET = { xs: "8px", sm: "12px" };
+export const EDITOR_PANEL_BOTTOM_INSET = { xs: "8px", sm: "11px" };
+export const EDITOR_PANEL_SX = {
+ bgcolor: uiColors.surface,
+ borderRadius: "24px",
+} as const;
+
+export const EDITOR_SCROLLBAR_SX = {
+ "&::-webkit-scrollbar": { width: "4px", height: "4px" },
+ "&::-webkit-scrollbar-track": { bgcolor: "transparent" },
+ "&::-webkit-scrollbar-thumb": { bgcolor: "#484848", borderRadius: "2px" },
+ "&::-webkit-scrollbar-thumb:hover": { bgcolor: "#666666" },
+ "@supports not selector(::-webkit-scrollbar)": {
+ scrollbarWidth: "thin",
+ scrollbarColor: "#484848 transparent",
+ },
+} as const;
diff --git a/web/apps/photobook/src/components/icons.tsx b/web/apps/photobook/src/components/icons.tsx
new file mode 100644
index 0000000000..6ba1920ebf
--- /dev/null
+++ b/web/apps/photobook/src/components/icons.tsx
@@ -0,0 +1,132 @@
+import {
+ Alert02Icon,
+ AlertCircleIcon,
+ ArrowDown01Icon,
+ ArrowLeft01Icon,
+ ArrowRight01Icon,
+ Cancel01Icon,
+ CheckmarkCircle02Icon,
+ Delete02Icon,
+ Download04Icon,
+ Edit02Icon,
+ FileAddIcon,
+ ImageAdd02Icon,
+ InformationCircleIcon,
+ Link01Icon,
+ Menu01Icon,
+ MoreHorizontalIcon,
+ PlayIcon,
+ Redo03Icon,
+ RotateCcwIcon,
+ SearchAddIcon,
+ SearchMinusIcon,
+ Undo03Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";
+import SvgIcon, { type SvgIconProps } from "@mui/material/SvgIcon";
+import { forwardRef } from "react";
+
+const AppIcon = forwardRef<
+ SVGSVGElement,
+ SvgIconProps & { icon: IconSvgElement }
+>(({ icon, ...props }, ref) => (
+ <SvgIcon
+ {...props}
+ ref={ref}
+ component={HugeiconsIcon}
+ icon={icon}
+ strokeWidth={Number(props.strokeWidth ?? 1.8)}
+ inheritViewBox
+ style={{ ...props.style, fill: "none" }}
+ />
+));
+
+export const AddPhotosIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={ImageAdd02Icon} />,
+);
+export const EditPhotoIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => (
+ <SvgIcon {...props} ref={ref}>
+ <g
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.8}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M10.5 21H8a5 5 0 0 1-5-5V8a5 5 0 0 1 5-5h8a5 5 0 0 1 5 5v1.5" />
+ <path d="m3 16 4.47-4.47a1.81 1.81 0 0 1 2.56 0L13 14.5" />
+ <circle cx={16.5} cy={7.5} r={0.5} />
+ <path d="m18.5 15 1.5 1.5m1.43-3.07.14.14a1.48 1.48 0 0 1 0 2.08l-4.76 4.76a2 2 0 0 1-1.42.59h-.89a.5.5 0 0 1-.5-.5v-.89a2 2 0 0 1 .59-1.42l4.76-4.76a1.48 1.48 0 0 1 2.08 0Z" />
+ </g>
+ </SvgIcon>
+ ),
+);
+EditPhotoIcon.displayName = "EditPhotoIcon";
+export const AddPageIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={FileAddIcon} />,
+);
+export const PreviewIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={PlayIcon} />,
+);
+export const CloseIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Cancel01Icon} />,
+);
+export const ChevronLeftIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={ArrowLeft01Icon} />,
+);
+export const ChevronRightIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={ArrowRight01Icon} />,
+);
+export const ChevronDownIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={ArrowDown01Icon} />,
+);
+export const EditIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Edit02Icon} />,
+);
+export const DownloadIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Download04Icon} />,
+);
+export const LinkIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Link01Icon} />,
+);
+export const MenuIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Menu01Icon} />,
+);
+export const MoreIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={MoreHorizontalIcon} />,
+);
+export const DeleteIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Delete02Icon} />,
+);
+export const ZoomInIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={SearchAddIcon} />,
+);
+export const ZoomOutIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={SearchMinusIcon} />,
+);
+export const RotateIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={RotateCcwIcon} />,
+);
+export const UndoIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Undo03Icon} />,
+);
+export const RedoIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Redo03Icon} />,
+);
+export const SuccessIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => (
+ <AppIcon {...props} ref={ref} icon={CheckmarkCircle02Icon} />
+ ),
+);
+export const InfoIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => (
+ <AppIcon {...props} ref={ref} icon={InformationCircleIcon} />
+ ),
+);
+export const WarningIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={Alert02Icon} />,
+);
+export const ErrorIcon = forwardRef<SVGSVGElement, SvgIconProps>(
+ (props, ref) => <AppIcon {...props} ref={ref} icon={AlertCircleIcon} />,
+);
diff --git a/web/apps/photobook/src/context/BookContext.tsx b/web/apps/photobook/src/context/BookContext.tsx
new file mode 100644
index 0000000000..c42f7c663d
--- /dev/null
+++ b/web/apps/photobook/src/context/BookContext.tsx
@@ -0,0 +1,1495 @@
+import {
+ isBlankPage,
+ isRequiredBlankPage,
+ makeBlankPage,
+ normalizeBookPages,
+} from "@/lib/bookPages";
+import {
+ clearAll,
+ getAppView,
+ getBookState,
+ getPhotos,
+ getPreview,
+ getThumbnail,
+ saveAppView,
+ saveBookState,
+ savePhotoBlob,
+ savePhotos,
+ savePreview,
+ saveThumbnail,
+} from "@/lib/db";
+import type { EnteCredentials, EnteFileDescriptor } from "@/lib/ente/types";
+import { clearImageCache } from "@/lib/imageCache";
+import {
+ createThumbnail,
+ extractExifDate,
+ normalizeImportedImageBlob,
+} from "@/lib/images";
+import {
+ applyVariant,
+ chooseBestLayout,
+ chooseBestVariantKey,
+ generateAutoLayout,
+ getVariantPreview,
+ getVariantsForCount,
+} from "@/lib/layouts";
+import {
+ availablePhotoSpaces,
+ normalizeFrontCover,
+ photoDestinationError,
+ placeImportedPhotos,
+ type AddPhotosOptions,
+} from "@/lib/photoPlacement";
+import { constrainTextBlock } from "@/lib/printLayout";
+import type {
+ AppView,
+ BookPage,
+ BookState,
+ Photo,
+ PhotoOriginalStatus,
+ PhotoSlot,
+ TextBlock,
+} from "@/lib/types";
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { BookContext } from "./book";
+
+const emptyBook: BookState = { pages: [], currentSpreadIndex: 0 };
+
+function isPendingEnteOriginal(photo: Photo): boolean {
+ return photo.source === "ente" && photo.originalStatus === "pending";
+}
+
+function pagePhotoIds(page: BookPage): string[] {
+ return page.slots
+ .map((s) => s.photoId)
+ .filter((id): id is string => id !== null);
+}
+
+function normalizeCoverLayout(state: BookState): BookState {
+ if (state.pages.length === 0) return state;
+ let pages = normalizeFrontCover(state.pages);
+
+ const cover = pages[0]!;
+ const coverIds = pagePhotoIds(cover);
+ const hasCoverLayout = getVariantsForCount(1, true).some(
+ (variant) => variant.key === cover.layoutVariant,
+ );
+ if (coverIds.length === 1 && !hasCoverLayout) {
+ pages = pages.map((p, i) =>
+ i === 0
+ ? {
+ ...p,
+ slots: cover.slots
+ .filter((slot) => slot.photoId)
+ .map((slot) => ({
+ ...slot,
+ ...getVariantPreview("1-full")[0],
+ })),
+ layoutVariant: "1-full",
+ }
+ : p,
+ );
+ }
+
+ pages = normalizeBookPages(pages);
+ pages = pages.map((page) => {
+ const textBlocks = page.textBlocks.map(constrainTextBlock);
+ return textBlocks.some((block, i) => block !== page.textBlocks[i])
+ ? { ...page, textBlocks }
+ : page;
+ });
+
+ return pages === state.pages ? state : { ...state, pages };
+}
+
+function buildEnteOriginalDownloadJob(
+ photo: Photo,
+): { credentials: EnteCredentials; descriptor: EnteFileDescriptor } | null {
+ const data = photo.enteOriginal;
+ if (!data) return null;
+
+ return {
+ credentials: {
+ downloadOrigin: data.downloadOrigin,
+ accessToken: data.accessToken,
+ accessTokenJWT: data.accessTokenJWT,
+ },
+ descriptor: {
+ enteFileId: data.enteFileId,
+ fileKey: data.fileKey,
+ mediaKind: data.mediaKind,
+ thumbnailDecryptionHeader: "",
+ fileDecryptionHeader: data.fileDecryptionHeader,
+ fileName: photo.fileName,
+ dateTaken: photo.dateTaken,
+ width: photo.width,
+ height: photo.height,
+ },
+ };
+}
+
+export function BookProvider({ children }: { children: React.ReactNode }) {
+ const [appView, setAppViewState] = useState<AppView>("edit");
+ const [loading, setLoading] = useState(true);
+ const [photos, setPhotos] = useState<Photo[]>([]);
+ const photosRef = useRef<Photo[]>(photos);
+ photosRef.current = photos;
+ const [thumbnailUrls, setThumbnailUrls] = useState<Map<string, string>>(
+ new Map(),
+ );
+ const thumbnailUrlsRef = useRef<Map<string, string>>(thumbnailUrls);
+ thumbnailUrlsRef.current = thumbnailUrls;
+ const [previewUrls, setPreviewUrls] = useState<Map<string, string>>(
+ new Map(),
+ );
+ const previewUrlsRef = useRef<Map<string, string>>(previewUrls);
+ previewUrlsRef.current = previewUrls;
+ const [book, setBookRaw] = useState<BookState>(emptyBook);
+ const [currentSpreadIndex, setCurrentSpreadIndex] = useState(0);
+ const resettingRef = useRef(false);
+ const isResetting = useCallback(() => resettingRef.current, []);
+ const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const autosaveRef = useRef<Promise<unknown>>(Promise.resolve());
+ const originalWritesRef = useRef<Set<Promise<unknown>>>(new Set());
+
+ useEffect(() => {
+ return () => {
+ thumbnailUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
+ previewUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
+ };
+ }, []);
+
+ const undoStackRef = useRef<BookState[]>([]);
+ const redoStackRef = useRef<BookState[]>([]);
+ const [canUndo, setCanUndo] = useState(false);
+ const [canRedo, setCanRedo] = useState(false);
+ const MAX_HISTORY = 50;
+
+ const setBook: React.Dispatch<React.SetStateAction<BookState>> =
+ useCallback((action) => {
+ setBookRaw((prev) => {
+ undoStackRef.current = [
+ ...undoStackRef.current.slice(-(MAX_HISTORY - 1)),
+ prev,
+ ];
+ redoStackRef.current = [];
+ const next =
+ typeof action === "function" ? action(prev) : action;
+ const pages = normalizeBookPages(
+ normalizeFrontCover(next.pages),
+ );
+ return pages === next.pages ? next : { ...next, pages };
+ });
+ setCanUndo(true);
+ setCanRedo(false);
+ }, []);
+
+ const undo = useCallback(() => {
+ if (undoStackRef.current.length === 0) return;
+ setBookRaw((current) => {
+ const prev = undoStackRef.current.pop()!;
+ redoStackRef.current = [...redoStackRef.current, current];
+ setCanUndo(undoStackRef.current.length > 0);
+ setCanRedo(true);
+ return normalizeCoverLayout(prev);
+ });
+ }, []);
+
+ const redo = useCallback(() => {
+ if (redoStackRef.current.length === 0) return;
+ setBookRaw((current) => {
+ const next = redoStackRef.current.pop()!;
+ undoStackRef.current = [...undoStackRef.current, current];
+ setCanUndo(true);
+ setCanRedo(redoStackRef.current.length > 0);
+ return normalizeCoverLayout(next);
+ });
+ }, []);
+ const photoUrls = useMemo(() => {
+ if (previewUrls.size === 0) return thumbnailUrls;
+ const merged = new Map(thumbnailUrls);
+ for (const [id, url] of previewUrls) {
+ merged.set(id, url);
+ }
+ return merged;
+ }, [thumbnailUrls, previewUrls]);
+
+ const loadingPreviewsRef = useRef<Set<string>>(new Set());
+
+ const loadPreviews = useCallback(async (photoIds: string[]) => {
+ const missing = photoIds.filter(
+ (id) =>
+ !previewUrlsRef.current.has(id) &&
+ !loadingPreviewsRef.current.has(id),
+ );
+ if (missing.length === 0) return;
+
+ missing.forEach((id) => loadingPreviewsRef.current.add(id));
+
+ const loaded = new Map<string, string>();
+ await Promise.all(
+ missing.map(async (id) => {
+ try {
+ const blob = await getPreview(id);
+ if (blob) {
+ loaded.set(id, URL.createObjectURL(blob));
+ }
+ } finally {
+ loadingPreviewsRef.current.delete(id);
+ }
+ }),
+ );
+
+ for (const [id, url] of loaded) {
+ if (!photosRef.current.some((photo) => photo.id === id)) {
+ URL.revokeObjectURL(url);
+ loaded.delete(id);
+ }
+ }
+ if (loaded.size > 0) {
+ setPreviewUrls((prev) => {
+ const next = new Map(prev);
+ for (const [id, url] of loaded) next.set(id, url);
+ return next;
+ });
+ }
+ }, []);
+
+ const [processingPhotos, setProcessingPhotos] = useState(false);
+ const [processingProgress, setProcessingProgress] = useState(0);
+ const [processingMessage, setProcessingMessage] = useState(
+ "Processing your photos...",
+ );
+ const [importNotice, setImportNotice] = useState<string | null>(null);
+ const clearImportNotice = useCallback(() => setImportNotice(null), []);
+ const pendingEnteOriginals = useMemo(() => {
+ const next = new Set<string>();
+ for (const photo of photos) {
+ if (isPendingEnteOriginal(photo)) {
+ next.add(photo.id);
+ }
+ }
+ return next;
+ }, [photos]);
+ const pendingEnteOriginalsRef = useRef<Set<string>>(pendingEnteOriginals);
+ pendingEnteOriginalsRef.current = pendingEnteOriginals;
+ const activeEnteOriginalDownloadsRef = useRef<Set<string>>(new Set());
+ const enteOriginalWaitersRef = useRef<Map<string, (() => void)[]>>(
+ new Map(),
+ );
+ useEffect(() => {
+ if (loading || processingPhotos || resettingRef.current) return;
+ const saveTimeout = setTimeout(() => {
+ saveTimeoutRef.current = null;
+ autosaveRef.current = autosaveRef.current
+ .then(() =>
+ Promise.all([
+ saveBookState({ ...book, currentSpreadIndex }),
+ savePhotos(photos),
+ saveAppView(appView),
+ ]),
+ )
+ .catch((error: unknown) =>
+ console.error("Failed to save photobook", error),
+ );
+ }, 500);
+ saveTimeoutRef.current = saveTimeout;
+
+ return () => clearTimeout(saveTimeout);
+ }, [book, photos, appView, currentSpreadIndex, loading, processingPhotos]);
+
+ useEffect(() => {
+ void (async () => {
+ try {
+ const [savedView, savedPhotos, savedBook] = await Promise.all([
+ getAppView(),
+ getPhotos(),
+ getBookState(),
+ ]);
+
+ if (savedBook?.pages.length === 0 && savedView === "edit") {
+ setBookRaw(emptyBook);
+ setAppViewState("edit");
+ } else if (savedPhotos && savedPhotos.length > 0 && savedBook) {
+ await document.fonts.ready;
+ const thumbUrls = new Map<string, string>();
+
+ await Promise.all(
+ savedPhotos.map(async (photo) => {
+ const thumb = await getThumbnail(photo.id);
+ if (thumb) {
+ thumbUrls.set(
+ photo.id,
+ URL.createObjectURL(thumb),
+ );
+ }
+ }),
+ );
+
+ setPhotos(savedPhotos);
+ setThumbnailUrls(thumbUrls);
+ setBookRaw(normalizeCoverLayout(savedBook));
+ setCurrentSpreadIndex(savedBook.currentSpreadIndex);
+
+ if (savedView === "edit" || savedView === "results") {
+ setAppViewState(savedView);
+ }
+ }
+ } catch (e) {
+ console.error("Failed to restore session:", e);
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, []);
+
+ const setAppView = useCallback((view: AppView) => {
+ setAppViewState(view);
+ }, []);
+
+ const progressRef = useRef(0);
+ const rafRef = useRef<number>(0);
+
+ const addPhotos = useCallback(
+ async (files: File[], options: AddPhotosOptions = {}) => {
+ const replace = options.replace ?? false;
+ const destination = options.destination ?? { kind: "end" as const };
+ if (!replace) {
+ const error = photoDestinationError(
+ book.pages,
+ destination,
+ files.length,
+ );
+ if (error) throw new Error(error);
+ }
+ setProcessingPhotos(true);
+ progressRef.current = 0;
+ setProcessingProgress(0);
+ setProcessingMessage("Processing your photos...");
+
+ try {
+ if (replace) {
+ thumbnailUrls.forEach((url) => URL.revokeObjectURL(url));
+ previewUrls.forEach((url) => URL.revokeObjectURL(url));
+ clearImageCache();
+ await clearAll();
+ }
+
+ const newPhotos: Photo[] = [];
+ const newThumbUrls = replace
+ ? new Map<string, string>()
+ : new Map(thumbnailUrls);
+ const newPreviewUrls = replace
+ ? new Map<string, string>()
+ : new Map(previewUrls);
+
+ const scheduleProgressUpdate = (value: number) => {
+ progressRef.current = value;
+ if (!rafRef.current) {
+ rafRef.current = requestAnimationFrame(() => {
+ rafRef.current = 0;
+ setProcessingProgress(progressRef.current);
+ });
+ }
+ };
+
+ interface PhotoResult {
+ photo: Photo;
+ thumbUrl: string;
+ previewUrl: string;
+ }
+ const results: (PhotoResult | null)[] = Array.from(
+ { length: files.length },
+ () => null,
+ );
+ let completed = 0;
+
+ const processPhoto = async (file: File, index: number) => {
+ try {
+ const blob = await normalizeImportedImageBlob(
+ file,
+ file.name,
+ );
+ const tempUrl = URL.createObjectURL(blob);
+ let img: HTMLImageElement;
+ try {
+ img = await loadImage(tempUrl);
+ } finally {
+ URL.revokeObjectURL(tempUrl);
+ }
+ const dateTaken = await extractExifDate(file);
+ const thumb = await createThumbnail(img, 256);
+ const preview = await createThumbnail(img, 1080);
+ const photo: Photo = {
+ id: crypto.randomUUID(),
+ fileName: file.name,
+ width: img.naturalWidth,
+ height: img.naturalHeight,
+ dateTaken:
+ dateTaken || file.lastModified || Date.now(),
+ source: "local",
+ originalStatus: "ready",
+ };
+ await savePhotoBlob(photo.id, blob);
+ await saveThumbnail(photo.id, thumb);
+ await savePreview(photo.id, preview);
+ results[index] = {
+ photo,
+ thumbUrl: URL.createObjectURL(thumb),
+ previewUrl: URL.createObjectURL(preview),
+ };
+ } catch (error) {
+ console.warn(
+ "Photo import failed for",
+ file.name,
+ error,
+ );
+ } finally {
+ completed++;
+ scheduleProgressUpdate(
+ Math.round((completed / files.length) * 100),
+ );
+ }
+ };
+
+ const CONCURRENCY = 6;
+ const taskQueue = files.map((f, i) => () => processPhoto(f, i));
+ const workers = Array.from(
+ { length: Math.min(CONCURRENCY, files.length) },
+ async () => {
+ while (taskQueue.length > 0) {
+ const task = taskQueue.shift()!;
+ await task();
+ }
+ },
+ );
+ await Promise.all(workers);
+
+ for (const result of results) {
+ if (result) {
+ newThumbUrls.set(result.photo.id, result.thumbUrl);
+ newPreviewUrls.set(result.photo.id, result.previewUrl);
+ newPhotos.push(result.photo);
+ }
+ }
+
+ if (rafRef.current) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = 0;
+ }
+ setProcessingProgress(100);
+
+ if (!replace && newPhotos.length === 0) {
+ throw new Error(
+ "These photos couldn't be read. Please choose different image files.",
+ );
+ }
+ const skipped = files.length - newPhotos.length;
+ if (skipped > 0)
+ setImportNotice(
+ `${skipped} photo${skipped === 1 ? "" : "s"} couldn't be imported.`,
+ );
+
+ const allPhotos = replace
+ ? newPhotos
+ : [...photos, ...newPhotos];
+ const nextPages = replace
+ ? generateAutoLayout(allPhotos)
+ : placeImportedPhotos(
+ book.pages,
+ allPhotos,
+ newPhotos,
+ destination,
+ );
+ const destinationIndex = replace
+ ? 0
+ : destination.kind === "page"
+ ? nextPages.findIndex(
+ (page) => page.id === destination.pageId,
+ )
+ : Math.max(0, book.pages.length - 1);
+ setPhotos(allPhotos);
+ setThumbnailUrls(newThumbUrls);
+ setPreviewUrls(newPreviewUrls);
+
+ if (replace) {
+ setBookRaw({ pages: nextPages, currentSpreadIndex: 0 });
+ undoStackRef.current = [];
+ redoStackRef.current = [];
+ setCanUndo(false);
+ setCanRedo(false);
+ setCurrentSpreadIndex(0);
+ } else if (newPhotos.length > 0) {
+ setBook((prev) => ({ ...prev, pages: nextPages }));
+ setCurrentSpreadIndex(destinationIndex);
+ }
+
+ setAppViewState("edit");
+ return nextPages[destinationIndex]?.id;
+ } finally {
+ if (rafRef.current) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = 0;
+ }
+ setProcessingPhotos(false);
+ }
+ },
+ [book.pages, thumbnailUrls, previewUrls, photos, setBook],
+ );
+
+ const markEnteOriginalDone = useCallback(
+ (
+ photoId: string,
+ status: PhotoOriginalStatus,
+ originalError?: string,
+ ) => {
+ setPhotos((prev) =>
+ prev.map((photo) => {
+ if (photo.id !== photoId || photo.source !== "ente") {
+ return photo;
+ }
+
+ const next: Photo = {
+ ...photo,
+ originalStatus: status,
+ originalError,
+ };
+ if (status === "ready" || status === "failed") {
+ next.enteOriginal = undefined;
+ }
+ return next;
+ }),
+ );
+ const waiters = enteOriginalWaitersRef.current.get(photoId);
+ if (waiters) {
+ enteOriginalWaitersRef.current.delete(photoId);
+ for (const w of waiters) w();
+ }
+ },
+ [],
+ );
+
+ const startEnteOriginalDownloads = useCallback(
+ async (photoIds: string[]) => {
+ const entries = photoIds
+ .map((photoId) => {
+ const photo = photosRef.current.find(
+ (candidate) => candidate.id === photoId,
+ );
+ if (!photo || !isPendingEnteOriginal(photo)) {
+ return null;
+ }
+ const job = buildEnteOriginalDownloadJob(photo);
+ if (!job) {
+ markEnteOriginalDone(
+ photoId,
+ "failed",
+ "Missing Ente download metadata.",
+ );
+ return null;
+ }
+ return { photoId, fileName: photo.fileName, ...job };
+ })
+ .filter(
+ (
+ entry,
+ ): entry is {
+ photoId: string;
+ fileName: string;
+ credentials: EnteCredentials;
+ descriptor: EnteFileDescriptor;
+ } => entry !== null,
+ );
+
+ const CONCURRENCY = 3;
+ let cursor = 0;
+ const workers = Array.from(
+ { length: Math.min(CONCURRENCY, entries.length) },
+ async () => {
+ while (cursor < entries.length) {
+ const i = cursor++;
+ const { photoId, fileName, credentials, descriptor } =
+ entries[i]!;
+ try {
+ if (
+ isResetting() ||
+ !photosRef.current.some(
+ (photo) => photo.id === photoId,
+ )
+ )
+ continue;
+ const {
+ fetchAndDecryptOriginal,
+ extractRenderableImage,
+ } = await import("@/lib/ente/import");
+ const blob = await fetchAndDecryptOriginal(
+ credentials,
+ descriptor,
+ );
+ const renderable = await extractRenderableImage(
+ descriptor,
+ blob,
+ );
+ const normalizedBlob =
+ await normalizeImportedImageBlob(
+ renderable.blob,
+ renderable.fileName,
+ );
+ const normalizedUrl =
+ URL.createObjectURL(normalizedBlob);
+ let previewBlob: Blob;
+ try {
+ const img = await loadImage(normalizedUrl);
+ previewBlob = await createThumbnail(img, 1080);
+ } finally {
+ URL.revokeObjectURL(normalizedUrl);
+ }
+ const currentPhoto = photosRef.current.find(
+ (candidate) => candidate.id === photoId,
+ );
+ if (
+ isResetting() ||
+ !currentPhoto ||
+ !isPendingEnteOriginal(currentPhoto)
+ ) {
+ continue;
+ }
+ const write = Promise.all([
+ savePhotoBlob(photoId, normalizedBlob),
+ savePreview(photoId, previewBlob),
+ ]);
+ originalWritesRef.current.add(write);
+ try {
+ await write;
+ } finally {
+ originalWritesRef.current.delete(write);
+ }
+ if (
+ isResetting() ||
+ !photosRef.current.some(
+ (photo) => photo.id === photoId,
+ )
+ )
+ continue;
+ const previewUrl = URL.createObjectURL(previewBlob);
+ setPreviewUrls((prev) => {
+ const next = new Map(prev);
+ const existing = next.get(photoId);
+ if (existing) {
+ URL.revokeObjectURL(existing);
+ }
+ next.set(photoId, previewUrl);
+ return next;
+ });
+ markEnteOriginalDone(photoId, "ready");
+ } catch (e) {
+ const currentPhoto = photosRef.current.find(
+ (candidate) => candidate.id === photoId,
+ );
+ if (
+ !resettingRef.current &&
+ currentPhoto &&
+ isPendingEnteOriginal(currentPhoto)
+ ) {
+ const message =
+ e instanceof Error
+ ? e.message
+ : "Failed to prepare the original photo.";
+ console.warn(
+ `Ente: failed to download original for "${fileName}"`,
+ e,
+ );
+ markEnteOriginalDone(
+ photoId,
+ "failed",
+ message,
+ );
+ }
+ } finally {
+ activeEnteOriginalDownloadsRef.current.delete(
+ photoId,
+ );
+ }
+ }
+ },
+ );
+ await Promise.all(workers);
+ },
+ [markEnteOriginalDone, isResetting],
+ );
+
+ const addEntePhotos = useCallback(
+ async (
+ albumUrl: string,
+ requestPassword: () => Promise<string | null>,
+ ) => {
+ setProcessingPhotos(true);
+ progressRef.current = 0;
+ setProcessingProgress(0);
+ setProcessingMessage("Importing your photos...");
+
+ let preparation;
+ let fetchAndDecryptThumbnail: (typeof import("@/lib/ente/import"))["fetchAndDecryptThumbnail"];
+ try {
+ const enteImport = await import("@/lib/ente/import");
+ fetchAndDecryptThumbnail = enteImport.fetchAndDecryptThumbnail;
+ preparation = await enteImport.prepareEnteAlbum(
+ albumUrl,
+ requestPassword,
+ );
+ if (preparation.files.length === 0)
+ throw new Error("This album has no photos we can import.");
+
+ thumbnailUrlsRef.current.forEach((url) =>
+ URL.revokeObjectURL(url),
+ );
+ previewUrlsRef.current.forEach((url) =>
+ URL.revokeObjectURL(url),
+ );
+ clearImageCache();
+ await clearAll();
+ activeEnteOriginalDownloadsRef.current.clear();
+ enteOriginalWaitersRef.current = new Map();
+ } catch (e) {
+ setProcessingPhotos(false);
+ setProcessingMessage("Processing your photos...");
+ throw e;
+ }
+
+ const { credentials, files } = preparation;
+ const MAX_PHOTOS = 800;
+ const limited = files.slice(0, MAX_PHOTOS);
+ if (files.length > MAX_PHOTOS) {
+ setImportNotice(
+ `This album has ${files.length} photos. We imported the first ${MAX_PHOTOS}.`,
+ );
+ }
+
+ interface ThumbResult {
+ photo: Photo;
+ thumbUrl: string;
+ previewUrl: string;
+ }
+ const thumbResults: (ThumbResult | null)[] = Array.from(
+ { length: limited.length },
+ () => null,
+ );
+ let completed = 0;
+
+ const scheduleProgressUpdate = (value: number) => {
+ progressRef.current = value;
+ if (!rafRef.current) {
+ rafRef.current = requestAnimationFrame(() => {
+ rafRef.current = 0;
+ setProcessingProgress(progressRef.current);
+ });
+ }
+ };
+
+ const processOne = async (index: number) => {
+ const descriptor = limited[index]!;
+ try {
+ const thumbBlob = await fetchAndDecryptThumbnail(
+ credentials,
+ descriptor,
+ );
+
+ let width = descriptor.width;
+ let height = descriptor.height;
+ if (!width || !height) {
+ const tempUrl = URL.createObjectURL(thumbBlob);
+ try {
+ const img = await loadImage(tempUrl);
+ width = img.naturalWidth;
+ height = img.naturalHeight;
+ } finally {
+ URL.revokeObjectURL(tempUrl);
+ }
+ }
+
+ const photoId = crypto.randomUUID();
+ const photo: Photo = {
+ id: photoId,
+ fileName: descriptor.fileName,
+ width,
+ height,
+ dateTaken: descriptor.dateTaken,
+ source: "ente",
+ originalStatus: "pending",
+ enteOriginal: {
+ downloadOrigin: credentials.downloadOrigin,
+ accessToken: credentials.accessToken,
+ accessTokenJWT: credentials.accessTokenJWT,
+ enteFileId: descriptor.enteFileId,
+ mediaKind: descriptor.mediaKind,
+ fileKey: descriptor.fileKey,
+ fileDecryptionHeader:
+ descriptor.fileDecryptionHeader,
+ },
+ };
+
+ await Promise.all([
+ saveThumbnail(photoId, thumbBlob),
+ savePreview(photoId, thumbBlob),
+ ]);
+
+ thumbResults[index] = {
+ photo,
+ thumbUrl: URL.createObjectURL(thumbBlob),
+ previewUrl: URL.createObjectURL(thumbBlob),
+ };
+ } catch (e) {
+ console.warn(
+ `Ente: failed to prepare "${descriptor.fileName}"`,
+ e,
+ );
+ } finally {
+ completed++;
+ scheduleProgressUpdate(
+ Math.round((completed / limited.length) * 100),
+ );
+ }
+ };
+
+ const THUMB_CONCURRENCY = 6;
+ let cursor = 0;
+ const workers = Array.from(
+ { length: Math.min(THUMB_CONCURRENCY, limited.length) },
+ async () => {
+ while (cursor < limited.length) {
+ const i = cursor++;
+ await processOne(i);
+ }
+ },
+ );
+ await Promise.all(workers);
+
+ if (rafRef.current) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = 0;
+ }
+ setProcessingProgress(100);
+
+ const successful = thumbResults.filter(
+ (r): r is ThumbResult => r !== null,
+ );
+ successful.sort((a, b) => a.photo.dateTaken - b.photo.dateTaken);
+
+ if (successful.length === 0) {
+ setProcessingPhotos(false);
+ setProcessingMessage("Processing your photos...");
+ throw new Error(
+ "We couldn't prepare any photos from this album.",
+ );
+ }
+
+ const newPhotos: Photo[] = successful.map((r) => r.photo);
+ const newThumbUrls = new Map<string, string>();
+ const newPreviewUrls = new Map<string, string>();
+ for (const r of successful) {
+ newThumbUrls.set(r.photo.id, r.thumbUrl);
+ newPreviewUrls.set(r.photo.id, r.previewUrl);
+ }
+
+ const pages = generateAutoLayout(newPhotos);
+ setPhotos(newPhotos);
+ setThumbnailUrls(newThumbUrls);
+ setPreviewUrls(newPreviewUrls);
+ setBookRaw({ pages, currentSpreadIndex: 0 });
+ undoStackRef.current = [];
+ redoStackRef.current = [];
+ setCanUndo(false);
+ setCanRedo(false);
+ setCurrentSpreadIndex(0);
+
+ setProcessingPhotos(false);
+ setProcessingMessage("Processing your photos...");
+ setAppViewState("edit");
+ },
+ [],
+ );
+
+ const waitForEnteOriginals = useCallback(
+ async (
+ photoIds?: string[],
+ onProgress?: (done: number, total: number) => void,
+ ) => {
+ const requested =
+ photoIds ?? Array.from(pendingEnteOriginalsRef.current);
+ const pending = requested.filter((id) =>
+ pendingEnteOriginalsRef.current.has(id),
+ );
+ if (pending.length === 0) return;
+ const total = pending.length;
+ let done = 0;
+ onProgress?.(done, total);
+ await Promise.all(
+ pending.map(
+ (id) =>
+ new Promise<void>((resolve) => {
+ if (!pendingEnteOriginalsRef.current.has(id)) {
+ done++;
+ onProgress?.(done, total);
+ resolve();
+ return;
+ }
+ const existing =
+ enteOriginalWaitersRef.current.get(id) ?? [];
+ existing.push(() => {
+ done++;
+ onProgress?.(done, total);
+ resolve();
+ });
+ enteOriginalWaitersRef.current.set(id, existing);
+ }),
+ ),
+ );
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (loading || processingPhotos) return;
+
+ const queue = photos
+ .filter(
+ (photo) =>
+ isPendingEnteOriginal(photo) &&
+ !activeEnteOriginalDownloadsRef.current.has(photo.id),
+ )
+ .map((photo) => photo.id);
+
+ if (queue.length === 0) return;
+
+ queue.forEach((photoId) =>
+ activeEnteOriginalDownloadsRef.current.add(photoId),
+ );
+ void startEnteOriginalDownloads(queue);
+ }, [loading, photos, processingPhotos, startEnteOriginalDownloads]);
+
+ const addPage = useCallback(
+ (afterIndex?: number) => {
+ const newPage = makeBlankPage();
+ setBook((prev) => {
+ const pages = [...prev.pages];
+ const lastIndex = pages.length - 1;
+ const requestedIndex =
+ afterIndex !== undefined ? afterIndex + 1 : lastIndex;
+ const idx =
+ pages.length > 1
+ ? Math.max(1, Math.min(requestedIndex, lastIndex))
+ : pages.length;
+ pages.splice(idx, 0, newPage);
+ return { ...prev, pages };
+ });
+ return newPage.id;
+ },
+ [setBook],
+ );
+
+ const removePage = useCallback(
+ (pageId: string) => {
+ setBook((prev) => {
+ if (
+ pageId === prev.pages[0]?.id ||
+ pageId === prev.pages.at(-1)?.id
+ )
+ return prev;
+ if (isRequiredBlankPage(prev.pages, pageId)) return prev;
+ const filtered = prev.pages.filter((p) => p.id !== pageId);
+ if (filtered.length < 2) return prev;
+ if (filtered.length % 2 !== 0) {
+ const blankIdx = filtered.findIndex(
+ (p, i) =>
+ i > 0 && i < filtered.length - 1 && isBlankPage(p),
+ );
+ if (blankIdx !== -1 && filtered.length - 1 >= 2) {
+ filtered.splice(blankIdx, 1);
+ } else {
+ filtered.splice(
+ filtered.length - 1,
+ 0,
+ makeBlankPage(),
+ );
+ }
+ }
+ return { ...prev, pages: filtered };
+ });
+ },
+ [setBook],
+ );
+
+ const reorderPages = useCallback(
+ (fromIndex: number, toIndex: number) => {
+ setBook((prev) => {
+ const lastIndex = prev.pages.length - 1;
+ if (
+ fromIndex <= 0 ||
+ fromIndex >= lastIndex ||
+ toIndex <= 0 ||
+ toIndex >= lastIndex
+ )
+ return prev;
+ const pages = [...prev.pages];
+ const [moved] = pages.splice(fromIndex, 1);
+ pages.splice(toIndex, 0, moved!);
+ return { ...prev, pages };
+ });
+ },
+ [setBook],
+ );
+
+ const updatePage = useCallback(
+ (pageId: string, updates: Partial<BookPage>) => {
+ setBook((prev) => ({
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId ? { ...p, ...updates } : p,
+ ),
+ }));
+ },
+ [setBook],
+ );
+
+ const updateSlot = useCallback(
+ (pageId: string, slotId: string, updates: Partial<PhotoSlot>) => {
+ setBook((prev) => ({
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? {
+ ...p,
+ slots: p.slots.map((s) =>
+ s.id === slotId ? { ...s, ...updates } : s,
+ ),
+ }
+ : p,
+ ),
+ }));
+ },
+ [setBook],
+ );
+
+ const removeSlot = useCallback(
+ (pageId: string, slotId: string) => {
+ setBook((prev) => {
+ const page = prev.pages.find((p) => p.id === pageId);
+ if (!page) return prev;
+
+ const remainingPhotos = page.slots
+ .filter((s) => s.id !== slotId && s.photoId)
+ .map((s) => s.photoId!);
+
+ if (remainingPhotos.length === 0) {
+ return {
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? { ...p, slots: [], layoutVariant: undefined }
+ : p,
+ ),
+ };
+ }
+
+ const isCoverPage = prev.pages[0]?.id === pageId;
+ let variantKey: string | undefined;
+ if (remainingPhotos.length === 1 && isCoverPage) {
+ variantKey = "1-full";
+ } else {
+ variantKey = getVariantsForCount(remainingPhotos.length)[0]
+ ?.key;
+ }
+ if (!variantKey) {
+ return {
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? {
+ ...p,
+ slots: p.slots.filter(
+ (s) => s.id !== slotId,
+ ),
+ }
+ : p,
+ ),
+ };
+ }
+
+ const newSlots = applyVariant(variantKey, remainingPhotos);
+
+ return {
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? {
+ ...p,
+ slots: newSlots,
+ layoutVariant: variantKey,
+ }
+ : p,
+ ),
+ };
+ });
+ },
+ [setBook],
+ );
+
+ const swapPhotos = useCallback(
+ (
+ fromPageId: string,
+ fromSlotId: string,
+ toPageId: string,
+ toSlotId: string,
+ ) => {
+ setBook((prev) => {
+ if (
+ toPageId === prev.pages.at(-1)?.id ||
+ fromPageId === prev.pages.at(-1)?.id
+ )
+ return prev;
+ const pages = prev.pages.map((p) => ({
+ ...p,
+ slots: p.slots.map((s) => {
+ if (p.id === fromPageId && s.id === fromSlotId) {
+ return { ...s };
+ }
+ if (p.id === toPageId && s.id === toSlotId) {
+ return { ...s };
+ }
+ return s;
+ }),
+ }));
+
+ let fromSlot: PhotoSlot | undefined;
+ let toSlot: PhotoSlot | undefined;
+
+ for (const page of pages) {
+ for (const slot of page.slots) {
+ if (page.id === fromPageId && slot.id === fromSlotId)
+ fromSlot = slot;
+ if (page.id === toPageId && slot.id === toSlotId)
+ toSlot = slot;
+ }
+ }
+
+ if (fromSlot && toSlot) {
+ const tempPhotoId = fromSlot.photoId;
+ fromSlot.photoId = toSlot.photoId;
+ toSlot.photoId = tempPhotoId;
+ }
+
+ return { ...prev, pages };
+ });
+ },
+ [setBook],
+ );
+
+ const movePhotoToPage = useCallback(
+ (fromPageId: string, fromSlotId: string, toPageId: string) => {
+ setBook((prev) => {
+ if (toPageId === prev.pages.at(-1)?.id) return prev;
+ const fromPage = prev.pages.find((p) => p.id === fromPageId);
+ const toPage = prev.pages.find((p) => p.id === toPageId);
+ if (!fromPage || !toPage || fromPageId === toPageId)
+ return prev;
+ if (
+ availablePhotoSpaces(
+ toPage,
+ prev.pages[0]?.id === toPageId,
+ ) === 0
+ )
+ return prev;
+
+ const fromSlot = fromPage.slots.find(
+ (s) => s.id === fromSlotId,
+ );
+ if (!fromSlot?.photoId) return prev;
+
+ const movedPhotoId = fromSlot.photoId;
+
+ const sourcePhotoIds = fromPage.slots
+ .map((s) => s.photoId)
+ .filter(
+ (id): id is string =>
+ id !== null && id !== movedPhotoId,
+ );
+ const targetPhotoIds = [
+ ...toPage.slots
+ .map((s) => s.photoId)
+ .filter((id): id is string => id !== null),
+ movedPhotoId,
+ ];
+
+ if (targetPhotoIds.length > 4) return prev;
+
+ const makePhotoStub = (photoId: string): Photo => {
+ const photo = photos.find((p) => p.id === photoId);
+ return (
+ photo || {
+ id: photoId,
+ fileName: "",
+ width: 1,
+ height: 1,
+ dateTaken: 0,
+ }
+ );
+ };
+
+ const newPages = prev.pages.map((p, pIdx) => {
+ const isCover = pIdx === 0;
+ const coverSingleKey = isCover ? "1-full" : null;
+ if (p.id === fromPageId) {
+ if (sourcePhotoIds.length === 0) {
+ return {
+ ...p,
+ slots: [],
+ layoutVariant: undefined,
+ };
+ }
+ if (coverSingleKey && sourcePhotoIds.length === 1) {
+ return {
+ ...p,
+ slots: applyVariant(
+ coverSingleKey,
+ sourcePhotoIds,
+ ),
+ layoutVariant: coverSingleKey,
+ };
+ }
+ const srcPhotos = sourcePhotoIds.map(makePhotoStub);
+ return {
+ ...p,
+ slots: chooseBestLayout(srcPhotos),
+ layoutVariant: chooseBestVariantKey(srcPhotos),
+ };
+ }
+ if (p.id === toPageId) {
+ if (coverSingleKey && targetPhotoIds.length === 1) {
+ return {
+ ...p,
+ slots: applyVariant(
+ coverSingleKey,
+ targetPhotoIds,
+ ),
+ layoutVariant: coverSingleKey,
+ };
+ }
+ const tgtPhotos = targetPhotoIds.map(makePhotoStub);
+ return {
+ ...p,
+ slots: chooseBestLayout(tgtPhotos),
+ layoutVariant: chooseBestVariantKey(tgtPhotos),
+ };
+ }
+ return p;
+ });
+
+ return { ...prev, pages: newPages };
+ });
+ },
+ [photos, setBook],
+ );
+
+ const setPageLayout = useCallback(
+ (pageId: string, variantKey: string) => {
+ setBook((prev) => {
+ if (pageId === prev.pages.at(-1)?.id) return prev;
+ const page = prev.pages.find((p) => p.id === pageId);
+ if (!page) return prev;
+ const photoIds = page.slots
+ .map((s) => s.photoId)
+ .filter((id): id is string => id !== null);
+ if (
+ pageId === prev.pages[0]?.id &&
+ getVariantPreview(variantKey).length !== 1
+ )
+ return prev;
+ const newSlots = applyVariant(variantKey, photoIds);
+ if (newSlots.length === 0) return prev;
+ return {
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? {
+ ...p,
+ slots: newSlots,
+ layoutVariant: variantKey,
+ }
+ : p,
+ ),
+ };
+ });
+ },
+ [setBook],
+ );
+
+ const addTextBlock = useCallback(
+ (pageId: string): TextBlock => {
+ const block: TextBlock = constrainTextBlock({
+ id: crypto.randomUUID(),
+ text: "",
+ x: 50,
+ y: 40,
+ width: 45,
+ height: 15,
+ style: "body",
+ alignment: "right",
+ color: "#555555",
+ rotation: 0,
+ fontSize: 2.5,
+ });
+ setBook((prev) => ({
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? { ...p, textBlocks: [...p.textBlocks, block] }
+ : p,
+ ),
+ }));
+ return block;
+ },
+ [setBook],
+ );
+
+ const updateTextBlock = useCallback(
+ (pageId: string, blockId: string, updates: Partial<TextBlock>) => {
+ setBook((prev) => ({
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? {
+ ...p,
+ textBlocks: p.textBlocks.map((t) =>
+ t.id === blockId
+ ? constrainTextBlock({ ...t, ...updates })
+ : t,
+ ),
+ }
+ : p,
+ ),
+ }));
+ },
+ [setBook],
+ );
+
+ const removeTextBlock = useCallback(
+ (pageId: string, blockId: string) => {
+ setBook((prev) => ({
+ ...prev,
+ pages: prev.pages.map((p) =>
+ p.id === pageId
+ ? {
+ ...p,
+ textBlocks: p.textBlocks.filter(
+ (t) => t.id !== blockId,
+ ),
+ }
+ : p,
+ ),
+ }));
+ },
+ [setBook],
+ );
+
+ const startOver = useCallback(async () => {
+ resettingRef.current = true;
+ if (saveTimeoutRef.current !== null)
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ try {
+ await Promise.allSettled([
+ autosaveRef.current,
+ ...originalWritesRef.current,
+ ]);
+ await clearAll();
+ thumbnailUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
+ previewUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
+ clearImageCache();
+
+ photosRef.current = [];
+ pendingEnteOriginalsRef.current = new Set();
+ setPhotos([]);
+ setThumbnailUrls(new Map());
+ setPreviewUrls(new Map());
+ setBookRaw(emptyBook);
+ undoStackRef.current = [];
+ redoStackRef.current = [];
+ setCanUndo(false);
+ setCanRedo(false);
+ setCurrentSpreadIndex(0);
+ setImportNotice(null);
+ setAppViewState("edit");
+ activeEnteOriginalDownloadsRef.current.clear();
+ enteOriginalWaitersRef.current.forEach((waiters) =>
+ waiters.forEach((resolve) => resolve()),
+ );
+ enteOriginalWaitersRef.current = new Map();
+ } catch (error) {
+ setPhotos((current) => [...current]);
+ throw error;
+ } finally {
+ resettingRef.current = false;
+ }
+ }, []);
+
+ return (
+ <BookContext.Provider
+ value={{
+ appView,
+ setAppView,
+ loading,
+ photos,
+ thumbnailUrls,
+ photoUrls,
+ loadPreviews,
+ addPhotos,
+ addEntePhotos,
+ processingPhotos,
+ processingProgress,
+ processingMessage,
+ importNotice,
+ clearImportNotice,
+ pendingEnteOriginals,
+ waitForEnteOriginals,
+ book,
+ setBook,
+ currentSpreadIndex,
+ setCurrentSpreadIndex,
+ addPage,
+ removePage,
+ reorderPages,
+ updatePage,
+ updateSlot,
+ removeSlot,
+ swapPhotos,
+ movePhotoToPage,
+ setPageLayout,
+ addTextBlock,
+ updateTextBlock,
+ removeTextBlock,
+ undo,
+ redo,
+ canUndo,
+ canRedo,
+ startOver,
+ }}
+ >
+ {children}
+ </BookContext.Provider>
+ );
+}
+
+function loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = reject;
+ img.src = src;
+ });
+}
diff --git a/web/apps/photobook/src/context/book.ts b/web/apps/photobook/src/context/book.ts
new file mode 100644
index 0000000000..3d4e269bad
--- /dev/null
+++ b/web/apps/photobook/src/context/book.ts
@@ -0,0 +1,94 @@
+import type { AddPhotosOptions } from "@/lib/photoPlacement";
+import type {
+ AppView,
+ BookPage,
+ BookState,
+ Photo,
+ PhotoSlot,
+ TextBlock,
+} from "@/lib/types";
+import {
+ createContext,
+ useContext,
+ type Dispatch,
+ type SetStateAction,
+} from "react";
+
+interface BookContextValue {
+ appView: AppView;
+ setAppView: (view: AppView) => void;
+ loading: boolean;
+
+ photos: Photo[];
+ thumbnailUrls: Map<string, string>;
+ photoUrls: Map<string, string>;
+ loadPreviews: (photoIds: string[]) => Promise<void>;
+ addPhotos: (
+ files: File[],
+ options?: AddPhotosOptions,
+ ) => Promise<string | undefined>;
+ addEntePhotos: (
+ albumUrl: string,
+ requestPassword: () => Promise<string | null>,
+ ) => Promise<void>;
+ processingPhotos: boolean;
+ processingProgress: number;
+ processingMessage: string;
+ importNotice: string | null;
+ clearImportNotice: () => void;
+ pendingEnteOriginals: Set<string>;
+ waitForEnteOriginals: (
+ photoIds?: string[],
+ onProgress?: (done: number, total: number) => void,
+ ) => Promise<void>;
+
+ book: BookState;
+ setBook: Dispatch<SetStateAction<BookState>>;
+ currentSpreadIndex: number;
+ setCurrentSpreadIndex: (idx: number) => void;
+
+ undo: () => void;
+ redo: () => void;
+ canUndo: boolean;
+ canRedo: boolean;
+
+ addPage: (afterIndex?: number) => string;
+ removePage: (pageId: string) => void;
+ reorderPages: (fromIndex: number, toIndex: number) => void;
+ updatePage: (pageId: string, updates: Partial<BookPage>) => void;
+ updateSlot: (
+ pageId: string,
+ slotId: string,
+ updates: Partial<PhotoSlot>,
+ ) => void;
+ removeSlot: (pageId: string, slotId: string) => void;
+ swapPhotos: (
+ fromPageId: string,
+ fromSlotId: string,
+ toPageId: string,
+ toSlotId: string,
+ ) => void;
+ movePhotoToPage: (
+ fromPageId: string,
+ fromSlotId: string,
+ toPageId: string,
+ ) => void;
+ setPageLayout: (pageId: string, variantKey: string) => void;
+ addTextBlock: (pageId: string) => TextBlock;
+ updateTextBlock: (
+ pageId: string,
+ blockId: string,
+ updates: Partial<TextBlock>,
+ ) => void;
+ removeTextBlock: (pageId: string, blockId: string) => void;
+
+ startOver: () => Promise<void>;
+}
+
+export const BookContext = createContext<BookContextValue | null>(null);
+
+export function useBook() {
+ const ctx = useContext(BookContext);
+ if (!ctx) throw new Error("useBook must be used within BookProvider");
+ return ctx;
+}
diff --git a/web/apps/photobook/src/globals.css b/web/apps/photobook/src/globals.css
new file mode 100644
index 0000000000..380520f264
--- /dev/null
+++ b/web/apps/photobook/src/globals.css
@@ -0,0 +1,53 @@
+:root {
+ --font-inter: "Inter Variable";
+ --font-outfit: "Outfit Variable";
+}
+
+* {
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+}
+
+html,
+body {
+ height: 100%;
+ overflow-x: hidden;
+ color-scheme: dark;
+}
+
+body {
+ background-color: #161616;
+ font-family: var(--font-inter), sans-serif;
+ color: #e9edef;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+button,
+input,
+select,
+textarea {
+ font-family: var(--font-inter), sans-serif;
+}
+
+::selection {
+ background-color: #08c225;
+ color: white;
+}
+::-webkit-scrollbar {
+ width: 6px;
+}
+
+::-webkit-scrollbar-track {
+ background: transparent;
+}
+
+::-webkit-scrollbar-thumb {
+ background: #4b555a;
+ border-radius: 3px;
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background: #657177;
+}
diff --git a/web/apps/photobook/src/hooks/useAutoScroll.ts b/web/apps/photobook/src/hooks/useAutoScroll.ts
new file mode 100644
index 0000000000..2ef8d60714
--- /dev/null
+++ b/web/apps/photobook/src/hooks/useAutoScroll.ts
@@ -0,0 +1,38 @@
+import { useCallback, useEffect, useRef } from "react";
+
+export function useAutoScroll(
+ containerRef: React.RefObject<HTMLElement | null>,
+) {
+ const frameRef = useRef<number | null>(null);
+ const speed = useRef(0);
+
+ const start = useCallback(() => {
+ if (frameRef.current !== null) return;
+ const tick = () => {
+ const el = containerRef.current;
+ if (el && speed.current !== 0) {
+ el.scrollTop += speed.current;
+ }
+ frameRef.current = requestAnimationFrame(tick);
+ };
+ frameRef.current = requestAnimationFrame(tick);
+ }, [containerRef]);
+
+ const stop = useCallback(() => {
+ if (frameRef.current !== null) {
+ cancelAnimationFrame(frameRef.current);
+ frameRef.current = null;
+ }
+ speed.current = 0;
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (frameRef.current !== null)
+ cancelAnimationFrame(frameRef.current);
+ },
+ [],
+ );
+
+ return { start, stop, speed };
+}
diff --git a/web/apps/photobook/src/hooks/usePageDrag.ts b/web/apps/photobook/src/hooks/usePageDrag.ts
new file mode 100644
index 0000000000..eeba6e5df3
--- /dev/null
+++ b/web/apps/photobook/src/hooks/usePageDrag.ts
@@ -0,0 +1,75 @@
+import { useBook } from "@/context/book";
+import { useCallback, useRef, useState } from "react";
+
+export function usePageDrag() {
+ const { book, reorderPages } = useBook();
+ const pageCount = book.pages.length;
+
+ const [pageDragSource, setPageDragSource] = useState<number | null>(null);
+ const [pageDragTarget, setPageDragTarget] = useState<number | null>(null);
+ const pageDragSourceRef = useRef<number | null>(null);
+
+ const handlePageDragStart = useCallback(
+ (e: React.DragEvent, pageIndex: number) => {
+ if (pageIndex === 0 || pageIndex === pageCount - 1) {
+ e.preventDefault();
+ return;
+ }
+ pageDragSourceRef.current = pageIndex;
+ setPageDragSource(pageIndex);
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData(
+ "application/x-page-drag",
+ String(pageIndex),
+ );
+ },
+ [pageCount],
+ );
+
+ const handlePageDragOverPage = useCallback(
+ (e: React.DragEvent, pageIndex: number) => {
+ if (pageDragSourceRef.current === null) return;
+ if (pageIndex === 0 || pageIndex === pageCount - 1) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ setPageDragTarget(pageIndex);
+ },
+ [pageCount],
+ );
+
+ const handlePageDropOnPage = useCallback(
+ (e: React.DragEvent, pageIndex: number) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const source = pageDragSourceRef.current;
+ if (
+ source !== null &&
+ source !== pageIndex &&
+ pageIndex > 0 &&
+ pageIndex < pageCount - 1
+ ) {
+ reorderPages(source, pageIndex);
+ }
+ pageDragSourceRef.current = null;
+ setPageDragSource(null);
+ setPageDragTarget(null);
+ },
+ [reorderPages, pageCount],
+ );
+
+ const handlePageDragEndCleanup = useCallback(() => {
+ pageDragSourceRef.current = null;
+ setPageDragSource(null);
+ setPageDragTarget(null);
+ }, []);
+
+ return {
+ pageDragSource,
+ pageDragTarget,
+ pageDragSourceRef,
+ handlePageDragStart,
+ handlePageDragOverPage,
+ handlePageDropOnPage,
+ handlePageDragEndCleanup,
+ };
+}
diff --git a/web/apps/photobook/src/hooks/usePhotoDrag.ts b/web/apps/photobook/src/hooks/usePhotoDrag.ts
new file mode 100644
index 0000000000..b4a06f4492
--- /dev/null
+++ b/web/apps/photobook/src/hooks/usePhotoDrag.ts
@@ -0,0 +1,240 @@
+import { useBook } from "@/context/book";
+import { availablePhotoSpaces } from "@/lib/photoPlacement";
+import { useCallback, useRef, useState } from "react";
+import type { useAutoScroll } from "./useAutoScroll";
+
+export interface DragInfo {
+ pageId: string;
+ slotId: string;
+}
+
+export function usePhotoDrag(
+ containerRef: React.RefObject<HTMLElement | null>,
+ autoScroll: ReturnType<typeof useAutoScroll>,
+) {
+ const { thumbnailUrls, swapPhotos, movePhotoToPage, book } = useBook();
+ const pages = book.pages;
+
+ const [dragSourceInfo, setDragSourceInfo] = useState<DragInfo | null>(null);
+ const dragSourceRef = useRef<DragInfo | null>(null);
+ const [dragOverInfo, setDragOverInfo] = useState<DragInfo | null>(null);
+ const dragOverRef = useRef<DragInfo | null>(null);
+ const [dragOverPageId, setDragOverPageId] = useState<string | null>(null);
+ const dragOverPageRef = useRef<string | null>(null);
+ const dragGhostRef = useRef<HTMLCanvasElement>(null);
+
+ const handleDragStart = useCallback(
+ (
+ e: React.DragEvent,
+ pageId: string,
+ slotId: string,
+ photoId: string,
+ ) => {
+ const source = { pageId, slotId };
+ dragSourceRef.current = source;
+ setDragSourceInfo(source);
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData(
+ "text/plain",
+ JSON.stringify({ pageId, slotId }),
+ );
+ const thumbUrl = thumbnailUrls.get(photoId);
+ if (thumbUrl && dragGhostRef.current) {
+ const canvas = dragGhostRef.current;
+ const ctx = canvas.getContext("2d");
+ const img = new window.Image();
+ img.src = thumbUrl;
+ const size = 200;
+ canvas.width = size;
+ canvas.height = size;
+ if (ctx) {
+ const aspect = img.naturalWidth / img.naturalHeight || 1;
+ const dw = aspect >= 1 ? size : size * aspect;
+ const dh = aspect >= 1 ? size / aspect : size;
+ ctx.clearRect(0, 0, size, size);
+ ctx.drawImage(
+ img,
+ (size - dw) / 2,
+ (size - dh) / 2,
+ dw,
+ dh,
+ );
+ }
+ e.dataTransfer.setDragImage(canvas, size / 2, size / 2);
+ }
+
+ const onGlobalEnd = () => {
+ autoScroll.stop();
+ dragSourceRef.current = null;
+ dragOverRef.current = null;
+ dragOverPageRef.current = null;
+ setDragSourceInfo(null);
+ setDragOverInfo(null);
+ setDragOverPageId(null);
+ window.removeEventListener("dragend", onGlobalEnd);
+ window.removeEventListener("drop", onGlobalEnd);
+ };
+ window.addEventListener("dragend", onGlobalEnd);
+ window.addEventListener("drop", onGlobalEnd);
+ },
+ [thumbnailUrls, autoScroll],
+ );
+
+ const handleSlotDragOver = useCallback(
+ (e: React.DragEvent, pageId: string, slotId: string) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ const cur = dragOverRef.current;
+ if (cur?.pageId !== pageId || cur.slotId !== slotId) {
+ const info = { pageId, slotId };
+ dragOverRef.current = info;
+ setDragOverInfo(info);
+ }
+ if (dragOverPageRef.current !== null) {
+ dragOverPageRef.current = null;
+ setDragOverPageId(null);
+ }
+ },
+ [],
+ );
+
+ const handleDrop = useCallback(
+ (e: React.DragEvent, toPageId: string, toSlotId: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ autoScroll.stop();
+ dragOverRef.current = null;
+ setDragOverInfo(null);
+ dragOverPageRef.current = null;
+ setDragOverPageId(null);
+ const source = dragSourceRef.current;
+ if (source) {
+ const { pageId: fromPageId, slotId: fromSlotId } = source;
+ if (fromPageId !== toPageId || fromSlotId !== toSlotId) {
+ swapPhotos(fromPageId, fromSlotId, toPageId, toSlotId);
+ }
+ dragSourceRef.current = null;
+ setDragSourceInfo(null);
+ }
+ },
+ [swapPhotos, autoScroll],
+ );
+
+ const handlePageDragOver = useCallback(
+ (e: React.DragEvent, pageId: string) => {
+ e.preventDefault();
+ const isBackCover = pages.at(-1)?.id === pageId;
+ const toPage = pages.find((p) => p.id === pageId);
+ const hasRoom =
+ !isBackCover &&
+ toPage &&
+ availablePhotoSpaces(toPage, pages[0]?.id === pageId) > 0;
+ e.dataTransfer.dropEffect = hasRoom ? "move" : "none";
+ const cur = dragOverRef.current;
+ if (cur !== null) {
+ dragOverRef.current = null;
+ setDragOverInfo(null);
+ }
+ const source = dragSourceRef.current;
+ if (source && source.pageId !== pageId && !isBackCover) {
+ if (hasRoom) {
+ if (dragOverPageRef.current !== pageId) {
+ dragOverPageRef.current = pageId;
+ setDragOverPageId(pageId);
+ }
+ } else if (dragOverPageRef.current !== null) {
+ dragOverPageRef.current = null;
+ setDragOverPageId(null);
+ }
+ } else if (dragOverPageRef.current !== null) {
+ dragOverPageRef.current = null;
+ setDragOverPageId(null);
+ }
+ },
+ [pages],
+ );
+
+ const handlePageDrop = useCallback(
+ (e: React.DragEvent, toPageId: string) => {
+ e.preventDefault();
+ autoScroll.stop();
+ dragOverRef.current = null;
+ setDragOverInfo(null);
+ dragOverPageRef.current = null;
+ setDragOverPageId(null);
+ const source = dragSourceRef.current;
+ if (source) {
+ const { pageId: fromPageId, slotId: fromSlotId } = source;
+ if (fromPageId !== toPageId && toPageId !== pages.at(-1)?.id) {
+ const toPage = pages.find((p) => p.id === toPageId);
+ if (
+ toPage &&
+ availablePhotoSpaces(
+ toPage,
+ pages[0]?.id === toPageId,
+ ) > 0
+ ) {
+ movePhotoToPage(fromPageId, fromSlotId, toPageId);
+ }
+ }
+ dragSourceRef.current = null;
+ setDragSourceInfo(null);
+ }
+ },
+ [pages, movePhotoToPage, autoScroll],
+ );
+
+ const handleDragEnd = useCallback(() => {
+ autoScroll.stop();
+ dragSourceRef.current = null;
+ dragOverRef.current = null;
+ dragOverPageRef.current = null;
+ setDragSourceInfo(null);
+ setDragOverInfo(null);
+ setDragOverPageId(null);
+ }, [autoScroll]);
+
+ const handleContainerDragOver = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+
+ const el = containerRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const edgeZone = 120;
+ const maxSpeed = 30;
+ const distFromTop = e.clientY - rect.top;
+ const distFromBottom = rect.bottom - e.clientY;
+
+ if (distFromTop < edgeZone) {
+ autoScroll.speed.current = -Math.round(
+ maxSpeed * (1 - distFromTop / edgeZone),
+ );
+ autoScroll.start();
+ } else if (distFromBottom < edgeZone) {
+ autoScroll.speed.current = Math.round(
+ maxSpeed * (1 - distFromBottom / edgeZone),
+ );
+ autoScroll.start();
+ } else {
+ autoScroll.speed.current = 0;
+ }
+ },
+ [containerRef, autoScroll],
+ );
+
+ return {
+ dragSourceInfo,
+ dragOverInfo,
+ dragOverPageId,
+ handleDragStart,
+ handleSlotDragOver,
+ handleDrop,
+ handlePageDragOver,
+ handlePageDrop,
+ handleDragEnd,
+ handleContainerDragOver,
+ dragGhostRef,
+ };
+}
diff --git a/web/apps/photobook/src/hooks/usePhotoImport.ts b/web/apps/photobook/src/hooks/usePhotoImport.ts
new file mode 100644
index 0000000000..68cc4a8a7a
--- /dev/null
+++ b/web/apps/photobook/src/hooks/usePhotoImport.ts
@@ -0,0 +1,260 @@
+import { useBook } from "@/context/book";
+import { useRouter } from "next/router";
+import {
+ createContext,
+ createElement,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+
+const ACCEPTED_TYPES = [
+ "image/jpeg",
+ "image/png",
+ "image/webp",
+ "image/heic",
+ "image/heif",
+];
+
+const MAX_PHOTOS = 800;
+
+type EnteDialogStage = "closed" | "url" | "password";
+
+function usePhotoImportSession() {
+ const router = useRouter();
+ const {
+ addPhotos,
+ addEntePhotos,
+ processingPhotos,
+ processingProgress,
+ processingMessage,
+ setAppView,
+ loading,
+ } = useBook();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [dragOver, setDragOver] = useState(false);
+ const [importError, setImportError] = useState<string | null>(null);
+ const [importActive, setImportActive] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const importingRef = useRef(false);
+ const retryFilesRef = useRef<File[]>([]);
+
+ const [enteStage, setEnteStage] = useState<EnteDialogStage>("closed");
+ const [enteUrl, setEnteUrl] = useState("");
+ const [entePassword, setEntePassword] = useState("");
+ const [enteError, setEnteError] = useState<string | null>(null);
+ const passwordResolverRef = useRef<((pw: string | null) => void) | null>(
+ null,
+ );
+
+ const beginImport = useCallback(() => {
+ if (loading || importingRef.current) return false;
+ importingRef.current = true;
+ setImportActive(true);
+ setImporting(true);
+ setImportError(null);
+ setEnteError(null);
+ setEnteStage("closed");
+ setAppView("edit");
+ void router.push("/app");
+ return true;
+ }, [loading, router, setAppView]);
+
+ const dismissImport = useCallback(() => {
+ if (importingRef.current) return;
+ setImportActive(false);
+ setImportError(null);
+ setEnteError(null);
+ retryFilesRef.current = [];
+ }, []);
+
+ const openEnteDialog = useCallback(() => {
+ setEnteStage("url");
+ setEnteError(null);
+ setEntePassword("");
+ }, []);
+
+ const closeEnteDialog = useCallback(() => {
+ const resolve = passwordResolverRef.current;
+ passwordResolverRef.current = null;
+ if (resolve) resolve(null);
+ setEnteStage("closed");
+ }, []);
+
+ const requestPassword = useCallback((): Promise<string | null> => {
+ return new Promise((resolve) => {
+ passwordResolverRef.current = resolve;
+ setEntePassword("");
+ setEnteError(null);
+ setEnteStage("password");
+ });
+ }, []);
+
+ const handleImportEnte = useCallback(async () => {
+ const url = enteUrl.trim();
+ if (!url) {
+ setEnteError("Paste the album link first.");
+ return;
+ }
+ if (!beginImport()) return;
+ retryFilesRef.current = [];
+
+ try {
+ await addEntePhotos(url, requestPassword);
+ setEnteUrl("");
+ setImportActive(false);
+ } catch (e) {
+ const cancelled =
+ (e as { cancelled?: boolean } | null)?.cancelled === true;
+ if (cancelled) {
+ setImportActive(false);
+ return;
+ }
+ const msg =
+ e instanceof Error ? e.message : "Something went wrong.";
+ setEnteStage("url");
+ setEnteError(msg);
+ } finally {
+ importingRef.current = false;
+ setImporting(false);
+ }
+ }, [enteUrl, addEntePhotos, requestPassword, beginImport]);
+
+ const handleSubmitPassword = useCallback(() => {
+ const resolve = passwordResolverRef.current;
+ passwordResolverRef.current = null;
+ setEnteStage("closed");
+ if (resolve) resolve(entePassword);
+ }, [entePassword]);
+
+ const handleCancelPassword = useCallback(() => {
+ const resolve = passwordResolverRef.current;
+ passwordResolverRef.current = null;
+ setEnteStage("closed");
+ if (resolve) resolve(null);
+ }, []);
+
+ const handleFiles = useCallback(
+ async (files: FileList | File[]) => {
+ const valid = Array.from(files)
+ .filter((f) => {
+ const ext = f.name.toLowerCase().split(".").pop();
+ return (
+ ACCEPTED_TYPES.includes(f.type) ||
+ ext === "heic" ||
+ ext === "heif" ||
+ ext === "jpg" ||
+ ext === "jpeg" ||
+ ext === "png" ||
+ ext === "webp"
+ );
+ })
+ .slice(0, MAX_PHOTOS);
+
+ if (valid.length > 0) {
+ if (!beginImport()) return;
+ retryFilesRef.current = valid;
+ try {
+ await addPhotos(valid, { replace: true });
+ retryFilesRef.current = [];
+ setImportActive(false);
+ } catch (error) {
+ setImportError(
+ error instanceof Error
+ ? error.message
+ : "Couldn't import these photos. Please try again.",
+ );
+ } finally {
+ importingRef.current = false;
+ setImporting(false);
+ }
+ }
+ },
+ [addPhotos, beginImport],
+ );
+
+ const retryImport = useCallback(() => {
+ if (retryFilesRef.current.length > 0)
+ return handleFiles(retryFilesRef.current);
+ return handleImportEnte();
+ }, [handleFiles, handleImportEnte]);
+
+ const handleDrop = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+ setDragOver(false);
+ void handleFiles(e.dataTransfer.files);
+ },
+ [handleFiles],
+ );
+
+ const handleDragOver = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ setDragOver(true);
+ }, []);
+
+ const handleDragLeave = useCallback(() => {
+ setDragOver(false);
+ }, []);
+
+ useEffect(
+ () => () => {
+ passwordResolverRef.current?.(null);
+ passwordResolverRef.current = null;
+ },
+ [],
+ );
+
+ return {
+ fileInputRef,
+ dragOver,
+ enteStage,
+ enteUrl,
+ setEnteUrl,
+ entePassword,
+ setEntePassword,
+ enteError,
+ importError,
+ processingPhotos,
+ processingProgress,
+ processingMessage,
+ openEnteDialog,
+ closeEnteDialog,
+ handleImportEnte,
+ handleSubmitPassword,
+ handleCancelPassword,
+ handleFiles,
+ handleDrop,
+ handleDragOver,
+ handleDragLeave,
+ importActive,
+ importing,
+ dismissImport,
+ retryImport,
+ };
+}
+
+const PhotoImportContext = createContext<ReturnType<
+ typeof usePhotoImportSession
+> | null>(null);
+
+export function PhotoImportProvider({ children }: { children: ReactNode }) {
+ const session = usePhotoImportSession();
+ return createElement(
+ PhotoImportContext.Provider,
+ { value: session },
+ children,
+ );
+}
+
+export function usePhotoImport() {
+ const session = useContext(PhotoImportContext);
+ if (!session)
+ throw new Error(
+ "usePhotoImport must be used within PhotoImportProvider",
+ );
+ return session;
+}
diff --git a/web/apps/photobook/src/hooks/useSpreads.ts b/web/apps/photobook/src/hooks/useSpreads.ts
new file mode 100644
index 0000000000..292f0c78bd
--- /dev/null
+++ b/web/apps/photobook/src/hooks/useSpreads.ts
@@ -0,0 +1,10 @@
+import { useBook } from "@/context/book";
+import { getPrintBinding } from "@/lib/printProducts";
+import { getSpreads, type Spread } from "@/lib/spreads";
+import { useMemo } from "react";
+
+export function useSpreads(pageCount: number): Spread[] {
+ const { book } = useBook();
+ const binding = getPrintBinding(book.printSelection);
+ return useMemo(() => getSpreads(pageCount, binding), [pageCount, binding]);
+}
diff --git a/web/apps/photobook/src/lib/bookFormats.ts b/web/apps/photobook/src/lib/bookFormats.ts
new file mode 100644
index 0000000000..5ed1b3548a
--- /dev/null
+++ b/web/apps/photobook/src/lib/bookFormats.ts
@@ -0,0 +1,10 @@
+export const BOOK_SIZE_MM = 210;
+const PRINT_SAFE_MARGIN_MM = 10;
+export const PRINT_SAFE_MARGIN_PCT =
+ (PRINT_SAFE_MARGIN_MM / BOOK_SIZE_MM) * 100;
+
+export const BOOK_LAYOUT = {
+ marginMm: { h: 25, v: 25 },
+ coverInsetMarginMm: { h: 29.4, v: 29.4 },
+ gapMm: { h: 0.9472, v: 0.945 },
+};
diff --git a/web/apps/photobook/src/lib/bookPages.test.ts b/web/apps/photobook/src/lib/bookPages.test.ts
new file mode 100644
index 0000000000..9a442ea3c0
--- /dev/null
+++ b/web/apps/photobook/src/lib/bookPages.test.ts
@@ -0,0 +1,166 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import {
+ isBlankPage,
+ isRequiredBlankPage,
+ makeBlankPage,
+ normalizeBookPages,
+} from "./bookPages";
+import { applyVariant } from "./layouts";
+
+test("a page with centered text is not disposable blank-page padding", () => {
+ const page = { ...makeBlankPage(), centerText: "Our holiday" };
+ assert.equal(isBlankPage(page), false);
+ assert.equal(isBlankPage({ ...page, centerText: "" }), true);
+});
+
+test("the only blank interior page is required to preserve the even print count", () => {
+ const pages = [
+ makeBlankPage(),
+ { ...makeBlankPage(), centerText: "Our holiday" },
+ makeBlankPage(),
+ makeBlankPage(),
+ ];
+ assert.equal(isRequiredBlankPage(pages, pages[2]!.id), true);
+ assert.equal(
+ isRequiredBlankPage(pages, pages[0]!.id),
+ false,
+ "front cover is not interior padding",
+ );
+ assert.equal(
+ isRequiredBlankPage(pages, pages[3]!.id),
+ false,
+ "back cover is not interior padding",
+ );
+ assert.equal(
+ isRequiredBlankPage(pages, pages[1]!.id),
+ false,
+ "pages with content can still be deleted",
+ );
+ assert.equal(
+ isRequiredBlankPage(
+ [pages[0]!, pages[2]!, pages[1]!, pages[3]!],
+ pages[2]!.id,
+ ),
+ true,
+ "moving the blank does not remove the requirement",
+ );
+});
+
+test("another blank interior page allows deletion without recreating padding", () => {
+ const pages = Array.from({ length: 4 }, makeBlankPage);
+ assert.equal(isRequiredBlankPage(pages, pages[1]!.id), false);
+ assert.equal(isRequiredBlankPage(pages, pages[2]!.id), false);
+});
+
+test("a required blank becomes removable when it gets content", () => {
+ const pages = [
+ makeBlankPage(),
+ { ...makeBlankPage(), centerText: "Our holiday" },
+ makeBlankPage(),
+ makeBlankPage(),
+ ];
+ for (const content of [
+ { centerText: "Last day" },
+ { slots: applyVariant("1-full", ["photo"]) },
+ { bottomCaption: "Goodbye" },
+ ]) {
+ const populated = pages.map((page, index) =>
+ index === 2 ? { ...page, ...content } : page,
+ );
+ assert.equal(isRequiredBlankPage(populated, pages[2]!.id), false);
+ }
+});
+
+test("odd or empty books have no blank that must be kept for parity", () => {
+ const pages = [makeBlankPage(), makeBlankPage(), makeBlankPage()];
+ assert.equal(isRequiredBlankPage(pages, pages[1]!.id), false);
+ assert.equal(isRequiredBlankPage([], "missing"), false);
+});
+
+test("migrates back-cover photos into the interior without changing crops or text", () => {
+ const front = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-full", ["front-photo"]),
+ layoutVariant: "1-full",
+ };
+ const back = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-moderate", ["back-photo"]),
+ layoutVariant: "1-moderate",
+ topCaption: "Last day",
+ textBlocks: [
+ {
+ id: "text",
+ text: "Goodbye",
+ x: 20,
+ y: 30,
+ width: 40,
+ height: 10,
+ style: "body" as const,
+ alignment: "left" as const,
+ color: "#333",
+ rotation: 0,
+ fontSize: 2.5,
+ },
+ ],
+ };
+ back.slots[0] = {
+ ...back.slots[0]!,
+ cropX: 0.2,
+ cropY: 0.8,
+ cropZoom: 1.5,
+ };
+ const pages = [front, makeBlankPage(), makeBlankPage(), back];
+ const original = structuredClone(pages);
+
+ const normalized = normalizeBookPages(pages);
+
+ assert.equal(normalized.length, 6);
+ assert.deepEqual(normalized.slice(0, 4), original);
+ assert.deepEqual(normalized.at(-1)?.slots, []);
+ assert.deepEqual(normalized.at(-2)?.slots, []);
+ assert.deepEqual(pages, original, "does not mutate saved state");
+ assert.strictEqual(
+ normalizeBookPages(normalized),
+ normalized,
+ "does not move or duplicate pages on subsequent saves",
+ );
+});
+
+test("preserves intentional blank pages and adds even-count padding before the existing back cover", () => {
+ const pages = Array.from({ length: 5 }, makeBlankPage);
+ pages[1]!.topCaption = "Content";
+ pages[4]!.topCaption = "Back-cover text";
+ const normalized = normalizeBookPages(pages);
+
+ assert.equal(normalized.length, 6);
+ assert.deepEqual(normalized.slice(0, 4), pages.slice(0, 4));
+ assert.strictEqual(normalized.at(-1), pages.at(-1));
+ assert.equal(normalized[4]!.topCaption, "");
+ assert.strictEqual(normalizeBookPages(normalized), normalized);
+});
+
+test("leaves even books and empty books unchanged", () => {
+ const empty: ReturnType<typeof makeBlankPage>[] = [];
+ const pages = Array.from({ length: 24 }, makeBlankPage);
+ assert.strictEqual(normalizeBookPages(empty), empty);
+ assert.strictEqual(normalizeBookPages(pages), pages);
+});
+
+test("adds a back cover to a single-page book and removes empty back-cover frames", () => {
+ const front = makeBlankPage();
+ const normalized = normalizeBookPages([front]);
+ assert.equal(normalized.length, 2);
+ assert.strictEqual(normalized[0]!, front);
+
+ const back = {
+ ...makeBlankPage(),
+ slots: [{ ...applyVariant("1-full", ["unused"])[0]!, photoId: null }],
+ layoutVariant: "1-full",
+ };
+ const cleaned = normalizeBookPages([front, back]);
+ assert.equal(cleaned.at(-1)?.id, back.id);
+ assert.deepEqual(cleaned.at(-1)?.slots, []);
+ assert.equal(cleaned.at(-1)?.layoutVariant, undefined);
+});
diff --git a/web/apps/photobook/src/lib/bookPages.ts b/web/apps/photobook/src/lib/bookPages.ts
new file mode 100644
index 0000000000..629fe68c44
--- /dev/null
+++ b/web/apps/photobook/src/lib/bookPages.ts
@@ -0,0 +1,52 @@
+import type { BookPage } from "./types";
+
+export const makeBlankPage = (): BookPage => ({
+ id: crypto.randomUUID(),
+ slots: [],
+ textBlocks: [],
+ topCaption: "",
+ bottomCaption: "",
+});
+
+export function isBlankPage(page: BookPage): boolean {
+ return (
+ page.slots.length === 0 &&
+ page.textBlocks.length === 0 &&
+ !page.topCaption &&
+ !page.bottomCaption &&
+ !page.centerText
+ );
+}
+
+export function isRequiredBlankPage(
+ pages: BookPage[],
+ pageId: string,
+): boolean {
+ if (pages.length % 2 !== 0) return false;
+ const blankPages = pages.slice(1, -1).filter(isBlankPage);
+ return blankPages.length === 1 && blankPages[0]!.id === pageId;
+}
+
+export function normalizeBookPages(pages: BookPage[]): BookPage[] {
+ if (pages.length === 0) return pages;
+ let result = pages;
+ const back = pages[pages.length - 1]!;
+
+ if (pages.length === 1 || back.slots.some((slot) => slot.photoId)) {
+ result = [...pages, makeBlankPage()];
+ } else if (back.slots.length > 0 || back.layoutVariant) {
+ result = [
+ ...pages.slice(0, -1),
+ { ...back, slots: [], layoutVariant: undefined },
+ ];
+ }
+
+ if (result.length % 2 !== 0) {
+ result = [
+ ...result.slice(0, -1),
+ makeBlankPage(),
+ result[result.length - 1]!,
+ ];
+ }
+ return result;
+}
diff --git a/web/apps/photobook/src/lib/db.ts b/web/apps/photobook/src/lib/db.ts
new file mode 100644
index 0000000000..4bd556ccdf
--- /dev/null
+++ b/web/apps/photobook/src/lib/db.ts
@@ -0,0 +1,114 @@
+import log from "ente-base/log";
+import { openDB, type DBSchema } from "idb";
+import type { AppView, BookState, Photo } from "./types";
+
+interface Metadata {
+ bookState: BookState;
+ photos: Photo[];
+ appView: AppView;
+}
+
+interface PhotobookDBSchema extends DBSchema {
+ photo_blobs: { key: string; value: Blob };
+ thumbnails: { key: string; value: Blob };
+ previews: { key: string; value: Blob };
+ metadata: { key: keyof Metadata; value: Metadata[keyof Metadata] };
+}
+
+let _photobookDB: ReturnType<typeof openPhotobookDB> | undefined;
+
+const openPhotobookDB = async () => {
+ const db = await openDB<PhotobookDBSchema>("photobook", 1, {
+ upgrade(db) {
+ db.createObjectStore("photo_blobs");
+ db.createObjectStore("thumbnails");
+ db.createObjectStore("previews");
+ db.createObjectStore("metadata");
+ },
+ blocking() {
+ db.close();
+ _photobookDB = undefined;
+ },
+ blocked() {
+ log.warn("Waiting for another tab to close the Photobook database");
+ },
+ terminated() {
+ log.warn("The Photobook database connection was terminated");
+ _photobookDB = undefined;
+ },
+ });
+ return db;
+};
+
+const photobookDB = () => (_photobookDB ??= openPhotobookDB());
+
+const getMetadata = async <K extends keyof Metadata>(key: K) => {
+ const db = await photobookDB();
+ return ((await db.get("metadata", key)) as Metadata[K] | undefined) ?? null;
+};
+
+const saveMetadata = async <K extends keyof Metadata>(
+ key: K,
+ value: Metadata[K],
+) => {
+ const db = await photobookDB();
+ await db.put("metadata", value, key);
+};
+
+export async function savePhotoBlob(id: string, blob: Blob): Promise<void> {
+ const db = await photobookDB();
+ await db.put("photo_blobs", blob, id);
+}
+
+export async function getPhotoBlob(id: string): Promise<Blob | null> {
+ const db = await photobookDB();
+ return (await db.get("photo_blobs", id)) ?? null;
+}
+
+export async function saveThumbnail(id: string, blob: Blob): Promise<void> {
+ const db = await photobookDB();
+ await db.put("thumbnails", blob, id);
+}
+
+export async function getThumbnail(id: string): Promise<Blob | null> {
+ const db = await photobookDB();
+ return (await db.get("thumbnails", id)) ?? null;
+}
+
+export async function savePreview(id: string, blob: Blob): Promise<void> {
+ const db = await photobookDB();
+ await db.put("previews", blob, id);
+}
+
+export async function getPreview(id: string): Promise<Blob | null> {
+ const db = await photobookDB();
+ return (await db.get("previews", id)) ?? null;
+}
+
+export const saveBookState = (state: BookState) =>
+ saveMetadata("bookState", state);
+
+export const getBookState = () => getMetadata("bookState");
+
+export const savePhotos = (photos: Photo[]) => saveMetadata("photos", photos);
+
+export const getPhotos = () => getMetadata("photos");
+
+export const saveAppView = (view: AppView) => saveMetadata("appView", view);
+
+export const getAppView = () => getMetadata("appView");
+
+export async function clearAll(): Promise<void> {
+ const db = await photobookDB();
+ const tx = db.transaction(
+ ["photo_blobs", "thumbnails", "previews", "metadata"],
+ "readwrite",
+ );
+ await Promise.all([
+ tx.objectStore("photo_blobs").clear(),
+ tx.objectStore("thumbnails").clear(),
+ tx.objectStore("previews").clear(),
+ tx.objectStore("metadata").clear(),
+ tx.done,
+ ]);
+}
diff --git a/web/apps/photobook/src/lib/ente/import.ts b/web/apps/photobook/src/lib/ente/import.ts
new file mode 100644
index 0000000000..a5019fe150
--- /dev/null
+++ b/web/apps/photobook/src/lib/ente/import.ts
@@ -0,0 +1,184 @@
+import { decryptBlobBytes, decryptStreamBytes } from "ente-base/crypto";
+import { isHTTP401Error } from "ente-base/http";
+import { getKVS, setKV } from "ente-base/kv";
+import log from "ente-base/log";
+import { apiOrigin, customAPIOrigin } from "ente-base/origins";
+import { decryptRemoteFile, type RemoteEnteFile } from "ente-media/file";
+import { fileCreationTime, fileFileName } from "ente-media/file-metadata";
+import { FileType } from "ente-media/file-type";
+import { decodeLivePhoto } from "ente-media/live-photo";
+import {
+ downloadPublicCollectionFile,
+ getPublicCollectionDiff,
+ getPublicCollectionInfo,
+ verifyPublicCollectionPassword,
+} from "ente-media/public-albums";
+import type { EnteCredentials, EnteFileDescriptor } from "./types";
+import { parseEnteAlbumUrl } from "./url";
+
+export async function prepareEnteAlbum(
+ albumUrl: string,
+ requestPassword: () => Promise<string | null>,
+) {
+ const { collectionKey, ...parsedCredentials } = parseEnteAlbumUrl(albumUrl);
+ const deviceTokenKey = `public-collection-link-device-token:${await apiOrigin()}:${parsedCredentials.accessToken}`;
+ const credentials: EnteCredentials = {
+ ...parsedCredentials,
+ linkDeviceToken: await getKVS(deviceTokenKey),
+ downloadOrigin:
+ (await customAPIOrigin()) ?? "https://public-albums.ente.com",
+ };
+ const info = await getPublicCollectionInfo(credentials);
+ if (info.linkDeviceToken) {
+ credentials.linkDeviceToken = info.linkDeviceToken;
+ await setKV(deviceTokenKey, info.linkDeviceToken);
+ }
+ const publicURL = info.collection.publicURLs[0];
+ if (!publicURL) throw new Error("Public album share has no active URL.");
+ if (!publicURL.enableDownload)
+ throw new Error(
+ "This album cannot be imported because downloads are disabled for this public link.",
+ );
+ if (publicURL.passwordEnabled) {
+ const password = await requestPassword();
+ if (password === null)
+ throw Object.assign(new Error("Album import cancelled."), {
+ cancelled: true,
+ });
+ try {
+ credentials.accessTokenJWT = await verifyPublicCollectionPassword(
+ credentials,
+ publicURL,
+ password,
+ );
+ } catch (error) {
+ if (isHTTP401Error(error))
+ throw new Error("That password is incorrect.", {
+ cause: error,
+ });
+ throw error;
+ }
+ }
+ const remote = new Map<number, RemoteEnteFile>();
+ let sinceTime = 0;
+ while (true) {
+ const { diff, hasMore } = await getPublicCollectionDiff(
+ credentials,
+ sinceTime,
+ );
+ for (const file of diff) {
+ sinceTime = Math.max(sinceTime, file.updationTime);
+ if (file.isDeleted) remote.delete(file.id);
+ else remote.set(file.id, file);
+ }
+ if (!hasMore || !diff.length) break;
+ }
+ const files: EnteFileDescriptor[] = [];
+ const pending = remote.values();
+ await Promise.all(
+ Array.from({ length: Math.min(6, remote.size) }, async () => {
+ for (const file of pending) {
+ try {
+ const decrypted = await decryptRemoteFile(
+ file,
+ collectionKey,
+ );
+ const kind = decrypted.metadata.fileType;
+ if (kind !== FileType.image && kind !== FileType.livePhoto)
+ continue;
+ files.push({
+ enteFileId: decrypted.id,
+ fileKey: decrypted.key,
+ mediaKind:
+ kind === FileType.image ? "image" : "live-photo",
+ thumbnailDecryptionHeader:
+ decrypted.thumbnail.decryptionHeader,
+ fileDecryptionHeader: decrypted.file.decryptionHeader,
+ fileName: fileFileName(decrypted),
+ dateTaken: Math.round(
+ fileCreationTime(decrypted) / 1000,
+ ),
+ width: decrypted.pubMagicMetadata?.data.w ?? 0,
+ height: decrypted.pubMagicMetadata?.data.h ?? 0,
+ fileSize: decrypted.info?.fileSize,
+ });
+ } catch (error) {
+ log.warn(`Failed to decrypt album photo ${file.id}`, error);
+ }
+ }
+ }),
+ );
+ files.sort((a, b) => a.dateTaken - b.dateTaken);
+ return { credentials, files };
+}
+
+export async function fetchAndDecryptThumbnail(
+ credentials: EnteCredentials,
+ file: EnteFileDescriptor,
+): Promise<Blob> {
+ const encryptedData = await downloadPublicCollectionFile(
+ credentials,
+ file.enteFileId,
+ true,
+ credentials.downloadOrigin,
+ );
+ const bytes = await decryptBlobBytes(
+ { encryptedData, decryptionHeader: file.thumbnailDecryptionHeader },
+ file.fileKey,
+ );
+ return new Blob([bytes], { type: "image/jpeg" });
+}
+
+export async function fetchAndDecryptOriginal(
+ credentials: EnteCredentials,
+ file: EnteFileDescriptor,
+): Promise<Blob> {
+ const encryptedData = await downloadPublicCollectionFile(
+ credentials,
+ file.enteFileId,
+ false,
+ credentials.downloadOrigin,
+ );
+ const bytes = await decryptStreamBytes(
+ { encryptedData, decryptionHeader: file.fileDecryptionHeader },
+ file.fileKey,
+ );
+ return new Blob([bytes], { type: guessMimeFromName(file.fileName) });
+}
+
+export async function extractRenderableImage(
+ file: EnteFileDescriptor,
+ originalBlob: Blob,
+): Promise<{ blob: Blob; fileName: string }> {
+ if (file.mediaKind === "image")
+ return { blob: originalBlob, fileName: file.fileName };
+ const { imageData, imageFileName } = await decodeLivePhoto(
+ file.fileName,
+ originalBlob,
+ );
+ return {
+ blob: new Blob([imageData], { type: guessMimeFromName(imageFileName) }),
+ fileName: imageFileName,
+ };
+}
+
+function guessMimeFromName(name: string): string {
+ const ext = name.toLowerCase().split(".").pop() ?? "";
+ switch (ext) {
+ case "jpg":
+ case "jpeg":
+ return "image/jpeg";
+ case "png":
+ return "image/png";
+ case "webp":
+ return "image/webp";
+ case "heic":
+ return "image/heic";
+ case "heif":
+ return "image/heif";
+ case "gif":
+ return "image/gif";
+ default:
+ return "image/jpeg";
+ }
+}
diff --git a/web/apps/photobook/src/lib/ente/types.ts b/web/apps/photobook/src/lib/ente/types.ts
new file mode 100644
index 0000000000..c987d3d1b4
--- /dev/null
+++ b/web/apps/photobook/src/lib/ente/types.ts
@@ -0,0 +1,18 @@
+import type { PublicAlbumsCredentials } from "ente-base/http";
+
+export interface EnteCredentials extends PublicAlbumsCredentials {
+ downloadOrigin: string;
+}
+
+export interface EnteFileDescriptor {
+ enteFileId: number;
+ fileKey: string;
+ mediaKind: "image" | "live-photo";
+ thumbnailDecryptionHeader: string;
+ fileDecryptionHeader: string;
+ fileName: string;
+ dateTaken: number;
+ width: number;
+ height: number;
+ fileSize?: number;
+}
diff --git a/web/apps/photobook/src/lib/ente/url.test.ts b/web/apps/photobook/src/lib/ente/url.test.ts
new file mode 100644
index 0000000000..6b63df9ac9
--- /dev/null
+++ b/web/apps/photobook/src/lib/ente/url.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "vitest";
+import { parseEnteAlbumUrl } from "./url";
+
+const base58 = "11111111111111111111111111111111";
+const hex = "00".repeat(32);
+
+describe("public album links", () => {
+ test.each(["albums.ente.com", "albums.ente.io", "albums.example.org"])(
+ "reads a link on %s without changing the configured API",
+ (host) => {
+ expect(
+ parseEnteAlbumUrl(`https://${host}/?t=token#${base58}`),
+ ).toEqual({
+ accessToken: "token",
+ collectionKey: btoa("\0".repeat(32)),
+ });
+ },
+ );
+ test("accepts legacy hexadecimal keys", () => {
+ expect(
+ parseEnteAlbumUrl(`https://albums.ente.com/?t=token#${hex}`),
+ ).toEqual(
+ parseEnteAlbumUrl(`https://albums.ente.com/?t=token#${base58}`),
+ );
+ });
+ test.each([
+ "bad URL",
+ "https://albums.ente.com/#key",
+ "https://albums.ente.com/?t=token",
+ `javascript:alert(1)?t=token#${base58}`,
+ "https://albums.ente.com/?t=token#111",
+ `https://albums.ente.com/?t=token#${"0g".repeat(32)}`,
+ ])("rejects an invalid link: %s", (url) => {
+ expect(() => parseEnteAlbumUrl(url)).toThrow();
+ });
+});
diff --git a/web/apps/photobook/src/lib/ente/url.ts b/web/apps/photobook/src/lib/ente/url.ts
new file mode 100644
index 0000000000..87c65f2375
--- /dev/null
+++ b/web/apps/photobook/src/lib/ente/url.ts
@@ -0,0 +1,38 @@
+import bs58 from "bs58";
+
+export function parseEnteAlbumUrl(input: string) {
+ let url: URL;
+ try {
+ url = new URL(input.trim());
+ } catch {
+ throw new Error("That doesn't look like a valid URL.");
+ }
+ if (url.protocol !== "https:" && url.protocol !== "http:")
+ throw new Error("Album links must use HTTP or HTTPS.");
+ const accessToken = url.searchParams.get("t");
+ if (!accessToken)
+ throw new Error("Album link is missing the access token (?t=…).");
+ const hash = url.hash.slice(1);
+ if (!hash)
+ throw new Error(
+ "Album link is missing the decryption key (the #… at the end).",
+ );
+ let bytes: Uint8Array;
+ try {
+ if (hash.length < 50) bytes = bs58.decode(hash);
+ else {
+ if (!/^[0-9a-f]{64}$/i.test(hash))
+ throw new Error("Expected a 64-character hexadecimal key.");
+ bytes = Uint8Array.from(hash.match(/../g)!, (pair) =>
+ parseInt(pair, 16),
+ );
+ }
+ } catch (cause) {
+ throw new Error("Album decryption key is malformed.", { cause });
+ }
+ if (bytes.length !== 32)
+ throw new Error(
+ `Album decryption key has wrong length: expected 32 bytes, got ${bytes.length}.`,
+ );
+ return { accessToken, collectionKey: btoa(String.fromCharCode(...bytes)) };
+}
diff --git a/web/apps/photobook/src/lib/export.test.ts b/web/apps/photobook/src/lib/export.test.ts
new file mode 100644
index 0000000000..1bd7c920fd
--- /dev/null
+++ b/web/apps/photobook/src/lib/export.test.ts
@@ -0,0 +1,611 @@
+import JSZip from "jszip";
+import assert from "node:assert/strict";
+import { afterAll, beforeAll, test, vi } from "vitest";
+import { makeBlankPage } from "./bookPages";
+import {
+ exportPdfX4Pages,
+ exportPngPagesZip,
+ renderPageToCanvas,
+} from "./export";
+import { applyVariant } from "./layouts";
+import * as pdfx from "./pdfx";
+import {
+ DEFAULT_PRINT_SELECTION,
+ getBindingPrintSelection,
+ PrintExportValidationError,
+ type PrintSelection,
+} from "./printProducts";
+
+const sizeMm = 210;
+
+interface TextDraw {
+ text: string;
+ x: number;
+ y: number;
+ fontSize: number;
+ align: string;
+}
+interface CanvasRecord {
+ width: number;
+ height: number;
+ marks: string[];
+ textDraws: TextDraw[];
+ imageDraws: { x: number; y: number; width: number; height: number }[];
+}
+const documentDescriptor = Object.getOwnPropertyDescriptor(
+ globalThis,
+ "document",
+);
+const imageDescriptor = Object.getOwnPropertyDescriptor(globalThis, "Image");
+const fileReaderDescriptor = Object.getOwnPropertyDescriptor(
+ globalThis,
+ "FileReader",
+);
+let canvasCount = 0;
+
+beforeAll(() => {
+ Object.defineProperty(globalThis, "document", {
+ configurable: true,
+ value: {
+ fonts: { ready: Promise.resolve() },
+ createElement(tag: string) {
+ assert.equal(tag, "canvas");
+ canvasCount++;
+ const canvas: CanvasRecord = {
+ width: 0,
+ height: 0,
+ marks: [],
+ textDraws: [],
+ imageDraws: [],
+ };
+ return Object.assign(canvas, {
+ getContext: () => ({
+ font: "10px sans-serif",
+ textAlign: "left",
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ rect: vi.fn(),
+ clip: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ fillRect: vi.fn(),
+ measureText(text: string) {
+ return {
+ width:
+ text.length *
+ Number(/([\d.]+)px/.exec(this.font)![1]!) *
+ 0.6,
+ };
+ },
+ fillText(text: string, x: number, y: number) {
+ canvas.marks.push(text);
+ canvas.textDraws.push({
+ text,
+ x,
+ y,
+ fontSize: Number(
+ /([\d.]+)px/.exec(this.font)![1]!,
+ ),
+ align: this.textAlign,
+ });
+ },
+ drawImage(
+ _image: unknown,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ ) {
+ canvas.marks.push("ente-logo");
+ canvas.imageDraws.push({ x, y, width, height });
+ },
+ }),
+ toBlob(callback: BlobCallback) {
+ callback(
+ new Blob([JSON.stringify(canvas)], {
+ type: "image/png",
+ }),
+ );
+ },
+ });
+ },
+ },
+ });
+ Object.defineProperty(globalThis, "Image", {
+ configurable: true,
+ value: class {
+ naturalWidth = 844;
+ naturalHeight = 264;
+ onload: (() => void) | null = null;
+ set src(_value: string) {
+ queueMicrotask(() => this.onload?.());
+ }
+ },
+ });
+ Object.defineProperty(globalThis, "FileReader", {
+ configurable: true,
+ value: class {
+ onload:
+ ((event: { target: { result: ArrayBuffer } }) => void) | null =
+ null;
+ onerror: ((event: { target: { error: unknown } }) => void) | null =
+ null;
+ readAsArrayBuffer(blob: Blob) {
+ blob.arrayBuffer().then(
+ (result) => this.onload?.({ target: { result } }),
+ (error: unknown) => this.onerror?.({ target: { error } }),
+ );
+ }
+ },
+ });
+ vi.spyOn(pdfx, "createPdfWriter").mockImplementation((size) => {
+ const pages: CanvasRecord[] = [];
+ return Promise.resolve({
+ addPage: (canvas) => {
+ pages.push(canvas as unknown as CanvasRecord);
+ return Promise.resolve();
+ },
+ finish: () =>
+ Promise.resolve(
+ new Blob([JSON.stringify({ pages, size })], {
+ type: "application/pdf",
+ }),
+ ),
+ dispose: vi.fn(),
+ });
+ });
+});
+
+afterAll(() => {
+ vi.restoreAllMocks();
+ for (const [key, descriptor] of [
+ ["document", documentDescriptor],
+ ["Image", imageDescriptor],
+ ["FileReader", fileReaderDescriptor],
+ ] as const) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+});
+
+function bookWithBlankPage(count: number) {
+ const pages = Array.from({ length: count }, (_, i) => ({
+ ...makeBlankPage(),
+ centerText: i === 10 || i === count - 1 ? "" : `Page ${i + 1}`,
+ }));
+ return pages;
+}
+
+test("hardcover and softcover export the same content without printer-added blanks", async () => {
+ const pages = bookWithBlankPage(24);
+ const original = structuredClone(pages);
+ const hardcover = await exportPdfX4Pages(
+ pages,
+ getBindingPrintSelection("Hardcover"),
+ );
+ const softcover = await exportPdfX4Pages(
+ pages,
+ getBindingPrintSelection("Softcover"),
+ );
+ assert.deepEqual(
+ JSON.parse(await hardcover.text()),
+ JSON.parse(await softcover.text()),
+ );
+ assert.equal(
+ (JSON.parse(await hardcover.text()) as { pages: CanvasRecord[] }).pages
+ .length,
+ 24,
+ );
+ assert.deepEqual(pages, original);
+});
+
+test("a missing photo cannot silently produce an incomplete print page", async () => {
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-full", ["missing-photo"]),
+ };
+ await assert.rejects(
+ renderPageToCanvas(page, () => Promise.resolve(null), 2480, 2480),
+ /photo is missing/,
+ );
+});
+
+test(`${sizeMm} mm PDF export preserves all 24 pages including a blank interior page`, async () => {
+ const pages = bookWithBlankPage(24);
+ const original = structuredClone(pages);
+ const blob = await exportPdfX4Pages(pages, DEFAULT_PRINT_SELECTION);
+ const result = JSON.parse(await blob.text()) as {
+ pages: CanvasRecord[];
+ size: pdfx.PdfXPageSize;
+ };
+
+ assert.equal(result.pages.length, 24);
+ assert.deepEqual(
+ result.pages.map((page) => page.marks),
+ pages.map((page, i) =>
+ i === 23 ? ["ente-logo"] : page.centerText ? [page.centerText] : [],
+ ),
+ );
+ assert.deepEqual(result.size, {
+ widthMm: 210,
+ heightMm: 210,
+ widthPx: 2480,
+ heightPx: 2480,
+ });
+ assert.deepEqual(pages, original);
+});
+
+test("PDF export adds an even-count blank immediately before the back cover", async () => {
+ const pages = bookWithBlankPage(23);
+ const blob = await exportPdfX4Pages(pages, DEFAULT_PRINT_SELECTION);
+ const result = JSON.parse(await blob.text()) as { pages: CanvasRecord[] };
+
+ assert.equal(result.pages.length, 24);
+ assert.deepEqual(result.pages[10]!.marks, [], "retains the existing blank");
+ assert.deepEqual(result.pages[21]!.marks, ["Page 22"]);
+ assert.deepEqual(
+ result.pages[22]!.marks,
+ [],
+ "adds the extra blank before the back cover",
+ );
+ assert.deepEqual(result.pages[23]!.marks, ["ente-logo"]);
+ assert.equal(pages.length, 23, "does not mutate the input book");
+});
+
+for (const count of [23, 24]) {
+ test(`PNG export preserves blanks and cover order for a ${count}-page input`, async () => {
+ const blob = await exportPngPagesZip(
+ bookWithBlankPage(count),
+ DEFAULT_PRINT_SELECTION,
+ );
+ const zip = await JSZip.loadAsync(await blob.arrayBuffer());
+ const names = Object.keys(zip.files);
+
+ assert.equal(names.length, 24);
+ assert.deepEqual(
+ names,
+ Array.from(
+ { length: 24 },
+ (_, i) => `page_${String(i + 1).padStart(3, "0")}.png`,
+ ),
+ );
+ const blank = JSON.parse(
+ await zip.file("page_011.png")!.async("string"),
+ ) as CanvasRecord;
+ const back = JSON.parse(
+ await zip.file("page_024.png")!.async("string"),
+ ) as CanvasRecord;
+ assert.deepEqual(blank.marks, []);
+ assert.deepEqual(back.marks, ["ente-logo"]);
+ assert.equal(back.width, 2480);
+ assert.equal(back.height, 2480);
+ });
+}
+
+for (const [format, runExport] of [
+ ["PDF", exportPdfX4Pages],
+ ["PNG", exportPngPagesZip],
+] as const) {
+ test(`${format} rejects invalid product counts before rendering or reporting progress`, async () => {
+ for (const count of [0, 2, 20, 301]) {
+ const before = canvasCount;
+ let progressCalls = 0;
+ await assert.rejects(
+ runExport(
+ bookWithBlankPage(count),
+ DEFAULT_PRINT_SELECTION,
+ () => {
+ progressCalls++;
+ },
+ ),
+ PrintExportValidationError,
+ );
+ assert.equal(canvasCount, before);
+ assert.equal(progressCalls, 0);
+ }
+ });
+
+ test(`${format} cannot bypass validation with an unknown product or unsupported size`, async () => {
+ for (const selection of [
+ { productId: "unknown", sizeMm: 210 },
+ { productId: "hardcover-gloss-200", sizeMm: 211 },
+ { productId: "softcover-gloss-150", sizeMm: 211 },
+ ] as PrintSelection[]) {
+ const before = canvasCount;
+ await assert.rejects(
+ runExport(bookWithBlankPage(24), selection),
+ PrintExportValidationError,
+ );
+ assert.equal(canvasCount, before);
+ }
+ });
+}
+
+test("softcover requires 24 pages and rejects the former 20-page minimum", async () => {
+ const selection: PrintSelection = {
+ productId: "softcover-gloss-150",
+ sizeMm: 210,
+ };
+ for (const runExport of [exportPdfX4Pages, exportPngPagesZip]) {
+ await assert.rejects(
+ runExport(bookWithBlankPage(20), selection),
+ PrintExportValidationError,
+ );
+ }
+ const pages = bookWithBlankPage(24);
+ const pdf = JSON.parse(
+ await (await exportPdfX4Pages(pages, selection)).text(),
+ ) as { pages: CanvasRecord[] };
+ const png = await exportPngPagesZip(pages, selection);
+ const zip = await JSZip.loadAsync(await png.arrayBuffer());
+ assert.equal(pdf.pages.length, 24);
+ assert.equal(Object.keys(zip.files).length, 24);
+});
+
+test("150 gsm hardcover accepts a 500-page PDF while other hardcover paper rejects it", async () => {
+ const pages = bookWithBlankPage(500);
+ const selection: PrintSelection = {
+ productId: "hardcover-gloss-150",
+ sizeMm: 210,
+ };
+ const result = JSON.parse(
+ await (await exportPdfX4Pages(pages, selection)).text(),
+ ) as { pages: CanvasRecord[] };
+ assert.equal(result.pages.length, 500);
+ await assert.rejects(
+ exportPdfX4Pages(pages, DEFAULT_PRINT_SELECTION),
+ PrintExportValidationError,
+ );
+});
+
+test("PNG dimensions match 210 mm pages at 300 DPI", async () => {
+ const blob = await exportPngPagesZip(
+ bookWithBlankPage(24),
+ DEFAULT_PRINT_SELECTION,
+ );
+ const zip = await JSZip.loadAsync(await blob.arrayBuffer());
+ const page = JSON.parse(
+ await zip.file("page_001.png")!.async("string"),
+ ) as CanvasRecord;
+ assert.equal(page.width, 2480);
+ assert.equal(page.height, page.width);
+});
+
+test(`${sizeMm} mm rendering centres captions between the photo and paper edge`, async () => {
+ for (const variant of ["2-side", "1-moderate", "1-padded"]) {
+ const isFrontCover = variant.startsWith("1-");
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant(
+ variant,
+ isFrontCover ? ["photo"] : ["photo-1", "photo-2"],
+ ),
+ topCaption: "Summer",
+ bottomCaption: "2026",
+ };
+ const sizePx = Math.round((sizeMm / 25.4) * 300);
+ const result = (await renderPageToCanvas(
+ page,
+ (id) => Promise.resolve(`test:${id}`),
+ sizePx,
+ sizePx,
+ false,
+ isFrontCover,
+ )) as unknown as CanvasRecord;
+ assert.equal(result.imageDraws.length, page.slots.length);
+ assert.equal(result.textDraws.length, 2);
+ const photoTop = Math.min(...result.imageDraws.map((draw) => draw.y));
+ const photoBottom = Math.max(
+ ...result.imageDraws.map((draw) => draw.y + draw.height),
+ );
+ const [topCaption, bottomCaption] = result.textDraws;
+ assert.ok(topCaption && bottomCaption);
+ const topPhotoGap = photoTop - topCaption.y - topCaption.fontSize * 0.7;
+ const topEdgeGap = topCaption.y - topCaption.fontSize * 0.7;
+ const bottomPhotoGap =
+ bottomCaption.y - bottomCaption.fontSize * 0.7 - photoBottom;
+ const bottomEdgeGap =
+ sizePx - bottomCaption.y - bottomCaption.fontSize * 0.7;
+ assert.ok(
+ Math.abs(topPhotoGap - topEdgeGap) < 1e-6,
+ "top caption has equal whitespace above and below",
+ );
+ assert.ok(
+ Math.abs(bottomPhotoGap - bottomEdgeGap) < 1e-6,
+ "bottom caption has equal whitespace above and below",
+ );
+ assert.ok(
+ ((topCaption.y - topCaption.fontSize * 0.7) / sizePx) * sizeMm >=
+ 10 - 1e-6,
+ );
+ assert.ok(
+ ((sizePx - bottomCaption.y - bottomCaption.fontSize * 0.7) /
+ sizePx) *
+ sizeMm >=
+ 10 - 1e-6,
+ );
+ const empty = (await renderPageToCanvas(
+ { ...page, topCaption: "", bottomCaption: "" },
+ (id) => Promise.resolve(`test:${id}`),
+ sizePx,
+ sizePx,
+ false,
+ isFrontCover,
+ )) as unknown as CanvasRecord;
+ assert.deepEqual(
+ empty.textDraws,
+ [],
+ "editor placeholders are never exported",
+ );
+ assert.deepEqual(
+ empty.imageDraws,
+ result.imageDraws,
+ "adding a caption does not shift the photos",
+ );
+ }
+});
+
+test(`${sizeMm} mm rendering keeps caption and custom-text bounds at least 10 mm from the trim`, async () => {
+ const text = "A long caption. ".repeat(30);
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-moderate", ["photo"]),
+ topCaption: "Ordinary caption",
+ bottomCaption: text,
+ textBlocks: [
+ {
+ id: "text",
+ text: "Saved text outside the page",
+ x: 110,
+ y: 110,
+ width: 45,
+ height: 15,
+ fontSize: 6,
+ rotation: 0,
+ color: "#555555",
+ style: "body" as const,
+ alignment: "left" as const,
+ },
+ ],
+ };
+ const original = structuredClone(page);
+ const sizePx = Math.round((sizeMm / 25.4) * 300);
+ const result = (await renderPageToCanvas(
+ page,
+ (id) => Promise.resolve(`test:${id}`),
+ sizePx,
+ sizePx,
+ )) as unknown as CanvasRecord;
+ const safe = (10 / sizeMm) * sizePx;
+ assert.equal(result.textDraws.length, 3);
+ for (const draw of result.textDraws) {
+ const width = draw.text.length * draw.fontSize * 0.6;
+ const left = draw.align === "center" ? draw.x - width / 2 : draw.x;
+ assert.ok(left >= safe - 1e-6);
+ assert.ok(left + width <= sizePx - safe + 1e-6);
+ assert.ok(draw.y - draw.fontSize * 0.7 >= safe - 1e-6);
+ assert.ok(draw.y + draw.fontSize * 0.7 <= sizePx - safe + 1e-6);
+ }
+ assert.deepEqual(
+ page,
+ original,
+ "export corrects legacy positions without mutating the book",
+ );
+});
+
+test(`${sizeMm} mm rendering switches centered page text to photo captions`, async () => {
+ const page = {
+ ...makeBlankPage(),
+ centerText: "Summer\n2026",
+ topCaption: "Top",
+ bottomCaption: "Bottom",
+ };
+ const original = structuredClone(page);
+ const sizePx = Math.round((sizeMm / 25.4) * 300);
+ const empty = (await renderPageToCanvas(
+ makeBlankPage(),
+ () => Promise.resolve(null),
+ sizePx,
+ sizePx,
+ )) as unknown as CanvasRecord;
+ assert.deepEqual(
+ empty.textDraws,
+ [],
+ "never exports Add text... on an empty page",
+ );
+ const result = (await renderPageToCanvas(
+ page,
+ () => Promise.resolve(null),
+ sizePx,
+ sizePx,
+ )) as unknown as CanvasRecord;
+ assert.deepEqual(
+ result.textDraws.map((draw) => draw.text),
+ ["Summer", "2026"],
+ );
+ assert.ok(
+ result.textDraws.every(
+ (draw) => draw.align === "center" && draw.x === sizePx / 2,
+ ),
+ );
+ assert.ok(
+ Math.abs(
+ (result.textDraws[0]!.y + result.textDraws[1]!.y) / 2 - sizePx / 2,
+ ) < 1e-6,
+ );
+ const withPhoto = (await renderPageToCanvas(
+ { ...page, slots: applyVariant("1-moderate", ["photo"]) },
+ (id) => Promise.resolve(`test:${id}`),
+ sizePx,
+ sizePx,
+ )) as unknown as CanvasRecord;
+ assert.deepEqual(
+ withPhoto.textDraws.map((draw) => draw.text),
+ ["Top", "Bottom"],
+ );
+ assert.deepEqual(page, original, "hiding text retains the saved value");
+});
+
+test(`${sizeMm} mm rendering places the entire back logo inside the safe area`, async () => {
+ const sizePx = Math.round((sizeMm / 25.4) * 300);
+ const result = (await renderPageToCanvas(
+ makeBlankPage(),
+ () => Promise.resolve(null),
+ sizePx,
+ sizePx,
+ true,
+ )) as unknown as CanvasRecord;
+ assert.equal(result.imageDraws.length, 1);
+ const logo = result.imageDraws[0]!;
+ const bottomGapMm = ((sizePx - logo.y - logo.height) / sizePx) * sizeMm;
+ assert.ok(bottomGapMm >= 10 - 1e-6);
+ assert.ok(Math.abs(bottomGapMm - 10) < 1e-6);
+});
+
+test(`${sizeMm} mm exports wrap page text at the same size as the cover title`, async () => {
+ const centerText =
+ "John didn't practise or sit around in his room thinking about drumming, he just did it and was magnificent.";
+ const page = { ...makeBlankPage(), centerText };
+ const sizePx = Math.round((sizeMm / 25.4) * 300);
+ const result = (await renderPageToCanvas(
+ page,
+ () => Promise.resolve(null),
+ sizePx,
+ sizePx,
+ )) as unknown as CanvasRecord;
+ const cover = (await renderPageToCanvas(
+ {
+ ...makeBlankPage(),
+ slots: applyVariant("1-padded", ["photo"]),
+ topCaption: "Summer",
+ },
+ (id) => Promise.resolve(`test:${id}`),
+ sizePx,
+ sizePx,
+ false,
+ true,
+ )) as unknown as CanvasRecord;
+ assert.ok(
+ result.textDraws.length > 1,
+ "a paragraph wraps without manual line breaks",
+ );
+ assert.equal(
+ result.textDraws.map((draw) => draw.text).join(" "),
+ centerText,
+ );
+ for (const draw of result.textDraws) {
+ assert.equal(draw.align, "center");
+ assert.equal(draw.x, sizePx / 2);
+ assert.equal(
+ draw.fontSize,
+ cover.textDraws[0]!.fontSize,
+ "page text matches the rendered cover title size",
+ );
+ assert.ok(draw.text.length * draw.fontSize * 0.6 <= sizePx * 0.64);
+ }
+ const first = result.textDraws[0]!;
+ const last = result.textDraws.at(-1)!;
+ assert.ok(Math.abs((first.y + last.y) / 2 - sizePx / 2) < 1e-6);
+ assert.equal(page.centerText, centerText);
+});
diff --git a/web/apps/photobook/src/lib/export.ts b/web/apps/photobook/src/lib/export.ts
new file mode 100644
index 0000000000..e606b16b03
--- /dev/null
+++ b/web/apps/photobook/src/lib/export.ts
@@ -0,0 +1,321 @@
+import JSZip from "jszip";
+import { BOOK_SIZE_MM } from "./bookFormats";
+import { getPhotoBlob } from "./db";
+import { createPdfWriter } from "./pdfx";
+import {
+ CAPTION_FONT_WEIGHT,
+ CENTER_TEXT_FONT_WEIGHT,
+ getBrandingLayout,
+ getCaptionLayout,
+ getCenterTextLayout,
+ getInterFont,
+ getOutfitFont,
+ getTextBlockLayout,
+ SAFE_AREA,
+ TEXT_LINE_HEIGHT,
+} from "./printLayout";
+import { preparePrintExport, type PrintSelection } from "./printProducts";
+import type { BookPage } from "./types";
+
+const DPI = 300;
+const MM_PER_INCH = 25.4;
+
+interface RenderSize {
+ widthMm: number;
+ heightMm: number;
+ widthPx: number;
+ heightPx: number;
+}
+
+function mmToPx(mm: number): number {
+ return Math.round((mm / MM_PER_INCH) * DPI);
+}
+
+function getPageRenderSize(): RenderSize {
+ const sizePx = mmToPx(BOOK_SIZE_MM);
+ return {
+ widthMm: BOOK_SIZE_MM,
+ heightMm: BOOK_SIZE_MM,
+ widthPx: sizePx,
+ heightPx: sizePx,
+ };
+}
+
+async function loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => resolve(img);
+ img.onerror = reject;
+ img.src = src;
+ });
+}
+
+function createPhotoUrlResolver() {
+ const cache = new Map<string, string>();
+
+ return {
+ resolve: async (photoId: string): Promise<string | null> => {
+ if (cache.has(photoId)) return cache.get(photoId)!;
+ const blob = await getPhotoBlob(photoId);
+ if (!blob) return null;
+ const url = URL.createObjectURL(blob);
+ cache.set(photoId, url);
+ return url;
+ },
+ revokeAll() {
+ cache.forEach((url) => URL.revokeObjectURL(url));
+ cache.clear();
+ },
+ };
+}
+
+export async function renderPageToCanvas(
+ page: BookPage,
+ resolvePhotoUrl: (photoId: string) => Promise<string | null>,
+ width: number,
+ height: number,
+ isBackCover = false,
+ isFrontCover = false,
+): Promise<HTMLCanvasElement> {
+ await document.fonts.ready;
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d")!;
+
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(0, 0, width, height);
+
+ for (const slot of page.slots) {
+ if (!slot.photoId) continue;
+ const url = await resolvePhotoUrl(slot.photoId);
+ if (!url)
+ throw new Error(
+ "A photo is missing. Re-import your photos before downloading.",
+ );
+
+ try {
+ const img = await loadImage(url);
+
+ const sx = (slot.x / 100) * width;
+ const sy = (slot.y / 100) * height;
+ const sw = (slot.width / 100) * width;
+ const sh = (slot.height / 100) * height;
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(sx, sy, sw, sh);
+ ctx.clip();
+
+ const imgAspect = img.naturalWidth / img.naturalHeight;
+ const slotAspect = sw / sh;
+
+ let drawW: number, drawH: number;
+ if (imgAspect > slotAspect) {
+ drawH = sh * slot.cropZoom;
+ drawW = drawH * imgAspect;
+ } else {
+ drawW = sw * slot.cropZoom;
+ drawH = drawW / imgAspect;
+ }
+
+ const drawX = sx + (sw - drawW) * slot.cropX;
+ const drawY = sy + (sh - drawH) * slot.cropY;
+
+ ctx.drawImage(img, drawX, drawY, drawW, drawH);
+ ctx.restore();
+ } catch {
+ throw new Error(
+ "A photo could not be rendered. Re-import your photos before downloading.",
+ );
+ }
+ }
+
+ const centerText = getCenterTextLayout(page);
+ for (const position of ["center", "top", "bottom"] as const) {
+ if (position === "bottom" && isBackCover) continue;
+ const text =
+ position === "center"
+ ? page.centerText
+ : position === "top"
+ ? page.topCaption
+ : page.bottomCaption;
+ const layout =
+ position === "center"
+ ? centerText
+ : getCaptionLayout(page, position, isFrontCover);
+ if (!text || !layout) continue;
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(
+ (layout.x / 100) * width,
+ (layout.y / 100) * height,
+ (layout.width / 100) * width,
+ (layout.height / 100) * height,
+ );
+ ctx.clip();
+ ctx.fillStyle = "#2a2a2a";
+ const isTitle = position === "center" || isFrontCover;
+ const fontFamily = isTitle ? getOutfitFont() : getInterFont();
+ const fontWeight = isTitle
+ ? CENTER_TEXT_FONT_WEIGHT
+ : CAPTION_FONT_WEIGHT;
+ ctx.font = `${fontWeight} ${(layout.fontSize / 100) * height}px ${fontFamily}, sans-serif`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ const lines = position === "center" ? centerText!.lines : [text];
+ const lineHeight =
+ layout.fontSize *
+ (position === "center" ? centerText!.lineHeight : TEXT_LINE_HEIGHT);
+ const startY =
+ layout.y + (layout.height - lines.length * lineHeight) / 2;
+ lines.forEach((line, index) => {
+ ctx.fillText(
+ line,
+ width / 2,
+ ((startY + (index + 0.5) * lineHeight) / 100) * height,
+ );
+ });
+ ctx.restore();
+ }
+
+ if (isBackCover) {
+ try {
+ const logo = await loadImage("/ente-branding.svg");
+ const layout = getBrandingLayout(
+ logo.naturalWidth / logo.naturalHeight,
+ );
+
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(
+ logo,
+ (layout.x / 100) * width,
+ (layout.y / 100) * height,
+ (layout.width / 100) * width,
+ (layout.height / 100) * height,
+ );
+ } catch {
+ throw new Error(
+ "The back-cover logo could not be loaded. Please try downloading again.",
+ );
+ }
+ }
+
+ for (const block of page.textBlocks) {
+ if (!block.text) continue;
+ const layout = getTextBlockLayout(block);
+ const bx = (layout.x / 100) * width;
+ const by = (layout.y / 100) * height;
+ const fontSize = height * (layout.fontSize / 100);
+ const color = block.color ?? "#555555";
+ const rotation = layout.rotation;
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(
+ (SAFE_AREA.x / 100) * width,
+ (SAFE_AREA.y / 100) * height,
+ (SAFE_AREA.width / 100) * width,
+ (SAFE_AREA.height / 100) * height,
+ );
+ ctx.clip();
+ if (rotation) {
+ ctx.translate(bx, by);
+ ctx.rotate((rotation * Math.PI) / 180);
+ ctx.translate(-bx, -by);
+ }
+
+ ctx.fillStyle = color;
+ ctx.font = `bold ${fontSize}px ${getInterFont()}, sans-serif`;
+ ctx.textAlign = "left";
+ ctx.textBaseline = "middle";
+
+ const lines = layout.lines;
+ const lineHeight = fontSize * TEXT_LINE_HEIGHT;
+ for (let li = 0; li < lines.length; li++) {
+ ctx.fillText(
+ lines[li]!,
+ bx + (layout.padding / 100) * width,
+ by + (li + 0.5) * lineHeight,
+ );
+ }
+
+ ctx.textBaseline = "alphabetic";
+ ctx.restore();
+ }
+
+ return canvas;
+}
+
+export async function exportPdfX4Pages(
+ inputPages: BookPage[],
+ selection: PrintSelection,
+ onProgress?: (pct: number) => void,
+): Promise<Blob> {
+ const pages = preparePrintExport(inputPages, selection);
+ const pageSize = getPageRenderSize();
+ const resolver = createPhotoUrlResolver();
+ const writer = await createPdfWriter(pageSize);
+ try {
+ for (const [i, page] of pages.entries()) {
+ const canvas = await renderPageToCanvas(
+ page,
+ resolver.resolve,
+ pageSize.widthPx,
+ pageSize.heightPx,
+ i === pages.length - 1,
+ i === 0,
+ );
+
+ await writer.addPage(canvas);
+ onProgress?.(Math.round(((i + 1) / pages.length) * 95));
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ }
+
+ const pdf = await writer.finish();
+ onProgress?.(100);
+ return pdf;
+ } finally {
+ writer.dispose();
+ resolver.revokeAll();
+ }
+}
+
+export async function exportPngPagesZip(
+ inputPages: BookPage[],
+ selection: PrintSelection,
+ onProgress?: (pct: number) => void,
+): Promise<Blob> {
+ const pages = preparePrintExport(inputPages, selection);
+ const pageSize = getPageRenderSize();
+ const resolver = createPhotoUrlResolver();
+ try {
+ const zip = new JSZip();
+
+ for (const [i, page] of pages.entries()) {
+ const canvas = await renderPageToCanvas(
+ page,
+ resolver.resolve,
+ pageSize.widthPx,
+ pageSize.heightPx,
+ i === pages.length - 1,
+ i === 0,
+ );
+
+ const blob = await new Promise<Blob>((resolve) =>
+ canvas.toBlob((b) => resolve(b!), "image/png"),
+ );
+
+ const pageNum = String(i + 1).padStart(3, "0");
+ zip.file(`page_${pageNum}.png`, blob);
+
+ onProgress?.(Math.round(((i + 1) / pages.length) * 100));
+ }
+
+ return await zip.generateAsync({ type: "blob" });
+ } finally {
+ resolver.revokeAll();
+ }
+}
diff --git a/web/apps/photobook/src/lib/imageCache.ts b/web/apps/photobook/src/lib/imageCache.ts
new file mode 100644
index 0000000000..a638f5dcdd
--- /dev/null
+++ b/web/apps/photobook/src/lib/imageCache.ts
@@ -0,0 +1,83 @@
+const MAX_ENTRIES = 250;
+
+interface CacheEntry {
+ img: HTMLImageElement;
+ url: string;
+}
+
+const cache = new Map<string, CacheEntry>();
+
+interface PendingEntry {
+ url: string;
+ promise: Promise<HTMLImageElement>;
+}
+
+const pending = new Map<string, PendingEntry>();
+
+function isUsable(img: HTMLImageElement): boolean {
+ return img.complete && img.naturalWidth > 0;
+}
+
+function touch(photoId: string, entry: CacheEntry): void {
+ cache.delete(photoId);
+ cache.set(photoId, entry);
+}
+
+function insert(photoId: string, entry: CacheEntry): void {
+ cache.delete(photoId);
+ cache.set(photoId, entry);
+ while (cache.size > MAX_ENTRIES) {
+ const oldest = cache.keys().next();
+ if (oldest.done) break;
+ cache.delete(oldest.value);
+ }
+}
+
+export function getCachedImage(photoId: string): HTMLImageElement | null {
+ const entry = cache.get(photoId);
+ if (entry && isUsable(entry.img)) {
+ touch(photoId, entry);
+ return entry.img;
+ }
+ return null;
+}
+
+export function getCachedUrl(photoId: string): string | null {
+ const entry = cache.get(photoId);
+ return entry ? entry.url : null;
+}
+
+export function loadImageCached(
+ photoId: string,
+ url: string,
+): Promise<HTMLImageElement> {
+ const existing = cache.get(photoId);
+ if (existing?.url === url && isUsable(existing.img)) {
+ touch(photoId, existing);
+ return Promise.resolve(existing.img);
+ }
+
+ const inflight = pending.get(photoId);
+ if (inflight?.url === url) return inflight.promise;
+
+ const promise = new Promise<HTMLImageElement>((resolve, reject) => {
+ const img = new window.Image();
+ img.onload = () => {
+ insert(photoId, { img, url });
+ pending.delete(photoId);
+ resolve(img);
+ };
+ img.onerror = (e) => {
+ pending.delete(photoId);
+ reject(new Error("Failed to load photo", { cause: e }));
+ };
+ img.src = url;
+ });
+ pending.set(photoId, { url, promise });
+ return promise;
+}
+
+export function clearImageCache(): void {
+ cache.clear();
+ pending.clear();
+}
diff --git a/web/apps/photobook/src/lib/images.ts b/web/apps/photobook/src/lib/images.ts
new file mode 100644
index 0000000000..940bb78628
--- /dev/null
+++ b/web/apps/photobook/src/lib/images.ts
@@ -0,0 +1,56 @@
+import { lowercaseExtension } from "ente-base/file-name";
+import { extractExif } from "ente-gallery/services/exif";
+import { isHEICExtension } from "ente-media/formats";
+import { heicToJPEG } from "ente-media/heic-convert";
+import { scaledImageDimensions } from "ente-media/image";
+
+const HEIC_MIME_TYPES = new Set(["image/heic", "image/heif"]);
+
+export async function extractExifDate(file: File): Promise<number | null> {
+ try {
+ const { creationDate } = await extractExif(file);
+ return creationDate ? Math.round(creationDate.timestamp / 1000) : null;
+ } catch {
+ return null;
+ }
+}
+
+function isHeicLike(mimeType: string | undefined, fileName: string): boolean {
+ return (
+ HEIC_MIME_TYPES.has(mimeType ?? "") ||
+ isHEICExtension(lowercaseExtension(fileName) ?? "")
+ );
+}
+
+export async function normalizeImportedImageBlob(
+ blob: Blob,
+ fileName: string,
+): Promise<Blob> {
+ if (!isHeicLike(blob.type, fileName)) {
+ return blob;
+ }
+
+ return heicToJPEG(blob);
+}
+
+export async function createThumbnail(
+ img: HTMLImageElement,
+ maxSize: number,
+): Promise<Blob> {
+ const canvas = document.createElement("canvas");
+ const { width, height } = scaledImageDimensions(
+ img.naturalWidth,
+ img.naturalHeight,
+ maxSize,
+ );
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d")!;
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(img, 0, 0, width, height);
+
+ return new Promise((resolve) => {
+ canvas.toBlob((blob) => resolve(blob!), "image/jpeg", 0.85);
+ });
+}
diff --git a/web/apps/photobook/src/lib/layouts.test.ts b/web/apps/photobook/src/lib/layouts.test.ts
new file mode 100644
index 0000000000..ed249adfc8
--- /dev/null
+++ b/web/apps/photobook/src/lib/layouts.test.ts
@@ -0,0 +1,373 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { normalizeBookPages } from "./bookPages";
+import {
+ applyVariant,
+ chooseBestVariantKey,
+ defaultVariantKeyForCount,
+ generateAutoLayout,
+ getLayoutMetrics,
+ getMirrorVariant,
+ getVariantPreview,
+ getVariantsForCount,
+} from "./layouts";
+import type { Photo } from "./types";
+
+const photos: Photo[] = Array.from({ length: 12 }, (_, i) => ({
+ id: `photo-${i}`,
+ fileName: `${i}.jpg`,
+ width: i % 2 === 0 ? 1200 : 800,
+ height: i % 2 === 0 ? 800 : 1200,
+ dateTaken: i,
+}));
+
+function bounds(slots: ReturnType<typeof getVariantPreview>) {
+ return {
+ left: Math.min(...slots.map((s) => s.x)),
+ top: Math.min(...slots.map((s) => s.y)),
+ right: Math.max(...slots.map((s) => s.x + s.width)),
+ bottom: Math.max(...slots.map((s) => s.y + s.height)),
+ };
+}
+
+function assertSameBounds(
+ actual: ReturnType<typeof bounds>,
+ expected: ReturnType<typeof bounds>,
+) {
+ for (const edge of ["left", "top", "right", "bottom"] as const) {
+ assert.ok(
+ Math.abs(actual[edge] - expected[edge]) < 1e-9,
+ `${edge} margin matches`,
+ );
+ }
+}
+
+test("single-photo pages use the same outer margins as multi-photo grids", () => {
+ const single = bounds(
+ getVariantPreview(chooseBestVariantKey(photos.slice(0, 1))),
+ );
+ for (const key of [
+ "2-side",
+ "2-stacked",
+ "3-left1-right2",
+ "4-grid",
+ "4-equal-cols",
+ ]) {
+ assertSameBounds(single, bounds(getVariantPreview(key)));
+ }
+ assert.equal(defaultVariantKeyForCount(1), "1-moderate");
+});
+
+test("all standard layouts have equal 25 mm margins on every side", () => {
+ const keys = new Set(
+ [1, 2, 3, 4].flatMap((count) =>
+ getVariantsForCount(count)
+ .flatMap((variant) => [
+ variant.key,
+ getMirrorVariant(variant.key),
+ ])
+ .filter((key): key is string => !!key && key !== "1-full"),
+ ),
+ );
+ const margin = (25 / 210) * 100;
+ for (const key of keys) {
+ assertSameBounds(bounds(getVariantPreview(key)), {
+ left: margin,
+ top: margin,
+ right: 100 - margin,
+ bottom: 100 - margin,
+ });
+ }
+});
+
+test("extra padding is an optional front-cover layout", () => {
+ assert.deepEqual(
+ getVariantsForCount(1).map((variant) => variant.key),
+ ["1-moderate", "1-full"],
+ );
+ assert.deepEqual(
+ getVariantsForCount(1, true).map((variant) => variant.key),
+ ["1-padded", "1-moderate", "1-full"],
+ );
+ const inset = bounds(getVariantPreview("1-padded"));
+ const standard = bounds(getVariantPreview("1-moderate"));
+ assert.ok(inset.left > standard.left && inset.top > standard.top);
+ assert.ok(inset.right < standard.right && inset.bottom < standard.bottom);
+ assert.equal(
+ inset.left,
+ inset.top,
+ "extra-inset covers also use equal horizontal and vertical padding",
+ );
+ assert.equal(inset.right, inset.bottom);
+});
+
+test("four-photo staggered layouts are selectable, retain every photo, and never overlap", () => {
+ const primary = "4-staggered";
+ const mirror = "4-staggered-reverse";
+ assert.ok(
+ getVariantsForCount(4).some((variant) => variant.key === primary),
+ );
+ assert.ok(
+ !getVariantsForCount(4).some((variant) => variant.key === mirror),
+ );
+ assert.ok(
+ !getVariantsForCount(3).some((variant) => variant.key === primary),
+ );
+ assert.equal(getMirrorVariant(primary), mirror);
+ assert.equal(getMirrorVariant(mirror), primary);
+
+ const ids = photos.slice(0, 4).map((photo) => photo.id);
+ const standard = bounds(getVariantPreview("4-grid"));
+ for (const key of [primary, mirror]) {
+ const slots = applyVariant(key, ids);
+ assert.deepEqual(
+ slots.map((slot) => slot.photoId),
+ ids,
+ );
+ assert.equal(new Set(slots.map((slot) => slot.id)).size, 4);
+ assertSameBounds(bounds(slots), standard);
+ assert.deepEqual(
+ slots.map(({ x, y, width, height }) => ({ x, y, width, height })),
+ getVariantPreview(key),
+ "the picker uses the same geometry as the page and export",
+ );
+ for (const [i, slot] of slots.entries()) {
+ assert.ok(slot.width > 0 && slot.height > 0);
+ for (const other of slots.slice(i + 1)) {
+ const overlapW =
+ Math.min(slot.x + slot.width, other.x + other.width) -
+ Math.max(slot.x, other.x);
+ const overlapH =
+ Math.min(slot.y + slot.height, other.y + other.height) -
+ Math.max(slot.y, other.y);
+ assert.ok(
+ overlapW <= 0 || overlapH <= 0,
+ `${key}: photo frames do not overlap`,
+ );
+ }
+ }
+ }
+});
+
+test("staggered layouts anchor the large photos at the outer edges and inset the smaller ones", () => {
+ const [largeTop, smallTop, smallBottom, largeBottom] =
+ getVariantPreview("4-staggered");
+ assert.ok(largeTop && smallTop && smallBottom && largeBottom);
+ const { left, top, cw, ch, hGap, vGap } = getLayoutMetrics();
+ assertSameBounds(bounds([largeTop, largeBottom]), {
+ left,
+ top,
+ right: left + cw,
+ bottom: top + ch,
+ });
+ assert.ok(
+ largeTop.width > smallTop.width && largeTop.height > smallTop.height,
+ );
+ assert.ok(
+ largeBottom.width > smallBottom.width &&
+ largeBottom.height > smallBottom.height,
+ );
+ assert.ok(smallTop.y > top && smallTop.x + smallTop.width < left + cw);
+ assert.ok(
+ smallBottom.x > left && smallBottom.y + smallBottom.height < top + ch,
+ );
+ for (const [actual, expected] of [
+ [smallTop.x - (largeTop.x + largeTop.width), hGap],
+ [largeBottom.x - (smallBottom.x + smallBottom.width), hGap],
+ [smallBottom.y - (largeTop.y + largeTop.height), vGap],
+ [largeBottom.y - (smallTop.y + smallTop.height), vGap],
+ ] as const) {
+ assert.ok(
+ Math.abs(actual - expected) < 1e-9,
+ "uses the standard gap between neighboring photos",
+ );
+ }
+
+ const mirrored = getVariantPreview("4-staggered-reverse");
+ assert.ok(
+ mirrored[0]!.x > mirrored[1]!.x && mirrored[3]!.x < mirrored[2]!.x,
+ );
+ assertSameBounds(
+ bounds([mirrored[0]!, mirrored[3]!]),
+ bounds([largeTop, largeBottom]),
+ );
+});
+
+test("auto-layout uses standard margins for interior single photos and a photo-free back cover", () => {
+ const pages = generateAutoLayout(photos);
+ assert.equal(pages[0]!.layoutVariant, "1-full");
+ assert.deepEqual(bounds(pages[0]!.slots), {
+ left: 0,
+ top: 0,
+ right: 100,
+ bottom: 100,
+ });
+ const standard = bounds(getVariantPreview("2-side"));
+ const singles = pages.slice(1).filter((page) => page.slots.length === 1);
+ assert.ok(singles.length >= 1, "includes an interior single-photo page");
+ for (const page of singles) {
+ assert.equal(page.layoutVariant, "1-moderate");
+ assertSameBounds(bounds(page.slots), standard);
+ }
+ assert.deepEqual(pages.at(-1)?.slots, []);
+ assert.equal(pages.length % 2, 0);
+ assert.deepEqual(
+ pages.flatMap((page) => page.slots.map((slot) => slot.photoId)),
+ photos.map((photo) => photo.id),
+ );
+});
+
+test("auto-layout retains every photo and keeps even page counts for small and large books", () => {
+ for (const count of [0, 1, 2, 3, 4, 5, 6, 11, 20, 31, 100]) {
+ const input = Array.from({ length: count }, (_, i) => ({
+ ...photos[i % photos.length]!,
+ id: `photo-${i}`,
+ dateTaken: i,
+ }));
+ const pages = generateAutoLayout(input);
+ assert.equal(
+ pages.length % 2,
+ 0,
+ `${count} photos produce an even page count`,
+ );
+ assert.deepEqual(
+ pages.flatMap((page) => page.slots.map((slot) => slot.photoId)),
+ input.map((photo) => photo.id),
+ );
+ if (count > 0) {
+ assert.deepEqual(
+ pages.at(-1)?.slots,
+ [],
+ `${count} photos leave the back cover photo-free`,
+ );
+ }
+ }
+});
+
+function makePhotos(count: number): Photo[] {
+ return Array.from({ length: count }, (_, i) => ({
+ ...photos[i % photos.length]!,
+ id: `photo-${i}`,
+ dateTaken: i,
+ }));
+}
+
+test("auto-layout fills every interior page whenever there are at least two interior photos", () => {
+ for (const count of [
+ ...Array.from({ length: 198 }, (_, i) => i + 3),
+ 500,
+ 1000,
+ ]) {
+ const input = makePhotos(count);
+ const pages = generateAutoLayout(input);
+ assert.equal(pages.length % 2, 0);
+ for (const page of pages.slice(1, -1)) {
+ assert.ok(
+ page.slots.length >= 1 && page.slots.length <= 4,
+ `${count} photos: all content pages are populated`,
+ );
+ assert.equal(
+ getVariantPreview(page.layoutVariant!).length,
+ page.slots.length,
+ );
+ }
+ assert.deepEqual(
+ pages.flatMap((page) => page.slots.map((slot) => slot.photoId)),
+ input.map((photo) => photo.id),
+ );
+ assert.strictEqual(
+ normalizeBookPages(pages),
+ pages,
+ "export normalization needs no extra padding",
+ );
+ }
+});
+
+test("splits the final pair across pages 33 and 34 instead of leaving page 34 blank", () => {
+ const pages = generateAutoLayout(makePhotos(75));
+ assert.equal(pages.length, 36);
+ assert.deepEqual(
+ pages[33]!.slots.map((slot) => slot.photoId),
+ ["photo-73"],
+ );
+ assert.deepEqual(
+ pages[34]!.slots.map((slot) => slot.photoId),
+ ["photo-74"],
+ );
+ assert.deepEqual(pages[35]!.slots, [], "back cover stays photo-free");
+ const cycle = [2, 3, 1, 4, 2, 3, 1, 2];
+ assert.deepEqual(
+ pages.slice(1, 33).map((page) => page.slots.length),
+ Array.from({ length: 32 }, (_, i) => cycle[i % cycle.length]!),
+ );
+});
+
+test("chooses a split that keeps adjacent portraits together and reduces cropping", () => {
+ for (const orientations of [
+ ["landscape", "portrait", "portrait"],
+ ["portrait", "portrait", "landscape"],
+ ]) {
+ const input = makePhotos(4);
+ orientations.forEach((orientation, i) => {
+ input[i + 1]!.width = orientation === "landscape" ? 1200 : 800;
+ input[i + 1]!.height = orientation === "landscape" ? 800 : 1200;
+ });
+ const pages = generateAutoLayout(input);
+ const expected = orientations[0] === "landscape" ? [1, 2] : [2, 1];
+ assert.deepEqual(
+ pages.slice(1, -1).map((page) => page.slots.length),
+ expected,
+ );
+ const pair = pages.find((page) => page.slots.length === 2)!;
+ assert.equal(pair.layoutVariant, "2-side");
+ assert.deepEqual(
+ pair.slots.map((slot) => slot.photoId),
+ input
+ .filter((photo) => photo.width < photo.height)
+ .map((photo) => photo.id),
+ );
+ }
+});
+
+test("preserves an already-even grouping", () => {
+ const pages = generateAutoLayout(makePhotos(6));
+ assert.deepEqual(
+ pages.map((page) => page.slots.map((slot) => slot.photoId)),
+ [
+ ["photo-0"],
+ ["photo-1", "photo-2"],
+ ["photo-3", "photo-4", "photo-5"],
+ [],
+ ],
+ );
+});
+
+test("keeps chronological order and stable ordering for equal timestamps without mutating input", () => {
+ const ordered = makePhotos(6).map((photo, i) => ({
+ ...photo,
+ dateTaken: Math.floor(i / 2),
+ }));
+ const input = [
+ ordered[3]!,
+ ordered[0]!,
+ ordered[5]!,
+ ordered[4]!,
+ ordered[1]!,
+ ordered[2]!,
+ ];
+ const original = structuredClone(input);
+ const pages = generateAutoLayout(input);
+ assert.deepEqual(
+ pages.flatMap((page) => page.slots.map((slot) => slot.photoId)),
+ ["photo-0", "photo-1", "photo-3", "photo-2", "photo-5", "photo-4"],
+ );
+ assert.deepEqual(input, original);
+});
+
+test("one interior photo retains the unavoidable blank without duplicating photos", () => {
+ const pages = generateAutoLayout(makePhotos(2));
+ assert.deepEqual(
+ pages.map((page) => page.slots.map((slot) => slot.photoId)),
+ [["photo-0"], ["photo-1"], [], []],
+ );
+});
diff --git a/web/apps/photobook/src/lib/layouts.ts b/web/apps/photobook/src/lib/layouts.ts
new file mode 100644
index 0000000000..f197d1590b
--- /dev/null
+++ b/web/apps/photobook/src/lib/layouts.ts
@@ -0,0 +1,882 @@
+import { BOOK_LAYOUT, BOOK_SIZE_MM } from "./bookFormats";
+import { makeBlankPage, normalizeBookPages } from "./bookPages";
+import type { BookPage, Photo, PhotoSlot } from "./types";
+
+export interface LayoutMetrics {
+ marginH: number;
+ marginV: number;
+ hGap: number;
+ vGap: number;
+ left: number;
+ top: number;
+ cw: number;
+ ch: number;
+}
+
+function mmToPct(mm: number, totalMm: number): number {
+ return (mm / totalMm) * 100;
+}
+
+export function getLayoutMetrics(): LayoutMetrics {
+ const format = BOOK_LAYOUT;
+ const marginH = mmToPct(format.marginMm.h, BOOK_SIZE_MM);
+ const marginV = mmToPct(format.marginMm.v, BOOK_SIZE_MM);
+
+ return {
+ marginH,
+ marginV,
+ hGap: mmToPct(format.gapMm.h, BOOK_SIZE_MM),
+ vGap: mmToPct(format.gapMm.v, BOOK_SIZE_MM),
+ left: marginH,
+ top: marginV,
+ cw: 100 - 2 * marginH,
+ ch: 100 - 2 * marginV,
+ };
+}
+
+type Orientation = "landscape" | "portrait" | "square";
+
+function getOrientation(photo: Photo): Orientation {
+ const ratio = photo.width / photo.height;
+ if (ratio > 1.15) return "landscape";
+ if (ratio < 0.85) return "portrait";
+ return "square";
+}
+
+function makeSlot(
+ photoId: string,
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+): PhotoSlot {
+ return {
+ id: crypto.randomUUID(),
+ photoId,
+ x,
+ y,
+ width: w,
+ height: h,
+ cropX: 0.5,
+ cropY: 0.5,
+ cropZoom: 1,
+ };
+}
+
+export interface LayoutVariant {
+ key: string;
+ photoCount: number;
+ generate: (photoIds: string[], metrics: LayoutMetrics) => PhotoSlot[];
+}
+
+export interface SlotPosition {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+function gen1Padded(ids: string[]): PhotoSlot[] {
+ const left = mmToPct(BOOK_LAYOUT.coverInsetMarginMm.h, BOOK_SIZE_MM);
+ const top = mmToPct(BOOK_LAYOUT.coverInsetMarginMm.v, BOOK_SIZE_MM);
+ return [makeSlot(ids[0]!, left, top, 100 - 2 * left, 100 - 2 * top)];
+}
+
+function gen1Moderate(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ return [makeSlot(ids[0]!, m.left, m.top, m.cw, m.ch)];
+}
+
+function gen1Full(ids: string[]): PhotoSlot[] {
+ return [makeSlot(ids[0]!, 0, 0, 100, 100)];
+}
+
+function gen2Stacked(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, vGap: V_GAP } = m;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, halfH),
+ makeSlot(ids[1]!, LEFT, TOP + halfH + V_GAP, CW, halfH),
+ ];
+}
+
+function gen2SideBySide(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, hGap: H_GAP } = m;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, halfW, CH),
+ makeSlot(ids[1]!, LEFT + halfW + H_GAP, TOP, halfW, CH),
+ ];
+}
+
+function gen2BigTop(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, vGap: V_GAP } = m;
+ const bigH = CH * 0.62;
+ const smallH = CH - bigH - V_GAP;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, bigH),
+ makeSlot(ids[1]!, LEFT, TOP + bigH + V_GAP, CW, smallH),
+ ];
+}
+
+function gen2BigLeft(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, hGap: H_GAP } = m;
+ const bigW = CW * 0.62;
+ const smallW = CW - bigW - H_GAP;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, bigW, CH),
+ makeSlot(ids[1]!, LEFT + bigW + H_GAP, TOP, smallW, CH),
+ ];
+}
+
+function gen2BigBottom(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, vGap: V_GAP } = m;
+ const bigH = CH * 0.62;
+ const smallH = CH - bigH - V_GAP;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, smallH),
+ makeSlot(ids[1]!, LEFT, TOP + smallH + V_GAP, CW, bigH),
+ ];
+}
+
+function gen2BigRight(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, hGap: H_GAP } = m;
+ const bigW = CW * 0.62;
+ const smallW = CW - bigW - H_GAP;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, smallW, CH),
+ makeSlot(ids[1]!, LEFT + smallW + H_GAP, TOP, bigW, CH),
+ ];
+}
+
+function gen3Top1Bot2(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const topH = CH * 0.55;
+ const botH = CH - topH - V_GAP;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, topH),
+ makeSlot(ids[1]!, LEFT, TOP + topH + V_GAP, halfW, botH),
+ makeSlot(
+ ids[2]!,
+ LEFT + halfW + H_GAP,
+ TOP + topH + V_GAP,
+ halfW,
+ botH,
+ ),
+ ];
+}
+
+function gen3Left1Right2(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const leftW = CW * 0.55;
+ const rightW = CW - leftW - H_GAP;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, leftW, CH),
+ makeSlot(ids[1]!, LEFT + leftW + H_GAP, TOP, rightW, halfH),
+ makeSlot(
+ ids[2]!,
+ LEFT + leftW + H_GAP,
+ TOP + halfH + V_GAP,
+ rightW,
+ halfH,
+ ),
+ ];
+}
+
+function gen3Bot1Top2(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const botH = CH * 0.55;
+ const topH = CH - botH - V_GAP;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, halfW, topH),
+ makeSlot(ids[1]!, LEFT + halfW + H_GAP, TOP, halfW, topH),
+ makeSlot(ids[2]!, LEFT, TOP + topH + V_GAP, CW, botH),
+ ];
+}
+
+function gen3Right1Left2(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const rightW = CW * 0.55;
+ const leftW = CW - rightW - H_GAP;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, leftW, halfH),
+ makeSlot(ids[1]!, LEFT, TOP + halfH + V_GAP, leftW, halfH),
+ makeSlot(ids[2]!, LEFT + leftW + H_GAP, TOP, rightW, CH),
+ ];
+}
+
+function gen3EqualRows(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, vGap: V_GAP } = m;
+ const rowH = (CH - V_GAP * 2) / 3;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, rowH),
+ makeSlot(ids[1]!, LEFT, TOP + rowH + V_GAP, CW, rowH),
+ makeSlot(ids[2]!, LEFT, TOP + (rowH + V_GAP) * 2, CW, rowH),
+ ];
+}
+
+function gen3EqualCols(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top: TOP, cw: CW, ch: CH, hGap: H_GAP } = m;
+ const colW = (CW - H_GAP * 2) / 3;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, colW, CH),
+ makeSlot(ids[1]!, LEFT + colW + H_GAP, TOP, colW, CH),
+ makeSlot(ids[2]!, LEFT + (colW + H_GAP) * 2, TOP, colW, CH),
+ ];
+}
+
+function gen3DominantTop(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigH = CH * 0.75;
+ const smallH = CH - bigH - V_GAP;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, bigH),
+ makeSlot(ids[1]!, LEFT, TOP + bigH + V_GAP, halfW, smallH),
+ makeSlot(
+ ids[2]!,
+ LEFT + halfW + H_GAP,
+ TOP + bigH + V_GAP,
+ halfW,
+ smallH,
+ ),
+ ];
+}
+
+function gen3DominantBottom(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigH = CH * 0.75;
+ const smallH = CH - bigH - V_GAP;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, halfW, smallH),
+ makeSlot(ids[1]!, LEFT + halfW + H_GAP, TOP, halfW, smallH),
+ makeSlot(ids[2]!, LEFT, TOP + smallH + V_GAP, CW, bigH),
+ ];
+}
+
+function gen3DominantLeft(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigW = CW * 0.75;
+ const smallW = CW - bigW - H_GAP;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, bigW, CH),
+ makeSlot(ids[1]!, LEFT + bigW + H_GAP, TOP, smallW, halfH),
+ makeSlot(
+ ids[2]!,
+ LEFT + bigW + H_GAP,
+ TOP + halfH + V_GAP,
+ smallW,
+ halfH,
+ ),
+ ];
+}
+
+function gen3DominantRight(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigW = CW * 0.75;
+ const smallW = CW - bigW - H_GAP;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, smallW, halfH),
+ makeSlot(ids[1]!, LEFT, TOP + halfH + V_GAP, smallW, halfH),
+ makeSlot(ids[2]!, LEFT + smallW + H_GAP, TOP, bigW, CH),
+ ];
+}
+
+function gen4Grid(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const halfW = (CW - H_GAP) / 2;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, halfW, halfH),
+ makeSlot(ids[1]!, LEFT + halfW + H_GAP, TOP, halfW, halfH),
+ makeSlot(ids[2]!, LEFT, TOP + halfH + V_GAP, halfW, halfH),
+ makeSlot(
+ ids[3]!,
+ LEFT + halfW + H_GAP,
+ TOP + halfH + V_GAP,
+ halfW,
+ halfH,
+ ),
+ ];
+}
+
+function gen4Staggered(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left, top, cw, ch, hGap, vGap } = m;
+ const largeW = (cw - hGap) / 2;
+ const largeH = (ch - vGap) * 0.56;
+ const smallW = largeW * 0.68;
+ const smallH = (ch - vGap) * 0.32;
+ const rightX = left + largeW + hGap;
+ const lowerY = top + ch - largeH;
+
+ return [
+ makeSlot(ids[0]!, left, top, largeW, largeH),
+ makeSlot(ids[1]!, rightX, lowerY - vGap - smallH, smallW, smallH),
+ makeSlot(
+ ids[2]!,
+ left + largeW - smallW,
+ top + largeH + vGap,
+ smallW,
+ smallH,
+ ),
+ makeSlot(ids[3]!, rightX, lowerY, largeW, largeH),
+ ];
+}
+
+function gen4StaggeredReverse(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ return gen4Staggered(ids, m).map((slot) => ({
+ ...slot,
+ x: m.left + m.cw - (slot.x - m.left) - slot.width,
+ }));
+}
+
+function gen4Top1Bot3(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const topH = CH * 0.5;
+ const botH = CH - topH - V_GAP;
+ const thirdW = (CW - H_GAP * 2) / 3;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, CW, topH),
+ makeSlot(ids[1]!, LEFT, TOP + topH + V_GAP, thirdW, botH),
+ makeSlot(
+ ids[2]!,
+ LEFT + thirdW + H_GAP,
+ TOP + topH + V_GAP,
+ thirdW,
+ botH,
+ ),
+ makeSlot(
+ ids[3]!,
+ LEFT + thirdW * 2 + H_GAP * 2,
+ TOP + topH + V_GAP,
+ thirdW,
+ botH,
+ ),
+ ];
+}
+
+function gen4Bot1Top3(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const botH = CH * 0.5;
+ const topH = CH - botH - V_GAP;
+ const thirdW = (CW - H_GAP * 2) / 3;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, thirdW, topH),
+ makeSlot(ids[1]!, LEFT + thirdW + H_GAP, TOP, thirdW, topH),
+ makeSlot(ids[2]!, LEFT + thirdW * 2 + H_GAP * 2, TOP, thirdW, topH),
+ makeSlot(ids[3]!, LEFT, TOP + topH + V_GAP, CW, botH),
+ ];
+}
+
+function gen4Left1Right3(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const leftW = CW * 0.5;
+ const rightW = CW - leftW - H_GAP;
+ const thirdH = (CH - V_GAP * 2) / 3;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, leftW, CH),
+ makeSlot(ids[1]!, LEFT + leftW + H_GAP, TOP, rightW, thirdH),
+ makeSlot(
+ ids[2]!,
+ LEFT + leftW + H_GAP,
+ TOP + thirdH + V_GAP,
+ rightW,
+ thirdH,
+ ),
+ makeSlot(
+ ids[3]!,
+ LEFT + leftW + H_GAP,
+ TOP + (thirdH + V_GAP) * 2,
+ rightW,
+ thirdH,
+ ),
+ ];
+}
+
+function gen4Right1Left3(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const rightW = CW * 0.5;
+ const leftW = CW - rightW - H_GAP;
+ const thirdH = (CH - V_GAP * 2) / 3;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, leftW, thirdH),
+ makeSlot(ids[1]!, LEFT, TOP + thirdH + V_GAP, leftW, thirdH),
+ makeSlot(ids[2]!, LEFT, TOP + (thirdH + V_GAP) * 2, leftW, thirdH),
+ makeSlot(ids[3]!, LEFT + leftW + H_GAP, TOP, rightW, CH),
+ ];
+}
+
+function gen4WideLeft(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigW = CW * 0.62;
+ const smallW = CW - bigW - H_GAP;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, bigW, halfH),
+ makeSlot(ids[1]!, LEFT + bigW + H_GAP, TOP, smallW, halfH),
+ makeSlot(ids[2]!, LEFT, TOP + halfH + V_GAP, bigW, halfH),
+ makeSlot(
+ ids[3]!,
+ LEFT + bigW + H_GAP,
+ TOP + halfH + V_GAP,
+ smallW,
+ halfH,
+ ),
+ ];
+}
+
+function gen4WideRight(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigW = CW * 0.62;
+ const smallW = CW - bigW - H_GAP;
+ const halfH = (CH - V_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, smallW, halfH),
+ makeSlot(ids[1]!, LEFT + smallW + H_GAP, TOP, bigW, halfH),
+ makeSlot(ids[2]!, LEFT, TOP + halfH + V_GAP, smallW, halfH),
+ makeSlot(
+ ids[3]!,
+ LEFT + smallW + H_GAP,
+ TOP + halfH + V_GAP,
+ bigW,
+ halfH,
+ ),
+ ];
+}
+
+function gen4TallTop(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigH = CH * 0.62;
+ const smallH = CH - bigH - V_GAP;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, halfW, bigH),
+ makeSlot(ids[1]!, LEFT + halfW + H_GAP, TOP, halfW, bigH),
+ makeSlot(ids[2]!, LEFT, TOP + bigH + V_GAP, halfW, smallH),
+ makeSlot(
+ ids[3]!,
+ LEFT + halfW + H_GAP,
+ TOP + bigH + V_GAP,
+ halfW,
+ smallH,
+ ),
+ ];
+}
+
+function gen4TallBottom(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const {
+ left: LEFT,
+ top: TOP,
+ cw: CW,
+ ch: CH,
+ hGap: H_GAP,
+ vGap: V_GAP,
+ } = m;
+ const bigH = CH * 0.62;
+ const smallH = CH - bigH - V_GAP;
+ const halfW = (CW - H_GAP) / 2;
+ return [
+ makeSlot(ids[0]!, LEFT, TOP, halfW, smallH),
+ makeSlot(ids[1]!, LEFT + halfW + H_GAP, TOP, halfW, smallH),
+ makeSlot(ids[2]!, LEFT, TOP + smallH + V_GAP, halfW, bigH),
+ makeSlot(
+ ids[3]!,
+ LEFT + halfW + H_GAP,
+ TOP + smallH + V_GAP,
+ halfW,
+ bigH,
+ ),
+ ];
+}
+
+function gen4EqualCols(ids: string[], m: LayoutMetrics): PhotoSlot[] {
+ const { left: LEFT, top, cw: CW, ch: height, hGap: H_GAP } = m;
+ const colW = (CW - H_GAP * 3) / 4;
+ return [
+ makeSlot(ids[0]!, LEFT, top, colW, height),
+ makeSlot(ids[1]!, LEFT + colW + H_GAP, top, colW, height),
+ makeSlot(ids[2]!, LEFT + (colW + H_GAP) * 2, top, colW, height),
+ makeSlot(ids[3]!, LEFT + (colW + H_GAP) * 3, top, colW, height),
+ ];
+}
+
+const ALL_VARIANTS: LayoutVariant[] = [
+ { key: "1-padded", photoCount: 1, generate: gen1Padded },
+ { key: "1-moderate", photoCount: 1, generate: gen1Moderate },
+ { key: "1-full", photoCount: 1, generate: gen1Full },
+ { key: "2-stacked", photoCount: 2, generate: gen2Stacked },
+ { key: "2-side", photoCount: 2, generate: gen2SideBySide },
+ { key: "2-big-top", photoCount: 2, generate: gen2BigTop },
+ { key: "2-big-left", photoCount: 2, generate: gen2BigLeft },
+ { key: "2-big-bottom", photoCount: 2, generate: gen2BigBottom },
+ { key: "2-big-right", photoCount: 2, generate: gen2BigRight },
+ { key: "3-top1-bot2", photoCount: 3, generate: gen3Top1Bot2 },
+ { key: "3-left1-right2", photoCount: 3, generate: gen3Left1Right2 },
+ { key: "3-bot1-top2", photoCount: 3, generate: gen3Bot1Top2 },
+ { key: "3-right1-left2", photoCount: 3, generate: gen3Right1Left2 },
+ { key: "3-dominant-top", photoCount: 3, generate: gen3DominantTop },
+ { key: "3-dominant-bottom", photoCount: 3, generate: gen3DominantBottom },
+ { key: "3-dominant-left", photoCount: 3, generate: gen3DominantLeft },
+ { key: "3-dominant-right", photoCount: 3, generate: gen3DominantRight },
+ { key: "3-equal-rows", photoCount: 3, generate: gen3EqualRows },
+ { key: "3-equal-cols", photoCount: 3, generate: gen3EqualCols },
+ { key: "4-grid", photoCount: 4, generate: gen4Grid },
+ { key: "4-staggered", photoCount: 4, generate: gen4Staggered },
+ {
+ key: "4-staggered-reverse",
+ photoCount: 4,
+ generate: gen4StaggeredReverse,
+ },
+ { key: "4-top1-bot3", photoCount: 4, generate: gen4Top1Bot3 },
+ { key: "4-bot1-top3", photoCount: 4, generate: gen4Bot1Top3 },
+ { key: "4-left1-right3", photoCount: 4, generate: gen4Left1Right3 },
+ { key: "4-right1-left3", photoCount: 4, generate: gen4Right1Left3 },
+ { key: "4-wide-left", photoCount: 4, generate: gen4WideLeft },
+ { key: "4-wide-right", photoCount: 4, generate: gen4WideRight },
+ { key: "4-tall-top", photoCount: 4, generate: gen4TallTop },
+ { key: "4-tall-bottom", photoCount: 4, generate: gen4TallBottom },
+ { key: "4-equal-cols", photoCount: 4, generate: gen4EqualCols },
+];
+
+const VARIANT_MAP = new Map(ALL_VARIANTS.map((v) => [v.key, v]));
+
+const MIRROR_MAP = new Map<string, string>([
+ ["2-big-top", "2-big-bottom"],
+ ["2-big-bottom", "2-big-top"],
+ ["2-big-left", "2-big-right"],
+ ["2-big-right", "2-big-left"],
+ ["3-top1-bot2", "3-bot1-top2"],
+ ["3-bot1-top2", "3-top1-bot2"],
+ ["3-left1-right2", "3-right1-left2"],
+ ["3-right1-left2", "3-left1-right2"],
+ ["3-dominant-top", "3-dominant-bottom"],
+ ["3-dominant-bottom", "3-dominant-top"],
+ ["3-dominant-left", "3-dominant-right"],
+ ["3-dominant-right", "3-dominant-left"],
+ ["4-staggered", "4-staggered-reverse"],
+ ["4-staggered-reverse", "4-staggered"],
+ ["4-top1-bot3", "4-bot1-top3"],
+ ["4-bot1-top3", "4-top1-bot3"],
+ ["4-left1-right3", "4-right1-left3"],
+ ["4-right1-left3", "4-left1-right3"],
+ ["4-wide-left", "4-wide-right"],
+ ["4-wide-right", "4-wide-left"],
+ ["4-tall-top", "4-tall-bottom"],
+ ["4-tall-bottom", "4-tall-top"],
+]);
+
+const HIDDEN_MIRRORS = new Set([
+ "2-big-bottom",
+ "2-big-right",
+ "3-bot1-top2",
+ "3-right1-left2",
+ "3-dominant-bottom",
+ "3-dominant-right",
+ "4-staggered-reverse",
+ "4-bot1-top3",
+ "4-right1-left3",
+ "4-wide-right",
+ "4-tall-bottom",
+]);
+
+export function getMirrorVariant(key: string): string | undefined {
+ return MIRROR_MAP.get(key);
+}
+
+export function getVariantsForCount(
+ count: number,
+ isFrontCover = false,
+): LayoutVariant[] {
+ return ALL_VARIANTS.filter(
+ (v) =>
+ v.photoCount === count &&
+ !HIDDEN_MIRRORS.has(v.key) &&
+ (isFrontCover || v.key !== "1-padded"),
+ );
+}
+
+export function getCaptionZones(page: BookPage): {
+ topPct: number;
+ bottomPct: number;
+} {
+ if (page.slots.length === 0) {
+ const metrics = getLayoutMetrics();
+ return { topPct: metrics.marginV, bottomPct: metrics.marginV };
+ }
+ const topPct = Math.min(...page.slots.map((s) => s.y));
+ const bottomPct = 100 - Math.max(...page.slots.map((s) => s.y + s.height));
+ return { topPct, bottomPct };
+}
+
+export function getVariantPreview(key: string): SlotPosition[] {
+ const variant = VARIANT_MAP.get(key);
+ if (!variant) return [];
+ const dummyIds = Array.from(
+ { length: variant.photoCount },
+ (_, i) => `d${i}`,
+ );
+ const slots = applyVariant(key, dummyIds);
+ return slots.map((s) => ({
+ x: s.x,
+ y: s.y,
+ width: s.width,
+ height: s.height,
+ }));
+}
+
+export function applyVariant(key: string, photoIds: string[]): PhotoSlot[] {
+ const variant = VARIANT_MAP.get(key);
+ if (!variant) return [];
+ const metrics = getLayoutMetrics();
+ return variant.generate(photoIds, metrics);
+}
+
+export function chooseBestVariantKey(photos: Photo[]): string {
+ const count = photos.length;
+ if (count <= 1) return "1-moderate";
+
+ if (count === 2) {
+ const o0 = getOrientation(photos[0]!);
+ const o1 = getOrientation(photos[1]!);
+ if (o0 === "landscape" && o1 === "landscape") return "2-stacked";
+ return "2-side";
+ }
+
+ if (count === 3) {
+ const o0 = getOrientation(photos[0]!);
+ if (o0 === "landscape") return "3-top1-bot2";
+ return "3-left1-right2";
+ }
+
+ const landscapes = photos.filter((p) => getOrientation(p) === "landscape");
+ if (landscapes.length >= 1) return "4-top1-bot3";
+ return "4-grid";
+}
+
+export function defaultVariantKeyForCount(count: number): string {
+ if (count <= 1) return "1-moderate";
+ if (count === 2) return "2-side";
+ if (count === 3) return "3-left1-right2";
+ return "4-grid";
+}
+
+export function chooseBestLayout(photos: Photo[]): PhotoSlot[] {
+ if (photos.length === 0) return [];
+ const variantKey = chooseBestVariantKey(photos);
+ return applyVariant(
+ variantKey,
+ photos.map((p) => p.id),
+ );
+}
+
+function layoutCropLoss(photos: Photo[]): number {
+ const slots = chooseBestLayout(photos);
+ return photos.reduce((loss, photo, index) => {
+ const photoRatio = photo.width / photo.height;
+ const slotRatio = slots[index]!.width / slots[index]!.height;
+ return (
+ loss + 1 - Math.min(photoRatio / slotRatio, slotRatio / photoRatio)
+ );
+ }, 0);
+}
+
+function groupInteriorPhotos(photos: Photo[]): Photo[][] {
+ const groups: Photo[][] = [];
+ const layoutCycle = [2, 3, 1, 4, 2, 3, 1, 2];
+ let idx = 0;
+
+ while (idx < photos.length) {
+ const remaining = photos.length - idx;
+ let count = Math.min(
+ layoutCycle[groups.length % layoutCycle.length]!,
+ remaining,
+ );
+
+ if (remaining - count === 1 && count < 4) {
+ count = Math.min(count + 1, remaining, 4);
+ }
+ groups.push(photos.slice(idx, idx + count));
+ idx += count;
+ }
+
+ if (groups.length % 2 !== 0) {
+ let groupIndex = groups.length - 1;
+ while (groupIndex >= 0 && groups[groupIndex]!.length < 2) groupIndex--;
+ if (groupIndex >= 0) {
+ const group = groups[groupIndex]!;
+ const splits = Array.from({ length: group.length - 1 }, (_, i) => {
+ const left = group.slice(0, i + 1);
+ const right = group.slice(i + 1);
+ return {
+ left,
+ right,
+ loss: layoutCropLoss(left) + layoutCropLoss(right),
+ };
+ });
+ splits.sort(
+ (a, b) =>
+ a.loss - b.loss ||
+ Math.abs(a.left.length - a.right.length) -
+ Math.abs(b.left.length - b.right.length),
+ );
+ const best = splits[0]!;
+ groups.splice(groupIndex, 1, best.left, best.right);
+ }
+ }
+
+ return groups;
+}
+
+export function generateAutoLayout(photos: Photo[]): BookPage[] {
+ const sorted = [...photos].sort((a, b) => a.dateTaken - b.dateTaken);
+
+ const pages: BookPage[] = [];
+
+ if (sorted.length === 0) return pages;
+
+ pages.push({
+ id: crypto.randomUUID(),
+ slots: applyVariant("1-full", [sorted[0]!.id]),
+ layoutVariant: "1-full",
+ textBlocks: [],
+ topCaption: "",
+ bottomCaption: "",
+ });
+
+ for (const pagePhotos of groupInteriorPhotos(sorted.slice(1))) {
+ const variantKey = chooseBestVariantKey(pagePhotos);
+
+ pages.push({
+ id: crypto.randomUUID(),
+ slots: applyVariant(
+ variantKey,
+ pagePhotos.map((photo) => photo.id),
+ ),
+ layoutVariant: variantKey,
+ textBlocks: [],
+ topCaption: "",
+ bottomCaption: "",
+ });
+ }
+
+ pages.push(makeBlankPage());
+ return normalizeBookPages(pages);
+}
diff --git a/web/apps/photobook/src/lib/pdfx.ts b/web/apps/photobook/src/lib/pdfx.ts
new file mode 100644
index 0000000000..cfcbe36ac7
--- /dev/null
+++ b/web/apps/photobook/src/lib/pdfx.ts
@@ -0,0 +1,41 @@
+import { PhotobookPdf } from "ente-photobook-wasm";
+
+export interface PdfXPageSize {
+ widthMm: number;
+ heightMm: number;
+ widthPx: number;
+ heightPx: number;
+}
+
+export async function createPdfWriter(size: PdfXPageSize) {
+ const response = await fetch("/pdfx/FOGRA39L_coated.icc");
+ if (!response.ok)
+ throw new Error(
+ `Failed to load the print colour profile: ${response.status}`,
+ );
+ const profile = new Uint8Array(await response.arrayBuffer());
+ const writer = await PhotobookPdf.create(
+ profile,
+ size.widthMm,
+ size.heightMm,
+ );
+ const chunks: Uint8Array<ArrayBuffer>[] = [];
+ return {
+ async addPage(canvas: HTMLCanvasElement) {
+ const { data } = canvas
+ .getContext("2d")!
+ .getImageData(0, 0, canvas.width, canvas.height);
+ const pixels = new Uint8Array(data.buffer);
+ chunks.push(
+ await writer.addPage(pixels, canvas.width, canvas.height),
+ );
+ },
+ async finish() {
+ chunks.push(await writer.finish());
+ return new Blob(chunks, { type: "application/pdf" });
+ },
+ dispose() {
+ writer.dispose();
+ },
+ };
+}
diff --git a/web/apps/photobook/src/lib/photoPlacement.test.ts b/web/apps/photobook/src/lib/photoPlacement.test.ts
new file mode 100644
index 0000000000..82a4b9430e
--- /dev/null
+++ b/web/apps/photobook/src/lib/photoPlacement.test.ts
@@ -0,0 +1,218 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { makeBlankPage } from "./bookPages";
+import { applyVariant } from "./layouts";
+import {
+ availablePhotoSpaces,
+ normalizeFrontCover,
+ photoDestinationError,
+ placeImportedPhotos,
+} from "./photoPlacement";
+import type { Photo } from "./types";
+
+const photos: Photo[] = Array.from({ length: 10 }, (_, index) => ({
+ id: `photo-${index}`,
+ fileName: `${index}.jpg`,
+ width: 1200,
+ height: 800,
+ dateTaken: 100 - index,
+}));
+const makeBook = () => [
+ {
+ ...makeBlankPage(),
+ slots: applyVariant("1-full", [photos[0]!.id]),
+ layoutVariant: "1-full",
+ },
+ { ...makeBlankPage(), centerText: "Our holiday", topCaption: "Summer" },
+ makeBlankPage(),
+ makeBlankPage(),
+];
+
+test("adding to a selected blank page keeps its identity, text and surrounding pages", () => {
+ const pages = makeBook();
+ const original = structuredClone(pages);
+ const added = photos.slice(1, 4);
+ const result = placeImportedPhotos(pages, photos, added, {
+ kind: "page",
+ pageId: pages[1]!.id,
+ });
+ assert.equal(result.length, pages.length);
+ assert.equal(result[1]!.id, pages[1]!.id);
+ assert.equal(result[1]!.centerText, "Our holiday");
+ assert.equal(result[1]!.topCaption, "Summer");
+ assert.deepEqual(
+ result[1]!.slots.map((slot) => slot.photoId),
+ added.map((photo) => photo.id),
+ );
+ for (const index of [0, 2, 3])
+ assert.strictEqual(result[index]!, pages[index]!);
+ assert.deepEqual(
+ pages,
+ original,
+ "the previous state remains available for Undo",
+ );
+});
+
+test("adding to a partly filled page preserves existing photo IDs and crop edits", () => {
+ const pages = makeBook();
+ pages[1] = {
+ ...pages[1]!,
+ slots: applyVariant("1-moderate", [photos[1]!.id]),
+ layoutVariant: "1-moderate",
+ };
+ const oldSlot = pages[1].slots[0]!;
+ Object.assign(oldSlot, { cropX: 0.25, cropY: 0.7, cropZoom: 1.6 });
+ const result = placeImportedPhotos(pages, photos, photos.slice(2, 5), {
+ kind: "page",
+ pageId: pages[1].id,
+ });
+ assert.equal(result[1]!.slots.length, 4);
+ const preserved = result[1]!.slots[0]!;
+ for (const key of ["id", "photoId", "cropX", "cropY", "cropZoom"] as const)
+ assert.equal(preserved[key], oldSlot[key]);
+ assert.equal(availablePhotoSpaces(result[1]!), 0);
+});
+
+test("end placement appends in selection order before the back cover, independent of photo dates", () => {
+ const pages = makeBook();
+ const original = structuredClone(pages);
+ const added = photos.slice(1, 10);
+ const result = placeImportedPhotos(pages, photos, added, { kind: "end" });
+ assert.deepEqual(pages, original);
+ assert.deepEqual(
+ result.slice(0, -1).slice(0, pages.length - 1),
+ pages.slice(0, -1),
+ );
+ assert.strictEqual(result.at(-1), pages.at(-1));
+ const newPages = result.slice(pages.length - 1, -1);
+ assert.deepEqual(
+ newPages.map((page) => page.slots.length),
+ [4, 4, 1, 0],
+ );
+ assert.deepEqual(
+ newPages.flatMap((page) => page.slots.map((slot) => slot.photoId)),
+ added.map((photo) => photo.id),
+ );
+ assert.equal(result.length % 2, 0);
+ assert.deepEqual(result.at(-1)!.slots, []);
+});
+
+test("invalid or full destinations reject the entire selection without changing the book", () => {
+ const pages = makeBook();
+ pages[1] = {
+ ...pages[1]!,
+ slots: applyVariant(
+ "3-top1-bot2",
+ photos.slice(1, 4).map((photo) => photo.id),
+ ),
+ };
+ const original = structuredClone(pages);
+ for (const pageId of [pages[1].id, pages.at(-1)!.id, "missing-page"]) {
+ const destination = { kind: "page" as const, pageId };
+ assert.ok(photoDestinationError(pages, destination, 2));
+ assert.throws(() =>
+ placeImportedPhotos(pages, photos, photos.slice(4, 6), destination),
+ );
+ assert.deepEqual(pages, original);
+ }
+ assert.equal(photoDestinationError(pages, { kind: "end" }, 9), null);
+});
+
+test("empty slots count as available and an empty front cover keeps its full-bleed layout", () => {
+ const pages = makeBook();
+ pages[0] = { ...pages[0]!, slots: [] };
+ pages[1] = {
+ ...pages[1]!,
+ slots: applyVariant("2-side", [photos[1]!.id, photos[2]!.id]).map(
+ (slot) => ({ ...slot, photoId: null }),
+ ),
+ };
+ assert.equal(availablePhotoSpaces(pages[1]), 4);
+ const result = placeImportedPhotos(pages, photos, [photos[0]!], {
+ kind: "page",
+ pageId: pages[0].id,
+ });
+ assert.equal(result[0]!.layoutVariant, "1-full");
+ assert.equal(result[0]!.slots.length, 1);
+ assert.strictEqual(
+ placeImportedPhotos(pages, photos, [], { kind: "end" }),
+ pages,
+ );
+});
+
+test("a cover import replaces one image, preserves its title/layout, and can be undone", () => {
+ const pages = makeBook();
+ pages[0] = {
+ ...pages[0]!,
+ slots: applyVariant("1-padded", [photos[0]!.id]),
+ layoutVariant: "1-padded",
+ topCaption: "Our holiday",
+ };
+ pages[0].slots[0]!.cropZoom = 2;
+ const original = structuredClone(pages);
+ const destination = { kind: "page" as const, pageId: pages[0].id };
+ assert.equal(photoDestinationError(pages, destination, 1), null);
+ assert.equal(
+ photoDestinationError(pages, destination, 2),
+ "Choose one photo for the front cover.",
+ );
+ assert.throws(() =>
+ placeImportedPhotos(pages, photos, photos.slice(1, 3), destination),
+ );
+ const result = placeImportedPhotos(
+ pages,
+ photos,
+ [photos[1]!],
+ destination,
+ );
+ assert.equal(result[0]!.slots.length, 1);
+ assert.equal(result[0]!.slots[0]!.photoId, photos[1]!.id);
+ assert.equal(
+ result[0]!.slots[0]!.cropZoom,
+ 1,
+ "new image starts with its own crop",
+ );
+ assert.equal(result[0]!.layoutVariant, "1-padded");
+ assert.equal(result[0]!.topCaption, "Our holiday");
+ assert.equal(result[0]!.id, pages[0].id);
+ assert.equal(result.length, pages.length);
+ assert.deepEqual(pages, original);
+ assert.equal(
+ availablePhotoSpaces(result[0]!, true),
+ 0,
+ "dragging cannot append another cover photo",
+ );
+ assert.equal(availablePhotoSpaces(makeBlankPage(), true), 1);
+});
+
+test("old collage covers retain all photos and crops when limited to one cover photo", () => {
+ const pages = makeBook();
+ pages[0] = {
+ ...pages[0]!,
+ slots: applyVariant(
+ "4-grid",
+ photos.slice(0, 4).map((photo) => photo.id),
+ ),
+ layoutVariant: "4-grid",
+ topCaption: "Our holiday",
+ };
+ pages[0].slots[2]!.cropZoom = 1.5;
+ const original = structuredClone(pages);
+ const result = normalizeFrontCover(pages);
+ assert.equal(result[0]!.slots.length, 1);
+ assert.equal(result[0]!.topCaption, "Our holiday");
+ assert.equal(result[0]!.id, pages[0].id);
+ assert.deepEqual(
+ result
+ .slice(0, 2)
+ .flatMap((page) => page.slots.map((slot) => slot.photoId)),
+ photos.slice(0, 4).map((photo) => photo.id),
+ );
+ assert.equal(result[1]!.slots[1]!.cropZoom, 1.5);
+ assert.equal(result[1]!.slots[1]!.id, pages[0].slots[2]!.id);
+ assert.strictEqual(result[2]!, pages[1]!);
+ assert.strictEqual(result.at(-1), pages.at(-1));
+ assert.equal(result.length % 2, 0);
+ assert.deepEqual(pages, original);
+ assert.strictEqual(normalizeFrontCover(result), result);
+});
diff --git a/web/apps/photobook/src/lib/photoPlacement.ts b/web/apps/photobook/src/lib/photoPlacement.ts
new file mode 100644
index 0000000000..dc68bf93ce
--- /dev/null
+++ b/web/apps/photobook/src/lib/photoPlacement.ts
@@ -0,0 +1,164 @@
+import { makeBlankPage, normalizeBookPages } from "./bookPages";
+import {
+ applyVariant,
+ chooseBestVariantKey,
+ generateAutoLayout,
+ getVariantsForCount,
+} from "./layouts";
+import type { BookPage, Photo } from "./types";
+
+export const MAX_PAGE_PHOTOS = 4;
+export type PhotoDestination =
+ { kind: "page"; pageId: string } | { kind: "end" };
+export interface AddPhotosOptions {
+ replace?: boolean;
+ destination?: PhotoDestination;
+}
+
+export function normalizeFrontCover(pages: BookPage[]): BookPage[] {
+ const cover = pages.at(0);
+ const filled = cover?.slots.filter((slot) => slot.photoId) ?? [];
+ if (!cover || filled.length <= 1) return pages;
+ const first = filled[0]!;
+ const remaining = filled.slice(1);
+ const coverSlot = applyVariant("1-full", [first.photoId!])[0]!;
+ const layoutVariant = getVariantsForCount(remaining.length)[0]!.key;
+ const slots = applyVariant(
+ layoutVariant,
+ remaining.map((slot) => slot.photoId!),
+ ).map((slot, index) => ({
+ ...slot,
+ id: remaining[index]!.id,
+ cropX: remaining[index]!.cropX,
+ cropY: remaining[index]!.cropY,
+ cropZoom: remaining[index]!.cropZoom,
+ }));
+ return normalizeBookPages([
+ {
+ ...cover,
+ layoutVariant: "1-full",
+ slots: [
+ {
+ ...first,
+ x: coverSlot.x,
+ y: coverSlot.y,
+ width: coverSlot.width,
+ height: coverSlot.height,
+ },
+ ],
+ },
+ { ...makeBlankPage(), layoutVariant, slots },
+ ...pages.slice(1),
+ ]);
+}
+
+export function availablePhotoSpaces(
+ page: BookPage,
+ isFrontCover = false,
+): number {
+ const capacity = isFrontCover ? 1 : MAX_PAGE_PHOTOS;
+ return Math.max(
+ 0,
+ capacity - page.slots.filter((slot) => slot.photoId).length,
+ );
+}
+
+export function photoDestinationError(
+ pages: BookPage[],
+ destination: PhotoDestination,
+ count: number,
+): string | null {
+ if (destination.kind === "end") return null;
+ const index = pages.findIndex((page) => page.id === destination.pageId);
+ if (index < 0)
+ return "That page is no longer available. Choose another page.";
+ if (index === pages.length - 1)
+ return "Choose an inside page or the front cover.";
+ if (index === 0)
+ return count === 1 ? null : "Choose one photo for the front cover.";
+ const spaces = availablePhotoSpaces(pages[index]!);
+ if (count > spaces)
+ return `This page has room for ${spaces} more photo${spaces === 1 ? "" : "s"}. Choose another page or create new pages at the end.`;
+ return null;
+}
+
+export function placeImportedPhotos(
+ pages: BookPage[],
+ allPhotos: Photo[],
+ newPhotos: Photo[],
+ destination: PhotoDestination,
+): BookPage[] {
+ if (newPhotos.length === 0) return pages;
+ const error = photoDestinationError(pages, destination, newPhotos.length);
+ if (error) throw new Error(error);
+ if (pages.length === 0) return generateAutoLayout(newPhotos);
+
+ if (destination.kind === "page") {
+ const photoMap = new Map(allPhotos.map((photo) => [photo.id, photo]));
+ return pages.map((page, index) => {
+ if (page.id !== destination.pageId) return page;
+ if (index === 0) {
+ const layoutVariant = getVariantsForCount(1, true).some(
+ (variant) => variant.key === page.layoutVariant,
+ )
+ ? page.layoutVariant!
+ : "1-full";
+ return {
+ ...page,
+ layoutVariant,
+ slots: applyVariant(layoutVariant, [newPhotos[0]!.id]),
+ };
+ }
+ const existingSlots = page.slots.filter((slot) => slot.photoId);
+ const ids = [
+ ...existingSlots.map((slot) => slot.photoId!),
+ ...newPhotos.map((photo) => photo.id),
+ ];
+ const photos = ids.map(
+ (id) =>
+ photoMap.get(id) ?? {
+ id,
+ fileName: "",
+ width: 1,
+ height: 1,
+ dateTaken: 0,
+ },
+ );
+ const layoutVariant = chooseBestVariantKey(photos);
+ const slots = applyVariant(layoutVariant, ids).map((slot) => {
+ const existing = existingSlots.find(
+ (candidate) => candidate.photoId === slot.photoId,
+ );
+ return existing
+ ? {
+ ...slot,
+ id: existing.id,
+ cropX: existing.cropX,
+ cropY: existing.cropY,
+ cropZoom: existing.cropZoom,
+ }
+ : slot;
+ });
+ return { ...page, slots, layoutVariant };
+ });
+ }
+
+ const appended: BookPage[] = [];
+ for (let i = 0; i < newPhotos.length; i += MAX_PAGE_PHOTOS) {
+ const photos = newPhotos.slice(i, i + MAX_PAGE_PHOTOS);
+ const layoutVariant = chooseBestVariantKey(photos);
+ appended.push({
+ ...makeBlankPage(),
+ layoutVariant,
+ slots: applyVariant(
+ layoutVariant,
+ photos.map((photo) => photo.id),
+ ),
+ });
+ }
+ return normalizeBookPages([
+ ...pages.slice(0, -1),
+ ...appended,
+ pages[pages.length - 1]!,
+ ]);
+}
diff --git a/web/apps/photobook/src/lib/printLayout.test.ts b/web/apps/photobook/src/lib/printLayout.test.ts
new file mode 100644
index 0000000000..9d078f36cd
--- /dev/null
+++ b/web/apps/photobook/src/lib/printLayout.test.ts
@@ -0,0 +1,371 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { makeBlankPage } from "./bookPages";
+import { applyVariant, getMirrorVariant, getVariantsForCount } from "./layouts";
+import {
+ getBrandingLayout,
+ getCaptionLayout,
+ getCenterTextLayout,
+ getTextBlockLayout,
+ SAFE_AREA,
+ TEXT_LINE_HEIGHT,
+ type MeasureText,
+} from "./printLayout";
+import type { TextBlock } from "./types";
+
+const sizeMm = 210;
+
+const measure: MeasureText = (text, fontSize) => text.length * fontSize * 0.6;
+const coverTitleFontSize = getCaptionLayout(
+ { ...makeBlankPage(), slots: applyVariant("1-padded", ["photo"]) },
+ "top",
+ true,
+ measure,
+)!.fontSize;
+const epsilon = 1e-9;
+const baseBlock: TextBlock = {
+ id: "text",
+ text: "Holiday",
+ x: 20,
+ y: 30,
+ width: 45,
+ height: 15,
+ fontSize: 2.5,
+ rotation: 0,
+ style: "body",
+ alignment: "left",
+ color: "#555555",
+};
+
+function assertSafeText(block: TextBlock) {
+ const layout = getTextBlockLayout(block, measure);
+ const angle = (layout.rotation * Math.PI) / 180;
+ for (const [x, y] of [
+ [0, 0],
+ [layout.width, 0],
+ [0, layout.height],
+ [layout.width, layout.height],
+ ] as const) {
+ const pageX =
+ ((layout.x + x * Math.cos(angle) - y * Math.sin(angle)) / 100) *
+ sizeMm;
+ const pageY =
+ ((layout.y + x * Math.sin(angle) + y * Math.cos(angle)) / 100) *
+ sizeMm;
+ assert.ok(
+ pageX >= 10 - epsilon && pageX <= sizeMm - 10 + epsilon,
+ `unsafe x: ${pageX}`,
+ );
+ assert.ok(
+ pageY >= 10 - epsilon && pageY <= sizeMm - 10 + epsilon,
+ `unsafe y: ${pageY}`,
+ );
+ }
+ return layout;
+}
+
+test("ordinary captions fit wholly inside the 10 mm safe area on 210 mm pages", () => {
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-moderate", ["photo"]),
+ topCaption: "Summer",
+ bottomCaption: "2026",
+ };
+ for (const position of ["top", "bottom"] as const) {
+ const layout = getCaptionLayout(page, position, false, measure)!;
+ const center = ((layout.y + layout.height / 2) / 100) * sizeMm;
+ const halfLine = ((layout.fontSize * TEXT_LINE_HEIGHT) / 200) * sizeMm;
+ assert.ok(center - halfLine >= 10);
+ assert.ok(center + halfLine <= sizeMm - 10);
+ assert.equal(
+ layout.fontSize,
+ 1.6,
+ "normal captions retain their font size",
+ );
+ assert.ok(Math.abs(Math.min(center, sizeMm - center) - 12.5) < epsilon);
+ }
+});
+
+test("cover titles have equal space toward the photo and paper edge in both inset layouts", () => {
+ for (const variant of ["1-moderate", "1-padded"]) {
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant(variant, ["photo"]),
+ topCaption: "Our holiday",
+ bottomCaption: "2026",
+ };
+ for (const position of ["top", "bottom"] as const) {
+ const layout = getCaptionLayout(page, position, true, measure)!;
+ const photo = page.slots[0]!;
+ const gap =
+ position === "top"
+ ? photo.y - layout.y - layout.height
+ : layout.y - photo.y - photo.height;
+ const outerGap =
+ position === "top" ? layout.y : 100 - layout.y - layout.height;
+ assert.ok(
+ Math.abs(gap - outerGap) < epsilon,
+ `${variant} ${position}: the caption is centred in the white margin`,
+ );
+ assert.ok((gap / 100) * sizeMm >= 10 - epsilon);
+ assert.ok((layout.y / 100) * sizeMm >= 10 - epsilon);
+ assert.ok(
+ ((layout.y + layout.height) / 100) * sizeMm <=
+ sizeMm - 10 + epsilon,
+ );
+ assert.ok(
+ layout.fontSize * TEXT_LINE_HEIGHT <= layout.height + epsilon,
+ );
+ }
+ }
+});
+
+test("all padded layouts centre captions and placeholders in the full white margin", () => {
+ const keys = new Set(
+ [1, 2, 3, 4].flatMap((count) =>
+ getVariantsForCount(count)
+ .flatMap((variant) => [
+ variant.key,
+ getMirrorVariant(variant.key),
+ ])
+ .filter((key): key is string => !!key && key !== "1-full"),
+ ),
+ );
+ for (const key of keys) {
+ const count = Number(key[0]!);
+ const slots = applyVariant(
+ key,
+ Array.from({ length: count }, (_, i) => `photo-${i}`),
+ );
+ const page = { ...makeBlankPage(), slots };
+ const top = Math.min(...slots.map((slot) => slot.y));
+ const bottom = Math.max(...slots.map((slot) => slot.y + slot.height));
+ for (const position of ["top", "bottom"] as const) {
+ const placeholder = getCaptionLayout(
+ page,
+ position,
+ false,
+ measure,
+ )!;
+ const caption = getCaptionLayout(
+ { ...page, topCaption: "Summer", bottomCaption: "2026" },
+ position,
+ false,
+ measure,
+ )!;
+ assert.deepEqual(
+ placeholder,
+ caption,
+ "adding a caption does not shift its position or shrink its font",
+ );
+ assert.equal(caption.fontSize, 1.6);
+ const gap =
+ position === "top"
+ ? top - caption.y - caption.height
+ : caption.y - bottom;
+ const outerGap =
+ position === "top"
+ ? caption.y
+ : 100 - caption.y - caption.height;
+ assert.ok(
+ Math.abs(gap - outerGap) < epsilon,
+ `${key} ${position}: equal space on both sides of the caption`,
+ );
+ assert.ok((gap / 100) * sizeMm >= 10 - epsilon);
+ assert.ok((caption.y / 100) * sizeMm >= 10 - epsilon);
+ assert.ok(
+ ((caption.y + caption.height) / 100) * sizeMm <=
+ sizeMm - 10 + epsilon,
+ );
+ }
+ }
+});
+
+test("captions are hidden when the photo leaves no safe caption band", () => {
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-full", ["photo"]),
+ topCaption: "Old caption",
+ };
+ assert.equal(getCaptionLayout(page, "top", true, measure), null);
+ assert.equal(getCaptionLayout(page, "bottom", true, measure), null);
+});
+
+test("long captions shrink to fit the safe width without changing their content", () => {
+ const text = "A long caption with all the names and places. ".repeat(10);
+ const page = {
+ ...makeBlankPage(),
+ slots: applyVariant("1-moderate", ["photo"]),
+ topCaption: text,
+ bottomCaption: text,
+ };
+ for (const position of ["top", "bottom"] as const) {
+ const layout = getCaptionLayout(page, position, false, measure)!;
+ assert.ok(layout.fontSize < 1.6);
+ assert.ok(measure(text, layout.fontSize, false) <= layout.width);
+ assert.ok(layout.x * 2.1 >= 10 - epsilon);
+ assert.ok((layout.x + layout.width) * 2.1 <= 200 + epsilon);
+ }
+ assert.equal(page.topCaption, text);
+ assert.equal(page.bottomCaption, text);
+});
+
+test("back-cover logo ends 10 mm above the page edge", () => {
+ const layout = getBrandingLayout();
+ const bottomGap = 100 - layout.y - layout.height;
+ assert.ok(Math.abs((bottomGap / 100) * 210 - 10) < epsilon);
+ assert.ok(Math.abs(layout.x + layout.width / 2 - 50) < epsilon);
+});
+
+test("adding and removing photos switches between centered text and captions", () => {
+ const page = {
+ ...makeBlankPage(),
+ centerText: "Summer in the city",
+ topCaption: "Summer",
+ bottomCaption: "2026",
+ };
+ const centered = getCenterTextLayout(page, measure)!;
+ assert.equal(centered.fontSize, coverTitleFontSize);
+ assert.equal(centered.x + centered.width / 2, 50);
+ assert.equal(centered.y + centered.height / 2, 50);
+ assert.equal(getCaptionLayout(page, "top", false, measure), null);
+ assert.equal(getCaptionLayout(page, "bottom", false, measure), null);
+
+ const withPhoto = { ...page, slots: applyVariant("1-moderate", ["photo"]) };
+ assert.equal(getCenterTextLayout(withPhoto, measure), null);
+ assert.ok(getCaptionLayout(withPhoto, "top", false, measure));
+ assert.ok(getCaptionLayout(withPhoto, "bottom", false, measure));
+ const emptied = {
+ ...withPhoto,
+ slots: withPhoto.slots.map((slot) => ({ ...slot, photoId: null })),
+ };
+ assert.deepEqual(getCenterTextLayout(emptied, measure), centered);
+ assert.equal(getCaptionLayout(emptied, "top", false, measure), null);
+ assert.equal(emptied.centerText, page.centerText);
+});
+
+test("page text wraps at a fixed column width without shrinking ordinary paragraphs", () => {
+ const centerText =
+ "John didn't practise or sit around in his room thinking about drumming, he just did it and was magnificent.";
+ const page = { ...makeBlankPage(), centerText };
+ const layout = getCenterTextLayout(page, measure)!;
+ const short = getCenterTextLayout(
+ { ...page, centerText: "Summer" },
+ measure,
+ )!;
+ assert.equal(layout.width, 64);
+ assert.equal(layout.width, short.width);
+ assert.equal(layout.fontSize, short.fontSize);
+ assert.equal(layout.fontSize, coverTitleFontSize);
+ assert.ok(layout.lines.length > 1);
+ assert.equal(layout.lines.join(" "), centerText);
+ assert.equal(layout.x + layout.width / 2, 50);
+ assert.equal(layout.y + layout.height / 2, 50);
+ for (const line of layout.lines)
+ assert.ok(
+ measure(line, layout.fontSize, false) <=
+ layout.width - layout.padding * 2,
+ );
+ assert.equal(
+ page.centerText,
+ centerText,
+ "automatic wrapping does not insert saved line breaks",
+ );
+});
+
+test("page text retains explicit blank lines and wraps unbroken words", () => {
+ const page = makeBlankPage();
+ assert.deepEqual(
+ getCenterTextLayout({ ...page, centerText: "Summer\n\n2026" }, measure)!
+ .lines,
+ ["Summer", "", "2026"],
+ );
+ const word = "supercalifragilisticexpialidocious";
+ const layout = getCenterTextLayout({ ...page, centerText: word }, measure)!;
+ assert.ok(layout.lines.length > 1);
+ assert.equal(layout.lines.join(""), word);
+ assert.equal(layout.fontSize, coverTitleFontSize);
+ for (const line of layout.lines)
+ assert.ok(
+ measure(line, layout.fontSize, false) <=
+ layout.width - layout.padding * 2,
+ );
+});
+
+test("page-length text fits inside the print safe area without changing the column width", () => {
+ for (const centerText of [
+ "A long line of text. ".repeat(60),
+ "A line\n".repeat(30),
+ ]) {
+ const layout = getCenterTextLayout(
+ { ...makeBlankPage(), centerText },
+ measure,
+ )!;
+ assert.ok(layout.fontSize < coverTitleFontSize);
+ assert.equal(layout.width, 64);
+ assert.equal(layout.x + layout.width / 2, 50);
+ assert.equal(layout.y + layout.height / 2, 50);
+ assert.ok(layout.y >= SAFE_AREA.y - epsilon);
+ assert.ok(layout.y + layout.height <= 100 - SAFE_AREA.y + epsilon);
+ for (const line of layout.lines) {
+ assert.ok(
+ measure(line, layout.fontSize, false) <=
+ layout.width - layout.padding * 2,
+ );
+ }
+ }
+});
+
+test("dragging custom text past any edge clamps every rotated corner", () => {
+ for (const rotation of [0, 30, 90, 135, 180, 270, -45]) {
+ for (const x of [-100, 50, 200]) {
+ for (const y of [-100, 50, 200]) {
+ const layout = assertSafeText({ ...baseBlock, x, y, rotation });
+ assert.equal(
+ layout.fontSize,
+ baseBlock.fontSize,
+ "dragging ordinary text does not shrink it",
+ );
+ }
+ }
+ }
+});
+
+test("resizing or extending custom text keeps every line inside the safe area", () => {
+ for (const rotation of [0, 45, -90]) {
+ for (const text of [
+ "A very long single line. ".repeat(25),
+ "Several lines\n".repeat(30),
+ ]) {
+ const original = {
+ ...baseBlock,
+ text,
+ fontSize: 6,
+ x: 95,
+ y: 98,
+ rotation,
+ };
+ const before = structuredClone(original);
+ const layout = assertSafeText(original);
+ assert.ok(layout.fontSize < original.fontSize);
+ assert.equal(
+ layout.lines.join("\n"),
+ text,
+ "retains all content and explicit line breaks",
+ );
+ assert.deepEqual(
+ original,
+ before,
+ "rendering does not mutate saved text",
+ );
+ }
+ }
+});
+
+test("safe text retains its position, rotation and font size", () => {
+ const layout = assertSafeText(baseBlock);
+ assert.equal(layout.x, baseBlock.x);
+ assert.equal(layout.y, baseBlock.y);
+ assert.equal(layout.fontSize, baseBlock.fontSize);
+ assert.equal(layout.rotation, baseBlock.rotation);
+});
diff --git a/web/apps/photobook/src/lib/printLayout.ts b/web/apps/photobook/src/lib/printLayout.ts
new file mode 100644
index 0000000000..868d5b255f
--- /dev/null
+++ b/web/apps/photobook/src/lib/printLayout.ts
@@ -0,0 +1,290 @@
+import {
+ BOOK_LAYOUT,
+ BOOK_SIZE_MM,
+ PRINT_SAFE_MARGIN_PCT,
+} from "./bookFormats";
+import { getCaptionZones } from "./layouts";
+import type { BookPage, TextBlock } from "./types";
+
+export const TEXT_LINE_HEIGHT = 1.4;
+export const CENTER_TEXT_FONT_WEIGHT = 600;
+export const CAPTION_FONT_WEIGHT = 300;
+const TITLE_FONT_SIZE = Math.min(
+ 5,
+ ((BOOK_LAYOUT.coverInsetMarginMm.v / BOOK_SIZE_MM) * 100 -
+ 2 * PRINT_SAFE_MARGIN_PCT) /
+ TEXT_LINE_HEIGHT,
+);
+export const SAFE_AREA = {
+ x: PRINT_SAFE_MARGIN_PCT,
+ y: PRINT_SAFE_MARGIN_PCT,
+ width: 100 - 2 * PRINT_SAFE_MARGIN_PCT,
+ height: 100 - 2 * PRINT_SAFE_MARGIN_PCT,
+};
+
+export function getInterFont(): string {
+ if (typeof window === "undefined") return "sans-serif";
+ return (
+ getComputedStyle(document.body)
+ .getPropertyValue("--font-inter")
+ .trim() || "sans-serif"
+ );
+}
+
+export function getOutfitFont(): string {
+ if (typeof window === "undefined") return "sans-serif";
+ return (
+ getComputedStyle(document.body)
+ .getPropertyValue("--font-outfit")
+ .trim() || "sans-serif"
+ );
+}
+
+export type MeasureText = (
+ text: string,
+ fontSize: number,
+ bold: boolean,
+) => number;
+let measureContext: CanvasRenderingContext2D | null = null;
+function measureTextWithFont(
+ text: string,
+ fontSize: number,
+ fontFamily: string,
+ fontWeight: number,
+): number {
+ measureContext ??= document.createElement("canvas").getContext("2d");
+ if (!measureContext) throw new Error("Unable to measure text.");
+ measureContext.font = `${fontWeight} ${fontSize * 10}px ${fontFamily}, sans-serif`;
+ const metrics = measureContext.measureText(text);
+ return Math.max(metrics.width, metrics.actualBoundingBoxRight || 0) / 10;
+}
+
+const measureBookText: MeasureText = (text, fontSize, bold) =>
+ measureTextWithFont(text, fontSize, getInterFont(), bold ? 700 : 400);
+const measureCaptionText: MeasureText = (text, fontSize) =>
+ measureTextWithFont(text, fontSize, getInterFont(), CAPTION_FONT_WEIGHT);
+const measureCenterText: MeasureText = (text, fontSize) =>
+ measureTextWithFont(
+ text,
+ fontSize,
+ getOutfitFont(),
+ CENTER_TEXT_FONT_WEIGHT,
+ );
+
+export interface CaptionLayout {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ fontSize: number;
+}
+
+export function getCaptionLayout(
+ page: BookPage,
+ position: "top" | "bottom",
+ isFrontCover = false,
+ measure: MeasureText = isFrontCover
+ ? measureCenterText
+ : measureCaptionText,
+): CaptionLayout | null {
+ if (!page.slots.some((slot) => slot.photoId)) return null;
+ const zones = getCaptionZones(page);
+ const zone = position === "top" ? zones.topPct : zones.bottomPct;
+ const height = zone - 2 * PRINT_SAFE_MARGIN_PCT;
+ if (height <= 0) return null;
+ const text = position === "top" ? page.topCaption : page.bottomCaption;
+ let fontSize = Math.min(
+ isFrontCover ? TITLE_FONT_SIZE : 1.6,
+ height / TEXT_LINE_HEIGHT,
+ );
+ if (text) {
+ const textWidth = measure(text, fontSize, false) + fontSize * 0.2;
+ fontSize *= Math.min(1, SAFE_AREA.width / textWidth);
+ }
+ return {
+ x: SAFE_AREA.x,
+ y:
+ position === "top"
+ ? SAFE_AREA.y
+ : 100 - zone + PRINT_SAFE_MARGIN_PCT,
+ width: SAFE_AREA.width,
+ height,
+ fontSize,
+ };
+}
+
+export interface CenterTextLayout extends CaptionLayout {
+ lines: string[];
+ lineHeight: number;
+ padding: number;
+}
+
+const CENTER_TEXT_WIDTH = 64;
+const CENTER_TEXT_LINE_HEIGHT = 1.2;
+
+function wrapCenterText(
+ text: string,
+ fontSize: number,
+ width: number,
+ measure: MeasureText,
+): string[] {
+ return text.split(/\r?\n/).flatMap((paragraph) => {
+ const lines: string[] = [];
+ let line = "";
+ let space = "";
+ for (const token of paragraph.match(/\s+|\S+/g) ?? []) {
+ if (/^\s+$/.test(token)) {
+ space += token;
+ continue;
+ }
+ const candidate = line + space + token;
+ if (measure(candidate, fontSize, false) <= width) {
+ line = candidate;
+ space = "";
+ continue;
+ }
+ if (line) lines.push(line);
+ line = "";
+ space = "";
+ if (measure(token, fontSize, false) <= width) {
+ line = token;
+ continue;
+ }
+ const graphemes = new Intl.Segmenter(undefined, {
+ granularity: "grapheme",
+ }).segment(token);
+ for (const { segment } of graphemes) {
+ if (line && measure(line + segment, fontSize, false) > width) {
+ lines.push(line);
+ line = "";
+ }
+ line += segment;
+ }
+ }
+ lines.push(line);
+ return lines;
+ });
+}
+
+export function getCenterTextLayout(
+ page: BookPage,
+ measure: MeasureText = measureCenterText,
+): CenterTextLayout | null {
+ if (page.slots.some((slot) => slot.photoId)) return null;
+ const text = page.centerText || "Add text...";
+ const wrap = (size: number) =>
+ wrapCenterText(text, size, CENTER_TEXT_WIDTH - size * 0.2, measure);
+ let fontSize = TITLE_FONT_SIZE;
+ let lines = wrap(fontSize);
+ if (lines.length * fontSize * CENTER_TEXT_LINE_HEIGHT > SAFE_AREA.height) {
+ let low = 0;
+ let high = fontSize;
+ for (let i = 0; i < 20; i++) {
+ const candidate = (low + high) / 2;
+ if (
+ wrap(candidate).length * candidate * CENTER_TEXT_LINE_HEIGHT <=
+ SAFE_AREA.height
+ )
+ low = candidate;
+ else high = candidate;
+ }
+ fontSize = low;
+ lines = wrap(fontSize);
+ }
+ const height = lines.length * fontSize * CENTER_TEXT_LINE_HEIGHT;
+ return {
+ x: (100 - CENTER_TEXT_WIDTH) / 2,
+ y: (100 - height) / 2,
+ width: CENTER_TEXT_WIDTH,
+ height,
+ fontSize,
+ lines,
+ lineHeight: CENTER_TEXT_LINE_HEIGHT,
+ padding: fontSize * 0.1,
+ };
+}
+
+export function getBrandingLayout(aspectRatio = 844 / 264) {
+ const height = 3.1;
+ const width = height * aspectRatio;
+ return {
+ x: (100 - width) / 2,
+ y: 100 - PRINT_SAFE_MARGIN_PCT - height,
+ width,
+ height,
+ };
+}
+
+function getRotatedBounds(width: number, height: number, rotation: number) {
+ const angle = (rotation * Math.PI) / 180;
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const xs = [0, width * cos, -height * sin, width * cos - height * sin];
+ const ys = [0, width * sin, height * cos, width * sin + height * cos];
+ return {
+ left: Math.min(...xs),
+ right: Math.max(...xs),
+ top: Math.min(...ys),
+ bottom: Math.max(...ys),
+ };
+}
+
+export function getTextBlockLayout(
+ block: TextBlock,
+ measure: MeasureText = measureBookText,
+) {
+ const lines = (block.text || "Type here").split(/\r?\n/);
+ let fontSize = Math.max(0.1, block.fontSize ?? 2.5);
+ let padding = fontSize * 0.1;
+ let width =
+ Math.max(
+ ...lines.map((line) => measure(line, fontSize, true)),
+ fontSize,
+ ) +
+ padding * 2;
+ let height = lines.length * fontSize * TEXT_LINE_HEIGHT;
+ const rotation = block.rotation ?? 0;
+ let bounds = getRotatedBounds(width, height, rotation);
+ const scale = Math.min(
+ 1,
+ SAFE_AREA.width / (bounds.right - bounds.left),
+ SAFE_AREA.height / (bounds.bottom - bounds.top),
+ );
+ fontSize *= scale;
+ padding *= scale;
+ width *= scale;
+ height *= scale;
+ bounds = getRotatedBounds(width, height, rotation);
+ const x = Math.max(
+ SAFE_AREA.x - bounds.left,
+ Math.min(100 - SAFE_AREA.x - bounds.right, block.x),
+ );
+ const y = Math.max(
+ SAFE_AREA.y - bounds.top,
+ Math.min(100 - SAFE_AREA.y - bounds.bottom, block.y),
+ );
+ return {
+ ...block,
+ x,
+ y,
+ width,
+ height,
+ fontSize,
+ rotation,
+ padding,
+ lines,
+ };
+}
+
+export function constrainTextBlock(block: TextBlock): TextBlock {
+ const { x, y, width, height, fontSize } = getTextBlockLayout(block);
+ if (
+ x === block.x &&
+ y === block.y &&
+ width === block.width &&
+ height === block.height &&
+ fontSize === block.fontSize
+ )
+ return block;
+ return { ...block, x, y, width, height, fontSize };
+}
diff --git a/web/apps/photobook/src/lib/printProducts.test.ts b/web/apps/photobook/src/lib/printProducts.test.ts
new file mode 100644
index 0000000000..5095936a82
--- /dev/null
+++ b/web/apps/photobook/src/lib/printProducts.test.ts
@@ -0,0 +1,120 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { makeBlankPage } from "./bookPages";
+import { applyVariant } from "./layouts";
+import {
+ DEFAULT_PRINT_SELECTION,
+ getBindingPrintSelection,
+ getPrintBinding,
+ getPrintExportError,
+ preparePrintExport,
+ PRINT_PRODUCTS,
+ PrintExportValidationError,
+ type PrintSelection,
+} from "./printProducts";
+
+const pages = (count: number) =>
+ Array.from({ length: count }, () => makeBlankPage());
+
+test("the cover selection uses 210 mm and the shared 24–300 page limits", () => {
+ assert.equal(getPrintBinding(), "Hardcover");
+ for (const binding of ["Hardcover", "Softcover"] as const) {
+ const selection = getBindingPrintSelection(binding);
+ assert.equal(getPrintBinding(selection), binding);
+ assert.equal(selection.sizeMm, 210);
+ assert.equal(getPrintExportError(selection, 24), null);
+ assert.equal(getPrintExportError(selection, 300), null);
+ assert.ok(getPrintExportError(selection, 22));
+ assert.ok(getPrintExportError(selection, 302));
+ assert.equal(preparePrintExport(pages(24), selection).length, 24);
+ }
+});
+
+for (const [productId, min, max] of [
+ ["hardcover-gloss-200", 24, 300],
+ ["hardcover-gloss-150", 24, 500],
+ ["hardcover-mohawk-120", 24, 300],
+ ["softcover-gloss-150", 24, 300],
+ ["softcover-mohawk-120", 24, 300],
+] as const) {
+ test(`${productId} enforces its ${min}–${max} page range at both boundaries`, () => {
+ const selection = { productId, sizeMm: 210 };
+ for (const count of [min, max]) {
+ assert.equal(getPrintExportError(selection, count), null);
+ assert.equal(
+ preparePrintExport(pages(count), selection).length,
+ count,
+ );
+ }
+ for (const count of [min - 2, max + 2]) {
+ assert.match(
+ getPrintExportError(selection, count)!,
+ /including covers/,
+ );
+ assert.throws(
+ () => preparePrintExport(pages(count), selection),
+ PrintExportValidationError,
+ );
+ }
+ assert.match(getPrintExportError(selection, min + 1)!, /even number/);
+ });
+}
+
+test("limits use the normalized export count, including blank interior pages and both covers", () => {
+ assert.equal(
+ preparePrintExport(pages(23), DEFAULT_PRINT_SELECTION).length,
+ 24,
+ );
+ assert.equal(
+ preparePrintExport(pages(299), DEFAULT_PRINT_SELECTION).length,
+ 300,
+ );
+ assert.throws(
+ () => preparePrintExport(pages(301), DEFAULT_PRINT_SELECTION),
+ /Remove 2 pages to stay within 300/,
+ );
+ const softcover: PrintSelection = {
+ productId: "softcover-gloss-150",
+ sizeMm: 210,
+ };
+ assert.equal(preparePrintExport(pages(23), softcover).length, 24);
+ assert.throws(
+ () => preparePrintExport(pages(21), softcover),
+ /Add 2 more pages to reach 24/,
+ );
+});
+
+test("moving an old back-cover photo inside is included before checking the maximum", () => {
+ const book = pages(300);
+ book[299]!.slots = applyVariant("1-full", ["old-back-photo"]);
+ const original = structuredClone(book);
+ assert.throws(
+ () => preparePrintExport(book, DEFAULT_PRINT_SELECTION),
+ /Remove 2 pages to stay within 300/,
+ );
+ assert.deepEqual(book, original);
+});
+
+test("every print product accepts only 210 mm square pages", () => {
+ for (const product of PRINT_PRODUCTS) {
+ assert.deepEqual(product.sizesMm, [210]);
+ for (const sizeMm of [0, 209, 211, NaN, Infinity]) {
+ const selection = { productId: product.id, sizeMm };
+ assert.match(
+ getPrintExportError(selection, 24)!,
+ /Only 210 Γ— 210 mm books are supported/,
+ );
+ assert.throws(
+ () => preparePrintExport(pages(24), selection),
+ PrintExportValidationError,
+ );
+ }
+ }
+ assert.match(
+ getPrintExportError(
+ { productId: "unknown", sizeMm: 210 } as unknown as PrintSelection,
+ 24,
+ )!,
+ /Choose a print product/,
+ );
+});
diff --git a/web/apps/photobook/src/lib/printProducts.ts b/web/apps/photobook/src/lib/printProducts.ts
new file mode 100644
index 0000000000..36b4a81e3e
--- /dev/null
+++ b/web/apps/photobook/src/lib/printProducts.ts
@@ -0,0 +1,119 @@
+import { BOOK_SIZE_MM } from "./bookFormats";
+import { normalizeBookPages } from "./bookPages";
+import type { BookPage } from "./types";
+
+export const PRINT_PRODUCTS = [
+ {
+ id: "hardcover-gloss-200",
+ binding: "Hardcover",
+ paper: "Gloss Β· 200 gsm",
+ minPages: 24,
+ maxPages: 300,
+ sizesMm: [BOOK_SIZE_MM],
+ },
+ {
+ id: "hardcover-gloss-150",
+ binding: "Hardcover",
+ paper: "Gloss Β· 150 gsm",
+ minPages: 24,
+ maxPages: 500,
+ sizesMm: [BOOK_SIZE_MM],
+ },
+ {
+ id: "hardcover-mohawk-120",
+ binding: "Hardcover",
+ paper: "Mohawk uncoated Β· 120 gsm",
+ minPages: 24,
+ maxPages: 300,
+ sizesMm: [BOOK_SIZE_MM],
+ },
+ {
+ id: "softcover-gloss-150",
+ binding: "Softcover",
+ paper: "Gloss Β· 150 gsm",
+ minPages: 24,
+ maxPages: 300,
+ sizesMm: [BOOK_SIZE_MM],
+ },
+ {
+ id: "softcover-mohawk-120",
+ binding: "Softcover",
+ paper: "Mohawk uncoated Β· 120 gsm",
+ minPages: 24,
+ maxPages: 300,
+ sizesMm: [BOOK_SIZE_MM],
+ },
+] as const;
+
+export type PrintProduct = (typeof PRINT_PRODUCTS)[number];
+export type PrintBinding = PrintProduct["binding"];
+export interface PrintSelection {
+ productId: PrintProduct["id"];
+ sizeMm: number;
+}
+
+export const DEFAULT_PRINT_SELECTION: PrintSelection = {
+ productId: "hardcover-gloss-200",
+ sizeMm: BOOK_SIZE_MM,
+};
+
+export function getPrintBinding(selection?: PrintSelection): PrintBinding {
+ return getPrintProduct(selection?.productId)?.binding ?? "Hardcover";
+}
+
+export function getBindingPrintSelection(
+ binding: PrintBinding,
+): PrintSelection {
+ return {
+ productId:
+ binding === "Hardcover"
+ ? "hardcover-gloss-200"
+ : "softcover-gloss-150",
+ sizeMm: BOOK_SIZE_MM,
+ };
+}
+
+export function getPrintProduct(id: unknown): PrintProduct | undefined {
+ return PRINT_PRODUCTS.find((product) => product.id === id);
+}
+
+export function getPrintExportError(
+ selection: PrintSelection,
+ pageCount: number,
+): string | null {
+ const product = getPrintProduct(selection.productId);
+ if (!product) return "Choose a print product before downloading.";
+ if (!(product.sizesMm as readonly number[]).includes(selection.sizeMm)) {
+ return `Only ${BOOK_SIZE_MM} Γ— ${BOOK_SIZE_MM} mm books are supported.`;
+ }
+ if (pageCount < product.minPages || pageCount > product.maxPages) {
+ const belowMinimum = pageCount < product.minPages;
+ const difference = belowMinimum
+ ? product.minPages - pageCount
+ : pageCount - product.maxPages;
+ const pageLabel = difference === 1 ? "page" : "pages";
+ return belowMinimum
+ ? `Add ${difference} more ${pageLabel} to reach ${product.minPages}, including covers.`
+ : `Remove ${difference} ${pageLabel} to stay within ${product.maxPages}, including covers.`;
+ }
+ if (pageCount % 2 !== 0)
+ return "The print product requires an even number of pages, including covers.";
+ return null;
+}
+
+export class PrintExportValidationError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "PrintExportValidationError";
+ }
+}
+
+export function preparePrintExport(
+ inputPages: BookPage[],
+ selection: PrintSelection,
+): BookPage[] {
+ const pages = normalizeBookPages(inputPages);
+ const error = getPrintExportError(selection, pages.length);
+ if (error) throw new PrintExportValidationError(error);
+ return pages;
+}
diff --git a/web/apps/photobook/src/lib/softcoverPreview.test.ts b/web/apps/photobook/src/lib/softcoverPreview.test.ts
new file mode 100644
index 0000000000..68932186bc
--- /dev/null
+++ b/web/apps/photobook/src/lib/softcoverPreview.test.ts
@@ -0,0 +1,131 @@
+import assert from "node:assert/strict";
+import type { PageFlip } from "page-flip";
+import { test, vi } from "vitest";
+import { clipSoftcoverInsidePages } from "./softcoverPreview";
+
+function fixture() {
+ const state = { index: 1, direction: 1, folding: true };
+ const pages = Array.from({ length: 8 }, () => {
+ const style = {
+ clipPath: "",
+ webkitClipPath: "",
+ setProperty(name: string, value: string) {
+ if (name === "-webkit-clip-path") this.webkitClipPath = value;
+ },
+ };
+ return {
+ style,
+ simpleDraw: vi.fn((orientation: number) => {
+ assert.ok(orientation === 0 || orientation === 1);
+ style.clipPath = "";
+ style.webkitClipPath = "";
+ }),
+ getElement: () => ({ style }),
+ };
+ });
+ const book = {
+ getPageCount: () => pages.length,
+ getPage: (index: number) => pages[index]!,
+ getCurrentPageIndex: () => state.index,
+ getRender: () => ({ getRect: () => ({ pageWidth: 300, height: 300 }) }),
+ getFlipController: () => ({
+ getCalculation: () =>
+ state.folding
+ ? {
+ getDirection: () => state.direction,
+ getBottomClipArea: () => [
+ null,
+ { x: 200, y: 0 },
+ { x: 300, y: 0 },
+ { x: 300, y: 300 },
+ { x: 100, y: 300 },
+ { x: 200, y: 0 },
+ ],
+ }
+ : null,
+ }),
+ } as unknown as PageFlip;
+ return { book, pages, state };
+}
+
+function visibleAt(clip: string, x: number, y: number) {
+ const points = [...clip.matchAll(/(-?[\d.]+)px (-?[\d.]+)px/g)].map(
+ (match) => [Number(match[1]!), Number(match[2]!)] as const,
+ );
+ let inside = false;
+ for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
+ const [xi, yi] = points[i]!;
+ const [xj, yj] = points[j]!;
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi)
+ inside = !inside;
+ }
+ return inside;
+}
+
+test("closing the front cover reveals the background behind the left fold", () => {
+ const { book, pages } = fixture();
+ clipSoftcoverInsidePages(book);
+ pages[1]!.simpleDraw(0);
+ const clip = pages[1]!.style.clipPath;
+ assert.match(clip, /^polygon\(evenodd,/);
+ assert.equal(
+ visibleAt(clip, 10, 150),
+ false,
+ "the exposed outside edge has no stationary white sheet",
+ );
+ assert.equal(
+ visibleAt(clip, 280, 150),
+ true,
+ "the unfolded inside face remains beside the spine",
+ );
+ assert.equal(pages[1]!.style.webkitClipPath, clip);
+});
+
+test("closing the back cover mirrors the cutout onto the right page", () => {
+ const { book, pages, state } = fixture();
+ state.index = 5;
+ state.direction = 0;
+ clipSoftcoverInsidePages(book);
+ pages[6]!.simpleDraw(1);
+ assert.equal(visibleAt(pages[6]!.style.clipPath, 290, 150), false);
+ assert.equal(visibleAt(pages[6]!.style.clipPath, 20, 150), true);
+});
+
+test("opening covers and turning interior pages retain the normal page drawing", () => {
+ const { book, pages, state } = fixture();
+ const originals = pages.map((page) => page.simpleDraw);
+ clipSoftcoverInsidePages(book);
+ for (const index of [0, 2, 3, 4, 5, 7])
+ assert.equal(pages[index]!.simpleDraw, originals[index]!);
+ for (const [index, direction] of [
+ [0, 0],
+ [7, 1],
+ [3, 0],
+ [3, 1],
+ [1, 0],
+ [5, 1],
+ ]) {
+ Object.assign(state, { index, direction });
+ pages[1]!.simpleDraw(0);
+ pages[6]!.simpleDraw(1);
+ assert.equal(pages[1]!.style.clipPath, "");
+ assert.equal(pages[6]!.style.clipPath, "");
+ }
+});
+
+test("cancelled and completed folds clear the cutout, and cleanup restores the library methods", () => {
+ const { book, pages, state } = fixture();
+ const originals = pages.map((page) => page.simpleDraw);
+ const restore = clipSoftcoverInsidePages(book);
+ pages[1]!.simpleDraw(0);
+ assert.notEqual(pages[1]!.style.clipPath, "");
+ state.folding = false;
+ pages[1]!.simpleDraw(0);
+ assert.equal(pages[1]!.style.clipPath, "");
+ assert.equal(pages[1]!.style.webkitClipPath, "");
+ restore();
+ assert.deepEqual(
+ pages.map((page) => page.simpleDraw),
+ originals,
+ );
+});
diff --git a/web/apps/photobook/src/lib/softcoverPreview.ts b/web/apps/photobook/src/lib/softcoverPreview.ts
new file mode 100644
index 0000000000..358e2f6cf6
--- /dev/null
+++ b/web/apps/photobook/src/lib/softcoverPreview.ts
@@ -0,0 +1,44 @@
+import type { PageFlip } from "page-flip";
+
+export function clipSoftcoverInsidePages(book: PageFlip): () => void {
+ const count = book.getPageCount();
+ if (count < 4) return () => undefined;
+
+ const restore = [
+ { index: 1, direction: 1, spreadStart: 1 },
+ { index: count - 2, direction: 0, spreadStart: count - 3 },
+ ].map(({ index, direction, spreadStart }) => {
+ const page = book.getPage(index);
+ const simpleDraw = page.simpleDraw;
+
+ page.simpleDraw = function (orientation) {
+ simpleDraw.call(this, orientation);
+ const fold = book.getFlipController().getCalculation();
+ if (
+ fold?.getDirection() !== direction ||
+ book.getCurrentPageIndex() !== spreadStart
+ )
+ return;
+
+ const { pageWidth: width, height } = book.getRender().getRect();
+ const exposed = fold
+ .getBottomClipArea()
+ .filter((point) => point !== null);
+ if (exposed.length < 3) return;
+
+ const hole = exposed.map(
+ ({ x, y }) => `${direction === 1 ? width - x : x}px ${y}px`,
+ );
+ const clip = `polygon(evenodd, 0px 0px, ${width}px 0px, ${width}px ${height}px, 0px ${height}px, 0px 0px, ${hole.join(", ")}, ${hole[0]})`;
+ const style = page.getElement().style;
+ style.clipPath = clip;
+ style.setProperty("-webkit-clip-path", clip);
+ };
+
+ return () => {
+ page.simpleDraw = simpleDraw;
+ };
+ });
+
+ return () => restore.forEach((reset) => reset());
+}
diff --git a/web/apps/photobook/src/lib/spreads.test.ts b/web/apps/photobook/src/lib/spreads.test.ts
new file mode 100644
index 0000000000..94b75251b3
--- /dev/null
+++ b/web/apps/photobook/src/lib/spreads.test.ts
@@ -0,0 +1,213 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import {
+ getFlipPageIndex,
+ getFlipPages,
+ getSpreadLabel,
+ getSpreadPageIndices,
+ getSpreads,
+} from "./spreads";
+
+test("hardcover adds the binding sheets shown in the guide, on both ends", () => {
+ assert.deepEqual(getSpreads(6, "Hardcover"), [
+ { left: null, right: 0 },
+ { left: "printer-blank", right: "printer-blank" },
+ { left: "printer-blank", right: 1 },
+ { left: 2, right: 3 },
+ { left: 4, right: "printer-blank" },
+ { left: "printer-blank", right: "printer-blank" },
+ { left: 5, right: null },
+ ]);
+});
+
+for (const binding of ["Hardcover", "Softcover"] as const) {
+ test(`${binding} preserves content order, recto/verso placement and page jumps at supported counts`, () => {
+ for (const count of [24, 100, 300]) {
+ const spreads = getSpreads(count, binding);
+ const physical = getFlipPages(count, binding);
+ assert.equal(
+ physical.filter((page) => page.pageIndex === null).length,
+ binding === "Hardcover" ? 6 : 2,
+ );
+ assert.deepEqual(
+ spreads.flatMap(getSpreadPageIndices),
+ Array.from({ length: count }, (_, i) => i),
+ );
+ assert.equal(
+ spreads.find((spread) => spread.right === 1)?.left,
+ "printer-blank",
+ );
+ assert.equal(
+ spreads.find((spread) => spread.left === count - 2)?.right,
+ "printer-blank",
+ );
+ for (let index = 0; index < count; index++) {
+ assert.equal(
+ physical[getFlipPageIndex(count, index, binding)!]!
+ .pageIndex,
+ index,
+ );
+ }
+ for (let row = 1; row < spreads.length - 1; row++) {
+ assert.equal(physical[row * 2 - 1]!.spreadIndex, row);
+ assert.equal(physical[row * 2]!.spreadIndex, row);
+ }
+ }
+ });
+}
+
+test("all-blank hardcover spreads have a label and never fabricate a numbered page", () => {
+ const spreads = getSpreads(24, "Hardcover");
+ for (const spread of [spreads[1]!, spreads.at(-2)!]) {
+ assert.equal(getSpreadLabel(spread, 24), "Blank pages");
+ assert.deepEqual(getSpreadPageIndices(spread), []);
+ }
+});
+
+test("content starts on the right and the last even content page faces a printer blank", () => {
+ assert.deepEqual(getSpreads(6, "Softcover"), [
+ { left: null, right: 0 },
+ { left: "printer-blank", right: 1 },
+ { left: 2, right: 3 },
+ { left: 4, right: "printer-blank" },
+ { left: 5, right: null },
+ ]);
+});
+
+test("all real pages appear exactly once in export order, with even content on the left", () => {
+ for (const count of [4, 6, 24, 100, 300]) {
+ const spreads = getSpreads(count, "Softcover");
+ assert.deepEqual(
+ spreads.flatMap(getSpreadPageIndices),
+ Array.from({ length: count }, (_, i) => i),
+ );
+ for (const spread of spreads.slice(1, -1)) {
+ if (typeof spread.left === "number")
+ assert.equal(spread.left % 2, 0);
+ if (typeof spread.right === "number")
+ assert.equal(spread.right % 2, 1);
+ }
+ assert.equal(
+ spreads
+ .flatMap((spread) => [spread.left, spread.right])
+ .filter((page) => page === "printer-blank").length,
+ 2,
+ );
+ }
+});
+
+test("empty and cover-only books do not gain spurious content pages", () => {
+ assert.deepEqual(getSpreads(0, "Softcover"), []);
+ assert.deepEqual(getSpreads(1, "Softcover"), [{ left: null, right: 0 }]);
+ assert.deepEqual(getSpreads(2, "Softcover"), [
+ { left: null, right: 0 },
+ { left: 1, right: null },
+ ]);
+});
+
+test("odd legacy page counts retain the last content page and a separate back cover", () => {
+ assert.deepEqual(getSpreads(5, "Softcover"), [
+ { left: null, right: 0 },
+ { left: "printer-blank", right: 1 },
+ { left: 2, right: 3 },
+ { left: 4, right: null },
+ ]);
+});
+
+test("flip preview includes physical blanks while keeping real book indices intact", () => {
+ assert.deepEqual(getFlipPages(6, "Softcover"), [
+ { pageIndex: 0, spreadIndex: 0 },
+ { pageIndex: null, spreadIndex: 1 },
+ { pageIndex: 1, spreadIndex: 1 },
+ { pageIndex: 2, spreadIndex: 2 },
+ { pageIndex: 3, spreadIndex: 2 },
+ { pageIndex: 4, spreadIndex: 3 },
+ { pageIndex: null, spreadIndex: 3 },
+ { pageIndex: 5, spreadIndex: 4 },
+ ]);
+ for (const count of [0, 1, 2, 5, 6, 24, 300]) {
+ const realIndices = getFlipPages(count, "Softcover").flatMap((page) =>
+ page.pageIndex === null ? [] : [page.pageIndex],
+ );
+ assert.deepEqual(
+ realIndices,
+ Array.from({ length: count }, (_, i) => i),
+ );
+ }
+});
+
+test("flip events and restored preview indices map both sides to the same spread", () => {
+ const spreads = getSpreads(24, "Softcover");
+ const preview = getFlipPages(24, "Softcover");
+ for (let spreadIndex = 0; spreadIndex < spreads.length; spreadIndex++) {
+ const physicalStart = spreadIndex === 0 ? 0 : 2 * spreadIndex - 1;
+ const physicalIndices =
+ spreadIndex === 0 || spreadIndex === spreads.length - 1
+ ? [physicalStart]
+ : [physicalStart, physicalStart + 1];
+ for (const index of physicalIndices)
+ assert.equal(preview[index]!.spreadIndex, spreadIndex);
+ assert.deepEqual(
+ physicalIndices.flatMap((index) =>
+ preview[index]!.pageIndex === null
+ ? []
+ : [preview[index]!.pageIndex],
+ ),
+ getSpreadPageIndices(spreads[spreadIndex]!),
+ );
+ }
+});
+
+test("page labels exclude printer blanks and keep content numbering unchanged", () => {
+ const spreads = getSpreads(24, "Softcover");
+ assert.deepEqual(
+ spreads.map((spread) => getSpreadLabel(spread, 24)),
+ [
+ "Cover",
+ "1",
+ "2–3",
+ "4–5",
+ "6–7",
+ "8–9",
+ "10–11",
+ "12–13",
+ "14–15",
+ "16–17",
+ "18–19",
+ "20–21",
+ "22",
+ "Back cover",
+ ],
+ );
+ assert.equal(getSpreadLabel(undefined, 0), "");
+ assert.deepEqual(
+ getSpreadPageIndices(spreads[1]!),
+ [1],
+ "opening blank has no edit/scroll target",
+ );
+ assert.deepEqual(getSpreadPageIndices(spreads.at(-2)!), [22]);
+});
+
+test("page jumps use editor numbers rather than the inserted printer blanks", () => {
+ assert.deepEqual(
+ Array.from({ length: 6 }, (_, index) =>
+ getFlipPageIndex(6, index, "Softcover"),
+ ),
+ [0, 2, 3, 4, 5, 7],
+ );
+ assert.equal(getFlipPageIndex(24, 22, "Softcover"), 23);
+ assert.equal(
+ getFlipPageIndex(24, 23, "Softcover"),
+ 25,
+ "back cover skips the final printer blank",
+ );
+ assert.equal(
+ getFlipPageIndex(5, 4, "Softcover"),
+ 5,
+ "odd legacy books have no final printer blank",
+ );
+ assert.equal(getFlipPageIndex(1, 0, "Softcover"), 0);
+ for (const index of [-1, 6, 1.5, NaN, Infinity])
+ assert.equal(getFlipPageIndex(6, index, "Softcover"), null);
+ assert.equal(getFlipPageIndex(0, 0, "Softcover"), null);
+});
diff --git a/web/apps/photobook/src/lib/spreads.ts b/web/apps/photobook/src/lib/spreads.ts
new file mode 100644
index 0000000000..bb9396f711
--- /dev/null
+++ b/web/apps/photobook/src/lib/spreads.ts
@@ -0,0 +1,76 @@
+import type { PrintBinding } from "./printProducts";
+
+type SpreadPageRef = number | "printer-blank" | null;
+
+export interface Spread {
+ left: SpreadPageRef;
+ right: SpreadPageRef;
+}
+
+export function getSpreads(pageCount: number, binding: PrintBinding): Spread[] {
+ if (pageCount === 0) return [];
+ const spreads: Spread[] = [{ left: null, right: 0 }];
+ if (pageCount === 1) return spreads;
+
+ if (pageCount > 2) {
+ if (binding === "Hardcover")
+ spreads.push({ left: "printer-blank", right: "printer-blank" });
+ spreads.push({ left: "printer-blank", right: 1 });
+ for (let i = 2; i < pageCount - 1; i += 2) {
+ spreads.push({
+ left: i,
+ right: i + 1 < pageCount - 1 ? i + 1 : "printer-blank",
+ });
+ }
+ if (binding === "Hardcover")
+ spreads.push({ left: "printer-blank", right: "printer-blank" });
+ }
+
+ spreads.push({ left: pageCount - 1, right: null });
+ return spreads;
+}
+
+export function getSpreadPageIndices(spread: Spread): number[] {
+ return [spread.left, spread.right].filter(
+ (page): page is number => typeof page === "number",
+ );
+}
+
+export function getSpreadLabel(
+ spread: Spread | undefined,
+ pageCount: number,
+): string {
+ if (!spread) return "";
+ const indices = getSpreadPageIndices(spread);
+ if (indices.length === 0) return "Blank pages";
+ if (indices.includes(0)) return "Cover";
+ if (indices.includes(pageCount - 1)) return "Back cover";
+ return indices.join("–");
+}
+
+export function getFlipPages(
+ pageCount: number,
+ binding: PrintBinding,
+): { pageIndex: number | null; spreadIndex: number }[] {
+ return getSpreads(pageCount, binding).flatMap((spread, spreadIndex) =>
+ [spread.left, spread.right]
+ .filter((page) => page !== null)
+ .map((page) => ({
+ pageIndex: typeof page === "number" ? page : null,
+ spreadIndex,
+ })),
+ );
+}
+
+export function getFlipPageIndex(
+ pageCount: number,
+ pageIndex: number,
+ binding: PrintBinding,
+): number | null {
+ if (!Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= pageCount)
+ return null;
+ const index = getFlipPages(pageCount, binding).findIndex(
+ (page) => page.pageIndex === pageIndex,
+ );
+ return index < 0 ? null : index;
+}
diff --git a/web/apps/photobook/src/lib/types.ts b/web/apps/photobook/src/lib/types.ts
new file mode 100644
index 0000000000..98c0feb963
--- /dev/null
+++ b/web/apps/photobook/src/lib/types.ts
@@ -0,0 +1,77 @@
+import type { PrintSelection } from "./printProducts";
+
+type PhotoSource = "local" | "ente";
+export type PhotoOriginalStatus = "pending" | "ready" | "failed";
+type EnteOriginalMediaKind = "image" | "live-photo";
+
+interface EntePhotoOriginalData {
+ downloadOrigin: string;
+ accessToken: string;
+ accessTokenJWT?: string;
+ enteFileId: number;
+ mediaKind: EnteOriginalMediaKind;
+ fileKey: string;
+ fileDecryptionHeader: string;
+}
+
+export interface Photo {
+ id: string;
+ fileName: string;
+ width: number;
+ height: number;
+ dateTaken: number;
+ source?: PhotoSource;
+ originalStatus?: PhotoOriginalStatus;
+ originalError?: string;
+ enteOriginal?: EntePhotoOriginalData;
+ thumbnailUrl?: string;
+ fullUrl?: string;
+}
+
+type TextStyle = "title" | "body";
+type TextAlignment = "left" | "center" | "right";
+
+export interface TextBlock {
+ id: string;
+ text: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ style: TextStyle;
+ alignment: TextAlignment;
+ color?: string;
+ rotation?: number;
+ fontSize?: number;
+}
+
+export interface PhotoSlot {
+ id: string;
+ photoId: string | null;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ cropX: number;
+ cropY: number;
+ cropZoom: number;
+}
+
+export interface BookPage {
+ id: string;
+ slots: PhotoSlot[];
+ textBlocks: TextBlock[];
+ topCaption: string;
+ bottomCaption: string;
+ centerText?: string;
+ layoutVariant?: string;
+}
+
+export interface BookState {
+ title?: string;
+ pages: BookPage[];
+ currentSpreadIndex: number;
+ printSelection?: PrintSelection;
+}
+
+export type AppView = "start" | "edit" | "results";
diff --git a/web/apps/photobook/src/pages/_app.tsx b/web/apps/photobook/src/pages/_app.tsx
new file mode 100644
index 0000000000..e0951d69e8
--- /dev/null
+++ b/web/apps/photobook/src/pages/_app.tsx
@@ -0,0 +1,33 @@
+import { BookProvider } from "@/context/BookContext";
+import { PhotoImportProvider } from "@/hooks/usePhotoImport";
+import theme from "@/theme/theme";
+import "@fontsource-variable/inter";
+import "@fontsource-variable/outfit";
+import "@fontsource/gochi-hand";
+import { CssBaseline } from "@mui/material";
+import { ThemeProvider } from "@mui/material/styles";
+import { staticAppTitle } from "ente-base/app";
+import { CustomHead } from "ente-base/components/Head";
+import { useSetupLogs } from "ente-base/components/utils/hooks-app";
+import type { AppProps } from "next/app";
+import "../globals.css";
+
+export default function App({ Component, pageProps }: AppProps) {
+ useSetupLogs({ disableDiskLogs: true });
+ return (
+ <ThemeProvider theme={theme} defaultMode="dark" storageManager={null}>
+ <CustomHead
+ title={staticAppTitle}
+ description="Create photobooks privately in your browser"
+ >
+ <link rel="apple-touch-icon" href="/icon-192x192.png" />
+ </CustomHead>
+ <CssBaseline enableColorScheme />
+ <BookProvider>
+ <PhotoImportProvider>
+ <Component {...pageProps} />
+ </PhotoImportProvider>
+ </BookProvider>
+ </ThemeProvider>
+ );
+}
diff --git a/web/apps/photobook/src/pages/app.tsx b/web/apps/photobook/src/pages/app.tsx
new file mode 100644
index 0000000000..012ef22732
--- /dev/null
+++ b/web/apps/photobook/src/pages/app.tsx
@@ -0,0 +1,22 @@
+import { Box, CircularProgress } from "@mui/material";
+import dynamic from "next/dynamic";
+
+const AppShell = dynamic(() => import("@/components/AppShell"), {
+ ssr: false,
+ loading: () => (
+ <Box
+ sx={{
+ minHeight: "100vh",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <CircularProgress sx={{ color: "#08C225" }} />
+ </Box>
+ ),
+});
+
+export default function Home() {
+ return <AppShell />;
+}
diff --git a/web/apps/photobook/src/pages/index.tsx b/web/apps/photobook/src/pages/index.tsx
new file mode 100644
index 0000000000..6d057ca277
--- /dev/null
+++ b/web/apps/photobook/src/pages/index.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/StartPage";
diff --git a/web/apps/photobook/src/theme/buttons.ts b/web/apps/photobook/src/theme/buttons.ts
new file mode 100644
index 0000000000..a280048abc
--- /dev/null
+++ b/web/apps/photobook/src/theme/buttons.ts
@@ -0,0 +1,59 @@
+import { toolbarColors, uiColors } from "./colors";
+
+export const accentGreen = "#08C225";
+export const accentGreenHover = "#07AE22";
+
+export const editorButtonSx = {
+ height: 44,
+ minWidth: 44,
+ borderRadius: "18px",
+ px: "14px",
+ py: 0,
+ fontSize: 14,
+ fontWeight: 600,
+ lineHeight: "18px",
+ whiteSpace: "nowrap",
+ boxShadow: "none",
+ transition: "background-color 120ms ease",
+ "&:focus-visible": {
+ outline: `2px solid ${accentGreen}`,
+ outlineOffset: 2,
+ },
+ "& .MuiButton-startIcon": { ml: 0, mr: "6px" },
+} as const;
+
+export const headerButtonSx = {
+ ...editorButtonSx,
+ flexShrink: 0,
+ minWidth: { xs: 38, sm: 0 },
+ width: "auto",
+ height: { xs: 38, sm: 40 },
+ px: { xs: "10px", sm: "16px" },
+ py: 0,
+ borderRadius: { xs: "12px", sm: "14px" },
+ lineHeight: "20px",
+ gap: { xs: 0, sm: "8px" },
+ "& .MuiButton-startIcon": { m: 0 },
+ "& .MuiSvgIcon-root": { fontSize: 18 },
+} as const;
+
+export const secondaryButtonSx = {
+ ...editorButtonSx,
+ color: uiColors.text,
+ bgcolor: uiColors.control,
+ "&:hover": { bgcolor: uiColors.controlHover, boxShadow: "none" },
+ "&.Mui-disabled": { color: uiColors.muted, opacity: 0.45 },
+} as const;
+
+export const editorToolbarButtonSx = {
+ ...editorButtonSx,
+ color: toolbarColors.text,
+ bgcolor: toolbarColors.control,
+ "&:hover": { bgcolor: toolbarColors.hover, boxShadow: "none" },
+ "&:active": { bgcolor: toolbarColors.active },
+ "&.Mui-disabled": {
+ color: toolbarColors.disabled,
+ bgcolor: "transparent",
+ opacity: 1,
+ },
+} as const;
diff --git a/web/apps/photobook/src/theme/colors.ts b/web/apps/photobook/src/theme/colors.ts
new file mode 100644
index 0000000000..5a33891752
--- /dev/null
+++ b/web/apps/photobook/src/theme/colors.ts
@@ -0,0 +1,42 @@
+export const uiColors = {
+ background: "#161616",
+ surface: "#212121",
+ canvas: "#161616",
+ paper: "#FFFFFF",
+ control: "#333A3E",
+ controlHover: "#414A4F",
+ text: "#E9EDEF",
+ muted: "#A6AFB4",
+ border: "#3B4348",
+ danger: "#FF9292",
+} as const;
+
+export const pageMenuColors = {
+ background: "#2B2B2B",
+ text: "#F5F5F5",
+ icon: "#BEC3C6",
+ hover: "#3B3B3B",
+ active: "#474747",
+ danger: "#FF9B9B",
+ dangerHover: "#482E31",
+ dangerActive: "#57363A",
+} as const;
+
+export const toolbarColors = {
+ background: "#282828",
+ control: "#3A3A3A",
+ hover: "#484848",
+ active: "#525252",
+ text: "#F2F2F2",
+ muted: "#B8B8B8",
+ disabled: "#737373",
+ border: "rgba(255,255,255,0.09)",
+} as const;
+
+export const bookPageShadow =
+ "0 2px 4px rgba(0,0,0,0.2), 0 12px 28px -8px rgba(0,0,0,0.35)";
+
+export const thumbnailShadow =
+ "0 0 0 1px rgba(255,255,255,0.1), 0 2px 4px rgba(0,0,0,0.2)";
+export const popupShadow =
+ "0 12px 36px rgba(0,0,0,0.35), 0 0 0 1px rgba(255,255,255,0.08)";
diff --git a/web/apps/photobook/src/theme/dialogs.ts b/web/apps/photobook/src/theme/dialogs.ts
new file mode 100644
index 0000000000..4bccc5ccaa
--- /dev/null
+++ b/web/apps/photobook/src/theme/dialogs.ts
@@ -0,0 +1,126 @@
+import { accentGreen } from "./buttons";
+
+export const dialogPaperSx = {
+ width: 381,
+ maxWidth: "calc(100% - 32px)",
+ m: 2,
+ p: 0,
+ borderRadius: "28px",
+ border: "1px solid rgba(255,255,255,0.18)",
+ bgcolor: "#1b1b1b",
+ backgroundImage: "none",
+ boxShadow: "none",
+ fontFamily: '"Inter Variable", sans-serif',
+ letterSpacing: "-0.011em",
+ "& .MuiTypography-root, & .MuiButton-root": { fontFamily: "inherit" },
+} as const;
+
+export const dialogHeaderSx = {
+ width: "100%",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: "9px",
+ textAlign: "center",
+ mb: "16px",
+} as const;
+
+export const dialogTitleSx = {
+ fontSize: 24,
+ lineHeight: "28px",
+ fontWeight: 600,
+ letterSpacing: "-0.48px",
+ color: "#FFFFFF",
+} as const;
+export const dialogDescriptionSx = {
+ fontSize: 14,
+ lineHeight: "20px",
+ fontWeight: 500,
+ color: "rgba(255,255,255,0.7)",
+ width: "100%",
+} as const;
+
+export const dialogCloseButtonSx = {
+ position: "absolute",
+ top: 11,
+ right: 12,
+ p: "10px",
+ flexShrink: 0,
+ color: "#FFFFFF",
+ bgcolor: "rgba(255,255,255,0.12)",
+ "&:hover": { bgcolor: "rgba(255,255,255,0.16)" },
+ "&:focus-visible": {
+ outline: `2px solid ${accentGreen}`,
+ outlineOffset: 2,
+ },
+} as const;
+
+export const dialogActionSx = {
+ display: "flex",
+ p: "20px 16px",
+ justifyContent: "center",
+ alignItems: "center",
+ gap: "8px",
+ flex: "1 0 0",
+ borderRadius: "20px",
+ fontSize: 16,
+ fontWeight: 500,
+ lineHeight: "20px",
+ textTransform: "none",
+ boxShadow: "none",
+ "&:focus-visible": {
+ outline: `2px solid ${accentGreen}`,
+ outlineOffset: 2,
+ },
+} as const;
+export const dialogCancelButtonSx = {
+ ...dialogActionSx,
+ color: "rgba(255,255,255,0.7)",
+ bgcolor: "rgba(255,255,255,0.04)",
+ border: "none",
+ "&:hover": { bgcolor: "rgba(255,255,255,0.08)", border: "none" },
+} as const;
+
+export const dialogSelectSx = {
+ height: 54,
+ bgcolor: "#282828",
+ borderRadius: "16px",
+ color: "#FFFFFF",
+ fontFamily: "inherit",
+ fontSize: 14,
+ fontWeight: 500,
+ "& .MuiSelect-select": { px: "16px" },
+ "& .MuiOutlinedInput-notchedOutline": { borderColor: "transparent" },
+ "&:hover .MuiOutlinedInput-notchedOutline": {
+ borderColor: "rgba(255,255,255,0.12)",
+ },
+ "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
+ borderColor: "rgba(255,255,255,0.18)",
+ borderWidth: 1,
+ },
+} as const;
+export const dialogSelectMenuProps = {
+ slotProps: {
+ paper: {
+ sx: {
+ bgcolor: "#282828",
+ borderRadius: "16px",
+ maxHeight: 320,
+ fontFamily: '"Inter Variable", sans-serif',
+ "& .MuiMenuItem-root": {
+ fontFamily: "inherit",
+ fontSize: 14,
+ "&.Mui-selected": { bgcolor: "transparent" },
+ "&:hover, &.Mui-selected:hover": {
+ bgcolor: "rgba(255,255,255,0.08)",
+ },
+ "&.Mui-focusVisible, &.Mui-selected.Mui-focusVisible": {
+ bgcolor: "rgba(255,255,255,0.08)",
+ outline: "1px solid rgba(255,255,255,0.3)",
+ outlineOffset: -1,
+ },
+ },
+ },
+ },
+ },
+};
diff --git a/web/apps/photobook/src/theme/theme.ts b/web/apps/photobook/src/theme/theme.ts
new file mode 100644
index 0000000000..5bc354b818
--- /dev/null
+++ b/web/apps/photobook/src/theme/theme.ts
@@ -0,0 +1,111 @@
+import {
+ ChevronDownIcon,
+ CloseIcon,
+ ErrorIcon,
+ InfoIcon,
+ SuccessIcon,
+ WarningIcon,
+} from "@/components/icons";
+import { createTheme, type ThemeOptions } from "@mui/material/styles";
+import { shareTheme } from "ente-base/components/utils/theme";
+import { createElement } from "react";
+
+import { accentGreen, accentGreenHover } from "./buttons";
+import { uiColors } from "./colors";
+
+const darkPalette = shareTheme.colorSchemes.dark!.palette;
+
+const overrides: ThemeOptions = {
+ palette: {
+ mode: "dark",
+ primary: {
+ main: accentGreen,
+ dark: accentGreenHover,
+ contrastText: "#ffffff",
+ },
+ secondary: { main: "#1E6D1D" },
+ background: {
+ ...darkPalette.background,
+ default: uiColors.background,
+ paper: uiColors.surface,
+ },
+ text: {
+ ...darkPalette.text,
+ primary: uiColors.text,
+ secondary: uiColors.muted,
+ base: uiColors.text,
+ muted: uiColors.muted,
+ },
+ divider: uiColors.border,
+ action: {
+ ...darkPalette.action,
+ active: uiColors.text,
+ hover: "rgba(233,237,239,0.06)",
+ selected: "rgba(233,237,239,0.1)",
+ disabled: "rgba(233,237,239,0.3)",
+ disabledBackground: uiColors.control,
+ },
+ error: { main: uiColors.danger },
+ },
+ components: {
+ MuiPaper: { styleOverrides: { root: { backgroundImage: "none" } } },
+ MuiSelect: { defaultProps: { IconComponent: ChevronDownIcon } },
+ MuiAlert: {
+ defaultProps: {
+ iconMapping: {
+ success: createElement(SuccessIcon, {
+ fontSize: "inherit",
+ }),
+ info: createElement(InfoIcon, { fontSize: "inherit" }),
+ warning: createElement(WarningIcon, {
+ fontSize: "inherit",
+ }),
+ error: createElement(ErrorIcon, { fontSize: "inherit" }),
+ },
+ slots: { closeIcon: CloseIcon },
+ },
+ },
+ MuiButton: {
+ styleOverrides: {
+ root: { borderRadius: 999, padding: "10px 24px" },
+ },
+ variants: [
+ {
+ props: { variant: "contained", color: "primary" },
+ style: {
+ backgroundColor: accentGreen,
+ backgroundImage: "none",
+ boxShadow: "none",
+ "&.Mui-disabled": {
+ backgroundColor: accentGreen,
+ color: "#FFFFFF",
+ opacity: 0.45,
+ },
+ "&:hover": {
+ backgroundColor: accentGreenHover,
+ boxShadow: "none",
+ },
+ },
+ },
+ ],
+ },
+ },
+};
+
+const theme = createTheme(
+ {
+ cssVariables: { colorSchemeSelector: "class" },
+ defaultColorScheme: "dark",
+ colorSchemes: {
+ light: false,
+ dark: { palette: { ...darkPalette, ...overrides.palette } },
+ },
+ typography: shareTheme.typography,
+ shape: shareTheme.shape,
+ transitions: shareTheme.transitions,
+ components: shareTheme.components,
+ },
+ { components: overrides.components },
+);
+
+export default theme;
diff --git a/web/apps/photobook/src/types/page-flip.d.ts b/web/apps/photobook/src/types/page-flip.d.ts
new file mode 100644
index 0000000000..8923cc9703
--- /dev/null
+++ b/web/apps/photobook/src/types/page-flip.d.ts
@@ -0,0 +1,62 @@
+declare module "page-flip" {
+ interface PageFlipOptions {
+ width: number;
+ height: number;
+ size?: "fixed" | "stretch";
+ minWidth?: number;
+ maxWidth?: number;
+ minHeight?: number;
+ maxHeight?: number;
+ showCover?: boolean;
+ maxShadowOpacity?: number;
+ mobileScrollSupport?: boolean;
+ flippingTime?: number;
+ useMouseEvents?: boolean;
+ swipeDistance?: number;
+ startPage?: number;
+ drawShadow?: boolean;
+ autoSize?: boolean;
+ startZIndex?: number;
+ showPageCorners?: boolean;
+ usePortrait?: boolean;
+ clickEventForward?: boolean;
+ }
+
+ class PageFlip {
+ constructor(element: HTMLElement, options: PageFlipOptions);
+ loadFromHTML(elements: HTMLElement[]): void;
+ loadFromImages(images: string[]): void;
+ turnToPage(pageNum: number): void;
+ turnToNextPage(): void;
+ turnToPrevPage(): void;
+ getCurrentPageIndex(): number;
+ getState(): "read" | "fold_corner" | "user_fold" | "flipping";
+ getPageCount(): number;
+ getPage(pageIndex: number): {
+ setDensity(density: "hard" | "soft"): void;
+ getDensity(): "hard" | "soft";
+ simpleDraw: (orientation: number) => void;
+ getElement(): HTMLElement;
+ };
+ getRender(): { getRect(): { pageWidth: number; height: number } };
+ getFlipController(): {
+ getCalculation(): {
+ getDirection(): number;
+ getBottomClipArea(): ({ x: number; y: number } | null)[];
+ } | null;
+ };
+ on(event: "flip", callback: (e: { data: number }) => void): PageFlip;
+ on(
+ event: "changeState",
+ callback: (e: { data: string }) => void,
+ ): PageFlip;
+ destroy(): void;
+ flip(page: number, corner?: "top" | "bottom"): void;
+ flipNext(corner: "top" | "bottom"): void;
+ flipPrev(corner: "top" | "bottom"): void;
+ update(): void;
+ }
+
+ export { PageFlip };
+ export type { PageFlipOptions };
+}
diff --git a/web/apps/photobook/tsconfig.json b/web/apps/photobook/tsconfig.json
new file mode 100644
index 0000000000..958987c193
--- /dev/null
+++ b/web/apps/photobook/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "ente-build-config/tsconfig-next.json",
+ "compilerOptions": { "paths": { "@/*": ["./src/*"] } },
+ "include": [
+ "src",
+ "*.ts",
+ "*.mts",
+ "next-env.d.ts",
+ "../../packages/base/global-electron.d.ts",
+ "../../packages/base/global-css.d.ts",
+ "../../packages/base/components/utils/mui-theme.d.ts"
+ ]
+}
diff --git a/web/apps/photobook/vitest.config.mts b/web/apps/photobook/vitest.config.mts
new file mode 100644
index 0000000000..f8e5dfcb70
--- /dev/null
+++ b/web/apps/photobook/vitest.config.mts
@@ -0,0 +1,9 @@
+import { fileURLToPath } from "node:url";
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ resolve: {
+ alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) },
+ },
+ test: { include: ["src/**/*.test.ts"] },
+});
diff --git a/web/package-lock.json b/web/package-lock.json
index 7b3d9958dc..af90d17724 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -295,6 +295,27 @@
}
}
},
+ "apps/photobook": {
+ "version": "0.0.0",
+ "dependencies": {
+ "@fontsource/gochi-hand": "5.3.0",
+ "@hugeicons/core-free-icons": "4.3.5",
+ "@hugeicons/react": "1.1.10",
+ "bs58": "6.0.0",
+ "ente-base": "*",
+ "ente-gallery": "*",
+ "ente-media": "*",
+ "ente-photobook-wasm": "*",
+ "jszip": "3.10.2",
+ "konva": "9.3.22",
+ "page-flip": "2.0.7",
+ "react-konva": "19.2.3"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "vitest": "5.0.4"
+ }
+ },
"apps/photos": {
"version": "0.0.0",
"dependencies": {
@@ -3869,6 +3890,15 @@
"@types/react": "^19.3.0"
}
},
+ "node_modules/@types/react-reconciler": {
+ "version": "0.33.1",
+ "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.33.1.tgz",
+ "integrity": "sha512-0kF59ji2mKuHUd5wytHSpmORybMYVerJvq0K10pz9ZFoOlJ3e+w1LBjLshWpCrokeyQOioRodNbO4PH4ddvRfg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*"
+ }
+ },
"node_modules/@types/react-transition-group": {
"version": "4.4.12",
"resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.12.tgz",
@@ -5284,6 +5314,10 @@
"resolved": "packages/wasm/paste",
"link": true
},
+ "node_modules/ente-photobook-wasm": {
+ "resolved": "packages/wasm/photobook",
+ "link": true
+ },
"node_modules/ente-photos-wasm": {
"resolved": "packages/wasm/photos",
"link": true
@@ -7253,6 +7287,27 @@
"node": ">= 0.4"
}
},
+ "node_modules/its-fine": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/its-fine/-/its-fine-2.1.1.tgz",
+ "integrity": "sha512-C5ZoVkeqSt0Aje0tzESO+iT/EQpNFNL39GkP7mCACtoZUFD6GcyerFCr6kp0ZtiII4W9HoYkY48Soy5xE/uHKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/react-reconciler": "^0.28.9"
+ },
+ "peerDependencies": {
+ "react": "^19.0.0"
+ }
+ },
+ "node_modules/its-fine/node_modules/@types/react-reconciler": {
+ "version": "0.28.9",
+ "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.9.tgz",
+ "integrity": "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*"
+ }
+ },
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@@ -7418,6 +7473,26 @@
"node": "^20.19.0 || >=22.12.0"
}
},
+ "node_modules/konva": {
+ "version": "9.3.22",
+ "resolved": "https://registry.npmjs.org/konva/-/konva-9.3.22.tgz",
+ "integrity": "sha512-yQI5d1bmELlD/fowuyfOp9ff+oamg26WOCkyqUyc+nczD/lhRa3EvD2MZOoc4c1293TAubW9n34fSQLgSeEgSw==",
+ "funding": [
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/lavrton"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/konva"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/lavrton"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
@@ -9263,6 +9338,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/page-flip": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/page-flip/-/page-flip-2.0.7.tgz",
+ "integrity": "sha512-96lQFUUz7r/LZzEUZJ3yBIMEKU9+m8HMFDzTvTdD6P7Ag/wXINjp9n0W7b4wanwnDbQETo4uNUoL3zMqpFxwGA==",
+ "license": "MIT"
+ },
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
@@ -9391,6 +9472,10 @@
"@napi-rs/canvas": "^1.0.0"
}
},
+ "node_modules/photobook": {
+ "resolved": "apps/photobook",
+ "link": true
+ },
"node_modules/photos": {
"resolved": "apps/photos",
"link": true
@@ -9730,6 +9815,43 @@
"integrity": "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ==",
"license": "MIT"
},
+ "node_modules/react-konva": {
+ "version": "19.2.3",
+ "resolved": "https://registry.npmjs.org/react-konva/-/react-konva-19.2.3.tgz",
+ "integrity": "sha512-VsO5CJZwUo12xFa33UEIDOQn6ZZBeE6jlkStGFvpR/3NiDA/9RPQTzw6Ri++C0Pnh3Arco1AehB8qJNv9YCRwg==",
+ "funding": [
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/lavrton"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/konva"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/lavrton"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@types/react-reconciler": "^0.33.0",
+ "its-fine": "^2.0.0",
+ "react-reconciler": "0.33.0",
+ "scheduler": "0.27.0"
+ },
+ "peerDependencies": {
+ "konva": "^8.0.1 || ^7.2.5 || ^9.0.0 || ^10.0.0",
+ "react": "^19.2.0",
+ "react-dom": "^19.2.0"
+ }
+ },
+ "node_modules/react-konva/node_modules/scheduler": {
+ "version": "0.27.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
+ "license": "MIT"
+ },
"node_modules/react-leaflet": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz",
@@ -9771,6 +9893,27 @@
"react": ">=18"
}
},
+ "node_modules/react-reconciler": {
+ "version": "0.33.0",
+ "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz",
+ "integrity": "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.27.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "peerDependencies": {
+ "react": "^19.2.0"
+ }
+ },
+ "node_modules/react-reconciler/node_modules/scheduler": {
+ "version": "0.27.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
+ "license": "MIT"
+ },
"node_modules/react-select": {
"version": "5.10.2",
"resolved": "https://registry.npmjs.org/react-select/-/react-select-5.10.2.tgz",
@@ -12156,6 +12299,18 @@
"wasm-pack": "0.15.0"
}
},
+ "packages/wasm/photobook": {
+ "name": "ente-photobook-wasm",
+ "version": "0.0.0",
+ "dependencies": {
+ "comlink": "4.4.2",
+ "ente-utils": "*"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+ },
"packages/wasm/photos": {
"name": "ente-photos-wasm",
"version": "0.0.0",
diff --git a/web/package.json b/web/package.json
index ea8de354ec..38d50fdead 100644
--- a/web/package.json
+++ b/web/package.json
@@ -26,6 +26,8 @@
"build:paste": "npm run build:paste-wasm && npm exec --workspace paste -- next build --webpack && npm run build:post --workspace paste",
"build:paste-wasm": "npm run build --workspace ente-paste-wasm",
"build:payments": "npm run build --workspace payments",
+ "build:photobook": "npm run build:prelogin-wasm && npm run build:photobook-wasm && npm exec --workspace photobook -- next build --webpack",
+ "build:photobook-wasm": "npm run build --workspace ente-photobook-wasm",
"build:photos": "npm run build:prelogin-wasm && npm run build:photos-wasm && npm exec --workspace photos -- next build --webpack",
"build:photos-wasm": "npm run build --workspace ente-photos-wasm",
"build:prelogin-wasm": "npm run build --workspace ente-prelogin-wasm",
@@ -33,7 +35,7 @@
"build:space": "npm run build:prelogin-wasm && npm run build:space-wasm && npm exec --workspace space -- next build --webpack && npm run build:post --workspace space",
"build:space-wasm": "npm run build --workspace ente-space-wasm",
"build:twoof3": "npm exec --workspace twoof3 -- next build --webpack",
- "build:wasm": "npm run build:prelogin-wasm && npm run build:auth-wasm && npm run build:cast-wasm && npm run build:ensu-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm run build:paste-wasm && npm run build:photos-wasm && npm run build:space-wasm",
+ "build:wasm": "npm run build:prelogin-wasm && npm run build:auth-wasm && npm run build:cast-wasm && npm run build:ensu-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm run build:paste-wasm && npm run build:photos-wasm && npm run build:space-wasm && npm run build:photobook-wasm",
"dev": "npm run dev:photos",
"dev:accounts": "npm run build:prelogin-wasm && npm exec --workspace accounts -- next dev --webpack -p 3001",
"dev:albums": "npm run build:prelogin-wasm && npm exec --workspace albums -- next dev --webpack -p 3002",
@@ -46,13 +48,14 @@
"dev:memories": "npm run build:prelogin-wasm && npm exec --workspace memories -- next dev --webpack -p 3010",
"dev:paste": "npm run build:paste-wasm && npm exec --workspace paste -- next dev --webpack -p 3008",
"dev:payments": "npm run dev --workspace payments",
+ "dev:photobook": "npm run build:prelogin-wasm && npm run build:photobook-wasm && npm exec --workspace photobook -- next dev --webpack -p 3014",
"dev:photos": "npm run build:prelogin-wasm && npm run build:photos-wasm && npm exec --workspace photos -- next dev --webpack -p 3000",
"dev:share": "npm run build:prelogin-wasm && npm exec --workspace share -- next dev --webpack -p 3005",
"dev:space": "npm run build:prelogin-wasm && npm run build:space-wasm && npm exec --workspace space -- next dev --webpack -p 3013",
"dev:twoof3": "npm exec --workspace twoof3 -- next dev --webpack -p 3012",
"lint": "node scripts/lint.mjs",
"lint:fix": "node scripts/lint.mjs --fix",
- "test": "npm run test --workspace ente-wasm-tests && npm run test --workspace ente-prelogin-wasm && npm run test --workspace ente-locker-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace ensu && npm run test --workspace locker && npm run test --workspace paste && npm run test --workspace photos && npm run test --workspace space"
+ "test": "npm run test --workspace ente-wasm-tests && npm run test --workspace ente-prelogin-wasm && npm run test --workspace ente-locker-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace ensu && npm run test --workspace locker && npm run test --workspace paste && npm run test --workspace photos && npm run test --workspace space && npm run test --workspace photobook"
},
"overrides": {
"@types/react": "19.3.0",
diff --git a/web/packages/accounts/services/redirect.ts b/web/packages/accounts/services/redirect.ts
index 878617c9cc..2702c27ffb 100644
--- a/web/packages/accounts/services/redirect.ts
+++ b/web/packages/accounts/services/redirect.ts
@@ -10,6 +10,7 @@ export const appHomeRoute: string = {
embed: "/",
share: "/",
photos: "/gallery",
+ photobook: "/app",
ensu: "/",
locker: "/locker",
legacy: "/",
diff --git a/web/packages/base/app.ts b/web/packages/base/app.ts
index 61a61330dc..aea612ad3f 100644
--- a/web/packages/base/app.ts
+++ b/web/packages/base/app.ts
@@ -12,6 +12,7 @@ export const appNames = [
"embed",
"share",
"photos",
+ "photobook",
"ensu",
"locker",
"legacy",
@@ -38,6 +39,7 @@ export const staticAppTitle = {
embed: "Ente Photos",
share: "Ente Locker",
photos: "Ente Photos",
+ photobook: "Ente Photobook",
ensu: "Ensu",
locker: "Ente Locker",
legacy: "Ente Legacy Kit",
@@ -59,6 +61,7 @@ export const clientPackageName = (() => {
embed: "io.ente.photos.web", // Use photos package name for embed app
share: "io.ente.share.web",
photos: "io.ente.photos.web",
+ photobook: "io.ente.photobook.web",
ensu: "io.ente.ensu",
locker: "io.ente.locker.web",
legacy: "io.ente.legacy.web",
diff --git a/web/packages/media/public-albums.ts b/web/packages/media/public-albums.ts
new file mode 100644
index 0000000000..c59d9b7308
--- /dev/null
+++ b/web/packages/media/public-albums.ts
@@ -0,0 +1,95 @@
+import { deriveKey } from "ente-base/crypto";
+import { fetchPublicCollectionFile } from "ente-base/file-download";
+import {
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders,
+ authenticatedPublicAlbumsInfoRequestHeaders,
+ authenticatedPublicAlbumsRequestHeaders,
+ ensureOk,
+ linkDeviceTokenFromResponse,
+ type PublicAlbumsCredentials,
+} from "ente-base/http";
+import { apiURL, customAPIOrigin } from "ente-base/origins";
+import { z } from "zod";
+import { RemoteCollection, type PublicURL } from "./collection";
+import { FileDiffResponse } from "./file";
+
+const PublicCollectionInfo = z.object({
+ collection: RemoteCollection,
+ referralCode: z.string(),
+});
+
+export const getPublicCollectionInfo = async (
+ credentials: PublicAlbumsCredentials,
+) => {
+ const res = await fetch(await apiURL("/public-collection/info"), {
+ headers: authenticatedPublicAlbumsInfoRequestHeaders(credentials),
+ });
+ ensureOk(res);
+ const info = PublicCollectionInfo.parse(await res.json());
+ return { ...info, linkDeviceToken: linkDeviceTokenFromResponse(res) };
+};
+
+export const verifyPublicCollectionPassword = async (
+ credentials: PublicAlbumsCredentials,
+ publicURL: PublicURL,
+ password: string,
+) => {
+ const passHash = await deriveKey(
+ password,
+ publicURL.nonce!,
+ publicURL.opsLimit!,
+ publicURL.memLimit!,
+ );
+ const res = await fetch(
+ await apiURL("/public-collection/verify-password"),
+ {
+ method: "POST",
+ headers: {
+ ...authenticatedPublicAlbumsRequestHeaders(credentials),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ passHash }),
+ },
+ );
+ ensureOk(res);
+ return z.object({ jwtToken: z.string() }).parse(await res.json()).jwtToken;
+};
+
+export const getPublicCollectionDiff = async (
+ credentials: PublicAlbumsCredentials,
+ sinceTime: number,
+) => {
+ const res = await fetch(
+ await apiURL("/public-collection/diff", { sinceTime }),
+ {
+ headers:
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders(credentials),
+ },
+ );
+ ensureOk(res);
+ return FileDiffResponse.parse(await res.json());
+};
+
+export const downloadPublicCollectionFile = async (
+ credentials: PublicAlbumsCredentials,
+ fileID: number,
+ thumbnail: boolean,
+ downloadOrigin?: string,
+) => {
+ const customOrigin = await customAPIOrigin();
+ const origin =
+ downloadOrigin ?? customOrigin ?? "https://public-albums.ente.com";
+ const path = thumbnail ? "preview" : "download";
+ const res =
+ customOrigin && origin === customOrigin
+ ? await fetchPublicCollectionFile(
+ fileID,
+ thumbnail ? "thumbnail" : "file",
+ credentials,
+ )
+ : await fetch(`${origin}/${path}/?fileID=${fileID}`, {
+ headers: authenticatedPublicAlbumsRequestHeaders(credentials),
+ });
+ ensureOk(res);
+ return new Uint8Array(await res.arrayBuffer());
+};
diff --git a/web/packages/wasm/photobook/eslint.config.mjs b/web/packages/wasm/photobook/eslint.config.mjs
new file mode 100644
index 0000000000..e6c7d4d3b0
--- /dev/null
+++ b/web/packages/wasm/photobook/eslint.config.mjs
@@ -0,0 +1,3 @@
+import config from "ente-build-config/eslintrc-base.mjs";
+
+export default [...config, { ignores: ["pkg/"] }];
diff --git a/web/packages/wasm/photobook/index.ts b/web/packages/wasm/photobook/index.ts
new file mode 100644
index 0000000000..6797104730
--- /dev/null
+++ b/web/packages/wasm/photobook/index.ts
@@ -0,0 +1,43 @@
+import { transfer, wrap, type Remote } from "comlink";
+import { workerReady } from "ente-utils/worker";
+import type { PhotobookWorker } from "./worker";
+
+export class PhotobookPdf {
+ private constructor(
+ private worker: Worker,
+ private remote: Remote<PhotobookWorker>,
+ ) {}
+
+ static async create(
+ profile: Uint8Array,
+ widthMm: number,
+ heightMm: number,
+ ) {
+ const worker = new Worker(new URL("worker.ts", import.meta.url));
+ const RemoteWorker = wrap<typeof PhotobookWorker>(worker);
+ const remote = await workerReady(worker, new RemoteWorker());
+ try {
+ await remote.initialize(profile, widthMm, heightMm, Date.now());
+ return new PhotobookPdf(worker, remote);
+ } catch (error) {
+ worker.terminate();
+ throw error;
+ }
+ }
+
+ addPage(pixels: Uint8Array<ArrayBuffer>, width: number, height: number) {
+ return this.remote.addPage(
+ transfer(pixels, [pixels.buffer]),
+ width,
+ height,
+ );
+ }
+
+ finish() {
+ return this.remote.finish();
+ }
+
+ dispose() {
+ this.worker.terminate();
+ }
+}
diff --git a/web/packages/wasm/photobook/package.json b/web/packages/wasm/photobook/package.json
new file mode 100644
index 0000000000..6580d99de6
--- /dev/null
+++ b/web/packages/wasm/photobook/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "ente-photobook-wasm",
+ "version": "0.0.0",
+ "private": true,
+ "exports": {
+ ".": {
+ "types": "./index.ts",
+ "import": "./index.ts"
+ }
+ },
+ "module": "./index.ts",
+ "types": "./index.ts",
+ "scripts": {
+ "build": "wasm-pack build ../../../../rust/bindings/wasm/photobook --target bundler --out-dir ../../../../web/packages/wasm/photobook/pkg --no-pack"
+ },
+ "dependencies": {
+ "comlink": "4.4.2",
+ "ente-utils": "*"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+}
diff --git a/web/packages/wasm/photobook/tsconfig.json b/web/packages/wasm/photobook/tsconfig.json
new file mode 100644
index 0000000000..3f3b6cd165
--- /dev/null
+++ b/web/packages/wasm/photobook/tsconfig.json
@@ -0,0 +1 @@
+{ "extends": "ente-build-config/tsconfig-typecheck.json", "include": ["."] }
diff --git a/web/packages/wasm/photobook/worker.ts b/web/packages/wasm/photobook/worker.ts
new file mode 100644
index 0000000000..abf2db4825
--- /dev/null
+++ b/web/packages/wasm/photobook/worker.ts
@@ -0,0 +1,38 @@
+import { expose, transfer } from "comlink";
+import { ensureArrayBufferBacked } from "ente-utils/bytes";
+import type { PdfX4Writer } from "./pkg/ente_photobook_wasm";
+
+export class PhotobookWorker {
+ private writer: PdfX4Writer | undefined;
+
+ async initialize(
+ profile: Uint8Array,
+ widthMm: number,
+ heightMm: number,
+ createdAt: number,
+ ) {
+ const { PdfX4Writer } = await import("./pkg/ente_photobook_wasm");
+ this.writer = new PdfX4Writer(
+ profile,
+ "FOGRA39",
+ widthMm,
+ heightMm,
+ createdAt,
+ );
+ }
+
+ addPage(pixels: Uint8Array, width: number, height: number) {
+ const chunk = ensureArrayBufferBacked(
+ this.writer!.addPage(pixels, width, height),
+ );
+ return transfer(chunk, [chunk.buffer]);
+ }
+
+ finish() {
+ const chunk = ensureArrayBufferBacked(this.writer!.finish());
+ this.writer = undefined;
+ return transfer(chunk, [chunk.buffer]);
+ }
+}
+
+expose(PhotobookWorker);