Release branch for 4.0.0.
This commit is contained in:
jubnl
2026-08-27 13:22:39 +02:00
committed by GitHub
parent e60427f813
commit 77dddd5e8a
3355 changed files with 403744 additions and 67215 deletions
@@ -0,0 +1,225 @@
import { describe, it, expect } from 'vitest'
import type { BookDocument, BookElement, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { BookSheetsView } from '../../../src/components/Studio/BookSheetsView'
/**
* The book, laid out for a press (#1973).
*
* These assertions are millimetres read back off the DOM, because millimetres
* are what the renderer maps onto the PDF. A sheet that is two millimetres out
* looks fine on screen and comes back from the printer with the picture cut in
* the wrong place.
*/
const page = (over: Record<string, unknown> = {}) =>
bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, ...over })
const photo = (id: string): BookElement => ({
id, kind: 'photo', frame: { x: 0, y: 0, w: 420, h: 210 },
rotation: 0, opacity: 1, locked: false,
photoId: 7, fit: 'cover', focalX: 0.5, focalY: 0.5,
radius: 0, filter: 'none', mask: null, frameStyle: 'none',
} as BookElement)
const spread = (role: BookSpread['role'], id: string, elements: BookElement[] = []): BookSpread => ({
id, role, background: '#ffffff', elements, parked: [], entryId: null,
})
function book(spreads: BookSpread[], over: Record<string, unknown> = {}): BookDocument {
return { version: 1, title: 'T', page: page(over), spreads } as BookDocument
}
/** The mm number off a style property, so the assertions read as measurements. */
function mm(el: HTMLElement, prop: 'width' | 'height' | 'left' | 'top'): number {
return parseFloat(el.style[prop])
}
function sheets(container: HTMLElement): HTMLElement[] {
return Array.from(container.querySelectorAll<HTMLElement>('.bx-sheet'))
}
/** The opening onto the spread — always a sheet's first child. */
const windowOf = (sheet: HTMLElement) => sheet.children[0] as HTMLElement
/** The spread behind it, positioned so the right leaf shows the right half. */
const canvasOf = (sheet: HTMLElement) => windowOf(sheet).children[0] as HTMLElement
describe('sheet geometry', () => {
it('sizes every sheet to the trim plus bleed when marks are off', () => {
const { container } = render(
<BookSheetsView doc={book([spread('cover', 'c')])} mode="pages" marks={false} />,
)
const [sheet] = sheets(container)
expect(mm(sheet, 'width')).toBe(216)
expect(mm(sheet, 'height')).toBe(216)
})
it('grows the sheet to make room for the marks', () => {
const { container } = render(
<BookSheetsView doc={book([spread('cover', 'c')])} mode="pages" marks />,
)
const [sheet] = sheets(container)
expect(mm(sheet, 'width')).toBe(224)
})
/*
* Eight hairlines, two per corner. Fewer means a corner without a mark, which
* is a corner the cutter has to guess at.
*/
it('draws two marks at each of the four corners', () => {
const { container } = render(
<BookSheetsView doc={book([spread('cover', 'c')])} mode="pages" marks />,
)
const [sheet] = sheets(container)
const hairlines = Array.from(sheet.children).filter(
c => (c as HTMLElement).style.background === 'rgb(0, 0, 0)',
)
expect(hairlines).toHaveLength(8)
})
it('draws none when they were not asked for', () => {
const { container } = render(
<BookSheetsView doc={book([spread('cover', 'c')])} mode="pages" marks={false} />,
)
const [sheet] = sheets(container)
const hairlines = Array.from(sheet.children).filter(
c => (c as HTMLElement).style.background === 'rgb(0, 0, 0)',
)
expect(hairlines).toHaveLength(0)
})
})
describe('cutting a spread', () => {
/*
* The one that decides whether a picture across the gutter survives printing:
* both leaves must be the same spread seen through openings exactly one page
* apart. Any other number and the halves do not meet.
*/
it('shifts the right-hand leaf by exactly one page width', () => {
const { container } = render(
<BookSheetsView doc={book([spread('inner', 'a', [photo('p')])])} mode="pages" marks={false} />,
)
const [left, right] = sheets(container)
// bleed - offset: 3 for the left leaf, 3 - 210 for the right.
expect(mm(canvasOf(left), 'left')).toBe(3)
expect(mm(canvasOf(right), 'left')).toBe(-207)
// Both windows hold the whole spread, not half of it.
expect(mm(canvasOf(left), 'width')).toBe(420)
expect(mm(canvasOf(right), 'width')).toBe(420)
})
it('keeps the whole spread on one sheet in spread mode', () => {
const { container } = render(
<BookSheetsView doc={book([spread('inner', 'a')])} mode="spreads" marks={false} />,
)
expect(sheets(container)).toHaveLength(1)
expect(mm(sheets(container)[0], 'width')).toBe(426)
})
/*
* A cover is one page wide and stays that way, even in a document whose other
* sheets are two. Sizing every sheet to the widest put the cover in the
* middle of a spread-sized page with white either side, which is not a cover.
*/
it('keeps a cover at its own size next to spreads', () => {
const { container } = render(
<BookSheetsView
doc={book([spread('cover', 'c'), spread('inner', 'a')])}
mode="spreads"
marks={false}
/>,
)
const [cover, inner] = sheets(container)
expect(mm(cover, 'width')).toBe(216)
expect(mm(inner, 'width')).toBe(426)
// Nothing is shifted to centre it — the window sits at the margin.
expect(mm(windowOf(cover), 'left')).toBe(0)
})
/* And says so, so the print CSS can give it a page box of its own. */
it('marks the one-page sheets for the named page rule', () => {
const { container } = render(
<BookSheetsView
doc={book([spread('cover', 'c'), spread('inner', 'a'), spread('back', 'b')])}
mode="spreads"
marks={false}
/>,
)
expect(sheets(container).map(s => s.classList.contains('is-single'))).toEqual([true, false, true])
})
it('marks every sheet single in page mode, where they all are', () => {
const { container } = render(
<BookSheetsView
doc={book([spread('cover', 'c'), spread('inner', 'a')])}
mode="pages"
marks={false}
/>,
)
expect(sheets(container).every(s => s.classList.contains('is-single'))).toBe(true)
})
})
describe('the bleed', () => {
/*
* The one that shows up as a white hairline along every edge of a finished
* book. On screen the page stops at the trim and anything past it is clipped;
* in print the part past the trim is exactly what gets cut away, so clipping
* it leaves nothing to cut into.
*/
it('lets the page run past the trim, and clips at the sheet instead', () => {
const { container } = render(
<BookSheetsView doc={book([spread('inner', 'a', [photo('p')])])} mode="pages" marks={false} />,
)
const [sheet] = sheets(container)
// The renderer does not clip.
const paper = canvasOf(sheet).children[0] as HTMLElement
expect(paper.style.overflow).toBe('visible')
// The window does, at trim plus a bleed on each side.
expect(windowOf(sheet).style.overflow).toBe('hidden')
expect(mm(windowOf(sheet), 'width')).toBe(216)
})
/* A coloured page cut with a white edge on three sides is the same defect. */
it('carries the page colour out into the bleed', () => {
const coloured = spread('inner', 'a')
coloured.background = '#123456'
const { container } = render(
<BookSheetsView doc={book([coloured])} mode="pages" marks={false} />,
)
expect(windowOf(sheets(container)[0]).style.background).toBe('rgb(18, 52, 86)')
})
})
describe('page breaks', () => {
it('breaks after every sheet but the last', () => {
const { container } = render(
<BookSheetsView
doc={book([spread('cover', 'c'), spread('inner', 'a'), spread('back', 'b')])}
mode="spreads"
marks={false}
/>,
)
const breaks = sheets(container).map(s => s.style.breakAfter)
// A break after the last sheet is the most common defect in a
// browser-printed PDF: one blank page at the end, every time.
expect(breaks).toEqual(['page', 'page', 'auto'])
})
})
describe('what the sheets are made of', () => {
/* One renderer. A second one for print is a second one to proofread. */
it('draws the document through the editor renderer, at full image size', () => {
const { container } = render(
<BookSheetsView doc={book([spread('inner', 'a', [photo('p')])])} mode="pages" marks={false} />,
)
const img = container.querySelector('img')
expect(img).not.toBeNull()
// `original`, not `thumbnail` — the print is the one place the big file is
// worth waiting for.
expect(img!.getAttribute('src')).toContain('/original')
})
})
@@ -0,0 +1,119 @@
import { describe, it, expect } from 'vitest'
import { render } from '../../helpers/render'
import { PeerCursors } from '../../../src/components/Studio/PeerCursors'
import { peerColour } from '../../../src/components/Studio/peerColour'
import { PeerBadges } from '../../../src/components/Studio/PeerBadges'
import type { PeerCursor } from '../../../src/components/Studio/useBookPresence'
/**
* Drawing the other people (#1973).
*/
const cursor = (over: Partial<PeerCursor> = {}): PeerCursor => ({
socketId: 3, userId: 2, username: 'ada', spreadIndex: 0, x: 100, y: 50, at: 0, ...over,
})
const t = (k: string) => k
describe('the pointers', () => {
/* A pointer on page 40 has no business being drawn on page 2. */
it('draws only the ones on the spread being looked at', () => {
const { container } = render(
<PeerCursors
cursors={[cursor({ socketId: 1, spreadIndex: 0 }), cursor({ socketId: 2, spreadIndex: 7 })]}
spreadIndex={0}
zoom={1}
/>,
)
expect(container.querySelectorAll('.st-peer')).toHaveLength(1)
})
it('renders nothing at all when nobody is on this spread', () => {
const { container } = render(
<PeerCursors cursors={[cursor({ spreadIndex: 3 })]} spreadIndex={0} zoom={1} />,
)
expect(container.querySelector('.st-peer')).toBeNull()
})
it('places it in the spread millimetres it was given', () => {
const { container } = render(
<PeerCursors cursors={[cursor({ x: 140, y: 80 })]} spreadIndex={0} zoom={1} />,
)
const el = container.querySelector<HTMLElement>('.st-peer')!
expect(el.style.left).toBe('140mm')
expect(el.style.top).toBe('80mm')
})
/*
* The sheet is scaled, the arrow is not: one that grew with the zoom would be
* a postage stamp at 30% and a dinner plate at 400%.
*/
it('undoes the sheet scale so the arrow stays one size', () => {
const { container } = render(
<PeerCursors cursors={[cursor()]} spreadIndex={0} zoom={0.5} />,
)
expect(container.querySelector<HTMLElement>('.st-peer')!.style.transform).toBe('scale(2)')
})
it('says whose it is', () => {
const { container } = render(<PeerCursors cursors={[cursor()]} spreadIndex={0} zoom={1} />)
expect(container.querySelector('.st-peer-name')!.textContent).toBe('ada')
})
})
describe('the colours', () => {
/* Same colour in everybody's window, and tomorrow, without storing anything. */
it('are the same for the same person, every time', () => {
expect(peerColour(7)).toBe(peerColour(7))
})
it('differ between neighbouring ids, which is the common case', () => {
expect(peerColour(1)).not.toBe(peerColour(2))
})
it('hold up for an id that is negative or enormous', () => {
expect(peerColour(-3)).toMatch(/^#[0-9a-f]{6}$/)
expect(peerColour(9_999_999)).toMatch(/^#[0-9a-f]{6}$/)
})
})
describe('the badges', () => {
it('show nothing when nobody else is here', () => {
const { container } = render(<PeerBadges peers={[]} t={t} />)
expect(container.querySelector('.st-peers')).toBeNull()
})
/*
* By person, not by socket. The presence list is keyed by socket because two
* tabs are two pointers; showing them as two people says the room is busier
* than it is.
*/
it('count one person once, however many tabs they have open', () => {
const { container } = render(
<PeerBadges
peers={[
{ socketId: 1, userId: 2, username: 'ada' },
{ socketId: 2, userId: 2, username: 'ada' },
]}
t={t}
/>,
)
expect(container.querySelectorAll('.st-peer-dot')).toHaveLength(1)
})
it('fall back to an initial when somebody has no picture', () => {
const { container } = render(
<PeerBadges peers={[{ socketId: 1, userId: 2, username: 'ada' }]} t={t} />,
)
expect(container.querySelector('.st-peer-dot')!.textContent).toBe('A')
})
it('stop at four faces and count the rest', () => {
const peers = Array.from({ length: 7 }, (_, i) => ({
socketId: i, userId: i, username: `p${i}`,
}))
const { container } = render(<PeerBadges peers={peers} t={t} />)
expect(container.querySelectorAll('.st-peer-dot')).toHaveLength(4)
expect(container.querySelector('.st-peer-more')!.textContent).toBe('+3')
})
})
@@ -0,0 +1,101 @@
import { describe, it, expect, vi } from 'vitest'
import type { BookRecord } from '@trek/shared'
import { fireEvent, render, screen } from '../../helpers/render'
import { SaveIndicator } from '../../../src/components/Studio/SaveIndicator'
/**
* The save status (#1973).
*
* Autosave without a sign of it is a promise the user has to take on faith, and
* the moment they stop doing that is the moment they close the tab to check. So
* the interesting cases here are the two that are not "fine": an error the user
* can retry, and a conflict that has to offer a real choice rather than
* announcing that one exists.
*/
const t = (k: string) => k
const current = (over: Partial<BookRecord> = {}): BookRecord => ({
id: 3, journeyId: 9, title: 'Theirs', version: 6,
updatedAt: '2026-08-19 10:00:00', updatedBy: 2,
document: { version: 1, title: 'Theirs', page: {}, spreads: [] },
...over,
} as BookRecord)
function draw(state: Parameters<typeof SaveIndicator>[0]['state'], handlers = {}) {
const props = {
state, t,
onAcceptTheirs: vi.fn(), onKeepMine: vi.fn(), onRetry: vi.fn(),
...handlers,
}
render(<SaveIndicator {...props} />)
return props
}
describe('the quiet states', () => {
/*
* Idle shows nothing at all. A status that is always there is a status people
* learn to stop reading, which is exactly the wrong habit for the one time it
* says something else.
*/
it('renders nothing while idle', () => {
const { container } = render(
<SaveIndicator
state={{ status: 'idle' }} t={t}
onAcceptTheirs={vi.fn()} onKeepMine={vi.fn()} onRetry={vi.fn()}
/>,
)
expect(container.textContent).toBe('')
})
it('says it is saving, and then that it saved', () => {
const { unmount } = render(
<SaveIndicator
state={{ status: 'saving' }} t={t}
onAcceptTheirs={vi.fn()} onKeepMine={vi.fn()} onRetry={vi.fn()}
/>,
)
expect(screen.getByText('journey.studio.saving')).toBeTruthy()
unmount()
draw({ status: 'saved', at: 0 })
expect(screen.getByText('journey.studio.saved')).toBeTruthy()
})
})
describe('an error', () => {
it('is a button, because the way out is to try again', () => {
const props = draw({ status: 'error' })
fireEvent.click(screen.getByText('journey.studio.saveFailed'))
expect(props.onRetry).toHaveBeenCalled()
})
})
describe('a conflict', () => {
/*
* There is no merge here, and pretending otherwise would be worse than saying
* so: one of these two documents is going to be the book. Both ways out are
* on screen, stated plainly.
*/
it('offers both ways out, and hands back the record it was given', () => {
const record = current()
const props = draw({ status: 'conflict', current: record })
expect(screen.getByText('journey.studio.saveConflict')).toBeTruthy()
fireEvent.click(screen.getByText('journey.studio.saveTakeTheirs'))
expect(props.onAcceptTheirs).toHaveBeenCalledWith(record)
fireEvent.click(screen.getByText('journey.studio.saveKeepMine'))
expect(props.onKeepMine).toHaveBeenCalledWith(record)
})
/*
* Announced, not just drawn. Losing an edit to someone else's save is the one
* thing here a screen-reader user must not have to notice by scanning.
*/
it('is announced rather than only drawn', () => {
draw({ status: 'conflict', current: current() })
expect(screen.getByRole('alert')).toBeTruthy()
})
})
@@ -0,0 +1,390 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { bookPageSetupSchema } from '@trek/shared'
/**
* The page renderer, with the elements added in #1973.
*
* `SpreadView` is the *only* renderer — headless Chromium runs this same
* component tree to make the PDF — so what these check is not "does the editor
* look right" but "would this print". The two questions that matter are whether
* an element draws at all, and whether it draws in millimetres.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
const frame = { x: 10, y: 20, w: 80, h: 60 }
const common = { frame, rotation: 0, opacity: 1, locked: false }
const typeset = { font: 'sans' as const, color: '#1a1a1a', accent: '#c2410c', textScale: 1, stale: false }
function spread(elements: BookElement[]): BookSpread {
return { id: 's1', role: 'inner', background: null, elements, parked: [], entryId: null }
}
function draw(elements: BookElement[], props: { print?: boolean } = {}) {
return render(<SpreadView spread={spread(elements)} page={page} {...props} />)
}
/**
* The first element on the sheet.
*
* `SpreadView` renders the sheet as one absolutely-positioned div and the
* elements inside it, so a plain `div > div` selector finds the sheet — which
* is a div inside Testing Library's own container. This walks in one more.
*/
function firstElement(container: HTMLElement): HTMLElement | null {
const sheet = container.firstElementChild
return (sheet?.firstElementChild as HTMLElement) ?? null
}
const photo = (over: Record<string, unknown> = {}): BookElement => ({
...common, id: 'p1', kind: 'photo', photoId: 42, fit: 'cover',
focalX: 0.5, focalY: 0.5, radius: 0, filter: 'none', mask: null, frameStyle: 'none',
...over,
} as BookElement)
const shape = (over: Record<string, unknown> = {}): BookElement => ({
...common, id: 's1', kind: 'shape', shape: 'rect', fill: '#112233', gradient: 'none',
stroke: null, strokeWidth: 0, strokeStyle: 'solid', radius: 0,
...over,
} as BookElement)
describe('shapes', () => {
it('draws a rectangle as a box, which is what CSS is good at', () => {
const { container } = draw([shape()])
expect(container.querySelector('svg')).toBeNull()
expect(firstElement(container)!.style.width).toBe('80mm')
})
it('draws anything else as an SVG path', () => {
const { container } = draw([shape({ shape: 'heart' })])
const svg = container.querySelector('svg')
expect(svg).not.toBeNull()
expect(svg!.querySelector('path')?.getAttribute('d')).toMatch(/^M/)
})
/*
* The viewBox is in millimetres and the element is that many millimetres
* wide, so one user unit is one millimetre. That is what keeps a stroke the
* same width on every side of a non-square frame — the whole reason the path
* is scaled rather than the coordinate system.
*/
it('gives the SVG a viewBox in millimetres, matching its own size', () => {
const { container } = draw([shape({ shape: 'star-5' })])
const svg = container.querySelector('svg')!
expect(svg.getAttribute('viewBox')).toBe('0 0 80 60')
expect(svg.getAttribute('width')).toBe('80mm')
expect(svg.getAttribute('height')).toBe('60mm')
})
it('scales the path to the frame, so the drawing fills the box it was snapped to', () => {
const { container } = draw([shape({ shape: 'diamond' })])
const d = container.querySelector('path')!.getAttribute('d')!
const nums = (d.match(/-?\d*\.?\d+/g) ?? []).map(Number)
const xs = nums.filter((_, i) => i % 2 === 0)
const ys = nums.filter((_, i) => i % 2 === 1)
expect(Math.max(...xs)).toBeCloseTo(80, 1)
expect(Math.max(...ys)).toBeCloseTo(60, 1)
})
it('insets the path by half the stroke, keeping the outline inside the frame', () => {
const { container } = draw([shape({ shape: 'pentagon', stroke: '#000000', strokeWidth: 2 })])
const path = container.querySelector('path')!
expect(path.getAttribute('transform')).toBe('translate(1 1)')
expect(path.getAttribute('stroke-width')).toBe('2')
})
it('turns a dashed stroke into a dash pattern proportional to its width', () => {
const { container } = draw([shape({ shape: 'hexagon', stroke: '#000000', strokeWidth: 1, strokeStyle: 'dashed' })])
expect(container.querySelector('path')!.getAttribute('stroke-dasharray')).toBe('3 2')
})
it('gives a gear the even-odd rule so its middle is a hole', () => {
const { container } = draw([shape({ shape: 'gear', fill: '#000000' })])
expect(container.querySelector('path')!.getAttribute('fill-rule')).toBe('evenodd')
})
it('leaves a heart alone, so its subpaths do not knock holes in each other', () => {
const { container } = draw([shape({ shape: 'heart', fill: '#000000' })])
expect(container.querySelector('path')!.getAttribute('fill-rule')).toBeNull()
})
})
describe('photo frames', () => {
it('draws a plain photo without a clip path', () => {
const { container } = draw([photo()])
expect(container.querySelector('clipPath')).toBeNull()
expect(container.querySelector('img')).not.toBeNull()
})
it('cuts a masked photo with an objectBoundingBox clip, so it follows a resize', () => {
const { container } = draw([photo({ mask: 'heart' })])
const clip = container.querySelector('clipPath')!
expect(clip.getAttribute('clipPathUnits')).toBe('objectBoundingBox')
// 0..1 coordinates, not 0..100 — that is what objectBoundingBox means.
const nums = (clip.querySelector('path')!.getAttribute('d')!.match(/\d*\.?\d+/g) ?? []).map(Number)
expect(Math.max(...nums)).toBeLessThanOrEqual(1.06)
})
it('treats a rect mask as no mask at all', () => {
const { container } = draw([photo({ mask: 'rect' })])
expect(container.querySelector('clipPath')).toBeNull()
})
it('gives a Polaroid a white body and a chin thicker than its sides', () => {
const { container } = draw([photo({ frameStyle: 'polaroid' })])
const outer = firstElement(container)!
expect(outer.style.background).toContain('rgb(255, 255, 255)')
const inner = outer.querySelector('div') as HTMLElement
// 5.5% of the short side at the sides, 17% at the bottom.
expect(inner.style.top).toBe('3.3mm')
expect(inner.style.bottom).toBe('10.2mm')
})
it('gives film a dark body and sprocket holes', () => {
const { container } = draw([photo({ frameStyle: 'film' })])
const outer = firstElement(container)!
expect(outer.style.background).toContain('rgb(20, 20, 20)')
// The picture, plus the two sprocket strips.
expect(outer.querySelectorAll('div').length).toBeGreaterThan(2)
})
/*
* Two strips, each centred on its corner. Both halves matter: the panel
* preview draws two as well, and a preview that disagrees with the result
* makes the second strip look like a bug.
*/
it('tapes both top corners, each strip centred on its corner', () => {
const { container } = draw([photo({ frameStyle: 'tape' })])
const strips = [...firstElement(container)!.querySelectorAll('div')]
.filter(d => (d as HTMLElement).style.transform.includes('rotate'))
expect(strips).toHaveLength(2)
const [left, right] = strips as HTMLElement[]
// 26% of the short side wide, 7.5% tall; half of each is the offset.
expect(left.style.left).toBe('-7.8mm')
expect(left.style.top).toBe('-2.25mm')
expect(right.style.right).toBe('-7.8mm')
// Mirrored, so the pair reads as symmetric rather than as two of the same.
expect(left.style.transform).toBe('rotate(-45deg)')
expect(right.style.transform).toBe('rotate(45deg)')
})
it('applies a filter to the image rather than to the frame around it', () => {
const { container } = draw([photo({ filter: 'bw' })])
expect((container.querySelector('img') as HTMLElement).style.filter).toContain('grayscale')
})
/*
* An empty frame is an instruction to the person laying out the book. Printed,
* it would be a hatched rectangle on a page somebody paid to have bound.
*/
it('shows an empty frame while editing and prints nothing at all', () => {
const { container: editing } = draw([photo({ photoId: null })], {})
expect(firstElement(editing)).not.toBeNull()
const { container: printing } = draw([photo({ photoId: null })], { print: true })
expect(printing.querySelector('img')).toBeNull()
expect(firstElement(printing)).toBeNull()
})
})
describe('travel elements', () => {
const map = (over: Record<string, unknown> = {}): BookElement => ({
...common, ...typeset, id: 'm1', kind: 'map', style: 'minimal',
showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: ['IS'],
points: [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík' },
{ lat: 65.68, lng: -18.12, label: 'Akureyri' },
],
...over,
} as BookElement)
it('draws the route as a polyline and its stops as pins', () => {
const { container } = draw([map()])
expect(container.querySelector('polyline')).not.toBeNull()
expect(container.querySelectorAll('circle')).toHaveLength(2)
})
it('draws the country outlines under the route', () => {
const { container } = draw([map()])
// One path for Iceland; the route itself is a polyline, not a path.
expect(container.querySelectorAll('path').length).toBeGreaterThan(0)
})
it('leaves out the layers that are switched off', () => {
const { container } = draw([map({ showRoute: false, showPins: false, showLand: false })])
expect(container.querySelector('polyline')).toBeNull()
expect(container.querySelectorAll('circle')).toHaveLength(0)
})
it('labels the stops only when asked', () => {
expect(draw([map()]).container.querySelectorAll('text')).toHaveLength(0)
const { container } = draw([map({ showLabels: true })])
expect(container.textContent).toContain('Reykjavík')
})
it('survives a map with no stops and no countries rather than dividing by zero', () => {
const { container } = draw([map({ points: [], countries: [] })])
const svg = container.querySelector('svg')!
expect(svg.getAttribute('viewBox')).toBe('0 0 80 60')
expect(svg.innerHTML).not.toContain('NaN')
})
it('survives a single stop, where the bounds have no extent', () => {
const { container } = draw([map({ points: [{ lat: 64.14, lng: -21.94, label: 'one' }] })])
expect(container.querySelector('svg')!.innerHTML).not.toContain('NaN')
})
it('draws the figures with the values the document holds', () => {
const stats = {
...common, ...typeset, id: 'st1', kind: 'stats',
metrics: ['distance', 'days'], layout: 'grid', showIcons: true, units: 'metric',
values: { distance: 1_189_000, days: 14 },
} as unknown as BookElement
const { container } = draw([stats])
expect(container.textContent).toContain('1,189')
expect(container.textContent).toContain('14')
})
it('converts distance to miles without touching the stored metres', () => {
const stats = {
...common, ...typeset, id: 'st1', kind: 'stats',
metrics: ['distance'], layout: 'row', showIcons: false, units: 'imperial',
values: { distance: 1_609_344 },
} as unknown as BookElement
expect(draw([stats]).container.textContent).toContain('1,000')
})
it('names the countries and draws their silhouettes', () => {
const countries = {
...common, ...typeset, id: 'c1', kind: 'countries',
codes: ['IS', 'NO'], names: ['Iceland', 'Norway'],
layout: 'list', showOutline: true, showFlag: false, showName: true, align: 'center',
} as unknown as BookElement
const { container } = draw([countries])
expect(container.textContent).toContain('Iceland')
expect(container.textContent).toContain('Norway')
expect(container.querySelectorAll('svg').length).toBe(2)
})
/*
* The bundled boundaries do not carry every dependency and territory as its
* own feature, so some codes have no silhouette. The name still has to print
* — a country page that silently drops a country would be worse than one
* without a drawing next to it.
*/
it('still names a country whose silhouette is not bundled', () => {
const countries = {
...common, ...typeset, id: 'c1', kind: 'countries',
codes: ['FO'], names: ['Faroe Islands'],
layout: 'list', showOutline: true, showFlag: false, showName: true, align: 'center',
} as unknown as BookElement
const { container } = draw([countries])
expect(container.textContent).toContain('Faroe Islands')
expect(container.querySelectorAll('svg')).toHaveLength(0)
})
it('leaves out the outlines when they are switched off', () => {
const countries = {
...common, ...typeset, id: 'c1', kind: 'countries',
codes: ['IS'], names: ['Iceland'],
layout: 'list', showOutline: false, showFlag: false, showName: true, align: 'center',
} as unknown as BookElement
expect(draw([countries]).container.querySelectorAll('svg')).toHaveLength(0)
})
it('draws a badge with its figure and its caption', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'date', text: '13', sub: 'APRIL', code: null, style: 'stacked',
} as unknown as BookElement
const { container } = draw([badge])
expect(container.textContent).toContain('13')
expect(container.textContent).toContain('APRIL')
})
/*
* Drawn, not typed. A regional-indicator pair renders as the two letters on
* Windows, which is where most readers are — see the note in flags.ts.
*/
/*
* ── What colour a mark's words are ────────────────────────────────────
*
* A chip is a filled capsule, so its words answer to the fill rather than to
* the page. Ink on ink is the failure this prevents, and it is not a subtle
* one: a black day counter on a black chip is an empty capsule.
*/
it('sets a chip on a dark fill in paper, not in ink', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'day', text: 'DAY 1', sub: '', code: null, style: 'chip',
accent: '#111111', color: '#111111', autoColor: true,
} as unknown as BookElement
const { container } = draw([badge])
const html = container.innerHTML
expect(html).toContain('rgb(255, 255, 255)')
})
it('sets a chip on a pale fill in ink', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'day', text: 'DAY 1', sub: '', code: null, style: 'chip',
accent: '#f4efe6', color: '#ffffff', autoColor: true,
} as unknown as BookElement
expect(draw([badge]).container.innerHTML).toContain('rgb(28, 27, 25)')
})
/* Automatic is a good default and a bad cage: a chosen colour wins outright. */
it('uses the chosen colour once automatic is off, fill or no fill', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'day', text: 'DAY 1', sub: '', code: null, style: 'chip',
accent: '#111111', color: '#c81e4a', autoColor: false,
} as unknown as BookElement
// The badge's own words, not the page behind it — the paper is white here,
// so asking the whole tree would pass whatever the mark did.
const words = draw([badge]).getByText('DAY 1')
expect(words.style.color).toBe('rgb(200, 30, 74)')
})
it('draws a flag badge as geometry rather than as an emoji', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'flag', text: '', sub: 'Iceland', code: 'IS', style: 'plain',
} as unknown as BookElement
const { container } = draw([badge])
expect(container.textContent).not.toContain('\u{1F1EE}\u{1F1F8}')
// Iceland is a Nordic cross: a field, an upright, a crossbar and two inner
// bars, plus the hairline that keeps a white edge off a white page.
expect(container.querySelectorAll('svg rect')).toHaveLength(6)
expect(container.querySelector('svg')!.getAttribute('viewBox')).toBe('0 0 30 20')
})
it('falls back to the outline for a country whose flag it cannot draw exactly', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'flag', text: '', sub: 'United Kingdom', code: 'GB', style: 'plain',
} as unknown as BookElement
const { container } = draw([badge])
// The silhouette, not a construction: one path, no bands.
expect(container.querySelectorAll('svg rect')).toHaveLength(0)
expect(container.querySelectorAll('svg path')).toHaveLength(1)
})
it('positions every travel element in millimetres, like everything else on the page', () => {
const badge = {
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'day', text: 'DAY 1', sub: '', code: null, style: 'chip',
} as unknown as BookElement
const el = firstElement(draw([badge]).container)!
expect(el.style.left).toBe('10mm')
expect(el.style.top).toBe('20mm')
expect(el.style.width).toBe('80mm')
})
})
@@ -0,0 +1,57 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen, act } from '../../helpers/render'
import { bookPageSetupSchema, bookSpreadSchema } from '@trek/shared'
import { seedStore } from '../../helpers/store'
import { buildSettings } from '../../helpers/factories'
import { useSettingsStore } from '../../../src/store/settingsStore'
import { useStudioStore } from '../../../src/store/studioStore'
import { StudioCanvas } from '../../../src/components/Studio/StudioCanvas'
const page = bookPageSetupSchema.parse({})
const spreadWith = (locked: boolean) => bookSpreadSchema.parse({
id: 'sp-1',
elements: [{ id: 'el-1', kind: 'shape', frame: { x: 10, y: 10, w: 40, h: 30 }, locked }],
})
/** Mount, then select the one element — the chrome only exists for a selection. */
const mountSelected = (locked = false) => {
render(
<StudioCanvas spread={spreadWith(locked)} spreadIndex={0} page={page} zoom={1} pxPerMm={2}
bookView={false} dropLabel="drop" />
)
act(() => { useStudioStore.setState({ selection: ['el-1'] }) })
}
describe('StudioCanvas', () => {
beforeEach(() => {
useStudioStore.setState({ selection: [] })
})
// The quickbar and the rotation handles were the last chrome in Studio with
// English written into the JSX, so they stayed English while the panels
// around them followed the reader's language.
it('FE-COMP-STUDIOCANVAS-001: the quickbar and the rotation handles are translated', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ language: 'de' }) })
mountSelected()
// The locale bundle is fetched, so the first paint is still English.
expect(await screen.findByTitle('Duplizieren')).toBeInTheDocument()
expect(screen.getAllByTitle('Drehen')).toHaveLength(4)
expect(screen.getByTitle('Nach links drehen')).toBeInTheDocument()
expect(screen.getByTitle('Nach rechts drehen')).toBeInTheDocument()
expect(screen.getByTitle('Ganz nach vorn')).toBeInTheDocument()
expect(screen.getByTitle('Ganz nach hinten')).toBeInTheDocument()
expect(screen.getByTitle('Sperren')).toBeInTheDocument()
expect(screen.getByTitle('Löschen')).toBeInTheDocument()
expect(screen.queryByTitle('Rotate')).not.toBeInTheDocument()
})
it('FE-COMP-STUDIOCANVAS-002: the lock button names the press that follows, in the same language', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ language: 'de' }) })
mountSelected(true)
expect(await screen.findByTitle('Entsperren')).toBeInTheDocument()
// A locked element keeps its handles hidden, so nothing rotates it by accident.
expect(screen.queryByTitle('Drehen')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,143 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { BookDocument, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { fireEvent, render, screen } from '../../helpers/render'
const printed = vi.hoisted(() => vi.fn())
vi.mock('../../../src/components/Studio/printSheets', () => ({ printSheets: printed }))
import { StudioExport } from '../../../src/components/Studio/StudioExport'
/**
* The export dialog (#1973).
*
* Two questions and a button. What is worth pinning is what the button hands
* over: the sheet size the `@page` rule is built from, and markup that actually
* contains the book — a print view assembled from an empty stage is a stack of
* blank pages, and it looks fine right up until it is printed.
*/
const spread = (role: BookSpread['role'], id: string): BookSpread => ({
id, role, background: '#ffffff', elements: [], parked: [], entryId: null,
})
const doc = (spreads: BookSpread[] = [spread('cover', 'c'), spread('inner', 'a')]): BookDocument => ({
version: 1,
title: 'Iceland',
page: bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3 }),
spreads,
} as BookDocument)
const t = (key: string) => key
function open(over: Partial<Parameters<typeof StudioExport>[0]> = {}) {
const onClose = vi.fn()
render(<StudioExport doc={doc()} title="Iceland" t={t} onClose={onClose} {...over} />)
return { onClose }
}
beforeEach(() => { printed.mockReset() })
afterEach(() => { vi.useRealTimers() })
describe('the choices', () => {
it('starts on single pages, which is what a printer takes', () => {
open()
expect(screen.getByText('journey.studio.exportPages').closest('button')!.className)
.toContain('is-on')
})
it('starts with crop marks on', () => {
open()
expect(screen.getByText('journey.studio.exportMarks').closest('button')!.getAttribute('aria-pressed'))
.toBe('true')
})
it('switches to spreads when asked', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportSpreads'))
expect(screen.getByText('journey.studio.exportSpreads').closest('button')!.className)
.toContain('is-on')
expect(screen.getByText('journey.studio.exportPages').closest('button')!.className)
.not.toContain('is-on')
})
it('turns the marks off again', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportMarks'))
expect(screen.getByText('journey.studio.exportMarks').closest('button')!.getAttribute('aria-pressed'))
.toBe('false')
})
})
describe('handing over', () => {
/*
* The sheet size is the `@page` rule. Get it wrong and the printer scales the
* whole book to fit whatever it thought the paper was, which is the one defect
* that survives every proofread because it looks correct on screen.
*/
it('passes the sheet size the marks and bleed add up to', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
expect(printed).toHaveBeenCalledTimes(1)
const call = printed.mock.calls[0][0]
// 210 trim + 2 × (3 bleed + 4 marks).
expect(call.sheetWidth).toBe(224)
expect(call.sheetHeight).toBe(224)
})
it('drops the room for marks when they are off', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportMarks'))
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
expect(printed.mock.calls[0][0].sheetWidth).toBe(216)
})
it('sizes the sheet to the spread when spreads were chosen', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportSpreads'))
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
expect(printed.mock.calls[0][0].sheetWidth).toBe(420 + (3 + 4) * 2)
})
/* An empty stage prints as blank pages, and only says so on paper. */
it('hands over markup with the book in it', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
const { html } = printed.mock.calls[0][0]
expect(html).toContain('bx-sheet')
// Cover, then both leaves of the inner spread.
expect(html.match(/bx-sheet/g)).toHaveLength(3)
})
it('carries the book title into the print view', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
expect(printed.mock.calls[0][0].title).toBe('Iceland')
})
it('closes itself once the print view is up', () => {
const { onClose } = open()
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
expect(onClose).toHaveBeenCalled()
})
/* Two clicks used to mean two print views, the second hidden behind the first. */
it('opens one print view, not one per render', () => {
open()
fireEvent.click(screen.getByText('journey.studio.exportOpen'))
expect(printed).toHaveBeenCalledTimes(1)
})
})
describe('leaving', () => {
it('closes without printing anything', () => {
const { onClose } = open()
fireEvent.click(screen.getByText('common.cancel'))
expect(onClose).toHaveBeenCalled()
expect(printed).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,131 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import type { BookElement } from '@trek/shared'
import { render } from '../../helpers/render'
import { TravelPreview } from '../../../src/components/Studio/TravelPreview'
/**
* The panel tiles (#1973).
*
* The point of these is that they are the real element at a smaller scale, not
* an icon standing in for one — four map styles are four maps, and a generic
* glyph cannot tell you which is which. So what is checked here is that the
* element genuinely renders, that its proportions survive, and that the tile
* takes its size from the element rather than from a number someone guessed.
*/
/*
* The tile measures itself, and jsdom reports every element as zero-sized. This
* gives the measured span a width the moment it is observed, which is what the
* browser does on the first frame — see useElementSize.test.ts for the same
* pattern applied to the hook itself.
*/
const OBSERVED_W = 190
class SizingResizeObserver {
constructor(private cb: ResizeObserverCallback) {}
observe(el: Element) {
Object.defineProperty(el, 'offsetWidth', { value: OBSERVED_W, configurable: true })
Object.defineProperty(el, 'offsetHeight', { value: 60, configurable: true })
this.cb([], this as unknown as ResizeObserver)
}
unobserve() {}
disconnect() {}
}
beforeEach(() => {
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
get() { return OBSERVED_W },
configurable: true,
})
vi.stubGlobal('ResizeObserver', SizingResizeObserver)
})
afterEach(() => {
vi.unstubAllGlobals()
})
const typeset = { font: 'sans' as const, color: '#1a1a1a', accent: '#c2410c', textScale: 1, stale: false }
const common = { rotation: 0, opacity: 1, locked: false }
const statsEl = (w: number, h: number): BookElement => ({
...common, ...typeset, id: 'st1', kind: 'stats',
frame: { x: 40, y: 90, w, h },
metrics: ['distance', 'days'], layout: 'grid', showIcons: true, units: 'metric',
values: { distance: 1_189_000, days: 14 },
} as unknown as BookElement)
const tileHeight = (container: HTMLElement) =>
parseFloat((container.firstElementChild as HTMLElement).style.height)
describe('TravelPreview', () => {
it('draws the element itself, with its real figures', () => {
const { container } = render(<TravelPreview el={statsEl(200, 60)} />)
expect(container.textContent).toContain('1,189')
expect(container.textContent).toContain('14')
})
it('takes its height from the element, so a wide panel gets a shallow tile', () => {
const wide = render(<TravelPreview el={statsEl(200, 50)} />)
const tall = render(<TravelPreview el={statsEl(80, 120)} />)
expect(tileHeight(wide.container)).toBeLessThan(tileHeight(tall.container))
})
it('clamps a very flat element rather than drawing a hairline', () => {
const { container } = render(<TravelPreview el={statsEl(400, 8)} minHeight={30} />)
expect(tileHeight(container)).toBe(30)
})
it('clamps a very tall element rather than running down the panel', () => {
const { container } = render(<TravelPreview el={statsEl(40, 400)} maxHeight={80} />)
expect(tileHeight(container)).toBe(80)
})
/*
* The tile is the frame. An element sitting at x=40 on the spread must draw
* at the tile's own origin, or half of it would be outside the preview.
*/
it('draws at the origin, ignoring where the element sits on the spread', () => {
const { container } = render(<TravelPreview el={statsEl(200, 60)} />)
const drawn = container.querySelector('.st-travel-preview > span > div') as HTMLElement
expect(drawn.style.left).toBe('0mm')
expect(drawn.style.top).toBe('0mm')
})
it('scales rather than squashes — one factor, applied to both axes', () => {
const { container } = render(<TravelPreview el={statsEl(200, 60)} />)
const scaler = container.querySelector('.st-travel-preview > span') as HTMLElement
const m = /scale\(([\d.]+)\)/.exec(scaler.style.transform)
expect(m).not.toBeNull()
expect(Number(m![1])).toBeGreaterThan(0)
expect(Number(m![1])).toBeLessThan(1)
})
/*
* The clipped right edge that started this: the drawn element must never be
* wider than the tile it was measured against.
*/
it('never draws wider than the width it measured', () => {
const { container } = render(<TravelPreview el={statsEl(400, 60)} />)
const scaler = container.querySelector('.st-travel-preview > span') as HTMLElement
const scale = Number(/scale\(([\d.]+)\)/.exec(scaler.style.transform)![1])
const drawnPx = 400 * (96 / 25.4) * scale
expect(drawnPx).toBeLessThanOrEqual(OBSERVED_W + 0.5)
expect(parseFloat(scaler.style.left)).toBeGreaterThanOrEqual(0)
})
it('renders a map tile without a broken coordinate', () => {
const map = {
...common, ...typeset, id: 'mp1', kind: 'map',
frame: { x: 0, y: 0, w: 150, h: 120 },
style: 'paper', showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: ['IS'],
points: [
{ lat: 64.14, lng: -21.94, label: 'a' },
{ lat: 65.68, lng: -18.12, label: 'b' },
],
} as unknown as BookElement
const { container } = render(<TravelPreview el={map} />)
expect(container.querySelector('polyline')).not.toBeNull()
expect(container.querySelector('svg')!.innerHTML).not.toContain('NaN')
})
})
@@ -0,0 +1,182 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, JourneyStats } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { applyTemplate, templateFit, type TemplateEntry } from '../../../src/components/Studio/applyTemplate'
import type { SpreadTemplate } from '../../../src/components/Studio/bookTemplates.data'
/**
* Laying an entry onto a template somebody drew (#1973).
*
* The contract between the person drawing a template and the code using it is
* a division: what the entry can answer for gets filled, everything else is the
* design and is copied as drawn. These cases are that division, and the sizing
* that lets a template drawn on one trim size land on another.
*/
const page = bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210 })
const ctx = { page, locale: 'en', stats: null, dayLabel: 'DAY' }
/** Fractions of a page, the way the templates store them. */
const el = (over: Record<string, unknown>): BookElement => ({
id: 't', rotation: 0, opacity: 1, locked: false,
frame: { x: 0.1, y: 0.1, w: 0.5, h: 0.25 },
...over,
} as BookElement)
const template = (elements: BookElement[]): SpreadTemplate => ({
id: 'ref', background: '#faf8f4', elements,
})
const entry = (over: Partial<TemplateEntry> = {}): TemplateEntry => ({
id: 7, title: 'A day', story: 'What happened.', location: 'Berlin', date: '2026-07-08',
photos: [], lat: 52.52, lng: 13.4, country: 'DE', dayNumber: 3, dayCount: 10,
...over,
})
const titleEl = el({ kind: 'text', text: 'TITLE', size: 0.1, binding: { source: 'entry.title' } })
const storyEl = el({ kind: 'text', text: 'Lorem', size: 0.05, binding: { source: 'entry.story' } })
const frameEl = el({ kind: 'photo', photoId: null, fit: 'cover', focalX: 0.5, focalY: 0.5, radius: 0, filter: 'none', mask: null, frameStyle: 'none' })
const panelEl = el({ kind: 'shape', shape: 'rect', fill: '#11224f', gradient: 'none', stroke: null, strokeWidth: 0, strokeStyle: 'solid', radius: 0 })
describe('sizing', () => {
/* Drawn as fractions so a template built on a square lands on an A4 too. */
it('multiplies the frame back up to the page it is laid on', () => {
const spread = applyTemplate(template([panelEl]), entry(), ctx)
expect(spread.elements[0].frame).toEqual({ x: 21, y: 21, w: 105, h: 52.5 })
})
it('scales to a different trim size without being redrawn', () => {
const a4 = bookPageSetupSchema.parse({ preset: 'a4-landscape', pageWidth: 297, pageHeight: 210 })
const spread = applyTemplate(template([panelEl]), entry(), { ...ctx, page: a4 })
expect(spread.elements[0].frame.x).toBe(29.7)
expect(spread.elements[0].frame.w).toBe(148.5)
})
it('takes type size off the page height, so it scales with the sheet', () => {
const spread = applyTemplate(template([titleEl]), entry(), ctx)
expect((spread.elements[0] as { size: number }).size).toBe(21)
})
})
describe('what gets filled', () => {
it('puts the entry title where the template asked for one', () => {
const spread = applyTemplate(template([titleEl]), entry(), ctx)
expect((spread.elements[0] as { text: string }).text).toBe('A day')
})
it('puts the story in', () => {
const spread = applyTemplate(template([storyEl]), entry(), ctx)
expect((spread.elements[0] as { text: string }).text).toBe('What happened.')
})
it('takes the photographs in order', () => {
const photos = [
{ photoId: 11, width: null, height: null },
{ photoId: 22, width: null, height: null },
]
const spread = applyTemplate(template([frameEl, frameEl]), entry({ photos }), ctx)
expect(spread.elements.map(e => (e as { photoId: number | null }).photoId)).toEqual([11, 22])
})
it('leaves a frame empty when the entry runs out of pictures', () => {
const spread = applyTemplate(
template([frameEl, frameEl]),
entry({ photos: [{ photoId: 11, width: null, height: null }] }),
ctx,
)
expect((spread.elements[1] as { photoId: number | null }).photoId).toBeNull()
})
it('fills the day chip from the stop', () => {
const chip = el({ kind: 'badge', variant: 'day', text: 'DAY 1', sub: '', code: null, style: 'chip' })
const spread = applyTemplate(template([chip]), entry(), ctx)
expect((spread.elements[0] as { text: string }).text).toBe('DAY 3')
})
it('fills the coordinates', () => {
const mark = el({ kind: 'badge', variant: 'coords', text: '', sub: '', code: null, style: 'plain' })
const spread = applyTemplate(template([mark]), entry(), ctx)
expect((spread.elements[0] as { text: string }).text).toContain('52°')
expect((spread.elements[0] as { text: string }).text).toContain('13°')
})
/*
* A mark the entry cannot answer keeps what it was drawn with. "DAY 1" on an
* entry with no date reads as a placeholder, which is what it is.
*/
it('leaves a mark alone when the entry has nothing to put in it', () => {
const chip = el({ kind: 'badge', variant: 'day', text: 'DAY 1', sub: '', code: null, style: 'chip' })
const spread = applyTemplate(template([chip]), entry({ dayNumber: null }), ctx)
expect((spread.elements[0] as { text: string }).text).toBe('DAY 1')
})
/* Every other figure on the page follows the book language; so does this one. */
it('sets the distance in the book language', () => {
const mark = el({ kind: 'badge', variant: 'distance', text: '', sub: '', code: null, style: 'plain' })
const travelled = { distance: 1_189_000, countries: [] } as unknown as JourneyStats
const spread = applyTemplate(template([mark]), entry(), { ...ctx, locale: 'de', stats: travelled })
expect((spread.elements[0] as { text: string }).text).toBe('1.189 km')
})
it('belongs to the entry it was filled from', () => {
expect(applyTemplate(template([titleEl]), entry(), ctx).entryId).toBe(7)
})
it('keeps the paper colour the template was drawn on', () => {
expect(applyTemplate(template([panelEl]), entry(), ctx).background).toBe('#faf8f4')
})
})
describe('what is left alone', () => {
/* The design is the design: a panel stays where it was put. */
it('copies a decorative shape as drawn, colour and all', () => {
const spread = applyTemplate(template([panelEl]), entry(), ctx)
const shape = spread.elements[0] as { fill: string; kind: string }
expect(shape.kind).toBe('shape')
expect(shape.fill).toBe('#11224f')
})
it('gives every element a fresh id, so two spreads never share one', () => {
const a = applyTemplate(template([panelEl]), entry(), ctx)
const b = applyTemplate(template([panelEl]), entry(), ctx)
expect(a.elements[0].id).not.toBe(b.elements[0].id)
expect(a.id).not.toBe(b.id)
})
})
describe('choosing a template', () => {
/*
* A template is one *for an entry* when it uses one. The distinction has to
* come out of the drawing rather than a label: a summary spread of figures
* and country outlines reads perfectly well on its own, and dropping a day's
* photographs into it would be nonsense.
*/
it('refuses one that uses nothing from the entry', () => {
const summary = template([panelEl, el({ kind: 'text', text: 'SUMMARY', size: 0.1 })])
expect(templateFit(summary, entry())).toBe(-1)
})
it('refuses one that wants a story from an entry with none', () => {
expect(templateFit(template([storyEl]), entry({ story: null }))).toBe(-1)
})
/* Two empty frames on a page with one picture is a finished page with a hole. */
it('refuses one with more frames than the entry can fill', () => {
expect(templateFit(template([frameEl, frameEl, frameEl]), entry({ photos: [] }))).toBe(-1)
})
it('prefers the one whose frame count matches', () => {
const photos = [
{ photoId: 1, width: null, height: null },
{ photoId: 2, width: null, height: null },
]
const two = templateFit(template([frameEl, frameEl]), entry({ photos }))
const one = templateFit(template([frameEl]), entry({ photos }))
expect(two).toBeGreaterThan(one)
})
it('accepts more pictures than frames — the rest are parked', () => {
const photos = Array.from({ length: 5 }, (_, i) => ({ photoId: i, width: null, height: null }))
expect(templateFit(template([frameEl]), entry({ photos }))).toBeGreaterThanOrEqual(0)
})
})
@@ -0,0 +1,173 @@
import { describe, it, expect, vi } from 'vitest'
/*
* These cases are about the layouts written in autoLayout.ts, which are what an
* entry falls back on when no hand-drawn template suits it. With the real
* templates in place they would be testing whichever spread somebody last drew
* in Studio — so the set is empty here on purpose.
*/
vi.mock('../../../src/components/Studio/bookTemplates.data', () => ({ SPREAD_TEMPLATES: [] }))
import { bookPageSetupSchema, type BookSpread } from '@trek/shared'
import { buildBook, type AutoEntry, type AutoInput } from '../../../src/components/Studio/autoLayout'
/**
* A journey with little in it (#1973).
*
* A journey built from a trip starts as one skeleton entry per stop: a date, a
* place name, nothing else. Each of those used to take a spread of its own — a
* numeral on the left, a heading on the right, and two-thirds of a metre of
* empty paper. Ten stops made ten of them, and the book was a stack of blanks.
*
* They share a page now. What follows is that, and the two things it must not
* break: the order the journey happened in, and the entries that do have
* something on them.
*/
const page = bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210 })
const bare = (id: number, over: Partial<AutoEntry> = {}): AutoEntry => ({
id, title: `Stop ${id}`, story: null, location: 'Berlin', date: '2026-07-07', photos: [], ...over,
})
const rich = (id: number): AutoEntry => ({
id, title: `Day ${id}`, story: 'Something actually happened here.',
location: 'Berlin', date: '2026-07-08', photos: [],
})
function build(entries: AutoEntry[]): BookSpread[] {
const input: AutoInput = {
locale: 'en', title: 'T', subtitle: null, coverPhotoId: null,
entries, page, stats: null, stationsLabel: 'Stations', dayLabel: 'DAY', summaryLabel: 'Trip summary', countriesLabel: 'Countries',
}
return buildBook(input).spreads
}
/** The inner spreads, which is where entries land. */
const inner = (spreads: BookSpread[]) => spreads.filter(s => s.role === 'inner')
describe('entries with nothing on them', () => {
it('share one page instead of taking one each', () => {
const spreads = inner(build([bare(1), bare(2), bare(3), bare(4), bare(5)]))
expect(spreads).toHaveLength(1)
})
it('all appear on it', () => {
const spreads = inner(build([bare(1), bare(2), bare(3)]))
const words = spreads[0].elements.map(e => (e as { text?: string }).text ?? '').join(' ')
expect(words).toContain('Stop 1')
expect(words).toContain('Stop 2')
expect(words).toContain('Stop 3')
})
it('carries the heading it was given, translated by the caller', () => {
const spreads = inner(build([bare(1)]))
const words = spreads[0].elements.map(e => (e as { text?: string }).text ?? '').join(' ')
expect(words).toContain('STATIONS')
})
/* Nothing to regenerate a list from, so it is not tied to a single entry. */
it('belongs to no single entry', () => {
expect(inner(build([bare(1), bare(2)]))[0].entryId).toBeNull()
})
it('runs onto a second page when there are more than fit', () => {
const many = Array.from({ length: 30 }, (_, i) => bare(i + 1))
expect(inner(build(many))).toHaveLength(2)
})
/*
* The old behaviour, restated as the thing that must not come back: one
* spread per stop, each of them nearly empty.
*/
it('does not give ten stops ten spreads', () => {
const spreads = inner(build(Array.from({ length: 10 }, (_, i) => bare(i + 1))))
expect(spreads.length).toBeLessThan(10)
})
})
describe('mixed with real entries', () => {
it('leaves an entry with a story its own spread', () => {
const spreads = inner(build([rich(1)]))
expect(spreads).toHaveLength(1)
expect(spreads[0].entryId).toBe(1)
})
/*
* The order the journey happened in is the order the book is in. Gathering
* every bare entry at the end would be tidier and wrong.
*/
it('keeps the run where it happened, between the entries around it', () => {
const spreads = inner(build([rich(1), bare(2), bare(3), rich(4)]))
expect(spreads.map(s => s.entryId)).toEqual([1, null, 4])
})
it('starts a new list after each entry that interrupts one', () => {
const spreads = inner(build([bare(1), rich(2), bare(3)]))
expect(spreads.map(s => s.entryId)).toEqual([null, 2, null])
})
/* A photograph is substance too, even with nothing written. */
it('treats an entry with a photo as one worth a spread', () => {
const withPhoto: AutoEntry = { ...bare(1), photos: [{ photoId: 5, width: 4000, height: 3000 }] }
expect(inner(build([withPhoto]))[0].entryId).toBe(1)
})
})
describe('an entry with words but no pictures', () => {
/*
* An entry with no photographs is usually one whose photographs have not been
* added yet. The page it deserves is the one it will look like once they are,
* so the layout puts the frames in and leaves them empty — the renderer draws
* them as outlines and a dropped photo fills one.
*/
it('lays out the frames the pictures will go in', () => {
const spread = inner(build([rich(1)]))[0]
const frames = spread.elements.filter(e => e.kind === 'photo')
expect(frames.length).toBeGreaterThan(0)
expect(frames.every(f => (f as { photoId: number | null }).photoId === null)).toBe(true)
})
it('gives the frame most of a page rather than a token strip', () => {
const spread = inner(build([rich(1)]))[0]
const frame = spread.elements.find(e => e.kind === 'photo')!.frame
// A page is 210 × 210. Anything much smaller is decoration, not somewhere
// a photograph goes.
expect(frame.w).toBeGreaterThan(150)
expect(frame.h).toBeGreaterThan(150)
})
/*
* The bug this replaced: everything sat in the middle of the left page and
* the right one was empty, because the layout used half a page width where
* it meant the far page. A spread has two pages and both get used.
*/
it('uses both pages, picture on the left and words on the right', () => {
const spread = inner(build([rich(1)]))[0]
const frame = spread.elements.find(e => e.kind === 'photo')!.frame
expect(frame.x).toBeLessThan(210)
const words = spread.elements.filter(e => e.kind === 'text')
expect(words.length).toBeGreaterThan(0)
// Every line of type starts on the right-hand page.
expect(words.every(w => w.frame.x >= 210)).toBe(true)
})
it('keeps everything inside the sheet', () => {
const spread = inner(build([rich(1)]))[0]
expect(spread.elements.every(e => e.frame.x + e.frame.w <= 420 && e.frame.y + e.frame.h <= 210)).toBe(true)
})
it('still writes the story', () => {
const spread = inner(build([rich(1)]))[0]
const words = spread.elements.map(e => (e as { text?: string }).text ?? '').join(' ')
expect(words).toContain('Something actually happened here.')
})
})
describe('a journey with nothing at all', () => {
it('produces a book of a cover and a back, and no blank pages between', () => {
const spreads = build([])
expect(inner(spreads)).toHaveLength(0)
expect(spreads.map(s => s.role)).toEqual(['cover', 'back'])
})
})
@@ -0,0 +1,340 @@
import { describe, it, expect, vi } from 'vitest'
/*
* These cases are about the layouts written in autoLayout.ts, which are what an
* entry falls back on when no hand-drawn template suits it. With the real
* templates in place they would be testing whichever spread somebody last drew
* in Studio — so the set is empty here on purpose.
*/
vi.mock('../../../src/components/Studio/bookTemplates.data', () => ({ SPREAD_TEMPLATES: [] }))
import type { BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'
import { buildBook, emptyBook, type AutoEntry, type AutoInput } from '../../../src/components/Studio/autoLayout'
import { bookPageSetupSchema } from '@trek/shared'
/**
* The auto layout, once it knows what the journey adds up to (#1973).
*
* The rule these all circle: a page is added because there is something to put
* on it. A summary spread over a journey with no coordinates, or a country page
* for a trip that never left one country, is padding — and padding in a book
* someone pays to have printed is worse than a shorter book.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
const entry = (over: Partial<AutoEntry> = {}): AutoEntry => ({
id: 1, title: 'A day', story: 'Something happened.', location: 'Reykjavík',
date: '2026-06-02', photos: [], ...over,
})
const stats = (over: Partial<JourneyStats> = {}): JourneyStats => ({
journeyId: 6,
distance: 1_189_000,
days: 14,
steps: 14,
photos: 57,
places: 21,
furthest: 408_000,
countries: [{ code: 'IS', name: 'Iceland', places: 14, firstVisit: '2026-06-02' }],
points: [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík', date: '2026-06-02', country: 'IS', tripId: null, photoId: null },
{ lat: 65.68, lng: -18.12, label: 'Akureyri', date: '2026-06-06', country: 'IS', tripId: null, photoId: null },
],
trips: [],
start: '2026-06-02',
end: '2026-06-15',
...over,
})
function build(over: Partial<AutoInput> = {}) {
return buildBook({
locale: 'en',
title: 'Iceland',
subtitle: null,
coverPhotoId: null,
stationsLabel: 'Stations',
dayLabel: 'DAY',
summaryLabel: 'Trip summary',
countriesLabel: 'Countries',
entries: [entry()],
page,
stats: stats(),
...over,
})
}
type ElementKind = BookSpread['elements'][number]['kind']
const kinds = (sp: BookSpread) => sp.elements.map(e => e.kind)
/** `Array.prototype.at` is ES2022; the client's lib target predates it. */
const last = <T,>(xs: T[]): T => xs[xs.length - 1]
const has = (doc: { spreads: BookSpread[] }, kind: ElementKind) =>
doc.spreads.some(sp => kinds(sp).includes(kind))
const find = (doc: { spreads: BookSpread[] }, kind: ElementKind) =>
doc.spreads.flatMap(sp => sp.elements).find(e => e.kind === kind)
describe('the summary spread', () => {
it('is placed, with the route and the figures', () => {
const doc = build()
expect(has(doc, 'map')).toBe(true)
expect(has(doc, 'stats')).toBe(true)
})
it('comes straight after the cover, before the entries', () => {
const doc = build()
expect(doc.spreads[0].role).toBe('cover')
expect(kinds(doc.spreads[1])).toContain('map')
})
it('carries the journey figures rather than placeholders', () => {
const el = find(build(), 'stats')!
expect(el.kind === 'stats' && el.values.distance).toBe(1_189_000)
expect(el.kind === 'stats' && el.values.days).toBe(14)
})
it('draws the route from the journey stops', () => {
const el = find(build(), 'map')!
expect(el.kind === 'map' && el.points).toHaveLength(2)
expect(el.kind === 'map' && el.countries).toEqual(['IS'])
})
/*
* The point of the whole feature: a figure that is zero is not a fact worth
* a tile, it is a hole in the composition.
*/
it('leaves out the figures the journey does not have', () => {
const el = find(build({ stats: stats({ photos: 0, furthest: 0 }) }), 'stats')!
expect(el.kind === 'stats' && el.metrics).not.toContain('photos')
expect(el.kind === 'stats' && el.metrics).not.toContain('furthest')
expect(el.kind === 'stats' && el.metrics).toContain('distance')
})
it('has no map when the journey has no route to draw', () => {
const doc = build({ stats: stats({ points: [] }) })
expect(has(doc, 'map')).toBe(false)
// The figures are still worth a page.
expect(has(doc, 'stats')).toBe(true)
})
it('is skipped entirely when there is nothing to summarise', () => {
const doc = build({
stats: stats({
points: [], distance: 0, days: 0, steps: 0, photos: 0, places: 0, furthest: 0, countries: [],
}),
})
// Cover, the one entry, back cover — no summary, no country page.
expect(doc.spreads.map(sp => sp.role)).toEqual(['cover', 'inner', 'back'])
expect(has(doc, 'map')).toBe(false)
expect(has(doc, 'stats')).toBe(false)
})
it('is skipped when the figures could not be fetched at all', () => {
const doc = build({ stats: null })
expect(has(doc, 'map')).toBe(false)
expect(has(doc, 'stats')).toBe(false)
expect(has(doc, 'countries')).toBe(false)
// And the book still builds: cover, the entry, back cover.
expect(doc.spreads).toHaveLength(3)
})
})
describe('the country page', () => {
const twoCountries = stats({
countries: [
{ code: 'IS', name: 'Iceland', places: 14, firstVisit: '2026-06-02' },
{ code: 'NO', name: 'Norway', places: 3, firstVisit: '2026-06-16' },
],
})
it('is placed for a journey that crossed a border', () => {
const el = find(build({ stats: twoCountries }), 'countries')!
expect(el.kind === 'countries' && el.codes).toEqual(['IS', 'NO'])
})
/*
* One country on a page of its own says nothing the cover did not already
* say, and every page in a printed book costs money.
*/
it('is skipped for a journey that stayed in one country', () => {
expect(has(build(), 'countries')).toBe(false)
})
it('names the countries in the book language, not the API language', () => {
const el = find(build({ stats: twoCountries, locale: 'de' }), 'countries')!
expect(el.kind === 'countries' && el.names).toEqual(['Island', 'Norwegen'])
})
it('falls back to the API name when the locale has none', () => {
const el = find(build({ stats: twoCountries, locale: 'en' }), 'countries')!
expect(el.kind === 'countries' && el.names).toEqual(['Iceland', 'Norway'])
})
it('sits between the summary and the entries', () => {
const doc = build({ stats: twoCountries })
const order = doc.spreads.map(sp => kinds(sp).find(k => k === 'map' || k === 'countries') ?? sp.role)
expect(order.slice(0, 3)).toEqual(['cover', 'map', 'countries'])
})
})
describe('the back cover', () => {
/*
* It used to build its tally as `${places} Orte` — German, hardcoded, in a
* book that follows the app's language everywhere else.
*/
it('closes with a figures element rather than a built string', () => {
const back = last(build().spreads)
expect(back.role).toBe('back')
expect(kinds(back)).toContain('stats')
expect(back.elements.every(e => e.kind !== 'text' || !/Orte|Fotos/.test(e.text))).toBe(true)
})
it('sets that tally quietly, against the dark card', () => {
const back = last(build().spreads)
const el = back.elements.find(e => e.kind === 'stats')!
expect(el.kind === 'stats' && el.showIcons).toBe(false)
expect(el.opacity).toBeLessThan(1)
})
/*
* places and steps are separate figures — a journal with entries but no
* linked trip has steps and no places at all, and the tile printed "0".
*/
it('leaves out the places tally when the journey has none', () => {
const back = last(build({ stats: stats({ places: 0, steps: 4 }) }).spreads)
const el = back.elements.find(e => e.kind === 'stats')!
expect(el.kind === 'stats' && el.metrics).not.toContain('places')
})
it('still closes the book when there are no figures', () => {
const back = last(build({ stats: null }).spreads)
expect(back.role).toBe('back')
expect(kinds(back)).toContain('text')
})
})
describe('the entry spreads', () => {
it('rules the heading with a short accent line', () => {
const doc = build()
const spread = doc.spreads.find(sp => sp.entryId === 1)!
const rule = spread.elements.find(e => e.kind === 'shape' && e.frame.h < 1)
expect(rule).toBeTruthy()
expect(rule!.frame.w).toBeLessThan(20)
})
/*
* The one spread with room to spare — the left page is otherwise blank, and
* a date set as a numeral turns a gap in the book into a pause in it.
*/
it('sets the date as a numeral on an entry with no photographs', () => {
const doc = build()
const spread = doc.spreads.find(sp => sp.entryId === 1)!
const badge = spread.elements.find(e => e.kind === 'badge')
expect(badge).toBeTruthy()
expect(badge!.kind === 'badge' && badge.variant).toBe('date')
expect(badge!.kind === 'badge' && badge.text).toBe('2')
expect(badge!.kind === 'badge' && badge.sub).toBe('JUNE')
})
it('sets that numeral in the book language', () => {
const doc = build({ locale: 'de' })
const spread = doc.spreads.find(sp => sp.entryId === 1)!
const badge = spread.elements.find(e => e.kind === 'badge')!
expect(badge.kind === 'badge' && badge.sub).toBe('JUNI')
})
it('leaves out the numeral on an undated entry rather than printing a blank', () => {
const doc = build({ entries: [entry({ date: null })] })
const spread = doc.spreads.find(sp => sp.entryId === 1)!
expect(spread.elements.some(e => e.kind === 'badge')).toBe(false)
})
/*
* The marks came back on purpose. A page carrying a picture, a date numeral
* and a day chip is what a printed travel book looks like; the same page with
* only the picture is what a document looks like.
*/
it('gives a photo entry the marks that make it a printed page', () => {
const doc = build({
entries: [entry({ photos: [{ photoId: 1, width: 4000, height: 3000, caption: null }] })],
})
const spread = doc.spreads.find(sp => sp.entryId === 1)!
expect(spread.elements.some(e => e.kind === 'photo')).toBe(true)
expect(spread.elements.some(e => e.kind === 'badge')).toBe(true)
})
})
describe('the document as a whole', () => {
it('stays within the schema cap on spreads', () => {
const many = Array.from({ length: 200 }, (_, i) => entry({ id: i + 1 }))
expect(build({ entries: many }).spreads.length).toBeLessThanOrEqual(150)
})
it('gives every spread and every element an id of its own', () => {
const doc = build({ stats: stats({ countries: [
{ code: 'IS', name: 'Iceland', places: 4, firstVisit: '2026-06-02' },
{ code: 'NO', name: 'Norway', places: 2, firstVisit: '2026-06-16' },
] }) })
const ids = doc.spreads.flatMap(sp => [sp.id, ...sp.elements.map(e => e.id)])
expect(new Set(ids).size).toBe(ids.length)
})
it('opens on the cover and closes on the back cover', () => {
const doc = build()
expect(doc.spreads[0].role).toBe('cover')
expect(last(doc.spreads).role).toBe('back')
expect(doc.spreads.filter(sp => sp.role === 'cover')).toHaveLength(1)
expect(doc.spreads.filter(sp => sp.role === 'back')).toHaveLength(1)
})
})
/**
* What a journey with no book opens on (#1973).
*
* The auto layout used to run on first open, which decided what the book was
* before its author had said anything. It is now on the Auto layout menu and
* this is what takes its place: a book with nothing on its pages, and both
* covers present because the pages rail can only ever insert between them.
*/
describe('an empty book', () => {
const input: AutoInput = {
locale: 'en',
title: 'Iceland',
subtitle: null,
coverPhotoId: null,
stationsLabel: 'Stations',
dayLabel: 'DAY',
summaryLabel: 'Trip summary',
countriesLabel: 'Countries',
entries: [entry()],
page,
stats: stats(),
}
it('has a cover, a page and a back cover, and nothing on any of them', () => {
const doc = emptyBook(input)
expect(doc.spreads.map(s => s.role)).toEqual(['cover', 'inner', 'back'])
expect(doc.spreads.every(s => s.elements.length === 0)).toBe(true)
expect(doc.spreads.every(s => s.background === null)).toBe(true)
})
it('carries the journey title and the page setup it was given', () => {
const doc = emptyBook(input)
expect(doc.title).toBe('Iceland')
expect(doc.page.pageWidth).toBe(page.pageWidth)
})
it('gives every spread its own id', () => {
const ids = emptyBook(input).spreads.map(s => s.id)
expect(new Set(ids).size).toBe(ids.length)
})
/*
* The layout is still there, on the menu. This is the difference between
* offering it and having already applied it.
*/
it('is what the auto layout replaces when somebody asks for it', () => {
expect(buildBook(input).spreads.length).toBeGreaterThan(emptyBook(input).spreads.length)
})
})
+210
View File
@@ -0,0 +1,210 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import { bookBadgeElementSchema, bookPageSetupSchema, normalizeBookDocument } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
/**
* The picture on a mood or weather mark (#1973).
*
* These are the only marks whose drawing comes from the journal rather than from
* the book, and the field that says which mood it is used to be capped at two
* characters, from back when nothing but a country code went in it. A mark
* reading "amazing" therefore failed the contract, which failed its spread,
* which failed the document, and what the editor handed back was an empty book.
* The first thing kept here is that a mood key survives a round trip with the
* book still around it.
*
* The rest is the controls built on the widened field: whether the mark draws
* its picture, whether it draws its words, and what colour the picture is. The
* default reading is the one that matters most. Every book written before these
* fields existed carries none of them, and every element the panels build is
* cast rather than parsed, so the renderer has to read an absent flag as what it
* always meant: draw it.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
const typeset = {
font: 'sans' as const, color: '#1a1a1a', accent: '#c2410c', textScale: 1, weight: 700, stale: false,
}
const common = { rotation: 0, opacity: 1, locked: false, frame: { x: 10, y: 20, w: 90, h: 40 } }
/**
* A badge built the way the panels build one: cast, not parsed, so nothing the
* contract would default is filled in unless a test fills it. That is also what
* a mark out of a book written before the icon fields existed looks like, which
* is why the absent case below is worth a test at all.
*/
const badge = (over: Record<string, unknown>): BookElement => ({
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'mood', text: '', sub: '', code: null, style: 'plain', ...over,
} as unknown as BookElement)
function draw(elements: BookElement[]) {
const spread: BookSpread = {
id: 's1', role: 'inner', background: null, elements, parked: [], entryId: null,
}
return render(<SpreadView spread={spread} page={page} />)
}
/** A document around a single mark, as it arrives from storage. */
function documentAround(el: Record<string, unknown>, title = 'Iceland') {
return {
version: 1,
title,
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
spreads: [{
id: 's1', role: 'inner', entryId: null, background: null, parked: [],
elements: [
{ id: 'p1', kind: 'photo', frame: { x: 0, y: 0, w: 50, h: 50 }, photoId: 3 },
el,
],
}],
}
}
describe('a mark made before the icon controls existed', () => {
it('still draws its icon in the mood palette the journal uses', () => {
const { container } = draw([badge({ variant: 'mood', code: 'amazing', text: 'Amazing' })])
const icon = container.querySelector('svg')
expect(icon).not.toBeNull()
// The pink of "amazing" on the journey page, not the element's accent.
expect(icon!.getAttribute('stroke')).toBe('#BE185D')
})
it('still draws its words and the line under them', () => {
const { container } = draw([badge({
variant: 'mood', code: 'amazing', text: 'Amazing', sub: 'Reykjavik',
})])
expect(container.textContent).toContain('Amazing')
expect(container.textContent).toContain('Reykjavik')
})
/*
* A parsed badge carries the default of `iconColor` whether or not anybody
* chose it, so reading the colour on its own rather than the flag beside it
* would repaint every mood mark in the field to a flat near-black.
*/
it('ignores the icon colour while Automatic is still on', () => {
const { container } = draw([badge({
variant: 'mood', code: 'amazing', text: 'Amazing',
autoIconColor: true, iconColor: '#111111',
})])
expect(container.querySelector('svg')!.getAttribute('stroke')).toBe('#BE185D')
})
})
describe('choosing the icon colour', () => {
/*
* Asserted on the stroke because that is where it has to land: lucide takes
* its colour as a prop and writes it onto the SVG, so `currentColor` from the
* wrapper never reaches it, which is why the swatch used to look dead.
*/
it('paints a mood icon that colour instead of the journal palette', () => {
const { container } = draw([badge({
variant: 'mood', code: 'amazing', text: 'Amazing',
autoIconColor: false, iconColor: '#0EA5E9',
})])
expect(container.querySelector('svg')!.getAttribute('stroke')).toBe('#0EA5E9')
})
it('paints a weather icon that colour instead of the element accent', () => {
const { container } = draw([badge({
variant: 'weather', code: 'partly', text: 'Partly cloudy',
autoIconColor: false, iconColor: '#0EA5E9',
})])
expect(container.querySelector('svg')!.getAttribute('stroke')).toBe('#0EA5E9')
})
it('leaves a weather icon on the accent when Automatic is left alone', () => {
const { container } = draw([badge({ variant: 'weather', code: 'partly', text: 'Partly cloudy' })])
expect(container.querySelector('svg')!.getAttribute('stroke')).toBe('#c2410c')
})
})
describe('showing the picture and the words', () => {
it('drops the icon and keeps the words when the icon is switched off', () => {
const { container } = draw([badge({
variant: 'mood', code: 'amazing', text: 'Amazing', sub: 'Reykjavik', showIcon: false,
})])
expect(container.querySelector('svg')).toBeNull()
expect(container.textContent).toContain('Amazing')
expect(container.textContent).toContain('Reykjavik')
})
it('drops the words and the line under them when the label is switched off', () => {
const { container } = draw([badge({
variant: 'mood', code: 'amazing', text: 'Amazing', sub: 'Reykjavik', showLabel: false,
})])
expect(container.querySelector('svg')).not.toBeNull()
expect(container.textContent).not.toContain('Amazing')
expect(container.textContent).not.toContain('Reykjavik')
})
/*
* A mark with no words is a pictogram, and a pictogram should fill the box it
* was given. The frame here is 90 by 40, so beside a label the icon is 0.46 of
* the height and on its own it is 0.8 of the shorter side: 18.4mm against
* 32mm. Left at the label size it would float in the middle of a frame that
* was measured for words no longer on the page.
*/
it('draws the icon larger once there are no words beside it', () => {
const withLabel = draw([badge({ variant: 'mood', code: 'amazing', text: 'Amazing' })])
expect(withLabel.container.querySelector('svg')!.style.width).toBe('18.4mm')
const alone = draw([badge({ variant: 'mood', code: 'amazing', text: 'Amazing', showLabel: false })])
const icon = alone.container.querySelector('svg')!
expect(icon.style.width).toBe('32mm')
expect(icon.style.height).toBe('32mm')
})
})
describe('the badge contract', () => {
it('defaults a mark that predates the icon fields to drawing both parts', () => {
const parsed = bookBadgeElementSchema.parse({
id: 'b1', kind: 'badge', frame: { x: 0, y: 0, w: 40, h: 20 },
variant: 'mood', code: 'amazing',
})
expect(parsed.showIcon).toBe(true)
expect(parsed.showLabel).toBe(true)
expect(parsed.autoIconColor).toBe(true)
})
/*
* The bug this all started from. A mood key is longer than a country code, the
* field was capped at two characters, and the element failing the union took
* its spread, its document and the whole book down with it.
*/
it('keeps the book when a mark carries a mood key rather than a country code', () => {
const doc = normalizeBookDocument(documentAround({
id: 'b1', kind: 'badge', frame: { x: 10, y: 20, w: 90, h: 40 },
variant: 'mood', code: 'amazing', text: 'Amazing',
}))
expect(doc.title).toBe('Iceland')
expect(doc.spreads).toHaveLength(1)
// Both elements, in order: the mark was not quietly salvaged away either.
expect(doc.spreads[0].elements.map(e => e.kind)).toEqual(['photo', 'badge'])
const mark = doc.spreads[0].elements[1]
expect(mark.kind === 'badge' && mark.code).toBe('amazing')
})
it('carries all four icon fields through a round trip with the spread intact', () => {
const doc = normalizeBookDocument(documentAround({
id: 'b1', kind: 'badge', frame: { x: 10, y: 20, w: 90, h: 40 },
variant: 'weather', code: 'partly', text: 'Partly cloudy',
showIcon: true, showLabel: false, autoIconColor: false, iconColor: '#0EA5E9',
}))
expect(doc.spreads[0].elements).toHaveLength(2)
const mark = doc.spreads[0].elements[1]
expect(mark.kind).toBe('badge')
expect(mark.kind === 'badge' && mark.showIcon).toBe(true)
expect(mark.kind === 'badge' && mark.showLabel).toBe(false)
expect(mark.kind === 'badge' && mark.autoIconColor).toBe(false)
expect(mark.kind === 'badge' && mark.iconColor).toBe('#0EA5E9')
})
})
+107
View File
@@ -0,0 +1,107 @@
import { describe, it, expect } from 'vitest'
import { BOOK_FONTS_IDS, bookTextElementSchema } from '@trek/shared'
import {
BOOK_FONTS, BOOK_FONT_ORDER, fontStack, hasWeight, nearestWeight,
} from '../../../src/components/Studio/bookFonts'
/**
* The book's typefaces (#1973).
*
* The rule the whole file exists for: a book is proofread on screen and printed
* somewhere else, so every family has to be one both machines have. A stack
* naming a system font — Georgia, which is on most desktops and on no Linux
* container — means the renderer substitutes silently and the printed book is
* set in a typeface nobody chose.
*/
describe('the registry', () => {
it('has an entry for every family the contract allows', () => {
for (const id of BOOK_FONTS_IDS) {
expect(BOOK_FONTS[id], id).toBeTruthy()
}
})
it('offers every family in the picker, in one order', () => {
expect([...BOOK_FONT_ORDER].sort()).toEqual([...BOOK_FONTS_IDS].sort())
expect(new Set(BOOK_FONT_ORDER).size).toBe(BOOK_FONT_ORDER.length)
})
/*
* The one that matters. Every stack must end in a generic — a stack ending in
* another named family is a stack that can silently land somewhere nobody
* bundled.
*/
it('ends every stack in a generic family', () => {
for (const id of BOOK_FONTS_IDS) {
const last = BOOK_FONTS[id].stack.split(',').pop()!.trim()
expect(['sans-serif', 'serif', 'monospace'], `${id}: ${last}`).toContain(last)
}
})
it('names a bundled family first in every stack', () => {
// The first entry is the one that will actually be used, so it is the one
// that has to be self-hosted.
const bundled = ['Poppins', 'Inter', 'Lora', 'EB Garamond', 'Playfair Display', 'MuseoModerno', 'Bebas Neue']
for (const id of BOOK_FONTS_IDS) {
const first = BOOK_FONTS[id].stack.split(',')[0].replace(/"/g, '').trim()
expect(bundled, `${id}: ${first}`).toContain(first)
}
})
it('keeps the three original ids, so old documents still parse', () => {
for (const id of ['sans', 'serif', 'display']) {
expect(BOOK_FONTS_IDS).toContain(id)
}
expect(bookTextElementSchema.parse({
id: 't', kind: 'text', frame: { x: 0, y: 0, w: 10, h: 10 }, font: 'serif',
}).font).toBe('serif')
})
it('no longer sets the serif slot in a system font', () => {
expect(BOOK_FONTS.serif.stack).toContain('Lora')
expect(BOOK_FONTS.serif.stack.split(',')[0]).not.toContain('Georgia')
})
it('gives every family at least one weight', () => {
for (const id of BOOK_FONTS_IDS) {
expect(BOOK_FONTS[id].weights.length, id).toBeGreaterThan(0)
}
})
})
describe('fontStack', () => {
it('resolves a known family', () => {
expect(fontStack('garamond')).toContain('EB Garamond')
})
/*
* A document naming a family that was later removed should render in
* something bundled, not in whatever the machine defaults to.
*/
it('falls back to a bundled family rather than to a generic', () => {
expect(fontStack('a-family-that-was-removed')).toBe(BOOK_FONTS.sans.stack)
})
})
describe('weights', () => {
it('reports what a family actually ships', () => {
expect(hasWeight('sans', 700)).toBe(true)
expect(hasWeight('bebas', 700)).toBe(false)
expect(hasWeight('bebas', 400)).toBe(true)
})
/*
* A synthesised bold is a smeared regular in print, so picking a display face
* that ships one weight has to move the weight rather than ask for one the
* renderer will fake.
*/
it('moves to the nearest weight a family really has', () => {
expect(nearestWeight('bebas', 700)).toBe(400)
expect(nearestWeight('sans', 700)).toBe(700)
})
it('leaves an unknown family alone rather than guessing', () => {
expect(nearestWeight('unknown', 600)).toBe(600)
expect(hasWeight('unknown', 600)).toBe(true)
})
})
+119
View File
@@ -0,0 +1,119 @@
import { describe, it, expect } from 'vitest'
import type { BookDocument, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { MARK_LENGTH, sheetBox, sheetsFor } from '../../../src/components/Studio/bookSheets'
/**
* Cutting a book into sheets (#1973).
*
* The arithmetic here is what a press measures, so the tests are about
* millimetres: where the trim edge lands on the sheet, how far the marks reach,
* and which half of a spread each leaf shows. Getting the offset wrong is not a
* visible bug on screen — it is a photograph that arrives cut in the wrong
* place, in a book someone paid to have printed.
*/
const page = (over: Record<string, unknown> = {}) =>
bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, ...over })
const spread = (role: BookSpread['role'], id: string): BookSpread => ({
id, role, background: null, elements: [], parked: [], entryId: null,
})
function book(roles: BookSpread['role'][], pageOver: Record<string, unknown> = {}): BookDocument {
return {
version: 1,
title: 'T',
page: page(pageOver),
spreads: roles.map((r, i) => spread(r, `s${i}`)),
} as BookDocument
}
describe('the sheet box', () => {
it('is the trim plus a bleed on each side when there are no marks', () => {
const box = sheetBox(210, 297, 3, false)
expect(box.width).toBe(216)
expect(box.height).toBe(303)
expect(box.margin).toBe(3)
})
/*
* Marks go outside the bleed, not inside it. Inside means printing them onto
* the strip that gets cut off — they would be trimmed away along with the
* thing they were marking.
*/
it('makes room outside the bleed for the marks', () => {
const box = sheetBox(210, 210, 3, true)
expect(box.margin).toBe(3 + MARK_LENGTH)
expect(box.width).toBe(210 + (3 + MARK_LENGTH) * 2)
// The bleed is still the bleed — the extra room is not more of it.
expect(box.bleed).toBe(3)
})
it('is the trim itself when the book has no bleed at all', () => {
const box = sheetBox(210, 210, 0, false)
expect(box.width).toBe(210)
expect(box.margin).toBe(0)
})
})
describe('single pages', () => {
it('cuts every inner spread into two leaves and leaves the covers whole', () => {
const sheets = sheetsFor(book(['cover', 'inner', 'inner', 'back']), 'pages')
expect(sheets).toHaveLength(1 + 2 + 2 + 1)
expect(sheets.map(s => s.width)).toEqual([210, 210, 210, 210, 210, 210])
})
/*
* The cut is a window onto the spread, never a re-layout: the right-hand leaf
* is the same spread shifted by one page width. That is what makes a
* photograph crossing the gutter line up again once both halves are printed.
*/
it('shows the right-hand leaf through a window one page further in', () => {
const sheets = sheetsFor(book(['cover', 'inner']), 'pages')
const [, left, right] = sheets
expect(left.offset).toBe(0)
expect(right.offset).toBe(210)
// Both halves are the same spread, so nothing was moved to make them fit.
expect(right.spread).toBe(left.spread)
expect(right.spreadWidth).toBe(420)
})
it('keeps a cover at one page wide, with nothing shifted', () => {
const [cover] = sheetsFor(book(['cover', 'inner']), 'pages')
expect(cover.width).toBe(210)
expect(cover.spreadWidth).toBe(210)
expect(cover.offset).toBe(0)
})
/* Labels are for the print view. Covers carry no folio, in any book. */
it('numbers the leaves the way the folios do, and leaves covers unlabelled', () => {
const sheets = sheetsFor(book(['cover', 'inner', 'inner']), 'pages')
expect(sheets.map(s => s.label)).toEqual(['', '2', '3', '4', '5'])
})
it('follows startAt when the book counts from somewhere else', () => {
const sheets = sheetsFor(book(['cover', 'inner'], { pageNumbers: { startAt: 1 } }), 'pages')
expect(sheets.map(s => s.label)).toEqual(['', '1', '2'])
})
})
describe('spreads', () => {
it('keeps each spread on one sheet', () => {
const sheets = sheetsFor(book(['cover', 'inner', 'inner', 'back']), 'spreads')
expect(sheets).toHaveLength(4)
expect(sheets.map(s => s.width)).toEqual([210, 420, 420, 210])
expect(sheets.every(s => s.offset === 0)).toBe(true)
})
it('labels an inner sheet with the pair of numbers it carries', () => {
const sheets = sheetsFor(book(['cover', 'inner', 'inner']), 'spreads')
expect(sheets.map(s => s.label)).toEqual(['', '2 – 3', '4 – 5'])
})
})
describe('an empty book', () => {
it('produces no sheets rather than one blank one', () => {
expect(sheetsFor(book([]), 'pages')).toEqual([])
})
})
@@ -0,0 +1,212 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { BookDocument, BookPageSetup, BookTextElement } from '@trek/shared'
import { bookPageSetupSchema, normalizeBookDocument } from '@trek/shared'
import { fireEvent, render, screen } from '../../helpers/render'
import { StudioSidebar, type JourneySource } from '../../../src/components/Studio/StudioSidebar'
import { useStudioStore } from '../../../src/store/studioStore'
/**
* The date and coordinate chips in Content > Entries (#1973).
*
* An entry knows two things nobody wants to re-type onto a page: which day it
* was and where it happened. What these check is that both arrive still
* attached to the entry, carrying the raw fact alongside the printed words,
* because that pair is what lets a book re-read its own text when it opens
* without rewriting a line that was only ever set in another language.
*
* The last test is the one that earns its place. Placing an element is half of
* it; the document has to survive the contract afterwards. A mood mark once
* failed the union over a two-character cap and took the whole book with it,
* normalising to an empty document that the autosave then wrote down, so a new
* binding field that quietly fails to parse is not a cosmetic problem.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
type Entry = JourneySource['entries'][number]
const entry = (over: Partial<Entry> = {}): Entry => ({
id: 7,
title: 'Kirkjufell',
story: null,
location: 'Grundarfjordur',
date: '2026-06-04',
lat: 64.9275,
lng: -23.3072,
mood: null,
weather: null,
pros: [],
cons: [],
...over,
})
const sourceOf = (...entries: Entry[]): JourneySource => ({ entries, photos: [], photoEntries: {} })
/** One empty inner spread, parsed rather than cast, so the store holds a real document. */
const emptyBook = (): BookDocument => normalizeBookDocument({
version: 1,
title: 'Iceland',
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
spreads: [{ id: 'sp1', role: 'inner', entryId: null, background: null, elements: [], parked: [] }],
})
beforeEach(() => {
useStudioStore.getState().load(emptyBook())
})
/**
* Render the sidebar and walk to the panel the chips live in.
*
* ContentPanel is private to the sidebar, so the way in is the way a person
* takes: the rail, then the Entries tab. `t` is the identity function, which is
* why every label below is a raw key.
*/
function openEntries(source: JourneySource) {
const view = render(
<StudioSidebar
page={page}
pxPerMm={96 / 25.4}
bookView={false}
source={source}
stats={null}
path={[]}
t={(k: string) => k}
locale="en-US"
/>,
)
fireEvent.click(screen.getByLabelText('journey.studio.content'))
fireEvent.click(screen.getByRole('button', { name: /journey\.studio\.entries/ }))
return view
}
/** The element the chip just dropped, narrowed so its binding can be read. */
function lastText(): BookTextElement {
const els = useStudioStore.getState().doc!.spreads[0].elements
const el = els[els.length - 1]
if (!el || el.kind !== 'text') throw new Error(`expected a text element, found ${el?.kind ?? 'nothing'}`)
return el
}
describe('which chips an entry offers', () => {
it('offers no coordinates for an entry that never recorded a point', () => {
openEntries(sourceOf(entry({ lat: null, lng: null })))
expect(screen.queryByText('journey.studio.coordsMark')).toBeNull()
// The place name is still on offer: a written location is not a point.
expect(screen.getByText('journey.studio.addPlace')).toBeInTheDocument()
})
it('offers no coordinates when only one half of the point survived', () => {
openEntries(sourceOf(entry({ lng: null })))
expect(screen.queryByText('journey.studio.coordsMark')).toBeNull()
})
it('offers coordinates once the entry has both halves', () => {
openEntries(sourceOf(entry()))
expect(screen.getByText('journey.studio.coordsMark')).toBeInTheDocument()
})
it('offers no date for an undated entry', () => {
openEntries(sourceOf(entry({ date: null })))
expect(screen.queryByText('journey.studio.dateMark')).toBeNull()
})
})
describe('the date chip', () => {
it('prints the day spelled out, with its year', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.dateMark'))
// Not the sidebar's short weekday form: a book outlives the year it was
// made in, so the year belongs on the page.
expect(lastText().text).toBe('June 4, 2026')
})
it('stays attached to the entry it came from, and unedited', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.dateMark'))
const el = lastText()
expect(el.binding).toMatchObject({ source: 'entry.date', entryId: 7 })
expect(el.overridden).toBe(false)
})
/*
* The words are a rendering of the date, so they cannot answer "has the
* journal changed?" on their own. The ISO date rides along to answer it.
*/
it('carries the entry ISO date as the fact behind the words', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.dateMark'))
expect(lastText().binding!.value).toBe('2026-06-04')
// A date has one printed form, so it claims no coordinate format.
expect(lastText().binding!.format).toBeUndefined()
})
})
describe('the coordinates chip', () => {
it('prints the point in degrees, minutes and seconds', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.coordsMark'))
expect(lastText().text).toBe(`64° 55' 39" N 23° 18' 26" W`)
// A printed page says W, never a minus sign.
expect(lastText().text).not.toContain('-')
})
it('binds to the entry location, marked as the coordinate reading of it', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.coordsMark'))
expect(lastText().binding).toMatchObject({
source: 'entry.location',
entryId: 7,
format: 'dms',
value: '64.9275,-23.3072',
})
})
it('lands on a short line rather than across the whole column', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.addPlace'))
const placeWidth = lastText().frame.w
fireEvent.click(screen.getByText('journey.studio.coordsMark'))
expect(lastText().frame.w).toBeLessThan(placeWidth)
})
})
describe('a spread holding both marks', () => {
/*
* Normalising is not a formality here: the client's load seam and both of the
* server's paths run through it, and it used to answer a single unreadable
* element with an empty book. Whatever the chips write has to come back out.
*/
it('survives normalizeBookDocument with the spread and both bindings intact', () => {
openEntries(sourceOf(entry()))
fireEvent.click(screen.getByText('journey.studio.dateMark'))
fireEvent.click(screen.getByText('journey.studio.coordsMark'))
const doc = normalizeBookDocument(useStudioStore.getState().doc)
expect(doc.title).toBe('Iceland')
expect(doc.spreads).toHaveLength(1)
expect(doc.spreads[0].elements).toHaveLength(2)
const [date, coords] = doc.spreads[0].elements
expect(date.kind === 'text' && date.text).toBe('June 4, 2026')
expect(date.kind === 'text' && date.binding).toMatchObject({
source: 'entry.date', entryId: 7, value: '2026-06-04',
})
expect(coords.kind === 'text' && coords.binding).toMatchObject({
source: 'entry.location', entryId: 7, format: 'dms', value: '64.9275,-23.3072',
})
})
})
@@ -0,0 +1,186 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import { bookListElementSchema, normalizeBookDocument } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { bookPageSetupSchema } from '@trek/shared'
/**
* Mood, weather and pros & cons (#1973).
*
* These come from the journal entry rather than from the trip, and they are the
* part of an entry a photo cannot carry. What is checked here is that they draw
* from the entry's own vocabulary — the same keys, icons and palette the journey
* page uses — rather than from a second copy that would drift.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
const typeset = { font: 'sans' as const, color: '#1a1a1a', accent: '#c2410c', textScale: 1, stale: false }
const common = { rotation: 0, opacity: 1, locked: false, frame: { x: 10, y: 20, w: 90, h: 40 } }
function draw(elements: BookElement[]) {
const spread: BookSpread = {
id: 's1', role: 'inner', background: null, elements, parked: [], entryId: null,
}
return render(<SpreadView spread={spread} page={page} />)
}
const badge = (over: Record<string, unknown>): BookElement => ({
...common, ...typeset, id: 'b1', kind: 'badge',
variant: 'mood', text: '', sub: '', code: null, style: 'plain', ...over,
} as unknown as BookElement)
const list = (over: Record<string, unknown> = {}): BookElement => ({
...common, ...typeset, id: 'l1', kind: 'list',
items: [
{ text: 'Warm all week', tone: 'pro' },
{ text: 'Ferry was late', tone: 'con' },
],
layout: 'columns', showMarks: true, proLabel: 'Pros', conLabel: 'Cons', ...over,
} as unknown as BookElement)
describe('the mood mark', () => {
it('draws the icon the journey page uses for that mood', () => {
const { container } = draw([badge({ variant: 'mood', code: 'good', text: 'Good' })])
expect(container.querySelector('svg')).not.toBeNull()
expect(container.textContent).toContain('Good')
})
/*
* The palette comes from MOOD_CONFIG rather than from the element's accent:
* a mood has a colour of its own in TREK, and a book that ignored it would
* disagree with the page the entry was written on.
*/
it('takes its colour from the mood, not from the element accent', () => {
const { container } = draw([badge({ variant: 'mood', code: 'good', text: 'Good' })])
const icon = container.querySelector('svg')!
expect(icon.getAttribute('stroke')).toBe('#B45309')
})
it('draws nothing for a mood key TREK does not know', () => {
const { container } = draw([badge({ variant: 'mood', code: 'elated', text: 'Elated' })])
expect(container.querySelector('svg')).toBeNull()
// The words still print — an unknown key is not a reason to lose the label.
expect(container.textContent).toContain('Elated')
})
})
describe('the weather mark', () => {
it('draws the icon for that weather', () => {
const { container } = draw([badge({ variant: 'weather', code: 'cloudy', text: 'Cloudy' })])
expect(container.querySelector('svg')).not.toBeNull()
expect(container.textContent).toContain('Cloudy')
})
it('uses the element accent, since weather has no palette of its own', () => {
const { container } = draw([badge({ variant: 'weather', code: 'sunny', text: 'Sunny' })])
expect(container.querySelector('svg')!.getAttribute('stroke')).toBe('#c2410c')
})
})
describe('the pros and cons list', () => {
it('prints both columns with their headings', () => {
const { container } = draw([list()])
expect(container.textContent).toContain('Warm all week')
expect(container.textContent).toContain('Ferry was late')
expect(container.textContent).toContain('Pros')
expect(container.textContent).toContain('Cons')
})
it('marks each line, a plus against a dash', () => {
const { container } = draw([list()])
expect(container.textContent).toContain('+')
// An en dash, not a hyphen — at 2mm a hyphen reads as a speck.
expect(container.textContent).toContain('–')
})
it('drops the marks when they are switched off', () => {
const { container } = draw([list({ showMarks: false })])
expect(container.textContent).toContain('Warm all week')
expect(container.textContent).not.toContain('+')
})
it('prints a one-sided list without an empty second column', () => {
const { container } = draw([list({
items: [{ text: 'Only good things', tone: 'pro' }],
conLabel: '',
})])
expect(container.textContent).toContain('Only good things')
expect(container.textContent).not.toContain('Cons')
})
it('runs as one column when stacked', () => {
const { container } = draw([list({ layout: 'stacked' })])
expect(container.textContent).toContain('Warm all week')
expect(container.textContent).toContain('Ferry was late')
})
it('survives an empty list rather than failing to draw', () => {
const { container } = draw([list({ items: [], proLabel: '', conLabel: '' })])
expect(container.querySelector('div')).not.toBeNull()
})
})
describe('the list contract', () => {
it('defaults to an empty two-column list with marks', () => {
const parsed = bookListElementSchema.parse({
id: 'l1', kind: 'list', frame: { x: 0, y: 0, w: 10, h: 10 },
})
expect(parsed.items).toEqual([])
expect(parsed.layout).toBe('columns')
expect(parsed.showMarks).toBe(true)
})
it('defaults an item with no tone to plain', () => {
const parsed = bookListElementSchema.parse({
id: 'l1', kind: 'list', frame: { x: 0, y: 0, w: 10, h: 10 },
items: [{ text: 'something' }],
})
expect(parsed.items[0].tone).toBe('plain')
})
/*
* The rule the whole format rests on: a document written before these
* elements existed still opens, and one written with them survives a round
* trip through storage.
*/
it('round-trips inside a document', () => {
const doc = normalizeBookDocument({
version: 1,
title: 'T',
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
spreads: [{
id: 's1', role: 'inner', entryId: null, background: null, parked: [],
elements: [{
id: 'l1', kind: 'list', frame: { x: 1, y: 2, w: 90, h: 40 },
items: [{ text: 'kept', tone: 'con' }],
proLabel: 'P', conLabel: 'C',
}],
}],
})
const el = doc.spreads[0].elements[0]
expect(el.kind).toBe('list')
expect(el.kind === 'list' && el.items[0]).toEqual({ text: 'kept', tone: 'con' })
expect(el.kind === 'list' && el.conLabel).toBe('C')
})
it('still opens a document that predates these elements', () => {
const doc = normalizeBookDocument({
version: 1,
title: 'Old',
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
spreads: [{
id: 's1', role: 'inner', entryId: null, background: null, parked: [],
elements: [{ id: 'p1', kind: 'photo', frame: { x: 0, y: 0, w: 50, h: 50 }, photoId: 3 }],
}],
})
const el = doc.spreads[0].elements[0]
expect(el.kind).toBe('photo')
// The fields added since default in rather than failing the parse.
expect(el.kind === 'photo' && el.mask).toBeNull()
expect(el.kind === 'photo' && el.frameStyle).toBe('none')
})
})
@@ -0,0 +1,65 @@
import { describe, it, expect } from 'vitest'
import { formatBookCoords, formatBookDate } from '../../../src/components/Studio/entryText'
/**
* The strings a journal entry lends to a page (#1973).
*
* These are pinned rather than sampled, because three call sites have to agree
* on them character for character: the chip that places a mark, the template
* filler that fills one that was drawn, and the resolver that re-reads it when
* the book is opened. If the chip and the resolver ever disagree by a space,
* opening a book rewrites the element and the autosave writes it back, which
* looks like a book that edits itself.
*
* The degrees form is also the one already printed by the auto layout and by
* the Travel panel, so changing it here changes what is on pages people have
* already made.
*/
describe('coordinates', () => {
it('sets degrees, minutes and seconds with a hemisphere letter', () => {
expect(formatBookCoords(52.5163, 13.3777)).toBe(`52° 30' 59" N 13° 22' 40" E`)
})
it('says south and west rather than using a minus sign', () => {
// A printed page has no room for a sign somebody has to decode, and the
// letter is unambiguous in a way -33.8688 is not.
expect(formatBookCoords(-33.8688, -70.6693)).toBe(`33° 52' 8" S 70° 40' 9" W`)
})
it('sets the decimal form to four places, which is about eleven metres', () => {
expect(formatBookCoords(52.5163, 13.3777, 'decimal')).toBe('52.5163° N 13.3777° E')
})
it('keeps the hemisphere letter in the decimal form too', () => {
expect(formatBookCoords(-33.8688, -70.6693, 'decimal')).toBe('33.8688° S 70.6693° W')
})
it('defaults to degrees, which is what the rest of Studio prints', () => {
expect(formatBookCoords(10, 20)).toBe(formatBookCoords(10, 20, 'dms'))
})
})
describe('the entry date', () => {
it('spells the month out, in the app language', () => {
expect(formatBookDate('2026-06-12', 'de-DE')).toBe('12. Juni 2026')
expect(formatBookDate('2026-06-12', 'en-GB')).toBe('12 June 2026')
})
/*
* Local midnight, not UTC. The date on an entry is the day the writer had,
* and reading it as an instant moves it backwards for everyone west of
* Greenwich, which is a photo book dated the day before the photographs.
*/
it('reads the day as a day rather than as a moment in time', () => {
expect(formatBookDate('2026-01-01', 'en-GB')).toBe('1 January 2026')
})
it('gives nothing back for an entry with no date', () => {
expect(formatBookDate(null, 'en-GB')).toBe('')
})
it('gives nothing back rather than printing Invalid Date', () => {
expect(formatBookDate('not-a-date', 'en-GB')).toBe('')
})
})
+171
View File
@@ -0,0 +1,171 @@
import { describe, it, expect } from 'vitest'
import { COUNTRY_SHAPES } from '../../../src/components/Studio/countryShapes'
import {
FLAG_H, FLAG_SPECS, FLAG_W, flagBands, flagDisc, flagSpec,
} from '../../../src/components/Studio/flags'
/**
* The drawn flags (#1973).
*
* The rule that matters is the one about restraint: a flag is listed only when
* its construction is exact. A wrong flag in a printed book is worse than a
* country outline, so the guard here is as much about what is *absent* as
* about what is drawn.
*/
describe('the flag table', () => {
it('uses two-letter uppercase codes throughout', () => {
for (const code of Object.keys(FLAG_SPECS)) {
expect(code, code).toMatch(/^[A-Z]{2}$/)
}
})
it('gives every colour as #rrggbb, so it can be handed straight to SVG', () => {
for (const [code, spec] of Object.entries(FLAG_SPECS)) {
const colours = spec.t === 'h' || spec.t === 'v'
? spec.c
: spec.t === 'nordic'
? [spec.field, spec.cross, ...(spec.inner ? [spec.inner] : [])]
: spec.t === 'cross'
? [spec.field, spec.cross]
: [spec.field, spec.disc]
for (const c of colours) expect(c, `${code}: ${c}`).toMatch(/^#[0-9a-f]{6}$/)
}
})
it('has at least two bands on any striped flag', () => {
for (const [code, spec] of Object.entries(FLAG_SPECS)) {
if (spec.t === 'h' || spec.t === 'v') {
expect(spec.c.length, code).toBeGreaterThanOrEqual(2)
}
}
})
/*
* The point of the whole approach: anything that cannot be built from bands,
* a cross or a disc is left out rather than approximated. These are the flags
* most likely to be reached for and wrongly added — each carries an emblem or
* unequal bands that this construction cannot express.
*/
it('leaves out the flags it cannot draw exactly', () => {
for (const code of ['GB', 'US', 'ES', 'PT', 'MX', 'BR', 'IN', 'EG', 'CA', 'AU', 'CO', 'LV', 'GR', 'TR']) {
expect(FLAG_SPECS[code], code).toBeUndefined()
}
})
it('has a country silhouette for every flag it does not draw', () => {
// The fallback has to exist, or a missing flag becomes bare letters.
for (const code of ['GB', 'US', 'ES', 'PT', 'MX', 'BR', 'IN', 'CA', 'AU', 'TR', 'GR']) {
expect(COUNTRY_SHAPES[code], code).toBeTruthy()
}
})
})
describe('flagBands', () => {
it('splits horizontal bands evenly across the height', () => {
const bands = flagBands({ t: 'h', c: ['#000000', '#dd0000', '#ffce00'] })
expect(bands).toHaveLength(3)
for (const b of bands) {
expect(b.w).toBe(FLAG_W)
expect(b.h).toBeCloseTo(FLAG_H / 3, 6)
}
expect(bands[0].y).toBe(0)
expect(bands[2].y + bands[2].h).toBeCloseTo(FLAG_H, 6)
})
it('splits vertical bands evenly across the width', () => {
const bands = flagBands({ t: 'v', c: ['#002395', '#ffffff', '#ed2939'] })
for (const b of bands) {
expect(b.h).toBe(FLAG_H)
expect(b.w).toBeCloseTo(FLAG_W / 3, 6)
}
expect(bands[2].x + bands[2].w).toBeCloseTo(FLAG_W, 6)
})
it('keeps the band order, which is the whole identity of a tricolour', () => {
const bands = flagBands(FLAG_SPECS.DE)
expect(bands.map(b => b.fill)).toEqual(['#000000', '#dd0000', '#ffce00'])
})
/*
* Left of centre is what separates a Nordic cross from a plain one — the
* upright at the halfway mark would be the Swiss flag's geometry, not
* Denmark's.
*/
it('puts the Nordic upright left of centre', () => {
const bands = flagBands(FLAG_SPECS.DK)
const upright = bands[1]
expect(upright.x + upright.w / 2).toBeLessThan(FLAG_W / 2)
expect(upright.h).toBe(FLAG_H)
})
it('draws the inner cross on top of the outer one, and thinner', () => {
const bands = flagBands(FLAG_SPECS.IS)
// field, upright, crossbar, then the two inner bars.
expect(bands).toHaveLength(5)
expect(bands[3].fill).toBe('#dc1e35')
expect(bands[3].w).toBeLessThan(bands[1].w)
})
it('omits the inner cross where the flag has none', () => {
expect(flagBands(FLAG_SPECS.DK)).toHaveLength(3)
})
it('centres the Swiss cross both ways and keeps it inside the field', () => {
const [field, upright, bar] = flagBands(FLAG_SPECS.CH)
expect(field.w).toBe(FLAG_W)
expect(upright.x + upright.w / 2).toBeCloseTo(FLAG_W / 2, 6)
expect(bar.y + bar.h / 2).toBeCloseTo(FLAG_H / 2, 6)
expect(upright.y).toBeGreaterThan(0)
expect(upright.y + upright.h).toBeLessThan(FLAG_H)
})
it('keeps every band inside the flag box', () => {
for (const [code, spec] of Object.entries(FLAG_SPECS)) {
for (const b of flagBands(spec)) {
expect(b.x, code).toBeGreaterThanOrEqual(0)
expect(b.y, code).toBeGreaterThanOrEqual(0)
expect(b.x + b.w, code).toBeLessThanOrEqual(FLAG_W + 0.001)
expect(b.y + b.h, code).toBeLessThanOrEqual(FLAG_H + 0.001)
}
}
})
it('covers the whole box with its first band, so no page shows through', () => {
for (const [code, spec] of Object.entries(FLAG_SPECS)) {
const bands = flagBands(spec)
const area = bands.reduce((sum, b) => sum + b.w * b.h, 0)
expect(area, code).toBeGreaterThanOrEqual(FLAG_W * FLAG_H - 0.001)
}
})
})
describe('flagDisc', () => {
it('is a centred circle on a disc flag', () => {
const disc = flagDisc(FLAG_SPECS.JP)!
expect(disc.cx).toBe(FLAG_W / 2)
expect(disc.cy).toBe(FLAG_H / 2)
expect(disc.r).toBeLessThan(FLAG_H / 2)
expect(disc.fill).toBe('#bc002d')
})
it('is null for every other construction', () => {
expect(flagDisc(FLAG_SPECS.DE)).toBeNull()
expect(flagDisc(FLAG_SPECS.IS)).toBeNull()
expect(flagDisc(FLAG_SPECS.CH)).toBeNull()
})
})
describe('flagSpec', () => {
it('is case-insensitive, because codes arrive from several places', () => {
expect(flagSpec('is')).toBe(FLAG_SPECS.IS)
expect(flagSpec('IS')).toBe(FLAG_SPECS.IS)
})
it('is null for nothing and for a country with no construction', () => {
expect(flagSpec(null)).toBeNull()
expect(flagSpec(undefined)).toBeNull()
expect(flagSpec('')).toBeNull()
expect(flagSpec('GB')).toBeNull()
})
})
@@ -0,0 +1,133 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookSpread } from '@trek/shared'
import { brightness, folioInk } from '../../../src/components/Studio/folioColour'
/**
* Choosing a folio colour (#1973).
*
* One fixed colour is wrong on half the pages of any real book: the warm grey
* that reads on paper vanishes into a full-bleed night photograph, and white
* vanishes the moment the page is white. So the renderer asks what is under the
* number. What follows is that question, and the order it has to be asked in.
*/
const DARK = '#3f3a33'
const LIGHT = '#ffffff'
const shape = (over: Partial<BookElement> = {}): BookElement => ({
id: 's', kind: 'shape', frame: { x: 0, y: 0, w: 100, h: 100 },
rotation: 0, opacity: 1, locked: false,
shape: 'rect', fill: '#000000', gradient: 'none',
stroke: null, strokeWidth: 0, strokeStyle: 'solid', radius: 0,
...over,
} as BookElement)
const photo = (over: Partial<BookElement> = {}): BookElement => ({
id: 'p', kind: 'photo', frame: { x: 0, y: 0, w: 100, h: 100 },
rotation: 0, opacity: 1, locked: false,
photoId: 1, fit: 'cover', focalX: 0.5, focalY: 0.5,
radius: 0, filter: 'none', mask: null, frameStyle: 'none',
...over,
} as BookElement)
const text = (over: Partial<BookElement> = {}): BookElement => ({
id: 't', kind: 'text', frame: { x: 0, y: 0, w: 100, h: 100 },
rotation: 0, opacity: 1, locked: false,
text: 'x', font: 'sans', size: 12, color: '#000000',
align: 'left', lineHeight: 1.3, letterSpacing: 0, weight: 400, italic: false,
...over,
} as unknown as BookElement)
const spread = (elements: BookElement[], background: string | null = '#ffffff'): BookSpread => ({
id: 's1', role: 'inner', background, elements, parked: [], entryId: null,
})
describe('brightness', () => {
it('reads the ends of the range', () => {
expect(brightness('#000000')).toBe(0)
expect(brightness('#ffffff')).toBe(1)
})
it('weights green the way an eye does', () => {
expect(brightness('#00ff00')).toBeGreaterThan(brightness('#ff0000'))
expect(brightness('#ff0000')).toBeGreaterThan(brightness('#0000ff'))
})
it('takes a three-digit hex', () => {
expect(brightness('#fff')).toBe(1)
})
})
describe('an empty page', () => {
it('takes dark ink on white paper', () => {
expect(folioInk(spread([]), 50, 50).color).toBe(DARK)
})
it('takes light ink on a dark page', () => {
expect(folioInk(spread([], '#101014'), 50, 50).color).toBe(LIGHT)
})
it('treats a page with no colour set as paper', () => {
expect(folioInk(spread([], null), 50, 50).color).toBe(DARK)
})
})
describe('under a shape', () => {
it('takes light ink over a dark fill', () => {
expect(folioInk(spread([shape({ fill: '#111111' })]), 50, 50).color).toBe(LIGHT)
})
it('takes dark ink over a pale fill, even on a dark page', () => {
const s = spread([shape({ fill: '#f5f0e8' })], '#101014')
expect(folioInk(s, 50, 50).color).toBe(DARK)
})
/* The array is paint order, so the last one drawn is the one you see. */
it('asks the topmost element, not the first', () => {
const s = spread([
shape({ id: 'under', fill: '#ffffff' }),
shape({ id: 'over', fill: '#000000' }),
])
expect(folioInk(s, 50, 50).color).toBe(LIGHT)
})
it('ignores a shape the number does not sit on', () => {
const s = spread([shape({ fill: '#000000', frame: { x: 0, y: 0, w: 20, h: 20 } })])
expect(folioInk(s, 80, 80).color).toBe(DARK)
})
/* A nearly transparent panel does not decide what is underneath it. */
it('looks past something barely there', () => {
const s = spread([shape({ fill: '#000000', opacity: 0.15 })])
expect(folioInk(s, 50, 50).color).toBe(DARK)
})
it('looks past a shape with no fill at all', () => {
const s = spread([shape({ fill: 'transparent' })], '#101014')
expect(folioInk(s, 50, 50).color).toBe(LIGHT)
})
})
describe('over a photograph', () => {
/*
* Unknowable without decoding it — and a printed photograph is dark far more
* often than not. White with a hairline of shadow reads on all of them.
*/
it('goes white, with a shadow to survive the pale ones', () => {
const ink = folioInk(spread([photo()]), 50, 50)
expect(ink.color).toBe(LIGHT)
expect(ink.shadow).toBeTruthy()
})
it('adds no shadow anywhere else', () => {
expect(folioInk(spread([]), 50, 50).shadow).toBeUndefined()
expect(folioInk(spread([shape({ fill: '#111' })]), 50, 50).shadow).toBeUndefined()
})
})
describe('type', () => {
/* A paragraph draws letters on nothing; the page behind it is the background. */
it('does not count as a background', () => {
expect(folioInk(spread([text()], '#101014'), 50, 50).color).toBe(LIGHT)
})
})
+178
View File
@@ -0,0 +1,178 @@
import { describe, it, expect } from 'vitest'
import type { BookPageSetup } from '@trek/shared'
import { GRIDS, defaultGridBox, gridElements } from '../../../src/components/Studio/grids'
import { bookPageSetupSchema } from '@trek/shared'
/**
* Photo grids (#1973).
*
* The rules worth pinning are geometric: a grid must tile the box it is given
* without gaps or overlaps, and the block it produces must occupy exactly that
* box — a grid asked to fill the safe area that overhangs it by one gutter is
* a grid that has to be dragged before it is any use.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
const box = { x: 0, y: 0, w: 100, h: 100 }
describe('the grid catalogue', () => {
it('gives every grid a unique id', () => {
const ids = GRIDS.map(g => g.id)
expect(new Set(ids).size).toBe(ids.length)
})
it('gives every grid at least one cell', () => {
for (const grid of GRIDS) expect(grid.cells.length, grid.id).toBeGreaterThan(0)
})
it('keeps every cell inside the unit block', () => {
for (const grid of GRIDS) {
for (const cell of grid.cells) {
expect(cell.x, grid.id).toBeGreaterThanOrEqual(0)
expect(cell.y, grid.id).toBeGreaterThanOrEqual(0)
expect(cell.x + cell.w, grid.id).toBeLessThanOrEqual(1.0001)
expect(cell.y + cell.h, grid.id).toBeLessThanOrEqual(1.0001)
expect(cell.w, grid.id).toBeGreaterThan(0)
expect(cell.h, grid.id).toBeGreaterThan(0)
}
}
})
/*
* Tiling grids cover the block exactly. The staggered and band arrangements
* deliberately do not — they are compositions with air around them — so they
* are checked for "no overlap" only, further down.
*/
it('tiles the block completely, for the grids that are meant to', () => {
const tiling = GRIDS.filter(g => !/stagger|band|filmstrip/.test(g.id))
for (const grid of tiling) {
const area = grid.cells.reduce((sum, c) => sum + c.w * c.h, 0)
expect(area, grid.id).toBeCloseTo(1, 5)
}
})
it('never overlaps two cells', () => {
for (const grid of GRIDS) {
for (let i = 0; i < grid.cells.length; i++) {
for (let j = i + 1; j < grid.cells.length; j++) {
const a = grid.cells[i]
const b = grid.cells[j]
const overlapX = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)
const overlapY = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y)
const overlaps = overlapX > 0.0001 && overlapY > 0.0001
expect(overlaps, `${grid.id}: cell ${i} and ${j}`).toBe(false)
}
}
}
})
})
describe('gridElements', () => {
it('makes one empty photo frame per cell', () => {
const els = gridElements(GRIDS.find(g => g.id === 'grid-4')!, box, 0)
expect(els).toHaveLength(4)
for (const el of els) {
expect(el.kind).toBe('photo')
expect(el.kind === 'photo' && el.photoId).toBeNull()
}
})
it('gives every frame its own id', () => {
const els = gridElements(GRIDS.find(g => g.id === 'grid-9')!, box, 0)
expect(new Set(els.map(e => e.id)).size).toBe(els.length)
})
it('fills the box exactly when there is no gutter', () => {
const els = gridElements(GRIDS.find(g => g.id === 'grid-4')!, box, 0)
const left = Math.min(...els.map(e => e.frame.x))
const top = Math.min(...els.map(e => e.frame.y))
const right = Math.max(...els.map(e => e.frame.x + e.frame.w))
const bottom = Math.max(...els.map(e => e.frame.y + e.frame.h))
expect(left).toBeCloseTo(0, 6)
expect(top).toBeCloseTo(0, 6)
expect(right).toBeCloseTo(100, 6)
expect(bottom).toBeCloseTo(100, 6)
})
/*
* The gutter comes out of the cells, not out of the block. Added between them
* instead, a four-across grid would be three gutters wider than the box it
* was told to fill, and would hang off the safe area it was aligned to.
*/
it('keeps the block inside its box once a gutter is applied', () => {
const els = gridElements(GRIDS.find(g => g.id === 'grid-6')!, box, 4)
for (const el of els) {
expect(el.frame.x).toBeGreaterThanOrEqual(-0.001)
expect(el.frame.y).toBeGreaterThanOrEqual(-0.001)
expect(el.frame.x + el.frame.w).toBeLessThanOrEqual(100.001)
expect(el.frame.y + el.frame.h).toBeLessThanOrEqual(100.001)
}
})
it('leaves the block edges flush and only splits the interior gaps', () => {
const gutter = 6
const els = gridElements(GRIDS.find(g => g.id === 'two-across')!, box, gutter)
const [a, b] = [...els].sort((x, y) => x.frame.x - y.frame.x)
// Outer edges untouched...
expect(a.frame.x).toBeCloseTo(0, 6)
expect(b.frame.x + b.frame.w).toBeCloseTo(100, 6)
// ...and exactly one gutter between them.
expect(b.frame.x - (a.frame.x + a.frame.w)).toBeCloseTo(gutter, 6)
})
it('offsets the whole block when the box does not start at the origin', () => {
const els = gridElements(GRIDS.find(g => g.id === 'single')!, { x: 20, y: 30, w: 50, h: 40 }, 0)
expect(els[0].frame).toMatchObject({ x: 20, y: 30, w: 50, h: 40 })
})
it('never produces a frame too small to see, even from a tiny box', () => {
const els = gridElements(GRIDS.find(g => g.id === 'grid-12')!, { x: 0, y: 0, w: 8, h: 8 }, 6)
for (const el of els) {
expect(el.frame.w).toBeGreaterThanOrEqual(2)
expect(el.frame.h).toBeGreaterThanOrEqual(2)
}
})
it('carries the corner radius onto every frame', () => {
const els = gridElements(GRIDS.find(g => g.id === 'grid-4')!, box, 3, 5)
for (const el of els) expect(el.kind === 'photo' && el.radius).toBe(5)
})
it('produces frames for every grid in the catalogue without a bad number', () => {
for (const grid of GRIDS) {
for (const el of gridElements(grid, box, 3)) {
for (const v of [el.frame.x, el.frame.y, el.frame.w, el.frame.h]) {
expect(Number.isFinite(v), grid.id).toBe(true)
}
}
}
})
})
describe('defaultGridBox', () => {
it('spans both pages of a spread', () => {
const b = defaultGridBox(page, false)
expect(b.x + b.w).toBeCloseTo(page.pageWidth * 2 - b.x, 6)
expect(b.w).toBeGreaterThan(page.pageWidth)
})
it('stays on one page for a cover', () => {
const b = defaultGridBox(page, true)
expect(b.x + b.w).toBeLessThanOrEqual(page.pageWidth)
})
it('keeps clear of the safe area rather than landing on it', () => {
const b = defaultGridBox(page, true)
expect(b.x).toBeGreaterThanOrEqual(page.safe)
expect(b.y).toBeGreaterThanOrEqual(page.safe)
})
it('is symmetric, so a grid dropped into it looks centred', () => {
const b = defaultGridBox(page, false)
expect(b.x).toBeCloseTo(page.pageWidth * 2 - (b.x + b.w), 6)
expect(b.y).toBeCloseTo(page.pageHeight - (b.y + b.h), 6)
})
})
@@ -0,0 +1,208 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import { bookIconElementSchema, bookPageSetupSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import {
FEATURED_ICONS, ICON_NAMES, iconLabel, searchIcons,
} from '../../../src/components/Studio/iconLibrary'
/**
* The icon element (#1973).
*
* An icon is the one thing on a Studio page that is not drawn in this repo. The
* document stores a name and trusts lucide to still know it, which is what these
* protect at both ends: that the mark reaches the page with the weight and the
* colour somebody chose, and that a name the library has since renamed costs a
* drawing rather than the page it stood on.
*
* The list the picker is built from matters for the same reason. lucide exports
* every drawing three times, so a list taken straight from the namespace shows
* every glyph three times and makes the search box look broken.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
/* Deliberately not square: an icon has to keep its shape in a frame that has not. */
const icon = (over: Record<string, unknown> = {}): BookElement => bookIconElementSchema.parse({
id: 'i1', kind: 'icon', frame: { x: 10, y: 20, w: 80, h: 60 }, name: 'Compass', ...over,
})
function draw(elements: BookElement[]) {
const spread: BookSpread = {
id: 's1', role: 'inner', background: null, elements, parked: [], entryId: null,
}
return render(<SpreadView spread={spread} page={page} />)
}
/** The sheet is a div inside Testing Library's container; the elements sit inside it. */
function firstElement(container: HTMLElement): HTMLElement {
return container.firstElementChild!.firstElementChild as HTMLElement
}
describe('an icon on the page', () => {
it('draws the named lucide glyph as an SVG', () => {
const { container } = draw([icon({ name: 'Compass' })])
const svg = container.querySelector('svg')!
expect(svg).not.toBeNull()
// lucide names the drawing it rendered, which is how we know the stored
// name was resolved rather than some default standing in for it.
expect(svg.getAttribute('class')).toContain('lucide-compass')
expect(svg.children.length).toBeGreaterThan(0)
})
it('strokes the drawing in the colour the element carries', () => {
const { container } = draw([icon({ color: '#c81e4a' })])
expect(container.querySelector('svg')!.getAttribute('stroke')).toBe('#c81e4a')
})
/*
* The weight is against lucide's own 24-unit grid, not millimetres, so it has
* to arrive unscaled: an icon set 60mm across with a hairline is a diagram
* rather than a mark, and a stroke silently converted to a length would be
* exactly that.
*/
it('sets the stroke to the stored line width, against lucide\'s own grid', () => {
const { container } = draw([icon({ lineWidth: 3.5 })])
const svg = container.querySelector('svg')!
expect(svg.getAttribute('stroke-width')).toBe('3.5')
expect(svg.getAttribute('viewBox')).toBe('0 0 24 24')
})
it('carries a hairline through just as faithfully as a heavy stroke', () => {
const { container } = draw([icon({ lineWidth: 0.25 })])
expect(container.querySelector('svg')!.getAttribute('stroke-width')).toBe('0.25')
})
/*
* A shape is scaled by moving its points and looks deliberate at any ratio.
* A stroked drawing does not: a compass pulled to twice its width reads as a
* mistake. So the drawing fills the frame but is never told to ignore its
* aspect ratio, and the box centres what is left over.
*/
it('fills the frame without being stretched out of shape', () => {
const { container } = draw([icon()])
const svg = container.querySelector('svg')!
expect(svg.style.width).toBe('100%')
expect(svg.style.height).toBe('100%')
expect(svg.getAttribute('preserveAspectRatio')).toBeNull()
const box = firstElement(container)
expect(box.style.alignItems).toBe('center')
expect(box.style.justifyContent).toBe('center')
})
it('sits where the frame puts it, in millimetres like everything else', () => {
const box = firstElement(draw([icon()]).container)
expect(box.style.left).toBe('10mm')
expect(box.style.top).toBe('20mm')
expect(box.style.width).toBe('80mm')
expect(box.style.height).toBe('60mm')
})
/*
* A book outlives the library it was made with. Whatever happens when a name
* goes, the page has to keep printing, so the missing drawing becomes the same
* fallback the plugin list uses rather than an empty rectangle.
*/
it('draws the fallback, not a hole, when lucide no longer knows the name', () => {
expect(ICON_NAMES).not.toContain('CarrierPigeon')
const { container } = draw([icon({ name: 'CarrierPigeon', color: '#0f766e', lineWidth: 1.5 })])
const svg = container.querySelector('svg')
expect(svg).not.toBeNull()
expect(svg!.children.length).toBeGreaterThan(0)
expect(svg!.getAttribute('class')).toContain('lucide-blocks')
// Still the element's own mark: the fallback inherits the choices made for
// the drawing it stands in for.
expect(svg!.getAttribute('stroke')).toBe('#0f766e')
expect(svg!.getAttribute('stroke-width')).toBe('1.5')
})
})
describe('the icon list the picker is built from', () => {
it('holds the whole of lucide, over a thousand drawings', () => {
expect(ICON_NAMES.length).toBeGreaterThan(1000)
expect(ICON_NAMES).toContain('Plane')
expect(ICON_NAMES).toContain('MountainSnow')
})
it('leaves out the Lucide-prefixed alias of a name it already has', () => {
expect(ICON_NAMES).not.toContain('LucidePlane')
const present = new Set(ICON_NAMES)
const aliases = ICON_NAMES.filter(n => n.startsWith('Lucide') && present.has(n.slice(6)))
expect(aliases).toEqual([])
})
it('leaves out the Icon-suffixed alias of a name it already has', () => {
expect(ICON_NAMES).not.toContain('PlaneIcon')
const present = new Set(ICON_NAMES)
const aliases = ICON_NAMES.filter(n => n.endsWith('Icon') && present.has(n.slice(0, -4)))
expect(aliases).toEqual([])
})
it('comes out sorted, so the grid does not have to sort it again', () => {
const outOfOrder = ICON_NAMES.filter((name, i) => i > 0 && ICON_NAMES[i - 1].localeCompare(name) > 0)
expect(outOfOrder).toEqual([])
})
})
describe('searching the icon list', () => {
it('finds a compound name by its first word', () => {
expect(searchIcons('mountain')).toContain('MountainSnow')
})
/* The second half is the part somebody types when they want the snowy one. */
it('finds a compound name by its second word', () => {
expect(searchIcons('snow')).toContain('MountainSnow')
})
it('finds it from both words, in either order', () => {
expect(searchIcons('snow mountain')).toContain('MountainSnow')
expect(searchIcons('mountain snow')).toContain('MountainSnow')
})
it('ignores case and stray spacing', () => {
expect(searchIcons('MOUNTAIN')).toContain('MountainSnow')
expect(searchIcons(' Snow ')).toContain('MountainSnow')
})
it('narrows as words are added rather than widening', () => {
const snow = searchIcons('snow')
const both = searchIcons('snow mountain')
expect(snow.length).toBeGreaterThan(both.length)
expect(both.every(name => snow.includes(name))).toBe(true)
})
it('returns the whole library when nothing has been typed', () => {
expect(searchIcons('')).toEqual(ICON_NAMES)
expect(searchIcons(' ')).toEqual(ICON_NAMES)
})
it('returns nothing for a word no drawing has', () => {
expect(searchIcons('zzzznotathing')).toEqual([])
})
})
describe('names and the starter shelf', () => {
it('spaces a PascalCase name out for the tooltip', () => {
expect(iconLabel('MountainSnow')).toBe('Mountain Snow')
expect(iconLabel('CloudRain')).toBe('Cloud Rain')
expect(iconLabel('Plane')).toBe('Plane')
})
/*
* The shelf is a hand-written list, so it is the one place a lucide rename
* would show up as a row of fallback glyphs. It is filtered against the real
* exports, and this is what keeps that filter honest.
*/
it('opens on drawings this version of lucide really has', () => {
expect(FEATURED_ICONS.length).toBeGreaterThan(0)
const missing = FEATURED_ICONS.filter(name => !ICON_NAMES.includes(name))
expect(missing).toEqual([])
})
})
+552
View File
@@ -0,0 +1,552 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import type { BookDocument, BookElement, BookPageNumbers, BookPageSetup } from '@trek/shared'
import {
bookIconElementSchema, bookPageSetupSchema, bookPhotoElementSchema,
bookShapeElementSchema, bookTextElementSchema,
} from '@trek/shared'
import { fireEvent, render } from '../../helpers/render'
import { StudioInspector } from '../../../src/components/Studio/StudioInspector'
import { useStudioStore } from '../../../src/store/studioStore'
import type { JourneySource } from '../../../src/components/Studio/StudioSidebar'
/**
* The inspector, control by control (#1973).
*
* The panel was rebuilt: same job, new shape. Duplicate, lock and delete moved
* out of a section and into the head, half the groups now start folded, every
* boolean became the app's switch, and the number fields stopped writing on
* every keystroke. Nothing in the suite rendered this panel, so any one of
* those controls could have come out of the rebuild writing nothing at all and
* the only thing that would have noticed was somebody laying out a book.
*
* So the assertions here are about the document rather than about the markup:
* what is protected is that the control still writes the field it used to
* write. Where a control has a rule of its own, that rule is pinned too: a
* shape cannot be made invisible, choosing a coordinate notation is not an
* override, an emptied number field leaves the value alone.
*/
const FRAME = { x: 20, y: 30, w: 60, h: 40 }
const text = (over: Record<string, unknown> = {}): BookElement =>
bookTextElementSchema.parse({ id: 't1', kind: 'text', frame: FRAME, text: 'Harbour', ...over }) as BookElement
const photo = (over: Record<string, unknown> = {}): BookElement =>
bookPhotoElementSchema.parse({ id: 'p1', kind: 'photo', frame: FRAME, ...over }) as BookElement
const shape = (over: Record<string, unknown> = {}): BookElement =>
bookShapeElementSchema.parse({ id: 's1', kind: 'shape', frame: FRAME, ...over }) as BookElement
const icon = (over: Record<string, unknown> = {}): BookElement =>
bookIconElementSchema.parse({ id: 'i1', kind: 'icon', frame: FRAME, name: 'Plane', ...over }) as BookElement
const setup = (folios: Partial<BookPageNumbers> = {}): BookPageSetup => bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5, pageNumbers: folios,
})
/** One entry with a point on it, so a coordinate mark has something to re-read. */
const source: JourneySource = {
entries: [{
id: 7, title: 'Bergen', story: null, location: 'Bergen', date: '2026-05-01',
lat: 60.3913, lng: 5.3221, mood: null, weather: null, pros: [], cons: [],
}],
photos: [],
photoEntries: {},
}
function load(elements: BookElement[], selection = elements.slice(0, 1).map(e => e.id)) {
useStudioStore.getState().load({
version: 1, title: 'T', page: setup(), spreads: [
{ id: 'sp1', role: 'inner', background: null, elements, parked: [], entryId: null },
],
} as BookDocument)
useStudioStore.getState().select(selection)
}
function draw(over: { page?: BookPageSetup; setPageNumbers?: (p: Partial<BookPageNumbers>) => void } = {}) {
return render(
<StudioInspector
spreadIndex={0}
page={over.page ?? setup()}
stats={null}
source={source}
setPageNumbers={over.setPageNumbers ?? (() => {})}
t={(k: string) => k}
locale="en"
/>,
)
}
/** What the store holds now, which is the thing every assertion here is about. */
const el = (i = 0) => useStudioStore.getState().doc!.spreads[0].elements[i]
const elements = () => useStudioStore.getState().doc!.spreads[0].elements
// ── Reaching the controls ──────────────────────────────────────────────────
function head(c: HTMLElement, label: string): HTMLElement {
const found = [...c.querySelectorAll('.st-section-head')]
.find(b => b.querySelector('.st-section-label')?.textContent === label)
return found as HTMLElement
}
/** Half the panel starts folded, so a control inside one has to be uncovered. */
function open(c: HTMLElement, label: string) {
const button = head(c, label)
if (button.getAttribute('aria-expanded') === 'false') fireEvent.click(button)
}
function num(c: HTMLElement, label: string): HTMLInputElement {
const span = [...c.querySelectorAll('.st-num-label')].find(s => s.textContent === label)
return span!.closest('.st-num')!.querySelector('input') as HTMLInputElement
}
/** Every number field the panel is currently showing, by label. */
const numLabels = (c: HTMLElement) => [...c.querySelectorAll('.st-num-label')].map(s => s.textContent)
/** Type and leave, which is the only thing that commits a number now. */
function typeNum(c: HTMLElement, label: string, value: string) {
const input = num(c, label)
fireEvent.change(input, { target: { value } })
fireEvent.blur(input)
}
function line(c: HTMLElement, label: string): HTMLElement {
const found = [...c.querySelectorAll('.st-line')]
.find(l => l.querySelector('.st-line-label')?.textContent === label)
return found as HTMLElement
}
/** The swatch row on one named line, so fill and stroke stay told apart. */
function pickSwatch(c: HTMLElement, lineLabel: string, hex: string) {
fireEvent.click(line(c, lineLabel).querySelector(`[aria-label="${hex}"]`)!)
}
/** One of several: a chip that reads as chosen. */
function pick(c: HTMLElement, label: string) {
const chip = [...c.querySelectorAll('[role="radio"]')].find(b => b.textContent === label)
fireEvent.click(chip!)
}
/** On or off: the app switch, on its own line beside the words. */
function toggle(c: HTMLElement, label: string) {
const row = [...c.querySelectorAll('.st-switch')]
.find(s => s.querySelector('.st-switch-label')?.textContent === label)
fireEvent.click(row!.querySelector('button')!)
}
beforeEach(() => {
useStudioStore.getState().load({
version: 1, title: 'T', page: setup(), spreads: [],
} as unknown as BookDocument)
})
// ── The head ───────────────────────────────────────────────────────────────
describe('the panel head', () => {
it('says what is selected', () => {
load([text()])
const { container } = draw()
expect(container.querySelector('.st-what')!.textContent).toContain('journey.studio.kind.text')
})
it('says how many, once there is more than one', () => {
load([text(), shape()], ['t1', 's1'])
const { container } = draw()
const what = container.querySelector('.st-what')!.textContent!
expect(what).toContain('journey.studio.multiple')
expect(what).toContain('2')
})
it('duplicates the selection into the spread', () => {
load([text()])
const { container } = draw()
fireEvent.click(container.querySelector('[aria-label="journey.studio.duplicate"]')!)
expect(elements()).toHaveLength(2)
// Offset, so the copy is a second thing rather than an exact overlay.
expect(elements()[1].frame).toMatchObject({ x: 24, y: 34 })
})
it('locks and unlocks, and the button says which it is', () => {
load([text()])
const { container } = draw()
fireEvent.click(container.querySelector('[aria-label="journey.studio.lock"]')!)
expect(el()).toMatchObject({ locked: true })
const unlock = container.querySelector('[aria-label="journey.studio.unlock"]')!
expect(unlock.getAttribute('aria-pressed')).toBe('true')
fireEvent.click(unlock)
expect(el()).toMatchObject({ locked: false })
})
it('deletes the selection and nothing else', () => {
load([text(), shape()], ['t1'])
const { container } = draw()
fireEvent.click(container.querySelector('[aria-label="journey.studio.delete"]')!)
expect(elements().map(e => e.id)).toEqual(['s1'])
expect(useStudioStore.getState().selection).toEqual([])
})
})
// ── Text ───────────────────────────────────────────────────────────────────
describe('a text element', () => {
it('takes the words typed into it, and stops re-reading its source', () => {
load([text()])
const { container } = draw()
fireEvent.change(container.querySelector('.st-textarea')!, { target: { value: 'Bergen harbour' } })
expect(el()).toMatchObject({ text: 'Bergen harbour', overridden: true })
})
it('sets the weight', () => {
load([text()])
const { container } = draw()
pick(container, '600')
expect(el()).toMatchObject({ weight: 600 })
})
it('sets the alignment', () => {
load([text()])
const { container } = draw()
fireEvent.click(container.querySelector('[aria-label="right"]')!)
expect(el()).toMatchObject({ align: 'right' })
})
/* Italic was drawn by the renderer and had no control at all before. */
it('sets italic, and the button reflects it', () => {
load([text()])
const { container } = draw()
fireEvent.click(container.querySelector('[aria-label="journey.studio.italic"]')!)
expect(el()).toMatchObject({ italic: true })
expect(container.querySelector('[aria-label="journey.studio.italic"]')!.getAttribute('aria-pressed'))
.toBe('true')
})
it('sets the size, the leading and the tracking', () => {
load([text()])
const { container } = draw()
typeNum(container, 'journey.studio.size', '18')
typeNum(container, 'journey.studio.leading', '1.8')
typeNum(container, 'journey.studio.tracking', '0.12')
expect(el()).toMatchObject({ size: 18, leading: 1.8, tracking: 0.12 })
})
it('sets the colour', () => {
load([text()])
const { container } = draw()
pickSwatch(container, 'journey.studio.text', '#9f1239')
expect(el()).toMatchObject({ color: '#9f1239' })
})
it('asks nothing about notation when the text is not a point', () => {
load([text()])
const { container } = draw()
expect(line(container, 'journey.studio.coordsMark')).toBeUndefined()
})
})
describe('a text element bound to a stop', () => {
const bound = () => text({
text: '60 deg N, 5 deg E',
binding: { source: 'entry.location', entryId: 7, format: 'dms' },
})
it('offers the two notations', () => {
load([bound()])
const { container } = draw()
expect(line(container, 'journey.studio.coordsMark')).toBeDefined()
})
/*
* Both halves, in one step. Rewriting only the binding leaves the old words
* on the page until the next open, which reads as a control that does
* nothing, and choosing a notation is not writing the text: `overridden` has
* to stay off or the mark would stop following the journal.
*/
it('rewrites the binding and the words together, without claiming an override', () => {
load([bound()])
const { container } = draw()
pick(container, 'journey.studio.coordsDecimal')
expect(el()).toMatchObject({
binding: { source: 'entry.location', entryId: 7, format: 'decimal' },
text: expect.stringContaining('60.3913° N'),
overridden: false,
})
})
})
// ── Photo ──────────────────────────────────────────────────────────────────
describe('a photo frame', () => {
it('sets the crop, the look and the frame style', () => {
load([photo({ photoId: 12 })])
const { container } = draw()
pick(container, 'journey.studio.fit.contain')
pick(container, 'journey.studio.filter.bw')
pick(container, 'journey.studio.polaroidFrame')
expect(el()).toMatchObject({ fit: 'contain', filter: 'bw', frameStyle: 'polaroid' })
})
/*
* An empty frame has no picture to aim at, and asking for one by id produced
* a request for /api/photos/null/thumbnail under a caption telling you to
* drag the point around.
*/
it('offers no focal point while the frame is empty', () => {
load([photo({ photoId: null })])
const { container } = draw()
expect(container.querySelector('.st-focal')).toBeNull()
expect(container.textContent).toContain('journey.studio.emptyFrame')
})
it('offers one once there is a picture in it', () => {
load([photo({ photoId: 12 })])
const { container } = draw()
expect(container.querySelector('.st-focal')).not.toBeNull()
expect(container.querySelector('.st-focal img')!.getAttribute('src'))
.toBe('/api/photos/12/thumbnail')
})
/* A radius and a mask are the same idea at two resolutions, and a radius the
renderer ignores once a shape is cut is a control that lies. */
it('drops the corner radius once the picture is cut to a shape', () => {
load([photo({ photoId: 12, mask: null })])
const plain = draw()
expect(numLabels(plain.container)).toContain('journey.studio.radius')
plain.unmount()
load([photo({ photoId: 12, mask: 'heart' })])
expect(numLabels(draw().container)).not.toContain('journey.studio.radius')
})
})
// ── Shape ──────────────────────────────────────────────────────────────────
describe('a shape', () => {
/* Swapping rather than deleting and re-adding is the whole point of the
grid: the thing on the page keeps where it is and what colour it is. */
it('keeps its position and its colour when the shape is swapped', () => {
load([shape({ shape: 'rect', fill: '#c2410c' })])
const { container } = draw()
fireEvent.click(container.querySelector('.st-mini-shapes [aria-label="ellipse"]')!)
expect(el()).toMatchObject({ shape: 'ellipse', fill: '#c2410c', frame: FRAME })
})
it('writes the fill and the outline separately', () => {
load([shape({ fill: '#111827', stroke: null, strokeWidth: 0 })])
const { container } = draw()
pickSwatch(container, 'journey.studio.fill', '#0f766e')
expect(el()).toMatchObject({ fill: '#0f766e', stroke: null })
pickSwatch(container, 'journey.studio.stroke', '#1e3a8a')
// A colour with no width would draw nothing, so the line gets one.
expect(el()).toMatchObject({ fill: '#0f766e', stroke: '#1e3a8a', strokeWidth: 0.5 })
})
/*
* The rule that matters here: a shape with neither fill nor stroke is a
* shape nobody can see or find again, so turning the fill off has to bring
* the outline on with it.
*/
it('cannot be turned invisible by switching the fill off', () => {
load([shape({ fill: '#111827', stroke: null, strokeWidth: 0 })])
const { container } = draw()
toggle(container, 'journey.studio.fillOn')
expect(el()).toMatchObject({ fill: null, stroke: '#141414', strokeWidth: 0.5 })
})
it('brings the fill back when it is switched on again', () => {
load([shape({ fill: null, stroke: '#141414', strokeWidth: 0.5 })])
const { container } = draw()
toggle(container, 'journey.studio.fillOn')
expect(el()).toMatchObject({ fill: '#111111', stroke: '#141414' })
})
it('fades the fill, and takes a direction once it does', () => {
load([shape()])
const { container } = draw()
toggle(container, 'journey.studio.gradient')
expect(el()).toMatchObject({ gradient: 'down' })
pick(container, 'journey.studio.gradientUp')
expect(el()).toMatchObject({ gradient: 'up' })
})
})
// ── Icon ───────────────────────────────────────────────────────────────────
describe('an icon', () => {
it('narrows the swap grid to what was searched for', () => {
load([icon()])
const { container } = draw()
const all = container.querySelectorAll('.st-mini-shape').length
fireEvent.change(container.querySelector('[aria-label="journey.studio.searchIcons"]')!, {
target: { value: 'compass' },
})
const found = container.querySelectorAll('.st-mini-shape').length
expect(found).toBeGreaterThan(0)
expect(found).toBeLessThan(all)
expect(container.querySelector('[aria-label="Compass"]')).not.toBeNull()
})
it('swaps the drawing, keeping everything else about the element', () => {
load([icon({ name: 'Plane', color: '#9f1239' })])
const { container } = draw()
fireEvent.change(container.querySelector('[aria-label="journey.studio.searchIcons"]')!, {
target: { value: 'compass' },
})
fireEvent.click(container.querySelector('[aria-label="Compass"]')!)
expect(el()).toMatchObject({ name: 'Compass', color: '#9f1239', frame: FRAME })
})
it('sets how heavy the drawing is', () => {
load([icon()])
const { container } = draw()
typeNum(container, 'journey.studio.lineWidth', '3')
expect(el()).toMatchObject({ lineWidth: 3 })
})
})
// ── The frame's numbers ────────────────────────────────────────────────────
describe('the position group', () => {
it('is folded away until it is asked for', () => {
load([shape()])
const { container } = draw()
expect(head(container, 'journey.studio.position').getAttribute('aria-expanded')).toBe('false')
expect(numLabels(container)).not.toContain('journey.studio.width')
open(container, 'journey.studio.position')
expect(numLabels(container)).toContain('journey.studio.width')
})
/* One value is one undo step. It used to be one per keystroke, so typing
"120" buried the previous state three steps down the stack. */
it('writes a width once, when the field is left rather than while it is typed', () => {
load([shape()])
const { container } = draw()
open(container, 'journey.studio.position')
const input = num(container, 'journey.studio.width')
fireEvent.change(input, { target: { value: '120' } })
expect(el().frame.w).toBe(60)
fireEvent.blur(input)
expect(el().frame.w).toBe(120)
expect(useStudioStore.getState().past).toHaveLength(1)
})
it('clamps a width below the minimum rather than taking it', () => {
load([shape()])
const { container } = draw()
open(container, 'journey.studio.position')
typeNum(container, 'journey.studio.width', '1')
expect(el().frame.w).toBe(4)
})
/* An emptied field used to collapse the element to zero on the keystroke
that emptied it, which typing the number back does not undo. */
it('leaves the width alone when the field is emptied', () => {
load([shape()])
const { container } = draw()
open(container, 'journey.studio.position')
typeNum(container, 'journey.studio.width', '')
expect(el().frame.w).toBe(60)
expect(useStudioStore.getState().past).toHaveLength(0)
})
it('turns and fades the element from the same group', () => {
load([shape()])
const { container } = draw()
open(container, 'journey.studio.position')
typeNum(container, 'journey.studio.rotation', '15')
typeNum(container, 'journey.studio.opacity', '40')
expect(el()).toMatchObject({ rotation: 15, opacity: 0.4 })
})
})
// ── Nothing selected ───────────────────────────────────────────────────────
describe('with nothing selected', () => {
it('turns page numbers on', () => {
load([])
const setPageNumbers = vi.fn()
const { container } = draw({ setPageNumbers })
toggle(container, 'journey.studio.pageNumbers')
expect(setPageNumbers).toHaveBeenCalledWith({ show: true })
})
it('sets where they sit', () => {
load([])
const setPageNumbers = vi.fn()
const { container } = draw({ page: setup({ show: true }), setPageNumbers })
pick(container, 'journey.studio.folio.inner')
expect(setPageNumbers).toHaveBeenCalledWith({ position: 'inner' })
})
it('sets the first number, the size and the margin', () => {
load([])
const setPageNumbers = vi.fn()
const { container } = draw({ page: setup({ show: true }), setPageNumbers })
typeNum(container, 'journey.studio.folioStart', '12')
typeNum(container, 'journey.studio.size', '10')
typeNum(container, 'journey.studio.folioMargin', '20')
expect(setPageNumbers).toHaveBeenCalledWith({ startAt: 12 })
expect(setPageNumbers).toHaveBeenCalledWith({ size: 10 })
expect(setPageNumbers).toHaveBeenCalledWith({ margin: 20 })
})
it('turns the automatic colour off, and picking one turns it off too', () => {
load([])
const setPageNumbers = vi.fn()
const { container } = draw({ page: setup({ show: true }), setPageNumbers })
toggle(container, 'journey.studio.folioAuto')
expect(setPageNumbers).toHaveBeenCalledWith({ autoColor: false })
pickSwatch(container, 'journey.studio.colour', '#111111')
expect(setPageNumbers).toHaveBeenCalledWith({ color: '#111111', autoColor: false })
})
})
@@ -0,0 +1,558 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { BookDocument, BookElement, JourneyStats } from '@trek/shared'
import {
bookBadgeElementSchema, bookCountriesElementSchema, bookListElementSchema,
bookMapElementSchema, bookPageSetupSchema, bookStatsElementSchema, journeyStatsSchema,
} from '@trek/shared'
import { fireEvent, render, screen, within } from '../../helpers/render'
import { StudioInspector } from '../../../src/components/Studio/StudioInspector'
import { useStudioStore } from '../../../src/store/studioStore'
/**
* The inspector, on the five travel elements (#1973).
*
* The panel was rebuilt: same functions, new structure. Sections fold, booleans
* are the app's switch instead of a chip, a set of several carries a tick, and
* duplicate, lock and delete moved out of "Arrange" and into the panel head.
* Nothing in the suite rendered the inspector at all, so a control that came
* out of that rebuild wired to nothing would have been found in a printed book
* rather than here.
*
* Two rules for what follows. The whole inspector is mounted rather than the
* travel half on its own, because the tail every travel element shares, type,
* colour, position, arrange, is drawn by the outer panel. And what is asserted
* is the document the store holds, not the markup: the question is whether a
* control still writes the field it used to write, whichever section it now
* lives in.
*/
const page = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5,
})
const frame = { x: 10, y: 10, w: 120, h: 90 }
/** A journey with figures no element below starts out agreeing with. */
const stats: JourneyStats = journeyStatsSchema.parse({
journeyId: 1,
distance: 1234, days: 5, steps: 7, photos: 12, places: 9, furthest: 400,
countries: [{ code: 'IS', name: 'Iceland', places: 9, firstVisit: '2026-01-01' }],
points: [
{ lat: 64.14, lng: -21.94, label: 'Reykjavik', date: '2026-01-01', country: 'IS' },
{ lat: 65.68, lng: -18.09, label: 'Akureyri', date: '2026-01-04', country: 'IS' },
],
start: '2026-01-01', end: '2026-01-05',
})
const mapEl = (over: Record<string, unknown> = {}): BookElement => bookMapElementSchema.parse({
id: 'm1', kind: 'map', frame, countries: ['IS'],
points: [{ lat: 64.14, lng: -21.94, label: 'Reykjavik' }],
...over,
}) as BookElement
const statsEl = (over: Record<string, unknown> = {}): BookElement => bookStatsElementSchema.parse({
id: 's1', kind: 'stats', frame, ...over,
}) as BookElement
const countriesEl = (over: Record<string, unknown> = {}): BookElement => bookCountriesElementSchema.parse({
id: 'c1', kind: 'countries', frame, codes: ['IS', 'NO'], names: ['Iceland', 'Norway'], ...over,
}) as BookElement
const badgeEl = (over: Record<string, unknown> = {}): BookElement => bookBadgeElementSchema.parse({
id: 'b1', kind: 'badge', frame, variant: 'flag', code: 'IS', text: 'ICELAND', ...over,
}) as BookElement
const listEl = (over: Record<string, unknown> = {}): BookElement => bookListElementSchema.parse({
id: 'l1', kind: 'list', frame,
items: [{ text: 'Warm all week', tone: 'pro' }, { text: 'Ferry was late', tone: 'con' }],
proLabel: 'Pros', conLabel: 'Cons',
...over,
}) as BookElement
function show(el: BookElement, live: JourneyStats | null = null) {
useStudioStore.getState().load({
version: 1, title: 'T', page,
spreads: [{ id: 'sp1', role: 'inner', background: null, elements: [el], parked: [], entryId: null }],
} as BookDocument)
useStudioStore.getState().select([el.id])
return render(
<StudioInspector
spreadIndex={0}
page={page}
stats={live}
source={{ entries: [], photos: [], photoEntries: {} }}
setPageNumbers={() => {}}
t={k => k}
locale="en"
/>,
)
}
/** The element as the store holds it. Every assertion below reads this. */
function saved(): Record<string, unknown> {
return useStudioStore.getState().doc!.spreads[0].elements[0] as unknown as Record<string, unknown>
}
/** One of a few. */
const pick = (name: string) => fireEvent.click(screen.getByRole('radio', { name }))
/** One of a set, which carries a tick. */
const tick = (name: string) => fireEvent.click(screen.getByRole('checkbox', { name }))
/** A switch, or any plain button: both answer to their accessible name. */
const press = (name: string) => fireEvent.click(screen.getByRole('button', { name }))
/** A section by its heading, since a label can repeat across sections. */
function section(container: HTMLElement, label: string): HTMLElement {
const found = [...container.querySelectorAll<HTMLElement>('.st-section')]
.find(s => s.querySelector('.st-section-label')?.textContent === label)
if (!found) throw new Error(`no section headed ${label}`)
return found
}
/** Some sections start folded, so a control inside one has to be uncovered. */
function open(container: HTMLElement, label: string) {
fireEvent.click(section(container, label).querySelector('.st-section-head')!)
}
/** The control side of one labelled line inside one section. */
function lineIn(container: HTMLElement, sectionLabel: string, lineLabel: string): HTMLElement {
const row = [...section(container, sectionLabel).querySelectorAll<HTMLElement>('.st-line')]
.find(l => l.querySelector('.st-line-label')?.textContent === lineLabel)
if (!row) throw new Error(`no line labelled ${lineLabel} under ${sectionLabel}`)
return row.querySelector<HTMLElement>('.st-line-body')!
}
beforeEach(() => {
useStudioStore.getState().load({ version: 1, title: 'T', page, spreads: [] } as unknown as BookDocument)
})
describe('the route map', () => {
it('takes the tiles and the credit from the source it is switched to', () => {
show(mapEl())
pick('journey.studio.mapSourceSatellite')
expect(saved().source).toBe('tiles')
expect(saved().tileUrl).toContain('tiles.maps.eox.at')
// The credit travels with the source, or the page prints the wrong one —
// and this one is CC BY, so printing it uncredited is a licence breach
// rather than a discourtesy.
expect(saved().attribution).toContain('EOX')
})
/*
* The planner's own street tiles and Mapbox are no longer offered: one is a
* street map that reads as a screenshot on paper and whose server asks people
* not to bulk-fetch, the other needs written permission before anything is
* printed. Removing an option must not remove a page, though.
*/
it('still offers the source a map already uses, even one no longer recommended', () => {
show(mapEl({
source: 'tiles',
tileUrl: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: '© OpenStreetMap contributors',
}))
const chip = screen.getByRole('radio', { name: 'journey.studio.mapSourceTiles' })
expect(chip.getAttribute('aria-checked')).toBe('true')
})
it('does not offer it on a map that never used it', () => {
show(mapEl())
expect(screen.queryByRole('radio', { name: 'journey.studio.mapSourceTiles' })).toBeNull()
expect(screen.queryByRole('radio', { name: 'journey.studio.mapSourceStatic' })).toBeNull()
})
it('writes the drawn style', () => {
show(mapEl())
pick('journey.studio.mapStyle.paper')
expect(saved().style).toBe('paper')
})
it('fits the stops rather than the countries, and back again', () => {
show(mapEl())
expect(saved().fitToCountries).toBe(true)
pick('journey.studio.mapFitStops')
expect(saved().fitToCountries).toBe(false)
pick('journey.studio.mapFitCountry')
expect(saved().fitToCountries).toBe(true)
})
it('writes how much room is left around what is drawn', () => {
show(mapEl())
pick('journey.studio.mapPadWide')
expect(saved().fitPadding).toBe(0.5)
pick('journey.studio.mapPadTight')
expect(saved().fitPadding).toBe(0.04)
})
it('cuts the picture to the coastline when the shape is switched', () => {
show(mapEl())
pick('journey.studio.mapClipCountry')
expect(saved().clip).toBe('country')
})
/* A country-shaped hole with no country to cut against is a filled box. */
it('refuses the country shape on a map that knows no countries', () => {
show(mapEl({ countries: [] }))
const chip = screen.getByRole('radio', { name: 'journey.studio.mapClipCountry' })
expect(chip).toBeDisabled()
fireEvent.click(chip)
expect(saved().clip).toBe('rect')
})
it('writes a zoom from the folded group, and hands it back automatically', () => {
const { container } = show(mapEl({ source: 'tiles', tileUrl: 'https://tile.example/{z}/{x}/{y}.png' }))
open(container, 'journey.studio.mapZoom')
pick('11')
expect(saved().zoom).toBe(11)
// Automatic is null rather than a number, which is what lets the element
// choose one that fits the route.
pick('journey.studio.mapZoomAuto')
expect(saved().zoom).toBeNull()
})
it('draws each layer, or does not', () => {
show(mapEl())
press('journey.studio.showLand')
expect(saved().showLand).toBe(false)
press('journey.studio.showRoute')
expect(saved().showRoute).toBe(false)
press('journey.studio.showPins')
expect(saved().showPins).toBe(false)
press('journey.studio.showLabels')
expect(saved().showLabels).toBe(true)
})
})
describe('the figures', () => {
it('adds a figure to the set', () => {
show(statsEl())
tick('journey.studio.metric.countries')
expect(saved().metrics).toEqual(['distance', 'days', 'steps', 'photos', 'countries'])
})
it('takes one back out', () => {
show(statsEl())
tick('journey.studio.metric.days')
expect(saved().metrics).toEqual(['distance', 'steps', 'photos'])
})
/* An empty panel is a blank rectangle nobody could get back out of. */
it('keeps the last figure', () => {
show(statsEl({ metrics: ['days'] }))
tick('journey.studio.metric.days')
expect(saved().metrics).toEqual(['days'])
})
it('writes the layout and the units', () => {
show(statsEl())
pick('journey.studio.layoutRow')
expect(saved().layout).toBe('row')
pick('mi')
expect(saved().units).toBe('imperial')
})
it('writes the icons switch', () => {
show(statsEl())
press('journey.studio.showIcons')
expect(saved().showIcons).toBe(false)
})
})
describe('the countries', () => {
it('writes the layout and the alignment', () => {
show(countriesEl())
pick('journey.studio.layoutColumn')
expect(saved().layout).toBe('column')
pick('journey.studio.align.right')
expect(saved().align).toBe('right')
})
it('writes the three things it draws', () => {
show(countriesEl())
press('journey.studio.showOutline')
expect(saved().showOutline).toBe(false)
press('journey.studio.showFlag')
expect(saved().showFlag).toBe(true)
press('journey.studio.showName')
expect(saved().showName).toBe(false)
})
it('keeps one name per code when a line is edited', () => {
show(countriesEl())
fireEvent.change(screen.getByLabelText('journey.studio.countryNames'), {
target: { value: 'Island\nNoreg' },
})
expect(saved().names).toEqual(['Island', 'Noreg'])
})
/*
* The reason the textarea does not simply store its own lines: a removed line
* must not shift every name after it onto the wrong outline, and a line
* nobody has a country for must not be printed at all.
*/
it('ignores a line past the last country, and keeps a name whose line is gone', () => {
show(countriesEl())
const box = screen.getByLabelText('journey.studio.countryNames')
fireEvent.change(box, { target: { value: 'Island\nNoreg\nSverige' } })
expect(saved().names).toEqual(['Island', 'Noreg'])
fireEvent.change(box, { target: { value: 'Island' } })
expect(saved().names).toEqual(['Island', 'Noreg'])
})
})
describe('the mark', () => {
it('writes the words and the caption', () => {
const { container } = show(badgeEl())
fireEvent.change(
within(lineIn(container, 'journey.studio.marks', 'journey.studio.text')).getByRole('textbox'),
{ target: { value: 'REYKJAVIK' } },
)
expect(saved().text).toBe('REYKJAVIK')
fireEvent.change(
within(lineIn(container, 'journey.studio.marks', 'journey.studio.styleCaption')).getByRole('textbox'),
{ target: { value: 'Day 1' } },
)
expect(saved().sub).toBe('Day 1')
})
it('writes the style, in the panel language rather than in the raw value', () => {
show(badgeEl())
pick('journey.studio.markStyle.chip')
expect(saved().style).toBe('chip')
pick('journey.studio.markStyle.stacked')
expect(saved().style).toBe('stacked')
// These four printed `plain`, `chip` and the rest in all twenty-three
// languages before, straight out of the value.
expect(screen.getByRole('radio', { name: 'journey.studio.markStyle.outline' })).toBeTruthy()
expect(screen.queryByRole('radio', { name: 'outline' })).toBeNull()
})
it('writes the three combinations of picture and words', () => {
show(badgeEl())
pick('journey.studio.iconOnly')
expect(saved().showIcon).toBe(true)
expect(saved().showLabel).toBe(false)
pick('journey.studio.labelOnly')
expect(saved().showIcon).toBe(false)
expect(saved().showLabel).toBe(true)
pick('journey.studio.iconAndLabel')
expect(saved().showIcon).toBe(true)
expect(saved().showLabel).toBe(true)
})
/* A mark with neither its picture nor its words is a way to lose an element. */
it('offers no way to switch both off', () => {
const { container } = show(badgeEl())
const shows = within(section(container, 'journey.studio.icon')).getAllByRole('radio')
expect(shows).toHaveLength(3)
for (const chip of shows) {
fireEvent.click(chip)
expect(saved().showIcon || saved().showLabel).toBe(true)
}
})
it('writes the icon colour, and stops the icon choosing its own', () => {
const { container } = show(badgeEl())
fireEvent.click(
within(lineIn(container, 'journey.studio.icon', 'journey.studio.colour'))
.getByRole('button', { name: '#0f766e' }),
)
expect(saved().iconColor).toBe('#0f766e')
expect(saved().autoIconColor).toBe(false)
})
it('hands the icon colour back with the automatic switch', () => {
const { container } = show(badgeEl({ autoIconColor: false, iconColor: '#0f766e' }))
fireEvent.click(
within(section(container, 'journey.studio.icon'))
.getByRole('button', { name: 'journey.studio.autoColour' }),
)
expect(saved().autoIconColor).toBe(true)
})
})
describe('the pros and cons list', () => {
it('writes the layout', () => {
show(listEl())
pick('journey.studio.layoutColumn')
expect(saved().layout).toBe('stacked')
pick('journey.studio.layoutGrid')
expect(saved().layout).toBe('columns')
})
it('writes the marks switch', () => {
show(listEl())
press('journey.studio.showMarks')
expect(saved().showMarks).toBe(false)
})
it('writes both headings', () => {
show(listEl())
fireEvent.change(screen.getByLabelText('journey.editor.pros'), { target: { value: 'Worth it' } })
expect(saved().proLabel).toBe('Worth it')
fireEvent.change(screen.getByLabelText('journey.editor.cons'), { target: { value: 'Less so' } })
expect(saved().conLabel).toBe('Less so')
})
})
describe('the tail all five share', () => {
it('writes the family, and moves the weight to one that family really has', () => {
const { container } = show(statsEl({ font: 'sans', weight: 700 }))
open(container, 'journey.studio.typography')
// Bebas ships one weight; a bold it does not have prints as a smeared
// regular, so the request moves rather than being passed through.
press('Bebas Neue')
expect(saved().font).toBe('bebas')
expect(saved().weight).toBe(400)
})
it('keeps a weight the new family does have', () => {
const { container } = show(statsEl({ font: 'sans', weight: 500 }))
open(container, 'journey.studio.typography')
press('Lora')
expect(saved().font).toBe('serif')
expect(saved().weight).toBe(500)
})
it('writes the weight', () => {
const { container } = show(countriesEl())
open(container, 'journey.studio.typography')
pick('500')
expect(saved().weight).toBe(500)
})
it('writes the text scale', () => {
const { container } = show(listEl())
open(container, 'journey.studio.typography')
pick('1.2×')
expect(saved().textScale).toBe(1.2)
})
it('writes the accent and the ink, which are two different rows', () => {
const { container } = show(statsEl())
fireEvent.click(
within(lineIn(container, 'journey.studio.colour', 'journey.studio.accent'))
.getByRole('button', { name: '#c2410c' }),
)
expect(saved().accent).toBe('#c2410c')
expect(saved().color).toBe('#1a1a1a')
fireEvent.click(
within(lineIn(container, 'journey.studio.colour', 'journey.studio.text'))
.getByRole('button', { name: '#1e3a8a' }),
)
expect(saved().color).toBe('#1e3a8a')
expect(saved().accent).toBe('#c2410c')
})
/* A chip's words answer to its fill, until somebody chooses otherwise. */
it('takes a mark off automatic when its ink is picked, and the switch puts it back', () => {
const { container } = show(badgeEl())
fireEvent.click(
within(lineIn(container, 'journey.studio.colour', 'journey.studio.text'))
.getByRole('button', { name: '#ffffff' }),
)
expect(saved().color).toBe('#ffffff')
expect(saved().autoColor).toBe(false)
fireEvent.click(
within(section(container, 'journey.studio.colour'))
.getByRole('button', { name: 'journey.studio.autoColour' }),
)
expect(saved().autoColor).toBe(true)
})
})
describe('an element the journey has moved past', () => {
it('says so, and offers to bring it up to date', () => {
show(statsEl(), stats)
expect(screen.getByText('journey.studio.staleHint')).toBeTruthy()
expect(screen.getByRole('button', { name: 'journey.studio.refresh' })).toBeTruthy()
})
it('writes the journey figures as they stand now, and stops asking', () => {
show(statsEl(), stats)
press('journey.studio.refresh')
expect(saved().values).toMatchObject({ distance: 1234, days: 5, steps: 7, photos: 12 })
expect(saved().stale).toBe(false)
expect(screen.queryByText('journey.studio.staleHint')).toBeNull()
})
/*
* Compared rather than timestamped: a page showing distance and days does not
* go stale because somebody fixed a typo in a caption.
*/
it('says nothing while the figures it shows still match', () => {
show(statsEl({ values: { distance: 1234, days: 5, steps: 7, photos: 12 } }), stats)
expect(screen.queryByText('journey.studio.staleHint')).toBeNull()
})
})
@@ -0,0 +1,161 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { BookDocument, BookElement } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { fireEvent, render } from '../../helpers/render'
import { StudioCanvas } from '../../../src/components/Studio/StudioCanvas'
import { useStudioStore } from '../../../src/store/studioStore'
/**
* A locked element (#1973).
*
* Locking used to switch the element's hit target off entirely, which made it a
* dead end: it could not be selected, so the inspector never showed it, so the
* unlock button was unreachable — the only way back was undo. Locked has to
* mean "cannot be moved", never "cannot be reached".
*/
const shape = (over: Partial<BookElement> = {}): BookElement => ({
id: 's1', kind: 'shape', frame: { x: 10, y: 10, w: 40, h: 30 },
rotation: 0, opacity: 1, locked: false,
shape: 'rect', fill: '#000000', gradient: 'none',
stroke: null, strokeWidth: 0, strokeStyle: 'solid', radius: 0,
...over,
} as BookElement)
const page = bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 })
function load(el: BookElement) {
useStudioStore.getState().load({
version: 1, title: 'T', page,
spreads: [{ id: 'sp1', role: 'inner', background: null, elements: [el], parked: [], entryId: null }],
} as BookDocument)
}
function draw() {
const spread = useStudioStore.getState().doc!.spreads[0]
return render(
<StudioCanvas
spread={spread}
spreadIndex={0}
page={page}
zoom={1}
pxPerMm={96 / 25.4}
bookView={false}
dropLabel=""
/>,
)
}
/** The hit target sits above the sheet, one per element. */
function hitTarget(container: HTMLElement): HTMLElement {
const sheet = container.querySelector('.st-sheet')!
return sheet.children[sheet.children.length - 1] as HTMLElement
}
beforeEach(() => {
useStudioStore.getState().load({
version: 1, title: 'T', page, spreads: [],
} as unknown as BookDocument)
})
describe('a locked element', () => {
it('can still be selected', () => {
load(shape({ locked: true }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
expect(useStudioStore.getState().selection).toEqual(['s1'])
})
/*
* The whole reason the previous behaviour was a trap: selection is what puts
* the element in the inspector, and the inspector is where the unlock is.
*/
it('can therefore be unlocked again', () => {
load(shape({ locked: true }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
const store = useStudioStore.getState()
store.commit(d => ({
...d,
spreads: d.spreads.map(sp => ({
...sp,
elements: sp.elements.map(e => (store.selection.includes(e.id) ? { ...e, locked: false } : e)),
})),
}))
expect(useStudioStore.getState().doc!.spreads[0].elements[0].locked).toBe(false)
})
it('does not move when dragged', () => {
load(shape({ locked: true }))
const { container } = draw()
const target = hitTarget(container)
fireEvent.pointerDown(target, { clientX: 100, clientY: 100 })
fireEvent.pointerMove(container.querySelector('.st-stage')!, { clientX: 300, clientY: 260 })
expect(useStudioStore.getState().doc!.spreads[0].elements[0].frame).toMatchObject({ x: 10, y: 10 })
})
it('offers no resize handles, since a drag on one would be refused', () => {
load(shape({ locked: true }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
expect(container.querySelectorAll('.st-handle')).toHaveLength(0)
// But it is selected, and the outline says so.
expect(container.querySelectorAll('.st-select')).toHaveLength(1)
})
/*
* Delete was the one gesture that ignored the flag: the element was still
* selectable, so a stray Delete took away exactly what had been pinned down.
*/
it('is not deleted by the Delete key', () => {
load(shape({ locked: true }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
fireEvent.keyDown(document, { key: 'Delete' })
expect(useStudioStore.getState().doc!.spreads[0].elements).toHaveLength(1)
})
it('is not deleted by the quick bar either', () => {
load(shape({ locked: true }))
const { container, getByTitle } = draw()
fireEvent.pointerDown(hitTarget(container))
fireEvent.pointerUp(container.querySelector('.st-stage')!)
fireEvent.click(getByTitle('Delete'))
expect(useStudioStore.getState().doc!.spreads[0].elements).toHaveLength(1)
})
it('leaves an unlocked element deletable', () => {
load(shape({ locked: false }))
const { container } = draw()
fireEvent.pointerDown(hitTarget(container))
fireEvent.keyDown(document, { key: 'Delete' })
expect(useStudioStore.getState().doc!.spreads[0].elements).toHaveLength(0)
})
it('leaves an unlocked element movable, with its handles', () => {
load(shape({ locked: false }))
const { container } = draw()
const stage = container.querySelector('.st-stage')!
fireEvent.pointerDown(hitTarget(container))
// The handles hide while a gesture is open — chrome that follows your hand
// around is noise — so the press has to be released before they appear.
fireEvent.pointerUp(stage)
expect(useStudioStore.getState().selection).toEqual(['s1'])
expect(container.querySelectorAll('.st-handle').length).toBeGreaterThan(0)
})
})
@@ -0,0 +1,208 @@
import { describe, it, expect } from 'vitest'
import { render } from '@testing-library/react'
import type { BookElement, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { tileView } from '../../../src/components/Studio/mapTiles'
/**
* What a route map shows, and what shape it is (#1973).
*
* The complaint this answers, in the words it arrived in: a trip that stayed in
* Berlin was drawn as the whole of Germany with two dots in the middle of it,
* and the line between stops was a zig-zag across country rather than the road
* anyone actually took. Both were decisions the element made for you.
*/
const page = bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210 })
const common = {
frame: { x: 0, y: 0, w: 120, h: 100 },
rotation: 0, opacity: 1, locked: false,
}
const typeset = { font: 'sans', color: '#111111', accent: '#111111', textScale: 1, weight: 700, stale: false }
const map = (over: Record<string, unknown> = {}): BookElement => ({
...common, ...typeset, id: 'm1', kind: 'map', style: 'minimal',
source: 'vector', tileUrl: '', attribution: '', zoom: null,
showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: ['DE'],
// Two stops a few kilometres apart, both well inside one large country.
points: [
{ lat: 52.52, lng: 13.40, label: 'Berlin' },
{ lat: 52.50, lng: 13.45, label: 'Kreuzberg' },
],
path: [],
fitPadding: 0.18,
fitToCountries: false,
clip: 'rect',
...over,
} as BookElement)
function draw(el: BookElement) {
const spread: BookSpread = { id: 's', role: 'inner', background: null, elements: [el], parked: [], entryId: null }
return render(<SpreadView spread={spread} page={page} />)
}
/** How far apart the two pins are drawn, in the SVG's own units. */
function pinSpread(container: HTMLElement): number {
const circles = [...container.querySelectorAll('circle')]
const xs = circles.map(c => Number(c.getAttribute('cx')))
return Math.max(...xs) - Math.min(...xs)
}
describe('what the map is fitted to', () => {
/*
* The whole point. Fitted to the country, two stops five kilometres apart are
* two dots a hair's breadth from each other; fitted to the stops they are the
* width of the page, which is what a page about those two places wants.
*/
it('fits the stops, not the country they are in', () => {
const toStops = pinSpread(draw(map()).container)
const toCountry = pinSpread(draw(map({ fitToCountries: true })).container)
expect(toStops).toBeGreaterThan(toCountry * 10)
})
it('fits the country when asked, so the country page still works', () => {
const { container } = draw(map({ fitToCountries: true }))
// The outline fills the frame rather than sitting inside a box drawn round
// two stops in the middle of it.
expect(pinSpread(container)).toBeLessThan(20)
})
it('leaves more air around it the wider the padding', () => {
const tight = pinSpread(draw(map({ fitPadding: 0.02 })).container)
const wide = pinSpread(draw(map({ fitPadding: 1.5 })).container)
expect(tight).toBeGreaterThan(wide)
})
/* A single stop is a place, not an extent: it needs a window, not a country. */
it('gives one stop a window rather than dividing by zero', () => {
const { container } = draw(map({ points: [{ lat: 52.52, lng: 13.4, label: 'Berlin' }] }))
const circle = container.querySelector('circle')!
expect(Number(circle.getAttribute('cx'))).toBeGreaterThan(0)
expect(container.innerHTML).not.toContain('NaN')
})
it('falls back to the country when there is nothing else to fit', () => {
const { container } = draw(map({ points: [], path: [] }))
expect(container.innerHTML).not.toContain('NaN')
expect(container.querySelectorAll('path').length).toBeGreaterThan(0)
})
})
describe('the line the map draws', () => {
const berlinToHamburg: [number, number][] = [
[52.52, 13.40], [52.8, 12.9], [53.2, 12.0], [53.55, 10.0],
]
it('follows the travelled way when the trip knows it', () => {
const { container } = draw(map({ path: [berlinToHamburg] }))
const line = container.querySelector('polyline')!
// Four points on the way, not two stops joined by a ruler.
expect(line.getAttribute('points')!.trim().split(/\s+/)).toHaveLength(4)
})
it('joins the stops when it does not', () => {
const { container } = draw(map())
const line = container.querySelector('polyline')!
expect(line.getAttribute('points')!.trim().split(/\s+/)).toHaveLength(2)
})
/*
* Two tracks that do not join must stay two lines. Drawn as one, a trip with
* a flight in the middle grows a road across the sea.
*/
it('keeps separate tracks separate', () => {
const { container } = draw(map({
path: [berlinToHamburg, [[48.1, 11.6], [48.0, 11.0]] as [number, number][]],
}))
expect(container.querySelectorAll('polyline')).toHaveLength(2)
})
it('takes the travelled way into account when fitting', () => {
const near = draw(map()).container.innerHTML
const far = draw(map({ path: [berlinToHamburg] })).container.innerHTML
expect(near).not.toEqual(far)
})
})
describe('cutting the map to the land', () => {
it('cuts the imagery to the outline rather than to a box', () => {
const { container } = draw(map({
source: 'tiles',
tileUrl: 'https://tile.example/{z}/{x}/{y}.png',
clip: 'country',
}))
expect(container.querySelectorAll('clipPath')).toHaveLength(1)
expect(container.querySelectorAll('svg image').length).toBeGreaterThan(0)
// Nothing outside the stencil: the tiles are not also drawn as plain images.
expect(container.querySelectorAll('img')).toHaveLength(0)
})
it('draws a boxed map as a picture under the page, with no stencil', () => {
const { container } = draw(map({
source: 'tiles',
tileUrl: 'https://tile.example/{z}/{x}/{y}.png',
clip: 'rect',
}))
expect(container.querySelectorAll('clipPath')).toHaveLength(0)
expect(container.querySelectorAll('img').length).toBeGreaterThan(0)
})
/* A country-shaped hole cut in a city-sized view is a coloured rectangle. */
it('shows the whole country when cutting, whatever the fit said', () => {
const cut = pinSpread(draw(map({
source: 'tiles', tileUrl: 'https://tile.example/{z}/{x}/{y}.png',
clip: 'country', fitToCountries: false,
})).container)
expect(cut).toBeLessThan(20)
})
it('has nothing to cut against without a country, and stays a rectangle', () => {
const { container } = draw(map({
source: 'tiles', tileUrl: 'https://tile.example/{z}/{x}/{y}.png',
clip: 'country', countries: [],
}))
expect(container.querySelectorAll('clipPath')).toHaveLength(0)
})
})
describe('the tile grid', () => {
const frame = { w: 120, h: 100 }
const template = 'https://{s}.tiles.example/{z}/{x}/{y}.png'
const points = [{ lat: 52.52, lng: 13.40 }, { lat: 53.55, lng: 10.0 }]
it('covers the frame on both axes, with no paper showing at the edges', () => {
const view = tileView(points, frame, template, null)!
const right = view.originX + (Math.max(...view.tiles.map(t => t.x)) + 1) * view.size
const bottom = view.originY + (Math.max(...view.tiles.map(t => t.y)) + 1) * view.size
expect(view.originX).toBeLessThanOrEqual(0.001)
expect(view.originY).toBeLessThanOrEqual(0.001)
expect(right).toBeGreaterThanOrEqual(frame.w - 0.001)
expect(bottom).toBeGreaterThanOrEqual(frame.h - 0.001)
})
/*
* `{s}` left in the URL is not a placeholder, it is a hostname that does not
* resolve — the map draws as an empty frame with a route across it.
*/
it('substitutes the shard letter', () => {
const view = tileView(points, frame, template, null)!
expect(view.tiles.every(t => !t.url.includes('{s}'))).toBe(true)
expect(view.tiles[0].url).toMatch(/^https:\/\/[abc]\.tiles\.example\//)
})
it('gives the same tile the same host every time, so a reprint hits the cache', () => {
const a = tileView(points, frame, template, null)!
const b = tileView(points, frame, template, null)!
expect(a.tiles.map(t => t.url)).toEqual(b.tiles.map(t => t.url))
})
it('covers the extent it is given rather than a second fit of its own', () => {
const extent = { minLng: 5, maxLng: 15, minLat: 47, maxLat: 55 }
const view = tileView(points, frame, template, null, extent)!
const plain = tileView(points, frame, template, null)!
expect(view.zoom).not.toBe(plain.zoom)
})
})
@@ -0,0 +1,154 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
/**
* The drawn route: photo markers, a bowed line and a casing (#1973).
*
* The stencil that rounds a photograph is the fragile part, and it failed
* silently the first time: it was written inside the `defs` that belongs to
* cutting a map to a coastline, so on an ordinary map the id it pointed at was
* never written. A clip-path pointing at nothing is not an error, it is simply
* no clip, and because the image is drawn with `slice` what showed was the
* photograph standing proud of its circle with all four corners on the map.
*
* So these cases check that the id on the image and an id in the defs are the
* same id, rather than checking that an image exists. The plain treatment is
* checked too: every book made before this feature has to keep drawing exactly
* as it did.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({ preset: 'square-210' })
const STOPS = [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík', photoId: 11 },
{ lat: 65.68, lng: -18.12, label: 'Akureyri', photoId: 12 },
{ lat: 38.72, lng: -9.14, label: 'Lisboa', photoId: null },
]
function map(over: Record<string, unknown> = {}): BookElement {
return {
id: 'mp1', kind: 'map', rotation: 0, opacity: 1, locked: false,
font: 'sans', color: '#1a1a1a', accent: '#ffffff', textScale: 1, weight: 400, stale: false,
frame: { x: 0, y: 0, w: 180, h: 140 },
style: 'minimal', source: 'vector', tileUrl: '', attribution: '', zoom: null, clip: 'rect',
showLand: true, showRoute: true, showPins: true, showLabels: false,
routeStyle: 'drawn', routeArc: 'bow', routeDash: 'arcs', pinStyle: 'photo',
countries: [], path: [], fitPadding: 0.5, fitToCountries: false, tripId: null,
points: STOPS,
...over,
} as unknown as BookElement
}
function draw(el: BookElement, big = true) {
const spread: BookSpread = {
id: 's1', role: 'inner', background: null, elements: [el], parked: [], entryId: null,
}
return render(<SpreadView spread={spread} page={page} big={big} />)
}
describe('a stop with a photograph', () => {
it('is cut to a circle by a stencil that really exists', () => {
const { container } = draw(map())
const images = Array.from(container.querySelectorAll('image'))
expect(images.length).toBe(2)
const ids = new Set(
Array.from(container.querySelectorAll('clipPath')).map(c => c.getAttribute('id')),
)
for (const im of images) {
const ref = im.getAttribute('clip-path')!
const id = ref.replace(/^url\(#/, '').replace(/\)$/, '')
// The assertion that would have caught the square photographs.
expect(ids.has(id), `no stencil for ${ref}`).toBe(true)
}
})
it('asks for the thumbnail rather than the original, at every print size', () => {
const { container } = draw(map())
for (const im of Array.from(container.querySelectorAll('image'))) {
expect(im.getAttribute('href')).toMatch(/^\/api\/photos\/\d+\/thumbnail$/)
}
})
it('crops the picture to fill its circle rather than letterboxing it', () => {
const { container } = draw(map())
expect(container.querySelector('image')!.getAttribute('preserveAspectRatio')).toBe('xMidYMid slice')
})
/*
* A stop with no photograph of its own is numbered rather than handed one
* from somewhere else in the journey. That was the first design and it was a
* caption that lies: a marker at the third stop showing a picture taken at
* the seventh is wrong in the one place a reader most trusts that a picture
* is OF what it sits on.
*/
it('numbers a stop that has no photograph of its own', () => {
const { container } = draw(map())
expect(container.querySelectorAll('image').length).toBe(STOPS.filter(s => s.photoId).length)
const numbers = Array.from(container.querySelectorAll('text')).map(t => t.textContent)
// The third stop carries no photo id, so it prints its position.
expect(numbers).toContain('3')
})
it('numbers nothing when the map was asked for dots', () => {
const { container } = draw(map({ pinStyle: 'dot' }))
expect(container.querySelectorAll('text').length).toBe(0)
expect(container.querySelectorAll('image').length).toBe(0)
})
/*
* Nobody prints the pages rail, and a thumbnail that fetched a photograph per
* stop would cost a request per stop every time a panel opened.
*/
it('costs nothing in a thumbnail', () => {
const { container } = draw(map(), false)
expect(container.querySelectorAll('image').length).toBe(0)
expect(container.querySelectorAll('clipPath').length).toBe(0)
})
})
describe('the drawn line', () => {
it('is two strokes, so it stays legible over dark sea and bright desert alike', () => {
const { container } = draw(map({ source: 'tiles', tileUrl: 'https://example.test/{z}/{x}/{y}.png' }))
const strokes = Array.from(container.querySelectorAll('path'))
.filter(p => p.getAttribute('fill') === 'none')
expect(strokes.length).toBeGreaterThanOrEqual(2)
// The casing is the wider of the pair, and it is the translucent one.
const widths = strokes.map(p => Number(p.getAttribute('stroke-width')))
expect(Math.max(...widths)).toBeGreaterThan(Math.min(...widths))
expect(strokes.some(p => p.getAttribute('stroke-opacity'))).toBe(true)
})
it('bows a long leg and dashes it, since it is inferred rather than recorded', () => {
const { container } = draw(map())
const paths = Array.from(container.querySelectorAll('path'))
expect(paths.some(p => (p.getAttribute('d') ?? '').includes('Q'))).toBe(true)
expect(paths.some(p => p.getAttribute('stroke-dasharray'))).toBe(true)
})
it('never bows a recorded track, which would draw a journey that did not happen', () => {
const { container } = draw(map({
path: [[[64.14, -21.94], [64.5, -21.0], [65.68, -18.12]]],
}))
const ds = Array.from(container.querySelectorAll('path'))
.filter(p => p.getAttribute('fill') === 'none')
.map(p => p.getAttribute('d') ?? '')
expect(ds.length).toBeGreaterThan(0)
for (const d of ds) expect(d).not.toContain('Q')
})
})
describe('a book made before any of this', () => {
it('still draws one flat polyline and plain circles', () => {
const { container } = draw(map({
routeStyle: 'plain', routeArc: 'straight', routeDash: 'solid', pinStyle: 'dot',
}))
expect(container.querySelectorAll('polyline').length).toBe(1)
expect(container.querySelectorAll('image').length).toBe(0)
expect(container.querySelectorAll('circle').length).toBe(STOPS.length)
})
})
@@ -0,0 +1,127 @@
import { describe, it, expect } from 'vitest'
import { maxZoomFor, tileView } from '../../../src/components/Studio/mapTiles'
/**
* How sharp a tiled map comes out on paper (#1973).
*
* The zoom used to be chosen so the route spanned the frame and nothing more,
* which put about two tiles across the picture whatever its physical size: a
* route across Iceland on a 210mm page arrived as 256 by 512 pixels stretched
* over the sheet. Seventeen dots to the inch, on paper that holds three
* hundred. It did not look like a bad map, it looked like a screenshot, which
* is exactly what it was.
*
* These cases pin the sum rather than the picture: how many tile pixels end up
* covering how many millimetres. A change that quietly puts the old behaviour
* back would show up here as a number falling by a factor of ten.
*/
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
const RELIEF = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best'
+ '/BlueMarble_ShadedRelief_Bathymetry/default/GoogleMapsCompatible_Level8/{z}/{y}/{x}.jpeg'
/** A tile is 256 CSS pixels, or 512 when the template asked for retina. */
const tilePixels = (template: string) => (template.includes('{r}') ? 512 : 256)
/** Dots per inch the grid actually delivers over the frame it covers. */
function dpi(view: { size: number }, template: string): number {
return tilePixels(template) / (view.size / 25.4)
}
const ICELAND = [
{ lat: 64.1466, lng: -21.9426 },
{ lat: 65.6885, lng: -18.1262 },
{ lat: 64.2539, lng: -15.2082 },
{ lat: 63.4194, lng: -19.0672 },
]
const BERLIN = [
{ lat: 52.5163, lng: 13.3777 },
{ lat: 52.5200, lng: 13.4050 },
{ lat: 52.5074, lng: 13.3904 },
]
describe('a full page of map', () => {
it('is drawn at print resolution rather than at screen resolution', () => {
const view = tileView(ICELAND, { w: 210, h: 297 }, OSM, null)!
// The old sum landed at 17. Anything in this range is a printable page.
expect(dpi(view, OSM)).toBeGreaterThan(250)
})
it('spends the tiles on the page it has, not on a fixed grid', () => {
const small = tileView(ICELAND, { w: 60, h: 60 }, OSM, null)!
const page = tileView(ICELAND, { w: 210, h: 297 }, OSM, null)!
// Same route, bigger paper, more pictures. That is the whole idea.
expect(page.tiles.length).toBeGreaterThan(small.tiles.length)
})
it('stays inside the request budget however large the page is', () => {
const spread = tileView(ICELAND, { w: 420, h: 297 }, OSM, null)!
expect(spread.tiles.length).toBeLessThanOrEqual(256)
})
it('asks for the retina tile a template offers, which is free resolution', () => {
const retina = 'https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'
const view = tileView(BERLIN, { w: 210, h: 210 }, retina, null)!
expect(view.tiles[0].url).toContain('@2x')
expect(view.tiles[0].url).not.toContain('{r}')
})
it('leaves a template with no retina placeholder alone', () => {
const view = tileView(BERLIN, { w: 210, h: 210 }, OSM, null)!
expect(view.tiles[0].url).not.toContain('@2x')
})
})
describe('a source with a ceiling', () => {
/*
* NASA's imagery stops at level 8. Asking for 9 answers with an error image,
* which arrives as a page-sized grey rectangle and no explanation.
*/
it('never asks NASA for a zoom it does not have', () => {
expect(maxZoomFor(RELIEF)).toBe(8)
const view = tileView(BERLIN, { w: 420, h: 297 }, RELIEF, null)!
expect(view.zoom).toBeLessThanOrEqual(8)
})
it('lets an ordinary tile source go further', () => {
expect(maxZoomFor(OSM)).toBe(19)
const relief = tileView(BERLIN, { w: 210, h: 210 }, RELIEF, null)!
const tiles = tileView(BERLIN, { w: 210, h: 210 }, OSM, null)!
expect(tiles.zoom).toBeGreaterThan(relief.zoom)
})
it('still honours a zoom the document asked for', () => {
const view = tileView(ICELAND, { w: 210, h: 297 }, OSM, 6)!
expect(view.zoom).toBe(6)
})
})
describe('the credit', () => {
it('names NASA for its imagery, because a printed book cannot add a footnote later', async () => {
const { attributionFor } = await import('../../../src/components/Studio/mapTiles')
expect(attributionFor(RELIEF)).toBe('NASA EOSDIS GIBS')
})
})
describe('a thumbnail of the same map', () => {
/*
* The pages rail and the travel panel draw the same element at about 130px.
* Cutting those to print resolution would mean a couple of hundred requests
* for a picture the size of a stamp, every time a panel opens — which
* against NASA or OpenStreetMap is the bulk fetching their policies ask
* people not to do.
*/
it('costs a handful of tiles rather than a page of them', () => {
const page = tileView(ICELAND, { w: 210, h: 297 }, OSM, null)!
const thumb = tileView(ICELAND, { w: 210, h: 297 }, OSM, null, undefined, 'preview')!
expect(thumb.tiles.length).toBeLessThanOrEqual(16)
expect(thumb.tiles.length).toBeLessThan(page.tiles.length / 4)
})
it('still covers the same ground, just less finely', () => {
const thumb = tileView(ICELAND, { w: 210, h: 297 }, OSM, null, undefined, 'preview')!
expect(thumb.tiles.length).toBeGreaterThan(0)
expect(thumb.zoom).toBeLessThan(tileView(ICELAND, { w: 210, h: 297 }, OSM, null)!.zoom)
})
})
+258
View File
@@ -0,0 +1,258 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { BookDocument, BookElement, BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { fireEvent, render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { StudioTravelPanel } from '../../../src/components/Studio/StudioTravelPanel'
import { useStudioStore } from '../../../src/store/studioStore'
import { fetchRoads } from '../../../src/components/Studio/roadRoute'
vi.mock('../../../src/components/Map/RouteCalculator', () => ({
calculateRouteWithLegs: vi.fn(),
}))
const { calculateRouteWithLegs } = await import('../../../src/components/Map/RouteCalculator')
/**
* The line following real roads, for the legs that have them (#1973).
*
* The trap this is built around: when the map element carries a track, the
* renderer draws that INSTEAD of the stop chain, whole. A road route that only
* covers some legs would therefore have printed those legs and silently dropped
* the rest — three legs of twelve, and the book looks like the journey stopped.
* So the roads are per leg and the chain is cut around them, and the case that
* proves it is the one below with a road on the middle leg only.
*
* The second thing worth protecting is what is NOT asked: a leg long enough to
* have been a flight is never sent to a router, because the answer would be a
* three-day drive and a ferry, and that is not the journey anybody made.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({ preset: 'square-210' })
const STOPS = [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík', photoId: null },
{ lat: 63.42, lng: -19.07, label: 'Vík', photoId: null },
{ lat: 65.68, lng: -18.12, label: 'Akureyri', photoId: null },
]
function map(over: Record<string, unknown> = {}): BookElement {
return {
id: 'mp1', kind: 'map', rotation: 0, opacity: 1, locked: false,
font: 'sans', color: '#1a1a1a', accent: '#ffffff', textScale: 1, weight: 400, stale: false,
frame: { x: 0, y: 0, w: 180, h: 140 },
style: 'minimal', source: 'vector', tileUrl: '', attribution: '', zoom: null, clip: 'rect',
showLand: true, showRoute: true, showPins: true, showLabels: false,
routeStyle: 'drawn', routeArc: 'bow', routeDash: 'arcs', pinStyle: 'dot',
countries: [], path: [], roads: [], fitPadding: 0.5, fitToCountries: false, tripId: null,
points: STOPS,
...over,
} as unknown as BookElement
}
function draw(el: BookElement) {
const spread: BookSpread = {
id: 's1', role: 'inner', background: null, elements: [el], parked: [], entryId: null,
}
return render(<SpreadView spread={spread} page={page} big />)
}
const strokes = (c: HTMLElement) =>
Array.from(c.querySelectorAll('path')).filter(p => p.getAttribute('fill') === 'none')
describe('a leg that has a road', () => {
it('is drawn as the road rather than as a line between its ends', () => {
const road: [number, number][] = [
[64.14, -21.94], [64.0, -21.5], [63.8, -20.6], [63.5, -19.6], [63.42, -19.07],
]
const { container } = draw(map({ roads: [road, null] }))
const ds = strokes(container).map(p => p.getAttribute('d') ?? '')
// A road is many points; a bow is one Q; a straight leg is one L.
expect(ds.some(d => (d.match(/L/g) ?? []).length >= 3)).toBe(true)
})
it('is drawn solid and unbowed, because it is the way that was taken', () => {
const road: [number, number][] = [
[64.14, -21.94], [64.0, -21.5], [63.8, -20.6], [63.42, -19.07],
]
const { container } = draw(map({ roads: [road, null] }))
const roadPaths = strokes(container).filter(p => (p.getAttribute('d') ?? '').match(/L/g))
for (const p of roadPaths) {
expect(p.getAttribute('d')).not.toContain('Q')
expect(p.getAttribute('stroke-dasharray')).toBeNull()
}
})
/*
* The bug this whole shape exists to avoid: `path` replaces the entire line,
* so a partial answer used to mean a partial journey.
*/
it('does not swallow the legs that have none', () => {
const middle: [number, number][] = [
[63.42, -19.07], [64.0, -18.5], [65.0, -18.2], [65.68, -18.12],
]
const { container } = draw(map({ roads: [null, middle] }))
const ds = strokes(container).map(p => p.getAttribute('d') ?? '')
// The first leg is still drawn: either bowed or straight, but drawn.
const hasFirstLeg = ds.some(d => d.includes('Q') || (d.match(/L/g) ?? []).length === 1)
expect(hasFirstLeg).toBe(true)
expect(ds.some(d => (d.match(/L/g) ?? []).length >= 2)).toBe(true)
})
it('is inside the frame, road and all', () => {
// A road that wanders well north of both its ends.
const road: [number, number][] = [
[64.14, -21.94], [66.5, -21.0], [66.6, -19.5], [63.42, -19.07],
]
const { container } = draw(map({ roads: [road, null] }))
const numbers = strokes(container)
.flatMap(p => (p.getAttribute('d') ?? '').match(/-?\d+(\.\d+)?/g) ?? [])
.map(Number)
// Coordinates come in pairs; none of them may leave the 180x140 element.
for (let i = 0; i < numbers.length; i += 2) {
expect(numbers[i]).toBeGreaterThanOrEqual(-0.01)
expect(numbers[i]).toBeLessThanOrEqual(180.01)
expect(numbers[i + 1]).toBeGreaterThanOrEqual(-0.01)
expect(numbers[i + 1]).toBeLessThanOrEqual(140.01)
}
})
})
describe('what gets asked for', () => {
beforeEach(() => {
vi.mocked(calculateRouteWithLegs).mockReset()
})
it('asks once per leg and keeps the answer in leg order', async () => {
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
coordinates: [[1, 1], [1.1, 1.1], [1.2, 1.2]],
distance: 1, duration: 1, legs: [],
} as never)
const roads = await fetchRoads([
{ lat: 52.5, lng: 13.4 },
{ lat: 52.4, lng: 13.1 },
{ lat: 52.3, lng: 13.0 },
])
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
expect(roads).toHaveLength(2)
expect(roads[0]).toHaveLength(3)
})
it('never asks about a leg long enough to have been a flight', async () => {
const roads = await fetchRoads([
{ lat: 64.14, lng: -21.94 },
{ lat: -33.87, lng: 151.21 },
])
expect(calculateRouteWithLegs).not.toHaveBeenCalled()
expect(roads).toEqual([null])
})
it('leaves a leg alone when the router refuses, rather than failing the lot', async () => {
vi.mocked(calculateRouteWithLegs)
.mockRejectedValueOnce(new Error('no route'))
.mockResolvedValueOnce({
coordinates: [[1, 1], [1.1, 1.1], [1.2, 1.2]], distance: 1, duration: 1, legs: [],
} as never)
const roads = await fetchRoads([
{ lat: 52.5, lng: 13.4 },
{ lat: 52.4, lng: 13.1 },
{ lat: 52.3, lng: 13.0 },
])
expect(roads[0]).toBeNull()
expect(roads[1]).not.toBeNull()
})
it('keeps nothing when the answer is just the straight line back', async () => {
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
coordinates: [[1, 1], [1.2, 1.2]], distance: 1, duration: 1, legs: [],
} as never)
const roads = await fetchRoads([{ lat: 52.5, lng: 13.4 }, { lat: 52.4, lng: 13.1 }])
expect(roads).toEqual([null])
})
/*
* A router answers a long drive with thousands of points, at a precision no
* press can resolve, and all of it is stored in the document. That is not a
* tidiness problem: the book is saved as one body, and a route kept whole is
* what pushed a real book past the body limit and left the editor showing
* "not saved" with no way forward.
*
* Thinned evenly rather than by cutting a run out of the middle, because a
* road's shape is the reason to draw it at all — losing the middle would
* straighten exactly the bends somebody wanted to see.
*/
it('thins a long answer, keeping both ends and the shape between them', async () => {
const many: [number, number][] = Array.from({ length: 900 }, (_, i) => [
52.5 - i * 0.001,
13.4 + i * 0.001,
])
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
coordinates: many, distance: 1, duration: 1, legs: [],
} as never)
const roads = await fetchRoads([{ lat: 52.5, lng: 13.4 }, { lat: 51.6, lng: 14.3 }])
const leg = roads[0]!
expect(leg).not.toBeNull()
expect(leg.length).toBe(120)
// Both ends survive, so the line still meets the stops it runs between.
expect(leg[0]).toEqual([52.5, 13.4])
expect(leg[leg.length - 1]).toEqual([51.601, 14.299])
// Evenly spaced: no two consecutive points sit further apart than one step.
const gaps = leg.slice(1).map((p, i) => Math.abs(p[0] - leg[i][0]))
expect(Math.max(...gaps) - Math.min(...gaps)).toBeLessThan(0.002)
})
it('leaves a leg the press can already resolve exactly as it came', async () => {
const few: [number, number][] = Array.from({ length: 40 }, (_, i) => [
52.5 - i * 0.01,
13.4 + i * 0.01,
])
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
coordinates: few, distance: 1, duration: 1, legs: [],
} as never)
const roads = await fetchRoads([{ lat: 52.5, lng: 13.4 }, { lat: 52.1, lng: 13.8 }])
expect(roads[0]!.length).toBe(40)
})
})
/**
* The lookups outlive the click by design — they are paced so the router is not
* hammered — so the panel has to take them with it when it goes.
*/
describe('placing a map from the panel', () => {
const journeyStats = {
journeyId: 1, distance: 0, days: 1, steps: 3, photos: 0, places: 3, furthest: 0,
countries: [], trips: [], start: null, end: null,
points: STOPS.map(p => ({ ...p, date: null, country: null, tripId: null })),
} as unknown as JourneyStats
beforeEach(() => {
vi.mocked(calculateRouteWithLegs).mockReset()
useStudioStore.getState().load({
version: 1, title: 'T', page,
spreads: [{ id: 's1', role: 'inner', background: null, elements: [], parked: [], entryId: null }],
} as unknown as BookDocument)
})
it('drops the road lookup when the panel goes away', async () => {
let asked: AbortSignal | undefined
vi.mocked(calculateRouteWithLegs).mockImplementation((_stops, opts) => {
asked = (opts as { signal?: AbortSignal } | undefined)?.signal
return new Promise(() => {}) as never
})
const { getByTitle, unmount } = render(
<StudioTravelPanel page={page} stats={journeyStats} path={[]} t={k => k} locale="en" />,
)
fireEvent.click(getByTitle('journey.studio.mapStyle.minimal'))
await vi.waitFor(() => expect(calculateRouteWithLegs).toHaveBeenCalled())
unmount()
expect(asked?.aborted).toBe(true)
})
})
@@ -0,0 +1,137 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
/**
* The route stays on the map, whatever shape the map is dragged to (#1973).
*
* Two fits used to disagree about what the map was of. The outlines and the
* route were contained in the frame, fitted whole with air on the long side;
* the imagery covered it, because a map with a strip of paper down one edge is
* not a map. On a frame whose proportions did not match the route's those are
* different windows, and the tiles won — so a map dragged narrow kept its
* picture and lost the end of its line.
*
* These cases drag the same route into deliberately awkward shapes and check
* every drawn point is still inside the box. They read the SVG rather than the
* document, because this is the one thing about a map that only goes wrong at
* draw time.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({ preset: 'square-210' })
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
/** A route that is far wider than it is tall: Lisbon to Kyiv. */
const WIDE = [
{ lat: 38.72, lng: -9.14, label: 'Lisboa' },
{ lat: 48.85, lng: 2.35, label: 'Paris' },
{ lat: 52.52, lng: 13.40, label: 'Berlin' },
{ lat: 50.45, lng: 30.52, label: 'Kyiv' },
]
/** And one far taller than it is wide: Tromso down to Palermo. */
const TALL = [
{ lat: 69.65, lng: 18.95, label: 'Tromso' },
{ lat: 59.33, lng: 18.07, label: 'Stockholm' },
{ lat: 47.37, lng: 8.54, label: 'Zurich' },
{ lat: 38.12, lng: 13.36, label: 'Palermo' },
]
function map(over: Record<string, unknown> = {}): BookElement {
return {
id: 'mp1', kind: 'map', rotation: 0, opacity: 1, locked: false,
font: 'sans', color: '#1a1a1a', accent: '#c2410c', textScale: 1, weight: 400, stale: false,
frame: { x: 0, y: 0, w: 120, h: 90 },
style: 'minimal', source: 'vector', tileUrl: '', attribution: '', zoom: null, clip: 'rect',
showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: [], points: WIDE, path: [],
fitPadding: 0.18, fitToCountries: false, tripId: null,
...over,
} as unknown as BookElement
}
function draw(el: BookElement) {
const spread: BookSpread = {
id: 's1', role: 'inner', background: null, elements: [el], parked: [], entryId: null,
}
return render(<SpreadView spread={spread} page={page} big />)
}
/** Every stop the map drew, in the element's own millimetres. */
function pins(container: HTMLElement): { x: number; y: number }[] {
return Array.from(container.querySelectorAll('circle')).map(c => ({
x: Number(c.getAttribute('cx')),
y: Number(c.getAttribute('cy')),
})).filter(p => Number.isFinite(p.x) && Number.isFinite(p.y))
}
const shapes = [
{ name: 'a wide letterbox', w: 180, h: 40 },
{ name: 'a tall column', w: 40, h: 180 },
{ name: 'a small square', w: 30, h: 30 },
{ name: 'a full spread', w: 420, h: 297 },
]
describe('however the map is dragged', () => {
for (const points of [WIDE, TALL]) {
for (const shape of shapes) {
it(`keeps every stop inside ${shape.name}`, () => {
const el = map({ points, frame: { x: 0, y: 0, w: shape.w, h: shape.h } })
const { container } = draw(el)
const drawn = pins(container)
expect(drawn).toHaveLength(points.length)
for (const p of drawn) {
expect(p.x).toBeGreaterThanOrEqual(0)
expect(p.x).toBeLessThanOrEqual(shape.w)
expect(p.y).toBeGreaterThanOrEqual(0)
expect(p.y).toBeLessThanOrEqual(shape.h)
}
})
}
}
/*
* The case that was actually broken: with imagery the route is projected onto
* the tile grid rather than onto the vector fit, and the tile grid covers.
*/
it('keeps every stop inside a narrow map drawn from tiles', () => {
const el = map({
points: WIDE,
source: 'tiles',
tileUrl: OSM,
frame: { x: 0, y: 0, w: 40, h: 170 },
})
const { container } = draw(el)
const drawn = pins(container)
expect(drawn).toHaveLength(WIDE.length)
for (const p of drawn) {
expect(p.x).toBeGreaterThanOrEqual(0)
expect(p.x).toBeLessThanOrEqual(40)
expect(p.y).toBeGreaterThanOrEqual(0)
expect(p.y).toBeLessThanOrEqual(170)
}
})
it('still fills the frame with imagery rather than leaving paper down one side', () => {
const el = map({
points: WIDE,
source: 'tiles',
tileUrl: OSM,
frame: { x: 0, y: 0, w: 180, h: 40 },
})
const { container } = draw(el)
const tiles = Array.from(container.querySelectorAll('img'))
expect(tiles.length).toBeGreaterThan(0)
// The grid has to reach past both edges, which is what cover means.
const rights = tiles.map(t => {
const left = parseFloat(t.style.left)
const width = parseFloat(t.style.width)
return left + width
})
expect(Math.max(...rights)).toBeGreaterThanOrEqual(180)
expect(Math.min(...tiles.map(t => parseFloat(t.style.left)))).toBeLessThanOrEqual(0)
})
})
+152
View File
@@ -0,0 +1,152 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, JourneyStats } from '@trek/shared'
import { isStale, refreshPatch, routeFor } from '../../../src/components/Studio/travelRefresh'
/**
* A map of one trip, out of a journey made of several (#1973).
*
* A journey is a collection of trips, and printing two of them as one route
* draws a line from the last stop of the first to the first stop of the second.
* On a journey that went to Iceland in June and Portugal in September that leg
* is the longest line on the page and nobody travelled it.
*
* The scope is stored on the element rather than worked out at draw time,
* because the stops are frozen into it when it is placed. These cases pin the
* part that would otherwise rot quietly: bringing a map up to date has to keep
* the scope, or a map of Iceland turns back into a map of everywhere the first
* time somebody clicks refresh.
*/
const ICELAND = 11
const PORTUGAL = 22
const stats: JourneyStats = {
journeyId: 5,
distance: 4_000_000,
days: 21,
steps: 6,
photos: 40,
places: 12,
furthest: 3_000_000,
countries: [
{ code: 'IS', name: 'Iceland', places: 2, firstVisit: '2026-06-02' },
{ code: 'PT', name: 'Portugal', places: 2, firstVisit: '2026-09-04' },
],
points: [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík', date: '2026-06-02', country: 'IS', tripId: ICELAND, photoId: null },
{ lat: 65.68, lng: -18.12, label: 'Akureyri', date: '2026-06-06', country: 'IS', tripId: ICELAND, photoId: null },
{ lat: 38.72, lng: -9.14, label: 'Lisboa', date: '2026-09-04', country: 'PT', tripId: PORTUGAL, photoId: null },
{ lat: 41.15, lng: -8.61, label: 'Porto', date: '2026-09-08', country: 'PT', tripId: PORTUGAL, photoId: null },
],
trips: [
{ id: ICELAND, title: 'Iceland', start: '2026-06-02', end: '2026-06-14', points: 2 },
{ id: PORTUGAL, title: 'Portugal', start: '2026-09-04', end: '2026-09-12', points: 2 },
],
start: '2026-06-02',
end: '2026-09-12',
}
const map = (over: Record<string, unknown> = {}): BookElement => ({
id: 'mp1', kind: 'map', frame: { x: 10, y: 10, w: 180, h: 140 },
rotation: 0, opacity: 1, locked: false,
font: 'sans', color: '#1a1a1a', accent: '#c2410c', textScale: 1, weight: 400, stale: false,
style: 'minimal', source: 'vector', tileUrl: '', attribution: '', zoom: null, clip: 'rect',
showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: ['IS', 'PT'],
points: stats.points.map(p => ({ lat: p.lat, lng: p.lng, label: p.label })),
path: [],
fitPadding: 0.18,
fitToCountries: true,
tripId: null,
...over,
} as unknown as BookElement)
describe('which stops a map is of', () => {
it('is the whole journey when no trip is named', () => {
expect(routeFor(stats, null)).toHaveLength(4)
})
it('is one trip when one is', () => {
const route = routeFor(stats, ICELAND)
expect(route.map(p => p.label)).toEqual(['Reykjavík', 'Akureyri'])
})
it('is empty for a trip with nothing on the route, rather than everything', () => {
expect(routeFor(stats, 999)).toEqual([])
})
})
describe('bringing a map up to date', () => {
it('keeps a journey map showing the journey', () => {
const patch = refreshPatch(map(), stats) as { points: unknown[]; countries: string[] }
expect(patch.points).toHaveLength(4)
expect(patch.countries).toEqual(['IS', 'PT'])
})
/*
* The case this test exists for: refresh used to read `stats.points` flat,
* so one click turned a map of Iceland back into a map of both trips.
*/
it('keeps a trip map showing that trip', () => {
const el = map({
tripId: ICELAND,
countries: ['IS'],
points: [{ lat: 64.14, lng: -21.94, label: 'Reykjavík' }],
})
const patch = refreshPatch(el, stats) as { points: { label: string }[]; countries: string[] }
expect(patch.points.map(p => p.label)).toEqual(['Reykjavík', 'Akureyri'])
expect(patch.countries).toEqual(['IS'])
})
it('notices a trip map is behind, against its own trip rather than the journey', () => {
const behind = map({
tripId: ICELAND,
points: [{ lat: 64.14, lng: -21.94, label: 'Reykjavík' }],
})
expect(isStale(behind, stats)).toBe(true)
const current = map({
tripId: ICELAND,
points: [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík' },
{ lat: 65.68, lng: -18.12, label: 'Akureyri' },
],
})
expect(isStale(current, stats)).toBe(false)
})
it('does not call a journey map stale merely because a trip map would be', () => {
expect(isStale(map(), stats)).toBe(false)
})
/*
* A marker draws the entry's own first photograph, so adding one to an entry
* changes the map without moving a single stop. The shape test — same number
* of stops, same two ends — cannot see that, and until it did the only way to
* get the picture onto the page was to delete the map and place it again.
*/
it('notices a photograph added to a stop, though nothing moved', () => {
const el = map({
points: stats.points.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: null })),
})
expect(isStale(el, stats)).toBe(false)
const withPhoto: JourneyStats = {
...stats,
points: stats.points.map((p, i) => (i === 1 ? { ...p, photoId: 42 } : p)),
}
expect(isStale(el, withPhoto)).toBe(true)
const patch = refreshPatch(el, withPhoto) as { points: { photoId: number | null }[] }
expect(patch.points[1].photoId).toBe(42)
})
it('notices one taken away again', () => {
const el = map({
points: stats.points.map((p, i) => ({
lat: p.lat, lng: p.lng, label: p.label, photoId: i === 0 ? 7 : null,
})),
})
expect(isStale(el, stats)).toBe(true)
})
})
+182
View File
@@ -0,0 +1,182 @@
import { describe, it, expect } from 'vitest'
import {
attributionFor, projectOntoTiles, staticMapUrl, tileView, toMercatorUnit,
} from '../../../src/components/Studio/mapTiles'
/**
* Real map imagery for the book (#1973).
*
* The vector map is the default and needs none of this. What is tested here is
* the opt-in: that a tiled map lands the route on the road it followed, that it
* cannot ask for a hundred tiles to fill a postcard, and that the credit the
* licence requires is never invented and never dropped.
*/
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
const frame = { w: 150, h: 120 }
const iceland = [
{ lat: 64.1466, lng: -21.9426 },
{ lat: 65.6885, lng: -18.1262 },
]
describe('toMercatorUnit', () => {
it('puts the origin at the top left and the antimeridian at the edges', () => {
expect(toMercatorUnit(-180, 85.0511).x).toBeCloseTo(0, 5)
expect(toMercatorUnit(180, -85.0511).x).toBeCloseTo(1, 5)
expect(toMercatorUnit(0, 0)).toEqual({ x: 0.5, y: 0.5 })
})
it('clamps past the poles rather than returning infinity', () => {
const north = toMercatorUnit(0, 89.9)
expect(Number.isFinite(north.y)).toBe(true)
expect(north.y).toBeGreaterThanOrEqual(0)
})
})
describe('tileView', () => {
it('is null without a template or without points', () => {
expect(tileView(iceland, frame, '', null)).toBeNull()
expect(tileView([], frame, OSM, null)).toBeNull()
})
it('covers the route with real tile urls', () => {
const view = tileView(iceland, frame, OSM, null)!
expect(view.tiles.length).toBeGreaterThan(0)
for (const t of view.tiles) {
expect(t.url).toMatch(/^https:\/\/tile\.openstreetmap\.org\/\d+\/\d+\/\d+\.png$/)
}
})
/*
* The budget is 16×16. It was 8×8, which sounds thriftier and was not: every
* zoom level quarters the ground a tile covers, so a page-sized map lands at
* 7×9 and the step that makes it printable needs 13×17. A budget of 64, or
* even 144, stops one level short of a page worth printing — see
* mapPrintResolution.test.ts, which pins the dots per inch this buys.
*/
it('never asks for more tiles than a printed map can use', () => {
for (const z of [null, 19]) {
const view = tileView(iceland, frame, OSM, z)!
expect(view.tiles.length, `zoom ${z}`).toBeLessThanOrEqual(256)
}
})
it('zooms in on a short route and out on a long one', () => {
const city = tileView(
[{ lat: 64.14, lng: -21.94 }, { lat: 64.15, lng: -21.90 }], frame, OSM, null,
)!
const world = tileView(
[{ lat: 64.14, lng: -21.94 }, { lat: -33.86, lng: 151.2 }], frame, OSM, null,
)!
expect(city.zoom).toBeGreaterThan(world.zoom)
})
it('takes a fixed zoom when one is asked for', () => {
expect(tileView(iceland, frame, OSM, 5)!.zoom).toBe(5)
})
it('gives a single stop a window rather than dividing by zero', () => {
const view = tileView([{ lat: 64.14, lng: -21.94 }], frame, OSM, null)!
expect(view.tiles.length).toBeGreaterThan(0)
expect(Number.isFinite(view.size)).toBe(true)
expect(view.size).toBeGreaterThan(0)
})
it('drops rows past the poles, where no tile exists', () => {
const view = tileView(
[{ lat: 85, lng: 0 }, { lat: 84.9, lng: 0.1 }], frame, OSM, 3,
)!
const scale = 2 ** view.zoom
for (const t of view.tiles) {
const absoluteY = view.tileY0 + t.y
expect(absoluteY).toBeGreaterThanOrEqual(0)
expect(absoluteY).toBeLessThan(scale)
}
})
it('wraps longitude, so a route across the antimeridian keeps its tiles', () => {
const view = tileView(
[{ lat: 0, lng: 179 }, { lat: 0, lng: -179 }], frame, OSM, 3,
)!
for (const t of view.tiles) {
const x = Number(/\/(\d+)\/(\d+)\/(\d+)\.png$/.exec(t.url)![2])
expect(x).toBeGreaterThanOrEqual(0)
expect(x).toBeLessThan(2 ** view.zoom)
}
})
})
describe('projectOntoTiles', () => {
/*
* The reason the grid origin is exposed at all: the vector map fits itself to
* country outlines, so a route placed by that fit sits next to the road
* rather than on it — an error that only shows up once it is printed.
*/
it('places the route inside the frame it was fitted to', () => {
const view = tileView(iceland, frame, OSM, null)!
for (const p of iceland) {
const at = projectOntoTiles(view, p.lng, p.lat)
expect(at.x).toBeGreaterThan(-1)
expect(at.x).toBeLessThan(frame.w + 1)
expect(at.y).toBeGreaterThan(-1)
expect(at.y).toBeLessThan(frame.h + 1)
}
})
it('keeps west of east and north above south', () => {
const view = tileView(iceland, frame, OSM, null)!
const west = projectOntoTiles(view, -21.94, 64.14)
const east = projectOntoTiles(view, -18.12, 65.68)
expect(west.x).toBeLessThan(east.x)
expect(west.y).toBeGreaterThan(east.y)
})
})
describe('attribution', () => {
it('credits the source a template comes from', () => {
expect(attributionFor(OSM)).toContain('OpenStreetMap')
expect(attributionFor('https://api.mapbox.com/x/{z}/{x}/{y}')).toContain('Mapbox')
expect(attributionFor('https://api.maptiler.com/x')).toContain('MapTiler')
})
it('credits OpenStreetMap for a self-hosted mirror of it', () => {
expect(attributionFor('https://tiles.example.org/openstreetmap/{z}/{x}/{y}.png'))
.toContain('OpenStreetMap')
})
/* A wrong credit is worse than none. */
it('invents nothing for a source it does not recognise', () => {
expect(attributionFor('https://tiles.internal/{z}/{x}/{y}.png')).toBe('')
})
})
describe('staticMapUrl', () => {
it('is null without a token, since the request would only 401', () => {
expect(staticMapUrl({ points: iceland, style: '', token: '', width: 600, height: 400 })).toBeNull()
})
it('is null without points to frame', () => {
expect(staticMapUrl({ points: [], style: '', token: 'tok', width: 600, height: 400 })).toBeNull()
})
it('asks for the route bounding box at twice the size, for print', () => {
const url = staticMapUrl({ points: iceland, style: '', token: 'tok', width: 600, height: 400 })!
expect(url).toContain('@2x')
expect(url).toContain('-21.94260,64.14660,-18.12620,65.68850')
})
it('takes a mapbox:// style and passes the plain path', () => {
const url = staticMapUrl({
points: iceland, style: 'mapbox://styles/mapbox/outdoors-v12', token: 'tok',
width: 600, height: 400,
})!
expect(url).toContain('/styles/v1/mapbox/outdoors-v12/static/')
expect(url).not.toContain('mapbox://')
})
it('stays inside the size the API accepts', () => {
const url = staticMapUrl({ points: iceland, style: '', token: 'tok', width: 9000, height: 9000 })!
expect(url).toContain('1280x1280')
})
})
@@ -0,0 +1,68 @@
import { describe, it, expect, vi } from 'vitest'
import { fireEvent, render, screen } from '../../helpers/render'
import { TrimField } from '../../../src/components/Studio/TrimField'
import { PAGE_MAX_MM, PAGE_MIN_MM } from '../../../src/components/Studio/pagePresets'
/**
* The bleed and the safe margin, which the press decides and not us (#1973).
*
* Both were hard-coded into every page preset at the values a photo-book vendor
* most often asks for, 3mm and 5mm, and neither had a control anywhere. That is
* fine until a printer asks for 5 and 10, at which point the book cannot be made
* here at all — the export would carry the wrong bleed to the press and the
* crop marks would sit in the wrong place, which is the kind of mistake nobody
* finds until the guillotine has already run.
*
* They share the trim size's field, which is right — they are millimetres of
* the same kind — but that field's floor was the smallest page a book may be.
* A 3mm bleed against a 60mm floor is untypeable, so the range had to become a
* property of the measurement rather than of the control. That is what these
* cases pin.
*/
describe('a measurement field', () => {
it('still keeps the page inside what a press takes, by default', () => {
const onCommit = vi.fn()
render(<TrimField label="W" value={210} onCommit={onCommit} />)
const input = screen.getByRole('spinbutton')
expect(input.getAttribute('min')).toBe(String(PAGE_MIN_MM))
expect(input.getAttribute('max')).toBe(String(PAGE_MAX_MM))
})
it('takes a range of its own, so a 3mm bleed can be typed at all', () => {
const onCommit = vi.fn()
render(<TrimField label="Bleed" value={3} min={0} max={20} step={0.5} onCommit={onCommit} />)
const input = screen.getByRole('spinbutton')
expect(input.getAttribute('min')).toBe('0')
expect(input.getAttribute('max')).toBe('20')
fireEvent.change(input, { target: { value: '5' } })
expect(onCommit).toHaveBeenCalledWith(5)
})
/*
* The reason the field holds a draft at all: on the page size, typing "500"
* used to be seen as "5", clamped to the floor and written back under the
* cursor. The same trap applies to a bleed typed as "10".
*/
it('lets a number be typed through a value it would otherwise refuse', () => {
const onCommit = vi.fn()
render(<TrimField label="Bleed" value={3} min={2} max={20} onCommit={onCommit} />)
const input = screen.getByRole('spinbutton')
fireEvent.change(input, { target: { value: '1' } })
expect(onCommit).not.toHaveBeenCalled()
fireEvent.change(input, { target: { value: '10' } })
expect(onCommit).toHaveBeenCalledWith(10)
})
it('commits what is there when the field is left', () => {
const onCommit = vi.fn()
render(<TrimField label="Bleed" value={3} min={0} max={20} onCommit={onCommit} />)
const input = screen.getByRole('spinbutton')
fireEvent.change(input, { target: { value: '7.5' } })
fireEvent.blur(input)
expect(onCommit).toHaveBeenLastCalledWith(7.5)
})
})
+162
View File
@@ -0,0 +1,162 @@
import { describe, it, expect } from 'vitest'
import type { BookPageSetup, BookSpread } from '@trek/shared'
import { bookPageSetupSchema, normalizeBookDocument } from '@trek/shared'
import { render } from '../../helpers/render'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { PAGE_MAX_MM, PAGE_MIN_MM, PAGE_PRESETS, clampPageSize } from '../../../src/components/Studio/pagePresets'
import { relayoutSpread, type AutoInput } from '../../../src/components/Studio/autoLayout'
/**
* A free trim size, page numbers, and laying out again (#1973).
*/
type PageOver = Partial<Omit<BookPageSetup, 'pageNumbers'>> & {
pageNumbers?: Partial<BookPageSetup['pageNumbers']>
}
const page = (over: PageOver = {}): BookPageSetup =>
bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210, ...over })
const spread = (over: Partial<BookSpread> = {}): BookSpread => ({
id: 's1', role: 'inner', background: null, elements: [], parked: [], entryId: null, ...over,
})
describe('a custom trim size', () => {
it('is offered as a preset of its own', () => {
expect(PAGE_PRESETS.custom).toBeTruthy()
expect(PAGE_PRESETS.custom.id).toBe('custom')
})
it('is what the document contract already allowed', () => {
const parsed = page({ preset: 'custom', pageWidth: 240, pageHeight: 180 })
expect(parsed.preset).toBe('custom')
expect(parsed.pageWidth).toBe(240)
})
/*
* The floor is a passport-sized book and the ceiling is what a large press
* takes — past either, the editor is scaling to a smear rather than showing
* a page.
*/
it('holds a typed size inside what a press can print', () => {
expect(clampPageSize(10)).toBe(PAGE_MIN_MM)
expect(clampPageSize(9000)).toBe(PAGE_MAX_MM)
expect(clampPageSize(240)).toBe(240)
})
it('rounds to a tenth of a millimetre, not to whatever was typed', () => {
expect(clampPageSize(210.06)).toBe(210.1)
})
it('refuses nonsense rather than passing NaN into the document', () => {
expect(clampPageSize(Number.NaN)).toBe(PAGE_MIN_MM)
})
})
describe('page numbers', () => {
it('are off until asked for', () => {
expect(page().pageNumbers.show).toBe(false)
const { container } = render(<SpreadView spread={spread()} page={page()} spreadIndex={1} />)
expect(container.textContent).toBe('')
})
it('number both pages of a spread, left then right', () => {
const { container } = render(
<SpreadView spread={spread()} page={page({ pageNumbers: { show: true } })} spreadIndex={1} />,
)
expect(container.textContent).toBe('23')
})
/*
* The first inner spread opens on `startAt`, and the cover is a separate
* sheet — which is why the index has to be offset rather than used raw.
*/
it('advance by two for each spread further into the book', () => {
const p = page({ pageNumbers: { show: true } })
const third = render(<SpreadView spread={spread()} page={p} spreadIndex={3} />)
expect(third.container.textContent).toBe('67')
})
it('start where the book says, since a binder may or may not count the cover', () => {
const p = page({ pageNumbers: { show: true, startAt: 1 } })
const { container } = render(<SpreadView spread={spread()} page={p} spreadIndex={1} />)
expect(container.textContent).toBe('12')
})
/* A folio on a cover is a mistake in every book ever bound. */
it('never appear on the cover or the back cover', () => {
const p = page({ pageNumbers: { show: true } })
for (const role of ['cover', 'back'] as const) {
const { container } = render(<SpreadView spread={spread({ role })} page={p} spreadIndex={0} />)
expect(container.textContent, role).toBe('')
}
})
it('sit against the cut edge on outer, and in the gutter on inner', () => {
const outer = render(
<SpreadView spread={spread()} page={page({ pageNumbers: { show: true, position: 'outer' } })} spreadIndex={1} />,
)
const inner = render(
<SpreadView spread={spread()} page={page({ pageNumbers: { show: true, position: 'inner' } })} spreadIndex={1} />,
)
const leftOf = (c: HTMLElement) =>
parseFloat(((c.firstElementChild!.children[0]) as HTMLElement).style.left)
// Outer puts the left page's number at the margin; inner pushes it in.
expect(leftOf(outer.container)).toBeLessThan(leftOf(inner.container))
})
it('survive a round trip through the document contract', () => {
const doc = normalizeBookDocument({
version: 1, title: 'T',
page: { preset: 'custom', pageWidth: 240, pageHeight: 180, pageNumbers: { show: true, startAt: 5 } },
spreads: [],
})
expect(doc.page.pageNumbers.show).toBe(true)
expect(doc.page.pageNumbers.startAt).toBe(5)
expect(doc.page.pageWidth).toBe(240)
})
it('default in for a document written before they existed', () => {
const doc = normalizeBookDocument({
version: 1, title: 'T',
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210 },
spreads: [],
})
expect(doc.page.pageNumbers.show).toBe(false)
expect(doc.page.pageNumbers.position).toBe('outer')
})
})
describe('laying a spread out again', () => {
const input: AutoInput = {
locale: 'en', title: 'T', subtitle: null, coverPhotoId: null,
entries: [{ id: 7, title: 'A day', story: 'Words.', location: 'Here', date: '2026-06-02', photos: [] }],
page: page(), stats: null, stationsLabel: 'Stations', dayLabel: 'DAY', summaryLabel: 'Trip summary', countriesLabel: 'Countries',
}
it('rebuilds the spread from the entry it came from', () => {
const next = relayoutSpread(spread({ entryId: 7, elements: [] }), input)
expect(next).not.toBeNull()
expect(next!.entryId).toBe(7)
expect(next!.elements.length).toBeGreaterThan(0)
})
/*
* Keeping the id is what makes it read as the same page rearranged: the rail
* does not scroll and the selection does not jump to a different card.
*/
it('keeps the spread id, so the rail does not jump', () => {
const next = relayoutSpread(spread({ id: 'keep-me', entryId: 7 }), input)
expect(next!.id).toBe('keep-me')
})
it('refuses a spread that did not come from an entry', () => {
expect(relayoutSpread(spread({ entryId: null }), input)).toBeNull()
expect(relayoutSpread(spread({ role: 'cover', entryId: 7 }), input)).toBeNull()
expect(relayoutSpread(spread({ role: 'back', entryId: 7 }), input)).toBeNull()
})
it('refuses when the entry is gone from the journey', () => {
expect(relayoutSpread(spread({ entryId: 999 }), input)).toBeNull()
})
})
@@ -0,0 +1,303 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { printSheets } from '../../../src/components/Studio/printSheets'
/**
* The print view (#1973).
*
* The browser is what turns this into a PDF, so the things worth pinning are
* the ones a browser silently gets wrong: a `@page` rule that does not match
* the sheets, a document printed before its photographs arrived, and a save
* button offered while neither has happened.
*/
const labels = { save: 'Save as PDF', close: 'Close', count: '17 sheets', preparing: 'Preparing' }
function open(over: Partial<Parameters<typeof printSheets>[0]> = {}) {
return printSheets({
html: '<div class="bx-sheet"></div>',
sheetWidth: 224,
sheetHeight: 224,
title: 'Iceland',
labels,
...over,
})
}
const overlay = () => document.getElementById('bx-overlay')
const frame = () => overlay()!.querySelector('iframe')!
const saveButton = () => overlay()!.querySelector<HTMLButtonElement>('#bx-save')!
beforeEach(() => {
document.body.innerHTML = ''
document.head.innerHTML = ''
})
afterEach(() => {
overlay()?.remove()
})
describe('the document', () => {
/*
* The rule the printer measures. A mismatch here scales the whole book to fit
* whatever the browser thought the paper was — and looks perfect on screen.
*/
it('sets one page rule to the sheet size, with no printer margin', () => {
open({ sheetWidth: 224, sheetHeight: 303 })
expect(frame().srcdoc).toContain('@page { size: 224mm 303mm; margin: 0; }')
})
/*
* Hyphenation is off in every browser until the language is known, so a
* heading the editor had broken as "Lorem ip-sum" printed unbroken, ran past
* its frame and was clipped. The editor's own lang is what makes the export
* agree with what was proofread.
*/
it('carries the app language over, which is what lets the export hyphenate', () => {
document.documentElement.lang = 'de'
open()
expect(frame().srcdoc).toContain('<html lang="de">')
})
it('falls back to English rather than leaving the language unsaid', () => {
document.documentElement.lang = ''
open()
expect(frame().srcdoc).toContain('<html lang="en">')
})
it('puts the sheets in the body', () => {
open({ html: '<div class="bx-sheet">page one</div>' })
expect(frame().srcdoc).toContain('<body><div class="bx-sheet">page one</div></body>')
})
/*
* The sheets are the editor's own components, so they need the editor's own
* CSS — including the @font-face rules. Without them a book proofread in one
* typeface prints in a substitute, which is the whole reason the faces are
* bundled in the first place.
*/
it('carries the app stylesheets across, inline and linked alike', () => {
const style = document.createElement('style')
style.textContent = '.st-x { color: red }'
document.head.appendChild(style)
const link = document.createElement('link')
link.rel = 'stylesheet'
link.href = 'http://localhost/assets/app.css'
document.head.appendChild(link)
open()
const html = frame().srcdoc
expect(html).toContain('.st-x { color: red }')
expect(html).toContain('<link rel="stylesheet" href="http://localhost/assets/app.css">')
})
/*
* Photographs are the point of the thing. Browsers drop backgrounds and
* colour-managed fills by default, which is right for a web page and would
* print a photo book as an outline of itself.
*/
it('asks the browser not to strip colour', () => {
open()
expect(frame().srcdoc).toContain('print-color-adjust: exact')
})
it('escapes the title rather than letting it into the markup', () => {
open({ title: '<script>x</script> & co' })
const html = frame().srcdoc
expect(html).toContain('&lt;script&gt;x&lt;/script&gt; &amp; co')
expect(html).not.toContain('<script>x</script>')
})
/* Nothing inside the frame runs, so printing is driven from out here. */
it('withholds allow-scripts from the frame', () => {
open()
expect(frame().getAttribute('sandbox')).toBe('allow-same-origin allow-modals')
})
})
describe('a document of two sheet sizes', () => {
/*
* Spread mode mixes them: covers are one page, everything between is two.
* Before the named rule every sheet was made as wide as the widest, which put
* a cover in the middle of a spread-sized page with white either side.
*/
it('gives the one-page sheets a page box of their own', () => {
open({ sheetWidth: 426, sheetHeight: 224, singleWidth: 224, singleHeight: 224 })
const html = frame().srcdoc
expect(html).toContain('@page { size: 426mm 224mm; margin: 0; }')
expect(html).toContain('@page single { size: 224mm 224mm; margin: 0; }')
expect(html).toContain('.bx-sheet.is-single { page: single; }')
})
/* Page mode has one size, so a second rule would be noise. */
it('writes no second rule when every sheet is the same size', () => {
open({ sheetWidth: 224, sheetHeight: 224, singleWidth: 224, singleHeight: 224 })
expect(frame().srcdoc).not.toContain('@page single')
})
it('writes none when no single size was given at all', () => {
open({ sheetWidth: 224, sheetHeight: 224 })
expect(frame().srcdoc).not.toContain('@page single')
})
})
describe('fitting the preview', () => {
/*
* A spread sheet is over 400 mm across — wider than any preview pane at 1:1 —
* and the book used to run off the side, to be read by scrolling sideways.
* Only on screen: the print itself stays at full size, or the press gets a
* shrunken book.
*/
it('scales the preview down to the pane, and only the preview', () => {
open()
const html = frame().srcdoc
expect(html).toContain('@media screen { .bx-book { zoom: var(--bx-fit, 1); } }')
// Nothing in the print block touches the scale.
const printBlock = html.slice(html.indexOf('@media print'))
expect(printBlock).not.toContain('zoom')
})
it('sets the factor from the pane width once the frame is up', () => {
open({ sheetWidth: 426 })
const iframe = frame()
const root = { style: { setProperty: vi.fn() } }
Object.defineProperty(iframe, 'clientWidth', { value: 800, configurable: true })
Object.defineProperty(iframe, 'contentDocument', {
value: { documentElement: root, images: [], fonts: { ready: Promise.resolve() } },
configurable: true,
})
Object.defineProperty(iframe, 'contentWindow', { value: { print: vi.fn() }, configurable: true })
iframe.dispatchEvent(new Event('load'))
// (800 - 32) / (426 mm × 96/25.4) ≈ 0.477
const [name, value] = root.style.setProperty.mock.calls[0]
expect(name).toBe('--bx-fit')
expect(Number(value)).toBeCloseTo(0.477, 2)
})
/* A book smaller than the pane is shown at its real size, not blown up. */
it('never enlarges', () => {
open({ sheetWidth: 100 })
const iframe = frame()
const root = { style: { setProperty: vi.fn() } }
Object.defineProperty(iframe, 'clientWidth', { value: 1600, configurable: true })
Object.defineProperty(iframe, 'contentDocument', {
value: { documentElement: root, images: [], fonts: { ready: Promise.resolve() } },
configurable: true,
})
Object.defineProperty(iframe, 'contentWindow', { value: { print: vi.fn() }, configurable: true })
iframe.dispatchEvent(new Event('load'))
expect(root.style.setProperty).toHaveBeenCalledWith('--bx-fit', '1')
})
it('stops listening for resizes when it closes', () => {
const remove = vi.spyOn(window, 'removeEventListener')
const close = open()
close()
expect(remove).toHaveBeenCalledWith('resize', expect.any(Function))
remove.mockRestore()
})
})
describe('the save button', () => {
it('starts disabled, because nothing has loaded yet', () => {
open()
expect(saveButton().disabled).toBe(true)
expect(saveButton().textContent).toBe('Preparing')
})
/*
* Enabled only once the images and the fonts are in. Printing early is how a
* book comes back from the press with empty rectangles where the photographs
* were.
*/
it('waits for the pictures before offering to save', async () => {
open()
const iframe = frame()
let resolveImage: () => void = () => {}
const pending = new Promise<void>(r => { resolveImage = r })
const image = {
complete: false,
addEventListener: (event: string, fn: () => void) => {
if (event === 'load') void pending.then(fn)
},
}
Object.defineProperty(iframe, 'contentDocument', {
value: { images: [image], fonts: { ready: Promise.resolve() } },
configurable: true,
})
Object.defineProperty(iframe, 'contentWindow', { value: { print: vi.fn() }, configurable: true })
iframe.dispatchEvent(new Event('load'))
await Promise.resolve()
expect(saveButton().disabled).toBe(true)
resolveImage()
await new Promise(r => setTimeout(r, 0))
expect(saveButton().disabled).toBe(false)
expect(saveButton().textContent).toBe('Save as PDF')
})
/* One picture that will not load must not hold the whole book hostage. */
it('gives up on a broken image rather than waiting forever', async () => {
open()
const iframe = frame()
const image = {
complete: false,
addEventListener: (event: string, fn: () => void) => {
if (event === 'error') setTimeout(fn, 0)
},
}
Object.defineProperty(iframe, 'contentDocument', {
value: { images: [image], fonts: { ready: Promise.resolve() } },
configurable: true,
})
Object.defineProperty(iframe, 'contentWindow', { value: { print: vi.fn() }, configurable: true })
iframe.dispatchEvent(new Event('load'))
await new Promise(r => setTimeout(r, 5))
expect(saveButton().disabled).toBe(false)
})
it('prints the frame, not the page around it', async () => {
open()
const iframe = frame()
const print = vi.fn()
Object.defineProperty(iframe, 'contentDocument', {
value: { images: [], fonts: { ready: Promise.resolve() } },
configurable: true,
})
Object.defineProperty(iframe, 'contentWindow', { value: { print }, configurable: true })
iframe.dispatchEvent(new Event('load'))
await new Promise(r => setTimeout(r, 0))
saveButton().click()
expect(print).toHaveBeenCalled()
})
})
describe('closing', () => {
it('takes the overlay with it', () => {
open()
expect(overlay()).not.toBeNull()
overlay()!.querySelector<HTMLButtonElement>('#bx-close')!.click()
expect(overlay()).toBeNull()
})
it('closes on a click outside the card, but not inside it', () => {
open()
overlay()!.querySelector<HTMLElement>('.bx-card')!.click()
expect(overlay()).not.toBeNull()
overlay()!.click()
expect(overlay()).toBeNull()
})
it('hands back a way to close it', () => {
const close = open()
close()
expect(overlay()).toBeNull()
})
})
@@ -0,0 +1,209 @@
import { describe, it, expect } from 'vitest'
import type { BookDocument, BookElement } from '@trek/shared'
import { normalizeBookDocument } from '@trek/shared'
import {
resolveBindings, coordValue, type BindingSource,
} from '../../../src/components/Studio/resolveBindings'
/**
* A bound element catching up with the journal (#1973).
*
* The contract has promised since the format was written that fixing a typo in
* an entry fixes it in the book, and nothing did it: the words placed from the
* Entries tab were a copy taken once. What is protected here is that the link
* now works AND that it is not eager — a resolver that rewrote more than it
* should would repaint pages people have already set, and because the editor
* autosaves, it would write those repaints down.
*
* The identity assertion at the end is the one to keep. `useBookStore` decides
* whether a document is an edit by comparing object references, so a resolver
* that always returned a new object would turn opening a book into saving it.
*/
const source: BindingSource = {
title: 'Iceland, all the way round',
subtitle: 'Two weeks in June',
entries: [{
id: 7,
title: 'The black beach',
story: ' Wind, and then more wind. ',
location: 'Reynisfjara',
date: '2026-06-12',
lat: 63.4027,
lng: -19.0448,
}],
photos: [{ photoId: 31, caption: 'Basalt columns' }],
}
const common = { rotation: 0, opacity: 1, locked: false, frame: { x: 10, y: 10, w: 80, h: 12 } }
function text(over: Record<string, unknown>): BookElement {
return {
...common,
id: 't1', kind: 'text', text: '', font: 'sans', size: 11, weight: 400, italic: false,
align: 'left', leading: 1.45, tracking: 0, color: '#1a1a1a',
binding: null, overridden: false, ...over,
} as unknown as BookElement
}
function doc(elements: BookElement[]): BookDocument {
return normalizeBookDocument({
version: 1,
title: 'A book',
spreads: [{ id: 's1', role: 'inner', background: null, elements, parked: [], entryId: null }],
})
}
const firstText = (d: BookDocument) => d.spreads[0].elements[0] as Extract<BookElement, { kind: 'text' }>
describe('what a bound element picks up', () => {
it('takes the entry title someone has since corrected', () => {
const before = doc([text({ text: 'TEST1', binding: { source: 'entry.title', entryId: 7 } })])
expect(firstText(resolveBindings(before, source, 'en-GB')).text).toBe('The black beach')
})
it('takes the story, trimmed the way the layout trims it', () => {
const before = doc([text({ text: 'old', binding: { source: 'entry.story', entryId: 7 } })])
expect(firstText(resolveBindings(before, source, 'en-GB')).text).toBe('Wind, and then more wind.')
})
it('falls back to the place name for a stop nobody has titled', () => {
const src = { ...source, entries: [{ ...source.entries[0], title: null }] }
const before = doc([text({ text: 'old', binding: { source: 'entry.title', entryId: 7 } })])
expect(firstText(resolveBindings(before, src, 'en-GB')).text).toBe('Reynisfjara')
})
it('follows a renamed journey on the cover', () => {
const before = doc([text({ text: 'Untitled', binding: { source: 'journey.title' } })])
expect(firstText(resolveBindings(before, source, 'en-GB')).text).toBe('Iceland, all the way round')
})
it('follows a photo caption', () => {
const before = doc([text({ text: 'old', binding: { source: 'photo.caption', entryId: 7, photoId: 31 } })])
expect(firstText(resolveBindings(before, source, 'en-GB')).text).toBe('Basalt columns')
})
})
describe('what it refuses to touch', () => {
it('leaves an element alone once a human has edited it', () => {
const before = doc([text({
text: 'My own words', overridden: true, binding: { source: 'entry.title', entryId: 7 },
})])
expect(resolveBindings(before, source, 'en-GB')).toBe(before)
})
/*
* A journal entry that has been deleted must not take a page down with it.
* Blanking the words would turn a change in the journal into a hole in a book
* nobody would connect back to it.
*/
it('leaves an element whose entry is gone', () => {
const before = doc([text({ text: 'The black beach', binding: { source: 'entry.title', entryId: 999 } })])
expect(resolveBindings(before, source, 'en-GB')).toBe(before)
})
it('leaves a heading standing when the title has been cleared', () => {
const cleared = { ...source, entries: [{ ...source.entries[0], title: null, location: null }] }
const before = doc([text({ text: 'A heading somebody set', binding: { source: 'entry.title', entryId: 7 } })])
// The same element does follow a title that still exists, so the case
// below is the empty answer being refused rather than nothing happening.
expect(firstText(resolveBindings(before, source, 'en-GB')).text).toBe('The black beach')
expect(resolveBindings(before, cleared, 'en-GB')).toBe(before)
})
})
describe('a date, which is formatted rather than copied', () => {
it('is left alone when the element predates the stored raw value', () => {
// Every date in every book made so far is in this state, and most of them
// are set in another language or in small caps by the auto layout. Reading
// them would rewrite pages that are finished.
const before = doc([text({ text: 'MAY 28, 2026', binding: { source: 'entry.date', entryId: 7 } })])
expect(resolveBindings(before, source, 'de-DE')).toBe(before)
})
it('is left alone when the day has not moved, whatever language the reader has', () => {
const before = doc([text({
text: '12 June 2026',
binding: { source: 'entry.date', entryId: 7, value: '2026-06-12' },
})])
expect(resolveBindings(before, source, 'de-DE')).toBe(before)
})
it('is re-set when the day itself moved', () => {
const src = { ...source, entries: [{ ...source.entries[0], date: '2026-06-14' }] }
const before = doc([text({
text: '12 June 2026',
binding: { source: 'entry.date', entryId: 7, value: '2026-06-12' },
})])
const after = firstText(resolveBindings(before, src, 'en-GB'))
expect(after.text).toBe('14 June 2026')
// And the raw value moves with it, or the next open would do it all again.
expect(after.binding?.value).toBe('2026-06-14')
})
})
describe('coordinates', () => {
it('are re-set when the stop moved, in the format the element was placed with', () => {
const src = { ...source, entries: [{ ...source.entries[0], lat: 64.1466, lng: -21.9426 }] }
const before = doc([text({
text: `63° 24' 10" S 19° 2' 41" W`,
binding: {
source: 'entry.location', entryId: 7, format: 'decimal', value: coordValue(63.4027, -19.0448),
},
})])
const after = firstText(resolveBindings(before, src, 'en-GB'))
expect(after.text).toBe('64.1466° N 21.9426° W')
expect(after.binding?.value).toBe('64.1466,-21.9426')
})
it('are left alone when the stop has not moved', () => {
const before = doc([text({
text: 'anything at all',
binding: {
source: 'entry.location', entryId: 7, format: 'dms', value: coordValue(63.4027, -19.0448),
},
})])
expect(resolveBindings(before, source, 'en-GB')).toBe(before)
})
/*
* The same source without a format is the place *name* — that is what the
* "Place" chip has always placed, and it is words rather than a reading, so
* it follows the journal directly.
*/
it('are not what an unformatted location binding means', () => {
const before = doc([text({ text: 'Vík', binding: { source: 'entry.location', entryId: 7 } })])
expect(firstText(resolveBindings(before, source, 'en-GB')).text).toBe('Reynisfjara')
})
})
describe('the document it hands back', () => {
it('is the very same object when nothing resolved differently', () => {
const before = doc([
text({ id: 't1', text: 'The black beach', binding: { source: 'entry.title', entryId: 7 } }),
text({ id: 't2', text: 'Iceland, all the way round', binding: { source: 'journey.title' } }),
])
expect(resolveBindings(before, source, 'en-GB')).toBe(before)
})
it('shares through every spread and element it did not change', () => {
const before = normalizeBookDocument({
version: 1,
title: 'A book',
spreads: [
{
id: 's1', role: 'inner', background: null, entryId: null, parked: [],
elements: [text({ id: 'keep', text: 'Iceland, all the way round', binding: { source: 'journey.title' } })],
},
{
id: 's2', role: 'inner', background: null, entryId: null, parked: [],
elements: [text({ id: 'move', text: 'TEST1', binding: { source: 'entry.title', entryId: 7 } })],
},
],
})
const after = resolveBindings(before, source, 'en-GB')
expect(after).not.toBe(before)
expect(after.spreads[0]).toBe(before.spreads[0])
expect(after.spreads[1]).not.toBe(before.spreads[1])
})
})
@@ -0,0 +1,62 @@
import { describe, it, expect } from 'vitest'
import type { BookElement } from '@trek/shared'
import { bookElementSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { TravelElementView } from '../../../src/components/Studio/TravelElements'
/** The renderer positions from the outside; a bare box is enough here. */
const box = { position: 'absolute' as const, width: '100mm', height: '80mm' }
/**
* What the travel elements are drawn in (#1973).
*
* Ink by default rather than the app's orange: a book is printed, and a colour
* that arrives without being chosen turns every element into the same accent
* whether the book wants one or not. The one exception is the dark map, where
* ink would be a black line on a near-black country.
*/
const mapEl = (over: Record<string, unknown> = {}): BookElement =>
bookElementSchema.parse({
id: 'm1', kind: 'map', frame: { x: 0, y: 0, w: 100, h: 80 },
points: [
{ lat: 64.1, lng: -21.9, label: 'A' },
{ lat: 65.7, lng: -18.1, label: 'B' },
],
countries: ['IS'],
showRoute: true,
showPins: true,
...over,
})
const strokes = (container: HTMLElement) =>
[...container.querySelectorAll('polyline')].map(p => p.getAttribute('stroke'))
describe('the default', () => {
it('is ink, not the app accent', () => {
const el = mapEl()
expect((el as { accent: string }).accent).toBe('#111111')
})
it('draws the route in ink on a light map', () => {
const { container } = render(<TravelElementView el={mapEl({ style: 'minimal' })} frameStyle={box} />)
expect(strokes(container)).toContain('#111111')
})
})
describe('the dark map', () => {
/* Ink on near-black is a line nobody can see. */
it('draws the route pale instead', () => {
const { container } = render(<TravelElementView el={mapEl({ style: 'dark' })} frameStyle={box} />)
expect(strokes(container)[0]).toBe('#f2efe9')
})
/*
* Only the default is overridden. A colour somebody picked is theirs, even
* when it is a poor choice on a dark map — that is their call to make.
*/
it('leaves a chosen colour alone', () => {
const { container } = render(<TravelElementView el={mapEl({ style: 'dark', accent: '#c2410c' })} frameStyle={box} />)
expect(strokes(container)[0]).toBe('#c2410c')
})
})
+319
View File
@@ -0,0 +1,319 @@
import { describe, it, expect } from 'vitest'
import { BOOK_SHAPES } from '@trek/shared'
import {
FRAME_SHAPES, HOLED_SHAPES, SHAPE_GROUPS, SHAPE_PATHS, scalePath, unitPath,
} from '../../../src/components/Studio/shapes'
/**
* The shape library (#1973).
*
* The invariant worth guarding is the boring one: `scalePath` scales numbers by
* position, alternating x and y from the start of the path. That only works if
* every path is written in the absolute M/L/C/Q/Z subset with an even count of
* numbers per command. Break that in one hand-drawn path and *that shape alone*
* comes out sheared — which is exactly the kind of bug nobody notices until it
* is printed.
*/
/** Commands and their coordinate counts. Anything else is out of the subset. */
const COMMANDS: Record<string, number> = { M: 2, L: 2, C: 6, Q: 4, Z: 0 }
/**
* Where the outline actually goes.
*
* Measuring the raw numbers would measure the control points, which for a curve
* sit outside the shape by design — a quadratic never reaches its control, and a
* cubic's two controls are usually well past the ink. Sampling the curves gives
* the box the shape really occupies, which is the thing "normalised to 0..100"
* is a claim about.
*/
function drawnBounds(path: string): { minX: number; minY: number; maxX: number; maxY: number } {
const nums = (path.match(/-?\d*\.?\d+/g) ?? []).map(Number)
const tokens = path.match(/[MLCQZ]/g) ?? []
let i = 0
let cx = 0
let cy = 0
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
const hit = (x: number, y: number) => {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
}
for (const cmd of tokens) {
if (cmd === 'Z') continue
if (cmd === 'M' || cmd === 'L') {
cx = nums[i++]; cy = nums[i++]
hit(cx, cy)
continue
}
if (cmd === 'Q') {
const [qx, qy, x, y] = [nums[i++], nums[i++], nums[i++], nums[i++]]
for (let t = 0; t <= 1.0001; t += 0.05) {
const u = 1 - t
hit(u * u * cx + 2 * u * t * qx + t * t * x, u * u * cy + 2 * u * t * qy + t * t * y)
}
cx = x; cy = y
continue
}
// C
const [c1x, c1y, c2x, c2y, x, y] = [nums[i++], nums[i++], nums[i++], nums[i++], nums[i++], nums[i++]]
for (let t = 0; t <= 1.0001; t += 0.05) {
const u = 1 - t
hit(
u * u * u * cx + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * x,
u * u * u * cy + 3 * u * u * t * c1y + 3 * u * t * t * c2y + t * t * t * y,
)
}
cx = x; cy = y
}
return { minX, minY, maxX, maxY }
}
/** Split a path into its subpaths, one per `M`. */
function subpaths(path: string): string[] {
return path.split('M').filter(Boolean).map(p => `M${p}`)
}
/**
* Twice the signed area of a subpath, sampling curves so a bubble's rounded
* body is measured as the ring it draws rather than as its corner points.
* Only the sign matters here — it is the winding direction.
*/
function signedArea(path: string): number {
const { points } = flatten(path)
let a = 0
for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
a += points[j][0] * points[i][1] - points[i][0] * points[j][1]
}
return a / 2
}
/** The subpath as a polyline, curves sampled. */
function flatten(path: string): { points: [number, number][] } {
const nums = (path.match(/-?\d*\.?\d+/g) ?? []).map(Number)
const cmds = path.match(/[MLCQZ]/g) ?? []
const points: [number, number][] = []
let i = 0
let cx = 0
let cy = 0
for (const cmd of cmds) {
if (cmd === 'Z') continue
if (cmd === 'M' || cmd === 'L') {
cx = nums[i++]; cy = nums[i++]
points.push([cx, cy])
continue
}
if (cmd === 'Q') {
const [qx, qy, x, y] = [nums[i++], nums[i++], nums[i++], nums[i++]]
for (let t = 0.25; t <= 1.0001; t += 0.25) {
const u = 1 - t
points.push([u * u * cx + 2 * u * t * qx + t * t * x, u * u * cy + 2 * u * t * qy + t * t * y])
}
cx = x; cy = y
continue
}
const [ax, ay, bx, by, x, y] = [nums[i++], nums[i++], nums[i++], nums[i++], nums[i++], nums[i++]]
for (let t = 0.25; t <= 1.0001; t += 0.25) {
const u = 1 - t
points.push([
u * u * u * cx + 3 * u * u * t * ax + 3 * u * t * t * bx + t * t * t * x,
u * u * u * cy + 3 * u * u * t * ay + 3 * u * t * t * by + t * t * t * y,
])
}
cx = x; cy = y
}
return { points }
}
function commandsOf(path: string): { cmd: string; nums: number }[] {
const out: { cmd: string; nums: number }[] = []
const re = /([MLCQZ])([^MLCQZ]*)/g
let m: RegExpExecArray | null
while ((m = re.exec(path))) {
const nums = (m[2].match(/-?\d*\.?\d+/g) ?? []).length
out.push({ cmd: m[1], nums })
}
return out
}
describe('SHAPE_PATHS', () => {
it('has a path for every shape the document schema allows', () => {
for (const shape of BOOK_SHAPES) {
expect(SHAPE_PATHS[shape], shape).toBeTruthy()
}
})
it('uses only absolute M, L, C, Q and Z', () => {
for (const shape of BOOK_SHAPES) {
const path = SHAPE_PATHS[shape]
expect(path, shape).not.toMatch(/[mlcqzahsvtHSVTA]/)
expect(path, shape).toMatch(/^M/)
}
})
it('gives every command the number of coordinates it takes', () => {
for (const shape of BOOK_SHAPES) {
for (const { cmd, nums } of commandsOf(SHAPE_PATHS[shape])) {
expect(nums, `${shape}: ${cmd}`).toBe(COMMANDS[cmd])
}
}
})
/*
* The one that makes scalePath valid: numbers alternate x, y across the whole
* path, so an odd total anywhere would swap the axes for everything after it.
*/
it('holds an even number of coordinates, so x/y alternation survives the whole path', () => {
for (const shape of BOOK_SHAPES) {
const total = (SHAPE_PATHS[shape].match(/-?\d*\.?\d+/g) ?? []).length
expect(total % 2, shape).toBe(0)
}
})
it('closes every subpath', () => {
for (const shape of BOOK_SHAPES) {
const opens = (SHAPE_PATHS[shape].match(/M/g) ?? []).length
const closes = (SHAPE_PATHS[shape].match(/Z/g) ?? []).length
expect(closes, shape).toBe(opens)
}
})
/*
* The invariant the editor depends on: selection outlines, resize handles and
* snap targets are all drawn from the element's frame, so a shape that does
* not fill its frame cannot be aligned to anything visible. `normalise()` in
* shapes.ts makes this true by construction; this checks it stayed true.
*
* Every offender is collected rather than failing on the first — a change to
* the geometry usually breaks a whole family of shapes at once, and one name
* at a time is a slow way to find that out.
*/
it('fills its 0..100 box exactly, on both axes', () => {
const off: string[] = []
for (const shape of BOOK_SHAPES) {
const { minX, minY, maxX, maxY } = drawnBounds(SHAPE_PATHS[shape])
const flat = shape === 'line' // a rule genuinely has no height
const wrong = Math.abs(minX) > 0.3 || Math.abs(maxX - 100) > 0.3
|| (!flat && (Math.abs(minY) > 0.3 || Math.abs(maxY - 100) > 0.3))
if (wrong) {
off.push(`${shape}: x ${minX.toFixed(1)}..${maxX.toFixed(1)} y ${minY.toFixed(1)}..${maxY.toFixed(1)}`)
}
}
expect(off).toEqual([])
})
})
describe('scalePath', () => {
it('leaves a path alone at 100 by 100', () => {
expect(scalePath('M0 0L100 0L100 100Z', 100, 100)).toBe('M0 0L100 0L100 100Z')
})
it('scales x and y independently', () => {
expect(scalePath('M0 0L100 50Z', 50, 20)).toBe('M0 0L50 10Z')
})
it('keeps alternating across commands with different arities', () => {
// C takes six numbers: three x/y pairs. The pair after it must still start
// on x.
expect(scalePath('M0 0C10 20 30 40 50 60L100 100Z', 10, 100))
.toBe('M0 0C1 20 3 40 5 60L10 100Z')
})
it('carries negative coordinates through with their sign', () => {
expect(scalePath('M-10 -20L100 100Z', 50, 50)).toBe('M-5 -10L50 50Z')
})
it('rounds to three decimals rather than emitting float noise', () => {
const out = scalePath('M33 33Z', 7, 7)
expect(out).toBe('M2.31 2.31Z')
expect(out).not.toMatch(/\d{5}/)
})
it('produces a drawable path for every shape at an extreme aspect ratio', () => {
for (const shape of BOOK_SHAPES) {
const wide = scalePath(SHAPE_PATHS[shape], 300, 4)
expect(wide, shape).not.toMatch(/NaN|Infinity|undefined/)
const nums = (wide.match(/-?\d*\.?\d+/g) ?? []).map(Number)
expect(nums.every(Number.isFinite), shape).toBe(true)
}
})
})
describe('unitPath', () => {
it('maps the 0..100 box onto 0..1 for an objectBoundingBox clip', () => {
expect(unitPath('M0 0L100 50Z')).toBe('M0 0L1 0.5Z')
})
it('scales both axes by the same factor, unlike scalePath', () => {
expect(unitPath('M25 75Z')).toBe('M0.25 0.75Z')
})
it('keeps every shape within the unit box, allowing for the blobs slack', () => {
for (const shape of BOOK_SHAPES) {
const { minX, minY, maxX, maxY } = drawnBounds(unitPath(SHAPE_PATHS[shape]))
expect(Math.min(minX, minY), shape).toBeGreaterThanOrEqual(-0.06)
expect(Math.max(maxX, maxY), shape).toBeLessThanOrEqual(1.06)
}
})
})
describe('the panel groupings', () => {
it('offers every shape in exactly one group', () => {
const grouped = SHAPE_GROUPS.flatMap(g => g.shapes)
expect(new Set(grouped).size).toBe(grouped.length)
})
it('groups every shape the schema allows, so none is unreachable in the UI', () => {
const grouped = new Set(SHAPE_GROUPS.flatMap(g => g.shapes))
// 'line' is offered as its own tile in the Lines section rather than as a
// shape you pick from a grid, since a hairline is invisible at tile size.
const missing = BOOK_SHAPES.filter(s => s !== 'line' && !grouped.has(s))
expect(missing).toEqual([])
})
it('only offers frames that actually exist as shapes', () => {
for (const shape of FRAME_SHAPES) {
expect(SHAPE_PATHS[shape], shape).toBeTruthy()
}
})
it('keeps thin and hollow shapes out of the frame list, since a photo cut to one is unreadable', () => {
for (const thin of ['line', 'gear', 'bubble-think', 'sparkle', 'cross', 'plus'] as const) {
expect(FRAME_SHAPES, thin).not.toContain(thin)
}
})
/*
* The bug this catches: a speech bubble's tail was listed anticlockwise while
* its body ran clockwise, and under the default non-zero fill rule the two
* cancelled where they met — the tail came out as a wedge of hole punched
* through the bubble. Nothing about the geometry was wrong; only the order
* the points were written in.
*
* So every subpath of a shape has to wind the same way as the first, except
* where a hole is the point.
*/
it('winds every subpath the same way, so overlapping parts join rather than cancel', () => {
const wrong: string[] = []
for (const shape of BOOK_SHAPES) {
if (HOLED_SHAPES.has(shape)) continue
const windings = subpaths(SHAPE_PATHS[shape]).map(signedArea)
if (windings.length < 2) continue
const first = Math.sign(windings[0])
if (windings.some(a => Math.sign(a) !== first)) {
wrong.push(`${shape}: ${windings.map(a => a.toFixed(0)).join(', ')}`)
}
}
expect(wrong).toEqual([])
})
it('marks only the shapes drawn as an outer ring plus an inner hole', () => {
for (const shape of HOLED_SHAPES) {
const subpaths = (SHAPE_PATHS[shape].match(/M/g) ?? []).length
expect(subpaths, shape).toBeGreaterThan(1)
}
})
})
+156
View File
@@ -0,0 +1,156 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { exportSpread, importSpread, MAX_SPREAD_FILE_BYTES } from '../../../src/components/Studio/spreadFile'
/**
* A spread leaving one book and arriving in another (#1973).
*
* Two things are being tested here, and the second matters more than the first:
* that a design survives the round trip onto a different page size, and that a
* file somebody else wrote cannot put anything into the document that the
* person opening it did not ask for.
*/
const square = bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210 })
const a4 = bookPageSetupSchema.parse({ preset: 'a4-landscape', pageWidth: 297, pageHeight: 210 })
const el = (over: Record<string, unknown>): BookElement => ({
id: 'e1', rotation: 0, opacity: 1, locked: false,
frame: { x: 21, y: 42, w: 105, h: 63 },
...over,
} as BookElement)
const spread = (elements: BookElement[], background: string | null = '#faf8f4'): BookSpread => ({
id: 'sp1', role: 'inner', background, elements, parked: [], entryId: null,
})
describe('exportSpread', () => {
it('measures everything as a fraction of the page it was drawn on', () => {
const file = exportSpread(spread([el({ kind: 'shape', shape: 'rect', fill: '#112233' })]), square)
expect(file.format).toBe('trek.studio.spread')
expect(file.elements[0]).toMatchObject({
frame: { x: 0.1, y: 0.2, w: 0.5, h: 0.3 },
})
})
it('leaves the photographs behind', () => {
const file = exportSpread(spread([el({ kind: 'photo', photoId: 41 })]), square)
expect((file.elements[0] as { photoId: number | null }).photoId).toBeNull()
})
it('leaves the map source behind, because it can carry a token', () => {
const file = exportSpread(spread([el({
kind: 'map',
tileUrl: 'https://api.mapbox.com/styles/v1/x/static/0,0,2/300x200?access_token=pk.SECRET',
attribution: 'Mapbox',
})]), square)
expect(JSON.stringify(file)).not.toContain('SECRET')
})
it('does not carry the ids across, since they only mean anything at home', () => {
const file = exportSpread(spread([el({ kind: 'shape', shape: 'rect' })]), square)
expect(file.elements[0]).not.toHaveProperty('id')
})
})
describe('importSpread', () => {
it('lays a square design out on a landscape page', () => {
const file = exportSpread(spread([el({ kind: 'shape', shape: 'rect', fill: '#112233' })]), square)
const back = importSpread(file, a4)!
expect(back).not.toBeNull()
// A tenth of the way in, and half the width, on whatever page it lands on.
expect(back.elements[0].frame.x).toBeCloseTo(29.7, 1)
expect(back.elements[0].frame.w).toBeCloseTo(148.5, 1)
expect(back.elements[0].frame.y).toBeCloseTo(42, 1)
})
it('keeps the design as it was drawn', () => {
const file = exportSpread(spread([el({ kind: 'shape', shape: 'rect', fill: '#112233' })]), square)
const back = importSpread(file, a4)!
expect(back.background).toBe('#faf8f4')
expect((back.elements[0] as { fill: string }).fill).toBe('#112233')
})
it('refuses a file that is not one of ours', () => {
expect(importSpread({ hello: 'world' }, a4)).toBeNull()
expect(importSpread(null, a4)).toBeNull()
expect(importSpread({ format: 'trek.studio.spread' }, a4)).toBeNull()
})
it('drops an element the document contract will not have', () => {
const back = importSpread({
format: 'trek.studio.spread',
version: 1,
background: null,
elements: [
{ kind: 'shape', shape: 'rect', fill: '#112233', frame: { x: 0.1, y: 0.1, w: 0.2, h: 0.2 } },
{ kind: 'not-a-thing', frame: { x: 0.1, y: 0.1, w: 0.2, h: 0.2 } },
],
}, a4)!
expect(back.elements).toHaveLength(1)
})
it('will not take a background that is not a colour', () => {
const back = importSpread({
format: 'trek.studio.spread',
version: 1,
background: 'url(https://example.invalid/pixel.png)',
elements: [{ kind: 'shape', shape: 'rect', frame: { x: 0.1, y: 0.1, w: 0.2, h: 0.2 } }],
}, a4)!
expect(back.background).toBeNull()
})
it('blanks a map source the file tried to bring with it', () => {
const back = importSpread({
format: 'trek.studio.spread',
version: 1,
background: null,
elements: [{
kind: 'map',
tileUrl: 'https://tracker.invalid/{z}/{x}/{y}.png',
attribution: 'x',
frame: { x: 0.1, y: 0.1, w: 0.4, h: 0.4 },
}],
}, a4)!
expect((back.elements[0] as { tileUrl: string }).tileUrl).toBe('')
})
it('takes no more elements than a spread is allowed to hold', () => {
const one = { kind: 'shape', shape: 'rect', frame: { x: 0.1, y: 0.1, w: 0.1, h: 0.1 } }
const back = importSpread({
format: 'trek.studio.spread',
version: 1,
background: null,
elements: Array.from({ length: 400 }, () => one),
}, a4)!
expect(back.elements).toHaveLength(60)
})
it('gives every element an id of its own', () => {
const one = { kind: 'shape', shape: 'rect', frame: { x: 0.1, y: 0.1, w: 0.1, h: 0.1 } }
const back = importSpread({
format: 'trek.studio.spread', version: 1, background: null, elements: [one, one, one],
}, a4)!
expect(new Set(back.elements.map(e => e.id)).size).toBe(3)
})
it('arrives as an inner spread, never as a cover', () => {
const back = importSpread({
format: 'trek.studio.spread', version: 1, background: null,
elements: [{ kind: 'shape', shape: 'rect', frame: { x: 0.1, y: 0.1, w: 0.1, h: 0.1 }, role: 'cover' }],
}, a4)!
expect(back.role).toBe('inner')
})
})
describe('the size limit', () => {
it('is small enough to be a limit and large enough for any real spread', () => {
// A full spread of 60 elements, as JSON, against the ceiling the file
// picker enforces before it reads anything.
const full = exportSpread(spread(Array.from({ length: 60 }, (_, i) =>
el({ id: `e${i}`, kind: 'text', text: 'x'.repeat(200) }))), square)
expect(JSON.stringify(full).length).toBeLessThan(MAX_SPREAD_FILE_BYTES)
expect(MAX_SPREAD_FILE_BYTES).toBeLessThanOrEqual(2 * 1024 * 1024)
})
})
@@ -0,0 +1,172 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { BookDocument, BookElement, BookSpread } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { render } from '../../helpers/render'
import { useStudioStore } from '../../../src/store/studioStore'
import { SpreadView } from '../../../src/components/Studio/SpreadView'
import { snapTargets } from '../../../src/components/Studio/useSpreadInteraction'
/**
* Three fixes to the editor (#1973).
*
* An empty frame that did not wear the frame it will wear, a page added in
* front of the cover with no way back, and a snap that only caught the fold.
*/
const page = bookPageSetupSchema.parse({ preset: 'square-210', pageWidth: 210, pageHeight: 210, safe: 8 })
const frame = (over: Partial<BookElement> = {}): BookElement => ({
id: 'f1', kind: 'photo', frame: { x: 20, y: 20, w: 120, h: 90 },
rotation: 0, opacity: 1, locked: false,
photoId: null, fit: 'cover', focalX: 0.5, focalY: 0.5,
radius: 0, filter: 'none', mask: null, frameStyle: 'none',
...over,
} as BookElement)
const spread = (elements: BookElement[], role: BookSpread['role'] = 'inner'): BookSpread => ({
id: 's1', role, background: '#ffffff', elements, parked: [], entryId: null,
})
const doc = (spreads: BookSpread[]): BookDocument =>
({ version: 1, title: 'T', page, spreads } as BookDocument)
describe('an empty frame', () => {
/*
* It used to render on its own, ignoring frameStyle: a Polaroid placeholder
* was a plain dashed rectangle until a photograph landed in it and the chin
* appeared from nowhere.
*/
it('wears the frame it will wear once it is filled', () => {
const { container } = render(
<SpreadView spread={spread([frame({ frameStyle: 'polaroid' })])} page={page} spreadIndex={1} />,
)
const outer = container.querySelector<HTMLElement>('[style*="left: 20mm"]')!
// A Polaroid's white card and the shadow of a print lying on a page.
expect(outer.style.background).toContain('rgb(255, 255, 255)')
expect(outer.style.boxShadow).toBeTruthy()
})
it('shows a film frame as film, black card and all', () => {
const { container } = render(
<SpreadView spread={spread([frame({ frameStyle: 'film' })])} page={page} spreadIndex={1} />,
)
const outer = container.querySelector<HTMLElement>('[style*="left: 20mm"]')!
expect(outer.style.background).toContain('rgb(20, 20, 20)')
})
it('leaves a plain frame plain', () => {
const { container } = render(
<SpreadView spread={spread([frame()])} page={page} spreadIndex={1} />,
)
const outer = container.querySelector<HTMLElement>('[style*="left: 20mm"]')!
expect(outer.style.boxShadow).toBe('')
})
/* In the bound book an unfilled frame is nothing at all. */
it('prints as nothing', () => {
const { container } = render(
<SpreadView spread={spread([frame({ frameStyle: 'polaroid' })])} page={page} spreadIndex={1} print />,
)
expect(container.querySelector('[style*="left: 20mm"]')).toBeNull()
})
})
describe('what an edge snaps to', () => {
/*
* The renderer draws the safe area per page, so a spread shows a dashed rule
* inset from each of its four vertical edges — including the two either side
* of the fold. Only the outer pair was a target, so dragging inwards caught
* the gutter and nothing else: the line you could see right before it was not
* something the pointer knew about.
*/
it('includes the safe lines either side of the fold', () => {
const { xs } = snapTargets(spread([]), page, new Set())
expect(xs).toContain(210) // the fold
expect(xs).toContain(202) // 210 - safe, the left page's inner rule
expect(xs).toContain(218) // 210 + safe, the right page's
})
it('keeps the outer ones it always had', () => {
const { xs, ys } = snapTargets(spread([]), page, new Set())
expect(xs).toContain(8) // safe
expect(xs).toContain(412) // 420 - safe
expect(ys).toContain(8)
expect(ys).toContain(202) // 210 - safe
})
/* A cover is one page and has no fold to snap to. */
it('has no fold on a single page', () => {
const { xs } = snapTargets(spread([], 'cover'), page, new Set())
expect(xs).not.toContain(218)
})
/*
* On a spread the halfway mark is the fold, not the middle of anything you
* are composing on: a picture centred on its own page had no line to find.
*/
it('includes the centre of each page, which is not the fold', () => {
const { xs } = snapTargets(spread([]), page, new Set())
expect(xs).toContain(105) // middle of the left page
expect(xs).toContain(315) // middle of the right
})
it('includes the quarters, where a two-column split lands', () => {
const { xs, ys } = snapTargets(spread([]), page, new Set())
expect(xs).toContain(52.5)
expect(xs).toContain(157.5)
expect(ys).toContain(52.5)
expect(ys).toContain(157.5)
})
it('centres a single page on itself', () => {
const { xs } = snapTargets(spread([], 'cover'), page, new Set())
expect(xs).toContain(105)
expect(xs).not.toContain(315)
})
it('snaps to the other elements on the page too', () => {
const { xs } = snapTargets(spread([frame({ id: 'other' })]), page, new Set())
expect(xs).toContain(20) // its left edge
expect(xs).toContain(140) // and its right
})
it('ignores the element being dragged, so it cannot snap to itself', () => {
const { xs } = snapTargets(spread([frame({ id: 'me' })]), page, new Set(['me']))
expect(xs).not.toContain(140)
})
})
describe('adding a page', () => {
beforeEach(() => {
useStudioStore.getState().load(doc([spread([], 'cover'), spread([], 'back')]))
})
/*
* The bug: an empty book reports its last inner spread as -1, which asked for
* a page at index 0 — in front of the cover, where it could not be moved back
* from either, because a move only ever swaps with another inner spread.
*/
it('lands after the cover even when the book has no inner pages yet', () => {
useStudioStore.getState().addSpread(-1)
const roles = useStudioStore.getState().doc!.spreads.map(s => s.role)
expect(roles).toEqual(['cover', 'inner', 'back'])
})
it('still lands after the page it was asked for', () => {
useStudioStore.getState().addSpread(-1)
useStudioStore.getState().addSpread(1)
expect(useStudioStore.getState().doc!.spreads.map(s => s.role))
.toEqual(['cover', 'inner', 'inner', 'back'])
})
it('never lands behind the back cover', () => {
useStudioStore.getState().addSpread(99)
const roles = useStudioStore.getState().doc!.spreads.map(s => s.role)
expect(roles[roles.length - 1]).toBe('back')
})
it('selects the page it just made', () => {
useStudioStore.getState().addSpread(-1)
expect(useStudioStore.getState().activeSpread).toBe(1)
})
})
@@ -0,0 +1,313 @@
import { describe, it, expect, beforeEach } from 'vitest'
import type { BookDocument, BookElement, BookSpread } from '@trek/shared'
import { useStudioStore } from '../../../src/store/studioStore'
/**
* Spread management (#1973).
*
* The rule everything else follows from: the cover and the back cover are fixed
* points. A book has exactly one of each, they are single pages, and no amount
* of dragging in the rail should be able to produce a book with two covers or
* none. Every operation here refuses on anything that is not an inner spread.
*/
const el = (id: string): BookElement => ({
id, kind: 'shape', frame: { x: 0, y: 0, w: 10, h: 10 },
rotation: 0, opacity: 1, locked: false,
shape: 'rect', fill: '#000000', gradient: 'none',
stroke: null, strokeWidth: 0, strokeStyle: 'solid', radius: 0,
} as BookElement)
const spread = (id: string, role: BookSpread['role'], elements: BookElement[] = []): BookSpread => ({
id, role, background: null, elements, parked: [], entryId: null,
})
function book(...spreads: BookSpread[]): BookDocument {
return {
version: 1, title: 'T',
page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 5 },
spreads,
} as BookDocument
}
const store = () => useStudioStore.getState()
const roles = () => store().doc!.spreads.map(s => s.role)
const ids = () => store().doc!.spreads.map(s => s.id)
beforeEach(() => {
useStudioStore.getState().load(book(
spread('cover', 'cover'),
spread('a', 'inner'),
spread('b', 'inner'),
spread('c', 'inner'),
spread('back', 'back'),
))
})
describe('canEditSpread', () => {
it('is true for an inner spread and false for the covers', () => {
expect(store().canEditSpread(0)).toBe(false)
expect(store().canEditSpread(1)).toBe(true)
expect(store().canEditSpread(4)).toBe(false)
})
it('is false past either end rather than throwing', () => {
expect(store().canEditSpread(-1)).toBe(false)
expect(store().canEditSpread(99)).toBe(false)
})
})
describe('addSpread', () => {
it('inserts after the given spread and selects it', () => {
store().addSpread(1)
expect(ids()).toEqual(['cover', 'a', expect.any(String), 'b', 'c', 'back'])
expect(store().activeSpread).toBe(2)
})
it('inserts an inner spread, whatever it was asked to follow', () => {
store().addSpread(0)
expect(roles()[1]).toBe('inner')
})
it('starts the new spread empty', () => {
store().addSpread(1)
const made = store().doc!.spreads[2]
expect(made.elements).toEqual([])
expect(made.parked).toEqual([])
expect(made.entryId).toBeNull()
})
/*
* The one that keeps the book a book: a page inserted behind the back cover
* is a page nobody would ever turn to.
*/
it('never lands behind the back cover', () => {
store().addSpread(4)
expect(roles()[roles().length - 1]).toBe('back')
expect(roles()).toEqual(['cover', 'inner', 'inner', 'inner', 'inner', 'back'])
})
it('gives the new spread an id of its own', () => {
store().addSpread(1)
expect(new Set(ids()).size).toBe(ids().length)
})
it('is one undo step', () => {
store().addSpread(1)
expect(store().doc!.spreads).toHaveLength(6)
store().undo()
expect(store().doc!.spreads).toHaveLength(5)
})
})
describe('duplicateSpread', () => {
beforeEach(() => {
useStudioStore.getState().load(book(
spread('cover', 'cover'),
spread('a', 'inner', [el('e1'), el('e2')]),
spread('back', 'back'),
))
})
it('copies the contents directly after the original', () => {
store().duplicateSpread(1)
expect(store().doc!.spreads).toHaveLength(4)
expect(store().doc!.spreads[2].elements).toHaveLength(2)
expect(store().activeSpread).toBe(2)
})
/*
* Two elements sharing an id would make selection ambiguous and every lookup
* that follows it wrong — including delete, which would take both.
*/
it('gives the copied elements fresh ids', () => {
store().duplicateSpread(1)
const [original, copy] = [store().doc!.spreads[1], store().doc!.spreads[2]]
expect(copy.id).not.toBe(original.id)
for (const e of copy.elements) {
expect(original.elements.map(o => o.id)).not.toContain(e.id)
}
})
it('refuses on the cover and on the back cover', () => {
store().duplicateSpread(0)
store().duplicateSpread(2)
expect(store().doc!.spreads).toHaveLength(3)
})
})
describe('removeSpread', () => {
it('takes the spread out', () => {
store().removeSpread(2)
expect(ids()).toEqual(['cover', 'a', 'c', 'back'])
})
it('refuses on the cover and on the back cover', () => {
store().removeSpread(0)
store().removeSpread(4)
expect(store().doc!.spreads).toHaveLength(5)
expect(roles()).toEqual(['cover', 'inner', 'inner', 'inner', 'back'])
})
it('lands on the spread that took its place', () => {
store().setActiveSpread(2)
store().removeSpread(2)
expect(store().activeSpread).toBe(2)
expect(ids()[2]).toBe('c')
})
it('clears the selection, since what was selected is gone', () => {
store().select(['e1'])
store().removeSpread(1)
expect(store().selection).toEqual([])
})
it('is undoable', () => {
store().removeSpread(2)
store().undo()
expect(ids()).toEqual(['cover', 'a', 'b', 'c', 'back'])
})
})
describe('moveSpread', () => {
it('swaps with the spread before it', () => {
store().moveSpread(2, -1)
expect(ids()).toEqual(['cover', 'b', 'a', 'c', 'back'])
expect(store().activeSpread).toBe(1)
})
it('swaps with the spread after it', () => {
store().moveSpread(1, 1)
expect(ids()).toEqual(['cover', 'b', 'a', 'c', 'back'])
expect(store().activeSpread).toBe(2)
})
/*
* Refusing at the ends is what keeps the covers in place without any of the
* callers having to know about roles.
*/
it('will not move an inner spread past the cover', () => {
store().moveSpread(1, -1)
expect(ids()).toEqual(['cover', 'a', 'b', 'c', 'back'])
})
it('will not move an inner spread past the back cover', () => {
store().moveSpread(3, 1)
expect(ids()).toEqual(['cover', 'a', 'b', 'c', 'back'])
})
it('will not move the covers themselves', () => {
store().moveSpread(0, 1)
store().moveSpread(4, -1)
expect(ids()).toEqual(['cover', 'a', 'b', 'c', 'back'])
})
it('is one undo step', () => {
store().moveSpread(1, 1)
store().undo()
expect(ids()).toEqual(['cover', 'a', 'b', 'c', 'back'])
})
})
describe('a book with no covers at all', () => {
beforeEach(() => {
useStudioStore.getState().load(book(spread('a', 'inner'), spread('b', 'inner')))
})
it('still adds at the end', () => {
store().addSpread(1)
expect(store().doc!.spreads).toHaveLength(3)
expect(store().activeSpread).toBe(2)
})
it('lets the last spread be deleted, leaving an empty book rather than failing', () => {
store().removeSpread(1)
store().removeSpread(0)
expect(store().doc!.spreads).toEqual([])
expect(store().activeSpread).toBe(0)
})
})
describe('inserting a spread that arrived from outside', () => {
beforeEach(() => {
useStudioStore.getState().load(book(
spread('cover', 'cover'),
spread('a', 'inner'),
spread('back', 'back'),
))
})
const imported = () => spread('from-a-file', 'inner', [el('x'), el('y')])
it('lands inside the covers and becomes the spread being edited', () => {
store().insertSpread(1, imported())
expect(roles()).toEqual(['cover', 'inner', 'inner', 'back'])
expect(store().activeSpread).toBe(2)
})
it('never lands in front of the cover, whatever index it is given', () => {
store().insertSpread(-1, imported())
expect(roles()[0]).toBe('cover')
})
it('never lands behind the back cover', () => {
store().insertSpread(99, imported())
expect(roles()[roles().length - 1]).toBe('back')
})
it('mints fresh ids, so nothing collides with what is already there', () => {
store().insertSpread(1, imported())
const all = store().doc!.spreads.flatMap(s => s.elements.map(e => e.id))
expect(new Set(all).size).toBe(all.length)
expect(ids()).not.toContain('from-a-file')
})
it('arrives as an inner spread even if the file claimed otherwise', () => {
store().insertSpread(1, { ...imported(), role: 'cover' as const })
expect(roles()).toEqual(['cover', 'inner', 'inner', 'back'])
})
it('is one undo step', () => {
store().insertSpread(1, imported())
store().undo()
expect(ids()).toEqual(['cover', 'a', 'back'])
})
})
describe('turning an element', () => {
beforeEach(() => {
useStudioStore.getState().load(book(spread('a', 'inner', [el('one'), el('two')])))
})
const rotationOf = (id: string) => store().doc!.spreads[0].elements.find(e => e.id === id)!.rotation
it('turns the one it was given and leaves the rest alone', () => {
store().setRotation(0, 'one', 45)
expect(rotationOf('one')).toBe(45)
expect(rotationOf('two')).toBe(0)
})
/*
* A drag calls this on every pointer move. If each call were its own undo
* step, undoing a turn would take a hundred presses — so the gesture owns the
* step, and this does not touch the stack by itself.
*/
it('is not an undo step on its own', () => {
store().setRotation(0, 'one', 45)
expect(store().canUndo()).toBe(false)
})
it('is one undo step for the whole gesture', () => {
store().beginGesture()
for (const deg of [5, 10, 15, 20]) store().setRotation(0, 'one', deg)
store().endGesture()
expect(rotationOf('one')).toBe(20)
store().undo()
expect(rotationOf('one')).toBe(0)
})
it('ignores an id that is not on the spread', () => {
store().setRotation(0, 'nope', 45)
expect(rotationOf('one')).toBe(0)
})
})
+150
View File
@@ -0,0 +1,150 @@
import { describe, it, expect } from 'vitest'
import type { BookPageSetup } from '@trek/shared'
import { bookPageSetupSchema } from '@trek/shared'
import { COVER_TEMPLATES, TEMPLATES, applyTemplate } from '../../../src/components/Studio/templates'
/**
* Layouts (#1973).
*
* The cover set exists because a cover is a different problem from a spread:
* one page, type as the subject rather than as a caption. A spread layout
* applied to it lands half its frames past the edge of the page, which is why
* the two sets are kept apart rather than filtered out of one.
*/
const page: BookPageSetup = bookPageSetupSchema.parse({
preset: 'square-210', pageWidth: 210, pageHeight: 210,
})
describe('the layout catalogue', () => {
it('gives every layout a unique id across both sets', () => {
const ids = [...TEMPLATES, ...COVER_TEMPLATES].map(t => t.id)
expect(new Set(ids).size).toBe(ids.length)
})
it('gives every layout at least one slot', () => {
for (const tpl of [...TEMPLATES, ...COVER_TEMPLATES]) {
expect(tpl.build(page).length, tpl.id).toBeGreaterThan(0)
}
})
it('counts its photo slots honestly', () => {
for (const tpl of [...TEMPLATES, ...COVER_TEMPLATES]) {
const drawn = tpl.build(page).filter(s => s.kind === 'photo').length
expect(drawn, tpl.id).toBe(tpl.photoSlots)
}
})
it('gives every slot a frame with a positive size', () => {
for (const tpl of [...TEMPLATES, ...COVER_TEMPLATES]) {
for (const slot of tpl.build(page)) {
expect(slot.frame.w, tpl.id).toBeGreaterThan(0)
expect(slot.frame.h, tpl.id).toBeGreaterThan(0)
}
}
})
})
describe('the cover set', () => {
it('is marked as single-page throughout', () => {
for (const tpl of COVER_TEMPLATES) {
expect(tpl.role, tpl.id).toBe('single')
}
})
/*
* The rule that makes them a separate set: everything stays on one page.
* A frame reaching past pageWidth would be half in the fold of a book that
* has no fold there.
*/
it('keeps every frame on the one page', () => {
for (const tpl of COVER_TEMPLATES) {
for (const slot of tpl.build(page)) {
expect(slot.frame.x, `${tpl.id} x`).toBeGreaterThanOrEqual(-page.bleed - 0.01)
expect(slot.frame.x + slot.frame.w, `${tpl.id} right`)
.toBeLessThanOrEqual(page.pageWidth + page.bleed + 0.01)
expect(slot.frame.y + slot.frame.h, `${tpl.id} bottom`)
.toBeLessThanOrEqual(page.pageHeight + page.bleed + 0.01)
}
}
})
it('always has somewhere for the title', () => {
for (const tpl of COVER_TEMPLATES) {
expect(tpl.build(page).some(s => s.kind === 'heading'), tpl.id).toBe(true)
}
})
it('includes one that needs no photograph at all', () => {
expect(COVER_TEMPLATES.some(t => t.photoSlots === 0)).toBe(true)
})
})
describe('the spread set', () => {
it('is not marked single, so the panel keeps the two apart', () => {
for (const tpl of TEMPLATES) {
expect(tpl.role ?? 'inner', tpl.id).toBe('inner')
}
})
it('stays within the spread', () => {
for (const tpl of TEMPLATES) {
for (const slot of tpl.build(page)) {
expect(slot.frame.x + slot.frame.w, `${tpl.id} right`)
.toBeLessThanOrEqual(page.pageWidth * 2 + page.bleed + 0.01)
}
}
})
it('offers a range of photo counts rather than five versions of one idea', () => {
const counts = new Set(TEMPLATES.map(t => t.photoSlots))
expect(counts.size).toBeGreaterThanOrEqual(6)
})
})
describe('applying a cover layout', () => {
const spread = {
id: 'c1', role: 'cover' as const, background: null, parked: [], entryId: null,
elements: [
{
id: 'p1', kind: 'photo' as const, frame: { x: 0, y: 0, w: 50, h: 50 },
rotation: 0, opacity: 1, locked: false, photoId: 42, fit: 'cover' as const,
focalX: 0.5, focalY: 0.5, radius: 0, filter: 'none' as const,
mask: null, frameStyle: 'none' as const,
},
{
id: 't1', kind: 'text' as const, frame: { x: 0, y: 60, w: 100, h: 20 },
rotation: 0, opacity: 1, locked: false, text: 'Iceland', font: 'sans' as const,
size: 30, weight: 700 as const, italic: false, align: 'left' as const,
leading: 1.1, tracking: 0, color: '#111111', binding: null, overridden: false,
},
],
}
it('pours the existing picture and title into the new arrangement', () => {
const next = applyTemplate(spread, COVER_TEMPLATES[0], page)
const photo = next.elements.find(e => e.kind === 'photo')
const text = next.elements.find(e => e.kind === 'text')
expect(photo?.kind === 'photo' && photo.photoId).toBe(42)
expect(text?.kind === 'text' && text.text).toBe('Iceland')
})
/*
* Trying the type-only cover must not cost the photograph — it comes back
* the moment a layout with a frame is applied.
*/
it('parks what a type-only cover has no room for', () => {
const quiet = COVER_TEMPLATES.find(t => t.photoSlots === 0)!
const next = applyTemplate(spread, quiet, page)
expect(next.elements.some(e => e.kind === 'photo')).toBe(false)
expect(next.parked.some(e => e.kind === 'photo' && e.photoId === 42)).toBe(true)
})
it('brings the parked picture back on a layout that has room', () => {
const quiet = COVER_TEMPLATES.find(t => t.photoSlots === 0)!
const parked = applyTemplate(spread, quiet, page)
const back = applyTemplate(parked, COVER_TEMPLATES[0], page)
const photo = back.elements.find(e => e.kind === 'photo')
expect(photo?.kind === 'photo' && photo.photoId).toBe(42)
})
})
@@ -0,0 +1,211 @@
import { describe, it, expect } from 'vitest'
import type { BookElement, JourneyStats } from '@trek/shared'
import { isStale, liveMetrics, refreshPatch } from '../../../src/components/Studio/travelRefresh'
/**
* Keeping a travel element in step with its journey (#1973).
*
* The behaviour being pinned is restraint: an element holds its own values so
* the print renderer never needs a network, and the editor offers to update
* them only when they have genuinely stopped matching. Marking a page stale
* because *something* changed would make the prompt meaningless.
*/
const stats: JourneyStats = {
journeyId: 6,
distance: 1_189_000,
days: 14,
steps: 14,
photos: 57,
places: 21,
furthest: 408_000,
countries: [
{ code: 'IS', name: 'Iceland', places: 14, firstVisit: '2026-06-02' },
],
points: [
{ lat: 64.14, lng: -21.94, label: 'Reykjavík', date: '2026-06-02', country: 'IS', tripId: null, photoId: null },
{ lat: 65.68, lng: -18.12, label: 'Akureyri', date: '2026-06-06', country: 'IS', tripId: null, photoId: null },
],
trips: [],
start: '2026-06-02',
end: '2026-06-15',
}
const frame = { x: 0, y: 0, w: 100, h: 60 }
const common = { frame, rotation: 0, opacity: 1, locked: false }
const typeset = { font: 'sans' as const, color: '#1a1a1a', accent: '#111111', textScale: 1, weight: 700 as const, stale: false }
function statsEl(over: Partial<Record<string, unknown>> = {}): BookElement {
return {
...common, ...typeset, id: 'st-1', kind: 'stats',
metrics: ['distance', 'days'],
layout: 'grid', showIcons: true, units: 'metric',
values: { distance: 1_189_000, days: 14 },
...over,
} as BookElement
}
function countriesEl(over: Partial<Record<string, unknown>> = {}): BookElement {
return {
...common, ...typeset, id: 'co-1', kind: 'countries',
codes: ['IS'], names: ['Island'],
layout: 'list', showOutline: true, showFlag: false, showName: true, align: 'center',
...over,
} as BookElement
}
function mapEl(over: Partial<Record<string, unknown>> = {}): BookElement {
return {
...common, ...typeset, id: 'mp-1', kind: 'map',
style: 'minimal', showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: ['IS'],
points: stats.points.map(p => ({ lat: p.lat, lng: p.lng, label: p.label })),
...over,
} as BookElement
}
describe('liveMetrics', () => {
it('maps every metric name onto a figure', () => {
expect(liveMetrics(stats)).toEqual({
distance: 1_189_000, days: 14, steps: 14, photos: 57, countries: 1, places: 21, furthest: 408_000,
})
})
it('reports the count of countries, not the list', () => {
expect(liveMetrics(stats).countries).toBe(1)
})
})
describe('isStale', () => {
it('is false with no figures to compare against', () => {
expect(isStale(statsEl(), null)).toBe(false)
})
it('is false for an element that carries no journey figures at all', () => {
const text = { ...common, id: 't-1', kind: 'text', text: 'hi' } as unknown as BookElement
expect(isStale(text, stats)).toBe(false)
})
it('is false while the stored figures still match', () => {
expect(isStale(statsEl(), stats)).toBe(false)
})
it('is true once a shown figure has moved', () => {
expect(isStale(statsEl({ values: { distance: 900_000, days: 14 } }), stats)).toBe(true)
})
/*
* The restraint that makes the prompt worth showing: a summary of distance
* and days does not go stale because somebody uploaded a photograph.
*/
it('ignores a figure the element does not show', () => {
expect(isStale(statsEl({ values: { distance: 1_189_000, days: 14, photos: 3 } }), stats)).toBe(false)
})
it('treats a missing stored value as zero and therefore stale', () => {
expect(isStale(statsEl({ values: { distance: 1_189_000 } }), stats)).toBe(true)
})
it('spots a country added to the journey', () => {
expect(isStale(countriesEl({ codes: [] }), stats)).toBe(true)
expect(isStale(countriesEl(), stats)).toBe(false)
})
it('spots countries reordered, since the list retells the route', () => {
const twoCountries: JourneyStats = {
...stats,
countries: [
{ code: 'IS', name: 'Iceland', places: 14, firstVisit: '2026-06-02' },
{ code: 'FO', name: 'Faroe Islands', places: 2, firstVisit: '2026-06-16' },
],
}
expect(isStale(countriesEl({ codes: ['FO', 'IS'], names: ['a', 'b'] }), twoCountries)).toBe(true)
})
it('spots a route that gained or lost a stop', () => {
expect(isStale(mapEl({ points: [stats.points[0]] }), stats)).toBe(true)
expect(isStale(mapEl(), stats)).toBe(false)
})
it('spots a route of the same length whose ends have moved', () => {
const moved = mapEl({
points: [{ lat: 0, lng: 0, label: '' }, { lat: 65.68, lng: -18.12, label: '' }],
})
expect(isStale(moved, stats)).toBe(true)
})
it('is false for an empty route against an empty journey', () => {
expect(isStale(mapEl({ points: [] }), { ...stats, points: [] })).toBe(false)
})
})
describe('refreshPatch', () => {
it('is null for an element with nothing to refresh', () => {
const text = { ...common, id: 't-1', kind: 'text', text: 'hi' } as unknown as BookElement
expect(refreshPatch(text, stats)).toBeNull()
})
it('takes the current figures and clears the stale flag', () => {
const patch = refreshPatch(statsEl({ values: { distance: 1, days: 1 } }), stats)!
expect(patch).toMatchObject({ stale: false })
expect((patch as { values: Record<string, number> }).values.distance).toBe(1_189_000)
})
it('brings a country list up to date', () => {
const patch = refreshPatch(countriesEl({ codes: [], names: [] }), stats)!
expect((patch as { codes: string[] }).codes).toEqual(['IS'])
})
/*
* Names are the book's language, resolved on the client when the element was
* placed. A refresh must not quietly replace "Island" with the API's English.
*/
it('keeps the name a country already had, in whatever language it was set', () => {
const twoCountries: JourneyStats = {
...stats,
countries: [
{ code: 'IS', name: 'Iceland', places: 14, firstVisit: '2026-06-02' },
{ code: 'FO', name: 'Faroe Islands', places: 2, firstVisit: '2026-06-16' },
],
}
const patch = refreshPatch(countriesEl(), twoCountries)!
expect((patch as { names: string[] }).names[0]).toBe('Island')
expect((patch as { names: string[] }).names[1]).toBe('Faroe Islands')
})
it('keeps a name matched to its country when the order changes', () => {
const reordered: JourneyStats = {
...stats,
countries: [
{ code: 'FO', name: 'Faroe Islands', places: 2, firstVisit: '2026-05-01' },
{ code: 'IS', name: 'Iceland', places: 14, firstVisit: '2026-06-02' },
],
}
const patch = refreshPatch(countriesEl(), reordered)!
const { codes, names } = patch as { codes: string[]; names: string[] }
expect(codes).toEqual(['FO', 'IS'])
// Iceland keeps the German name it was placed with, now in second position.
expect(names[codes.indexOf('IS')]).toBe('Island')
})
it('replaces the route and the countries a map draws', () => {
const patch = refreshPatch(mapEl({ points: [], countries: [] }), stats)!
expect((patch as { points: unknown[] }).points).toHaveLength(2)
expect((patch as { countries: string[] }).countries).toEqual(['IS'])
})
it('carries only what a map draws with, not the whole stats point', () => {
const patch = refreshPatch(mapEl({ points: [] }), stats)!
// The date, the country and the trip stay behind; the photograph comes
// along because a marker can be a picture of the stop.
expect((patch as { points: object[] }).points[0]).toEqual({
lat: 64.14, lng: -21.94, label: 'Reykjavík', photoId: null,
})
})
it('leaves the element stale-free after refreshing, so the prompt goes away', () => {
const el = statsEl({ values: { distance: 1, days: 1 } })
const patched = { ...el, ...refreshPatch(el, stats) } as BookElement
expect(isStale(patched, stats)).toBe(false)
})
})
+107
View File
@@ -0,0 +1,107 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fireEvent, render, screen } from '../../helpers/render'
import { TrimField } from '../../../src/components/Studio/TrimField'
/**
* Typing a trim size (#1973).
*
* The field clamped on every keystroke, so typing 500 meant it saw 5, clamped
* that to the minimum and wrote it back under the cursor: the number could not
* be typed at all, only nudged with the arrows. What follows is the behaviour
* that fixes it, and the two things the fix must not break — the arrows, and
* leaving the field with something unusable in it.
*/
const onCommit = vi.fn()
function open(value = 210) {
render(<TrimField label="Width" value={value} onCommit={onCommit} />)
return screen.getByLabelText('Width') as HTMLInputElement
}
beforeEach(() => { onCommit.mockReset() })
describe('typing', () => {
/* The whole point: a number gets to be typed in full before it is judged. */
it('does not clamp a half-typed number back under the cursor', () => {
const input = open()
fireEvent.change(input, { target: { value: '5' } })
expect(input.value).toBe('5')
expect(onCommit).not.toHaveBeenCalled()
})
it('keeps taking keystrokes while the number is still too small', () => {
const input = open()
fireEvent.change(input, { target: { value: '5' } })
fireEvent.change(input, { target: { value: '50' } })
expect(input.value).toBe('50')
expect(onCommit).not.toHaveBeenCalled()
})
it('commits as soon as what was typed can be used', () => {
const input = open()
fireEvent.change(input, { target: { value: '5' } })
fireEvent.change(input, { target: { value: '50' } })
fireEvent.change(input, { target: { value: '500' } })
expect(onCommit).toHaveBeenCalledWith(500)
})
/* The arrows produce values already in range, and those go straight through. */
it('lets the arrows work exactly as they did', () => {
const input = open()
fireEvent.change(input, { target: { value: '211' } })
expect(onCommit).toHaveBeenCalledWith(211)
})
it('shows the document size again once a committed value comes back', () => {
const input = open()
fireEvent.change(input, { target: { value: '240' } })
expect(onCommit).toHaveBeenCalledWith(240)
// The draft is dropped on commit, so the field follows the document rather
// than holding a stale copy of what was typed.
expect(input.value).toBe('210')
})
})
describe('leaving the field', () => {
/*
* Someone who typed 5 and clicked away meant the smallest book, not the one
* they started with — so the clamp still happens, just at the end.
*/
it('commits what is there, out of range and all', () => {
const input = open()
fireEvent.change(input, { target: { value: '5' } })
fireEvent.blur(input)
expect(onCommit).toHaveBeenCalledWith(5)
})
it('leaves the size alone when the field was emptied', () => {
const input = open()
fireEvent.change(input, { target: { value: '' } })
fireEvent.blur(input)
expect(onCommit).not.toHaveBeenCalled()
expect(input.value).toBe('210')
})
it('commits on enter without waiting for a click elsewhere', () => {
const input = open()
fireEvent.change(input, { target: { value: '5' } })
fireEvent.keyDown(input, { key: 'Enter' })
fireEvent.blur(input)
expect(onCommit).toHaveBeenCalledWith(5)
})
it('drops the draft on escape and shows the real size again', () => {
const input = open()
fireEvent.change(input, { target: { value: '5' } })
fireEvent.keyDown(input, { key: 'Escape' })
expect(input.value).toBe('210')
expect(onCommit).not.toHaveBeenCalled()
})
})
describe('what it shows', () => {
it('rounds to a tenth, the way the document stores it', () => {
expect(open(210.06).value).toBe('210.1')
})
})
@@ -0,0 +1,191 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { act, renderHook } from '@testing-library/react'
/**
* Presence and pointers (#1973).
*
* The parts worth pinning are the ones that leave something behind when they
* are wrong: an arrow belonging to somebody who has closed the tab, a pointer
* drawn on the wrong spread, and a mousemove handler that puts sixty frames a
* second onto the socket.
*/
const ws = vi.hoisted(() => ({
listeners: new Set<(e: Record<string, unknown>) => void>(),
joinBook: vi.fn(),
leaveBook: vi.fn(),
sendBookCursor: vi.fn(),
}))
vi.mock('../../../src/api/websocket', () => ({
addListener: (fn: (e: Record<string, unknown>) => void) => { ws.listeners.add(fn) },
removeListener: (fn: (e: Record<string, unknown>) => void) => { ws.listeners.delete(fn) },
joinBook: ws.joinBook,
leaveBook: ws.leaveBook,
sendBookCursor: ws.sendBookCursor,
}))
import { useBookPresence } from '../../../src/components/Studio/useBookPresence'
/** Deliver a frame the way the gateway broadcasts it. */
function deliver(event: Record<string, unknown>) {
act(() => { for (const fn of ws.listeners) fn(event) })
}
const peersFrame = (journeyId: number, peers: unknown[]) =>
({ type: 'journey:book:peers', journeyId, peers })
const cursorFrame = (over: Record<string, unknown> = {}) => ({
type: 'journey:book:cursor',
journeyId: 9,
socketId: 3,
userId: 2,
spreadIndex: 0,
x: 100,
y: 50,
...over,
})
const ada = { socketId: 3, userId: 2, username: 'ada', avatar: null }
beforeEach(() => {
vi.useFakeTimers()
ws.listeners.clear()
ws.joinBook.mockReset()
ws.leaveBook.mockReset()
ws.sendBookCursor.mockReset()
})
afterEach(() => { vi.useRealTimers() })
describe('joining', () => {
it('joins the book and leaves it again when the editor closes', () => {
const { unmount } = renderHook(() => useBookPresence(9))
expect(ws.joinBook).toHaveBeenCalledWith(9)
unmount()
expect(ws.leaveBook).toHaveBeenCalledWith(9)
expect(ws.listeners.size).toBe(0)
})
it('takes the list of who is here', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada]))
expect(result.current.peers).toEqual([ada])
})
it('ignores another journey entirely', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(11, [ada]))
expect(result.current.peers).toEqual([])
})
})
describe('the pointers', () => {
it('keeps one per socket, at the latest position', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada]))
deliver(cursorFrame({ x: 100 }))
deliver(cursorFrame({ x: 140 }))
expect(result.current.cursors).toHaveLength(1)
expect(result.current.cursors[0].x).toBe(140)
})
it('names the pointer from the presence list, so the frame need not carry it', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada]))
deliver(cursorFrame())
expect(result.current.cursors[0].username).toBe('ada')
})
it('keeps two people apart', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada, { socketId: 4, userId: 5, username: 'bo', avatar: null }]))
deliver(cursorFrame({ socketId: 3 }))
deliver(cursorFrame({ socketId: 4, userId: 5, x: 10 }))
expect(result.current.cursors.map(c => c.socketId).sort()).toEqual([3, 4])
})
/* Null coordinates mean the pointer left the page. */
it('drops a pointer that left the page', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada]))
deliver(cursorFrame())
expect(result.current.cursors).toHaveLength(1)
deliver(cursorFrame({ x: null, y: null }))
expect(result.current.cursors).toEqual([])
})
/*
* The one that leaves a ghost: an arrow still on the page after its owner has
* gone, belonging to nobody.
*/
it('drops the pointer of somebody who left the book', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada]))
deliver(cursorFrame())
expect(result.current.cursors).toHaveLength(1)
deliver(peersFrame(9, []))
expect(result.current.cursors).toEqual([])
})
it('carries the spread, so a pointer on page 40 is not drawn on page 2', () => {
const { result } = renderHook(() => useBookPresence(9))
deliver(peersFrame(9, [ada]))
deliver(cursorFrame({ spreadIndex: 20 }))
expect(result.current.cursors[0].spreadIndex).toBe(20)
})
})
describe('sending this pointer', () => {
/*
* Called from a mousemove, so it is called constantly. Sixty frames a second
* of something the eye cannot use is the whole reason this is throttled.
*/
it('sends one frame for a burst of movement', () => {
const { result } = renderHook(() => useBookPresence(9))
act(() => {
for (let i = 0; i < 40; i++) result.current.moveCursor(0, i, i)
})
act(() => { vi.advanceTimersByTime(120) })
expect(ws.sendBookCursor).toHaveBeenCalledTimes(1)
// The last position, not the first: where the pointer ended up is the only
// part of its history anybody wants.
expect(ws.sendBookCursor).toHaveBeenCalledWith(9, 0, 39, 39)
})
it('keeps sending while the pointer keeps moving', () => {
const { result } = renderHook(() => useBookPresence(9))
act(() => { result.current.moveCursor(0, 1, 1) })
act(() => { vi.advanceTimersByTime(120) })
act(() => { result.current.moveCursor(0, 2, 2) })
act(() => { vi.advanceTimersByTime(120) })
expect(ws.sendBookCursor).toHaveBeenCalledTimes(2)
})
/* Leaving goes at once — an arrow lingering where somebody is not is worse. */
it('sends the pointer leaving immediately', () => {
const { result } = renderHook(() => useBookPresence(9))
act(() => { result.current.moveCursor(0, 5, 5) })
act(() => { result.current.moveCursor(0, null, null) })
expect(ws.sendBookCursor).toHaveBeenCalledWith(9, 0, null, null)
})
it('sends nothing more once the editor is gone', () => {
const { result, unmount } = renderHook(() => useBookPresence(9))
act(() => { result.current.moveCursor(0, 1, 1) })
unmount()
act(() => { vi.advanceTimersByTime(500) })
expect(ws.sendBookCursor).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,558 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import type { BookDocument, BookRecord } from '@trek/shared'
/**
* Autosaving a Studio book (#1973).
*
* The document used to live as long as the tab did. What replaced that is a
* debounce, a queue and a conflict state, and each of those is a place where
* someone's work can quietly go missing — a save dropped because another was in
* flight, a 409 swallowed as a generic error, a pending edit abandoned on close.
* These tests are aimed at exactly those three.
*/
const api = vi.hoisted(() => ({
getBook: vi.fn(),
saveBook: vi.fn(),
deleteBook: vi.fn(),
}))
vi.mock('../../../src/api/client', () => ({ journeyApi: api }))
/** The websocket seam, so a save from another editor can be delivered by hand. */
const listeners = vi.hoisted(() => new Set<(e: Record<string, unknown>) => void>())
vi.mock('../../../src/api/websocket', () => ({
addListener: (fn: (e: Record<string, unknown>) => void) => { listeners.add(fn) },
removeListener: (fn: (e: Record<string, unknown>) => void) => { listeners.delete(fn) },
}))
/** Deliver a `journey:book:saved` the way the server broadcasts it. */
async function remoteSave(version = 6, journeyId = 9) {
await act(async () => {
for (const fn of listeners) fn({ type: 'journey:book:saved', journeyId, version, savedBy: 2 })
for (let i = 0; i < 10; i++) await Promise.resolve()
})
}
import { useBookStore } from '../../../src/components/Studio/useBookStore'
const doc = (title = 'one') => ({ version: 1, title, page: {}, spreads: [] } as unknown as BookDocument)
const record = (over: Partial<BookRecord> = {}): BookRecord => ({
id: 3, journeyId: 9, title: 'T', version: 1,
updatedAt: '2026-08-19 10:00:00', updatedBy: 1,
document: doc(),
...over,
} as BookRecord)
/** A 409 as axios reports it — the shape useBookStore has to recognise. */
function conflictError(current: BookRecord) {
return Object.assign(new Error('Request failed'), {
response: { status: 409, data: { error: 'Book was changed by someone else', current } },
})
}
/**
* Advance past the debounce and let the request settle.
*
* Written out rather than reached for via waitFor: waitFor polls on a timer,
* and the timers here are fake, so it would sit spinning until the test timed
* out. Draining the microtask queue by hand is what actually works.
*/
async function tick(ms = 1300) {
await act(async () => {
vi.advanceTimersByTime(ms)
for (let i = 0; i < 10; i++) await Promise.resolve()
})
}
beforeEach(() => {
vi.useFakeTimers()
listeners.clear()
api.getBook.mockReset().mockResolvedValue({ book: null })
api.saveBook.mockReset().mockResolvedValue(record({ version: 2 }))
})
afterEach(() => {
vi.useRealTimers()
})
/** Render the hook and let the initial load settle. */
async function mount(journeyId = 9) {
const view = renderHook(() => useBookStore(journeyId))
await tick(0)
return view
}
// -- Loading ------------------------------------------------------------------
describe('loading', () => {
it('reports loaded even when the journey has no book yet', async () => {
const { result } = await mount()
expect(result.current.loaded).toBe(true)
expect(result.current.record).toBeNull()
})
it('keeps the version it loaded, so the first save is not a blind write', async () => {
api.getBook.mockResolvedValue({ book: record({ version: 7 }) })
const { result } = await mount()
act(() => { result.current.queueSave(doc('two'), 'T') })
await tick()
expect(api.saveBook).toHaveBeenCalledWith(9, expect.objectContaining({ baseVersion: 7 }))
})
/*
* Opening is not editing.
*
* The editor hands the loaded document straight back on its next render, and
* for a while that counted as a change: every open bumped the version and
* showed up in the history as an edit nobody made. The store recognises the
* document it just handed out by identity, which is also why it — and not the
* editor — is where normalisation happens.
*/
it('does not save the book it just loaded', async () => {
api.getBook.mockResolvedValue({ book: record({ version: 4 }) })
const { result } = await mount()
act(() => { result.current.queueSave(result.current.record!.document, 'T') })
await tick()
expect(api.saveBook).not.toHaveBeenCalled()
})
/* A document missing a field the contract has since gained still has to open. */
it('fills in what an older build left out', async () => {
api.getBook.mockResolvedValue({
book: record({ document: { version: 1, title: 'old', spreads: [] } as never }),
})
const { result } = await mount()
expect(result.current.record!.document.page.pageNumbers.show).toBe(false)
})
/*
* A book that will not load is a book that gets created. Studio has to open
* either way — refusing to start because the GET failed would turn a blip
* into "I cannot get at my book".
*/
it('still opens when the load fails', async () => {
api.getBook.mockRejectedValue(new Error('offline'))
const { result } = await mount()
expect(result.current.loaded).toBe(true)
expect(result.current.record).toBeNull()
})
})
// -- Debounce -----------------------------------------------------------------
describe('debounce', () => {
it('does not write while the document is still moving', async () => {
const { result } = await mount()
act(() => { result.current.queueSave(doc('a'), 'T') })
act(() => { vi.advanceTimersByTime(800) })
act(() => { result.current.queueSave(doc('b'), 'T') })
act(() => { vi.advanceTimersByTime(800) })
expect(api.saveBook).not.toHaveBeenCalled()
})
/* A drag is hundreds of commits and one edit. */
it('collapses a burst into a single write, carrying the last document', async () => {
const { result } = await mount()
act(() => {
for (let i = 0; i < 40; i++) result.current.queueSave(doc(`step-${i}`), 'T')
})
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(1)
expect(api.saveBook.mock.calls[0][1].document.title).toBe('step-39')
})
/*
* Someone typing a caption never pauses long enough to trigger the quiet
* timer. Without the ceiling their work would sit unwritten for as long as
* they kept going.
*/
it('writes anyway once it has been dirty too long', async () => {
const { result } = await mount()
for (let i = 0; i < 20; i++) {
act(() => { result.current.queueSave(doc(`t${i}`), 'T') })
act(() => { vi.advanceTimersByTime(1000) })
}
await tick(0)
expect(api.saveBook).toHaveBeenCalled()
})
it('goes through saving to saved', async () => {
const { result } = await mount()
act(() => { result.current.queueSave(doc('a'), 'T') })
act(() => { vi.advanceTimersByTime(1300) })
expect(result.current.state.status).toBe('saving')
await tick(0)
expect(result.current.state.status).toBe('saved')
})
it('takes the version back from the server, so the next save is not stale', async () => {
api.saveBook.mockResolvedValue(record({ version: 5 }))
const { result } = await mount()
act(() => { result.current.queueSave(doc('a'), 'T') })
await tick()
act(() => { result.current.queueSave(doc('b'), 'T') })
await tick()
expect(api.saveBook.mock.calls[1][1].baseVersion).toBe(5)
})
})
// -- Queueing -----------------------------------------------------------------
describe('a save during a save', () => {
/*
* The one that loses work if it is wrong: an edit made while a request is
* open must be written after it, not dropped because the store was busy.
*/
it('is queued rather than dropped', async () => {
let release: (r: BookRecord) => void = () => {}
api.saveBook.mockImplementationOnce(
() => new Promise<BookRecord>(resolve => { release = resolve }),
)
const { result } = await mount()
act(() => { result.current.queueSave(doc('first'), 'T') })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(1)
// Arrives while the first request is still open.
act(() => { result.current.queueSave(doc('second'), 'T') })
await act(async () => {
release(record({ version: 2 }))
for (let i = 0; i < 10; i++) await Promise.resolve()
})
expect(api.saveBook).toHaveBeenCalledTimes(2)
expect(api.saveBook.mock.calls[1][1].document.title).toBe('second')
})
it('does not fire two requests at once', async () => {
let open = 0
let peak = 0
api.saveBook.mockImplementation(async () => {
open++
peak = Math.max(peak, open)
await Promise.resolve()
open--
return record({ version: 2 })
})
const { result } = await mount()
act(() => { result.current.queueSave(doc('a'), 'T') })
await tick()
act(() => { result.current.queueSave(doc('b'), 'T') })
await tick()
expect(peak).toBe(1)
})
})
// -- saveNow ------------------------------------------------------------------
describe('saveNow', () => {
/*
* Closing the editor writes what is pending. The debounce exists so a drag is
* one request, not so the last edit before leaving is lost.
*/
it('writes a pending edit without waiting out the debounce', async () => {
const { result } = await mount()
act(() => { result.current.queueSave(doc('unsaved'), 'T') })
await act(async () => { await result.current.saveNow() })
expect(api.saveBook).toHaveBeenCalledTimes(1)
expect(api.saveBook.mock.calls[0][1].document.title).toBe('unsaved')
})
it('is a no-op when there is nothing pending', async () => {
const { result } = await mount()
await act(async () => { await result.current.saveNow() })
expect(api.saveBook).not.toHaveBeenCalled()
})
it('takes a document handed to it directly', async () => {
const { result } = await mount()
await act(async () => { await result.current.saveNow(doc('explicit'), 'Title') })
expect(api.saveBook.mock.calls[0][1].document.title).toBe('explicit')
expect(api.saveBook.mock.calls[0][1].title).toBe('Title')
})
})
// -- Conflicts ----------------------------------------------------------------
describe('conflicts', () => {
it('reads a 409 as the other person, not as a failure', async () => {
api.saveBook.mockRejectedValue(conflictError(record({ version: 6, title: 'Theirs' })))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
expect(result.current.state).toMatchObject({ current: { version: 6, title: 'Theirs' } })
})
it('reports anything else as an error', async () => {
api.saveBook.mockRejectedValue(new Error('network'))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('error')
})
/*
* A 409 with no record in it is still a 409, but there is nothing to offer a
* choice between — so it reports as an error rather than a conflict the
* editor cannot render.
*/
it('falls back to an error when the 409 carries no record', async () => {
api.saveBook.mockRejectedValue(
Object.assign(new Error('conflict'), { response: { status: 409, data: {} } }),
)
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('error')
})
/*
* The one that turned into a loop on screen: every change queued a save,
* every save was refused, and the refusal re-rendered the thing that queued
* it. A conflict is a question only the user can answer, so nothing is
* written until they have.
*/
it('stops writing until the conflict is answered', async () => {
api.saveBook.mockRejectedValue(conflictError(record({ version: 6 })))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(1)
// More edits arrive; none of them go out.
act(() => { result.current.queueSave(doc('mine again'), 'T') })
await tick()
act(() => { result.current.queueSave(doc('and again'), 'T') })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(1)
})
it('writes again once the user has chosen', async () => {
const theirs = record({ version: 6 })
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
api.saveBook.mockResolvedValue(record({ version: 7 }))
// Choosing re-sends what was refused, so this is the third write, not the second.
act(() => { result.current.keepMine(theirs) })
await tick()
act(() => { result.current.queueSave(doc('mine again'), 'T') })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(3)
})
/*
* The one that lost an afternoon: write() empties the queue before it makes
* the request, so after a 409 nothing is queued. "Keep mine" cleared the
* conflict and left the document unsent until the user happened to touch the
* book again — and closing the editor writes the queue, which was empty.
*/
it('sends the refused document as soon as the local one is kept', async () => {
const theirs = record({ version: 6 })
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
api.saveBook.mockResolvedValue(record({ version: 7 }))
act(() => { result.current.keepMine(theirs) })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(2)
expect(api.saveBook.mock.calls[1][1]).toMatchObject({ title: 'T', baseVersion: 6 })
expect((api.saveBook.mock.calls[1][1].document as BookDocument).title).toBe('mine')
expect(result.current.state.status).toBe('saved')
})
/* Nothing of their own to send: keeping theirs-as-mine is just the version. */
it('only clears the conflict when the local document is the agreed one', async () => {
const theirs = record({ version: 6 })
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
act(() => { result.current.acceptTheirs(theirs) })
act(() => { result.current.keepMine(theirs) })
await tick()
expect(api.saveBook).toHaveBeenCalledTimes(1)
expect(result.current.state.status).toBe('idle')
})
it('returns their document when their version is taken, and drops the pending write', async () => {
const theirs = record({ version: 6, document: doc('theirs') })
api.saveBook.mockRejectedValue(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
let taken: BookDocument | undefined
act(() => { taken = result.current.acceptTheirs(theirs) })
expect(taken?.title).toBe('theirs')
expect(result.current.state.status).toBe('idle')
// Nothing left queued: taking theirs discards the local edit on purpose.
api.saveBook.mockResolvedValue(record({ version: 7 }))
await act(async () => { await result.current.saveNow() })
expect(api.saveBook).toHaveBeenCalledTimes(1)
})
/*
* Keeping yours is a rebase, not a merge — it moves the local document onto
* their version number so the next save lands instead of conflicting forever.
*/
it('rebases onto their version when the local one is kept', async () => {
const theirs = record({ version: 6 })
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
const { result } = await mount()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
api.saveBook.mockResolvedValue(record({ version: 7 }))
act(() => { result.current.keepMine(theirs) })
await tick()
expect(api.saveBook.mock.calls[1][1].baseVersion).toBe(6)
})
})
// -- Somebody else saved ------------------------------------------------------
describe('another editor saving', () => {
/** Render with a book already stored, and a spy for what gets handed back. */
async function withBook() {
api.getBook.mockResolvedValue({ book: record({ version: 4, document: doc('theirs') }) })
const onRemote = vi.fn()
const view = renderHook(() => useBookStore(9, onRemote))
await tick(0)
return { ...view, onRemote }
}
it('takes their version when nothing local is outstanding', async () => {
const { result, onRemote } = await withBook()
api.getBook.mockResolvedValue({ book: record({ version: 6, document: doc('newer') }) })
await remoteSave(6)
expect(onRemote).toHaveBeenCalledTimes(1)
expect(onRemote.mock.calls[0][0].title).toBe('newer')
expect(result.current.record?.version).toBe(6)
})
/*
* The one that would lose work: replacing an open document that has unsaved
* edits in it. The next save conflicts instead, which is the whole point of
* the version.
*/
it('leaves an edited document alone', async () => {
const { result, onRemote } = await withBook()
act(() => { result.current.queueSave(doc('mine'), 'T') })
await remoteSave(6)
expect(onRemote).not.toHaveBeenCalled()
})
it('leaves it alone after a conflict too, where nothing is queued but the work is still local', async () => {
const { result, onRemote } = await withBook()
api.saveBook.mockRejectedValue(conflictError(record({ version: 6 })))
act(() => { result.current.queueSave(doc('mine'), 'T') })
await tick()
expect(result.current.state.status).toBe('conflict')
await remoteSave(7)
expect(onRemote).not.toHaveBeenCalled()
})
it('ignores a save on another journey', async () => {
const { onRemote } = await withBook()
await remoteSave(6, 11)
expect(onRemote).not.toHaveBeenCalled()
})
/* A second tab on the same account is a different socket and the same person. */
it('ignores the version it already has', async () => {
const { onRemote } = await withBook()
await remoteSave(4)
expect(onRemote).not.toHaveBeenCalled()
})
it('does not write back what it just took', async () => {
const { result, onRemote } = await withBook()
api.getBook.mockResolvedValue({ book: record({ version: 6, document: doc('newer') }) })
await remoteSave(6)
// The editor hands the loaded document straight back on the next render.
const taken = onRemote.mock.calls[0][0]
act(() => { result.current.queueSave(taken, 'T') })
await tick()
expect(api.saveBook).not.toHaveBeenCalled()
})
it('stops listening once the editor is gone', async () => {
const { unmount } = await withBook()
expect(listeners.size).toBe(1)
unmount()
expect(listeners.size).toBe(0)
})
})
// -- Teardown -----------------------------------------------------------------
describe('unmounting', () => {
it('does not fire a debounced save after the editor is gone', async () => {
const { result, unmount } = await mount()
act(() => { result.current.queueSave(doc('a'), 'T') })
unmount()
await tick(5000)
expect(api.saveBook).not.toHaveBeenCalled()
})
})