feat(studio): follow-ups from using Studio on a real journey (#1984)

* feat(studio): widen the document, and stop a save from losing it

The schema gains what the elements coming after it need: an icon element, a
badge that can be restyled rather than only placed, a date and a pair of
coordinates on a text binding, and the map's route, pin and road settings.

Widening it turned up two ways a book could fail to come back.

The mood badge writes its code into the document, and the schema said that
code was exactly two characters, from a first draft where it was a country.
The real codes are words, so every save was rejected and the read that
followed parsed to an empty document: seventeen spreads in, nothing out.
Widened to what the badge actually writes, and normalizeBookDocument now
drops the elements it cannot read rather than the whole book, so one bad
element costs a picture frame instead of a year of work.

The other was the body limit. The parser allowed 100kb for everything, and a
book with a routed map measures past that, so the save came back 413 and the
editor sat on "not saved" with no way forward. Book writes get their own
parser at 8mb; everything else keeps the limit it had.

* feat(studio): a date, a pair of coordinates and an icon library

Three things that had to be drawn by hand before.

A journal entry knows when it happened and where, and neither could be put
on a page: you read the date off the entry and typed it into a text box,
where it then stayed while the entry moved. Both are chips now, next to the
title and the story, and both follow their entry the way the others do.
The formatting lives in one place so the chip, the template and the resolver
cannot drift by a character — coordinates in degrees or decimals, the date
in the reader's language.

The icons are the whole Lucide set, searchable, placed as a real element
with its own colour and stroke rather than as a character in a font. The
stroke is deliberately not called strokeWidth: three separate places rescale
a field of that name by page width, and an icon whose line thins as the book
grows is not what anyone asked for.

And the badges finally have their settings. A mood or weather badge could be
placed and then only moved: the icon's colour was fixed, the icon could not
be turned off, and there was no way to keep the icon and drop the words. All
three are switches now, with the colour following the badge unless you say
otherwise.

* fix(studio): let a placed entry field follow its journal entry again

The inspector says a bound field follows the journal entry and that editing
it here breaks the link. The first half was not true: nothing ever re-read
the entry, so renaming a title in Journey left the old words on the page for
good, and the same went for every other bound field.

The resolver runs where the journey is loaded and re-reads the fields that
still point at an entry. What it will not do is as important as what it
does. A field somebody has typed over stays typed over, an entry that is
gone leaves its element alone rather than blanking it, and an entry that
answers with nothing never wipes what is already on the page.

Formatted fields — the date, the coordinates — are only re-read when the
format itself changed, which is what keeps this from quietly rewriting
books that already exist: an entry whose date was placed as a heading and
then set in capitals keeps its capitals. Checked against the real
database before it shipped, where the first version overwrote three of them.

* feat(studio): start a new book empty, with six layouts to choose from

A new journey opened onto a book that had already been laid out, which is
the wrong first move: it decides the shape of somebody's book before they
have seen it, and undoing it means deleting pages one at a time. A new book
starts empty now, and the auto layout runs when it is asked to.

The layouts themselves went from two to six, so choosing one is a real
choice: what was there covered a photo-heavy spread and a text-heavy one and
nothing in between.

* fix(studio): hyphenate the export the way the editor does, and set the bleed

Two things the press sees and the editor did not.

A paragraph broke in different places in the PDF than on screen. The print
document is written from scratch and never carried a language, so the
browser hyphenated the editor's German and the export's nothing-in-
particular. It takes the page's own language now. The wait for the sheet to
be ready also covers the images inside SVG, with a ceiling, so a map that is
slow to draw does not print half-finished.

And the bleed and the safe margin are typeable. Both were baked into every
page preset at what a photo-book vendor usually asks for, 3mm and 5mm, with
no 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 carries the wrong
bleed and the crop marks sit in the wrong place, which nobody finds until
the guillotine has run.

* feat(studio): rebuild the inspector

The panel on the right had grown by accretion: every element type had added
its own controls in whatever shape suited it that day, so the same idea —
a colour, a size, a toggle — looked different depending on what you had
selected, and long panels were a wall of unlabelled fields.

It is one set of controls now, used by every element: foldable sections, a
line that holds a label and its control, radio choices, checkboxes, the
app's own toggle, and a number field that holds a draft so typing "500" is
not read as "5", clamped and written back under the cursor. Duplicated
controls were merged rather than deleted; nothing an element could do before
it cannot do now.

The head carries the element's identity and its actions, so what you have
selected is readable without counting fields, and the sections have room to
breathe: what was there was correct and unreadable.

* feat(studio): a route map worth printing

The map in a book was a straight grey line between grey dots on a tile that
was chosen for a screen. At print size those tiles are read at roughly four
times the resolution they were fetched for, which is why it looked soft next
to everything around it.

The imagery comes from sources that hold up on paper: NASA's shaded relief
and EOX's cloudless Sentinel-2, both licensed for it, picked at a zoom that
matches the printer rather than the screen. Tiles are fetched at twice the
density where the source offers it, and the seam between them scales with
the tile instead of sitting at a fixed fraction of a millimetre, which under
editor zoom fell below one device pixel and showed as white threads.

The route is drawn rather than plotted. A leg that was never recorded bows,
by an amount that grows with its length and turns away from the pole, and it
dashes, because an inferred line should not claim to be a track — a recorded
track never bows. Both strokes are laid down in two passes, casing then core,
so the line stays legible over dark sea and bright desert alike. Legs can
follow roads instead, routed leg by leg with the geometry thinned before it
is stored, which is the setting a road trip wants and the one a flight
cannot have.

Stops carry their own first photograph, cut to a circle by a stencil that
exists — the first one was written into a defs block that only appears on a
map clipped to a coastline, so on an ordinary map it clipped nothing and the
photographs sat square on the page. A stop with no photograph of its own is
numbered rather than handed one from elsewhere in the journey: a marker at
one place showing a picture taken at another is a caption that lies.

Whatever the frame, the whole route is inside it. The window takes the
frame's aspect, so the fit and the imagery agree instead of one containing
what the other covers, and a map dragged narrow no longer cuts off its end.
Each linked trip can carry its own map, and a map notices a photograph added
to a stop afterwards rather than having to be placed again.

* i18n(journey): the new Studio strings, in all 23 locales

* test(journey): pin the coverage the map work brought with it

The journey domain measures higher than its floor after this round, so the
floor follows it up. Only journey moved; the generator's suggestion would
have taken memories' functions down a point, and a ratchet that can fall is
not a ratchet.

* test(studio): cover the thinning that keeps a road route saveable

The one path in roadRoute nothing exercised, and the one that matters most:
a router answers a long drive with thousands of points at a precision no
press can resolve, and all of it goes into the document. Keeping a leg whole
is what pushed a real book past the body limit.

Both ends have to survive so the line still meets its stops, and the spacing
has to stay even, because cutting a run out of the middle would straighten
exactly the bends somebody wanted to see.
This commit is contained in:
Maurice
2026-08-20 15:43:27 +02:00
committed by GitHub
parent 736599a89b
commit eae8480728
73 changed files with 9631 additions and 805 deletions
+43 -3
View File
@@ -1,8 +1,9 @@
import type { CSSProperties } from 'react'
import type {
BookElement, BookPageSetup, BookPhotoElement, BookShapeElement, BookSpread,
BookElement, BookIconElement, BookPageSetup, BookPhotoElement, BookShapeElement, BookSpread,
} from '@trek/shared'
import { FONT_STACKS, photoSrc } from './bookRender'
import { iconComponent } from './iconLibrary'
import { HOLED_SHAPES, SHAPE_PATHS, scalePath, unitPath } from './shapes'
import { TravelElementView } from './TravelElements'
import { PageNumbers } from './PageNumbers'
@@ -197,8 +198,18 @@ function PhotoView({ el, big, print, dropLabel }: {
style={{
position: 'absolute',
inset: 0,
/*
* Opaque, and that is the point.
*
* The hatch used to be laid over nothing, so an empty frame showed
* whatever was behind it and every attempt to arrange a shape *under*
* one looked like it had done nothing: the frame appeared to sit at the
* bottom of the stack no matter where it was, right up until a
* photograph landed in it and it suddenly covered things. A frame is a
* promise that a picture goes here, and a picture is not see-through.
*/
background:
'repeating-linear-gradient(45deg, rgba(0,0,0,.045) 0 6px, rgba(0,0,0,.02) 6px 12px)',
'repeating-linear-gradient(45deg, rgba(0,0,0,.055) 0 6px, rgba(0,0,0,.025) 6px 12px), #ffffff', // theme-lint-disable — paper, not app chrome
// A dashed border would be cut in half lengthwise by the clip, so a
// masked placeholder shows its shape through the hatch alone.
border: clipped ? undefined : '1px dashed rgba(0,0,0,.16)',
@@ -338,6 +349,31 @@ function PhotoView({ el, big, print, dropLabel }: {
)
}
/**
* A lucide drawing, at the size the frame gives it.
*
* Kept proportional rather than stretched to the box. A shape is scaled by
* moving its points and looks deliberate at any ratio; a stroked icon does not
* — a stretched compass reads as a mistake — so it sits centred in whatever
* rectangle it was given, which is also what the handles then appear to do.
*
* The stroke follows the drawing rather than staying a fixed width, because an
* icon set 60mm across with a hairline is a diagram, not a mark. `lineWidth` is
* the weight against lucide's own 24-unit grid, exactly as the icons are drawn.
*/
function IconView({ el }: { el: BookIconElement }) {
const Icon = iconComponent(el.name)
return (
<div style={{ ...frameStyle(el), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Icon
color={el.color}
strokeWidth={el.lineWidth}
style={{ width: '100%', height: '100%', display: 'block' }}
/>
</div>
)
}
export function ElementView({
el, big, print = false, dropLabel = '',
}: { el: BookElement; big: boolean; print?: boolean; dropLabel?: string }) {
@@ -347,12 +383,16 @@ export function ElementView({
if (el.kind === 'shape') return <ShapeView el={el} />
// Above the catch-all below, which routes everything that is not text into
// the travel elements and draws null for anything they do not know.
if (el.kind === 'icon') return <IconView el={el} />
if (el.kind !== 'text') {
// map, stats, countries, badge — the elements drawn from the journey's own
// figures. They live in their own file because they are a different kind of
// drawing: type and vector graphics laid out from data, rather than one box
// with one property set.
return <TravelElementView el={el} frameStyle={frameStyle(el)} />
return <TravelElementView el={el} frameStyle={frameStyle(el)} big={big} />
}
return (
@@ -0,0 +1,200 @@
import { useState, type ReactNode } from 'react'
import { Check, ChevronDown } from 'lucide-react'
import ToggleSwitch from '../Settings/ToggleSwitch'
/**
* The inspector's vocabulary.
*
* ── Why this file exists ─────────────────────────────────────────────────
*
* The panel had grown four ways of saying "this one is on" — a filled pill, a
* ring, a tinted border, ink on a tint — and used the *same* pill for a choice
* between four things and for a switch that turns one thing off. A map showed
* seventy controls in ten sections that were all open at once, all labelled in
* the same small capitals, so nothing on the panel looked more important than
* anything else. None of that was a decision; it was what happens when a panel
* grows one control at a time.
*
* So there are now exactly three ways to answer a question here, and each looks
* like what it is:
*
* **Choose one** is a row of chips, and the chosen one is filled.
* **Choose several** is a row of chips that carry a tick when they are on,
* because a set with three of seven picked has to be readable at a glance.
* **On or off** is the app's switch, on its own line beside the words —
* the one control in TREK that already means exactly that.
*
* A section can be folded away, which is the other half of the answer: a
* property panel is a reference, and a reference nobody can collapse is a wall.
*/
/**
* One group of properties.
*
* `defaultOpen={false}` is for the groups you set once and rarely return to —
* the frame's numbers, mostly. The state is per mounted section rather than
* remembered: coming back to an element and finding its panel folded up
* differently from last time is worse than opening one group again.
*/
export function Section({ label, children, defaultOpen = true, hint }: {
label: string
children: ReactNode
defaultOpen?: boolean
/** A line under the label, for a group whose name cannot carry the whole idea. */
hint?: string
}) {
const [open, setOpen] = useState(defaultOpen)
return (
<div className={`st-section is-fold ${open ? '' : 'is-folded'}`}>
<button className="st-section-head" onClick={() => setOpen(!open)} aria-expanded={open}>
<span className="st-section-label">{label}</span>
<ChevronDown size={13} className="st-section-caret" />
</button>
{open && (
<div className="st-section-body">
{hint && <p className="st-hint st-section-hint">{hint}</p>}
{children}
</div>
)}
</div>
)
}
/** A labelled line. The label sits left, the control fills what is left. */
export function Line({ label, children, wide = false }: {
label: string
children: ReactNode
/** Put the control under the label rather than beside it, when it needs the width. */
wide?: boolean
}) {
return (
<div className={`st-line ${wide ? 'is-wide' : ''}`}>
<span className="st-line-label">{label}</span>
<div className="st-line-body">{children}</div>
</div>
)
}
/** Choose one of a few. The chosen one is filled in. */
export function Choice<T extends string | number>({ value, options, onPick, ariaLabel }: {
value: T
options: { value: T; label: ReactNode; title?: string; disabled?: boolean }[]
onPick: (v: T) => void
ariaLabel?: string
}) {
return (
<div className="st-row" role="radiogroup" aria-label={ariaLabel}>
{options.map(o => (
<button
key={String(o.value)}
role="radio"
aria-checked={o.value === value}
className={`st-chip ${o.value === value ? 'is-on' : ''}`}
disabled={o.disabled}
title={o.title}
onClick={() => onPick(o.value)}
>
{o.label}
</button>
))}
</div>
)
}
/**
* Choose several. A tick marks what is in the set.
*
* Not switches: seven metrics as seven switched lines is a column of switches
* taller than the element it configures, and what matters about a set is which
* of it is in — a question a row answers and a list does not.
*/
export function Picks<T extends string>({ value, options, onToggle }: {
value: readonly T[]
options: { value: T; label: ReactNode; disabled?: boolean }[]
onToggle: (v: T) => void
}) {
return (
<div className="st-row">
{options.map(o => {
const on = value.includes(o.value)
return (
<button
key={o.value}
role="checkbox"
aria-checked={on}
className={`st-chip is-pick ${on ? 'is-on' : ''}`}
disabled={o.disabled}
onClick={() => onToggle(o.value)}
>
{on && <Check size={12} strokeWidth={3} />}
{o.label}
</button>
)
})}
</div>
)
}
/** On or off, said the way the rest of TREK says it. */
export function Switch({ label, on, onToggle }: { label: string; on: boolean; onToggle: () => void }) {
return (
<div className="st-switch">
<span className="st-switch-label">{label}</span>
<ToggleSwitch on={on} onToggle={onToggle} label={label} />
</div>
)
}
/**
* A number, with its unit.
*
* Held as text while it is being typed and only read back on blur or Enter,
* which fixes three things at once: "0." no longer snaps to "0" the moment the
* point is typed, an emptied field no longer collapses the element to zero,
* and a value is one undo step rather than one per keystroke.
*/
export function NumField({
label, value, onChange, min, max, step = 0.5, unit,
}: {
label: string
value: number
onChange: (v: number) => void
min?: number
max?: number
step?: number
unit?: string
}) {
const shown = String(Math.round(value * 100) / 100)
const [draft, setDraft] = useState<string | null>(null)
const commit = (raw: string) => {
setDraft(null)
const v = Number(raw)
if (raw.trim() === '' || !Number.isFinite(v)) return
const clamped = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, v))
if (clamped !== value) onChange(clamped)
}
return (
<label className="st-num">
<span className="st-num-label">{label}</span>
<span className="st-num-box">
<input
className="st-input"
type="number"
value={draft ?? shown}
step={step}
min={min}
max={max}
onChange={e => setDraft(e.target.value)}
onBlur={e => commit(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') (e.target as HTMLInputElement).blur()
if (e.key === 'Escape') setDraft(null)
}}
/>
{unit && <span className="st-num-unit">{unit}</span>}
</span>
</label>
)
}
@@ -1,22 +1,26 @@
import { useState } from 'react'
import { Minus, Quote, Square } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { Minus, Quote, Search, Square, X } from 'lucide-react'
import type { BookElement, BookPageSetup, BookShapeId } from '@trek/shared'
import { useStudioStore } from '../../store/studioStore'
import { FRAME_SHAPES, HOLED_SHAPES, SHAPE_GROUPS, SHAPE_PATHS } from './shapes'
import { GRIDS, defaultGridBox, gridElements } from './grids'
import { PanelHead } from './StudioPanelHead'
import { FEATURED_ICONS, iconComponent, iconLabel, searchIcons } from './iconLibrary'
/**
* Everything you can add that does not come from the journey: type, shapes,
* picture frames and photo grids.
* picture frames, photo grids and the icon set.
*
* Three tabs rather than three more entries on the rail. They are all the same
* Four tabs rather than four more entries on the rail. They are all the same
* kind of answer to "what do I put on this page", and a rail long enough to
* hold them separately stops being faster to hit than a word would be.
*/
const uid = (p: string) => `${p}-${Math.random().toString(36).slice(2, 9)}`
/** How many icons the grid draws at a time. Two screens' worth at four across. */
const ICON_PAGE = 120
type FrameStyle = 'none' | 'polaroid' | 'white' | 'shadow' | 'film' | 'tape'
/**
@@ -74,8 +78,35 @@ function FrameStyleGlyph({ style }: { style: FrameStyle }) {
)
}
function IconCell({ name, onPick }: { name: string; onPick: (name: string) => void }) {
const Icon = iconComponent(name)
return (
<button
className="st-shape-btn is-glyph"
onClick={() => onPick(name)}
aria-label={name}
title={iconLabel(name)}
>
<Icon strokeWidth={1.7} />
</button>
)
}
export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: string) => string }) {
const [tab, setTab] = useState<'shapes' | 'frames' | 'grids'>('shapes')
const [tab, setTab] = useState<'shapes' | 'frames' | 'grids' | 'icons'>('shapes')
const [iconQuery, setIconQuery] = useState('')
/*
* How much of the library is on screen.
*
* Fourteen hundred icons is fourteen hundred React components, each a
* forwardRef around several SVG nodes, and rendering them all costs about a
* second of blocked main thread on the first click of the tab — for a grid
* whose first two rows are all anybody sees. So it grows as it is scrolled,
* and a search resets it: the results of a search are short, and starting
* them part-drawn would be wrong.
*/
const [iconLimit, setIconLimit] = useState(ICON_PAGE)
const iconTail = useRef<HTMLDivElement>(null)
const addElement = useStudioStore(s => s.addElement)
const commit = useStudioStore(s => s.commit)
const select = useStudioStore(s => s.select)
@@ -130,6 +161,22 @@ export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: s
} as BookElement)
}
/**
* An icon, placed as a square.
*
* Square because that is what it is: unlike a shape, an icon keeps its
* proportions inside whatever frame it is given, so a rectangle would only
* pad it with air on two sides.
*/
const addIcon = (name: string) => {
const side = Math.min(page.pageWidth, page.pageHeight) * 0.18
addElement(active, {
id: uid('i'), kind: 'icon', frame: centre(side, side),
rotation: 0, opacity: 1, locked: false,
name, color: '#111827', lineWidth: 2,
} as BookElement)
}
/** An empty frame, cut to a shape and waiting for a picture. */
const addFrame = (mask: BookShapeId | null, frameStyle: FrameStyle = 'none') => {
const side = Math.min(page.pageWidth, page.pageHeight) * 0.45
@@ -144,6 +191,26 @@ export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: s
} as BookElement)
}
const matchedIcons = useMemo(() => searchIcons(iconQuery), [iconQuery])
const shownIcons = useMemo(() => matchedIcons.slice(0, iconLimit), [matchedIcons, iconLimit])
/*
* Grow the grid when its foot comes into view.
*
* An observer rather than a scroll handler: the panel is the scroller, the
* foot is the thing that matters, and asking the browser to tell us when they
* meet costs nothing per frame.
*/
useEffect(() => {
const tail = iconTail.current
if (!tail) return
const io = new IntersectionObserver(entries => {
if (entries.some(e => e.isIntersecting)) setIconLimit(n => n + ICON_PAGE)
})
io.observe(tail)
return () => io.disconnect()
}, [shownIcons.length, matchedIcons.length])
return (
<>
<PanelHead label={t('journey.studio.elements')} />
@@ -158,6 +225,9 @@ export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: s
<button className={tab === 'grids' ? 'is-on' : ''} onClick={() => setTab('grids')}>
{t('journey.studio.grids')}
</button>
<button className={tab === 'icons' ? 'is-on' : ''} onClick={() => setTab('icons')}>
{t('journey.studio.icons')}
</button>
</div>
<div className="st-panel-scroll">
@@ -319,6 +389,54 @@ export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: s
<p className="st-hint" style={{ paddingTop: 8 }}>{t('journey.studio.gridHint')}</p>
</div>
)}
{tab === 'icons' && (
<div className="st-section">
{/*
The search sits inside the scroller rather than above the tab
strip, unlike the Content panel's: that one filters both of its
tabs, this one belongs to a single tab, and hanging it above the
strip would make the strip move when you switch away from it.
*/}
<div className="st-search" style={{ margin: '0 0 10px' }}>
<Search size={14} />
<input
value={iconQuery}
onChange={e => { setIconQuery(e.target.value); setIconLimit(ICON_PAGE) }}
placeholder={t('journey.studio.searchIcons')}
aria-label={t('journey.studio.searchIcons')}
spellCheck={false}
/>
{iconQuery && (
<button onClick={() => { setIconQuery(''); setIconLimit(ICON_PAGE) }} aria-label={t('common.clear')}>
<X size={13} />
</button>
)}
</div>
{/* The shelf, until somebody searches. */}
{!iconQuery && (
<>
<div className="st-section-label">{t('journey.studio.iconsForTravel')}</div>
<div className="st-shape-grid" style={{ marginBottom: 14 }}>
{FEATURED_ICONS.map(name => (
<IconCell key={name} name={name} onPick={addIcon} />
))}
</div>
<div className="st-section-label">{t('journey.studio.iconsAll')}</div>
</>
)}
<div className="st-shape-grid">
{shownIcons.map(name => (
<IconCell key={name} name={name} onPick={addIcon} />
))}
</div>
{/* What the observer below watches for. */}
{shownIcons.length < matchedIcons.length && <div ref={iconTail} style={{ height: 1 }} />}
{!matchedIcons.length && (
<p className="st-hint" style={{ paddingTop: 8 }}>{t('journey.studio.noMatches')}</p>
)}
</div>
)}
</div>
</>
)
+453 -211
View File
@@ -1,9 +1,9 @@
import type { BookElement, BookPageNumbers, BookPageSetup, BookShapeId, JourneyStats } from '@trek/shared'
import {
AlignCenter, AlignJustify, AlignLeft, AlignRight, ArrowDown, ArrowUp,
ChevronsDown, ChevronsUp, Lock, Trash2, Unlock,
ChevronsDown, ChevronsUp, Copy, Italic, Lock, Trash2, Unlock,
} from 'lucide-react'
import { useRef } from 'react'
import { useMemo, useRef, useState } from 'react'
import { useStudioStore } from '../../store/studioStore'
import { photoSrc } from './bookRender'
import { BOOK_FONTS, BOOK_FONT_ORDER, hasWeight, nearestWeight } from './bookFonts'
@@ -11,19 +11,47 @@ import { FRAME_SHAPES, SHAPE_GROUPS } from './shapes'
import { ShapeGlyph } from './StudioElementsPanel'
import { TravelInspector } from './StudioTravelInspector'
import { Swatches } from './StudioSwatches'
import { formatBookCoords } from './entryText'
import { iconComponent, iconLabel, searchIcons } from './iconLibrary'
import { Choice, Line, NumField, Section, Switch } from './StudioControls'
import type { JourneySource } from './StudioSidebar'
/** How many icons the swap grid offers at once. A search narrows it below this. */
const ICON_CHOICES = 60
/**
* Properties of whatever is selected.
*
* Deliberately narrow: it shows what the selected thing actually has, and
* nothing else. A panel that lists every property of every element type with
* most of them greyed out reads as a settings dialog, not as a tool.
* ── What it shows, and in what order ─────────────────────────────────────
*
* Deliberately narrow: what the selected thing actually has, and nothing else.
* A panel that lists every property of every element with most of them greyed
* out reads as a settings dialog, not as a tool.
*
* The order is the same for every kind, because the panel is used by muscle
* memory more than by reading: **what it says** first, then **how it looks**,
* then **where it sits**, then **what is in front of what**. A photo's crop and
* a mark's words are the same step in that sequence, so they sit in the same
* place on the panel.
*
* The frame's numbers are folded away by default. They are the least-used group
* in the panel — dragging is how anyone actually positions an element — and
* four number fields left open at the top pushed everything worth looking at
* below the fold.
*
* ── What is not here any more ────────────────────────────────────────────
*
* Duplicate, lock and delete are in the panel head rather than in a section of
* their own: they act on the element rather than describing it, and a group
* called "Arrange" that held two of those next to the stacking buttons was the
* one group in the panel whose name did not say what was inside it.
*/
export function StudioInspector({
spreadIndex,
page,
stats,
source,
setPageNumbers,
t,
locale,
@@ -33,14 +61,23 @@ export function StudioInspector({
setPageNumbers: (patch: Partial<BookPageNumbers>) => void
/** Live journey figures, so a travel element can be brought up to date. */
stats: JourneyStats | null
/** The journal itself, so a bound mark can be re-set from it. */
source: JourneySource
t: (k: string) => string
locale: string
}) {
const [iconQuery, setIconQuery] = useState('')
/*
* A page of results, memoised because the inspector re-renders on every
* pointer move of a drag and the library is fourteen hundred names long.
*/
const iconChoices = useMemo(() => searchIcons(iconQuery).slice(0, ICON_CHOICES), [iconQuery])
const doc = useStudioStore(s => s.doc)
const selection = useStudioStore(s => s.selection)
const update = useStudioStore(s => s.updateElement)
const commit = useStudioStore(s => s.commit)
const raise = useStudioStore(s => s.raise)
const duplicate = useStudioStore(s => s.duplicate)
const removeElements = useStudioStore(s => s.removeElements)
const spread = doc?.spreads[spreadIndex]
@@ -59,30 +96,27 @@ export function StudioInspector({
<div className="st-panel-head"><span>{t('journey.studio.document')}</span></div>
<div className="st-panel-scroll">
<Section label={t('journey.studio.pageNumbers')}>
<div className="st-row">
<button
className={`st-chip ${folios.show ? 'is-on' : ''}`}
onClick={() => setPageNumbers({ show: !folios.show })}
>
{t(folios.show ? 'journey.studio.pageNumbersOn' : 'journey.studio.pageNumbersOff')}
</button>
</div>
<Switch
label={t('journey.studio.pageNumbers')}
on={folios.show}
onToggle={() => setPageNumbers({ show: !folios.show })}
/>
{folios.show && (
<>
<div className="st-row" style={{ marginTop: 8 }}>
{(['outer', 'inner', 'centre'] as const).map(pos => (
<button
key={pos}
className={`st-chip ${folios.position === pos ? 'is-on' : ''}`}
onClick={() => setPageNumbers({ position: pos })}
>
{t(`journey.studio.folio.${pos}`)}
</button>
))}
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.position')}>
<Choice
value={folios.position}
options={(['outer', 'inner', 'centre'] as const).map(pos => ({
value: pos, label: t(`journey.studio.folio.${pos}`),
}))}
onPick={position => setPageNumbers({ position })}
/>
</Line>
</div>
<div className="st-grid2" style={{ marginTop: 8 }}>
<Num
<div className="st-grid2" style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.folioStart')}
value={folios.startAt}
min={0}
@@ -90,50 +124,54 @@ export function StudioInspector({
step={1}
onChange={v => setPageNumbers({ startAt: Math.round(v) })}
/>
<Num
label="pt"
<NumField
label={t('journey.studio.size')}
value={folios.size}
min={4}
max={48}
step={0.5}
unit="pt"
onChange={v => setPageNumbers({ size: v })}
/>
</div>
<div style={{ marginTop: 8 }}>
<Num
<div style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.folioMargin')}
value={folios.margin}
min={0}
max={60}
step={0.5}
unit="mm"
onChange={v => setPageNumbers({ margin: v })}
/>
</div>
{/*
Automatic first, and picking a colour is what turns it off —
no separate switch to find and no state where a chosen colour
is quietly ignored.
*/}
<div className="st-row" style={{ marginTop: 8 }}>
<button
className={`st-chip ${folios.autoColor ? 'is-on' : ''}`}
onClick={() => setPageNumbers({ autoColor: true })}
aria-pressed={folios.autoColor}
>
{t('journey.studio.folioAuto')}
</button>
</div>
<div style={{ marginTop: 8, opacity: folios.autoColor ? 0.45 : 1 }}>
<Swatches
value={folios.color}
onPick={c => setPageNumbers({ color: c, autoColor: false })}
<div style={{ marginTop: 10 }}>
<Switch
label={t('journey.studio.folioAuto')}
on={folios.autoColor}
onToggle={() => setPageNumbers({ autoColor: !folios.autoColor })}
/>
</div>
{/* Picking a colour is the other way to turn automatic off, so
the row stays reachable and simply reads as inactive. */}
<div style={{ marginTop: 10, opacity: folios.autoColor ? 0.45 : 1 }}>
<Line label={t('journey.studio.colour')} wide>
<Swatches
value={folios.color}
onPick={c => setPageNumbers({ color: c, autoColor: false })}
/>
</Line>
</div>
</>
)}
</Section>
<p className="st-hint">{t('journey.studio.inspectorEmpty')}</p>
<p className="st-hint" style={{ paddingTop: 10 }}>
{t('journey.studio.inspectorEmpty')}
</p>
<p className="st-hint" style={{ paddingTop: 6 }}>
{t('journey.studio.pageHint')} {page.pageWidth} × {page.pageHeight} mm
</p>
</div>
</aside>
)
@@ -155,23 +193,46 @@ export function StudioInspector({
return (
<aside className="st-panel st-inspector">
<div className="st-panel-head">
<span>{one ? t(`journey.studio.kind.${el.kind}`) : t('journey.studio.multiple')}</span>
<span style={{ fontVariantNumeric: 'tabular-nums' }}>{sel.length > 1 ? sel.length : ''}</span>
{/*
The head says what is selected and carries the three things you do TO
it. It used to say only the kind, in the same small capitals as every
section label below it, which left the panel with no top.
*/}
<div className="st-panel-head st-inspector-head">
<span className="st-what">
{one ? t(`journey.studio.kind.${el.kind}`) : t('journey.studio.multiple')}
{sel.length > 1 && <em>{sel.length}</em>}
</span>
<span className="st-head-acts">
<button
className="st-act"
onClick={() => duplicate(spreadIndex, selection)}
title={t('journey.studio.duplicate')}
aria-label={t('journey.studio.duplicate')}
>
<Copy size={14} />
</button>
<button
className={`st-act ${el.locked ? 'is-on' : ''}`}
onClick={() => set({ locked: !el.locked })}
title={t(el.locked ? 'journey.studio.unlock' : 'journey.studio.lock')}
aria-label={t(el.locked ? 'journey.studio.unlock' : 'journey.studio.lock')}
aria-pressed={el.locked}
>
{el.locked ? <Lock size={14} /> : <Unlock size={14} />}
</button>
<button
className="st-act is-danger"
onClick={() => removeElements(spreadIndex, selection)}
title={t('journey.studio.delete')}
aria-label={t('journey.studio.delete')}
>
<Trash2 size={14} />
</button>
</span>
</div>
<div className="st-panel-scroll">
{one && (
<Section label={t('journey.studio.position')}>
<div className="st-grid2">
<Num label="X" value={el.frame.x} onChange={v => set({ frame: { ...el.frame, x: v } })} />
<Num label="Y" value={el.frame.y} onChange={v => set({ frame: { ...el.frame, y: v } })} />
<Num label={t('journey.studio.width')} value={el.frame.w} min={4} onChange={v => set({ frame: { ...el.frame, w: v } })} />
<Num label={t('journey.studio.height')} value={el.frame.h} min={4} onChange={v => set({ frame: { ...el.frame, h: v } })} />
</div>
</Section>
)}
{el.kind === 'text' && (
<>
<Section label={t('journey.studio.text')}>
@@ -185,6 +246,33 @@ export function StudioInspector({
{el.binding && !el.overridden && (
<p className="st-hint" style={{ paddingTop: 6 }}>{t('journey.studio.boundHint')}</p>
)}
{/*
How a point is set. Only a coordinate binding has the question,
and answering it re-sets the words on the spot rather than at
the next open — switching a notation and seeing nothing happen
reads as a broken control. Deliberately not `overridden`:
choosing a format is not writing the text.
*/}
{el.binding?.source === 'entry.location' && el.binding.format && (
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.coordsMark')}>
<Choice
value={el.binding.format}
options={[
{ value: 'dms' as const, label: t('journey.studio.coordsDms') },
{ value: 'decimal' as const, label: t('journey.studio.coordsDecimal') },
]}
onPick={f => {
const entry = source.entries.find(e => e.id === el.binding!.entryId)
const text = entry?.lat != null && entry.lng != null
? formatBookCoords(entry.lat, entry.lng, f)
: el.text
set({ binding: { ...el.binding!, format: f }, text })
}}
/>
</Line>
</div>
)}
</Section>
<Section label={t('journey.studio.typography')}>
@@ -215,34 +303,72 @@ export function StudioInspector({
)
})}
</div>
<div className="st-grid2" style={{ marginTop: 8 }}>
<Num label="pt" value={el.size} min={4} max={200} step={0.5} onChange={v => set({ size: v })} />
<Num label={t('journey.studio.leading')} value={el.leading} min={0.7} max={3} step={0.05} onChange={v => set({ leading: v })} />
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.weight')}>
<Choice
value={el.weight}
options={([400, 500, 600, 700] as const).map(w => ({
value: w,
label: String(w),
disabled: !hasWeight(el.font, w),
title: hasWeight(el.font, w) ? undefined : t('journey.studio.weightMissing'),
}))}
onPick={weight => set({ weight })}
/>
</Line>
<Line label={t('journey.studio.align')}>
<div className="st-row">
{([['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight], ['justify', AlignJustify]] as const).map(([a, Icon]) => (
<button
key={a}
className={`st-chip is-icon ${el.align === a ? 'is-on' : ''}`}
onClick={() => set({ align: a })}
aria-label={a}
>
<Icon size={14} />
</button>
))}
{/* Italic sits with the alignment because both are things
you do to a line rather than to a typeface. It had no
control at all before, though the renderer drew it. */}
<button
className={`st-chip is-icon ${el.italic ? 'is-on' : ''}`}
onClick={() => set({ italic: !el.italic })}
title={t('journey.studio.italic')}
aria-label={t('journey.studio.italic')}
aria-pressed={el.italic}
>
<Italic size={14} />
</button>
</div>
</Line>
</div>
<div className="st-row" style={{ marginTop: 8 }}>
{([400, 500, 600, 700] as const).map(w => (
<button
key={w}
className={`st-chip ${el.weight === w ? 'is-on' : ''}`}
disabled={!hasWeight(el.font, w)}
title={hasWeight(el.font, w) ? undefined : t('journey.studio.weightMissing')}
onClick={() => set({ weight: w })}
>
{w}
</button>
))}
<div className="st-grid2" style={{ marginTop: 10 }}>
<NumField label={t('journey.studio.size')} value={el.size} min={4} max={200} step={0.5} unit="pt" onChange={v => set({ size: v })} />
<NumField label={t('journey.studio.leading')} value={el.leading} min={0.7} max={3} step={0.05} onChange={v => set({ leading: v })} />
</div>
<div className="st-row" style={{ marginTop: 8 }}>
{([['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight], ['justify', AlignJustify]] as const).map(([a, Icon]) => (
<button key={a} className={`st-chip is-icon ${el.align === a ? 'is-on' : ''}`} onClick={() => set({ align: a })} aria-label={a}>
<Icon size={14} />
</button>
))}
<div style={{ marginTop: 10 }}>
{/*
Letter spacing was rendered but had no control, so type the
layout had tracked out could be edited in every way except the
one that made it look like that.
*/}
<NumField
label={t('journey.studio.tracking')}
value={el.tracking}
min={-0.2}
max={1}
step={0.01}
unit="em"
onChange={v => set({ tracking: v })}
/>
</div>
</Section>
<Section label={t('journey.studio.colour')}>
<Swatches value={el.color} onPick={c => set({ color: c })} />
<Line label={t('journey.studio.text')} wide>
<Swatches value={el.color} onPick={c => set({ color: c })} />
</Line>
</Section>
</>
)}
@@ -250,66 +376,79 @@ export function StudioInspector({
{el.kind === 'photo' && (
<>
<Section label={t('journey.studio.crop')}>
<div className="st-row">
{(['cover', 'contain'] as const).map(f => (
<button key={f} className={`st-chip ${el.fit === f ? 'is-on' : ''}`} onClick={() => set({ fit: f })}>
{t(`journey.studio.fit.${f}`)}
</button>
))}
</div>
<FocalPad
photoId={el.photoId}
x={el.focalX}
y={el.focalY}
onDrag={(x, y) => live({ focalX: x, focalY: y })}
onCommit={(x, y) => set({ focalX: x, focalY: y })}
hint={t('journey.studio.focalHint')}
/>
</Section>
<Section label={t('journey.studio.look')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
{(['none', 'bw', 'warm', 'cool', 'fade', 'contrast'] as const).map(f => (
<button key={f} className={`st-chip ${el.filter === f ? 'is-on' : ''}`} onClick={() => set({ filter: f })}>
{t(`journey.studio.filter.${f}`)}
</button>
))}
</div>
<div style={{ marginTop: 8 }}>
{/* A corner radius and a mask are the same idea at different
resolutions, so the radius steps aside once a shape is cut. */}
<Num
label={t('journey.studio.radius')}
value={el.radius}
min={0}
max={60}
step={0.5}
onChange={v => set({ radius: v })}
<Line label={t('journey.studio.crop')} wide>
<Choice
value={el.fit}
options={(['cover', 'contain'] as const).map(f => ({
value: f, label: t(`journey.studio.fit.${f}`),
}))}
onPick={fit => set({ fit })}
/>
</div>
</Line>
{/*
An empty frame has no picture to aim at, and asking for one by
id produced a request for /api/photos/null/thumbnail and a
broken image under a caption telling you to drag it.
*/}
{el.photoId != null ? (
<FocalPad
photoId={el.photoId}
x={el.focalX}
y={el.focalY}
onDrag={(x, y) => live({ focalX: x, focalY: y })}
onCommit={(x, y) => set({ focalX: x, focalY: y })}
hint={t('journey.studio.focalHint')}
/>
) : (
<p className="st-hint" style={{ paddingTop: 8 }}>{t('journey.studio.emptyFrame')}</p>
)}
</Section>
<Section label={t('journey.studio.frameStyle')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
{([
['none', 'plainFrame'],
['polaroid', 'polaroidFrame'],
['white', 'whiteFrame'],
['shadow', 'shadowFrame'],
['film', 'filmFrame'],
['tape', 'tapeFrame'],
] as const).map(([style, key]) => (
<button
key={style}
className={`st-chip ${el.frameStyle === style ? 'is-on' : ''}`}
onClick={() => set({ frameStyle: style })}
>
{t(`journey.studio.${key}`)}
</button>
))}
<Section label={t('journey.studio.look')}>
<Line label={t('journey.studio.look')} wide>
<Choice
value={el.filter}
options={(['none', 'bw', 'warm', 'cool', 'fade', 'contrast'] as const).map(f => ({
value: f, label: t(`journey.studio.filter.${f}`),
}))}
onPick={filter => set({ filter })}
/>
</Line>
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.frameStyle')} wide>
<Choice
value={el.frameStyle}
options={([
['none', 'plainFrame'],
['polaroid', 'polaroidFrame'],
['white', 'whiteFrame'],
['shadow', 'shadowFrame'],
['film', 'filmFrame'],
['tape', 'tapeFrame'],
] as const).map(([style, key]) => ({ value: style, label: t(`journey.studio.${key}`) }))}
onPick={frameStyle => set({ frameStyle })}
/>
</Line>
</div>
{/* A corner radius and a mask are the same idea at different
resolutions, so the radius steps aside once a shape is cut.
It did not, and edited a property the renderer ignored. */}
{(!el.mask || el.mask === 'rect') && (
<div style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.radius')}
value={el.radius}
min={0}
max={60}
step={0.5}
unit="mm"
onChange={v => set({ radius: v })}
/>
</div>
)}
</Section>
<Section label={t('journey.studio.mask')}>
<Section label={t('journey.studio.mask')} defaultOpen={false}>
<div className="st-mini-shapes">
<button
className={`st-mini-shape ${el.mask ? '' : 'is-on'}`}
@@ -351,40 +490,95 @@ export function StudioInspector({
</button>
))}
</div>
<div style={{ marginTop: 8 }}>
<Swatches value={el.fill ?? '#111111'} onPick={c => set({ fill: c })} />
<div style={{ marginTop: 10 }}>
{/* A photo had a corner radius and a shape did not, although
both store the same field and the renderer draws both. */}
<NumField
label={t('journey.studio.radius')}
value={el.radius}
min={0}
max={60}
step={0.5}
unit="mm"
onChange={v => set({ radius: v })}
/>
</div>
</Section>
<Section label={t('journey.studio.strokeStyle')}>
<div className="st-row">
{([
['solid', 'strokeSolid'],
['dashed', 'strokeDashed'],
['dotted', 'strokeDotted'],
] as const).map(([style, key]) => (
<button
key={style}
className={`st-chip ${el.strokeStyle === style ? 'is-on' : ''}`}
onClick={() => set({
strokeStyle: style,
// A stroke style with no stroke is invisible, so asking
// for dashes turns the outline on rather than doing
// nothing and looking broken.
...(el.stroke ? {} : { stroke: el.fill ?? '#141414', strokeWidth: el.strokeWidth || 0.5 }),
})}
>
{t(`journey.studio.${key}`)}
</button>
))}
<Section label={t('journey.studio.colour')}>
{/*
Fill and stroke, both named. The panel used to show one
unlabelled swatch row that wrote `fill`, so on an outline-only
shape it lit up a colour that was not being drawn and there was
no way to reach the line you could actually see.
*/}
<Line label={t('journey.studio.fill')} wide>
<Swatches value={el.fill ?? '#111111'} onPick={c => set({ fill: c })} />
</Line>
<Line label={t('journey.studio.stroke')} wide>
<Swatches
value={el.stroke ?? '#141414'}
onPick={c => set({ stroke: c, strokeWidth: el.strokeWidth || 0.5 })}
/>
</Line>
<div style={{ marginTop: 10 }}>
<Switch
label={t('journey.studio.fillOn')}
on={el.fill !== null}
onToggle={() => set({
// Turning the fill off on a shape with no stroke would make
// it invisible, so the outline comes on with it.
fill: el.fill === null ? '#111111' : null,
...(el.fill !== null && !el.stroke ? { stroke: '#141414', strokeWidth: el.strokeWidth || 0.5 } : {}),
})}
/>
<Switch
label={t('journey.studio.gradient')}
on={el.gradient !== 'none'}
onToggle={() => set({ gradient: el.gradient === 'none' ? 'down' : 'none' })}
/>
</div>
<div style={{ marginTop: 8 }}>
<Num
label={t('journey.studio.strokeStyle')}
{el.gradient !== 'none' && (
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.gradient')}>
<Choice
value={el.gradient}
options={[
{ value: 'down' as const, label: t('journey.studio.gradientDown') },
{ value: 'up' as const, label: t('journey.studio.gradientUp') },
]}
onPick={gradient => set({ gradient })}
/>
</Line>
</div>
)}
</Section>
<Section label={t('journey.studio.strokeStyle')} defaultOpen={false}>
<Line label={t('journey.studio.strokeStyle')} wide>
<Choice
value={el.strokeStyle}
options={([
['solid', 'strokeSolid'],
['dashed', 'strokeDashed'],
['dotted', 'strokeDotted'],
] as const).map(([style, key]) => ({ value: style, label: t(`journey.studio.${key}`) }))}
onPick={strokeStyle => set({
strokeStyle,
// A stroke style with no stroke is invisible, so asking for
// dashes turns the outline on rather than doing nothing.
...(el.stroke ? {} : { stroke: el.fill ?? '#141414', strokeWidth: el.strokeWidth || 0.5 }),
})}
/>
</Line>
<div style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.strokeWidth')}
value={el.strokeWidth}
min={0}
max={20}
step={0.1}
unit="mm"
onChange={v => set({ strokeWidth: v, ...(v > 0 && !el.stroke ? { stroke: '#141414' } : {}) })}
/>
</div>
@@ -392,9 +586,102 @@ export function StudioInspector({
</>
)}
<TravelInspector el={el} stats={stats} set={set} t={t} locale={locale} Section={Section} />
{el.kind === 'icon' && (
<>
<Section label={t('journey.studio.icon')}>
{/*
A search rather than the whole library: the picker in the panel
can afford to grow as it is scrolled, but the inspector is a
column beside a page and its job here is swapping one drawing
for a near neighbour. Swapping keeps the position, size and
colour that deleting and re-placing would lose.
*/}
<input
className="st-input"
value={iconQuery}
onChange={e => setIconQuery(e.target.value)}
placeholder={t('journey.studio.searchIcons')}
aria-label={t('journey.studio.searchIcons')}
spellCheck={false}
/>
<div className="st-mini-shapes" style={{ marginTop: 8 }}>
{iconChoices.map(name => {
const Glyph = iconComponent(name)
return (
<button
key={name}
className={`st-mini-shape ${el.name === name ? 'is-on' : ''}`}
onClick={() => set({ name })}
aria-label={name}
title={iconLabel(name)}
>
<Glyph strokeWidth={1.7} />
</button>
)
})}
</div>
</Section>
<Section label={t('journey.studio.arrange')}>
<Section label={t('journey.studio.colour')}>
<Line label={t('journey.studio.icon')} wide>
<Swatches value={el.color} onPick={c => set({ color: c })} />
</Line>
<div style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.lineWidth')}
value={el.lineWidth}
min={0.25}
max={4}
step={0.25}
onChange={v => set({ lineWidth: v })}
/>
</div>
</Section>
</>
)}
<TravelInspector el={el} stats={stats} set={set} t={t} locale={locale} />
{/*
Where it sits, folded away.
Everything in here can be done by dragging, which is how it is
actually done; the numbers are for the one time in ten you need the
same margin on two pages. Opacity and rotation live here too — both
were painted by the renderer and neither had a control anywhere.
*/}
{one && (
<Section label={t('journey.studio.position')} defaultOpen={false}>
<div className="st-grid2">
<NumField label="X" value={el.frame.x} unit="mm" onChange={v => set({ frame: { ...el.frame, x: v } })} />
<NumField label="Y" value={el.frame.y} unit="mm" onChange={v => set({ frame: { ...el.frame, y: v } })} />
<NumField label={t('journey.studio.width')} value={el.frame.w} min={4} unit="mm" onChange={v => set({ frame: { ...el.frame, w: v } })} />
<NumField label={t('journey.studio.height')} value={el.frame.h} min={4} unit="mm" onChange={v => set({ frame: { ...el.frame, h: v } })} />
</div>
<div className="st-grid2" style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.rotation')}
value={el.rotation}
min={-180}
max={180}
step={1}
unit="°"
onChange={v => set({ rotation: v })}
/>
<NumField
label={t('journey.studio.opacity')}
value={Math.round(el.opacity * 100)}
min={0}
max={100}
step={5}
unit="%"
onChange={v => set({ opacity: Math.min(1, Math.max(0, v / 100)) })}
/>
</div>
</Section>
)}
<Section label={t('journey.studio.arrange')} defaultOpen={false}>
<div className="st-row">
<button className="st-chip is-icon" onClick={() => raise(spreadIndex, el.id, 'front')} title={t('journey.studio.toFront')}>
<ChevronsUp size={14} />
@@ -409,57 +696,12 @@ export function StudioInspector({
<ChevronsDown size={14} />
</button>
</div>
<div className="st-row" style={{ marginTop: 8 }}>
<button className="st-chip" onClick={() => set({ locked: !el.locked })}>
{el.locked ? <Unlock size={13} /> : <Lock size={13} />}
{t(el.locked ? 'journey.studio.unlock' : 'journey.studio.lock')}
</button>
<button className="st-chip is-danger" onClick={() => removeElements(spreadIndex, selection)}>
<Trash2 size={13} />
{t('journey.studio.delete')}
</button>
</div>
</Section>
<p className="st-hint" style={{ paddingTop: 4 }}>
{t('journey.studio.pageHint')} {page.pageWidth} × {page.pageHeight} mm
</p>
</div>
</aside>
)
}
function Section({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="st-section">
<div className="st-section-label">{label}</div>
{children}
</div>
)
}
function Num({
label, value, onChange, min, max, step = 0.5,
}: { label: string; value: number; onChange: (v: number) => void; min?: number; max?: number; step?: number }) {
return (
<label className="st-field">
<span>{label}</span>
<input
className="st-input"
type="number"
value={Math.round(value * 100) / 100}
step={step}
min={min}
max={max}
onChange={e => {
const v = Number(e.target.value)
if (Number.isFinite(v)) onChange(v)
}}
/>
</label>
)
}
/**
* Where the picture is anchored inside its frame.
*
@@ -94,6 +94,7 @@ export default function StudioShell() {
spreadIndex={s.activeSpread}
page={s.page}
stats={s.stats}
source={s.source}
setPageNumbers={s.setPageNumbers}
t={s.t}
locale={s.locale}
@@ -380,6 +381,35 @@ function FormatPicker({ s }: { s: Studio }) {
/>
<span className="st-menu-unit">mm</span>
</div>
{/*
What the press takes off, and what it must not print into.
Under the trim size because they answer the same question — how big
is this book, really — and because a vendor states all three in one
breath. They were fixed at 3 and 5, which is what most photo-book
printers ask for and is useless to the one that asks for 5 and 10.
*/}
<div className="st-menu-custom">
<TrimField
label={s.t('journey.studio.bleed')}
value={s.page.bleed}
min={0}
max={20}
step={0.5}
onCommit={v => s.setPageEdge('bleed', v)}
/>
<span className="st-menu-times" />
<TrimField
label={s.t('journey.studio.safeArea')}
value={s.page.safe}
min={0}
max={40}
step={0.5}
onCommit={v => s.setPageEdge('safe', v)}
/>
<span className="st-menu-unit">mm</span>
</div>
</div>
)}
</div>
+62 -3
View File
@@ -9,6 +9,8 @@ import { useStudioStore } from '../../store/studioStore'
import { formatDate } from '../../utils/formatters'
import { SpreadFold, SpreadView } from './SpreadView'
import { photoSrc } from './bookRender'
import { formatBookCoords, formatBookDate, type CoordFormat } from './entryText'
import { coordValue } from './resolveBindings'
import { COVER_TEMPLATES, TEMPLATES, applyTemplate } from './templates'
import { MOOD_CONFIG, WEATHER_CONFIG } from '../../pages/journeyDetail/JourneyDetailPage.constants'
import { PanelHead as Head } from './StudioPanelHead'
@@ -36,6 +38,9 @@ export interface JourneySource {
story: string | null
location: string | null
date: string | null
/** Where the stop is, when the entry recorded one. Null on a written-only entry. */
lat: number | null
lng: number | null
mood: string | null
weather: string | null
pros: string[]
@@ -338,14 +343,39 @@ function ContentPanel({
} as BookElement)
}
const dropText = (value: string, size: number, weight: 400 | 700, entryId: number, kind: 'entry.title' | 'entry.story' | 'entry.location' | 'entry.date') => {
const w = page.pageWidth - 32
/**
* One piece of the entry, dropped on the page and still attached to it.
*
* `format` is what separates a place name from a set of coordinates: both
* read the entry's location, and which of the two gets printed is a property
* of the binding rather than a second source — see the contract. `width`
* exists because a line of coordinates arriving inside a full-column
* selection rectangle looks like a bug; only the short marks pass it.
*/
const dropText = (
value: string,
size: number,
weight: 400 | 700,
entryId: number,
kind: 'entry.title' | 'entry.story' | 'entry.location' | 'entry.date',
opts: { format?: CoordFormat; width?: number; value?: string } = {},
) => {
const w = opts.width ?? page.pageWidth - 32
addElement(active, {
id: uid('t'), kind: 'text', frame: centre(w, size * 0.4 + 10),
rotation: 0, opacity: 1, locked: false,
text: value, font: 'sans', size, weight, italic: false,
align: 'left', leading: weight === 700 ? 1.1 : 1.55, tracking: weight === 700 ? -0.02 : 0,
color: '#1a1a1a', binding: { source: kind, entryId }, overridden: false,
color: '#1a1a1a',
binding: {
source: kind,
entryId,
...(opts.format ? { format: opts.format } : {}),
// The fact behind the words, for the marks whose words are formatted —
// see `value` in the contract.
...(opts.value ? { value: opts.value } : {}),
},
overridden: false,
} as BookElement)
}
@@ -364,6 +394,8 @@ function ContentPanel({
const dropMark = (variant: 'mood' | 'weather', code: string, label: string) =>
addElement(active, {
...base, id: uid('bd'), kind: 'badge', autoColor: true,
// Set here as well as in the contract: this object is cast, not parsed.
showIcon: true, showLabel: true, autoIconColor: true, iconColor: '#111111',
frame: centre(page.pageWidth * 0.22, page.pageHeight * 0.062),
variant, text: label, sub: '', code, style: 'plain',
} as BookElement)
@@ -473,6 +505,33 @@ function ContentPanel({
{t('journey.studio.addPlace')}
</button>
)}
{/*
The day and the point. Both are set the way the rest of the
book sets them — the long date, coordinates in degrees — so a
mark placed here and one the auto layout placed read alike.
*/}
{e.date && (
<button
className="st-chip"
onClick={() => dropText(
formatBookDate(e.date!, locale), 8, 700, e.id, 'entry.date',
{ width: page.pageWidth * 0.36, value: e.date! },
)}
>
{t('journey.studio.dateMark')}
</button>
)}
{e.lat != null && e.lng != null && (
<button
className="st-chip"
onClick={() => dropText(
formatBookCoords(e.lat!, e.lng!, 'dms'), 8, 700, e.id, 'entry.location',
{ format: 'dms', width: page.pageWidth * 0.36, value: coordValue(e.lat!, e.lng!) },
)}
>
{t('journey.studio.coordsMark')}
</button>
)}
{/*
What the entry recorded besides its story. Each chip shows
the value rather than the field name — "Sunny" tells you
@@ -1,3 +1,4 @@
import { useState } from 'react'
import type {
BookBadgeElement, BookCountriesElement, BookElement, BookListElement, BookMapElement,
BookMetric, BookStatsElement, JourneyStats,
@@ -6,7 +7,11 @@ import { BOOK_METRICS } from '@trek/shared'
import { isStale, refreshPatch } from './travelRefresh'
import { Swatches } from './StudioSwatches'
import { BOOK_FONTS, BOOK_FONT_ORDER, hasWeight, nearestWeight } from './bookFonts'
import { useMapSources } from './mapSources'
import { sourceIdOf, useMapSources } from './mapSources'
import { printDpi, tileView } from './mapTiles'
import { routeFor } from './travelRefresh'
import { Choice, Line, Picks, Section, Switch } from './StudioControls'
import { fetchRoads } from './roadRoute'
/**
* Properties of the travel elements.
@@ -24,18 +29,15 @@ export interface TravelInspectorProps {
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
locale: string
Section: (p: { label: string; children: React.ReactNode }) => React.JSX.Element
}
function Toggle({ on, label, onClick }: { on: boolean; label: string; onClick: () => void }) {
return (
<button className={`st-chip ${on ? 'is-on' : ''}`} onClick={onClick}>
{label}
</button>
)
interface Props<T> {
el: T
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
}
export function TravelInspector({ el, stats, set, t, Section }: TravelInspectorProps) {
export function TravelInspector({ el, stats, set, t }: TravelInspectorProps) {
if (
el.kind !== 'map' && el.kind !== 'stats' && el.kind !== 'countries'
&& el.kind !== 'badge' && el.kind !== 'list'
@@ -63,11 +65,11 @@ export function TravelInspector({ el, stats, set, t, Section }: TravelInspectorP
</div>
)}
{el.kind === 'map' && <MapProps el={el} set={set} t={t} Section={Section} />}
{el.kind === 'stats' && <StatsProps el={el} set={set} t={t} Section={Section} />}
{el.kind === 'countries' && <CountriesProps el={el} set={set} t={t} Section={Section} />}
{el.kind === 'badge' && <BadgeProps el={el} set={set} t={t} Section={Section} />}
{el.kind === 'list' && <ListProps el={el} set={set} t={t} Section={Section} />}
{el.kind === 'map' && <MapProps el={el} set={set} t={t} stats={stats} />}
{el.kind === 'stats' && <StatsProps el={el} set={set} t={t} />}
{el.kind === 'countries' && <CountriesProps el={el} set={set} t={t} />}
{el.kind === 'badge' && <BadgeProps el={el} set={set} t={t} />}
{el.kind === 'list' && <ListProps el={el} set={set} t={t} />}
{/*
* Type, for all five alike.
@@ -78,7 +80,7 @@ export function TravelInspector({ el, stats, set, t, Section }: TravelInspectorP
* stats block in the default sans is a book with one element in the
* wrong typeface and no way to fix it.
*/}
<Section label={t('journey.studio.typography')}>
<Section label={t('journey.studio.typography')} defaultOpen={false}>
<div className="st-fonts">
{BOOK_FONT_ORDER.map(id => {
const font = BOOK_FONTS[id]
@@ -101,102 +103,91 @@ export function TravelInspector({ el, stats, set, t, Section }: TravelInspectorP
)
})}
</div>
<div className="st-row" style={{ marginTop: 8 }}>
{([400, 500, 600, 700] as const).map(w => (
<button
key={w}
className={`st-chip ${el.weight === w ? 'is-on' : ''}`}
disabled={!hasWeight(el.font, w)}
title={hasWeight(el.font, w) ? undefined : t('journey.studio.weightMissing')}
onClick={() => set({ weight: w } as Partial<BookElement>)}
>
{w}
</button>
))}
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.weight')}>
<Choice
value={el.weight}
options={([400, 500, 600, 700] as const).map(w => ({
value: w,
label: String(w),
disabled: !hasWeight(el.font, w),
title: hasWeight(el.font, w) ? undefined : t('journey.studio.weightMissing'),
}))}
onPick={weight => set({ weight } as Partial<BookElement>)}
/>
</Line>
<Line label={t('journey.studio.textScale')}>
<Choice
value={el.textScale}
options={([0.7, 0.85, 1, 1.2, 1.5] as const).map(scale => ({
value: scale, label: `${scale}×`,
}))}
onPick={textScale => set({ textScale } as Partial<BookElement>)}
/>
</Line>
</div>
</Section>
{/*
* Colour, for all five alike.
* Colour, for all five alike, and in one group.
*
* These were two sections called Accent and Colour, one under the other,
* each ten unlabelled swatches wrapping onto two rows: twenty squares and
* no way to tell which of them painted what. The role now sits beside the
* row and says it — the accent is the mark's own colour, the ink is what
* is written on it.
*
* They ship with one warm accent so a book made without touching anything
* still reads as designed — but that is a starting point, not a house
* style. A book printed to match a cover, or one that simply should not be
* orange, needs both of these, and they are the same two properties on
* every travel element.
* still reads as designed. That is a starting point, not a house style: a
* book printed to match a cover, or one that simply should not be orange,
* needs both of these.
*/}
<Section label={t('journey.studio.accent')}>
<Swatches value={el.accent} onPick={c => set({ accent: c } as Partial<BookElement>)} />
</Section>
<Section label={t('journey.studio.colour')}>
{/*
Picking a colour is what turns automatic off.
A chip works out its own text colour from the fill it carries, which
is right until somebody wants something else — and then a separate
switch to find first is one step too many. So the swatch does both,
and the Automatic chip beside it is the way back rather than the way
in. Only marks have this; the other elements have no fill of their
own to answer to.
*/}
<Swatches
value={el.color}
onPick={c => set(
(el.kind === 'badge' ? { color: c, autoColor: false } : { color: c }) as Partial<BookElement>,
)}
/>
<Line label={t('journey.studio.accent')} wide>
<Swatches value={el.accent} onPick={c => set({ accent: c } as Partial<BookElement>)} />
</Line>
<Line label={t('journey.studio.text')} wide>
{/*
Picking a colour is what turns automatic off, so the swatch does
both and the switch below is the way back rather than the way in.
Only marks have it; nothing else here has a fill of its own for the
words to answer to.
*/}
<Swatches
value={el.color}
onPick={c => set(
(el.kind === 'badge' ? { color: c, autoColor: false } : { color: c }) as Partial<BookElement>,
)}
/>
</Line>
{el.kind === 'badge' && (
<div className="st-row" style={{ marginTop: 8 }}>
<Toggle
on={el.autoColor}
<div style={{ marginTop: 10 }}>
<Switch
label={t('journey.studio.autoColour')}
onClick={() => set({ autoColor: !el.autoColor } as Partial<BookElement>)}
on={el.autoColor}
onToggle={() => set({ autoColor: !el.autoColor } as Partial<BookElement>)}
/>
</div>
)}
</Section>
<Section label={t('journey.studio.textScale')}>
<div className="st-row">
{([0.7, 0.85, 1, 1.2, 1.5] as const).map(scale => (
<button
key={scale}
className={`st-chip ${Math.abs(el.textScale - scale) < 0.01 ? 'is-on' : ''}`}
onClick={() => set({ textScale: scale } as Partial<BookElement>)}
>
{scale === 1 ? '1×' : `${scale}×`}
</button>
))}
</div>
</Section>
</>
)
}
function ListProps({ el, set, t, Section }: {
el: BookListElement
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
Section: TravelInspectorProps['Section']
}) {
function ListProps({ el, set, t }: Props<BookListElement>) {
return (
<Section label={t('journey.studio.addProsCons')}>
<div className="st-row">
{(['columns', 'stacked'] as const).map(layout => (
<button
key={layout}
className={`st-chip ${el.layout === layout ? 'is-on' : ''}`}
onClick={() => set({ layout } as Partial<BookElement>)}
>
{t(layout === 'columns' ? 'journey.studio.layoutGrid' : 'journey.studio.layoutColumn')}
</button>
))}
<Toggle
on={el.showMarks}
label={t('journey.studio.showMarks')}
onClick={() => set({ showMarks: !el.showMarks } as Partial<BookElement>)}
<Line label={t('journey.studio.layout')}>
<Choice
value={el.layout}
options={[
{ value: 'columns' as const, label: t('journey.studio.layoutGrid') },
{ value: 'stacked' as const, label: t('journey.studio.layoutColumn') },
]}
onPick={layout => set({ layout } as Partial<BookElement>)}
/>
</div>
<div className="st-grid2" style={{ marginTop: 8 }}>
</Line>
<div className="st-grid2" style={{ marginTop: 10 }}>
<label className="st-field">
<span>{t('journey.editor.pros')}</span>
<input
@@ -214,52 +205,139 @@ function ListProps({ el, set, t, Section }: {
/>
</label>
</div>
<div style={{ marginTop: 10 }}>
<Switch
label={t('journey.studio.showMarks')}
on={el.showMarks}
onToggle={() => set({ showMarks: !el.showMarks } as Partial<BookElement>)}
/>
</div>
</Section>
)
}
function MapProps({ el, set, t, Section }: {
el: BookMapElement
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
Section: TravelInspectorProps['Section']
}) {
const sources = useMapSources(el.frame, el.points)
function MapProps({ el, set, t, stats }: Props<BookMapElement> & { stats: JourneyStats | null }) {
const [roadState, setRoadState] = useState<'idle' | 'busy'>('idle')
const [roadDone, setRoadDone] = useState(0)
const hasRoads = (el.roads ?? []).some(r => r && r.length > 1)
/*
* One leg at a time, paced, and written into the document when it is done
* rather than leg by leg: a hundred commits would be a hundred undo steps and
* a hundred autosaves for one action.
*/
const loadRoads = async () => {
setRoadState('busy')
setRoadDone(0)
try {
const roads = await fetchRoads(
el.points.map(p => ({ lat: p.lat, lng: p.lng })),
{ onProgress: done => setRoadDone(done) },
)
set({ roads } as Partial<BookElement>)
} finally {
setRoadState('idle')
}
}
const sources = useMapSources(el.frame, el.points, { source: el.source, tileUrl: el.tileUrl })
/** Only trips that put stops on the route: a map of the others is a blank. */
const tripsWithRoute = (stats?.trips ?? []).filter(t => t.points > 0)
/*
* The grid this element will really fetch, asked for here so the panel can
* say what it will print at. Same call the renderer makes, same answer.
*/
const view = el.source === 'tiles' && el.tileUrl
? tileView(el.points, { w: el.frame.w, h: el.frame.h }, el.tileUrl, el.zoom)
: null
const dpi = view ? printDpi(view, el.tileUrl) : null
return (
<>
{/*
Which trip, when the journey is made of more than one.
A journey of two trips drawn as one route puts a line from the last
stop of the first to the first stop of the second: usually the longest
leg on the page, and one nobody travelled. Switching here re-cuts the
route on the spot rather than at the next refresh, because a control
that changes nothing visible reads as broken.
*/}
{tripsWithRoute.length > 1 && (
<Section label={t('journey.studio.mapScope')}>
<Choice
value={el.tripId ?? 0}
options={[
{ value: 0, label: t('journey.studio.mapWholeJourney') },
...tripsWithRoute.map(trip => ({
value: trip.id,
label: trip.title || t('journey.studio.untitled'),
})),
]}
onPick={id => {
if (!stats) return
const tripId = id === 0 ? null : id
const route = routeFor(stats, tripId)
set({
tripId,
countries: tripId == null
? stats.countries.map(c => c.code)
: [...new Set(route.map(p => p.country).filter((c): c is string => !!c))],
points: route.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null })),
} as Partial<BookElement>)
}}
/>
</Section>
)}
{/* Where the picture comes from and what it looks like: one question
with two halves, which is one group rather than two. */}
<Section label={t('journey.studio.routeMap')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
{(['minimal', 'outline', 'paper', 'dark'] as const).map(style => (
<button
key={style}
className={`st-chip ${el.style === style ? 'is-on' : ''}`}
onClick={() => set({ style } as Partial<BookElement>)}
>
{t(`journey.studio.mapStyle.${style}`)}
</button>
))}
</div>
</Section>
<Section label={t('journey.studio.mapSource')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
{sources.map(src => (
<button
key={src.id}
className={`st-chip ${el.source === src.id ? 'is-on' : ''}`}
onClick={() => set({
source: src.id,
<Line label={t('journey.studio.mapSource')} wide>
<Choice
value={sourceIdOf(el, sources)}
options={sources.map(src => ({ value: src.id, label: t(src.labelKey) }))}
onPick={id => {
const src = sources.find(x => x.id === id)
if (!src) return
set({
source: src.source,
tileUrl: src.url,
// The credit travels with the source. Switching to imagery and
// leaving the previous attribution would print the wrong one.
attribution: src.attribution,
} as Partial<BookElement>)}
>
{t(src.labelKey)}
</button>
))}
} as Partial<BookElement>)
}}
/>
</Line>
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.style')} wide>
<Choice
value={el.style}
options={(['minimal', 'outline', 'paper', 'dark'] as const).map(style => ({
value: style, label: t(`journey.studio.mapStyle.${style}`),
}))}
onPick={style => set({ style } as Partial<BookElement>)}
/>
</Line>
</div>
{el.source !== 'vector' && (
<p className="st-hint" style={{ paddingTop: 6 }}>{t('journey.studio.mapSourceHint')}</p>
<>
<p className="st-hint" style={{ paddingTop: 8 }}>
{t(SOURCE_HINT[sourceIdOf(el, sources)] ?? 'journey.studio.mapSourceHint')}
</p>
{/*
What this map will actually print at, at the size it is now.
A number rather than a warning icon: 300 means nothing to argue
with, and somebody who wants a soft map on purpose can have one.
*/}
{dpi != null && (
<p className={`st-hint ${dpi < 150 ? 'st-stale' : ''}`} style={{ paddingTop: 6 }}>
{t('journey.studio.mapPrintDpi')} {dpi} dpi
{dpi < 150 && ` — ${t('journey.studio.mapPrintDpiLow')}`}
</p>
)}
</>
)}
</Section>
@@ -274,108 +352,201 @@ function MapProps({ el, set, t, Section }: {
two dots in the middle of it.
*/}
<Section label={t('journey.studio.mapFraming')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
<button
className={`st-chip ${!el.fitToCountries ? 'is-on' : ''}`}
onClick={() => set({ fitToCountries: false } as Partial<BookElement>)}
>
{t('journey.studio.mapFitStops')}
</button>
<button
className={`st-chip ${el.fitToCountries ? 'is-on' : ''}`}
onClick={() => set({ fitToCountries: true } as Partial<BookElement>)}
>
{t('journey.studio.mapFitCountry')}
</button>
</div>
<Line label={t('journey.studio.mapFit')}>
<Choice
value={el.fitToCountries ? 'country' : 'stops'}
options={[
{ value: 'stops' as const, label: t('journey.studio.mapFitStops') },
{ value: 'country' as const, label: t('journey.studio.mapFitCountry') },
]}
onPick={v => set({ fitToCountries: v === 'country' } as Partial<BookElement>)}
/>
</Line>
{/*
Room around what is drawn, as a share of it: the same setting has to
look right around a walk across a city and a drive across a
continent, and millimetres cannot do that.
*/}
<div className="st-row" style={{ marginTop: 8, flexWrap: 'wrap' }}>
{([
['journey.studio.mapPadTight', 0.04],
['journey.studio.mapPadNormal', 0.18],
['journey.studio.mapPadWide', 0.5],
['journey.studio.mapPadFar', 1.2],
] as const).map(([key, value]) => (
<button
key={key}
className={`st-chip ${Math.abs(el.fitPadding - value) < 0.001 ? 'is-on' : ''}`}
onClick={() => set({ fitPadding: value } as Partial<BookElement>)}
>
{t(key)}
</button>
))}
</div>
<Line label={t('journey.studio.mapPadding')}>
<Choice
value={([0.04, 0.18, 0.5, 1.2] as const).find(v => Math.abs(el.fitPadding - v) < 0.001) ?? 0.18}
options={[
{ value: 0.04, label: t('journey.studio.mapPadTight') },
{ value: 0.18, label: t('journey.studio.mapPadNormal') },
{ value: 0.5, label: t('journey.studio.mapPadWide') },
{ value: 1.2, label: t('journey.studio.mapPadFar') },
]}
onPick={fitPadding => set({ fitPadding } as Partial<BookElement>)}
/>
</Line>
{/*
And the shape. A rectangle is a map in a box, which is what a full
page wants; cut to the coastline it stops being a figure and becomes
an illustration that can sit next to anything.
*/}
<div className="st-row" style={{ marginTop: 8, flexWrap: 'wrap' }}>
<button
className={`st-chip ${el.clip === 'rect' ? 'is-on' : ''}`}
onClick={() => set({ clip: 'rect' } as Partial<BookElement>)}
>
{t('journey.studio.mapClipRect')}
</button>
<button
className={`st-chip ${el.clip === 'country' ? 'is-on' : ''}`}
disabled={el.countries.length === 0}
title={el.countries.length === 0 ? t('journey.studio.mapClipNeedsCountry') : undefined}
onClick={() => set({ clip: 'country' } as Partial<BookElement>)}
>
{t('journey.studio.mapClipCountry')}
</button>
</div>
<Line label={t('journey.studio.mapShape')}>
<Choice
value={el.clip}
options={[
{ value: 'rect' as const, label: t('journey.studio.mapClipRect') },
{
value: 'country' as const,
label: t('journey.studio.mapClipCountry'),
disabled: el.countries.length === 0,
title: el.countries.length === 0 ? t('journey.studio.mapClipNeedsCountry') : undefined,
},
]}
onPick={clip => set({ clip } as Partial<BookElement>)}
/>
</Line>
</Section>
{el.source === 'tiles' && (
<Section label={t('journey.studio.mapZoom')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
<button
className={`st-chip ${el.zoom === null ? 'is-on' : ''}`}
onClick={() => set({ zoom: null } as Partial<BookElement>)}
>
{t('journey.studio.mapZoomAuto')}
</button>
{[3, 5, 7, 9, 11, 13, 15, 17].map(z => (
<button
key={z}
className={`st-chip ${el.zoom === z ? 'is-on' : ''}`}
onClick={() => set({ zoom: z } as Partial<BookElement>)}
>
{z}
</button>
))}
</div>
<Section label={t('journey.studio.mapZoom')} defaultOpen={false}>
<Choice
value={el.zoom ?? -1}
options={[
{ value: -1, label: t('journey.studio.mapZoomAuto') },
...[3, 5, 7, 9, 11, 13, 15, 17].map(z => ({ value: z, label: String(z) })),
]}
onPick={z => set({ zoom: z === -1 ? null : z } as Partial<BookElement>)}
/>
</Section>
)}
<Section label={t('journey.studio.mapLayers')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
{el.source !== 'tiles' && el.source !== 'static' && (
<Toggle on={el.showLand} label={t('journey.studio.showLand')} onClick={() => set({ showLand: !el.showLand } as Partial<BookElement>)} />
{/*
How the line itself is drawn, and whether it follows real roads.
Open by default, unlike the groups below it. It was folded, on the
reasoning that a look is chosen once per book — but a control nobody can
see is a control nobody has, and the first thing anyone wants from a map
of a journey is the line across it.
*/}
<Section label={t('journey.studio.routeLook')}>
<Line label={t('journey.studio.routeStyle')} wide>
<Choice
value={el.routeStyle}
options={[
{ value: 'plain' as const, label: t('journey.studio.routePlain') },
{ value: 'drawn' as const, label: t('journey.studio.routeDrawn') },
]}
onPick={routeStyle => set({ routeStyle } as Partial<BookElement>)}
/>
</Line>
{/*
The roads, fetched once and kept.
Not a switch, because it is not free: it asks a public routing service
one question per leg, from this browser, and the answer is then frozen
into the document so the book prints the same line offline and next
year. A switch would imply it could simply be turned back on later,
on a page that is being exported, which is exactly when it cannot.
*/}
<div style={{ marginTop: 10 }}>
{/*
Which way the line goes between two stops.
A choice rather than a button, because that is what it is from where
the user sits: the roads, or the way a map has always drawn a leg it
does not know. That the roads have to be fetched once and are then
kept in the book is an implementation detail, and the only place it
shows is the counter while it works.
*/}
<Line label={t('journey.studio.roads')} wide>
{roadState === 'busy' ? (
<div className="st-row">
<span className="st-chip is-on">
{t('journey.studio.roadsBusy')} {roadDone}/{Math.max(1, el.points.length - 1)}
</span>
</div>
) : (
<Choice
value={hasRoads ? 'roads' : 'direct'}
options={[
{ value: 'roads' as const, label: t('journey.studio.roadsFollow') },
{ value: 'direct' as const, label: t('journey.studio.roadsDirect') },
]}
onPick={v => {
if (v === 'direct') {
set({ roads: [] } as Partial<BookElement>)
} else {
void loadRoads()
}
}}
/>
)}
</Line>
{hasRoads && roadState !== 'busy' && (
<div className="st-row" style={{ marginTop: 8 }}>
<button className="st-chip" onClick={() => void loadRoads()}>
{t('journey.studio.roadsAgain')}
</button>
</div>
)}
<Toggle on={el.showRoute} label={t('journey.studio.showRoute')} onClick={() => set({ showRoute: !el.showRoute } as Partial<BookElement>)} />
<Toggle on={el.showPins} label={t('journey.studio.showPins')} onClick={() => set({ showPins: !el.showPins } as Partial<BookElement>)} />
<Toggle on={el.showLabels} label={t('journey.studio.showLabels')} onClick={() => set({ showLabels: !el.showLabels } as Partial<BookElement>)} />
<p className="st-hint" style={{ paddingTop: 6 }}>
{t(hasRoads ? 'journey.studio.roadsHave' : 'journey.studio.roadsHint')}
</p>
</div>
{el.routeStyle === 'drawn' && (
<>
<Line label={t('journey.studio.routeArc')} wide>
<Choice
value={el.routeArc}
options={[
{ value: 'straight' as const, label: t('journey.studio.routeStraight') },
{ value: 'bow' as const, label: t('journey.studio.routeBow') },
]}
onPick={routeArc => set({ routeArc } as Partial<BookElement>)}
/>
</Line>
{el.routeArc === 'bow' && (
<div style={{ marginTop: 10 }}>
<Switch
label={t('journey.studio.routeDashArcs')}
on={el.routeDash === 'arcs'}
onToggle={() => set({
routeDash: el.routeDash === 'arcs' ? 'solid' : 'arcs',
} as Partial<BookElement>)}
/>
</div>
)}
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.mapStops')} wide>
<Choice
value={el.pinStyle}
options={[
{ value: 'dot' as const, label: t('journey.studio.pinDot') },
{ value: 'photo' as const, label: t('journey.studio.pinPhoto') },
]}
onPick={pinStyle => set({ pinStyle } as Partial<BookElement>)}
/>
</Line>
</div>
{el.pinStyle === 'photo' && !el.points.some(p => p.photoId != null) && (
<p className="st-hint" style={{ paddingTop: 8 }}>{t('journey.studio.pinPhotoNone')}</p>
)}
</>
)}
</Section>
{/* Four things that are either drawn or not. They used to be the same
pill as the style choice above, so a layer looked like an option. */}
<Section label={t('journey.studio.mapLayers')}>
{el.source !== 'tiles' && el.source !== 'static' && (
<Switch label={t('journey.studio.showLand')} on={el.showLand} onToggle={() => set({ showLand: !el.showLand } as Partial<BookElement>)} />
)}
<Switch label={t('journey.studio.showRoute')} on={el.showRoute} onToggle={() => set({ showRoute: !el.showRoute } as Partial<BookElement>)} />
<Switch label={t('journey.studio.showPins')} on={el.showPins} onToggle={() => set({ showPins: !el.showPins } as Partial<BookElement>)} />
<Switch label={t('journey.studio.showLabels')} on={el.showLabels} onToggle={() => set({ showLabels: !el.showLabels } as Partial<BookElement>)} />
</Section>
</>
)
}
function StatsProps({ el, set, t, Section }: {
el: BookStatsElement
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
Section: TravelInspectorProps['Section']
}) {
function StatsProps({ el, set, t }: Props<BookStatsElement>) {
const toggleMetric = (m: BookMetric) => {
const next = el.metrics.includes(m) ? el.metrics.filter(x => x !== m) : [...el.metrics, m]
// An empty panel would be a blank rectangle nobody could get back out of,
@@ -386,44 +557,46 @@ function StatsProps({ el, set, t, Section }: {
return (
<>
{/*
Which figures, out of seven. A set rather than a row of choices, and it
looks like one now: the picked ones carry a tick instead of being the
same filled pill the layout below uses for "this one".
*/}
<Section label={t('journey.studio.metrics')}>
<div className="st-row" style={{ flexWrap: 'wrap' }}>
{BOOK_METRICS.map(m => (
<Toggle
key={m}
on={el.metrics.includes(m)}
label={t(`journey.studio.metric.${m}`)}
onClick={() => toggleMetric(m)}
/>
))}
</div>
<Picks
value={el.metrics}
options={BOOK_METRICS.map(m => ({ value: m, label: t(`journey.studio.metric.${m}`) }))}
onToggle={toggleMetric}
/>
</Section>
<Section label={t('journey.studio.layout')}>
<div className="st-row">
{(['grid', 'row', 'column'] as const).map(layout => (
<button
key={layout}
className={`st-chip ${el.layout === layout ? 'is-on' : ''}`}
onClick={() => set({ layout } as Partial<BookElement>)}
>
{t(`journey.studio.layout${layout[0].toUpperCase()}${layout.slice(1)}`)}
</button>
))}
</div>
<div className="st-row" style={{ marginTop: 8 }}>
{(['metric', 'imperial'] as const).map(units => (
<button
key={units}
className={`st-chip ${el.units === units ? 'is-on' : ''}`}
onClick={() => set({ units } as Partial<BookElement>)}
>
{units === 'metric' ? 'km' : 'mi'}
</button>
))}
<Toggle
<Line label={t('journey.studio.layout')}>
<Choice
value={el.layout}
options={(['grid', 'row', 'column'] as const).map(layout => ({
value: layout,
label: t(`journey.studio.layout${layout[0].toUpperCase()}${layout.slice(1)}`),
}))}
onPick={layout => set({ layout } as Partial<BookElement>)}
/>
</Line>
<Line label={t('journey.studio.units')}>
<Choice
value={el.units}
options={[
{ value: 'metric' as const, label: 'km' },
{ value: 'imperial' as const, label: 'mi' },
]}
onPick={units => set({ units } as Partial<BookElement>)}
/>
</Line>
<div style={{ marginTop: 10 }}>
{/* Its label used to be "Elements", which is the name of a panel on
the other side of the screen and not what this draws. */}
<Switch
label={t('journey.studio.showIcons')}
on={el.showIcons}
label={t('journey.studio.elements')}
onClick={() => set({ showIcons: !el.showIcons } as Partial<BookElement>)}
onToggle={() => set({ showIcons: !el.showIcons } as Partial<BookElement>)}
/>
</div>
</Section>
@@ -431,40 +604,34 @@ function StatsProps({ el, set, t, Section }: {
)
}
function CountriesProps({ el, set, t, Section }: {
el: BookCountriesElement
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
Section: TravelInspectorProps['Section']
}) {
function CountriesProps({ el, set, t }: Props<BookCountriesElement>) {
return (
<Section label={t('journey.studio.countries')}>
<div className="st-row">
{(['list', 'grid', 'column'] as const).map(layout => (
<button
key={layout}
className={`st-chip ${el.layout === layout ? 'is-on' : ''}`}
onClick={() => set({ layout } as Partial<BookElement>)}
>
{t(`journey.studio.layout${layout[0].toUpperCase()}${layout.slice(1)}`)}
</button>
))}
</div>
<div className="st-row" style={{ marginTop: 8, flexWrap: 'wrap' }}>
<Toggle on={el.showOutline} label={t('journey.studio.showOutline')} onClick={() => set({ showOutline: !el.showOutline } as Partial<BookElement>)} />
<Toggle on={el.showFlag} label={t('journey.studio.showFlag')} onClick={() => set({ showFlag: !el.showFlag } as Partial<BookElement>)} />
<Toggle on={el.showName} label={t('journey.studio.showName')} onClick={() => set({ showName: !el.showName } as Partial<BookElement>)} />
</div>
<div className="st-row" style={{ marginTop: 8 }}>
{(['left', 'center', 'right'] as const).map(align => (
<button
key={align}
className={`st-chip ${el.align === align ? 'is-on' : ''}`}
onClick={() => set({ align } as Partial<BookElement>)}
>
{align}
</button>
))}
<Line label={t('journey.studio.layout')}>
<Choice
value={el.layout}
options={(['list', 'grid', 'column'] as const).map(layout => ({
value: layout,
label: t(`journey.studio.layout${layout[0].toUpperCase()}${layout.slice(1)}`),
}))}
onPick={layout => set({ layout } as Partial<BookElement>)}
/>
</Line>
{/* These three read as raw English out of the code before: `left`,
`center`, `right`, straight from the value. */}
<Line label={t('journey.studio.align')}>
<Choice
value={el.align}
options={(['left', 'center', 'right'] as const).map(align => ({
value: align, label: t(`journey.studio.align.${align}`),
}))}
onPick={align => set({ align } as Partial<BookElement>)}
/>
</Line>
<div style={{ marginTop: 10 }}>
<Switch label={t('journey.studio.showOutline')} on={el.showOutline} onToggle={() => set({ showOutline: !el.showOutline } as Partial<BookElement>)} />
<Switch label={t('journey.studio.showFlag')} on={el.showFlag} onToggle={() => set({ showFlag: !el.showFlag } as Partial<BookElement>)} />
<Switch label={t('journey.studio.showName')} on={el.showName} onToggle={() => set({ showName: !el.showName } as Partial<BookElement>)} />
</div>
{/*
@@ -503,41 +670,97 @@ function CountriesProps({ el, set, t, Section }: {
)
}
function BadgeProps({ el, set, t, Section }: {
el: BookBadgeElement
set: (patch: Partial<BookElement>) => void
t: (k: string) => string
Section: TravelInspectorProps['Section']
}) {
/** What each imagery source is for, said once where it is chosen. */
const SOURCE_HINT: Record<string, string> = {
relief: 'journey.studio.mapSourceReliefHint',
satellite: 'journey.studio.mapSourceSatelliteHint',
}
/** The variants that draw something as well as saying something. */
const ICON_VARIANTS = ['flag', 'country', 'mood', 'weather']
function BadgeProps({ el, set, t }: Props<BookBadgeElement>) {
const showIcon = el.showIcon !== false
const showLabel = el.showLabel !== false
const parts = (icon: boolean, label: boolean) =>
set({ showIcon: icon, showLabel: label } as Partial<BookElement>)
return (
<>
<Section label={t('journey.studio.marks')}>
<label className="st-field">
<span>{t('journey.studio.text')}</span>
<Line label={t('journey.studio.text')}>
<input
className="st-input"
value={el.text}
onChange={e => set({ text: e.target.value } as Partial<BookElement>)}
/>
</label>
<label className="st-field" style={{ marginTop: 8 }}>
<span>{t('journey.studio.styleCaption')}</span>
</Line>
<Line label={t('journey.studio.styleCaption')}>
<input
className="st-input"
value={el.sub}
onChange={e => set({ sub: e.target.value } as Partial<BookElement>)}
/>
</label>
<div className="st-row" style={{ marginTop: 8, flexWrap: 'wrap' }}>
{(['plain', 'chip', 'outline', 'stacked'] as const).map(style => (
<button
key={style}
className={`st-chip ${el.style === style ? 'is-on' : ''}`}
onClick={() => set({ style } as Partial<BookElement>)}
>
{style}
</button>
))}
</div>
</Line>
{/* These four printed the raw value — `plain`, `chip` — in every one of
the twenty-three languages. */}
<Line label={t('journey.studio.style')} wide>
<Choice
value={el.style}
options={(['plain', 'chip', 'outline', 'stacked'] as const).map(style => ({
value: style, label: t(`journey.studio.markStyle.${style}`),
}))}
onPick={style => set({ style } as Partial<BookElement>)}
/>
</Line>
</Section>
{/*
The icon, for the marks that have one.
Three combinations rather than two switches: a mark with neither its
picture nor its words is an empty box, and offering it as a state people
can reach means offering them a way to lose an element on the page.
*/}
{ICON_VARIANTS.includes(el.variant) && (
<Section label={t('journey.studio.icon')}>
<Line label={t('journey.studio.shows')} wide>
<Choice
value={showIcon && showLabel ? 'both' : showIcon ? 'icon' : 'label'}
options={[
{ value: 'both' as const, label: t('journey.studio.iconAndLabel') },
{ value: 'icon' as const, label: t('journey.studio.iconOnly') },
{ value: 'label' as const, label: t('journey.studio.labelOnly') },
]}
onPick={v => parts(v !== 'label', v !== 'icon')}
/>
</Line>
{showIcon && (
<>
{/*
A mood's icon carries the journal's own colour and the others
carry the element's accent — which is right until it is not, and
until now there was no way past it: the swatch below is the only
thing that reaches the icon, because lucide takes its colour as a
prop rather than inheriting it.
*/}
<Line label={t('journey.studio.colour')} wide>
<Swatches
value={el.iconColor}
onPick={c => set({ iconColor: c, autoIconColor: false } as Partial<BookElement>)}
/>
</Line>
<div style={{ marginTop: 10 }}>
<Switch
label={t('journey.studio.autoColour')}
on={el.autoIconColor !== false}
onToggle={() => set({ autoIconColor: el.autoIconColor === false } as Partial<BookElement>)}
/>
</div>
</>
)}
</Section>
)}
</>
)
}
@@ -3,6 +3,10 @@ import { BOOK_METRICS } from '@trek/shared'
import { useStudioStore } from '../../store/studioStore'
import { PanelHead } from './StudioPanelHead'
import { TravelPreview } from './TravelPreview'
import { formatBookCoords } from './entryText'
import { routeFor } from './travelRefresh'
import { useMapSources } from './mapSources'
import { fetchRoads } from './roadRoute'
/**
* The journey's own figures, as things you can put on a page.
@@ -47,27 +51,27 @@ function formatDistance(metres: number, locale: string): string {
return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(metres / 1000)} km`
}
/**
* Degrees and minutes with a hemisphere letter, the way a chart labels a
* position. The decimal form is what a machine reads; this is for a page
* someone is holding.
*/
function formatCoords(lat: number, lng: number): string {
const part = (v: number, pos: string, neg: string) => {
const deg = Math.floor(Math.abs(v))
const min = Math.round((Math.abs(v) - deg) * 60)
return `${deg}°${String(min).padStart(2, '0')}'${v >= 0 ? pos : neg}`
}
return `${part(lat, 'N', 'S')} ${part(lng, 'E', 'W')}`
}
function Card({ label, onClick, children }: {
function Card({ label, onClick, children, recommended = false, title }: {
label: string
onClick: () => void
/**
* Marked as the one to reach for, with a ring rather than with words.
*
* The label sits in a grid cell about eighty pixels wide, where "Satellite ·
* recommended" is two lines of ellipsis. A ring says the same thing in no
* space at all, and the tooltip carries the word for anyone who wonders why
* this card looks different.
*/
recommended?: boolean
title?: string
children: React.ReactNode
}) {
return (
<button className="st-travel-card" onClick={onClick} title={label}>
<button
className={`st-travel-card ${recommended ? 'is-recommended' : ''}`}
onClick={onClick}
title={title ? `${label} — ${title}` : label}
>
{children}
<span className="st-travel-card-label">{label}</span>
</button>
@@ -85,6 +89,7 @@ export function StudioTravelPanel({
locale: string
}) {
const addElement = useStudioStore(s => s.addElement)
const updateElement = useStudioStore(s => s.updateElement)
const active = useStudioStore(s => s.activeSpread)
const doc = useStudioStore(s => s.doc)
const spread = doc?.spreads[active]
@@ -95,6 +100,23 @@ export function StudioTravelPanel({
return { x: (W - w) / 2, y: (page.pageHeight - h) / 2, w, h }
}
const mapSide = Math.min(page.pageWidth, page.pageHeight) * 0.72
/*
* The imagery this instance can reach, so the relief card below places a map
* that already has its template and its credit rather than an empty one the
* user then has to point at a source.
*
* Asked for above the empty-state return, and not beside the card that reads
* it: a journey whose figures are still loading renders this panel once with
* no stats at all, and a hook that only runs on the second render is a hook
* count that changes between them.
*/
const sources = useMapSources(
{ x: 0, y: 0, w: mapSide, h: mapSide * 0.78 },
(stats?.points ?? []).map(p => ({ lat: p.lat, lng: p.lng })),
)
if (!stats) {
return (
<>
@@ -144,7 +166,13 @@ export function StudioTravelPanel({
* click places it, so the preview and the result are the same object — there
* is no second description of what a card means.
*/
const mapSide = Math.min(page.pageWidth, page.pageHeight) * 0.72
/** The linked trips that actually put stops on the route. */
const tripsWithRoute = (stats.trips ?? []).filter(t => t.points > 0)
/* Satellite first: the recommendation should not be the second thing read. */
const imagery = sources
.filter(s => s.id === 'relief' || s.id === 'satellite')
.sort((a, b) => (a.id === 'satellite' ? -1 : b.id === 'satellite' ? 1 : 0))
/**
* One country, as the entry a list would have made of it.
@@ -172,22 +200,44 @@ export function StudioTravelPanel({
url = '',
attribution = '',
clip: 'rect' | 'country' = 'rect',
): BookElement => ({
/** Null is the whole journey; a trip id is a map of that trip alone. */
tripId: number | null = null,
): BookElement => {
const route = routeFor(stats, tripId)
return {
...base, id: uid('mp'), kind: 'map',
frame: centre(mapSide, mapSide * 0.78),
style, source, tileUrl: url, attribution, zoom: null, clip,
style, source, tileUrl: url, attribution, zoom: null, clip, tripId,
/*
* White over a photograph, ink on paper. The accent IS the line, so this is
* how a satellite map arrives drawn the way the reference draws it, while
* the colour stays something the user can change afterwards.
*/
accent: source === 'tiles' || source === 'static' ? '#ffffff' : base.accent,
showLand: true, showRoute: true, showPins: true, showLabels: false,
countries: stats.countries.map(c => c.code),
points: stats.points.map(p => ({ lat: p.lat, lng: p.lng, label: p.label })),
/*
* A map placed today gets the drawn treatment; the contract defaults to the
* plain line so that every book made before this existed opens unchanged.
* Set explicitly rather than inherited because this object is cast, not
* parsed.
*/
routeStyle: 'drawn', routeArc: 'bow', routeDash: 'arcs', pinStyle: 'photo',
countries: tripId == null
? stats.countries.map(c => c.code)
: [...new Set(route.map(p => p.country).filter((c): c is string => !!c))],
points: route.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null })),
/*
* Frozen into the element, like every other travel figure: a page that
* fetches its own route at print time is a page that changes when someone
* edits the trip, and prints empty when the export runs signed out.
*/
path,
fitPadding: 0.18,
// Empty until somebody asks for the roads; see roadRoute.ts.
roads: [],
fitPadding: 0.5,
fitToCountries: true,
} as BookElement)
} as BookElement
}
/*
* A mark is placed at the size that suits what it holds.
@@ -216,6 +266,7 @@ export function StudioTravelPanel({
const [fw, fh] = MARK_SIZE[variant] ?? [0.24, 0.08]
return {
...base, id: uid('bd'), kind: 'badge', autoColor: true,
showIcon: true, showLabel: true, autoIconColor: true, iconColor: '#111111',
frame: centre(page.pageWidth * fw, page.pageHeight * fh),
variant, text, sub, code, style,
} as BookElement
@@ -236,7 +287,32 @@ export function StudioTravelPanel({
} as BookElement)
/** Place a copy — the previewed element keeps its own id for React. */
const place = (el: BookElement) => addElement(active, { ...el, id: uid(el.kind[0]) } as BookElement)
const place = (el: BookElement) => {
const placed = { ...el, id: uid(el.kind[0]) } as BookElement
addElement(active, placed)
/*
* A map arrives following the roads.
*
* Asked for after the element is on the page rather than before, so the map
* appears at once and the line firms up a moment later: a panel that sat
* there for fifteen seconds after a click would read as broken, and the
* straight line it starts with is the one it would have had anyway.
*
* Legs long enough to have been flights are never sent (see roadRoute.ts),
* the router's own cache answers a second placement of the same journey for
* free, and a failure leaves the leg exactly as it was.
*/
if (placed.kind === 'map' && placed.points.length > 1) {
void fetchRoads(placed.points.map(pt => ({ lat: pt.lat, lng: pt.lng })))
.then(roads => {
if (roads.some(r => r && r.length > 1)) {
updateElement(active, placed.id, { roads } as Partial<BookElement>)
}
})
.catch(() => { /* No roads is a state the map already draws. */ })
}
}
const first = stats.points[0] ?? null
const firstCountry = stats.countries[0] ?? null
@@ -256,7 +332,7 @@ export function StudioTravelPanel({
})
if (first) {
marks.push({
el: badgeEl('coords', formatCoords(first.lat, first.lng), first.label, null),
el: badgeEl('coords', formatBookCoords(first.lat, first.lng), first.label, null),
label: t('journey.studio.coordsMark'),
})
}
@@ -302,8 +378,74 @@ export function StudioTravelPanel({
</Card>
)
})}
{/*
The two imagery maps, as cards rather than as settings.
They were reachable only by placing an outline map and then
changing its source in the inspector, which is a thing nobody
finds. They are different pictures, not variants of one: relief
is land shaded in its own colours against a dark sea, drawn at
a scale that suits a continent, and satellite is the ground
itself, which is what a page about one country wants.
*/}
{imagery.map(src => (
<Card
key={src.id}
/*
* Satellite is marked rather than merely listed. The three
* imagery options are not equals: relief stops at about six
* hundred metres to the pixel, which is a continent's worth
* of detail and a smudge at country size, and the outlines
* are a diagram. For the page most people are making —
* a route across one or two countries — this is the one
* that prints, and saying so beats letting them find out
* after the book is bound.
*/
label={t(src.labelKey)}
recommended={src.id === 'satellite'}
title={src.id === 'satellite' ? t('journey.studio.recommended') : undefined}
onClick={() => place(mapEl('minimal', 'tiles', src.url, src.attribution))}
>
<TravelPreview
el={mapEl('minimal', 'tiles', src.url, src.attribution)}
minHeight={62}
maxHeight={80}
/>
</Card>
))}
</div>
{/*
A map per trip, for a journey made of more than one.
Two trips printed as a single route draw a line from the last
stop of the first to the first stop of the second, which is
usually the longest leg on the page and one nobody travelled.
Offered rather than imposed: some journeys really are one route
across several trips, and those still get the map above.
Only trips that have stops on the route are listed — a linked
trip nobody wrote about would place an empty frame.
*/}
{tripsWithRoute.length > 1 && (
<div style={{ marginTop: 12 }}>
<div className="st-section-label">{t('journey.studio.mapPerTrip')}</div>
<div className="st-travel-grid">
{tripsWithRoute.map(trip => {
const el = mapEl('minimal', 'vector', '', '', 'rect', trip.id)
return (
<Card
key={trip.id}
label={trip.title || t('journey.studio.untitled')}
onClick={() => place(el)}
>
<TravelPreview el={el} minHeight={62} maxHeight={80} />
</Card>
)
})}
</div>
</div>
)}
</>
) : (
<p className="st-hint">{t('journey.studio.noRoute')}</p>
+630 -37
View File
@@ -73,7 +73,30 @@ function typeSize(el: TravelElement, base: number): number {
const round2 = (n: number) => Math.round(n * 100) / 100
/** Tile geometry, kept finer than the rest: see the note where it is used. */
const round3 = (n: number) => Math.round(n * 1000) / 1000
const TILE_OVERLAP = 0.12
/**
* How far each tile is drawn past its own square, in millimetres.
*
* ── Why it is this large, and why it is a fraction ───────────────────────
*
* A tile boundary that lands mid-pixel leaves a hairline of paper showing
* through the map, and the eye finds it immediately: it reads as a fold or a
* scratch rather than as rounding. Drawing each tile slightly larger than its
* spacing closes that, and costs nothing, because the strip that overlaps is
* the same picture the neighbour draws there anyway.
*
* It used to be a flat twelve hundredths of a millimetre, which is about half a
* device pixel at 1:1 — and the editor does not draw at 1:1. The page is
* scaled, so at a third of full size that overlap is a sixth of a pixel and the
* seams come back, which is exactly when a map is full of them: a page-sized
* satellite map is a hundred and fifty tiles, so it has some three hundred
* internal edges to get wrong.
*
* Four percent of a tile survives every zoom the canvas offers, and the floor
* covers the case of a tile drawn very small. The element clips, so the
* overhang at the last row and column never shows.
*/
const tileOverlapMm = (size: number) => Math.max(0.8, size * 0.04)
/** #rrggbb plus an alpha. */
function rgba(hex: string, alpha: number): string {
@@ -81,8 +104,13 @@ function rgba(hex: string, alpha: number): string {
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
}
export function TravelElementView({ el, frameStyle }: { el: BookElement; frameStyle: CSSProperties }) {
if (el.kind === 'map') return <MapView el={el} frameStyle={frameStyle} />
export function TravelElementView({ el, frameStyle, big = false }: {
el: BookElement
frameStyle: CSSProperties
/** Drawn at a size worth fetching real imagery for, rather than as a thumbnail. */
big?: boolean
}) {
if (el.kind === 'map') return <MapView el={el} frameStyle={frameStyle} big={big} />
if (el.kind === 'stats') return <StatsView el={el} frameStyle={frameStyle} />
if (el.kind === 'countries') return <CountriesView el={el} frameStyle={frameStyle} />
if (el.kind === 'badge') return <BadgeView el={el} frameStyle={frameStyle} />
@@ -166,18 +194,24 @@ function routeInk(accent: string, onDark: boolean): string {
* than a fixed number of millimetres, which keeps the margin looking the same
* whether the map is 40mm across or 300.
*/
function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProperties }) {
function MapView({ el, frameStyle, big = false }: {
el: BookMapElement
frameStyle: CSSProperties
/** False in a thumbnail, where a page of imagery would be a page of waste. */
big?: boolean
}) {
const palette = MAP_PALETTES[el.style]
// Per element: two cut maps on one spread sharing a stencil would both be cut
// to whichever of them rendered last.
const clipId = `st-clip-${el.id}`
const ink = routeInk(el.accent, palette.onDark)
/** Whether the ground under the line is a photograph rather than paper. */
const imagery = el.source === 'tiles' || el.source === 'static'
/*
* Country outlines are the vector map's *subject*; over real imagery they are
* a second coastline drawn on top of the one in the picture. So they are only
* drawn when there is no picture underneath.
*/
const imagery = el.source === 'tiles' || el.source === 'static'
/*
* The outlines are needed for two different jobs, and only one of them is
* drawing. As a picture they are the vector map's subject, and over real
@@ -208,6 +242,13 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
* down with it, in a renderer that also has to run for print.
*/
const path = el.path ?? []
/*
* The roads, one per leg, `null` where a leg has none. Read the same
* defensive way `path` is: an element built by hand and cast rather than
* parsed genuinely has the field missing, and `.length` on undefined takes
* the whole spread down in a renderer that also has to run for print.
*/
const roads = el.roads ?? []
const trail = path.map(seg => seg.map(([lat, lng]) => projectMercator(lng, lat)))
/*
@@ -245,6 +286,109 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y)
}
}
/*
* A road wanders well outside the box around the two stops it joins — that is
* the whole point of drawing it. Fitted to the stops alone, the interesting
* part of it would be outside the frame.
*/
for (const road of roads) {
if (!road) continue
for (const [lat, lng] of road) {
const q = projectMercator(lng, lat)
minX = Math.min(minX, q.x); minY = Math.min(minY, q.y)
maxX = Math.max(maxX, q.x); maxY = Math.max(maxY, q.y)
}
}
/*
* ── The bow ───────────────────────────────────────────────────────────
*
* A straight line between two stops a continent apart is a claim about the
* journey that is plainly false, and a shallow curve is how printed maps have
* always said "this part was a flight". Two gates decide how much:
*
* **How far it was, in kilometres.** A fact about the journey rather than
* about the zoom, so two cafes four kilometres apart stay straight at every
* size and Tokyo to Los Angeles bows at every size. Ramped smoothly from
* 150km to 15000km rather than switched at a threshold, or a route would have
* one leg visibly curved and its neighbour dead straight.
*
* **Which way it runs.** A meridian is a great circle *and* a straight line
* in Mercator, so bowing a due north-south leg draws a detour that never
* happened. The east-west share of the leg damps it.
*
* The direction is poleward from the route's MEAN latitude, decided once for
* the element: per leg, a chain crossing the equator would flip sides halfway
* along and read as random rather than as drawn.
*/
const bowed = el.routeArc === 'bow' && trail.length === 0 && points.length > 1
/** Kilometres between two coordinates, for the ramp. */
const km = (a: { lat: number; lng: number }, b: { lat: number; lng: number }) => {
const r = (d: number) => (d * Math.PI) / 180
const dLat = r(b.lat - a.lat)
const dLng = r(b.lng - a.lng)
const h = Math.sin(dLat / 2) ** 2
+ Math.cos(r(a.lat)) * Math.cos(r(b.lat)) * Math.sin(dLng / 2) ** 2
return 12742 * Math.asin(Math.min(1, Math.sqrt(h)))
}
const meanLat = el.points.length
? el.points.reduce((sum, p) => sum + p.lat, 0) / el.points.length
: 0
/**
* How far each leg bows, as a share of its own chord, and which way.
*
* A fraction rather than a distance, so the same numbers are right on a 40mm
* inset and a 400mm spread — what the eye reads is the angle the line leaves
* its marker at, and that is scale free.
*/
const bows: { k: number; nx: number; ny: number }[] = bowed
? el.points.slice(0, -1).map((a, i) => {
const b = el.points[i + 1]
const pa = projectMercator(a.lng, a.lat)
const pb = projectMercator(b.lng, b.lat)
const dx = pb.x - pa.x
const dy = pb.y - pa.y
const d = Math.hypot(dx, dy)
if (d < 1e-6) return { k: 0, nx: 0, ny: 0 }
const u = Math.min(1, Math.max(0, Math.log(km(a, b) / 150) / Math.log(10)))
const ramp = u * u * (3 - 2 * u)
// How much of the leg runs east-west, which is where a bow is truthful.
const eastWest = 0.35 + 0.65 * Math.abs(dx / d)
// The normal, turned to point away from the equator side the route is on.
let nx = -dy / d
let ny = dx / d
const poleward = meanLat >= 0 ? -1 : 1
if (Math.abs(ny) < 1e-9) {
// A due north-south leg has no poleward side; break the tie east.
nx = Math.abs(nx)
} else if (Math.sign(ny) !== poleward) {
nx = -nx
ny = -ny
}
return { k: 0.07 * ramp * eastWest, nx, ny }
})
: []
/*
* The apexes join the extent before it is fitted. Without this the tile
* window and the vector fit are both cut to the straight chords, and a bowed
* leg is clipped by the very frame it was fitted to.
*/
bows.forEach((bow, i) => {
if (!bow.k) return
const a = points[i]
const b = points[i + 1]
const d = Math.hypot(b.x - a.x, b.y - a.y)
const ax = (a.x + b.x) / 2 + bow.k * d * bow.nx
const ay = (a.y + b.y) / 2 + bow.k * d * bow.ny
minX = Math.min(minX, ax); maxX = Math.max(maxX, ax)
minY = Math.min(minY, ay); maxY = Math.max(maxY, ay)
})
const empty = !Number.isFinite(minX)
if (empty) { minX = -1; minY = -1; maxX = 1; maxY = 1 }
@@ -280,6 +424,36 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
minX = cx - spanX / 2; maxX = cx + spanX / 2
minY = cy - spanY / 2; maxY = cy + spanY / 2
/*
* ── The window takes the frame's proportions ─────────────────────────
*
* 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 — while the imagery *covered* it, because a map with a strip of paper
* down one edge is not a map. On a frame whose shape did not match the
* route's, those are different windows, and the tiles won: the picture filled
* the box and the route ran off the top of it. Drag a map narrow enough and
* the line simply left the page.
*
* Widening the window to the frame's own proportions makes the two the same
* window. Cover and contain agree by construction, the route is inside
* whatever shape the element is dragged to, and the imagery still reaches
* every edge — it just shows a little more ground on the short side, which is
* what the extra room was always going to be filled with.
*/
const aspect = W / H
const haveW = maxX - minX
const haveH = maxY - minY
if (haveW / haveH < aspect) {
const want = haveH * aspect
minX = cx - want / 2
maxX = cx + want / 2
} else {
const want = haveW / aspect
minY = cy - want / 2
maxY = cy + want / 2
}
const scale = Math.min(W / (maxX - minX), H / (maxY - minY))
const offX = (W - (maxX - minX) * scale) / 2 - minX * scale
const offY = (H - (maxY - minY) * scale) / 2 - minY * scale
@@ -296,6 +470,68 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
const pin = Math.max(0.35, Math.min(W, H) * 0.0085)
const label = typeSize(el, 0.035)
/*
* ── The drawn treatment ───────────────────────────────────────────────
*
* A separate scale from the plain one above, because it is a different
* drawing rather than the same drawing recoloured. Fractions of the shorter
* side with a floor and a ceiling: the floor keeps a 40mm inset from losing
* the line, and the ceiling is what the plain route is missing — `routeWidth`
* has no upper bound and reaches 1.6mm on a page, which is part of why the
* current map reads as plotted rather than as drawn.
*
* The line lands at about a third of a marker's radius, which is the ratio
* the printed reference holds at every size.
*/
const S = Math.min(W, H)
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
const drawn = el.routeStyle === 'drawn'
const coreW = clamp(S * 0.0055, 0.32, 1.3)
const casingW = coreW * 1.9
const beadR = clamp(coreW * 3.1, 1.7, 4.8)
const beadRing = beadR * 0.2
const dotR = coreW * 1.5
/*
* A numbered stop is bigger than a dot and smaller than a photograph: it has
* to hold two digits legibly at page size without competing with the pictures
* beside it.
*/
const numR = clamp(coreW * 2.2, 1.3, 3.4)
/*
* The digit reads against the marker's own fill rather than against the page,
* so it inverts with it: dark on a light line, light on a dark one. Measured
* the same way the marks decide their ink.
*/
const numInk = brightness(el.accent) > 0.55 ? '#1c1b19' : '#ffffff' // theme-lint-disable — print ink
const dashOn = coreW * 2.4
const dashOff = coreW * 1.8
/*
* ── Why the colours key on the ground rather than on the accent ───────
*
* One route crosses near-black bathymetry and bright desert in the same
* picture, so no single colour works: what works is a light line with a dark
* edge under it over imagery, and the same idea inverted over pale paper.
* Keying it on what is underneath means any accent the user picks stays
* legible, instead of the panel having to warn them off half the palette.
*/
const lightGround = imagery || palette.onDark
/*
* The line is the element's accent, full stop — which is why a map placed
* over imagery is given a white accent rather than being special-cased here.
* Guessing "the accent is still the default, so I will override it" cannot
* tell a colour somebody chose from one a constructor happened to write, and
* the moment it guesses wrong the user has a control that does nothing.
*
* The casing is the part that reads the ground: a dark halo under a light
* line over photography, a light halo under a dark line on pale paper. That
* is what keeps one route legible across near-black sea and bright desert in
* the same picture, whatever colour the line itself is.
*/
const coreInk = el.accent
const casingInk = lightGround ? '#000000' : '#ffffff' // theme-lint-disable — a halo, not app chrome
const casingAlpha = lightGround ? 0.3 : 0.55
/*
* Real imagery, when the element was placed with a source that has some.
*
@@ -322,7 +558,7 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
maxLat: topLeft.lat,
maxLng: bottomRight.lng,
minLat: bottomRight.lat,
})
}, big ? 'print' : 'preview')
: null
/*
@@ -348,7 +584,165 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
const trailOnScreen = tiled
? path.map(seg => seg.map(([lat, lng]) => projectOntoTiles(tiled, lng, lat)))
: trail.map(seg => seg.map(p => at(p.x, p.y)))
const lines = trailOnScreen.length ? trailOnScreen : (route.length > 1 ? [route] : [])
/*
* ── What the plain line is made of ────────────────────────────────────
*
* A recorded track wins outright, as it always has. Otherwise the stop chain,
* cut at every leg that has a road so the road can be drawn in its place —
* without that cut, a journey with roads for three legs of twelve would print
* the three and silently drop the other nine, which is what `path` does today
* when it only covers part of a trip.
*/
const roadOnScreen = (leg: number) => {
const road = roads[leg]
if (!road || road.length < 2) return null
return road.map(([lat, lng]) => {
const q = projectMercator(lng, lat)
return tiled ? projectOntoTiles(tiled, lng, lat) : at(q.x, q.y)
})
}
const chain: { x: number; y: number }[][] = []
if (route.length > 1) {
let run: { x: number; y: number }[] = [route[0]]
for (let i = 0; i < route.length - 1; i++) {
const road = roadOnScreen(i)
if (road) {
if (run.length > 1) chain.push(run)
chain.push(road)
run = [route[i + 1]]
} else {
run.push(route[i + 1])
}
}
if (run.length > 1) chain.push(run)
}
const lines = trailOnScreen.length ? trailOnScreen : chain
/*
* ── The drawn line, as path strings ───────────────────────────────────
*
* One strand per contiguous run. A recorded track is always straight
* segments and always solid: bowing a line somebody actually walked, or
* dashing it, would be drawing a journey that did not happen. The inferred
* stop chain is where the bows and the dashes live.
*
* The bow is faded out a second time here, in millimetres. `bows` decided how
* much a leg curves as a share of its own chord, which is a fact about the
* journey; this is the fact about the page, and it stops a 40mm inset from
* showing a hairline wobble that reads as a wobble rather than as a curve.
*/
const strands: { d: string; dash?: string }[] = []
if (drawn) {
if (trailOnScreen.length) {
for (const seg of trailOnScreen) {
if (seg.length < 2) continue
strands.push({ d: `M${seg.map(pt => `${round2(pt.x)} ${round2(pt.y)}`).join(' L')}` })
}
} else if (route.length > 1) {
// Straight legs join into one strand; each bowed leg is its own, so it
// can be dashed without dashing its neighbours.
let run: string[] = []
const flush = () => {
if (run.length > 1) strands.push({ d: `M${run.join(' L')}` })
run = []
}
for (let i = 0; i < route.length - 1; i++) {
const a = route[i]
const b = route[i + 1]
/*
* A leg somebody asked the roads for is drawn as the road, solid and
* unbowed: it is the way that was actually taken, so neither the curve
* nor the dash — both of which mean "inferred" — belongs on it.
*/
const road = roads[i]
if (road && road.length > 1) {
flush()
const onScreen = road.map(([lat, lng]) => {
const q = projectMercator(lng, lat)
return tiled ? projectOntoTiles(tiled, lng, lat) : at(q.x, q.y)
})
strands.push({ d: `M${onScreen.map(pt => `${round2(pt.x)} ${round2(pt.y)}`).join(' L')}` })
continue
}
const bow = bows[i]
const dmm = Math.hypot(b.x - a.x, b.y - a.y)
let sag = bow ? bow.k * dmm : 0
if (sag > 0) {
// Below about a stroke width the curve is not read as one.
const v = Math.min(1, Math.max(0, (sag - coreW * 0.6) / coreW))
sag *= v * v * (3 - 2 * v)
}
if (!sag) {
if (!run.length) run.push(`${round2(a.x)} ${round2(a.y)}`)
run.push(`${round2(b.x)} ${round2(b.y)}`)
continue
}
flush()
/*
* A quadratic reaches only half way to its control point at the middle,
* which is why the apex is doubled here — the same arithmetic the shape
* paths already rely on.
*/
const cxp = (a.x + b.x) / 2 + 2 * sag * bow.nx
const cyp = (a.y + b.y) / 2 + 2 * sag * bow.ny
const d = `M${round2(a.x)} ${round2(a.y)} Q${round2(cxp)} ${round2(cyp)} ${round2(b.x)} ${round2(b.y)}`
if (el.routeDash === 'arcs') {
/*
* Phase-fitted, so every leg ends on a whole dash at its marker
* rather than on a stub. Butt caps: a round cap swells each dash by a
* full stroke width and closes the gaps it was drawn for.
*/
const arcLen = dmm * (1 + (8 / 3) * (sag / dmm) ** 2)
const n = Math.max(1, Math.round(arcLen / (dashOn + dashOff)))
const fit = arcLen / (n * (dashOn + dashOff))
strands.push({ d, dash: `${round2(dashOn * fit)} ${round2(dashOff * fit)}` })
} else {
strands.push({ d })
}
}
flush()
}
}
/*
* ── Which stops carry a photograph ────────────────────────────────────
*
* Walked in order, carrying the last bead's position: a stop closer than a
* bead's width to the one before it becomes a dot instead. That is what
* produces the reference's string of beads that touch and overlap slightly,
* rather than a solid caterpillar of overlapping discs — and nothing is
* dropped, so the shape of the route survives whatever the spacing does.
*
* The two ends always keep their picture when they have one: they are where
* a reader looks first.
*/
const beads: { i: number; x: number; y: number; photo: number | null }[] = []
let numbered = false
if (drawn) {
// Too small to carry photographs at all: a bead wider than a twelfth of the
// frame is a picture with a map around it.
const roomForPhotos = el.pinStyle === 'photo' && big && beadR * 2 <= S * 0.16
/*
* Numbers stand in for the photographs that are not there, so they belong
* to the photo treatment alone. A map asked for dots gets dots, and a
* thumbnail gets dots too: two digits at 130px is a smudge.
*/
numbered = el.pinStyle === 'photo' && big && numR * 2 <= S * 0.12
let last: { x: number; y: number } | null = null
route.forEach((pt, i) => {
const photoId = (el.points[i] as { photoId?: number | null } | undefined)?.photoId ?? null
const isEnd = i === 0 || i === route.length - 1
const room = !last || Math.hypot(pt.x - last.x, pt.y - last.y) >= beadR * 1.15
const bead = roomForPhotos && photoId != null && (isEnd || room)
if (bead) last = { x: pt.x, y: pt.y }
beads.push({ i, x: pt.x, y: pt.y, photo: bead ? photoId : null })
})
}
const anyBead = beads.some(b => b.photo != null)
return (
<div style={{ ...frameStyle, overflow: 'hidden' }}>
@@ -357,14 +751,9 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
Each tile is placed rather than flowed: a grid of images with no gaps
between them is not something CSS layout gives you for free at
fractional millimetre sizes.
They are drawn a little larger than their spacing on purpose. A tile
boundary that lands mid-pixel leaves a hairline of white paper showing
through the map, and the eye finds it immediately — it reads as a fold
or a scratch rather than as rounding. A tenth of a millimetre of
overlap costs nothing (the overlapping strip is the same picture) and
closes the seam at every zoom and every print size.
fractional millimetre sizes. They are drawn past their own square on
purpose — see `tileOverlapMm`, which is what keeps the seams closed at
every zoom the canvas offers.
*/}
{tiled && !cutToLand && tiled.tiles.map(t => (
<img
@@ -376,8 +765,8 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
position: 'absolute',
left: `${round3(tiled.originX + t.x * tiled.size)}mm`,
top: `${round3(tiled.originY + t.y * tiled.size)}mm`,
width: `${round3(tiled.size + TILE_OVERLAP)}mm`,
height: `${round3(tiled.size + TILE_OVERLAP)}mm`,
width: `${round3(tiled.size + tileOverlapMm(tiled.size))}mm`,
height: `${round3(tiled.size + tileOverlapMm(tiled.size))}mm`,
display: 'block',
}}
/>
@@ -408,6 +797,18 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
width={`${W}mm`}
height={`${H}mm`}
viewBox={`0 0 ${W} ${H}`}
/*
* Accuracy over speed, everywhere on this map.
*
* The default lets a browser trade geometric precision for drawing
* speed once a picture gets busy, and a route with two hundred stops
* over a hundred and fifty tiles is busy. What that trade costs is
* exactly what a printed line must not lose: a bowed leg goes faceted
* and a bead's ring goes lumpy. Nothing here is a filter, so the whole
* drawing stays vector into the PDF and the press resolves it, not the
* browser.
*/
shapeRendering="geometricPrecision"
style={{ display: 'block', position: 'relative' }}
>
{/*
@@ -417,6 +818,30 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
else: the outlines below draw themselves normally when the map is a
rectangle, and become the edge of the picture when it is not.
*/}
{/*
A stencil per bead, in the map's own millimetres.
Its own `defs` rather than a shared one: the block below belongs to
cutting the map to a coastline and only exists when that is on, and a
stencil nested inside a condition that has nothing to do with it is
how the photographs came out square — the clip-path pointed at an id
that was never written, so `slice` showed the corners it was supposed
to cut off.
User space rather than the tidier fractional stencil, because a
fractional clip on an `<image>` is applied against a box browsers
disagree about, and a silent no-op looks exactly like the bug above.
*/}
{anyBead && (
<defs>
{beads.filter(m => m.photo != null).map(m => (
<clipPath key={m.i} id={`st-bead-${el.id}-${m.i}`} clipPathUnits="userSpaceOnUse">
<circle cx={m.x} cy={m.y} r={beadR} />
</clipPath>
))}
</defs>
)}
{cutToLand && (
<defs>
<clipPath id={clipId} clipPathUnits="userSpaceOnUse">
@@ -443,8 +868,8 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
href={t.url}
x={round3(tiled.originX + t.x * tiled.size)}
y={round3(tiled.originY + t.y * tiled.size)}
width={round3(tiled.size + TILE_OVERLAP)}
height={round3(tiled.size + TILE_OVERLAP)}
width={round3(tiled.size + tileOverlapMm(tiled.size))}
height={round3(tiled.size + tileOverlapMm(tiled.size))}
preserveAspectRatio="none"
/>
))}
@@ -474,7 +899,7 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
/>
))}
{el.showRoute && lines.map((seg, i) => seg.length > 1 && (
{el.showRoute && !drawn && lines.map((seg, i) => seg.length > 1 && (
<polyline
key={i}
points={seg.map(p => `${round2(p.x)},${round2(p.y)}`).join(' ')}
@@ -486,7 +911,49 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
/>
))}
{el.showPins && route.map((p, i) => (
{/*
The drawn line: two strokes, casing first.
Not a filter. A drop shadow does survive the print round trip, but a
filtered subtree is rasterised into the PDF at whatever resolution the
browser picks, which is the one thing the millimetres-in-the-DOM design
exists to avoid. Two stacked paths give the same faint dark edge and
stay vector all the way to the press.
All the casings before any core, never leg by leg: interleaved, the
casing of one leg overprints the core of the last one at the joint.
*/}
{el.showRoute && drawn && strands.length > 0 && (
<>
{strands.map((strand, i) => (
<path
key={`c${i}`}
d={strand.d}
fill="none"
stroke={casingInk}
strokeOpacity={casingAlpha}
strokeWidth={casingW}
strokeLinecap={strand.dash ? 'butt' : 'round'}
strokeLinejoin="round"
strokeDasharray={strand.dash}
/>
))}
{strands.map((strand, i) => (
<path
key={`s${i}`}
d={strand.d}
fill="none"
stroke={coreInk}
strokeWidth={coreW}
strokeLinecap={strand.dash ? 'butt' : 'round'}
strokeLinejoin="round"
strokeDasharray={strand.dash}
/>
))}
</>
)}
{el.showPins && !drawn && route.map((p, i) => (
<circle
key={i}
cx={p.x}
@@ -500,6 +967,100 @@ function MapView({ el, frameStyle }: { el: BookMapElement; frameStyle: CSSProper
/>
))}
{/*
The drawn markers: a small round photograph where there is one, a dot
where there is not.
The dot is the designed state rather than a failure — a printed route
with a few plain marks between the pictures reads as a route, while
one with empty rings reads as a bug. The white disc under the picture
is also what a photograph that fails to load degrades to, so the paper
shows a deliberate marker rather than a hole.
*/}
{el.showPins && drawn && beads.map(m => (
m.photo != null ? (
<g key={m.i}>
{/* The shadow, as two translucent discs rather than a filter. */}
<circle cx={m.x} cy={m.y + coreW * 0.3} r={beadR + coreW * 0.55} fill="#000000" fillOpacity={0.1} />
<circle cx={m.x} cy={m.y + coreW * 0.15} r={beadR + coreW * 0.25} fill="#000000" fillOpacity={0.16} />
<circle cx={m.x} cy={m.y} r={beadR} fill="#ffffff" />
{/*
Always the thumbnail, never photoSrc(id, big): `big` is true in
print, and a full-size original to fill a seven-millimetre
circle is several megabytes per stop for detail no press can
resolve.
*/}
<image
href={`/api/photos/${m.photo}/thumbnail`}
x={round2(m.x - beadR)}
y={round2(m.y - beadR)}
width={round2(beadR * 2)}
height={round2(beadR * 2)}
preserveAspectRatio="xMidYMid slice"
clipPath={`url(#st-bead-${el.id}-${m.i})`}
/>
<circle
cx={m.x}
cy={m.y}
r={beadR - beadRing / 2}
fill="none"
stroke="#ffffff"
strokeWidth={beadRing}
/>
</g>
) : numbered ? (
/*
A stop with no photograph of its own, numbered.
The alternative was to hand it a picture from somewhere else in
the journey, which is what this did first and which is a caption
that lies: a marker at Akureyri showing a photograph taken in Vík
is wrong in the one place a reader most trusts that a picture is
OF what it sits on. A number says what the map actually knows —
this is the fourth stop — and reads as deliberate rather than as
something missing.
*/
<g key={m.i}>
<circle cx={m.x} cy={m.y + coreW * 0.2} r={numR + coreW * 0.35} fill="#000000" fillOpacity={0.14} />
<circle
cx={m.x}
cy={m.y}
r={numR}
fill={coreInk}
stroke={casingInk}
strokeOpacity={casingAlpha}
strokeWidth={coreW * 0.5}
/>
<text
x={m.x}
y={m.y + numR * 0.36}
textAnchor="middle"
fill={numInk}
style={{
fontFamily: fontStack(el.font),
fontSize: `${round2(numR * 1.15)}px`,
fontWeight: 700,
letterSpacing: '-0.02em',
fontVariantNumeric: 'tabular-nums',
}}
>
{m.i + 1}
</text>
</g>
) : (
<circle
key={m.i}
cx={m.x}
cy={m.y}
r={dotR}
fill={coreInk}
stroke={casingInk}
strokeOpacity={casingAlpha}
strokeWidth={dotR * 0.22}
/>
)
))}
{el.showLabels && points.map((p, i) => {
if (!p.label) return null
const at2 = route[i]
@@ -914,6 +1475,26 @@ function BadgeView({ el, frameStyle }: { el: BookBadgeElement; frameStyle: CSSPr
const chip = el.style === 'chip'
const outline = el.style === 'outline'
/*
* What the mark shows, and what colour its picture is.
*
* Read as `!== false` rather than as a truth test: a badge dropped from a
* panel is built by hand and cast, so it never passes through the contract's
* defaults until the book has been saved and read back. An absent flag has to
* mean what it meant before the flag existed.
*/
const showIcon = el.showIcon !== false
const showLabel = el.showLabel !== false
const iconTint = (automatic: string) => (el.autoIconColor === false ? el.iconColor : automatic)
/*
* A mark with no words is a pictogram, and a pictogram should fill its box.
* Beside a label the icon is a share of the height; on its own it takes four
* fifths of whichever side is shorter, so a wide mark grows into the space
* the words left and a narrow one stays inside its own edges rather than
* bleeding over them.
*/
const iconScale = showLabel ? 0.46 : Math.min(el.frame.w, el.frame.h) / el.frame.h * 0.8
return (
<div
style={{
@@ -937,7 +1518,9 @@ function BadgeView({ el, frameStyle }: { el: BookBadgeElement; frameStyle: CSSPr
overflow: 'hidden',
}}
>
{el.variant === 'flag' && el.code && <FlagMark code={el.code} size={el.frame.h * 0.5} />}
{el.variant === 'flag' && el.code && showIcon && (
<FlagMark code={el.code} size={el.frame.h * (showLabel ? 0.5 : iconScale)} />
)}
{/*
Mood and weather come from the journal entry, and they are drawn with
@@ -945,15 +1528,22 @@ function BadgeView({ el, frameStyle }: { el: BookBadgeElement; frameStyle: CSSPr
rather than re-listed, so a mood added to TREK appears here without
anyone remembering to add it twice.
*/}
{(el.variant === 'mood' || el.variant === 'weather') && el.code && (() => {
{(el.variant === 'mood' || el.variant === 'weather') && el.code && showIcon && (() => {
// Kept apart rather than narrowed out of one union: only a mood has a
// colour of its own, and `'text' in config` types it as unknown.
const mood = el.variant === 'mood' ? MOOD_CONFIG[el.code] : null
const config = mood ?? WEATHER_CONFIG[el.code]
if (!config) return null
const Icon = config.icon
const size = el.frame.h * 0.46
const tint = mood ? mood.text : el.accent
const size = el.frame.h * iconScale
/*
* Automatic is the journal's own palette for a mood and the element's
* accent for the weather. Note the colour has to be passed rather than
* inherited: lucide writes it onto the SVG's stroke, so `currentColor`
* from the wrapper never reaches it — which is why the Colour swatch
* appeared to do nothing to a mood icon.
*/
const tint = iconTint(mood ? mood.text : el.accent)
return (
<Icon
color={tint}
@@ -963,18 +1553,21 @@ function BadgeView({ el, frameStyle }: { el: BookBadgeElement; frameStyle: CSSPr
)
})()}
{el.variant === 'country' && shape && (
<svg
width={`${round2((el.frame.h * 0.72 * shape.w) / shape.h)}mm`}
height={`${round2(el.frame.h * 0.72)}mm`}
viewBox={`0 0 ${shape.w} ${shape.h}`}
style={{ display: 'block', flex: '0 0 auto' }}
>
<path d={shape.d} fill={el.accent} />
</svg>
)}
{el.variant === 'country' && shape && showIcon && (() => {
const h = el.frame.h * (showLabel ? 0.72 : iconScale)
return (
<svg
width={`${round2((h * shape.w) / shape.h)}mm`}
height={`${round2(h)}mm`}
viewBox={`0 0 ${shape.w} ${shape.h}`}
style={{ display: 'block', flex: '0 0 auto' }}
>
<path d={shape.d} fill={iconTint(el.accent)} />
</svg>
)
})()}
{el.text && (
{el.text && showLabel && (
<span
style={{
fontSize: `${round2(el.variant === 'coords' ? small * 1.3 : big)}mm`,
@@ -990,7 +1583,7 @@ function BadgeView({ el, frameStyle }: { el: BookBadgeElement; frameStyle: CSSPr
</span>
)}
{el.sub && (
{el.sub && showLabel && (
<span
style={{
fontSize: `${small}mm`,
+17 -5
View File
@@ -18,11 +18,23 @@ import { PAGE_MAX_MM, PAGE_MIN_MM } from './pagePresets'
* book, not the one they had.
*/
export function TrimField({
label, value, onCommit,
label, value, onCommit, min = PAGE_MIN_MM, max = PAGE_MAX_MM, step = 1,
}: {
label: string
value: number
onCommit: (mm: number) => void
/**
* The range this particular measurement lives in.
*
* Defaulted to the page's own, which is what the field was built for. The
* bleed and the safe margin are millimetres of the same kind and want the
* same field, but a floor of 60mm would make a 3mm bleed untypeable and its
* arrows useless — the range is a property of the measurement, not of the
* control.
*/
min?: number
max?: number
step?: number
}) {
const [draft, setDraft] = useState<string | null>(null)
const shown = draft ?? String(Math.round(value * 10) / 10)
@@ -41,16 +53,16 @@ export function TrimField({
type="number"
inputMode="decimal"
value={shown}
min={PAGE_MIN_MM}
max={PAGE_MAX_MM}
step={1}
min={min}
max={max}
step={step}
onChange={e => {
const raw = e.target.value
setDraft(raw)
// Anything already usable goes straight through, so the arrows and a
// fully typed number both take effect without waiting for a blur.
const n = Number(raw)
if (raw !== '' && Number.isFinite(n) && n >= PAGE_MIN_MM && n <= PAGE_MAX_MM) {
if (raw !== '' && Number.isFinite(n) && n >= min && n <= max) {
setDraft(null)
onCommit(n)
}
+22 -23
View File
@@ -1,5 +1,7 @@
import type { BookElement, BookPageSetup, BookSpread, JourneyStats } from '@trek/shared'
import type { SpreadTemplate } from './bookTemplates.data'
import { formatBookCoords, formatBookDate } from './entryText'
import { coordValue } from './resolveBindings'
/**
* Laying an entry out on a template somebody drew.
@@ -131,10 +133,27 @@ export function applyTemplate(
if (out.kind === 'text' && out.binding) {
const source = out.binding.source
const format = out.binding.format
// What the words were made from, where they were made rather than copied.
let value: string | undefined
if (source === 'entry.title') out.text = heading
else if (source === 'entry.story') out.text = story
else if (source === 'entry.date') out.text = formatDate(entry.date, ctx.locale)
out.binding = { ...out.binding, entryId: entry.id }
else if (source === 'entry.date') {
out.text = formatBookDate(entry.date, ctx.locale)
value = entry.date ?? undefined
}
// The place, as its name or as its point — see the `format` note in the
// contract. A stop the entry cannot answer keeps the words the template
// was drawn with, the same bargain fillBadge makes below.
else if (source === 'entry.location') {
if (format && entry.lat != null && entry.lng != null) {
out.text = formatBookCoords(entry.lat, entry.lng, format)
value = coordValue(entry.lat, entry.lng)
} else if (!format && entry.location) {
out.text = entry.location
}
}
out.binding = { ...out.binding, entryId: entry.id, ...(value ? { value } : {}) }
}
if (out.kind === 'photo' && out.photoId == null) {
@@ -188,7 +207,7 @@ function fillBadge(el: BookElement & { kind: 'badge' }, entry: TemplateEntry, ct
el.text = `${ctx.dayLabel} ${entry.dayNumber}`
}
if (el.variant === 'coords' && entry.lat != null && entry.lng != null) {
el.text = coords(entry.lat, entry.lng)
el.text = formatBookCoords(entry.lat, entry.lng)
}
if ((el.variant === 'flag' || el.variant === 'country') && entry.country) {
el.code = entry.country
@@ -215,24 +234,4 @@ function countryName(code: string, ctx: TemplateContext): string {
}
}
/** Degrees, minutes and seconds, the way a place page prints them. */
function coords(lat: number, lng: number): string {
const dms = (v: number, pos: string, neg: string) => {
const hemisphere = v >= 0 ? pos : neg
const abs = Math.abs(v)
const deg = Math.floor(abs)
const min = Math.floor((abs - deg) * 60)
const sec = Math.round((((abs - deg) * 60) - min) * 60)
return `${deg}° ${min}' ${sec}" ${hemisphere}`
}
return `${dms(lat, 'N', 'S')} ${dms(lng, 'E', 'W')}`
}
function formatDate(iso: string | null, locale: string): string {
if (!iso) return ''
const d = new Date(`${iso}T00:00:00`)
if (Number.isNaN(d.getTime())) return ''
return d.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric' })
}
const round2 = (n: number) => Math.round(n * 100) / 100
+72 -26
View File
@@ -3,6 +3,7 @@ import type {
} from '@trek/shared'
import { SPREAD_TEMPLATES } from './bookTemplates.data'
import { applyTemplate, templateFit } from './applyTemplate'
import { formatBookCoords, formatBookDate } from './entryText'
/**
* The auto mode: turn a journey into a book.
@@ -84,6 +85,16 @@ export interface AutoInput {
stationsLabel: string
/** The word before a day number on a chip — "DAY 5". Already translated. */
dayLabel: string
/**
* The real geometry of the route, when the journey has any.
*
* GPX and KML imports are the only thing in TREK that stores an actual path
* — every other route is a straight line between stops. The editor already
* fetches it for the Travel panel; an auto-laid-out book used to hard-code an
* empty array here and throw it away, which is why the one journey with a
* recorded track still printed a map drawn with a ruler.
*/
path?: [number, number][][]
/** "TRIP SUMMARY" over the figures. */
summaryLabel: string
/** "COUNTRIES" over the outlines. */
@@ -243,15 +254,24 @@ function mapEl(
showRoute: true,
showPins: true,
showLabels: false,
// The drawn line, for the same reason the panel places one: the contract
// stays plain so old books do not change, and new books look like a book.
routeStyle: 'drawn',
routeArc: 'bow',
routeDash: 'arcs',
pinStyle: 'photo',
countries: stats.countries.map(c => c.code),
points: stats.points.map(pt => ({ lat: pt.lat, lng: pt.lng, label: pt.label })),
points: stats.points.map(pt => ({
lat: pt.lat, lng: pt.lng, label: pt.label, photoId: pt.photoId ?? null,
})),
/*
* The fields the contract would default for a parsed element, spelled out
* because this one is cast. `path` in particular is read as an array while
* the map draws, so leaving it out is not a cosmetic difference.
*/
path: [],
fitPadding: 0.18,
roads: [],
fitPadding: 0.5,
fitToCountries: true,
clip: 'rect',
...opts,
@@ -300,6 +320,10 @@ function badgeEl(
// apply: left out, a mark reads as having been given a colour, and a chip
// draws its words in ink on an ink-coloured capsule.
autoColor: true,
showIcon: true,
showLabel: true,
autoIconColor: true,
iconColor: INK,
...opts,
} as BookElement
}
@@ -338,16 +362,8 @@ function coordsMark(
lng: number | null | undefined,
): BookElement | null {
if (lat == null || lng == null) return null
const dms = (v: number, positive: string, negative: string) => {
const hemisphere = v >= 0 ? positive : negative
const abs = Math.abs(v)
const deg = Math.floor(abs)
const min = Math.floor((abs - deg) * 60)
const sec = Math.round((((abs - deg) * 60) - min) * 60)
return `${deg}° ${min}' ${sec}" ${hemisphere}`
}
return badgeEl(frame, 'coords', {
text: `${dms(lat, 'N', 'S')} ${dms(lng, 'E', 'W')}`,
text: formatBookCoords(lat, lng),
}, { style: 'plain', textScale: 0.7 })
}
@@ -425,15 +441,22 @@ function placeMap(
id: uid('mp'),
kind: 'map',
frame,
points: [{ lat: entry.lat, lng: entry.lng, label: entry.location ?? '' }],
points: [{ lat: entry.lat, lng: entry.lng, label: entry.location ?? '', photoId: null }],
countries: entry.country ? [entry.country] : (stats?.countries.map(c => c.code) ?? []),
style: 'minimal',
source: 'vector',
tileUrl: '',
attribution: '',
zoom: 5,
// Deliberately the plain treatment: this is one dot on a country outline,
// and a bowed casing around a single stop would be decoration.
routeStyle: 'plain',
routeArc: 'straight',
routeDash: 'solid',
pinStyle: 'dot',
path: [],
fitPadding: 0.18,
roads: [],
fitPadding: 0.5,
/*
* This one is the "where in the world was this" mark beside an entry, so it
* wants the country whole with a dot in it — the opposite of the route map,
@@ -466,13 +489,6 @@ function dateMark(iso: string | null, locale: string, frame: { x: number; y: num
}, { style: 'stacked' })
}
function formatDate(iso: string | null, locale: string): string {
if (!iso) return ''
const d = new Date(iso + 'T00:00:00')
if (Number.isNaN(d.getTime())) return ''
return d.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric' })
}
/** A full-bleed frame: out past the trim on every side the page is cut on. */
function bleedFrame(page: BookPageSetup, spread: boolean) {
const w = spread ? page.pageWidth * 2 : page.pageWidth
@@ -569,11 +585,13 @@ function stationsSpread(entries: AutoEntry[], input: AutoInput, label: string):
const w = W - m * 2
column.forEach((entry, i) => {
const y = top + i * step
const date = formatDate(entry.date, input.locale)
const date = formatBookDate(entry.date, input.locale)
if (date) {
// Set in small caps, so the words on the page are not the words in the
// journal — and a bound element has to hold exactly its source or
// opening the book would quietly rewrite it. See resolveBindings.ts.
els.push(text({ x, y, w: w * 0.32, h: 5 }, date.toUpperCase(), {
size: 7, weight: 600, tracking: 0.1, color: '#a09a8e', // theme-lint-disable — book ink, not app chrome
binding: { source: 'entry.date', entryId: entry.id },
}))
}
const name = entry.title || entry.location || ''
@@ -699,16 +717,17 @@ function headingBlock(
const ink = opts.ink ?? '#141414' // theme-lint-disable — book ink, not app chrome
const muted = opts.muted ?? '#8a8578' // theme-lint-disable — book ink, not app chrome
const heading = entry.title || entry.location || ''
const meta = [formatDate(entry.date, input.locale), entry.location].filter(Boolean).join(' · ')
const meta = [formatBookDate(entry.date, input.locale), entry.location].filter(Boolean).join(' · ')
let cy = y
if (meta || heading) {
els.push(shape({ x, y: cy - 6, w: Math.min(14, w * 0.18), h: 0.5 }, ACCENT))
}
if (meta) {
// Two facts run together and upper-cased: neither the date nor the place as
// the journal holds them, so this line is not bound to either.
els.push(text({ x, y: cy, w, h: 5 }, meta.toUpperCase(), {
size: 7.5, weight: 600, tracking: 0.14, color: muted,
binding: { source: 'entry.date', entryId: entry.id },
}))
cy += 8
}
@@ -1290,7 +1309,9 @@ function summarySpread(input: AutoInput): BookSpread | null {
const els: BookElement[] = []
if (stats.points.length >= 2) {
els.push(mapEl({ x: m, y: m, w: W - m * 2, h: H - m * 2 }, stats))
// With the recorded track, when the journey has one: the editor fetches it
// and this was the line that threw it away.
els.push(mapEl({ x: m, y: m, w: W - m * 2, h: H - m * 2 }, stats, { path: input.path ?? [] }))
}
// Which figures are worth the space: everything the journey actually has.
@@ -1431,7 +1452,7 @@ function backSpread(input: AutoInput): BookSpread {
.filter((d): d is string => !!d)
.sort()
const span = dates.length
? [formatDate(dates[0], input.locale), formatDate(dates[dates.length - 1], input.locale)].filter(Boolean).join(' — ')
? [formatBookDate(dates[0], input.locale), formatBookDate(dates[dates.length - 1], input.locale)].filter(Boolean).join(' — ')
: ''
els.push(shape({ x: -page.bleed, y: -page.bleed, w: page.pageWidth + page.bleed * 2, h: page.pageHeight + page.bleed * 2 }, '#141414')) // theme-lint-disable — book ink, not app chrome
@@ -1535,6 +1556,31 @@ export function buildBook(input: AutoInput): BookDocument {
}
}
/**
* A book nobody has laid out yet.
*
* What a journey with no book now opens on. It used to open on the auto layout,
* which was generous and wrong: it decided what the book was before its author
* had said anything, and everything after that was undoing rather than making.
* The layout is still one click away, on the Auto layout menu, and it reads
* very differently when it is offered than when it has already happened.
*
* The covers are here rather than left out because a book has them and there is
* no other way to add one: the pages rail only inserts inner spreads, between
* the two. Empty, though, in the same way the page between them is.
*/
export function emptyBook(input: AutoInput): BookDocument {
const blank = (role: BookSpread['role']): BookSpread => ({
id: uid('sp'), role, background: null, elements: [], parked: [], entryId: null,
})
return {
version: 1,
title: input.title,
page: input.page,
spreads: [blank('cover'), blank('inner'), blank('back')],
}
}
/**
* Lay one spread out again, from the entry it came from.
*
@@ -46,7 +46,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
background: null,
elements: [
{
"id": "p-flxgo8u",
"id": "p-iy13loy",
"frame": {
"x": 0.0238,
"y": 0.0238,
@@ -59,15 +59,15 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"focalX": 0.572289143475242,
"focalY": 0.5726791042512355,
"radius": 0.0238,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "s-iqku6eo",
"id": "s-kafy6t4",
"frame": {
"x": 1.5898,
"y": 0.0238,
@@ -79,7 +79,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"locked": false,
"kind": "shape",
"shape": "rect",
"fill": "#11224f",
"fill": "#111111",
"gradient": "none",
"stroke": null,
"strokeWidth": 0,
@@ -87,7 +87,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"radius": 0
},
{
"id": "t-nszckjj",
"id": "t-v4jhfu6",
"frame": {
"x": 1.5898,
"y": 0.0563,
@@ -111,7 +111,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"overridden": true
},
{
"id": "t-6ntyuak",
"id": "t-nh804rp",
"frame": {
"x": 1.1136,
"y": 0.0563,
@@ -135,7 +135,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"overridden": true
},
{
"id": "s-v58hbqa",
"id": "s-8c3kwzk",
"frame": {
"x": 1.0812,
"y": 0.1757,
@@ -148,7 +148,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"font": "sans",
"color": "#1a1a1a",
"accent": "#111111",
"textScale": 1.2,
"textScale": 1.5,
"weight": 700,
"stale": false,
"kind": "stats",
@@ -167,18 +167,18 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"distance": 352677,
"days": 1,
"steps": 2,
"photos": 0,
"photos": 3,
"countries": 2,
"places": 0,
"furthest": 352677
}
},
{
"id": "b-u0di1u7",
"id": "b-15vswaz",
"frame": {
"x": 1.1768,
"y": 0.7603,
"w": 0.26,
"y": 0.7685,
"w": 0.2587,
"h": 0.066
},
"rotation": 0,
@@ -191,18 +191,22 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"weight": 700,
"stale": false,
"kind": "badge",
"autoColor": true,
"variant": "distance",
"text": "0 km",
"sub": "Distance",
"code": null,
"style": "chip"
"style": "chip",
"autoColor": true,
"showIcon": true,
"showLabel": true,
"autoIconColor": true,
"iconColor": "#111111"
},
{
"id": "c-roas8tw",
"id": "c-jdsxmvn",
"frame": {
"x": 1.628,
"y": 0.2397,
"y": 0.2315,
"w": 0.31,
"h": 0.537
},
@@ -239,7 +243,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
{
"id": "s-f7yltlr",
"frame": {
"x": -0.1277,
"x": -0.1264,
"y": 0.6775,
"w": 0.5595,
"h": 0.5973
@@ -249,7 +253,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"locked": false,
"kind": "shape",
"shape": "flower-5",
"fill": "#11254c",
"fill": "#111111",
"gradient": "none",
"stroke": null,
"strokeWidth": 0,
@@ -269,7 +273,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"locked": false,
"kind": "shape",
"shape": "rect",
"fill": "#11224f",
"fill": "#111111",
"gradient": "none",
"stroke": "#11224f",
"strokeWidth": 0.0024,
@@ -288,10 +292,10 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"photoId": 69,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"focalX": 0.42168673729754674,
"focalY": 0.23833399057977409,
"radius": 0,
"filter": "none",
"mask": null,
@@ -309,7 +313,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"opacity": 1,
"locked": false,
"kind": "text",
"text": "TEST1",
"text": "Lorem ipsum dolor sit amet",
"font": "sans",
"size": 0.1048,
"weight": 700,
@@ -443,7 +447,7 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"photoId": 68,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
@@ -464,40 +468,15 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"photoId": 69,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"mask": "heart",
"frameStyle": "polaroid"
},
{
"id": "b-ga9zv0w",
"frame": {
"x": 0.0399,
"y": 0.041,
"w": 0.17,
"h": 0.062
},
"rotation": 0,
"opacity": 1,
"locked": false,
"font": "sans",
"color": "#1a1a1a",
"accent": "#111111",
"textScale": 1,
"weight": 700,
"stale": false,
"kind": "badge",
"autoColor": true,
"variant": "day",
"text": "DAY 1",
"sub": "",
"code": null,
"style": "chip"
},
{
"id": "b-gmtenyt",
"frame": {
@@ -516,12 +495,16 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"weight": 700,
"stale": false,
"kind": "badge",
"autoColor": true,
"variant": "coords",
"text": "51°10'N 10°27'E",
"sub": "",
"code": null,
"style": "plain"
"style": "plain",
"autoColor": true,
"showIcon": true,
"showLabel": true,
"autoIconColor": true,
"iconColor": "#111111"
},
{
"id": "b-4rd95kg",
@@ -541,12 +524,755 @@ export const SPREAD_TEMPLATES: SpreadTemplate[] = [
"weight": 700,
"stale": false,
"kind": "badge",
"autoColor": true,
"variant": "coords",
"text": "51°10'N 10°27'E",
"sub": "",
"code": null,
"style": "plain"
"style": "plain",
"autoColor": true,
"showIcon": true,
"showLabel": true,
"autoIconColor": true,
"iconColor": "#111111"
}
],
},
{
id: 'ref-3',
background: null,
elements: [
{
"id": "p-sa5cabi",
"frame": {
"x": 0.025,
"y": 0.025,
"w": 1.9512,
"h": 0.5919
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "t-kws7inb",
"frame": {
"x": 0.054,
"y": 0.688,
"w": 0.8919,
"h": 0.2294
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet",
"font": "sans",
"size": 0.2381,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.title",
"entryId": 62
},
"overridden": false
},
{
"id": "t-1zzydde",
"frame": {
"x": 1.0808,
"y": 0.6542,
"w": 0.8385,
"h": 0.1917
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
"font": "sans",
"size": 0.0476,
"weight": 400,
"italic": false,
"align": "left",
"leading": 1.55,
"tracking": 0,
"color": "#1a1a1a",
"binding": {
"source": "entry.story",
"entryId": 62
},
"overridden": false
},
{
"id": "t-kht4sfu",
"frame": {
"x": 0.054,
"y": 0.6542,
"w": 0.36,
"h": 0.0314
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "August 19, 2026",
"font": "sans",
"size": 0.0762,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.date",
"entryId": 62,
"value": "2026-08-19"
},
"overridden": false
}
],
},
{
id: 'ref-4',
background: null,
elements: [
{
"id": "s-19c5q0x",
"frame": {
"x": -0.1119,
"y": 0.4164,
"w": 0.7143,
"h": 0.7143
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "shape",
"shape": "ellipse",
"fill": "#141414",
"gradient": "none",
"stroke": null,
"strokeWidth": 0,
"strokeStyle": "solid",
"radius": 0
},
{
"id": "p-e8ee9j8",
"frame": {
"x": 0.0816,
"y": 0.0763,
"w": 0.3367,
"h": 0.3827
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "polaroid"
},
{
"id": "p-fimcc5x",
"frame": {
"x": 0.5662,
"y": 0.202,
"w": 0.3367,
"h": 0.3827
},
"rotation": -10.1,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "polaroid"
},
{
"id": "p-nva57q1",
"frame": {
"x": 0.1739,
"y": 0.5,
"w": 0.3367,
"h": 0.3827
},
"rotation": 5.1,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": "seal",
"frameStyle": "polaroid"
},
{
"id": "t-7zfrwms",
"frame": {
"x": 1.0762,
"y": 0.1605,
"w": 0.8476,
"h": 0.0895
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet",
"font": "sans",
"size": 0.1429,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.title",
"entryId": 63
},
"overridden": false
},
{
"id": "t-culm58m",
"frame": {
"x": 1.0762,
"y": 0.2676,
"w": 0.8476,
"h": 0.2073
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
"font": "sans",
"size": 0.0476,
"weight": 400,
"italic": false,
"align": "left",
"leading": 1.55,
"tracking": 0,
"color": "#1a1a1a",
"binding": {
"source": "entry.story",
"entryId": 62
},
"overridden": false
},
{
"id": "li-dukbgme",
"frame": {
"x": 1.0762,
"y": 0.5116,
"w": 0.72,
"h": 0.0731
},
"rotation": 0,
"opacity": 1,
"locked": false,
"font": "sans",
"color": "#1a1a1a",
"accent": "#c2410c",
"textScale": 1,
"weight": 700,
"stale": false,
"kind": "list",
"items": [
{
"text": "TEST1",
"tone": "pro"
},
{
"text": "TEST1",
"tone": "con"
}
],
"layout": "columns",
"showMarks": true,
"proLabel": "Pros",
"conLabel": "Cons"
},
{
"id": "t-x3ysuxa",
"frame": {
"x": 1.0762,
"y": 0.116,
"w": 0.36,
"h": 0.0314
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "August 19, 2026",
"font": "sans",
"size": 0.069,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.date",
"entryId": 62,
"value": "2026-08-19"
},
"overridden": false
}
],
},
{
id: 'ref-5',
background: null,
elements: [
{
"id": "p-adrg53f",
"frame": {
"x": 0.025,
"y": 0.025,
"w": 0.475,
"h": 0.9512
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "t-crm4sem",
"frame": {
"x": 0.5297,
"y": 0.119,
"w": 0.4258,
"h": 0.8012
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet",
"font": "sans",
"size": 0.2381,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.title",
"entryId": 62
},
"overridden": false
},
{
"id": "s-3dhohc7",
"frame": {
"x": 1.0762,
"y": 0.3541,
"w": 0.5,
"h": 0.0024
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "shape",
"shape": "rect",
"fill": "#f2f2f2",
"gradient": "none",
"stroke": "#141414",
"strokeWidth": 0.0005,
"strokeStyle": "solid",
"radius": 0
},
{
"id": "t-0l6zeg7",
"frame": {
"x": 1.0762,
"y": 0.119,
"w": 0.8346,
"h": 0.2047
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
"font": "sans",
"size": 0.0476,
"weight": 400,
"italic": false,
"align": "left",
"leading": 1.55,
"tracking": 0,
"color": "#1a1a1a",
"binding": {
"source": "entry.story",
"entryId": 62
},
"overridden": false
},
{
"id": "p-igt1irs",
"frame": {
"x": 1.0762,
"y": 0.4469,
"w": 0.368,
"h": 0.2495
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "shadow"
},
{
"id": "p-2akhm3w",
"frame": {
"x": 1.5105,
"y": 0.4469,
"w": 0.368,
"h": 0.2495
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "shadow"
},
{
"id": "bd-g6o9fvm",
"frame": {
"x": 0.53,
"y": 0.4577,
"w": 0.2604,
"h": 0.062
},
"rotation": 0,
"opacity": 1,
"locked": false,
"font": "sans",
"color": "#1a1a1a",
"accent": "#111111",
"textScale": 1,
"weight": 700,
"stale": false,
"kind": "badge",
"variant": "weather",
"text": "Partly cloudy",
"sub": "",
"code": "partly",
"style": "chip",
"autoColor": true,
"showIcon": true,
"showLabel": true,
"autoIconColor": false,
"iconColor": "#ffffff"
},
{
"id": "bd-ewxvw6v",
"frame": {
"x": 0.53,
"y": 0.5406,
"w": 0.2607,
"h": 0.062
},
"rotation": 0,
"opacity": 1,
"locked": false,
"font": "sans",
"color": "#1a1a1a",
"accent": "#111111",
"textScale": 1,
"weight": 700,
"stale": false,
"kind": "badge",
"variant": "mood",
"text": "Amazing",
"sub": "",
"code": "amazing",
"style": "chip",
"autoColor": true,
"showIcon": true,
"showLabel": true,
"autoIconColor": false,
"iconColor": "#ffffff"
},
{
"id": "t-az8f0nc",
"frame": {
"x": 0.5297,
"y": 0.0858,
"w": 0.36,
"h": 0.0347
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "August 19, 2026",
"font": "sans",
"size": 0.0714,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.date",
"entryId": 62,
"value": "2026-08-19"
},
"overridden": false
}
],
},
{
id: 'ref-6',
background: null,
elements: [
{
"id": "s-7go39mg",
"frame": {
"x": 0.0238,
"y": 0.309,
"w": 0.9524,
"h": 0.666
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "shape",
"shape": "triangle",
"fill": "#141414",
"gradient": "none",
"stroke": null,
"strokeWidth": 0,
"strokeStyle": "solid",
"radius": 0
},
{
"id": "p-a9065nh",
"frame": {
"x": 0.0238,
"y": 0.0238,
"w": 0.2745,
"h": 0.9512
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "p-fvcm5kq",
"frame": {
"x": 0.3628,
"y": 0.0914,
"w": 0.2745,
"h": 0.8848
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "p-aski19e",
"frame": {
"x": 0.7017,
"y": 0.0238,
"w": 0.2745,
"h": 0.9512
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "p-tfs5cdi",
"frame": {
"x": 1.0238,
"y": 0.0238,
"w": 0.9524,
"h": 0.45
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "photo",
"photoId": null,
"fit": "cover",
"focalX": 0.5,
"focalY": 0.5,
"radius": 0,
"filter": "none",
"mask": null,
"frameStyle": "none"
},
{
"id": "t-9zjrvsn",
"frame": {
"x": 1.0592,
"y": 0.5,
"w": 0.8476,
"h": 0.0518
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet",
"font": "sans",
"size": 0.1048,
"weight": 700,
"italic": false,
"align": "left",
"leading": 1.1,
"tracking": -0.02,
"color": "#1a1a1a",
"binding": {
"source": "entry.title",
"entryId": 62
},
"overridden": false
},
{
"id": "t-4lgyrab",
"frame": {
"x": 1.0592,
"y": 0.5682,
"w": 0.8476,
"h": 0.1995
},
"rotation": 0,
"opacity": 1,
"locked": false,
"kind": "text",
"text": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
"font": "sans",
"size": 0.0476,
"weight": 400,
"italic": false,
"align": "left",
"leading": 1.55,
"tracking": 0,
"color": "#1a1a1a",
"binding": {
"source": "entry.story",
"entryId": 62
},
"overridden": false
},
{
"id": "li-93gcznw",
"frame": {
"x": 1.0592,
"y": 0.7876,
"w": 0.72,
"h": 0.0731
},
"rotation": 0,
"opacity": 1,
"locked": false,
"font": "sans",
"color": "#1a1a1a",
"accent": "#c2410c",
"textScale": 1,
"weight": 700,
"stale": false,
"kind": "list",
"items": [
{
"text": "TEST1",
"tone": "pro"
},
{
"text": "TEST1",
"tone": "con"
}
],
"layout": "columns",
"showMarks": true,
"proLabel": "Pros",
"conLabel": "Cons"
}
],
},
+63
View File
@@ -0,0 +1,63 @@
/**
* The words a journal entry lends to a page.
*
* Three things print an entry's date or its point: the chips in the Entries
* tab, the template filler, and the auto layout. They used to do it with five
* private helpers between them — two long-date formatters that were copies of
* each other, and three coordinate formatters, one of which printed degrees and
* minutes where the other two printed seconds. A journey-wide mark and an entry
* mark on the same spread read as a bug when they disagree by a notation.
*
* There is a second, harder reason for one implementation. A bound element is
* re-read when the book is opened (see resolveBindings.ts), and re-reading is
* only invisible while the resolver produces exactly the string the chip
* produced. One character of drift and every open rewrites the element, which
* the autosave then writes back — a book that saves itself every time someone
* looks at it. Sharing the function is what holds that invariant.
*/
export type CoordFormat = 'dms' | 'decimal'
/** One axis, as degrees, minutes and seconds. */
function dms(v: number, pos: string, neg: string): string {
const hemisphere = v >= 0 ? pos : neg
const abs = Math.abs(v)
const deg = Math.floor(abs)
const min = Math.floor((abs - deg) * 60)
const sec = Math.round((((abs - deg) * 60) - min) * 60)
return `${deg}° ${min}' ${sec}" ${hemisphere}`
}
/**
* A point, set for print.
*
* Neither form carries a minus sign: a printed page says 33° 51' S, not
* -33.8688, and the hemisphere letter is both shorter and unambiguous. Decimal
* keeps four places — about eleven metres, which is the width of the building
* you were standing next to and finer than a book needs.
*/
export function formatBookCoords(lat: number, lng: number, format: CoordFormat = 'dms'): string {
if (format === 'decimal') {
const dec = (v: number, pos: string, neg: string) =>
`${Math.abs(v).toFixed(4)}° ${v >= 0 ? pos : neg}`
return `${dec(lat, 'N', 'S')} ${dec(lng, 'E', 'W')}`
}
return `${dms(lat, 'N', 'S')} ${dms(lng, 'E', 'W')}`
}
/**
* The entry's day, spelled out.
*
* Parsed at local midnight rather than as UTC, because the date on a journal
* entry is the day the writer had, not an instant — reading it as UTC moves it
* a day backwards for anyone west of Greenwich. Note this is deliberately not
* `utils/formatters.ts:formatDate`, which is the short weekday form the sidebar
* badges use and hides the year inside the current one; a page in a book that
* outlives the year has to say which year it was.
*/
export function formatBookDate(iso: string | null, locale: string): string {
if (!iso) return ''
const d = new Date(`${iso}T00:00:00`)
if (Number.isNaN(d.getTime())) return ''
return d.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric' })
}
+118
View File
@@ -0,0 +1,118 @@
import * as LucideIcons from 'lucide-react'
import { resolvePluginIcon } from '../shared/PluginIcon'
import type { LucideIcon } from 'lucide-react'
/**
* Every drawing in lucide, as a list a picker can show.
*
* ── Why the whole set, and why it costs nothing ──────────────────────────
*
* The obvious worry with a fourteen-hundred-icon library is the bundle, and it
* is worth being precise about why it does not apply. TREK already pulls lucide
* in whole: `SystemNoticeModal` and `PluginIcon` both index the namespace with a
* computed key, which no bundler can tree-shake, and both sit in the eager entry
* graph. The library ships either way, so enumerating it here adds names, not
* kilobytes — and it avoids the alternative, which would be fourteen hundred
* lazily-imported chunks that the export path could not wait for. Studio prints
* by serialising the live DOM in one synchronous pass; an icon that had not
* finished loading would print as a hole in the book.
*
* ── The alias problem ────────────────────────────────────────────────────
*
* lucide exports every icon three times — `Plane`, `PlaneIcon`, `LucidePlane` —
* so the namespace holds about forty-five hundred names for about fourteen
* hundred drawings. A picker built from the raw keys shows every glyph three
* times, and the search box then looks broken. Both alias shapes are dropped.
*/
const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/
function buildNames(): string[] {
const all = LucideIcons as unknown as Record<string, unknown>
const names = Object.keys(all).filter(k => PASCAL_CASE.test(k))
const present = new Set(names)
return names
.filter(name => {
// `LucidePlane` is always an alias of `Plane`.
if (name.startsWith('Lucide') && present.has(name.slice(6))) return false
// `PlaneIcon` likewise — but only when the bare name really exists, so a
// drawing genuinely called something-Icon is not thrown away with them.
if (name.endsWith('Icon') && present.has(name.slice(0, -4))) return false
return true
})
.sort((a, b) => a.localeCompare(b))
}
/** Built once: the namespace cannot change while the tab is open. */
export const ICON_NAMES: string[] = buildNames()
/**
* What the tab opens on.
*
* Alphabetical order puts `AArrowDown`, `AArrowUp` and `ALargeSmall` in the
* first row, which is a poor answer to "what can I put on this page" in a book
* about a journey. These are the drawings a travel page actually reaches for,
* in the order somebody would look for them; the whole library is underneath.
*
* Filtered against the real export list, so a lucide version that renames one
* of them quietly drops it instead of drawing a fallback in the shelf.
*/
const FEATURED = [
'Plane', 'Train', 'TrainFront', 'Car', 'Bus', 'Ship', 'Bike', 'Footprints', 'Sailboat',
'MapPin', 'Map', 'Compass', 'Navigation', 'Route', 'Globe', 'Milestone', 'Signpost',
'Mountain', 'MountainSnow', 'Waves', 'TreePine', 'Palmtree', 'Flower2', 'Leaf', 'Bird', 'Fish',
'Sun', 'Sunrise', 'Sunset', 'Moon', 'Cloud', 'CloudRain', 'CloudLightning', 'Snowflake',
'Umbrella', 'Thermometer', 'Wind',
'Tent', 'Backpack', 'Luggage', 'BedDouble', 'Hotel', 'Key', 'Anchor',
'Coffee', 'UtensilsCrossed', 'Wine', 'Beer', 'IceCream', 'Croissant',
'Camera', 'Image', 'Film', 'Music', 'BookOpen', 'PenLine', 'Quote', 'Sticker',
'Heart', 'Star', 'Sparkles', 'Flag', 'Ticket', 'Gift', 'PartyPopper',
'Clock', 'CalendarDays', 'CreditCard', 'Wallet', 'ShoppingBag',
'Landmark', 'Church', 'Castle', 'Building2', 'Home', 'Binoculars', 'Telescope',
]
/** The starter shelf, minus anything this version of lucide does not have. */
export const FEATURED_ICONS: string[] = FEATURED.filter(name => ICON_NAMES.includes(name))
/**
* The words to match a search against.
*
* "mountainsnow" for MountainSnow as well as its parts, so both "mountain" and
* "snow" find it — searching an icon set is searching for a thing, and the
* thing's name is rarely the first word someone types.
*/
function searchable(name: string): string {
return `${name} ${name.replace(/([a-z0-9])([A-Z])/g, '$1 $2')}`.toLowerCase()
}
const SEARCH_INDEX: Record<string, string> = Object.fromEntries(
ICON_NAMES.map(name => [name, searchable(name)]),
)
export function searchIcons(query: string): string[] {
const q = query.trim().toLowerCase()
if (!q) return ICON_NAMES
// Every word has to appear, so "snow mountain" finds MountainSnow too.
const words = q.split(/\s+/)
return ICON_NAMES.filter(name => {
const haystack = SEARCH_INDEX[name]
return words.every(w => haystack.includes(w))
})
}
/** Spaced out for a tooltip: `MountainSnow` reads as "Mountain Snow". */
export function iconLabel(name: string): string {
return name.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
}
/**
* The component for a stored name.
*
* The same resolver the plugin system uses, so a book that outlives an icon
* behaves the way the rest of TREK does with a name it no longer knows: it
* draws the fallback rather than leaving a hole where a drawing was.
*/
export function iconComponent(name: string): LucideIcon {
return resolvePluginIcon(name)
}
+142 -25
View File
@@ -1,7 +1,5 @@
import type { BookFrame } from '@trek/shared'
import { useSettingsStore } from '../../store/settingsStore'
import { attributionFor, staticMapUrl } from './mapTiles'
import { normalizeTileUrl } from '../../utils/tileUrl'
import { attributionFor } from './mapTiles'
/**
* Which map sources this instance can actually offer.
@@ -17,7 +15,18 @@ import { normalizeTileUrl } from '../../utils/tileUrl'
*/
export interface MapSourceOption {
id: 'vector' | 'tiles' | 'static'
/**
* What this option is called in the panel.
*
* Not the same thing as `source`: relief and the instance's own tiles are
* both raster grids and the renderer draws them identically, so they share a
* `source` and differ only in where the pictures come from. Widening the
* contract's enum to tell them apart would mean a document an older build
* cannot read, for a distinction only the panel cares about.
*/
id: 'vector' | 'tiles' | 'static' | 'relief' | 'satellite'
/** What goes into the document. */
source: 'vector' | 'tiles' | 'static'
/** i18n key for the name. */
labelKey: string
/** The tile template or static URL to freeze into the element. */
@@ -25,37 +34,145 @@ export interface MapSourceOption {
attribution: string
}
/** The default tile template, when the instance has not set its own. */
const DEFAULT_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
/** Which option a placed element came from, matched back by what it stored. */
export function sourceIdOf(el: { source: string; tileUrl: string }, options: MapSourceOption[]): string {
const exact = options.find(o => o.source === el.source && o.url === el.tileUrl)
return exact?.id ?? el.source
}
export function useMapSources(frame: BookFrame, points: { lat: number; lng: number }[]): MapSourceOption[] {
const settings = useSettingsStore(s => s.settings)
/**
* NASA's shaded relief, and why it is the one worth printing.
*
* ── What it looks like ───────────────────────────────────────────────────
*
* Land in its own colours with the terrain shaded into it, sea rendered dark
* with the depth showing through, and no roads, no borders and no labels. It
* is the look printed travel books have used for decades, and it is the one
* the street map underneath a planner can never be: a street map is a working
* document, and enlarged onto a page it reads as a screenshot.
*
* ── Why this source rather than a better-known one ───────────────────────
*
* Because a book gets printed, and possibly sold. Mapbox's own documentation
* says to contact them before printing an exported map; Esri's imagery is
* licensed for use with ArcGIS and not for commercial work; the OSM tile
* server's policy forbids bulk fetching, which is what covering a page at
* print resolution is. This is US government imagery: the service's own
* capabilities document answers both questions in two lines, `<ows:Fees>none`
* and `<ows:AccessConstraints>none`, and no account or token exists to get
* wrong.
*
* ── Its one limit, stated rather than discovered ─────────────────────────
*
* Level 8, about 600 metres to the pixel. A journey across a country or a
* continent is exactly what it is for; a weekend inside one city is not, and
* for that the instance's own tiles are still the better answer.
*
* Note the path is `{z}/{y}/{x}` — WMTS names its axes row then column, the
* reverse of the slippy convention. The substitution is by name, so the order
* in the template is all that matters.
*/
const RELIEF_TILES = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best'
+ '/BlueMarble_ShadedRelief_Bathymetry/default/GoogleMapsCompatible_Level8'
+ '/{z}/{y}/{x}.jpeg'
/**
* Real satellite imagery, and the answer to what relief cannot do.
*
* Relief stops at about 600 metres to the pixel, which is a continent's worth
* of detail: it draws Europe beautifully and a fortnight in the Netherlands as
* a green smudge. This is the same picture at ten metres — cloud-free Sentinel-2,
* composited by EOX from a year of passes, so there is no weather in the way and
* no seams between scenes.
*
* ── Why the 2016 layer specifically ──────────────────────────────────────
*
* EOX publish a layer per year, and only this one is usable in a book somebody
* might sell: the service's own capabilities document releases it under CC BY
* 4.0, while 2018 onwards are CC BY-NC-SA, which rules out a printed product.
* The imagery being a decade old costs nothing here — a coastline, a mountain
* range and a desert do not move, and the map is a backdrop for a route rather
* than a survey.
*
* Attribution is not optional under that licence, which is why it travels into
* the document with the source.
*/
const SATELLITE_TILES = 'https://tiles.maps.eox.at/wmts/1.0.0'
+ '/s2cloudless_3857/default/g/{z}/{y}/{x}.jpg'
/**
* What a book may be made of.
*
* ── Why the planner's own tiles are not on this list ─────────────────────
*
* They are a street map, and a street map enlarged onto a page reads as a
* screenshot of a working document rather than as an illustration — which is
* the whole difference between the reference books and what this drew before.
* Worse, covering a page at print resolution means fetching a few hundred tiles
* at once, and the OSM tile server's usage policy names exactly that as
* something not to do. Mapbox is off the list for a different reason: its own
* documentation says to contact them before printing an exported map, so it
* cannot be offered as a thing to put in a book somebody might sell.
*
* What is left is the three that are honestly printable: outlines drawn from
* boundaries this server already ships, NASA's relief, and Sentinel-2.
*
* ── But a book that already uses one keeps working ───────────────────────
*
* Removing an option must not remove a page. An element placed with the
* instance's tiles or with Mapbox still renders exactly as it did, and its own
* source is added back to the list below so the panel can show it as the chosen
* one — otherwise the map would draw correctly while the panel claimed it was
* something else, and one stray click would silently convert it.
*/
export function useMapSources(
frame: BookFrame,
points: { lat: number; lng: number }[],
/** What the element being inspected already uses, so it stays reachable. */
current?: { source: string; tileUrl: string },
): MapSourceOption[] {
// Through the same normaliser the planner's map uses: a template saved
// before OSM dropped its shards still names a host that no longer exists.
const tiles = normalizeTileUrl((settings.map_tile_url || '').trim()) || DEFAULT_TILES
const out: MapSourceOption[] = [
{ id: 'vector', labelKey: 'journey.studio.mapSourceVector', url: '', attribution: '' },
{ id: 'tiles', labelKey: 'journey.studio.mapSourceTiles', url: tiles, attribution: attributionFor(tiles) },
{ id: 'vector', source: 'vector', labelKey: 'journey.studio.mapSourceVector', url: '', attribution: '' },
{
id: 'relief',
source: 'tiles',
labelKey: 'journey.studio.mapSourceRelief',
url: RELIEF_TILES,
attribution: attributionFor(RELIEF_TILES),
},
{
id: 'satellite',
source: 'tiles',
labelKey: 'journey.studio.mapSourceSatellite',
url: SATELLITE_TILES,
attribution: attributionFor(SATELLITE_TILES),
},
]
// Millimetres to pixels at roughly 200dpi — enough for print without asking
// the API for more than it will give.
const token = (settings.mapbox_access_token || '').trim()
if (token) {
const url = staticMapUrl({
points,
style: settings.mapbox_style || '',
token,
width: frame.w * 7.9,
height: frame.h * 7.9,
})
if (url) {
/*
* The one the element is already on, when it is not one of the three above.
* Listed last, so the recommended sources read as the answer and this reads
* as what happens to be in place.
*/
if (current && !out.some(o => o.source === current.source && o.url === current.tileUrl)) {
if (current.source === 'tiles' && current.tileUrl) {
out.push({
id: 'tiles',
source: 'tiles',
labelKey: 'journey.studio.mapSourceTiles',
url: current.tileUrl,
attribution: attributionFor(current.tileUrl),
})
}
if (current.source === 'static' && current.tileUrl) {
out.push({
id: 'static',
source: 'static',
labelKey: 'journey.studio.mapSourceStatic',
url,
attribution: attributionFor(url),
url: current.tileUrl,
attribution: attributionFor(current.tileUrl),
})
}
}
+132 -6
View File
@@ -68,12 +68,78 @@ export function projectOntoTiles(view: TileView, lng: number, lat: number): { x:
}
}
/** How many tiles across a printed map may use, before it is not worth it. */
const MAX_TILES = 8 * 8
/**
* How many tiles a printed map may use.
*
* Sixteen across rather than eight, and the number is chosen by arithmetic
* rather than by taste. Each zoom level quarters the ground a tile covers, so
* the grid quadruples: a page-sized map lands at 7x9 tiles, and the step that
* would make it sharp enough to print needs 13x17 — 221. A budget of 144 stops
* one level short of a printable page, every time, which is the worst place to
* stop.
*
* What it costs is requests, once, cached by the browser between the editor
* and the print run. What it buys is the element most likely to fill a whole
* page, at a resolution a print shop will take.
*/
const MAX_TILES = 16 * 16
/**
* What a thumbnail is worth fetching.
*
* The same map is drawn in three places at three sizes: the page, the sheet the
* press gets, and a 130px tile in the pages rail or the travel panel. Cutting
* the small ones to print resolution would mean a couple of hundred requests
* for a picture the size of a postage stamp, every time the panel opens — and
* against NASA or OpenStreetMap that is not merely wasteful, it is the bulk
* fetching their policies ask people not to do.
*
* `big` already travels down the render tree for exactly this kind of decision;
* the photo views use it to pick a thumbnail over a full-size image.
*/
const PREVIEW_TILES = 4 * 4
const PREVIEW_TILE_MM = 90
/**
* What a tile is worth drawing at, in millimetres.
*
* ── The bug this constant exists to fix ──────────────────────────────────
*
* The zoom used to be chosen so the route spanned the frame and nothing else,
* which by construction put about two tiles across the picture whatever its
* physical size. A route across Iceland on a 210mm page came back as 256x512
* pixels stretched over the sheet: seventeen dots per inch, on paper that
* holds three hundred. It looked exactly like what it was — a screenshot of a
* web map, enlarged.
*
* A tile is 256 pixels, or 512 when the source offers `{r}`. Holding one to
* about 22mm therefore asks for roughly 300dpi, which is what a print shop
* wants and the point past which more tiles buy nothing a reader can see.
*/
const TILE_MM_AT_PRINT = 22
/** Shard letters for templates that still carry `{s}`. */
const TILE_SHARDS = ['a', 'b', 'c']
/**
* How far in a source can actually be asked to go.
*
* Matched on the host, the same way the attribution is: a template carries no
* capabilities of its own, and asking a source for a zoom it does not have
* answers with an error image rather than with a picture. NASA's imagery stops
* at 8, which is about 600 metres to the pixel — plenty for a country and not
* enough for a city, which is the honest limit of that source.
*/
export function maxZoomFor(template: string): number {
const url = template.toLowerCase()
if (url.includes('gibs.earthdata.nasa.gov')) return 8
// Sentinel-2 is a ten-metre sensor; past 16 the tiles are enlargements of
// pixels rather than more picture.
if (url.includes('tiles.maps.eox.at')) return 16
if (url.includes('arcgisonline')) return 17
return 19
}
/**
* Which tiles cover a set of points, and where to draw them.
*
@@ -97,6 +163,11 @@ export function tileView(
* wrong towns.
*/
extent?: { minLng: number; minLat: number; maxLng: number; maxLat: number },
/**
* How much this drawing is worth. `preview` is a thumbnail: a handful of
* tiles, deliberately soft, because nobody prints the pages rail.
*/
quality: 'print' | 'preview' = 'print',
): TileView | null {
if (!template || (!points.length && !extent)) return null
@@ -178,10 +249,38 @@ export function tileView(
y1 = Math.ceil(cy * scale + halfH) - 1
}
// Back off until the grid is a size worth printing. A 12x12 grid is 144
// requests for a picture 60mm across.
layOut()
while (zoom > 0 && (x1 - x0 + 1) * (y1 - y0 + 1) > MAX_TILES) {
/*
* Up, then down.
*
* Up first: while a tile is being drawn larger than it is worth, and the
* source has a level left, and the extra level still fits inside the grid
* budget, take it. Each level halves the millimetres a tile covers, so this
* converges in a handful of steps.
*
* Then the old back-off, unchanged, because a fixed zoom or a very long
* route can still ask for more tiles than are worth fetching.
*/
const budget = quality === 'preview' ? PREVIEW_TILES : MAX_TILES
const targetTileMm = quality === 'preview' ? PREVIEW_TILE_MM : TILE_MM_AT_PRINT
const ceiling = fixedZoom ?? maxZoomFor(template)
while (zoom < ceiling && size > targetTileMm) {
const before = { zoom, size, x0, x1, y0, y1 }
zoom += 1
layOut()
if ((x1 - x0 + 1) * (y1 - y0 + 1) > budget) {
// One level too far: put it back rather than leaving the grid over budget.
zoom = before.zoom
size = before.size
x0 = before.x0; x1 = before.x1; y0 = before.y0; y1 = before.y1
scale = 2 ** zoom
break
}
}
while (zoom > 0 && (x1 - x0 + 1) * (y1 - y0 + 1) > budget) {
zoom -= 1
layOut()
}
@@ -205,7 +304,13 @@ export function tileView(
// Longitude wraps, so a route across the antimeridian keeps its tiles.
.replace('{x}', String(wrap(x)))
.replace('{y}', String(y))
.replace('{r}', '')
/*
* `{r}` is the retina placeholder, and a template only carries it
* when its source really serves 512px tiles. It used to be replaced
* with nothing, which threw that away and asked for a quarter of the
* pixels for the same number of requests.
*/
.replace('{r}', '@2x')
/*
* The shard letter, chosen from the tile's own coordinates.
*
@@ -224,6 +329,24 @@ export function tileView(
return { tiles, originX, originY, size, zoom, tileX0: x0, tileY0: y0 }
}
/**
* How sharp this grid will actually print, in dots per inch.
*
* Worth showing rather than hiding. Every raster source has a level past which
* no more detail exists — NASA's relief stops at about 600 metres to the pixel
* — and when a map is asked for a smaller area than its source can resolve,
* the picture does not fail, it just goes soft. On screen that is invisible.
* On a printed page it is the difference between a map and a smudge, and by
* then the book is bound.
*
* A print shop wants 300. Anything from about 150 is passable on matte stock.
* Below that, the honest answer is a different source or a wider view.
*/
export function printDpi(view: TileView, template: string): number {
const px = template.includes('{r}') ? 512 : 256
return Math.round(px / (view.size / 25.4))
}
/**
* The credit a tile source requires.
*
@@ -239,6 +362,9 @@ export function attributionFor(template: string): string {
if (url.includes('stadiamaps')) return '© Stadia Maps © OpenStreetMap'
if (url.includes('carto')) return '© CARTO © OpenStreetMap'
if (url.includes('esri') || url.includes('arcgisonline')) return '© Esri'
if (url.includes('gibs.earthdata.nasa.gov')) return 'NASA EOSDIS GIBS'
// The wording CC BY 4.0 asks for: who made it, and what it is made of.
if (url.includes('tiles.maps.eox.at')) return 'Sentinel-2 cloudless © EOX (CC BY 4.0)'
return ''
}
+43 -12
View File
@@ -113,8 +113,21 @@ function escapeText(value: string): string {
* photographs were.
*/
export function printSheets(input: PrintSheetsInput): () => void {
/*
* The document's language, carried over from the editor.
*
* Not decoration: `hyphens: auto` does nothing at all until the browser knows
* which language's rules to break the words by, and it reads that from the
* nearest `lang`. Without it a heading the editor had set as "Lorem ip-sum"
* came out unhyphenated in the export, ran past its own frame and was clipped
* — the one place where what you proofread and what you print disagreed.
* TranslationContext sets this on the app, so taking it from there is what
* makes the two agree by construction rather than by a second setting.
*/
const lang = document.documentElement.lang || 'en'
const doc = `<!doctype html>
<html>
<html lang="${escapeAttr(lang)}">
<head>
<meta charset="utf-8">
<title>${escapeText(input.title)}</title>
@@ -254,16 +267,34 @@ async function whenReady(iframe: HTMLIFrameElement): Promise<void> {
const doc = iframe.contentDocument
if (!win || !doc) return
const images = Array.from(doc.images).map(img =>
img.complete
? Promise.resolve()
: new Promise<void>(resolve => {
// A picture that will not load must not hold the button hostage —
// better a book with one gap than a dialog that never finishes.
img.addEventListener('load', () => resolve(), { once: true })
img.addEventListener('error', () => resolve(), { once: true })
}),
)
const settle = (el: Element) => new Promise<void>(resolve => {
// A picture that will not load must not hold the button hostage — better a
// book with one gap than a dialog that never finishes.
el.addEventListener('load', () => resolve(), { once: true })
el.addEventListener('error', () => resolve(), { once: true })
})
await Promise.all([...images, doc.fonts?.ready ?? Promise.resolve()])
const images = Array.from(doc.images).map(img => (img.complete ? Promise.resolve() : settle(img)))
/*
* The photographs inside the map's markers are SVG `<image>`, which
* `doc.images` does not collect and which has no `complete` to ask, so there
* is nothing to do but wait on the events. Missing them meant a book could go
* to print with its route beads still blank.
*/
const svgImages = Array.from(doc.querySelectorAll?.('image') ?? []).map(settle)
/*
* And a ceiling over the lot. Without `complete` to fall back on there is no
* way to tell a picture that is still coming from one whose events already
* fired before this ran, and a Save button that never enables is worse than a
* marker that prints blank.
*/
const wait = win.setTimeout?.bind(win) ?? setTimeout
const ceiling = new Promise<void>(resolve => { wait(resolve, 8000) })
await Promise.race([
Promise.all([...images, ...svgImages, doc.fonts?.ready ?? Promise.resolve()]),
ceiling,
])
}
@@ -0,0 +1,147 @@
import type { BookDocument } from '@trek/shared'
import { formatBookCoords, formatBookDate } from './entryText'
/**
* Reading a book's bound text back out of the journey.
*
* The contract has promised this since the format was written — "a bound
* element re-reads its source when the book is opened, so fixing a typo in the
* journal fixes it in the book" — and until now nothing did it. An element
* placed from the Entries tab carried a `binding` that only `applyTemplate`
* ever looked at, so correcting an entry's title left every page that quoted it
* showing the old words, while the inspector went on telling people the link
* existed. This is that link.
*
* ── Three rules, all of them load-bearing ────────────────────────────────
*
* **A missing value never blanks a page.** An entry that has been deleted, a
* title that has been cleared, a photo whose caption is gone: the element keeps
* the words it has. Overwriting them with an empty string would turn a data
* change in the journal into a hole in a printed book, and nobody would connect
* the two.
*
* **`overridden` wins.** Editing the text in Studio is a decision, and after it
* the journal stops being the source. That flag is set by the canvas editor and
* by the inspector, and read here — its only reader.
*
* **A formatted source is only re-read when the fact behind it moved.** A title
* is its own value, so comparing the words is enough. A date is not: the same
* day is "28. Mai 2026" here and "MAY 28, 2026" on a page set in English and in
* small caps, and a resolver that compared the words would rewrite every such
* line the moment somebody with another language opened the book — and the two
* of them would then take turns doing it to each other. So date and coordinate
* bindings carry the raw value they were set from and are compared against
* that. An element written before that field existed has none, and is left
* exactly as it is.
*
* **Nothing changed means the same object.** Not an optimisation: `useBookStore`
* recognises the document it has agreed with the server by identity, so a
* resolver that always returned a fresh object would make every open count as
* an edit, and the autosave would write the book back every time somebody
* looked at it. Spreads and elements are shared through untouched, too.
*/
/**
* What the journey can answer with.
*
* Declared structurally rather than imported from the sidebar: this module
* knows about the journal, not about the panel that browses it, and the source
* the editor already builds satisfies this shape as it is.
*/
export interface BindingSource {
title: string
subtitle: string | null
entries: {
id: number
title: string | null
story: string | null
location: string | null
date: string | null
lat: number | null
lng: number | null
}[]
photos: { photoId: number; caption?: string | null }[]
}
export function resolveBindings(doc: BookDocument, src: BindingSource, locale: string): BookDocument {
let documentChanged = false
const spreads = doc.spreads.map(spread => {
let spreadChanged = false
const elements = spread.elements.map(el => {
if (el.kind !== 'text' || !el.binding || el.overridden) return el
const next = resolveOne(el.binding, src, locale)
// An empty answer is not an answer — see the first rule above. A journey
// with no subtitle, an entry whose title has been cleared and a photo
// that lost its caption all arrive here as an empty string, and none of
// them is a reason to blank a line somebody has set.
if (!next || !next.text || next.text === el.text) return el
spreadChanged = true
return next.value === undefined
? { ...el, text: next.text }
: { ...el, text: next.text, binding: { ...el.binding, value: next.value } }
})
if (!spreadChanged) return spread
documentChanged = true
return { ...spread, elements }
})
return documentChanged ? { ...doc, spreads } : doc
}
type Binding = NonNullable<Extract<BookDocument['spreads'][number]['elements'][number], { kind: 'text' }>['binding']>
/** The words, and — for a formatted source — the fact they were made from. */
interface Resolved {
text: string
value?: string
}
function resolveOne(binding: Binding, src: BindingSource, locale: string): Resolved | null {
if (binding.source === 'journey.title') return { text: src.title }
if (binding.source === 'journey.subtitle') return { text: src.subtitle ?? '' }
if (binding.source === 'photo.caption') {
const photo = src.photos.find(p => p.photoId === binding.photoId)
return { text: photo?.caption ?? '' }
}
const entry = src.entries.find(e => e.id === binding.entryId)
if (!entry) return null
switch (binding.source) {
// The same fallback the layout and the template filler use: a stop nobody
// has written about is known by where it is.
case 'entry.title': return { text: entry.title || entry.location || '' }
case 'entry.story': return { text: (entry.story || '').trim() }
case 'entry.date':
// No stored value means an element older than this machinery, or one the
// layout composed a longer line from. Either way its words are not this
// function's to rewrite.
if (!binding.value || !entry.date || binding.value === entry.date) return null
return { text: formatBookDate(entry.date, locale), value: entry.date }
case 'entry.location': {
// With a format it is the point, without one it is the place name. A
// hand-built element from the auto layout has never been through Zod, so
// the field is genuinely absent rather than defaulted.
if (!binding.format) return { text: entry.location ?? '' }
if (entry.lat == null || entry.lng == null) return null
const value = coordValue(entry.lat, entry.lng)
if (!binding.value || binding.value === value) return null
return { text: formatBookCoords(entry.lat, entry.lng, binding.format), value }
}
default: return null
}
}
/** What a point is, as one string, for the comparison above. */
export function coordValue(lat: number, lng: number): string {
return `${lat},${lng}`
}
+133
View File
@@ -0,0 +1,133 @@
import { calculateRouteWithLegs } from '../Map/RouteCalculator'
/**
* The roads between a book's stops.
*
* ── Why this is fetched here and frozen, rather than stored ──────────────
*
* TREK already asks OSRM for road geometry every time the planner draws a
* driving day, and then throws it away: it lives in React state and a tab-local
* cache, is never persisted, and no endpoint accepts it. Rather than build the
* table, the write path, the read path and the migration that would keep it,
* this asks the same router the planner asks, once, when somebody turns the
* option on — and writes the answer into the document like every other travel
* figure. The book then prints the same line offline, next year, on a machine
* that has never heard of OSRM.
*
* ── What it refuses to route ─────────────────────────────────────────────
*
* A leg is only sent if a road answer is plausible. Two reasons, and both are
* about honesty rather than about cost: a router asked for Reykjavík to Lisbon
* either fails or answers with three days of driving and a ferry, and neither
* is the flight that was actually taken. Past the ceiling the leg keeps the
* bow, which is how a printed map has always said "this part was flown".
*
* ── And why it is polite about it ────────────────────────────────────────
*
* The public router is a community service, asked from the designer's own
* browser with no identifying header, one request per leg. So the legs go one
* at a time with a pause between them, the way the transport-booking hook
* already paces itself, and a failure is an answer rather than an error: that
* leg simply has no road, and the map draws the line it drew before.
*/
/** Past this, a leg is a flight rather than a drive. */
const ROAD_CEILING_KM = 1200
/** A pause between legs, so a long journey is not a burst. */
const PACE_MS = 120
/**
* What a printed leg can resolve.
*
* A hundred and twenty, not four hundred, and the reason is bytes rather than
* looks: the whole book travels in one request on every autosave, and four
* hundred points a leg puts a thirteen-leg journey over a hundred kilobytes on
* its own. At page size a road with this many points is already smoother than
* the press can resolve — the extra detail was costing the save, not the map.
*/
const MAX_POINTS_PER_LEG = 120
/**
* Five decimals, which is about a metre.
*
* OSRM answers with six or seven, and the last two describe a position more
* precisely than the road is wide. Rounding here rather than at draw time is
* what keeps them out of the document, where they would be paid for on every
* save for the rest of the book's life.
*/
const round5 = (n: number): number => Math.round(n * 1e5) / 1e5
export interface RoadStop {
lat: number
lng: number
}
function km(a: RoadStop, b: RoadStop): number {
const r = (d: number) => (d * Math.PI) / 180
const dLat = r(b.lat - a.lat)
const dLng = r(b.lng - a.lng)
const h = Math.sin(dLat / 2) ** 2
+ Math.cos(r(a.lat)) * Math.cos(r(b.lat)) * Math.sin(dLng / 2) ** 2
return 12742 * Math.asin(Math.min(1, Math.sqrt(h)))
}
/**
* Thin a leg to what a printed line can show.
*
* Evenly spaced and keeping both ends, the same rule the journey's own route
* thinning uses: dropping a run out of the middle would cut the shape of the
* road out, while every n-th point keeps it and loses only detail no press can
* resolve.
*/
function thin(points: [number, number][]): [number, number][] {
if (points.length <= MAX_POINTS_PER_LEG) return points
const out: [number, number][] = []
const step = (points.length - 1) / (MAX_POINTS_PER_LEG - 1)
for (let i = 0; i < MAX_POINTS_PER_LEG; i++) out.push(points[Math.round(i * step)])
return out
}
/**
* The road for every leg, or null where there is none.
*
* Always as long as `stops.length - 1`, so entry `i` is unambiguously the way
* from stop `i` to stop `i + 1` — a shorter array would leave the renderer
* guessing which legs it had answers for.
*/
export async function fetchRoads(
stops: RoadStop[],
opts: { signal?: AbortSignal; onProgress?: (done: number, total: number) => void } = {},
): Promise<([number, number][] | null)[]> {
const legs = Math.max(0, stops.length - 1)
const out: ([number, number][] | null)[] = new Array(legs).fill(null)
for (let i = 0; i < legs; i++) {
if (opts.signal?.aborted) break
const a = stops[i]
const b = stops[i + 1]
if (km(a, b) > ROAD_CEILING_KM) {
opts.onProgress?.(i + 1, legs)
continue
}
try {
const r = await calculateRouteWithLegs([a, b], { signal: opts.signal, profile: 'driving' })
// Two points back is the straight line the caller already draws, so it is
// not a road and storing it would only cost bytes.
if (r.coordinates.length > 2) {
out[i] = thin(r.coordinates).map(([lat, lng]) => [round5(lat), round5(lng)])
}
} catch {
// A leg with no road keeps the line it had. Not an error worth a message:
// an island, a closed border and a router having a bad day all look the
// same from here, and all three mean the same thing for the drawing.
}
opts.onProgress?.(i + 1, legs)
if (i < legs - 1 && PACE_MS) await new Promise(resolve => { setTimeout(resolve, PACE_MS) })
}
return out
}
+45 -6
View File
@@ -49,21 +49,54 @@ export function isStale(el: BookElement, stats: JourneyStats | null): boolean {
return el.codes.join(',') !== stats.countries.map(c => c.code).join(',')
}
if (el.kind === 'map') {
// Against the route this map is of, which is not always the whole journey.
const live = routeFor(stats, el.tripId)
// The route is compared by shape rather than element-by-element: a
// four-hundred-point deep-equal on every render would cost more than it
// could ever catch, and a changed route almost always changes its length or
// one of its ends.
if (el.points.length !== stats.points.length) return true
if (el.points.length !== live.length) return true
if (!el.points.length) return false
const a = el.points[0]
const b = stats.points[0]
const b = live[0]
const y = el.points[el.points.length - 1]
const z = stats.points[stats.points.length - 1]
return a.lat !== b.lat || a.lng !== b.lng || y.lat !== z.lat || y.lng !== z.lng
const z = live[live.length - 1]
if (a.lat !== b.lat || a.lng !== b.lng || y.lat !== z.lat || y.lng !== z.lng) return true
/*
* And whether the photographs moved.
*
* A marker draws the entry's own first picture, so adding one to an entry
* changes the map without moving a single stop — the shape test above would
* never notice, and the only way to get the picture onto the page was to
* delete the map and place it again.
*
* Compared in full rather than by its ends, unlike the coordinates: a photo
* added to the middle of a journey is the ordinary case, where a stop added
* to the middle is not. It is a few hundred numbers joined into a string,
* which costs nothing next to the render it happens in.
*/
const shown = el.points.map(p => p.photoId ?? 0).join(',')
const now = live.map(p => p.photoId ?? 0).join(',')
return shown !== now
}
return false
}
/**
* The stops a map of this scope should draw.
*
* `null` is the journey entire. A trip id narrows it to that trip's own stops,
* which is the difference between a book with one map of everywhere and a book
* with a page per trip — and, on a journey made of two trips, the difference
* between a route and a route with an eight-hundred-kilometre ruler line across
* the middle of it joining two places nobody travelled between.
*/
export function routeFor(stats: JourneyStats, tripId: number | null): JourneyStats['points'] {
if (tripId == null) return stats.points
return stats.points.filter(p => p.tripId === tripId)
}
/**
* The patch that takes an element's values from the journey as it stands now.
*
@@ -92,10 +125,16 @@ export function refreshPatch(el: BookElement, stats: JourneyStats): Partial<Book
}
if (el.kind === 'map') {
const live = routeFor(stats, el.tripId)
return {
stale: false,
countries: stats.countries.map(c => c.code),
points: stats.points.map(p => ({ lat: p.lat, lng: p.lng, label: p.label })),
// Only the countries this map's own stops fall in: a map of one trip that
// listed every country in the journey would outline places it does not
// show.
countries: el.tripId == null
? stats.countries.map(c => c.code)
: [...new Set(live.map(p => p.country).filter((c): c is string => !!c))],
points: live.map(p => ({ lat: p.lat, lng: p.lng, label: p.label, photoId: p.photoId ?? null })),
} as Partial<BookElement>
}