Skip to content

armgit / ente

Public Imported from GitHub
0

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

[photobook][web] Improve large-book performance and page layouts (#14348)

Anand926b867aa5fb
diff --git a/web/apps/photobook/src/components/AppShell.tsx b/web/apps/photobook/src/components/AppShell.tsx
index 314463cde1..d2cf422b68 100644
--- a/web/apps/photobook/src/components/AppShell.tsx
+++ b/web/apps/photobook/src/components/AppShell.tsx
@@ -16,7 +16,12 @@ import ImportProgress from "./ImportProgress";
export default function AppShell() {
const mobile = useMediaQuery(MOBILE_QUERY, { noSsr: true });
- const { appView, loading, importNotice, clearImportNotice } = useBook();
+ const { appView, loading, importNotice, clearImportNotice } = useBook(
+ "appView",
+ "loading",
+ "importNotice",
+ "clearImportNotice",
+ );
const showPreview = mobile || appView === "results";
const {
importActive,
diff --git a/web/apps/photobook/src/components/BookBindingSelect.tsx b/web/apps/photobook/src/components/BookBindingSelect.tsx
index 6a9e0a6d8f..48943d155c 100644
--- a/web/apps/photobook/src/components/BookBindingSelect.tsx
+++ b/web/apps/photobook/src/components/BookBindingSelect.tsx
@@ -12,7 +12,11 @@ export default function BookBindingSelect({
}: {
disabled?: boolean;
}) {
- const { book, setBook, processingPhotos } = useBook();
+ const { book, setBook, processingPhotos } = useBook(
+ "book",
+ "setBook",
+ "processingPhotos",
+ );
const binding = getPrintBinding(book.printSelection);
return (
<Select
diff --git a/web/apps/photobook/src/components/BookBrand.tsx b/web/apps/photobook/src/components/BookBrand.tsx
index 0dab823f23..562af784af 100644
--- a/web/apps/photobook/src/components/BookBrand.tsx
+++ b/web/apps/photobook/src/components/BookBrand.tsx
@@ -2,11 +2,13 @@ import { Box, Typography } from "@mui/material";
export default function BookBrand({
showTitle = true,
+ scale = 1,
}: {
showTitle?: boolean;
+ scale?: number;
}) {
return (
- <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
+ <Box sx={{ display: "flex", alignItems: "center", gap: scale }}>
<Box
component="img"
src="/ente-branding.svg"
@@ -14,13 +16,13 @@ export default function BookBrand({
sx={{
display: "block",
height: {
- xs: showTitle ? 16 : 20,
- sm: showTitle ? 20 : 24,
+ xs: (showTitle ? 16 : 20) * scale,
+ sm: (showTitle ? 20 : 24) * scale,
},
width: "auto",
filter: "invert(1)",
"@media (max-width: 359px)": {
- height: showTitle ? 13 : 17,
+ height: (showTitle ? 13 : 17) * scale,
},
}}
/>
@@ -28,13 +30,13 @@ export default function BookBrand({
<Typography
sx={{
fontFamily: '"Gochi Hand", cursive',
- fontSize: { xs: 24, sm: 32 },
+ fontSize: { xs: 24 * scale, sm: 32 * scale },
lineHeight: 1.2,
fontWeight: 400,
color: "#F2C14E",
transform: "translateY(1px)",
whiteSpace: "nowrap",
- "@media (max-width: 359px)": { fontSize: 21 },
+ "@media (max-width: 359px)": { fontSize: 21 * scale },
}}
>
photobook
diff --git a/web/apps/photobook/src/components/BookHeader.tsx b/web/apps/photobook/src/components/BookHeader.tsx
index b37ea4e70f..5df5e65603 100644
--- a/web/apps/photobook/src/components/BookHeader.tsx
+++ b/web/apps/photobook/src/components/BookHeader.tsx
@@ -8,10 +8,12 @@ import { EDITOR_HEADER_HEIGHT } from "./editorLayout";
export default function BookHeader({
children,
showBookControls = true,
+ showBindingSelect = false,
titleDisabled = false,
}: {
children: ReactNode;
showBookControls?: boolean;
+ showBindingSelect?: boolean;
titleDisabled?: boolean;
}) {
return (
@@ -48,16 +50,18 @@ export default function BookHeader({
gap: 1,
}}
>
- <Box
- sx={{
- gridColumn: 2,
- gridRow: 2,
- justifySelf: "end",
- display: "flex",
- }}
- >
- <BookBindingSelect disabled={titleDisabled} />
- </Box>
+ {showBindingSelect && (
+ <Box
+ sx={{
+ gridColumn: 2,
+ gridRow: 2,
+ justifySelf: "end",
+ display: "flex",
+ }}
+ >
+ <BookBindingSelect disabled={titleDisabled} />
+ </Box>
+ )}
<Box
sx={{
gridColumn: 2,
diff --git a/web/apps/photobook/src/components/BookTitleInput.tsx b/web/apps/photobook/src/components/BookTitleInput.tsx
index c78161679f..9e7aa8a639 100644
--- a/web/apps/photobook/src/components/BookTitleInput.tsx
+++ b/web/apps/photobook/src/components/BookTitleInput.tsx
@@ -13,10 +13,9 @@ export default function BookTitleInput({
}) {
const compact = useMediaQuery(MOBILE_QUERY);
const [editing, setEditing] = useState(false);
- const { book, setBook } = useBook();
+ const { book, setBook } = useBook("book", "setBook");
const [title, setTitle] = useState(book.title ?? "");
const [focused, setFocused] = useState(false);
- const placeholder = focused ? "" : "Book title (on spine)";
useEffect(() => {
if (!focused) setTitle(book.title ?? "");
@@ -25,90 +24,63 @@ export default function BookTitleInput({
return (
<>
<Box
+ component="input"
+ aria-label="Photobook title"
+ value={title}
+ placeholder="Book title (on spine)"
+ autoComplete="off"
+ disabled={disabled}
+ readOnly={compact}
+ onClick={compact ? () => setEditing(true) : undefined}
+ onChange={(event) => setTitle(event.target.value)}
+ onFocus={() => {
+ if (!compact) setFocused(true);
+ }}
+ onBlur={() => {
+ setFocused(false);
+ if (title !== (book.title ?? "")) {
+ setBook((previous) => ({ ...previous, title }));
+ }
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ if (compact) setEditing(true);
+ else event.currentTarget.blur();
+ }
+ }}
sx={{
- position: "relative",
gridColumn: { xs: 1, md: 2 },
gridRow: { xs: 2, md: 1 },
justifySelf: { xs: "start", md: "center" },
- width: "max-content",
- maxWidth: { xs: "100%", md: "min(360px, 100%)" },
- minWidth: compact ? 0 : !title && !focused ? 167 : 0,
+ width: 240,
+ maxWidth: "100%",
+ minWidth: 0,
minHeight: compact ? 44 : undefined,
+ p: { xs: "8px 12px", sm: "9px 16px" },
fontFamily: "var(--font-inter), sans-serif",
fontSize: 14,
fontWeight: 600,
lineHeight: "20px",
+ 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 },
+ "&:enabled:hover": {
+ bgcolor: "#2E2E2E",
+ borderColor: "#484848",
+ },
+ "&:enabled:focus": {
+ bgcolor: "#2E2E2E",
+ borderColor: "#707070",
+ },
+ "&:disabled": { opacity: 0.45 },
}}
- >
- <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"
- disabled={disabled}
- readOnly={compact}
- onClick={compact ? () => setEditing(true) : undefined}
- onChange={(event) => setTitle(event.target.value)}
- onFocus={() => {
- if (!compact) setFocused(true);
- }}
- onBlur={() => {
- setFocused(false);
- if (title !== (book.title ?? "")) {
- setBook((previous) => ({ ...previous, title }));
- }
- }}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- if (compact) setEditing(true);
- else 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 },
- "&:enabled:hover": {
- bgcolor: "#2E2E2E",
- borderColor: "#484848",
- },
- "&:enabled:focus": {
- bgcolor: "#2E2E2E",
- borderColor: "#707070",
- },
- "&:disabled": { opacity: 0.45 },
- }}
- />
- </Box>
+ />
{editing && (
<MobileTextDialog
title="Book title (on spine)"
diff --git a/web/apps/photobook/src/components/BookViewer.tsx b/web/apps/photobook/src/components/BookViewer.tsx
index daabd89dc5..b8ef7d0e76 100644
--- a/web/apps/photobook/src/components/BookViewer.tsx
+++ b/web/apps/photobook/src/components/BookViewer.tsx
@@ -1,4 +1,5 @@
import { useBook } from "@/context/book";
+import { usePreviews } from "@/hooks/usePreviews";
import { getPrintBinding } from "@/lib/printProducts";
import { clipSoftcoverInsidePages } from "@/lib/softcoverPreview";
import {
@@ -13,6 +14,7 @@ import { Box, IconButton, useMediaQuery } from "@mui/material";
import { PageFlip } from "page-flip";
import {
forwardRef,
+ memo,
useCallback,
useEffect,
useImperativeHandle,
@@ -24,7 +26,11 @@ import {
import { createPortal } from "react-dom";
import { Layer, Stage } from "react-konva";
import BookPageNavigation from "./BookPageNavigation";
-import { SINGLE_PAGE_QUERY } from "./editorLayout";
+import {
+ LARGE_DESKTOP_QUERY,
+ MAX_DISPLAY_PAGE_SIZE,
+ SINGLE_PAGE_QUERY,
+} from "./editorLayout";
import { ChevronLeftIcon, ChevronRightIcon } from "./icons";
import PageCanvas from "./PageCanvas";
import PrinterBlankPage from "./PrinterBlankPage";
@@ -57,17 +63,15 @@ interface BookViewerProps {
const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
function BookViewer({ pages, onSpreadChange }, ref) {
const singlePage = useMediaQuery(SINGLE_PAGE_QUERY);
+ const largeDesktop = useMediaQuery(LARGE_DESKTOP_QUERY);
const swipeStart = useRef<{ x: number; y: number } | null>(null);
- const { book: bookState, photoUrls, loadPreviews } = useBook();
+ const { book: bookState } = useBook("book");
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],
+ () => getFlipPages(pages.length),
+ [pages.length],
);
+ const spreads = useMemo(() => getSpreads(pages.length), [pages.length]);
const containerRef = useRef<HTMLDivElement>(null);
const mountRef = useRef<HTMLDivElement>(null);
const pageFlipRef = useRef<PageFlip | null>(null);
@@ -79,39 +83,51 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
onSpreadChangeRef.current = onSpreadChange;
const startPageRef = useRef(0);
- const allPhotoIds = useMemo(
+ const currentSpread = flipPages[currentPage]?.spreadIndex ?? 0;
+ const renderedPages = useMemo(
+ () =>
+ flipPages
+ .map((entry, index) => ({ ...entry, index }))
+ .filter(
+ (entry) =>
+ Math.abs(entry.spreadIndex - currentSpread) <= 1,
+ ),
+ [flipPages, currentSpread],
+ );
+ const nearbyPhotoIds = useMemo(
() => [
...new Set(
- pages.flatMap((page) =>
- page.slots.flatMap((slot) =>
- slot.photoId ? [slot.photoId] : [],
- ),
+ renderedPages.flatMap(({ pageIndex }) =>
+ pageIndex === null
+ ? []
+ : pages[pageIndex]!.slots.flatMap(({ photoId }) =>
+ photoId ? [photoId] : [],
+ ),
),
),
],
- [pages],
+ [renderedPages, pages],
);
- useEffect(() => {
- if (allPhotoIds.length > 0)
- void loadPreviews(allPhotoIds).catch((error: unknown) =>
- console.error("Failed to load previews", error),
- );
- }, [allPhotoIds, loadPreviews]);
+ usePreviews(nearbyPhotoIds);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const measure = () => {
const { width, height } = container.getBoundingClientRect();
+ const availableSize = Math.min(
+ width / (singlePage ? 1 : 2),
+ Math.max(1, height - PAGE_NAVIGATION_SPACE),
+ );
+ const scale = singlePage || largeDesktop ? 1 : 0.768;
setPageSize(
Math.max(
1,
Math.floor(
Math.min(
- width / (singlePage ? 1 : 2),
- Math.max(1, height - PAGE_NAVIGATION_SPACE),
- 1200,
- ) * (singlePage ? 1 : 0.768),
+ availableSize * scale,
+ MAX_DISPLAY_PAGE_SIZE,
+ ),
),
),
);
@@ -120,7 +136,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
const observer = new ResizeObserver(measure);
observer.observe(container);
return () => observer.disconnect();
- }, [singlePage]);
+ }, [singlePage, largeDesktop]);
const showMobilePage = useCallback(
(index: number) => {
@@ -173,7 +189,6 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
getFlipPageIndex(
pages.length,
Math.min(startPageRef.current, pages.length - 1),
- binding,
) ?? 0,
);
return;
@@ -191,10 +206,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
index % 2 === 0 ? "left" : "right";
}
element.dataset.density =
- binding === "Hardcover" &&
- (index < 2 || index >= flipPages.length - 2)
- ? "hard"
- : "soft";
+ binding === "Hardcover" && index < 2 ? "hard" : "soft";
if (pageIndex === null)
element.setAttribute("aria-label", "Blank page (required)");
root.appendChild(element);
@@ -209,8 +221,8 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
size: "stretch",
minWidth: 1,
minHeight: 1,
- maxWidth: 1200,
- maxHeight: 1200,
+ maxWidth: MAX_DISPLAY_PAGE_SIZE,
+ maxHeight: MAX_DISPLAY_PAGE_SIZE,
autoSize: false,
showCover: true,
mobileScrollSupport: true,
@@ -221,7 +233,6 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
getFlipPageIndex(
pages.length,
Math.min(startPageRef.current, pages.length - 1),
- binding,
) ?? 0,
drawShadow: false,
showPageCorners: false,
@@ -251,10 +262,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
.getPage(index)
.setDensity(element.dataset.density as "hard" | "soft"),
);
- const restoreCoverDrawing =
- binding === "Softcover"
- ? clipSoftcoverInsidePages(book)
- : undefined;
+ const restoreCoverDrawing = clipSoftcoverInsidePages(book);
book.update();
startPageRef.current = requestedPage;
pageFlipRef.current = book;
@@ -272,7 +280,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
indices[0] ??
(index < flipPages.length / 2 ? 0 : pages.length - 1);
pageFlipRef.current = null;
- restoreCoverDrawing?.();
+ restoreCoverDrawing();
book.destroy();
};
}, [
@@ -372,7 +380,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
<Layer>
<PageCanvas
page={page}
- photoUrls={photoUrls}
+ preview
pageWidth={pageSize}
pageHeight={pageSize}
isFrontCover={
@@ -566,7 +574,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
/>
</Box>
</Box>
- {flipPages.map(({ pageIndex, spreadIndex }, index) => {
+ {renderedPages.map(({ pageIndex, spreadIndex, index }) => {
const element = pageElements.at(index);
const page = pageIndex === null ? null : pages[pageIndex];
if (!element || !page) return null;
@@ -579,7 +587,7 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
<Layer>
<PageCanvas
page={page}
- photoUrls={photoUrls}
+ preview
pageWidth={pageSize}
pageHeight={pageSize}
isBackCover={pageIndex === pages.length - 1}
@@ -596,4 +604,4 @@ const BookViewer = forwardRef<BookViewerHandle, BookViewerProps>(
},
);
-export default BookViewer;
+export default memo(BookViewer);
diff --git a/web/apps/photobook/src/components/EditPage.tsx b/web/apps/photobook/src/components/EditPage.tsx
index a06fb73cd5..f7b83711d5 100644
--- a/web/apps/photobook/src/components/EditPage.tsx
+++ b/web/apps/photobook/src/components/EditPage.tsx
@@ -3,6 +3,7 @@ import { useAutoScroll } from "@/hooks/useAutoScroll";
import { usePageDrag } from "@/hooks/usePageDrag";
import { usePhotoDrag } from "@/hooks/usePhotoDrag";
import { useSpreads } from "@/hooks/useSpreads";
+import { isRequiredBlankPage } from "@/lib/bookPages";
import type { PhotoDestination } from "@/lib/photoPlacement";
import { getSpreadPageIndices } from "@/lib/spreads";
import type { TextBlock } from "@/lib/types";
@@ -14,8 +15,10 @@ import {
CircularProgress,
Snackbar,
Typography,
+ useMediaQuery,
} from "@mui/material";
import React, {
+ memo,
useCallback,
useEffect,
useLayoutEffect,
@@ -39,12 +42,14 @@ import {
EDITOR_PANEL_SX,
EDITOR_SCROLLBAR_SX,
EDITOR_SIDEBAR_WIDTH,
+ LARGE_DESKTOP_QUERY,
+ MAX_DISPLAY_PAGE_SIZE,
} from "./editorLayout";
const PAGE_GAP = 2;
-const NEIGHBORHOOD_RADIUS = 4;
-export default function EditPage() {
+function EditPage() {
+ const largeDesktop = useMediaQuery(LARGE_DESKTOP_QUERY);
const {
book,
currentSpreadIndex,
@@ -58,7 +63,20 @@ export default function EditPage() {
redo,
processingPhotos,
processingProgress,
- } = useBook();
+ } = useBook(
+ "book",
+ "currentSpreadIndex",
+ "setCurrentSpreadIndex",
+ "addPage",
+ "addPhotos",
+ "removeSlot",
+ "updateTextBlock",
+ "removeTextBlock",
+ "undo",
+ "redo",
+ "processingPhotos",
+ "processingProgress",
+ );
const [selectedSlotId, setSelectedSlotId] = useState<string | null>(null);
const [selectedPageId, setSelectedPageId] = useState<string | null>(null);
@@ -96,6 +114,7 @@ export default function EditPage() {
const pages = book.pages;
const totalPages = pages.length;
+ const frontCoverId = pages[0]?.id;
const autoScroll = useAutoScroll(containerRef);
const photoDrag = usePhotoDrag(containerRef, autoScroll);
@@ -103,14 +122,6 @@ export default function EditPage() {
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]),
);
@@ -142,7 +153,7 @@ export default function EditPage() {
return next;
});
},
- { root, rootMargin: "2000px 0px" },
+ { root, rootMargin: "600px 0px" },
);
observerRef.current = observer;
@@ -154,9 +165,9 @@ export default function EditPage() {
};
}, [spreads.length]);
- const spreadRefCallback = useCallback(
- (idx: number): RefCallback<HTMLDivElement> =>
- (el) => {
+ const spreadRefs = useMemo(
+ () =>
+ spreads.map((_, idx): RefCallback<HTMLDivElement> => (el) => {
const prev = spreadElsRef.current.get(idx);
if (prev && observerRef.current)
observerRef.current.unobserve(prev);
@@ -167,8 +178,8 @@ export default function EditPage() {
} else {
spreadElsRef.current.delete(idx);
}
- },
- [],
+ }),
+ [spreads],
);
useEffect(() => {
@@ -243,10 +254,18 @@ export default function EditPage() {
EDITOR_CANVAS_PADDING * 2 -
PAGE_GAP -
PICKER_WIDTH * 2;
- const size = Math.round(Math.max(200, Math.min(availW / 2, 500)));
+ const size = Math.round(
+ Math.max(
+ 200,
+ Math.min(
+ availW / 2,
+ largeDesktop ? MAX_DISPLAY_PAGE_SIZE : 500,
+ ),
+ ),
+ );
return { pageWidth: size, pageHeight: size };
- }, [containerWidth]);
+ }, [containerWidth, largeDesktop]);
const scrollRafRef = useRef<number | null>(null);
const handleMainScroll = useCallback(() => {
@@ -346,10 +365,10 @@ export default function EditPage() {
if (!input || processingPhotos) return;
setPhotoImportError(null);
photoDestinationRef.current = pageId;
- input.multiple = !pageId || pageId !== pages[0]?.id;
+ input.multiple = !pageId || pageId !== frontCoverId;
input.click();
},
- [pages, processingPhotos],
+ [frontCoverId, processingPhotos],
);
const importPhotos = useCallback(
@@ -491,15 +510,10 @@ export default function EditPage() {
xs: "calc(144px + env(safe-area-inset-bottom))",
sm: "calc(96px + env(safe-area-inset-bottom))",
},
- gap: 3,
+ gap: 8,
}}
>
{spreads.map((spread, spreadIdx) => {
- const isVisible =
- visibleSpreads.has(spreadIdx) ||
- Math.abs(
- spreadIdx - currentSpreadRow,
- ) <= NEIGHBORHOOD_RADIUS;
const leftIndex =
typeof spread.left === "number"
? spread.left
@@ -517,10 +531,16 @@ export default function EditPage() {
? pages[rightIndex]
: null;
+ const isVisible =
+ visibleSpreads.has(spreadIdx) ||
+ (selectedPageId !== null &&
+ (lp?.id === selectedPageId ||
+ rp?.id === selectedPageId));
+
return (
<Box
key={spreadIdx}
- ref={spreadRefCallback(spreadIdx)}
+ ref={spreadRefs[spreadIdx]}
data-spread-index={spreadIdx}
sx={{
display: "flex",
@@ -561,17 +581,29 @@ export default function EditPage() {
pageWidth={pageWidth}
pageHeight={pageHeight}
totalPages={totalPages}
+ requiredBlank={isRequiredBlankPage(
+ pages,
+ lp.id,
+ )}
selectedSlotId={
- selectedSlotId
+ selectedPageId === lp.id
+ ? selectedSlotId
+ : null
}
selectedPageId={
- selectedPageId
+ selectedPageId === lp.id
+ ? selectedPageId
+ : null
}
selectedTextId={
- selectedTextId
+ selectedPageId === lp.id
+ ? selectedTextId
+ : null
}
editingTextId={
- editingTextId
+ selectedPageId === lp.id
+ ? editingTextId
+ : null
}
onSlotClick={
handleSlotClick
@@ -658,17 +690,29 @@ export default function EditPage() {
pageWidth={pageWidth}
pageHeight={pageHeight}
totalPages={totalPages}
+ requiredBlank={isRequiredBlankPage(
+ pages,
+ rp.id,
+ )}
selectedSlotId={
- selectedSlotId
+ selectedPageId === rp.id
+ ? selectedSlotId
+ : null
}
selectedPageId={
- selectedPageId
+ selectedPageId === rp.id
+ ? selectedPageId
+ : null
}
selectedTextId={
- selectedTextId
+ selectedPageId === rp.id
+ ? selectedTextId
+ : null
}
editingTextId={
- editingTextId
+ selectedPageId === rp.id
+ ? editingTextId
+ : null
}
onSlotClick={
handleSlotClick
@@ -896,3 +940,5 @@ export default function EditPage() {
</Box>
);
}
+
+export default memo(EditPage);
diff --git a/web/apps/photobook/src/components/EditorActions.tsx b/web/apps/photobook/src/components/EditorActions.tsx
index adbfe600e6..dbf05fabc3 100644
--- a/web/apps/photobook/src/components/EditorActions.tsx
+++ b/web/apps/photobook/src/components/EditorActions.tsx
@@ -42,7 +42,14 @@ export default function EditorActions({
onAddPage: () => void;
onAddPhotos: () => void;
}) {
- const { book, processingPhotos, undo, redo, canUndo, canRedo } = useBook();
+ const { book, processingPhotos, undo, redo, canUndo, canRedo } = useBook(
+ "book",
+ "processingPhotos",
+ "undo",
+ "redo",
+ "canUndo",
+ "canRedo",
+ );
return (
<Box
@@ -121,7 +128,11 @@ export default function EditorActions({
}
export function EditorPreviewButton() {
- const { book, setAppView, processingPhotos } = useBook();
+ const { book, setAppView, processingPhotos } = useBook(
+ "book",
+ "setAppView",
+ "processingPhotos",
+ );
const [validationError, setValidationError] = useState<{
title: string;
description: string;
diff --git a/web/apps/photobook/src/components/PageCanvas.tsx b/web/apps/photobook/src/components/PageCanvas.tsx
index a94e3bf935..9a22b2b604 100644
--- a/web/apps/photobook/src/components/PageCanvas.tsx
+++ b/web/apps/photobook/src/components/PageCanvas.tsx
@@ -1,9 +1,5 @@
-import { useBook } from "@/context/book";
-import {
- getCachedImage,
- getCachedUrl,
- loadImageCached,
-} from "@/lib/imageCache";
+import { useBookSelector } from "@/context/book";
+import { getCachedImage, loadImageCached } from "@/lib/imageCache";
import {
CAPTION_FONT_WEIGHT,
CAPTION_TEXT_COLOR,
@@ -19,8 +15,7 @@ import {
type CaptionLayout,
} from "@/lib/printLayout";
import type { BookPage, PhotoSlot, TextBlock } from "@/lib/types";
-import Konva from "konva";
-import { useEffect, useMemo, useState } from "react";
+import { memo, useEffect, useMemo, useState } from "react";
import { Group, Image as KonvaImage, Rect, Text } from "react-konva";
export type CaptionPosition = "top" | "bottom";
@@ -31,7 +26,7 @@ interface PageCanvasProps {
pageHeight: number;
isBackCover?: boolean;
isFrontCover?: boolean;
- photoUrls?: Map<string, string>;
+ preview?: boolean;
onSlotClick?: (slotId: string) => void;
selectedSlotId?: string | null;
selectedTextId?: string | null;
@@ -64,7 +59,7 @@ function PhotoSlotRenderer({
}) {
const photoId = slot.photoId;
const [image, setImage] = useState<HTMLImageElement | null>(() =>
- photoId ? getCachedImage(photoId) : null,
+ photoUrl ? getCachedImage(photoUrl) : null,
);
const sx = (slot.x / 100) * pageWidth;
@@ -77,28 +72,24 @@ function PhotoSlotRenderer({
setImage(null);
return;
}
- const cached = getCachedImage(photoId);
+ const cached = getCachedImage(photoUrl);
if (cached) setImage(cached);
- if (cached && getCachedUrl(photoId) === photoUrl) return;
+ if (cached) return;
let cancelled = false;
- loadImageCached(photoId, photoUrl)
+ loadImageCached(photoUrl)
.then((img) => {
if (!cancelled) setImage(img);
})
.catch(() => {
- if (!cancelled && !cached) setImage(null);
+ if (!cancelled) 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;
@@ -120,7 +111,7 @@ function PhotoSlotRenderer({
}, [image, sx, sy, sw, sh, slot.cropX, slot.cropY, slot.cropZoom]);
return (
- <Group clipFunc={clipFunc}>
+ <Group clipX={sx} clipY={sy} clipWidth={sw} clipHeight={sh}>
<Rect
x={sx}
y={sy}
@@ -346,7 +337,24 @@ function CaptionText({
);
}
-export default function PageCanvas({
+export default function PageCanvas(props: PageCanvasProps) {
+ const photoUrls = useBookSelector(
+ (state) =>
+ props.page.slots.map(({ photoId }) =>
+ photoId
+ ? (props.preview
+ ? state.photoUrls
+ : state.thumbnailUrls
+ ).get(photoId)
+ : undefined,
+ ),
+ (a, b) =>
+ a.length === b.length && a.every((url, index) => url === b[index]),
+ );
+ return <PageCanvasContent {...props} photoUrls={photoUrls} />;
+}
+
+const PageCanvasContent = memo(function PageCanvasContent({
page,
pageWidth,
pageHeight,
@@ -361,11 +369,8 @@ export default function PageCanvas({
editingCaption,
hideCaptions = false,
hideCenterText = false,
- photoUrls: photoUrlsProp,
-}: PageCanvasProps) {
- const { thumbnailUrls } = useBook();
- const urls = photoUrlsProp ?? thumbnailUrls;
-
+ photoUrls: urls,
+}: PageCanvasProps & { photoUrls: (string | undefined)[] }) {
const [, setFontsReady] = useState(false);
useEffect(() => {
let active = true;
@@ -393,13 +398,13 @@ export default function PageCanvas({
listening={false}
/>
- {page.slots.map((slot) => (
+ {page.slots.map((slot, index) => (
<PhotoSlotRenderer
key={slot.id}
slot={slot}
pageWidth={pageWidth}
pageHeight={pageHeight}
- photoUrl={slot.photoId ? urls.get(slot.photoId) : undefined}
+ photoUrl={urls[index]}
isSelected={selectedSlotId === slot.id}
isDragOver={dragOverSlotId === slot.id}
isDragSource={dragSourceSlotId === slot.id}
@@ -485,4 +490,4 @@ export default function PageCanvas({
/>
</>
);
-}
+});
diff --git a/web/apps/photobook/src/components/PageStrip.tsx b/web/apps/photobook/src/components/PageStrip.tsx
index 414e7d8d82..99c9c59280 100644
--- a/web/apps/photobook/src/components/PageStrip.tsx
+++ b/web/apps/photobook/src/components/PageStrip.tsx
@@ -4,8 +4,9 @@ import { useSpreads } from "@/hooks/useSpreads";
import { thumbnailShadow, toolbarColors, uiColors } from "@/theme/colors";
import { Box, Typography, useMediaQuery } from "@mui/material";
import {
- useCallback,
+ memo,
useEffect,
+ useMemo,
useRef,
useState,
type RefCallback,
@@ -19,8 +20,8 @@ interface PageStripProps {
onSpreadClick?: (spreadIdx: number) => void;
}
-export default function PageStrip({ onSpreadClick }: PageStripProps) {
- const { book } = useBook();
+function PageStrip({ onSpreadClick }: PageStripProps) {
+ const { book } = useBook("book");
const isCompact = useMediaQuery("(max-width: 599px)");
const thumbnailWidth = isCompact ? 52 : 136;
const rowPadding = isCompact ? 8 : 12;
@@ -75,9 +76,9 @@ export default function PageStrip({ onSpreadClick }: PageStripProps) {
};
}, [spreads.length]);
- const stripSpreadRefCallback = useCallback(
- (idx: number): RefCallback<HTMLDivElement> =>
- (el) => {
+ const stripSpreadRefs = useMemo(
+ () =>
+ spreads.map((_, idx): RefCallback<HTMLDivElement> => (el) => {
const prev = stripElsRef.current.get(idx);
if (prev && stripObserverRef.current)
stripObserverRef.current.unobserve(prev);
@@ -89,8 +90,8 @@ export default function PageStrip({ onSpreadClick }: PageStripProps) {
} else {
stripElsRef.current.delete(idx);
}
- },
- [],
+ }),
+ [spreads],
);
return (
@@ -135,7 +136,7 @@ export default function PageStrip({ onSpreadClick }: PageStripProps) {
{spreads.map((spread, spreadIdx) => (
<Box
key={spreadIdx}
- ref={stripSpreadRefCallback(spreadIdx)}
+ ref={stripSpreadRefs[spreadIdx]}
data-strip-spread-index={spreadIdx}
onClick={() => onSpreadClick?.(spreadIdx)}
sx={{
@@ -305,3 +306,5 @@ export default function PageStrip({ onSpreadClick }: PageStripProps) {
</Box>
);
}
+
+export default memo(PageStrip);
diff --git a/web/apps/photobook/src/components/PrinterBlankPage.tsx b/web/apps/photobook/src/components/PrinterBlankPage.tsx
index a7704c15cf..6b7d616359 100644
--- a/web/apps/photobook/src/components/PrinterBlankPage.tsx
+++ b/web/apps/photobook/src/components/PrinterBlankPage.tsx
@@ -30,7 +30,7 @@ export default function PrinterBlankPage({
color: uiColors.muted,
fontWeight: 600,
textAlign: "center",
- mt: 0.5,
+ mt: 1.5,
}}
>
Blank page (required)
diff --git a/web/apps/photobook/src/components/ResetBookButton.tsx b/web/apps/photobook/src/components/ResetBookButton.tsx
index 5e8caae92b..ab1d6617c7 100644
--- a/web/apps/photobook/src/components/ResetBookButton.tsx
+++ b/web/apps/photobook/src/components/ResetBookButton.tsx
@@ -19,7 +19,11 @@ export default function ResetBookButton({
}: {
disabled?: boolean;
}) {
- const { startOver, processingPhotos, book } = useBook();
+ const { startOver, processingPhotos, book } = useBook(
+ "startOver",
+ "processingPhotos",
+ "book",
+ );
const [open, setOpen] = useState(false);
const [resetting, setResetting] = useState(false);
const [error, setError] = useState<string | null>(null);
diff --git a/web/apps/photobook/src/components/ResultsPage.tsx b/web/apps/photobook/src/components/ResultsPage.tsx
index ef99118048..78e2abec3a 100644
--- a/web/apps/photobook/src/components/ResultsPage.tsx
+++ b/web/apps/photobook/src/components/ResultsPage.tsx
@@ -23,7 +23,7 @@ import {
useMediaQuery,
} from "@mui/material";
import { saveAsFileAndRevokeObjectURL } from "ente-base/utils/web";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import BookHeader from "./BookHeader";
import BookViewer, { type BookViewerHandle } from "./BookViewer";
import {
@@ -35,9 +35,14 @@ import {
import { DownloadIcon, EditIcon } from "./icons";
import ResetBookButton from "./ResetBookButton";
-export default function ResultsPage() {
+function ResultsPage() {
const mobile = useMediaQuery(MOBILE_QUERY, { noSsr: true });
- const { book, photos, setAppView, waitForEnteOriginals } = useBook();
+ const { book, photos, setAppView, waitForEnteOriginals } = useBook(
+ "book",
+ "photos",
+ "setAppView",
+ "waitForEnteOriginals",
+ );
const viewerRef = useRef<BookViewerHandle>(null);
const [spreadIndex, setSpreadIndex] = useState(0);
const [downloadPhase, setDownloadPhase] = useState<
@@ -208,7 +213,7 @@ export default function ResultsPage() {
bgcolor: uiColors.background,
}}
>
- <BookHeader titleDisabled={busy}>
+ <BookHeader showBindingSelect titleDisabled={busy}>
{mobile ? (
<ResetBookButton disabled={busy} />
) : (
@@ -435,3 +440,5 @@ export default function ResultsPage() {
</Box>
);
}
+
+export default memo(ResultsPage);
diff --git a/web/apps/photobook/src/components/SpreadPage.tsx b/web/apps/photobook/src/components/SpreadPage.tsx
index ccbc90d053..fccede01ee 100644
--- a/web/apps/photobook/src/components/SpreadPage.tsx
+++ b/web/apps/photobook/src/components/SpreadPage.tsx
@@ -1,10 +1,12 @@
import { useBook } from "@/context/book";
+import { useDragDraft } from "@/hooks/useDragDraft";
import type { DragInfo } from "@/hooks/usePhotoDrag";
-import { isRequiredBlankPage } from "@/lib/bookPages";
+import { usePreviews } from "@/hooks/usePreviews";
import {
CAPTION_FONT_WEIGHT,
CAPTION_TEXT_COLOR,
CENTER_TEXT_FONT_WEIGHT,
+ constrainTextBlock,
getCaptionLayout,
getCenterTextLayout,
getTextBlockLayout,
@@ -13,7 +15,7 @@ import {
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 React, { memo, useEffect, useMemo, useRef, useState } from "react";
import { Layer, Stage } from "react-konva";
import { AddPhotosIcon, DeleteIcon, ZoomInIcon, ZoomOutIcon } from "./icons";
import LayoutPicker from "./LayoutPicker";
@@ -41,7 +43,7 @@ function SlotControls({
pageWidth: number;
pageHeight: number;
}) {
- const { updateSlot, removeSlot } = useBook();
+ const { updateSlot, removeSlot } = useBook("updateSlot", "removeSlot");
const handleZoomIn = (e: React.MouseEvent) => {
e.stopPropagation();
@@ -64,7 +66,7 @@ function SlotControls({
const btnSize = Math.max(22, Math.min(28, pageWidth * 0.06));
const iconSize = btnSize * 0.58;
- const padding = Math.max(4, pageWidth * 0.012);
+ const padding = Math.max(4, Math.min(6, pageWidth * 0.012));
return (
<div
@@ -189,6 +191,7 @@ interface SpreadPageProps {
pageWidth: number;
pageHeight: number;
totalPages: number;
+ requiredBlank: boolean;
selectedSlotId: string | null;
selectedPageId: string | null;
selectedTextId: string | null;
@@ -233,13 +236,14 @@ interface SpreadPageProps {
onPageDragEndCleanup: () => void;
}
-export default function SpreadPage({
- page,
+function SpreadPage({
+ page: savedPage,
pageIndex,
pickerSide,
pageWidth,
pageHeight,
totalPages,
+ requiredBlank,
selectedSlotId,
selectedPageId,
selectedTextId,
@@ -270,29 +274,33 @@ export default function SpreadPage({
onPageDropOnPage,
onPageDragEndCleanup,
}: SpreadPageProps) {
+ const { draft, startDrag } = useDragDraft<BookPage>();
+ const page = draft ?? savedPage;
const {
- book,
thumbnailUrls,
- photoUrls,
- loadPreviews,
+
removePage,
setPageLayout,
updatePage,
updateSlot,
- photos,
+ getPhoto,
processingPhotos,
- } = useBook();
+ } = useBook(
+ "thumbnailUrls",
+
+ "removePage",
+ "setPageLayout",
+ "updatePage",
+ "updateSlot",
+ "getPhoto",
+ "processingPhotos",
+ );
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]);
+ usePreviews(pagePhotoIds);
const [editingCaption, setEditingCaption] =
useState<CaptionPosition | null>(null);
@@ -390,7 +398,7 @@ export default function SpreadPage({
page={page}
pageWidth={pageWidth}
pageHeight={pageHeight}
- photoUrls={photoUrls}
+ preview
isBackCover={isBackCover}
isFrontCover={isFrontCover}
selectedSlotId={
@@ -522,9 +530,7 @@ export default function SpreadPage({
canPanCrop
? (e) => {
if (e.button !== 0) return;
- const photo = photos.find(
- (p) => p.id === slot.photoId,
- );
+ const photo = getPhoto(slot.photoId!);
if (!photo) return;
e.preventDefault();
e.stopPropagation();
@@ -549,58 +555,73 @@ export default function SpreadPage({
}
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,
+ startDrag(
+ (ev) => {
+ 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;
+ return {
+ ...page,
+ slots: page.slots.map(
+ (current) =>
+ current.id ===
+ slot.id
+ ? {
+ ...current,
+ cropX: newCropX,
+ cropY: newCropY,
+ }
+ : current,
+ ),
+ };
+ },
+ (next) => {
+ const cropped =
+ next.slots.find(
+ (current) =>
+ current.id ===
+ slot.id,
+ )!;
+ if (
+ cropped.cropX !==
+ origCropX ||
+ cropped.cropY !==
+ origCropY
+ )
+ updateSlot(
+ page.id,
+ slot.id,
+ {
+ cropX: cropped.cropX,
+ cropY: cropped.cropY,
+ },
+ );
+ },
);
}
: undefined
@@ -657,37 +678,58 @@ export default function SpreadPage({
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,
+ startDrag(
+ (ev) => {
+ const dx =
+ ((ev.clientX - startX) /
+ pageWidth) *
+ 100;
+ const dy =
+ ((ev.clientY - startY) /
+ pageHeight) *
+ 100;
+ return {
+ ...page,
+ textBlocks:
+ page.textBlocks.map(
+ (current) =>
+ current.id ===
+ block.id
+ ? constrainTextBlock(
+ {
+ ...current,
+ x:
+ origX +
+ dx,
+ y:
+ origY +
+ dy,
+ },
+ )
+ : current,
+ ),
+ };
+ },
+ (next) => {
+ const moved =
+ next.textBlocks.find(
+ (current) =>
+ current.id ===
+ block.id,
+ )!;
+ if (
+ moved.x !== block.x ||
+ moved.y !== block.y
+ )
+ onTextUpdate(
+ page.id,
+ block.id,
+ {
+ x: moved.x,
+ y: moved.y,
+ },
+ );
+ },
);
}
: undefined
@@ -1083,7 +1125,7 @@ export default function SpreadPage({
color: uiColors.muted,
fontWeight: 600,
textAlign: "center",
- mt: 0.5,
+ mt: 1.5,
}}
>
{pageIndex === 0
@@ -1139,7 +1181,7 @@ export default function SpreadPage({
totalPages={totalPages}
side={pickerSide}
photoCount={photoCount}
- requiredBlank={isRequiredBlankPage(book.pages, page.id)}
+ requiredBlank={requiredBlank}
onAddPhotos={() => onAddPhotos(page.id)}
onInsert={(position) => onInsertPage(pageIndex, position)}
onDelete={() => {
@@ -1180,3 +1222,5 @@ export default function SpreadPage({
</Box>
);
}
+
+export default memo(SpreadPage);
diff --git a/web/apps/photobook/src/components/StartPage.tsx b/web/apps/photobook/src/components/StartPage.tsx
index 796a50c324..f25fca3009 100644
--- a/web/apps/photobook/src/components/StartPage.tsx
+++ b/web/apps/photobook/src/components/StartPage.tsx
@@ -10,11 +10,12 @@ import {
} from "@mui/material";
import { useRouter } from "next/router";
import { useEffect } from "react";
+import BookBrand from "./BookBrand";
import { AddPhotosIcon } from "./icons";
export default function StartPage() {
const router = useRouter();
- const { loading } = useBook();
+ const { loading } = useBook("loading");
useEffect(() => {
void router.prefetch("/app");
}, [router]);
@@ -60,14 +61,25 @@ export default function StartPage() {
position: "relative",
overflow: "hidden",
borderRadius: { xs: "20px", sm: "28px" },
- px: { xs: 2.5, sm: 4 },
- pt: { xs: 3, sm: "clamp(24px, 4vh, 48px)" },
+ px: { xs: 3.5, sm: 5 },
+ pt: { xs: 3, sm: 4 },
pb: {
xs: "max(20px, env(safe-area-inset-bottom))",
sm: "clamp(24px, 4vh, 48px)",
},
}}
>
+ <Box
+ component="header"
+ sx={{
+ alignSelf: "stretch",
+ display: "flex",
+ justifyContent: { xs: "center", sm: "flex-start" },
+ mb: { xs: 2, sm: 3 },
+ }}
+ >
+ <BookBrand scale={1.15} />
+ </Box>
{dragOver && (
<Box
sx={{
@@ -98,9 +110,10 @@ export default function StartPage() {
position: "relative",
zIndex: 10,
display: "flex",
- flex: { xs: 1, sm: "initial" },
+ flex: 1,
flexDirection: "column",
alignItems: "center",
+ justifyContent: "center",
textAlign: "center",
maxWidth: 660,
width: "100%",
@@ -325,8 +338,9 @@ export default function StartPage() {
}
sx={{
height: 53,
- color: "#FFF2CD",
- borderColor: "rgba(255,242,205,0.3)",
+ color: "rgba(255,253,245,0.9)",
+ borderColor: "rgba(255,255,255,0.35)",
+ bgcolor: "rgba(255,255,255,0.12)",
fontFamily: "var(--font-outfit), sans-serif",
fontSize: 14,
fontWeight: 500,
@@ -335,15 +349,16 @@ export default function StartPage() {
py: 0,
borderRadius: "999px",
"&:hover": {
- bgcolor: "rgba(255,242,205,0.12)",
- borderColor: "rgba(255,242,205,0.55)",
+ bgcolor: "rgba(255,255,255,0.18)",
+ borderColor: "rgba(255,255,255,0.55)",
},
"&.Mui-disabled": {
- color: "rgba(255,242,205,0.45)",
- borderColor: "rgba(255,242,205,0.2)",
+ color: "rgba(255,253,245,0.45)",
+ borderColor: "rgba(255,255,255,0.2)",
+ bgcolor: "rgba(255,255,255,0.05)",
},
"&.Mui-focusVisible": {
- outline: "3px solid #FFF2CD",
+ outline: "3px solid rgba(255,255,255,0.7)",
outlineOffset: 3,
},
}}
diff --git a/web/apps/photobook/src/components/editorLayout.ts b/web/apps/photobook/src/components/editorLayout.ts
index 0f7f7c148d..f1bea1d370 100644
--- a/web/apps/photobook/src/components/editorLayout.ts
+++ b/web/apps/photobook/src/components/editorLayout.ts
@@ -1,7 +1,10 @@
+import { BOOK_SIZE_MM } from "@/lib/bookFormats";
import { uiColors } from "@/theme/colors";
export const MOBILE_QUERY = "(max-width: 959px)";
export const SINGLE_PAGE_QUERY = "(max-width: 599px)";
+export const LARGE_DESKTOP_QUERY = "(min-width: 1920px)";
+export const MAX_DISPLAY_PAGE_SIZE = Math.floor((BOOK_SIZE_MM / 25.4) * 96);
export const EDITOR_SIDEBAR_WIDTH = { xs: 156, sm: 366 };
export const EDITOR_CANVAS_PADDING = 16;
diff --git a/web/apps/photobook/src/context/BookContext.tsx b/web/apps/photobook/src/context/BookContext.tsx
index 3053da2b9d..8b09d2085d 100644
--- a/web/apps/photobook/src/context/BookContext.tsx
+++ b/web/apps/photobook/src/context/BookContext.tsx
@@ -41,6 +41,7 @@ import {
placeImportedPhotos,
type AddPhotosOptions,
} from "@/lib/photoPlacement";
+import { PreviewCache } from "@/lib/previewCache";
import { constrainTextBlock } from "@/lib/printLayout";
import type {
AppView,
@@ -54,11 +55,12 @@ import type {
import React, {
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
-import { BookContext } from "./book";
+import { BookContext, createBookStore } from "./book";
const MAX_PHOTOS = 650;
const emptyBook: BookState = { pages: [], currentSpreadIndex: 0 };
@@ -143,6 +145,10 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
const [photos, setPhotos] = useState<Photo[]>([]);
const photosRef = useRef<Photo[]>(photos);
photosRef.current = photos;
+ const getPhoto = useCallback(
+ (id: string) => photosRef.current.find((photo) => photo.id === id),
+ [],
+ );
const [thumbnailUrls, setThumbnailUrls] = useState<Map<string, string>>(
new Map(),
);
@@ -151,8 +157,9 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
const [previewUrls, setPreviewUrls] = useState<Map<string, string>>(
new Map(),
);
- const previewUrlsRef = useRef<Map<string, string>>(previewUrls);
- previewUrlsRef.current = previewUrls;
+ const [previews] = useState(
+ () => new PreviewCache(getPreview, setPreviewUrls),
+ );
const [book, setBookRaw] = useState<BookState>(emptyBook);
const [currentSpreadIndex, setCurrentSpreadIndex] = useState(0);
const resettingRef = useRef(false);
@@ -164,9 +171,9 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
return () => {
thumbnailUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
- previewUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
+ previews.clear();
};
- }, []);
+ }, [previews]);
const undoStackRef = useRef<BookState[]>([]);
const redoStackRef = useRef<BookState[]>([]);
@@ -223,46 +230,10 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
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 retainPreviews = useCallback(
+ (photoIds: string[]) => previews.retain(photoIds),
+ [previews],
+ );
const [processingPhotos, setProcessingPhotos] = useState(false);
const [processingProgress, setProcessingProgress] = useState(0);
@@ -396,7 +367,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
try {
if (replace) {
thumbnailUrls.forEach((url) => URL.revokeObjectURL(url));
- previewUrls.forEach((url) => URL.revokeObjectURL(url));
+ previews.clear();
clearImageCache();
await clearAll();
}
@@ -405,9 +376,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
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;
@@ -422,7 +390,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
interface PhotoResult {
photo: Photo;
thumbUrl: string;
- previewUrl: string;
}
const results: (PhotoResult | null)[] = Array.from(
{ length: files.length },
@@ -462,7 +429,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
results[index] = {
photo,
thumbUrl: URL.createObjectURL(thumb),
- previewUrl: URL.createObjectURL(preview),
};
} catch (error) {
console.warn(
@@ -494,7 +460,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
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);
}
}
@@ -542,7 +507,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
: Math.max(0, book.pages.length - 1);
setPhotos(allPhotos);
setThumbnailUrls(newThumbUrls);
- setPreviewUrls(newPreviewUrls);
if (replace) {
setBookRaw({ pages: nextPages, currentSpreadIndex: 0 });
@@ -566,7 +530,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
setProcessingPhotos(false);
}
},
- [book.pages, thumbnailUrls, previewUrls, photos, setBook],
+ [book.pages, thumbnailUrls, previews, photos, setBook],
);
const markEnteOriginalDone = useCallback(
@@ -703,16 +667,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
)
)
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;
- });
+ previews.refresh(photoId, previewBlob);
markEnteOriginalDone(photoId, "ready");
} catch (e) {
const currentPhoto = photosRef.current.find(
@@ -747,7 +702,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
);
await Promise.all(workers);
},
- [markEnteOriginalDone, isResetting],
+ [markEnteOriginalDone, isResetting, previews],
);
const addEntePhotos = useCallback(
@@ -775,9 +730,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
thumbnailUrlsRef.current.forEach((url) =>
URL.revokeObjectURL(url),
);
- previewUrlsRef.current.forEach((url) =>
- URL.revokeObjectURL(url),
- );
+ previews.clear();
clearImageCache();
await clearAll();
activeEnteOriginalDownloadsRef.current.clear();
@@ -799,7 +752,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
interface ThumbResult {
photo: Photo;
thumbUrl: string;
- previewUrl: string;
}
const thumbResults: (ThumbResult | null)[] = Array.from(
{ length: limited.length },
@@ -867,7 +819,6 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
thumbResults[index] = {
photo,
thumbUrl: URL.createObjectURL(thumbBlob),
- previewUrl: URL.createObjectURL(thumbBlob),
};
} catch (e) {
console.warn(
@@ -916,16 +867,13 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
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 = [];
@@ -937,7 +885,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
setProcessingMessage("Processing your photos...");
setAppViewState("edit");
},
- [],
+ [previews],
);
const waitForEnteOriginals = useCallback(
@@ -1272,7 +1220,9 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
if (targetPhotoIds.length > 4) return prev;
const makePhotoStub = (photoId: string): Photo => {
- const photo = photos.find((p) => p.id === photoId);
+ const photo = photosRef.current.find(
+ (p) => p.id === photoId,
+ );
return (
photo || {
id: photoId,
@@ -1336,7 +1286,7 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
return { ...prev, pages: newPages };
});
},
- [photos, setBook],
+ [setBook],
);
const setPageLayout = useCallback(
@@ -1452,13 +1402,12 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
]);
await clearAll();
thumbnailUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
- previewUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
+ previews.clear();
clearImageCache();
photosRef.current = [];
setPhotos([]);
setThumbnailUrls(new Map());
- setPreviewUrls(new Map());
setBookRaw(emptyBook);
undoStackRef.current = [];
redoStackRef.current = [];
@@ -1478,54 +1427,55 @@ export function BookProvider({ children }: { children: React.ReactNode }) {
} finally {
resettingRef.current = false;
}
- }, []);
+ }, [previews]);
+
+ const value = {
+ appView,
+ setAppView,
+ loading,
+ photos,
+ getPhoto,
+ thumbnailUrls,
+ photoUrls,
+ retainPreviews,
+ 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,
+ };
+ const [store] = useState(() => createBookStore(value));
+ useLayoutEffect(() => store.update(value));
if (restoreFailed) return <RestoreErrorDialog />;
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>
+ <BookContext.Provider value={store}>{children}</BookContext.Provider>
);
}
diff --git a/web/apps/photobook/src/context/book.ts b/web/apps/photobook/src/context/book.ts
index 0e6e37ef54..780fdd0620 100644
--- a/web/apps/photobook/src/context/book.ts
+++ b/web/apps/photobook/src/context/book.ts
@@ -10,19 +10,22 @@ import type {
import {
createContext,
useContext,
+ useRef,
+ useSyncExternalStore,
type Dispatch,
type SetStateAction,
} from "react";
-interface BookContextValue {
+export interface BookContextValue {
appView: AppView;
setAppView: (view: AppView) => void;
loading: boolean;
photos: Photo[];
+ getPhoto: (id: string) => Photo | undefined;
thumbnailUrls: Map<string, string>;
photoUrls: Map<string, string>;
- loadPreviews: (photoIds: string[]) => Promise<void>;
+ retainPreviews: (photoIds: string[]) => () => void;
addPhotos: (
files: File[],
options?: AddPhotosOptions,
@@ -85,10 +88,56 @@ interface BookContextValue {
startOver: () => Promise<void>;
}
-export const BookContext = createContext<BookContextValue | null>(null);
+export function createBookStore(initial: BookContextValue) {
+ let value = initial;
+ const listeners = new Set<() => void>();
+ return {
+ getSnapshot: () => value,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ update: (next: BookContextValue) => {
+ value = next;
+ listeners.forEach((listener) => listener());
+ },
+ };
+}
+
+export const BookContext = createContext<ReturnType<
+ typeof createBookStore
+> | null>(null);
+
+export function useBookSelector<T>(
+ selector: (state: BookContextValue) => T,
+ equal: (a: T, b: T) => boolean = Object.is,
+): T {
+ const store = useContext(BookContext);
+ if (!store) throw new Error("useBook must be used within BookProvider");
+ const previous = useRef<{ value: T } | undefined>(undefined);
+ const getSnapshot = () => {
+ const selected = selector(store.getSnapshot());
+ if (previous.current && equal(previous.current.value, selected))
+ return previous.current.value;
+ previous.current = { value: selected };
+ return selected;
+ };
+ return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
+}
-export function useBook() {
- const ctx = useContext(BookContext);
- if (!ctx) throw new Error("useBook must be used within BookProvider");
- return ctx;
+export function useBook<K extends keyof BookContextValue>(
+ ...keys: [K, ...K[]]
+): Pick<BookContextValue, K> {
+ return useBookSelector(
+ (state) =>
+ Object.fromEntries(keys.map((key) => [key, state[key]])) as Pick<
+ BookContextValue,
+ K
+ >,
+ (a, b) =>
+ Object.keys(a).length === keys.length &&
+ keys.every((key) => Object.is(a[key], b[key])),
+ );
}
diff --git a/web/apps/photobook/src/hooks/useAutoScroll.ts b/web/apps/photobook/src/hooks/useAutoScroll.ts
index 2ef8d60714..bf68791615 100644
--- a/web/apps/photobook/src/hooks/useAutoScroll.ts
+++ b/web/apps/photobook/src/hooks/useAutoScroll.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
export function useAutoScroll(
containerRef: React.RefObject<HTMLElement | null>,
@@ -34,5 +34,5 @@ export function useAutoScroll(
[],
);
- return { start, stop, speed };
+ return useMemo(() => ({ start, stop, speed }), [start, stop]);
}
diff --git a/web/apps/photobook/src/hooks/useDragDraft.ts b/web/apps/photobook/src/hooks/useDragDraft.ts
new file mode 100644
index 0000000000..6efa284d01
--- /dev/null
+++ b/web/apps/photobook/src/hooks/useDragDraft.ts
@@ -0,0 +1,41 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export function useDragDraft<T>() {
+ const [draft, setDraft] = useState<T | null>(null);
+ const cleanup = useRef<(() => void) | null>(null);
+
+ useEffect(() => () => cleanup.current?.(), []);
+
+ const startDrag = useCallback(
+ (calculate: (event: MouseEvent) => T, commit: (value: T) => void) => {
+ cleanup.current?.();
+ let frame: number | null = null;
+ let latest: MouseEvent | null = null;
+ const move = (event: MouseEvent) => {
+ latest = event;
+ if (frame !== null) return;
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ setDraft(calculate(latest!));
+ });
+ };
+ const stop = () => {
+ if (frame !== null) cancelAnimationFrame(frame);
+ document.removeEventListener("mousemove", move);
+ document.removeEventListener("mouseup", finish);
+ cleanup.current = null;
+ };
+ const finish = (event: MouseEvent) => {
+ stop();
+ if (latest) commit(calculate(event));
+ setDraft(null);
+ };
+ cleanup.current = stop;
+ document.addEventListener("mousemove", move);
+ document.addEventListener("mouseup", finish);
+ },
+ [],
+ );
+
+ return { draft, startDrag };
+}
diff --git a/web/apps/photobook/src/hooks/usePageDrag.ts b/web/apps/photobook/src/hooks/usePageDrag.ts
index eeba6e5df3..be60cdb51f 100644
--- a/web/apps/photobook/src/hooks/usePageDrag.ts
+++ b/web/apps/photobook/src/hooks/usePageDrag.ts
@@ -2,7 +2,7 @@ import { useBook } from "@/context/book";
import { useCallback, useRef, useState } from "react";
export function usePageDrag() {
- const { book, reorderPages } = useBook();
+ const { book, reorderPages } = useBook("book", "reorderPages");
const pageCount = book.pages.length;
const [pageDragSource, setPageDragSource] = useState<number | null>(null);
diff --git a/web/apps/photobook/src/hooks/usePhotoDrag.ts b/web/apps/photobook/src/hooks/usePhotoDrag.ts
index b4a06f4492..7200cf26ef 100644
--- a/web/apps/photobook/src/hooks/usePhotoDrag.ts
+++ b/web/apps/photobook/src/hooks/usePhotoDrag.ts
@@ -12,8 +12,14 @@ export function usePhotoDrag(
containerRef: React.RefObject<HTMLElement | null>,
autoScroll: ReturnType<typeof useAutoScroll>,
) {
- const { thumbnailUrls, swapPhotos, movePhotoToPage, book } = useBook();
- const pages = book.pages;
+ const { thumbnailUrls, swapPhotos, movePhotoToPage, book } = useBook(
+ "thumbnailUrls",
+ "swapPhotos",
+ "movePhotoToPage",
+ "book",
+ );
+ const pagesRef = useRef(book.pages);
+ pagesRef.current = book.pages;
const [dragSourceInfo, setDragSourceInfo] = useState<DragInfo | null>(null);
const dragSourceRef = useRef<DragInfo | null>(null);
@@ -122,6 +128,7 @@ export function usePhotoDrag(
const handlePageDragOver = useCallback(
(e: React.DragEvent, pageId: string) => {
+ const pages = pagesRef.current;
e.preventDefault();
const isBackCover = pages.at(-1)?.id === pageId;
const toPage = pages.find((p) => p.id === pageId);
@@ -151,11 +158,12 @@ export function usePhotoDrag(
setDragOverPageId(null);
}
},
- [pages],
+ [],
);
const handlePageDrop = useCallback(
(e: React.DragEvent, toPageId: string) => {
+ const pages = pagesRef.current;
e.preventDefault();
autoScroll.stop();
dragOverRef.current = null;
@@ -181,7 +189,7 @@ export function usePhotoDrag(
setDragSourceInfo(null);
}
},
- [pages, movePhotoToPage, autoScroll],
+ [movePhotoToPage, autoScroll],
);
const handleDragEnd = useCallback(() => {
diff --git a/web/apps/photobook/src/hooks/usePhotoImport.ts b/web/apps/photobook/src/hooks/usePhotoImport.ts
index 53f4058d1c..dedebf88ef 100644
--- a/web/apps/photobook/src/hooks/usePhotoImport.ts
+++ b/web/apps/photobook/src/hooks/usePhotoImport.ts
@@ -31,7 +31,15 @@ function usePhotoImportSession() {
processingMessage,
setAppView,
loading,
- } = useBook();
+ } = useBook(
+ "addPhotos",
+ "addEntePhotos",
+ "processingPhotos",
+ "processingProgress",
+ "processingMessage",
+ "setAppView",
+ "loading",
+ );
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragOver, setDragOver] = useState(false);
const [importError, setImportError] = useState<string | null>(null);
diff --git a/web/apps/photobook/src/hooks/usePreviews.ts b/web/apps/photobook/src/hooks/usePreviews.ts
new file mode 100644
index 0000000000..deb4f054f9
--- /dev/null
+++ b/web/apps/photobook/src/hooks/usePreviews.ts
@@ -0,0 +1,27 @@
+import { useBook } from "@/context/book";
+import { useEffect, useRef } from "react";
+
+export function usePreviews(photoIds: string[]) {
+ const { retainPreviews } = useBook("retainPreviews");
+ const releases = useRef(new Map<string, () => void>());
+ useEffect(() => {
+ const wanted = new Set(photoIds);
+ for (const id of wanted) {
+ if (!releases.current.has(id))
+ releases.current.set(id, retainPreviews([id]));
+ }
+ for (const [id, release] of releases.current) {
+ if (!wanted.has(id)) {
+ release();
+ releases.current.delete(id);
+ }
+ }
+ }, [photoIds, retainPreviews]);
+ useEffect(() => {
+ const retained = releases.current;
+ return () => {
+ retained.forEach((release) => release());
+ retained.clear();
+ };
+ }, []);
+}
diff --git a/web/apps/photobook/src/hooks/useSpreads.ts b/web/apps/photobook/src/hooks/useSpreads.ts
index 292f0c78bd..d9a39d494c 100644
--- a/web/apps/photobook/src/hooks/useSpreads.ts
+++ b/web/apps/photobook/src/hooks/useSpreads.ts
@@ -1,10 +1,6 @@
-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]);
+ return useMemo(() => getSpreads(pageCount), [pageCount]);
}
diff --git a/web/apps/photobook/src/lib/imageCache.test.ts b/web/apps/photobook/src/lib/imageCache.test.ts
new file mode 100644
index 0000000000..d3711f9eb6
--- /dev/null
+++ b/web/apps/photobook/src/lib/imageCache.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import {
+ clearImageCache,
+ evictCachedImage,
+ getCachedImage,
+ loadImageCached,
+} from "./imageCache";
+
+class TestImage {
+ static created: TestImage[] = [];
+ naturalWidth = 1080;
+ naturalHeight = 1080;
+ onload = vi.fn<() => void>();
+ src = "";
+ constructor() {
+ TestImage.created.push(this);
+ }
+}
+
+beforeEach(() => {
+ clearImageCache();
+ TestImage.created = [];
+ vi.stubGlobal("window", { Image: TestImage });
+});
+afterEach(() => {
+ clearImageCache();
+ vi.unstubAllGlobals();
+});
+
+test("thumbnail and preview loads coexist and identical requests are deduplicated", async () => {
+ const thumbnail = loadImageCached("blob:thumbnail");
+ const preview = loadImageCached("blob:preview");
+ expect(loadImageCached("blob:preview")).toBe(preview);
+ TestImage.created.forEach((image) => image.onload());
+ expect(await thumbnail).not.toBe(await preview);
+ expect(getCachedImage("blob:thumbnail")).toBe(await thumbnail);
+ expect(getCachedImage("blob:preview")).toBe(await preview);
+});
+
+test("decoded image retention is limited by bytes and recently used images survive", async () => {
+ for (let i = 0; i < 14; i++) {
+ const load = loadImageCached(String(i));
+ TestImage.created.at(-1)!.onload();
+ await load;
+ }
+ expect(getCachedImage("0")).not.toBeNull();
+ const next = loadImageCached("14");
+ TestImage.created.at(-1)!.onload();
+ await next;
+ expect(getCachedImage("0")).not.toBeNull();
+ expect(getCachedImage("1")).toBeNull();
+});
+
+test("eviction and reset invalidate loads still in flight", async () => {
+ const first = loadImageCached("first");
+ evictCachedImage("first");
+ TestImage.created.at(-1)!.onload();
+ await first;
+ expect(getCachedImage("first")).toBeNull();
+ const second = loadImageCached("second");
+ clearImageCache();
+ TestImage.created.at(-1)!.onload();
+ await second;
+ expect(getCachedImage("second")).toBeNull();
+});
diff --git a/web/apps/photobook/src/lib/imageCache.ts b/web/apps/photobook/src/lib/imageCache.ts
index a638f5dcdd..c1aea2a54b 100644
--- a/web/apps/photobook/src/lib/imageCache.ts
+++ b/web/apps/photobook/src/lib/imageCache.ts
@@ -1,83 +1,58 @@
-const MAX_ENTRIES = 250;
+const MAX_BYTES = 64 * 1024 * 1024;
-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;
-}
+const cache = new Map<string, HTMLImageElement>();
+const pending = new Map<string, Promise<HTMLImageElement>>();
+let bytes = 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 evictCachedImage(url: string): void {
+ const image = cache.get(url);
+ if (image) {
+ bytes -= image.naturalWidth * image.naturalHeight * 4;
+ cache.delete(url);
}
+ pending.delete(url);
}
-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 getCachedImage(url: string): HTMLImageElement | null {
+ const image = cache.get(url);
+ if (!image) return null;
+ cache.delete(url);
+ cache.set(url, image);
+ return image;
}
-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;
+export function loadImageCached(url: string): Promise<HTMLImageElement> {
+ const existing = getCachedImage(url);
+ if (existing) return Promise.resolve(existing);
+ const inflight = pending.get(url);
+ if (inflight) return inflight;
const promise = new Promise<HTMLImageElement>((resolve, reject) => {
- const img = new window.Image();
- img.onload = () => {
- insert(photoId, { img, url });
- pending.delete(photoId);
- resolve(img);
+ const image = new window.Image();
+ image.decoding = "async";
+ image.onload = () => {
+ if (pending.get(url) === promise) {
+ pending.delete(url);
+ cache.set(url, image);
+ bytes += image.naturalWidth * image.naturalHeight * 4;
+ while (bytes > MAX_BYTES && cache.size > 0) {
+ evictCachedImage(cache.keys().next().value!);
+ }
+ }
+ resolve(image);
};
- img.onerror = (e) => {
- pending.delete(photoId);
- reject(new Error("Failed to load photo", { cause: e }));
+ image.onerror = (cause) => {
+ if (pending.get(url) === promise) pending.delete(url);
+ reject(new Error("Failed to load photo", { cause }));
};
- img.src = url;
+ image.src = url;
});
- pending.set(photoId, { url, promise });
+ pending.set(url, promise);
return promise;
}
export function clearImageCache(): void {
cache.clear();
pending.clear();
+ bytes = 0;
}
diff --git a/web/apps/photobook/src/lib/previewCache.test.ts b/web/apps/photobook/src/lib/previewCache.test.ts
new file mode 100644
index 0000000000..8aef01b772
--- /dev/null
+++ b/web/apps/photobook/src/lib/previewCache.test.ts
@@ -0,0 +1,104 @@
+import { afterEach, expect, test, vi } from "vitest";
+import { PreviewCache } from "./previewCache";
+
+afterEach(() => vi.restoreAllMocks());
+
+test("overlapping consumers keep one URL until the last release", async () => {
+ const create = vi
+ .spyOn(URL, "createObjectURL")
+ .mockReturnValue("blob:preview");
+ const revoke = vi
+ .spyOn(URL, "revokeObjectURL")
+ .mockImplementation(() => undefined);
+ const load = vi.fn().mockResolvedValue(new Blob(["image"]));
+ const change = vi.fn<(urls: Map<string, string>) => void>();
+ const cache = new PreviewCache(load, change);
+ const first = cache.retain(["photo", "photo"]);
+ const second = cache.retain(["photo"]);
+ await Promise.resolve();
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(create).toHaveBeenCalledTimes(1);
+ first();
+ expect(revoke).not.toHaveBeenCalled();
+ second();
+ expect(revoke).toHaveBeenCalledWith("blob:preview");
+ expect(change.mock.lastCall?.[0].size).toBe(0);
+});
+
+test("late reads cannot resurrect released or reset previews", async () => {
+ const create = vi.spyOn(URL, "createObjectURL");
+ let complete!: (blob: Blob) => void;
+ const cache = new PreviewCache(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ vi.fn(),
+ );
+ const release = cache.retain(["photo"]);
+ release();
+ complete(new Blob(["image"]));
+ await Promise.resolve();
+ expect(create).not.toHaveBeenCalled();
+ cache.retain(["other"]);
+ cache.clear();
+ complete(new Blob(["image"]));
+ await Promise.resolve();
+ expect(create).not.toHaveBeenCalled();
+});
+
+test("an original arriving during an IndexedDB read wins, and offscreen originals create no URL", async () => {
+ const create = vi
+ .spyOn(URL, "createObjectURL")
+ .mockReturnValue("blob:original");
+ vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
+ let complete!: (blob: Blob) => void;
+ const change = vi.fn<(urls: Map<string, string>) => void>();
+ const cache = new PreviewCache(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ change,
+ );
+ const release = cache.retain(["photo"]);
+ const original = new Blob(["original"]);
+ cache.refresh("photo", original);
+ complete(new Blob(["thumbnail"]));
+ await Promise.resolve();
+ cache.refresh("offscreen", original);
+ expect(create).toHaveBeenCalledTimes(1);
+ expect(create).toHaveBeenCalledWith(original);
+ expect(change.mock.lastCall?.[0].get("photo")).toBe("blob:original");
+ release();
+});
+
+test("traversing a large book keeps only the active window's URLs", async () => {
+ let id = 0;
+ const create = vi
+ .spyOn(URL, "createObjectURL")
+ .mockImplementation(() => `blob:${++id}`);
+ const revoke = vi
+ .spyOn(URL, "revokeObjectURL")
+ .mockImplementation(() => undefined);
+ let active = new Map<string, string>();
+ const cache = new PreviewCache(
+ () => Promise.resolve(new Blob(["image"])),
+ (urls) => {
+ active = urls;
+ },
+ );
+ let release: () => void = () => undefined;
+ for (let page = 0; page < 300; page++) {
+ const nextRelease = cache.retain(
+ Array.from({ length: 6 }, (_, i) => String(page + i)),
+ );
+ release();
+ release = nextRelease;
+ await Promise.resolve();
+ expect(active.size).toBe(6);
+ }
+ release();
+ expect(active.size).toBe(0);
+ expect(revoke).toHaveBeenCalledTimes(create.mock.calls.length);
+});
diff --git a/web/apps/photobook/src/lib/previewCache.ts b/web/apps/photobook/src/lib/previewCache.ts
new file mode 100644
index 0000000000..34f4835e45
--- /dev/null
+++ b/web/apps/photobook/src/lib/previewCache.ts
@@ -0,0 +1,76 @@
+import { evictCachedImage } from "./imageCache";
+
+export class PreviewCache {
+ private urls = new Map<string, string>();
+ private users = new Map<string, number>();
+ private pending = new Map<string, Promise<Blob | null>>();
+
+ constructor(
+ private load: (id: string) => Promise<Blob | null>,
+ private onChange: (urls: Map<string, string>) => void,
+ ) {}
+
+ retain(photoIds: string[]): () => void {
+ const ids = [...new Set(photoIds)];
+ for (const id of ids) {
+ this.users.set(id, (this.users.get(id) ?? 0) + 1);
+ if (this.urls.has(id) || this.pending.has(id)) continue;
+ const request = this.load(id);
+ this.pending.set(id, request);
+ void request
+ .then((blob) => {
+ if (this.pending.get(id) !== request) return;
+ this.pending.delete(id);
+ if (blob) this.refresh(id, blob);
+ })
+ .catch((error: unknown) => {
+ if (this.pending.get(id) === request)
+ this.pending.delete(id);
+ console.error("Failed to load preview", error);
+ });
+ }
+ return () => {
+ const next = new Map(this.urls);
+ for (const id of ids) {
+ const count = (this.users.get(id) ?? 0) - 1;
+ if (count > 0) {
+ this.users.set(id, count);
+ continue;
+ }
+ this.users.delete(id);
+ this.pending.delete(id);
+ const url = next.get(id);
+ if (url) {
+ this.release(url);
+ next.delete(id);
+ }
+ }
+ if (next.size !== this.urls.size) {
+ this.urls = next;
+ this.onChange(next);
+ }
+ };
+ }
+
+ refresh(id: string, blob: Blob): void {
+ this.pending.delete(id);
+ if (!this.users.has(id)) return;
+ const previous = this.urls.get(id);
+ if (previous) this.release(previous);
+ this.urls = new Map(this.urls).set(id, URL.createObjectURL(blob));
+ this.onChange(this.urls);
+ }
+
+ clear(): void {
+ this.urls.forEach((url) => this.release(url));
+ this.urls = new Map();
+ this.users.clear();
+ this.pending.clear();
+ this.onChange(this.urls);
+ }
+
+ private release(url: string): void {
+ URL.revokeObjectURL(url);
+ evictCachedImage(url);
+ }
+}
diff --git a/web/apps/photobook/src/lib/softcoverPreview.test.ts b/web/apps/photobook/src/lib/softcoverPreview.test.ts
index 68932186bc..a58a690692 100644
--- a/web/apps/photobook/src/lib/softcoverPreview.test.ts
+++ b/web/apps/photobook/src/lib/softcoverPreview.test.ts
@@ -15,6 +15,10 @@ function fixture() {
};
return {
style,
+ density: "soft",
+ getDensity() {
+ return this.density;
+ },
simpleDraw: vi.fn((orientation: number) => {
assert.ok(orientation === 0 || orientation === 1);
style.clipPath = "";
@@ -91,6 +95,26 @@ test("closing the back cover mirrors the cutout onto the right page", () => {
assert.equal(visibleAt(pages[6]!.style.clipPath, 20, 150), true);
});
+test("a hard front cover retains its drawing while the back cover uses the soft fold cutout", () => {
+ const { book, pages, state } = fixture();
+ pages[0]!.density = "hard";
+ pages[1]!.density = "hard";
+ const frontDraw = pages[1]!.simpleDraw;
+ const backDraw = pages[6]!.simpleDraw;
+ const restore = clipSoftcoverInsidePages(book);
+ assert.equal(pages[1]!.simpleDraw, frontDraw);
+ pages[1]!.simpleDraw(0);
+ assert.equal(pages[1]!.style.clipPath, "");
+ state.index = 5;
+ state.direction = 0;
+ pages[6]!.simpleDraw(1);
+ assert.equal(visibleAt(pages[6]!.style.clipPath, 290, 150), false);
+ assert.equal(visibleAt(pages[6]!.style.clipPath, 20, 150), true);
+ restore();
+ assert.equal(pages[1]!.simpleDraw, frontDraw);
+ assert.equal(pages[6]!.simpleDraw, backDraw);
+});
+
test("opening covers and turning interior pages retain the normal page drawing", () => {
const { book, pages, state } = fixture();
const originals = pages.map((page) => page.simpleDraw);
diff --git a/web/apps/photobook/src/lib/softcoverPreview.ts b/web/apps/photobook/src/lib/softcoverPreview.ts
index 358e2f6cf6..c064186086 100644
--- a/web/apps/photobook/src/lib/softcoverPreview.ts
+++ b/web/apps/photobook/src/lib/softcoverPreview.ts
@@ -7,38 +7,40 @@ export function clipSoftcoverInsidePages(book: PageFlip): () => void {
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;
+ ]
+ .filter(({ index }) => book.getPage(index).getDensity() === "soft")
+ .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;
+ 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 { 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);
- };
+ 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 () => {
+ 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
index 94b75251b3..4c99ea6f36 100644
--- a/web/apps/photobook/src/lib/spreads.test.ts
+++ b/web/apps/photobook/src/lib/spreads.test.ts
@@ -8,64 +8,42 @@ import {
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",
- );
+test("editor and preview use softcover page order for both cover choices", () => {
+ for (const count of [24, 100, 300]) {
+ const spreads = getSpreads(count);
+ const physical = getFlipPages(count);
+ assert.equal(
+ physical.filter((page) => page.pageIndex === null).length,
+ 2,
+ "Both cover choices show only the two softcover blanks; extra hardcover binding sheets are intentionally hidden",
+ );
+ 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(
- spreads.find((spread) => spread.left === count - 2)?.right,
- "printer-blank",
+ physical[getFlipPageIndex(count, index)!]!.pageIndex,
+ index,
);
- 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), []);
+ 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("content starts on the right and the last even content page faces a printer blank", () => {
- assert.deepEqual(getSpreads(6, "Softcover"), [
+ assert.deepEqual(getSpreads(6), [
{ left: null, right: 0 },
{ left: "printer-blank", right: 1 },
{ left: 2, right: 3 },
@@ -76,7 +54,7 @@ test("content starts on the right and the last even content page faces a printer
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");
+ const spreads = getSpreads(count);
assert.deepEqual(
spreads.flatMap(getSpreadPageIndices),
Array.from({ length: count }, (_, i) => i),
@@ -97,16 +75,16 @@ test("all real pages appear exactly once in export order, with even content on t
});
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"), [
+ assert.deepEqual(getSpreads(0), []);
+ assert.deepEqual(getSpreads(1), [{ left: null, right: 0 }]);
+ assert.deepEqual(getSpreads(2), [
{ 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"), [
+ assert.deepEqual(getSpreads(5), [
{ left: null, right: 0 },
{ left: "printer-blank", right: 1 },
{ left: 2, right: 3 },
@@ -115,7 +93,7 @@ test("odd legacy page counts retain the last content page and a separate back co
});
test("flip preview includes physical blanks while keeping real book indices intact", () => {
- assert.deepEqual(getFlipPages(6, "Softcover"), [
+ assert.deepEqual(getFlipPages(6), [
{ pageIndex: 0, spreadIndex: 0 },
{ pageIndex: null, spreadIndex: 1 },
{ pageIndex: 1, spreadIndex: 1 },
@@ -126,7 +104,7 @@ test("flip preview includes physical blanks while keeping real book indices inta
{ pageIndex: 5, spreadIndex: 4 },
]);
for (const count of [0, 1, 2, 5, 6, 24, 300]) {
- const realIndices = getFlipPages(count, "Softcover").flatMap((page) =>
+ const realIndices = getFlipPages(count).flatMap((page) =>
page.pageIndex === null ? [] : [page.pageIndex],
);
assert.deepEqual(
@@ -137,8 +115,8 @@ test("flip preview includes physical blanks while keeping real book indices inta
});
test("flip events and restored preview indices map both sides to the same spread", () => {
- const spreads = getSpreads(24, "Softcover");
- const preview = getFlipPages(24, "Softcover");
+ const spreads = getSpreads(24);
+ const preview = getFlipPages(24);
for (let spreadIndex = 0; spreadIndex < spreads.length; spreadIndex++) {
const physicalStart = spreadIndex === 0 ? 0 : 2 * spreadIndex - 1;
const physicalIndices =
@@ -159,7 +137,7 @@ test("flip events and restored preview indices map both sides to the same spread
});
test("page labels exclude printer blanks and keep content numbering unchanged", () => {
- const spreads = getSpreads(24, "Softcover");
+ const spreads = getSpreads(24);
assert.deepEqual(
spreads.map((spread) => getSpreadLabel(spread, 24)),
[
@@ -190,24 +168,22 @@ test("page labels exclude printer blanks and keep content numbering unchanged",
test("page jumps use editor numbers rather than the inserted printer blanks", () => {
assert.deepEqual(
- Array.from({ length: 6 }, (_, index) =>
- getFlipPageIndex(6, index, "Softcover"),
- ),
+ Array.from({ length: 6 }, (_, index) => getFlipPageIndex(6, index)),
[0, 2, 3, 4, 5, 7],
);
- assert.equal(getFlipPageIndex(24, 22, "Softcover"), 23);
+ assert.equal(getFlipPageIndex(24, 22), 23);
assert.equal(
- getFlipPageIndex(24, 23, "Softcover"),
+ getFlipPageIndex(24, 23),
25,
"back cover skips the final printer blank",
);
assert.equal(
- getFlipPageIndex(5, 4, "Softcover"),
+ getFlipPageIndex(5, 4),
5,
"odd legacy books have no final printer blank",
);
- assert.equal(getFlipPageIndex(1, 0, "Softcover"), 0);
+ assert.equal(getFlipPageIndex(1, 0), 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);
+ assert.equal(getFlipPageIndex(6, index), null);
+ assert.equal(getFlipPageIndex(0, 0), null);
});
diff --git a/web/apps/photobook/src/lib/spreads.ts b/web/apps/photobook/src/lib/spreads.ts
index bb9396f711..9e992212e0 100644
--- a/web/apps/photobook/src/lib/spreads.ts
+++ b/web/apps/photobook/src/lib/spreads.ts
@@ -1,5 +1,3 @@
-import type { PrintBinding } from "./printProducts";
-
type SpreadPageRef = number | "printer-blank" | null;
export interface Spread {
@@ -7,14 +5,12 @@ export interface Spread {
right: SpreadPageRef;
}
-export function getSpreads(pageCount: number, binding: PrintBinding): Spread[] {
+export function getSpreads(pageCount: number): 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({
@@ -22,8 +18,6 @@ export function getSpreads(pageCount: number, binding: PrintBinding): Spread[] {
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 });
@@ -50,9 +44,8 @@ export function getSpreadLabel(
export function getFlipPages(
pageCount: number,
- binding: PrintBinding,
): { pageIndex: number | null; spreadIndex: number }[] {
- return getSpreads(pageCount, binding).flatMap((spread, spreadIndex) =>
+ return getSpreads(pageCount).flatMap((spread, spreadIndex) =>
[spread.left, spread.right]
.filter((page) => page !== null)
.map((page) => ({
@@ -65,11 +58,10 @@ export function getFlipPages(
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(
+ const index = getFlipPages(pageCount).findIndex(
(page) => page.pageIndex === pageIndex,
);
return index < 0 ? null : index;
diff --git a/web/apps/photobook/src/pages/app.tsx b/web/apps/photobook/src/pages/app.tsx
index 3968b1eac8..1ff72d049b 100644
--- a/web/apps/photobook/src/pages/app.tsx
+++ b/web/apps/photobook/src/pages/app.tsx
@@ -23,7 +23,7 @@ const AppShell = dynamic(() => import("@/components/AppShell"), {
export default function Home() {
const router = useRouter();
- const { book, loading } = useBook();
+ const { book, loading } = useBook("book", "loading");
const { importActive } = usePhotoImport();
const emptyBook = !loading && !importActive && book.pages.length === 0;
diff --git a/web/apps/photobook/src/pages/index.tsx b/web/apps/photobook/src/pages/index.tsx
index 38f87a76f3..c88c944b18 100644
--- a/web/apps/photobook/src/pages/index.tsx
+++ b/web/apps/photobook/src/pages/index.tsx
@@ -5,7 +5,7 @@ import { useEffect } from "react";
export default function Home() {
const router = useRouter();
- const { book, loading } = useBook();
+ const { book, loading } = useBook("book", "loading");
const hasBook = book.pages.length > 0;
useEffect(() => {