feat(studio): Auto layout lays the book on the designed pages

"The whole book" now lays the book on the designed templates through
autoDesignedBook, in the book's own page format and theme (a recoloured
one of its own included), its title kept and every page holding a locked
element kept; each press takes a new seed, so a second press gives another
book, one undo away as before. "This spread" lays the page on another
design than the one on screen and its neighbours, its id kept, and now
works on the cover, the summary and the countries too, so the menu offers
it wherever the auto layout knows the page. Loose gallery photos reach the
layout with the day they were taken, which it shares them out by. The
menu's two hints say what the button now does, in every language. Nothing
here places the classic summary, countries or marks any more.
This commit is contained in:
Maurice
2026-10-24 20:05:32 +02:00
parent 0879b5aecc
commit 73fdbdc0c3
30 changed files with 124 additions and 76 deletions
@@ -37,10 +37,13 @@ vi.mock('../../api/websocket', async importOriginal => ({
// The auto layout lives in @trek/shared now; the hook's call into it is watched through a partial mock.
const shared = await vi.importActual<typeof import('@trek/shared')>('@trek/shared')
const buildBook = vi.fn(shared.buildBook)
const autoDesignedBook = vi.fn(shared.autoDesignedBook)
vi.mock('@trek/shared', async importOriginal => {
const actual = await importOriginal<typeof import('@trek/shared')>()
return { ...actual, buildBook: (...args: Parameters<typeof actual.buildBook>) => buildBook(...args) }
return {
...actual,
autoDesignedBook: (...args: Parameters<typeof actual.autoDesignedBook>) => autoDesignedBook(...args),
}
})
import { useJourneyStudio } from './useJourneyStudio'
@@ -67,7 +70,7 @@ function seedJourney() {
beforeEach(() => {
seedJourney()
buildBook.mockClear()
autoDesignedBook.mockClear()
useStudioStore.setState({ doc: null, selection: [], activeSpread: 0, past: [], future: [], readOnly: false })
vi.spyOn(journeyApi, 'getBook').mockResolvedValue({ book: null } as never)
vi.spyOn(journeyApi, 'saveBook').mockResolvedValue({} as never)
@@ -140,8 +143,8 @@ describe('the auto layout input', () => {
act(() => { result.current.relayoutBook() })
expect(buildBook).toHaveBeenCalled()
const input = buildBook.mock.calls[buildBook.mock.calls.length - 1][0]
expect(autoDesignedBook).toHaveBeenCalled()
const input = autoDesignedBook.mock.calls[autoDesignedBook.mock.calls.length - 1][1]
expect(input.path).toEqual([TRACK])
})
@@ -176,9 +179,51 @@ describe('the auto layout input', () => {
act(() => { result.current.relayoutBook() })
const input = buildBook.mock.calls[buildBook.mock.calls.length - 1][0]
const input = autoDesignedBook.mock.calls[autoDesignedBook.mock.calls.length - 1][1]
expect(input.path).toEqual([])
})
it("lays the whole book on the designed pages in the book's own page format, theme and title", async () => {
const { result } = await mountStudio()
const theme = shared.bookThemeOf('midnight')
const page = { ...shared.bookPageSetupSchema.parse({}), pageWidth: 200 }
act(() => {
useStudioStore.getState().commit(d => ({ ...d, title: 'My own title', page, theme }))
})
act(() => { result.current.relayoutBook() })
const [doc, input, opts] = autoDesignedBook.mock.calls[autoDesignedBook.mock.calls.length - 1]
expect(input.page).toEqual(page)
expect(opts?.theme).toEqual(theme)
expect(doc?.title).toBe('My own title')
const laid = useStudioStore.getState().doc
expect(laid?.title).toBe('My own title')
expect(laid?.theme).toEqual(theme)
expect(laid?.page.pageWidth).toBe(200)
expect(laid?.spreads.some(s => s.role === 'inner' && s.entryId === 1)).toBe(true)
})
it('lays this spread on another design, its id kept, and knows the cover but not the back', async () => {
const { result } = await mountStudio()
act(() => { result.current.relayoutBook() })
const before = useStudioStore.getState().doc
if (!before) throw new Error('a laid book')
const at = before.spreads.findIndex(s => s.role === 'inner' && s.entryId === 1)
act(() => { useStudioStore.getState().setActiveSpread(at) })
expect(result.current.canRelayoutSpread).toBe(true)
const was = shared.matchDecoratedTemplate(before.spreads[at], before.page)?.id
act(() => { result.current.relayoutCurrentSpread() })
const after = useStudioStore.getState().doc?.spreads[at]
expect(after?.id).toBe(before.spreads[at].id)
expect(shared.matchDecoratedTemplate(after as never, before.page)?.id).not.toBe(was)
act(() => { useStudioStore.getState().setActiveSpread(0) })
expect(result.current.canRelayoutSpread).toBe(true)
act(() => { useStudioStore.getState().setActiveSpread(before.spreads.length - 1) })
expect(result.current.canRelayoutSpread).toBe(false)
})
})
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router'
import type { AutoEntry, AutoInput, AutoPhoto, BookElement, BookPageNumbers, JourneyStats } from '@trek/shared'
import type { AutoDesignedInput, AutoEntry, AutoPhoto, BookElement, BookPageNumbers, JourneyStats } from '@trek/shared'
import {
autoEntriesWithStops, bookElementId as elementId, bookPageSetupSchema, bookPath, buildBook, distributeGallery,
emptyBook, layoutAroundLocks, relayoutSpread,
autoDesignedBook, autoEntriesWithStops, autoRelayoutKind, autoRelayoutSpread, bookElementId as elementId,
bookPageSetupSchema, bookPath, emptyBook,
} from '@trek/shared'
import { journeyApi } from '../../api/client'
import { useJourneyStore, type GalleryPhoto, type JourneyEntry, type JourneyPhoto } from '../../store/journeyStore'
@@ -153,7 +153,7 @@ export function useJourneyStudio() {
* possible; rebuilding it from the journey on every click would be the same
* work plus a chance of the two disagreeing.
*/
const autoInput = useRef<AutoInput | null>(null)
const autoInput = useRef<AutoDesignedInput | null>(null)
const journey = current && current.id === journeyId ? current : null
@@ -274,15 +274,15 @@ export function useJourneyStudio() {
})),
}))
// When each loose photo was taken: the auto layout gives it to the entry of its day first.
const gallery: AutoPhoto[] = (journey.gallery || []).map((p: GalleryPhoto) => ({
photoId: p.photo_id,
width: p.width ?? null,
height: p.height ?? null,
caption: p.caption ?? null,
takenAt: p.taken_at ?? null,
}))
const withPhotos = distributeGallery(entries, gallery)
/*
* Give every entry what the journey's figures know about its stop: the
* coordinates and country its place resolved to and which day it is, so a
@@ -290,7 +290,7 @@ export function useJourneyStudio() {
* is shared (autoEntriesWithStops) so the server's design tool reads the
* same stops.
*/
const placed = autoEntriesWithStops(withPhotos, stats)
const placed = autoEntriesWithStops(entries, stats)
const preset = PAGE_PRESETS['square-210']
@@ -300,6 +300,8 @@ export function useJourneyStudio() {
subtitle: journey.subtitle ?? null,
coverPhotoId: gallery[0]?.photoId ?? null,
entries: placed,
// The loose photos stay loose here: the layout shares them out itself, by day, and loses none.
gallery,
page: {
preset: preset.id,
pageWidth: preset.pageWidthMm,
@@ -375,7 +377,7 @@ export function useJourneyStudio() {
*
* The build effect runs as soon as the book and the figures are in, which is
* usually before this answers, and what it froze is what the Auto layout
* buttons hand to buildBook afterwards. Without the patch a relayout drew
* buttons hand to the layout afterwards. Without the patch a relayout drew
* the straight line between stops over a route somebody had walked.
*/
const applyPath = (p: [number, number][][]) => {
@@ -471,8 +473,10 @@ export function useJourneyStudio() {
const relayoutBook = useCallback(() => {
const input = autoInput.current
if (!input) return
// A new seed every press: "the whole book" twice gives two books, each one undo away.
const seed = Date.now() % 2 ** 31
commit(d => ({
...buildBook({ ...input, page: d.page }),
...autoDesignedBook(d, { ...input, page: d.page }, { theme: d.theme, seed }),
title: d.title,
}))
setActiveSpread(0)
@@ -481,22 +485,20 @@ export function useJourneyStudio() {
const relayoutCurrentSpread = useCallback(() => {
const input = autoInput.current
if (!input) return
const seed = Date.now() % 2 ** 31
commit(d => {
const sp = d.spreads[activeSpread]
if (!sp) return d
// Laid out around what is locked, as the assistant's auto layout leaves it.
const next = layoutAroundLocks(sp, free => relayoutSpread(free, { ...input, page: d.page }))
// Laid out around what is locked, its id kept, on another template than the one on screen.
const next = autoRelayoutSpread(d, activeSpread, { ...input, page: d.page }, { seed })
if (!next) return d
return { ...d, spreads: d.spreads.map((x, i) => (i === activeSpread ? next : x)) }
})
select([])
}, [commit, activeSpread, select])
/** Whether the spread on screen came from an entry, and so can be redone. */
/** Whether the auto layout knows the spread on screen (an entry's page, the cover, the summary, the countries). */
const canRelayoutSpread = !!(
autoInput.current
&& doc?.spreads[activeSpread]?.entryId != null
&& doc.spreads[activeSpread].role === 'inner'
&& autoRelayoutKind(doc?.spreads[activeSpread]) !== null
)
/** Page numbers and anything else that belongs to the book rather than a page. */