Files
TREK/client/src/components/Studio/shapes.ts
T
Maurice 736599a89b feat(journey): TREK Studio — a photo book designer for Journey (#1973)
* fix(photos): serve local photos root-relative so a dotted install path works

res.sendFile(absolutePath) resolves against the rewritten req.url under the Nest
ExpressAdapter and answers a spurious 404 even though the file is there — the
same trap files-download.controller.ts:60 and plugin-frame.controller.ts:74
already work around with an explicit { root } + basename. The photo resolver
never got that treatment, so every thumbnail and original 404s on any install
whose uploads path contains a dot segment (~/.local/share/trek and friends).
The public journey asset route had it too, which took shared journeys with it.

The guards above each call already confine the path to the uploads tree, so the
root form is no weaker than what it replaces.

* feat(shared): add the book document contract for TREK Studio

Millimetres throughout, not pixels: a pixel means nothing to a print shop and
changes meaning with the device pixel ratio. CSS maps 1in onto 96px, 25.4mm and
72pt with a fixed ratio, so the editor can render the document at a scale and the
print renderer at 1:1 and land on the same page.

Paint order is the array order rather than a zIndex field that can disagree with
itself, text elements may stay bound to the journal entry they came from, and a
spread can park content a layout has no room for instead of dropping it.

* feat(journey): open TREK Studio over the journey

Studio is a child route of /journey/:id and portals itself above it, so the
journey stays mounted and shows through the panel's 16px margin — it reads as
something opened on top of the journey rather than a place you navigated to. The
URL exists for reload, the back button and shared links; the user never sees it.

Every rule in studio.css is scoped under .trek-dash on purpose: dashboard.css:95
resets button font, colour, background and padding at a specificity a bare .st-x
loses to, so an unscoped rule silently does not apply to a button.

Escape clears the selection and only leaves on a second press. In a dialog
Escape means go away; in an editor that reflex would cost you the page.

* feat(journey): build, edit and arrange the book in Studio

The auto mode turns a journey into a book once and then gets out of the way: what
it produces is an ordinary document, every element as editable as one placed by
hand. Templates work the same way — applying one pours the spread's existing
photos and text into the new arrangement and parks whatever will not fit, so
trying a text-only layout does not cost you the pictures.

Moving and resizing are hand-rolled on pointer events. The drag-and-drop
libraries in this space move items between lists and have no notion of a free
frame, a handle or a magnetic edge; HTML5 drag hands you a ghost image you cannot
control and no position until the drop. It is used for exactly the one shape it
suits — dragging a photo out of the content panel onto a frame.

Selection chrome carries two rings, dark inside light. A single line vanishes
against a photograph of its own value, and over a picture that is bright on one
side and dark on the other no measurement of the background can be right.

The sheet renders in DOM rather than on a canvas so the same component tree can
be what the print renderer runs — one renderer, nothing to drift against. Edit
affordances live in a layer above it and can never reach the page.

* i18n(journey): studio strings across all 23 locales

The empty-frame prompt breaks per language rather than copying the English line
break onto everything — forced onto Japanese or Arabic it strands a fragment on
the second line.

* refactor(journey): keep SpreadView to components only

FONT_STACKS and photoSrc move to their own module: a file that exports both
components and constants breaks Fast Refresh, and this is a file you edit
constantly while designing a page. Types come from the journey store instead of
any, and the count beside the content tabs is a badge rather than competing with
the label for the same weight.

* feat(journey): more shapes, decoration and a content search in Studio

Six shapes now instead of three — rounded rectangle, triangle and an outline-only
box join the rest, plus a quotation mark and an outlined circle under decoration.
A triangle is a clip path rather than the old CSS border trick: that hack cannot
take a fill gradient or a stroke and its size does not follow the frame the way
everything else does. A stroke sits inside the frame, or the drawn shape would be
wider than the box the editor snapped and the print would not match it.

The content panel gets a search over photos and entries. A photo matches on its
own caption and on the entry it hangs from — most photos carry no words at all,
so matching captions alone would look broken on exactly the journeys that need
it. Plain filtering over what is already in memory; a journey holds tens or
hundreds of items, not thousands.

Dates in the panel and in the book now follow the app's language through the
house formatDate rather than the browser's locale, and the entry's date and place
are two badges instead of one dot-joined string the eye has to parse.

* @
feat(journey): a shape library, picture frames and photo grids for Studio

Studio had six shapes, two frames and no grids. This is the library that
makes it usable for a book rather than for a diagram.

Shapes are SVG paths now, not clip-paths. That was forced rather than
chosen: a clipped div cannot take a stroke — the clip cuts the border in
half lengthwise — and a heart is not a box with a radius. Rectangles and
ellipses keep their old div rendering, since a box genuinely is better as
a box and every document written so far contains those two.

Two decisions in shapes.ts are worth stating.

The path *points* are scaled, not the coordinate system. Fitting a path
with preserveAspectRatio="none" scales the stroke with it, so a 0.5mm
outline on a frame twice as wide as it is tall comes out 0.7mm on the
sides and 0.35mm top and bottom. Printed next to a straight rule at
300dpi, you see it. Hence the deliberately boring path subset: absolute
M/L/C/Q/Z, numbers alternating x and y, no arcs.

And every shape fills its 0..100 box exactly, enforced by normalise() at
module load rather than asked for in a comment. The editor draws its
selection outline, its resize handles and every snap target from the
element frame, so a shape occupying 86% of its own frame cannot be
aligned against anything you can see. It costs a regularity nobody can
spot — a hexagon in a square frame still reads as a hexagon.

Frames are the same list: a picture frame is a shape with a photograph
inside it, and keeping two would mean a heart that exists as one but not
the other. Photos gain a mask and a decoration, kept independent, plus
the Polaroid, film and tape treatments that are not expressible as either.

Grids take their gutter out of the cells rather than adding it between
them, so a grid asked to fill the safe area fills it instead of
overhanging by one gutter.
@

* @
feat(journey): derive what a journey adds up to

GET /api/journeys/:id/stats — distance, days, steps, photos, places, the
furthest point, the countries in visit order, and the route itself. Read
only and derived: nothing here is stored, it is what the trips added to
the journey come to.

The route comes from the journey entries where they carry coordinates,
and falls back to the places on the linked trips where they do not —
which is the common case for a journey assembled from trips nobody has
written up yet. The two are never mixed: an entry written about a place
that is also on the trip would be two stops at one location, and the
distance would count that leg twice.

Countries read place_regions first, which Atlas already fills, and fall
through to getCountryFromCoords for the rest. That import is a plain
function from a module built without DI or Nest edges, so it costs the
journey domain no coupling to Atlas.

Distance is great-circle metres, not driving distance: there is no
routing engine here, consecutive stops are not necessarily joined by a
road, and a book that prints a road distance it never measured is worse
than one that says "as the crow flies". Metres because kilometres and
miles are a display choice.

A hotel across three nights is one place with three day assignments, so
the place query aggregates back down to one row at its earliest day —
otherwise the route would visit the hotel three times.

Two test fixes came out of writing this. journey.controller.test.ts still
asserted an absolute path from res.sendFile, which the photo fix in this
branch had already changed to the basename-plus-root pair; and
linkTripToJourney in the factories wrote to linked_at, a column that does
not exist — it had no callers, so it had never once run.
@

* @
feat(journey): travel elements — the route, the figures, the countries

A photo book of a trip is not an album: the trip carries facts, and those
facts make pages photographs cannot. Four new elements — a vector route
map, a figures panel, a country page and a set of small marks — plus the
mood, weather and pros/cons an entry already records.

Every one of them carries its own values, resolved when the element is
placed and written into the document. The print renderer is headless
Chromium loading a page; one that needs an authenticated fetch to know
what it says will print blank the day a token expires. It also makes a
book a record of a trip as it was, rather than something that quietly
rewrites last year distance when a stop is added. travelRefresh compares
what is stored against the journey and offers an update, so bringing an
element up to date is a choice.

The map is vector, from the coordinates, over silhouettes simplified
offline from the admin-0 boundaries the server already bundles for Atlas
— no licence question, nothing to fetch at render time, sharp at any
print size. It paints no background: a map is geography sitting on the
paper, not a window cut through it, so it can be laid over a photograph.

Flags are drawn rather than typed. A regional-indicator pair is the
obvious answer and works everywhere except Chrome on Windows, which has
no flag glyphs and renders the two letters instead — "DE" in a printed
book is not a flag. Thirty-three flags are exact constructions; anything
with an emblem or unequal bands is deliberately absent and falls back to
the country outline, because a wrong flag is worse than no flag.

Panel tiles render the real element small, through the page own
renderer. These differ from each other by what they say rather than by
their shape: four map styles are four maps, and no icon can tell you
which is which.
@

* @
feat(journey): manage spreads from the pages rail

Add, insert between two spreads, duplicate, reorder and delete. None of
it existed — a book was whatever the auto layout produced.

The cover and the back cover are fixed points: a book has exactly one of
each, they are single pages, and no sequence of clicks should be able to
produce a book with two covers or none. Every operation asks one
predicate whether a spread is inner, rather than each caller testing role
for itself, and a spread inserted after the back cover lands before it.

Duplicating re-ids every element it copies. Two elements sharing an id
would make selection ambiguous and every lookup that follows it wrong,
delete included.

Also: a locked element can be selected again. Locking used to switch its
hit target off entirely, which was a dead end — it could not be picked,
so the inspector never showed it, so the unlock button was unreachable
and the only way back was undo. Locked now means what it says: it cannot
be moved, and its resize handles are hidden so the editor does not offer
a drag it will refuse.
@

* @
feat(journey): let the auto layout use the travel elements

The book now opens on a summary spread — the route drawn on the left, the
figures on the right — and, for a journey that crossed a border, a country
page after it. Both are omitted rather than left empty when there is
nothing to draw: a spread holding a blank frame over the words "0 KM" is
worse than a shorter book, and every page in a printed one costs money.

Only the figures the journey actually has make it onto the page. A zero
is not a fact worth a tile, it is a hole in a composition.

Each entry gains a short accent rule above its heading — one drawn
element, and the cheapest thing here that makes a spread read as designed
rather than as text placed on a page. An entry with no photographs, which
is the one spread with a blank left page, sets its date as a numeral
there: a gap in the book becomes a pause in it.

The back cover closed with `${places} Orte` — German, hardcoded, in a
book that follows the app language everywhere else. It is a figures
element now, so it takes its labels from the same translations as the
rest of Studio.

The layout waits for the figures rather than racing them. Laying out
first would give a journey a summary spread or not depending on which
promise resolved first, and Studio already shows its loading state until
the document exists, so the wait costs nothing.
@

* @
feat(journey): the Studio wordmark replaces the book-name field

The field asked for a second name for something already named after the
journey — a box whose only real use was being left alone. The bar says
what this is instead: the lockup, inline so it takes the theme ink
through currentColor rather than needing a light-on-dark copy, and a beta
mark beside it.

Along with the strings for everything in this branch, across all 23
locales, and the two keys the name field used, removed rather than left
as orphans nobody can tell from live ones.

journey.studio.frames was "Picture frames" — too long for a tab sharing a
row with two others, and untranslated in 21 of the 23 locales, which
showed the English through. It is one word now, in every language.
@

* @
feat(journey): a free trim size, page numbers, and auto layout as a button

Three from the list the PR left open.

**Custom trim.** The five presets are what vendors actually bind, which
covers almost everyone — "almost" being the problem. A local printer with
a 24x18 press, or a book meant for a particular shelf, could not be made
here at all. Two fields under the format list, and typing in them *is*
picking custom: a book that is 210 by 240 is not square-21 with a typo,
so the preset follows rather than needing to be chosen first. Switching
to custom keeps the page it is on — it adjusts the format you have.

**Page numbers.** Set on the document and drawn by the renderer, which is
the only place that knows what number a page is. Stamping them with
pdf-lib afterwards would print numbers the editor never showed, and a book
you cannot proofread on screen is not much of an editor. They are also the
one thing on a page that is not an element: an element holding "14" would
still say 14 after its spread was moved. `startAt` exists because the
first inner spread is rarely page 1 once bound, and outer/inner is a real
distinction on a spread — getting it backwards puts both numbers in the
fold.

The controls live in the inspector empty state, which was one line of
hint text. With nothing selected, that panel is where the book own
settings belong.

**Auto layout as a button.** It ran once, on open, which made it the one
thing in Studio you could not ask for; a page that came out wrong had to
be rebuilt by hand. Now it does one spread or the whole book, both as
ordinary commits — the first thing anyone does with a button like this is
press it to see, and the second is want their page back. A single spread
keeps its id so the rail does not scroll, and refuses on anything not
built from an entry rather than replacing it with a blank.
@

* @
feat(journey): cover layouts, and five more for the spreads

The cover had none. The panel said covers are designed by hand, which was
true and unhelpful — it is the page people care most about and the one
they had no starting point for.

A cover is a different problem from a spread and gets its own set rather
than a filter over the existing one: it is a single page, the type is the
subject rather than a caption to a photograph, and a spread layout applied
to it lands half its frames past the edge. Five of them, from full bleed
to type-only, and the panel serves the right set for whichever spread is
open. The cards scale as one page there, and drop the fold line, since
there is no fold.

Five more spread layouts as well — a picture with a narrow column of
story, nine up, a mosaic around one large frame, two pictures with the
words between them, and four staggered so a row of squares stops reading
as a contact sheet.

Applying a layout also stopped mangling a single text. The old rule took
the longest text as the story and looked for a heading among the rest,
which reads a three-text spread correctly and gets a one-text cover
exactly wrong: the 30pt title *is* the longest text, so it was the story,
so a cover layout with a heading slot and no body slot had nowhere to put
it and parked the title. Size decides the heading now; length only sorts
what is left.
@

* @
feat(journey): seven self-hosted book faces, and a picker that shows them

The serif slot was Georgia. Georgia is a system font — on most desktops,
on no Linux container — so the print renderer would have substituted
something else and a book proofread in one typeface would have printed in
another. The existing Journey PDF export has exactly this bug today,
asking for Inter while only Poppins is bundled.

Every family is self-hosted through @fontsource now, all OFL, all loaded
with Studio own chunk so a face cannot arrive after the text has been
laid out and reflow the line endings someone was setting. Two sans, three
serifs from bookish to high-contrast, two display faces for a cover.
Every stack ends in a generic rather than in another named font nobody
shipped.

The three original ids are kept by name, so documents written so far
still parse — they point at bundled faces rather than at whatever the
machine happened to have.

The picker sets each family in itself. A row of chips reading
"Poppins / Lora / Bebas" in the interface font tells you their names and
nothing about the only thing anyone is choosing between.

Weights a family does not ship are disabled rather than offered: asking
for bold on a single-weight display face gets a synthesised one, which
prints as a smeared regular. Picking such a family moves the weight to
the nearest it really has.
@

* @
feat(journey): real map imagery, from the providers TREK already has

The map element drew country outlines and nothing else. That is still the
default and still the right one — nothing fetched, nothing licensed,
sharp at any print size. But an outline of Iceland cannot show which road
you took, and some books want that.

So two more sources, both reading the tile template and Mapbox token an
admin already configured for the planner and Atlas. A second place to
paste a token is a second place for it to be wrong, and a source with
nothing behind it is not offered at all — showing "Mapbox" to someone
without a token produces a grey rectangle and no explanation anywhere.

Both costs are stated rather than hidden: tiles are fetched when the page
renders, and they are raster, cut for one zoom, so printing much larger
than they were fetched goes soft.

Attribution is neither optional nor a setting. The licence requires
credit and a book is a published work — nobody can add a footnote after
it is bound. The credit is matched on the host, so an instance running its
own OSM mirror still credits OpenStreetMap, and an unrecognised source
gets none rather than an invented one. It is written into the document
when the element is placed, so the renderer cannot lose it.

The route is projected onto the tile grid when there is one. The vector
map fits itself to country outlines, and a line placed by that fit sits
next to the road rather than on it — the sort of error that only shows up
once it is printed. Outlines are dropped under imagery, where they would
be a second coastline over the one in the picture.
@

* @
fix(journey): make the Studio type-check again

The map element used tileView and projectOntoTiles without importing them,
useMapSources declared a stricter frame type than any real frame satisfies,
and the mood icon read a colour through an `in` check that types as unknown.
The page fixtures in the studio tests predate page numbers, so they build a
BookPageSetup that the contract no longer accepts — now parsed from the
schema, which cannot drift from it.
@

* @
feat(journey): the book is saved

Studio laid a book out on every open and kept it in the tab. Close the tab
and the afternoon went with it, and the auto layout was not a starting point
but the only point.

The document now lives in journey_books, one row per journey, and autosaves:
quiet for a moment after the last change, or at the latest fifteen seconds
in, so a drag across a spread is one request rather than four hundred. A
stored book wins over a fresh layout on open, and closing the editor writes
whatever is still queued.

Everyone on a journey can edit its book, so the write carries the version it
was made against and the update matches on it in a single statement. A save
that has been overtaken is refused with the current record in the body,
which turns "your work vanished" into a choice between two versions. The
server broadcasts journey:book:saved to the other editors — the version, not
the document — and a client with nothing outstanding takes the new one. A
client with unsaved edits deliberately takes nothing and conflicts on its
next save instead.
@

* @
feat(journey): export the book

The one thing Studio could not do. The button was there and disabled.

A book now goes out as sheets: every inner spread cut down the middle into
leaves in reading order, bleed carried out past the trim on all four sides,
crop marks outside that saying where to cut. The cut is a window rather than
a re-layout, so a photograph crossing the gutter still meets itself once both
halves are printed. Spreads stay whole in the other mode, which is what you
send someone to read.

The browser makes the PDF, from the editor components at 1:1. Considered and
rejected: headless Chromium on the server, and a PDF library drawing the
pages a second time. TREK is self-hosted, and neither Chromium in the image
nor a second renderer to proofread against is worth carrying when the browser
already produces exactly what the editor shows — it is also how the other
exports here work. What the browser will not write is PDF metadata and the
TrimBox entries; the marks carry that instead, as they have since long before
the format existed.

Two things had to give. `SpreadView` clipped at the trim, which is right on
screen and leaves a white hairline down every edge of a bound book, so print
mode lets the page run out and the sheet does the clipping. And the print
document is its own document: it carries the app stylesheets across so the
seven bundled faces are the ones that print, and waits for images and fonts
before it offers to save.
@

* @
fix(journey): make the Studio popovers cover what they cover

The auto-layout menu sat on the glass tokens, which carry 42-58% opacity when
the user has transparency on. That reads as depth over the workbench, where
the rails and the bar use it, and as a mess over the inspector, where this
menu opens: two layers of text through each other, neither readable.

The export dialog was worse — it named --panel and --card, which are not
tokens here, so its background resolved to nothing at all and the whole thing
was see-through.

Both are opaque now. The other glass surfaces are left alone: they float over
the workbench, and that is what the material is for.

The print preview also fits the pane. A spread sheet is over 400 mm across,
so at 1:1 the book ran off the side and had to be read by scrolling sideways.
Screen only — the print stays at full size.
@

* fix(journey): a cover keeps its own size, and a trim size can be typed

Three things the export and the page setup got wrong.

Spread mode made every sheet as wide as the widest so that one @page rule
would cover them all. That put a cover — one page — in the middle of a
spread-sized sheet with white either side, which is not a cover. Each sheet
is now sized to what is on it, and the print CSS carries a named page rule
for the single-page ones.

The trim fields clamped on every keystroke, so typing 500 meant the field saw
5, clamped it to the minimum and wrote that back under the cursor: the number
could not be typed at all, only nudged with the arrows. The field now keeps
what is being typed and tells the document about values it can use. The
arrows are unchanged, and leaving the field still clamps — someone who typed
5 and clicked away meant the smallest book.

And the autosave could loop. The save effect depended on the whole store
object, which is new on every render, so after a conflict — where the local
document is by definition not the saved one — it was a save attempt per
render: a 409, a re-render, another attempt. It depends on the callbacks now,
and a conflict holds the autosave until somebody answers it.

* feat(journey): page numbers pick their own colour

A book has dark pages and light ones, often on the same spread, so one folio
colour is wrong on half of them: the warm grey that reads on paper vanishes
into a full-bleed night photograph, and white vanishes the moment the page is
white. The way out used to be setting it per spread, which the document has
no place for.

The renderer asks what is under the number instead. It knows every element
and where it sits, so it walks them from the top down and takes the first one
that covers the spot: a shape's fill is arithmetic, a photograph gets white
with a hairline of shadow — unknowable without decoding it, and dark more
often than not once printed — and bare page takes the page colour.

A heuristic, deliberately: the alternative is sampling pixels from an image
that may not have loaded, in a renderer that also has to run for print.
Anyone it gets wrong can still pick a colour, and picking one turns it off.

* feat(journey): see who else is in the book, and where they are

Two people editing the same document without seeing each other is how you get
two people editing the same spread. So: a badge in the bar saying who has the
book open, and an arrow with a name on it for each of them.

The coordinates are millimetres on the spread, not pixels on a screen — the
two of you are at different zoom levels on different monitors, and a pixel
means nothing to the other one. They carry a spread index too, so a pointer
on page 40 is not drawn on page 2.

Ephemeral throughout. Nothing is written down, the room is the authorisation
for the pointer path, and a socket that dies takes its arrow with it rather
than leaving it on everyone else's page. Presence is keyed by socket because
two tabs are two pointers; the badge folds them back into one person, because
two tabs are not two people.

The rate limit needed room. Pointers move about ten times a second, three
times what the per-socket limit allows, and that limit is what stops a client
flooding the process — so it is now two: an outer ceiling every frame counts
against before parsing, and the original tight limit on everything a pointer
is not. Malformed JSON still counts against the tight one, which is what the
guard was for.

Throttled to ten frames a second going out and interpolated coming in: sixty
would be five times the traffic for something the eye cannot use, and drawing
ten as they land reads as a stutter rather than a hand.

* fix(journey): keep the zoom bar on screen at every zoom level

Zoomed far enough in, the bar slid off the bottom of the window — and it is
the only way back out, so the editor was stuck at 300%.

The workbench sat in a grid track sized `auto`, which grows to whatever is in
it; `overflow: auto` on the child does not stop that, because a grid item's
minimum size is its content unless told otherwise. So at 300% the box grew to
2400px inside a 660px window and took its absolutely positioned bottom edge
with it. The track is bound now, and the workbench scrolls instead of growing.

The bar also has a z-index, for the same reason it has to stay in view: it
must never be the thing something else covers.

* feat(journey): Studio replaces the old book export

The journey PDF and Studio were two ways to print the same book that disagreed
about what it looks like — and only one of them can be edited. The old export
goes: the two buttons on the desktop already sat next to the Studio one, and
the renderer they called is deleted rather than left as a second answer.

Nothing takes its place on the phone. The book is a Studio document now and
Studio is a desktop editor; a phone-sized PDF of something laid out for print
was the old export's answer to a question nobody was asking.

* feat(journey): lay the book out the way a travel book is laid out

The auto layout built every spread the same way: a picture on the left, words
on the right, and nothing else. It came out looking like a template because it
was one — and on a journey with little in it, like a stack of blank paper.

Five layouts now, chosen by what an entry has and alternating as the book goes
on. A place page for a stop nobody wrote about, with the country pale behind
the name and the coordinates under it. A story page with a small map of the
stop and the picture bleeding off three edges. A panorama across the fold. A
gallery with the hero on one page and a ruled strip on the other. And every
fourth picture spread goes full bleed with the words set over it, because a
book of loud pages has no loud pages.

The marks are what actually make these pages: a flag beside the country, a
date numeral, a chip saying which day this is, a rule along the foot with a
dot showing how far in you are. Each is trivial and together they are the
difference between a page that was designed and one that was filled in. All of
them are elements the panels can make, so what comes out can be taken apart.

The summary spread gained a heading and the furthest point drawn as two dots
and a line — that figure means nothing until it is a distance between two
names. The countries page went dark, because the printed one is: pale outlines
on near-black is the single most recognisable page in these books.

Two things the old layout got wrong are fixed on the way. Entries with nothing
on them share one page instead of taking a spread each, in the order they
happened rather than gathered at the end. And an entry whose photographs have
not arrived gets the frames they will go in, empty, rather than blank paper —
the layout is finished and the pictures are the only thing missing, which is
the right way round.

* feat(journey): build the spreads out of areas, and set the elements in ink

Two things, both about what a page is made of.

The layouts were photographs with captions. A printed travel book is built out
of areas: a page laid solid in ink with pale type on it, a band down the outer
edge, a picture that overruns the panel it sits against, a box ruled around a
block of text. Two more layouts do that now — one with a whole page in ink and
a second photograph crossing the fold onto it, one with an edge band and the
words in a ruled box, pictures at two sizes and one overlapping the hero. Six
layouts on a rotation, so the book stops reading as a template.

None of it needed a new feature. The document paints in array order, so a panel
pushed first is a panel everything else lands on; that is all layering is, and
it needed using rather than adding.

And the travel elements are ink by default rather than the app's orange. A book
is printed and a printed page is ink on paper; a colour that arrives without
being chosen turns every element into the same accent whether the book wants
one or not. Picking one is a click. The dark map is the exception — the route
goes pale there, because ink on a near-black country is a line nobody can see,
and only the default is overridden: a colour somebody chose stays theirs.

* fix(journey): three things the editor got wrong

An empty photo frame rendered on its own, ignoring frameStyle entirely — so a
Polaroid placeholder was a plain dashed rectangle until a photograph landed in
it and the chin appeared from nowhere. The two branches are folded together
now: the surround is drawn once and only what goes inside it differs, so a
frame shows what it will look like before it is filled.

Adding a page to a book with no inner pages yet put it in front of the cover,
where it could not be moved back from either — a move only ever swaps with
another inner spread, and the cover is not one. An empty book reports its last
inner spread as -1, and -1 + 1 is 0. The insert is bounded at both ends now.

And snapping only knew the outer safe lines. A spread draws that dashed rule
inset from each of its four vertical edges, so dragging inwards caught the fold
and nothing else — the line you could see just before it was not a target. All
four are, along with the centre of each page and the quarters within it: on a
spread the halfway mark is the fold, so a picture centred on its own page had
nothing to find.

* feat(journey): take the auto layout's spreads from templates drawn by hand

The layouts written as code are what a function can reason its way to: a
picture here, words there, margins that add up. What they are not is designed —
a panel bled off one edge, a shape running off a corner, a strip of pictures at
two sizes with the coordinates set beneath them. Those decisions come from
looking at a page, and the editor is where looking at a page happens.

So a spread built in Studio can now be the layout. `extract-templates.cjs`
reads a journey's book and writes its spreads out as data, with every
measurement divided by the page it was drawn on — a template built on a 210mm
square lays out on an A4 landscape book without being redrawn. `applyTemplate`
does the other half: it fills what the entry can answer for and copies
everything else as drawn.

That division is the whole contract. Text carrying a binding takes the title or
the story; empty frames take the photographs in order; the day, coordinate,
date and country marks take what the stop knows. Panels, rules and decorative
shapes are the design and are left exactly as they were put.

A template is one *for an entry* when it uses one — which has to come out of
the drawing rather than a label somebody remembers to set. A summary spread of
figures and country outlines reads perfectly well on its own, and dropping a
day's photographs into it would be nonsense.

Two templates ship with this, drawn by the person who will use them. The
built-in layouts stay as the fallback for entries no template suits.

* feat(journey): turn elements freely, and pass a spread on as a file

Rotation by the corner, the way it works everywhere else: a handle sits
diagonally outside each of the four corners of the selection, and dragging one
turns the element by the change in angle rather than to the angle under the
pointer, so it can be picked up anywhere without jumping. Held to 15 degree
steps unless shift is down. Four handles rather than one because a single
handle off the top right sits under the inspector for anything in the right
page's upper half.

And a spread can now leave the book it was made in. The zoom bar downloads the
one on screen as a file; Import, beside Add spread in the pages rail, brings one
back. Measurements travel as fractions of the page, so a spread drawn on a 210mm
square lays out correctly in an A4 landscape book, the same way the auto
layout's templates do.

What deliberately does not travel:

  - Photographs. The file carries the design, and the frames arrive empty.
  - The map source. A static map freezes the URL it was rendered from, and on a
    Mapbox instance that URL has the access token in it, so a file meant to be
    posted in a forum would carry a credential. Coming the other way, a tile
    template from a stranger is a URL every reader's browser would fetch tile by
    tile: an IP address handed to whoever wrote the file.

An imported file is treated as what it is, somebody else's JSON. It is read in
the tab that chose it and never uploaded, parsed and never evaluated, and every
element goes through the document contract, which drops unknown fields and
range-checks the rest. Colours in particular are #rrggbb or nothing. The size of
the file and the number of elements are both capped, because the damage a
hostile file can do here is not code execution, it is handing the editor more
than the server will accept and leaving a document that will not save.

Also fixes the rotation handle being drawn but not grabbable: the chrome layer
and the selection box both pass pointers through, and a handle has to opt back
in with pointer-events.

* docs(wiki): add two Studio screenshots for the addon page

The editor with a stats spread open, and the frames panel. Both are what the
Journey addon page will want once Studio ships, and both are wanted now to show
the feature off while it is still in review.

* test(realtime): cover the book room's refusals and its dead sockets

The realtime coverage ratchet caught what the book room work left behind: the
three handlers each have an early return for a message that is missing its
journey id or comes from a socket with no user, and none of them was exercised.
Every one of those is a silent failure by construction. A handler that did
something with a missing journey id would not throw, it would put a socket
somewhere it does not belong, and nobody would notice until two strangers were
looking at the same page.

The other half is sockets that are in a room but cannot be used: a connection
that dropped before its close handler ran, or one put in a room without ever
being registered. The peer list has to walk past both rather than showing a
ghost, and the broadcast has to skip them rather than throwing on a path that
runs ten times a second per editor.

Both files are back to full branch coverage, so the domain's pins hold as they
are rather than being lowered to fit.

* feat(journey): make the route map a map of the journey

Four things were wrong with it, and they compounded.

**It showed the wrong place.** The view was fitted to the country outlines as
well as the stops, so a trip that stayed inside Berlin was drawn as the whole of
Germany with two dots in the middle of it. It fits what the journey did now, and
the outlines run off the edge of the frame the way a coastline does on any real
map. Fitting to the country is still there as a deliberate choice, for the page
every travel book has, and how much air to leave around either is a setting
rather than a constant.

**It drew a line nobody travelled.** Stops joined in order is a claim about the
journey that is almost always false: it crosses mountains, water and borders the
trip went around. TREK already stores routed geometry per place, from the
planner and from imported GPX, so the map now follows the road where the trip
knows it and falls back to joining the stops where it does not. Segments stay
separate, so a trip with a flight in the middle does not grow a road across the
sea. The geometry is thinned when it is frozen into the element: a printed line
gains nothing from a point every fifteen metres, and a book carrying every GPS
fix of a three-week trip is a document nobody can save.

**The tiled and static sources drew nothing at all.** The tile grid was
computed, the route was projected onto it, and then no picture was ever
rendered — the map came out as a frame with a line across it. Three separate
faults behind that: the imagery layer did not exist, `{s}` was left unsubstituted
so every tile URL named a host that does not resolve, and the grid was cut from
the tiles the route happened to sit on rather than from what the frame shows, so
it stopped short of the edge. The frame decides the grid now, and it covers by
construction. Tiles overlap by a tenth of a millimetre, which closes the hairline
of white paper that rounding left between them.

Mapbox needed one more thing: `mapbox/standard` is a 3D GL style and the Static
Images API refuses it outright, so an instance configured for the planner's map
was configured with a style this cannot use. It falls back to the classic
equivalent, and a URL frozen into a document before that existed is repaired on
the way out rather than left broken for good.

**A map was always a rectangle.** It can be cut to the outline of the countries
now, so the picture *is* the country: no frame, no box, the page showing through
around the coastline. That is the version worth laying next to a photograph, and
the one thing a rectangle can never be. The tile grid and the vector fit are
projected from one extent so the picture and the shape it is cut to line up —
two fits meant the country was full of the wrong towns.

Also here: the credit line comes off the map itself. It is still resolved and
still stored, for the colophon, which is where a book has always credited its
sources.

* feat(journey): split the country list, and trim the map cards

The country list and the country grid were compositions somebody else made:
they decided the order, the spacing and the type size, and the only way to
change any of it was to not use them. They are gone, and what is left is the
same entry — the name over its silhouette, set the same way — as an element
placed one country at a time. Three down a page is the list, with the spacing
yours; one at 80mm is a chapter opener, which the list could never be. The name
is editable, so numbering them "1. Germany", "2. Netherlands" is typing rather
than a feature. The compact mark, outline beside the name at the size of a line
of type, stays for the places that want a mark rather than a heading.

The map section offers the four vector styles and nothing else. Tiles, Mapbox
and the cut-out are one click away in the inspector, where the rest of the map's
settings already live, and four cards that are the same map four times were
crowding out everything under them.

A map is fitted to the country by default now, which is the picture a travel
book usually wants. Fitting to the stops is still there and still matters the
moment the trip is smaller than the country it happened in.

Also: no navigation fallback from the dev service worker. In production it is
right — offline, a deep link has to be answered by the cached shell. In
development it answers a reload with the index.html it cached earlier, whose
script tags point at module URLs from before the last restart, so the browser
re-runs the previous version of the app while the editor shows the new one.
Every explanation for that is wrong until someone thinks of the service worker.

* fix(journey): drop what the trimmed map section left behind

Three bindings that only fed the cards removed in the commit before: the map
sources hook, the country codes the cut-out card needed, and the frame the
preview sized itself from. Lint had them as warnings rather than errors, so
they would have ridden along quietly.
2026-08-19 23:36:42 +02:00

501 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { BookShapeId } from '@trek/shared'
/**
* Every shape Studio can draw, as a path on a 0..100 square.
*
* ── Why paths and not clip-paths ──────────────────────────────────────────
*
* The first four shapes drew as `<div>`s: a rectangle is a box, an ellipse is a
* box with a radius, a triangle was a `clip-path`. That works for four shapes
* and stops working at five — a clipped div cannot take a stroke (the clip cuts
* the border in half, lengthwise), and a heart is not a box with a radius.
*
* So everything past the rectangle and the ellipse is an SVG path. Those two
* keep their old rendering, because a box genuinely is better as a box: exact
* corner radii, an even border, and no regression on documents that already
* exist.
*
* ── Why 0..100 and not a viewBox ──────────────────────────────────────────
*
* The obvious way to fit a path to a frame is `viewBox="0 0 100 100"` with
* `preserveAspectRatio="none"`, and it is wrong for a book. That scales the
* coordinate system, and the stroke scales with it — a 0.5mm outline on a frame
* twice as wide as it is tall comes out 0.7mm on the sides and 0.35mm top and
* bottom. On screen you might not notice. Printed at 300dpi next to a straight
* rule, you do.
*
* Instead the *points* are scaled and the coordinate system is left in
* millimetres, so a stroke width means one thing everywhere. That is what
* `scalePath` does, and it is the reason every path here is written in a
* deliberately boring subset: absolute `M`, `L`, `C`, `Q`, `Z`, every number an
* x or a y in strict alternation. No arcs — `A` carries radii and a rotation
* flag that do not survive a non-uniform scale — and no relative commands.
*
* Curves are cubics because a cubic through a quarter circle is exact to within
* 0.03%, which is far below what a printer resolves.
*/
/** Circle-to-cubic constant: the handle length that makes a quarter arc. */
const K = 0.5523
const r2 = (n: number) => Math.round(n * 100) / 100
/**
* Stretch a ring of points to fill the 0..100 box exactly.
*
* A regular hexagon inscribed in a circle is 86.6 units wide and 100 tall, and
* drawn that way it would leave 7 units of nothing down each side of its own
* frame. In an editor that is a real problem rather than a cosmetic one: the
* selection outline, the resize handles and every snap target follow the frame,
* so a shape that does not fill its frame cannot be aligned to anything you can
* see. Filling the box is also what Canva does, and it costs a regularity
* nobody can spot — a hexagon in a square frame still reads as a hexagon.
*/
function fit(points: [number, number][]): string {
const xs = points.map(p => p[0])
const ys = points.map(p => p[1])
const minX = Math.min(...xs), maxX = Math.max(...xs)
const minY = Math.min(...ys), maxY = Math.max(...ys)
const sx = maxX > minX ? 100 / (maxX - minX) : 1
const sy = maxY > minY ? 100 / (maxY - minY) : 1
return `M${points
.map(([x, y]) => `${r2((x - minX) * sx)} ${r2((y - minY) * sy)}`)
.join('L')}Z`
}
/** A regular polygon, first point at the top, stretched to fill the box. */
function polygon(sides: number, rotation = -90): string {
const pts: [number, number][] = []
for (let i = 0; i < sides; i++) {
const a = ((rotation + (360 / sides) * i) * Math.PI) / 180
pts.push([50 + 50 * Math.cos(a), 50 + 50 * Math.sin(a)])
}
return fit(pts)
}
/**
* A star, `points` tips alternating with `points` valleys.
*
* `inner` is the valley radius as a fraction of the tip radius, and it is the
* only number that decides whether a star looks like a star or like a gear:
* roughly 0.38 for five points, higher as the count grows, or the tips get so
* thin they disappear at print size.
*/
function star(points: number, inner: number, rotation = -90): string {
const pts: [number, number][] = []
for (let i = 0; i < points * 2; i++) {
const rad = i % 2 === 0 ? 50 : 50 * inner
const a = ((rotation + (180 / points) * i) * Math.PI) / 180
pts.push([50 + rad * Math.cos(a), 50 + rad * Math.sin(a)])
}
return fit(pts)
}
/**
* A scalloped edge — a wax seal, a sticker, a burst.
*
* Not a star with a soft inner radius: the lobes have to bulge *outwards*
* between the points, which needs a curve through each valley rather than a
* straight line to it.
*/
function scallop(lobes: number, depth: number): string {
const step = (Math.PI * 2) / lobes
/*
* The petal tip is the curve's midpoint, not its control point.
*
* A quadratic at t=0.5 sits a quarter of the way to each end and half the way
* to the control, so the furthest the outline actually reaches is
* `0.5·R·cos(Δ/2) + 0.5·rm` — well short of `rm` itself. Sizing from `rm`
* would draw a flower that overflows its box by a tenth and gets clipped;
* solving for that midpoint instead makes the drawn petals touch the edge
* exactly, which is what "normalised to 0..100" has to mean.
*/
const reach = 0.5 * Math.cos(step / 2) + 0.5 * (1 + depth)
const R = 50 / reach
const rm = R * (1 + depth)
let d = ''
for (let i = 0; i < lobes; i++) {
const a0 = -Math.PI / 2 + step * i
const a1 = a0 + step
const am = (a0 + a1) / 2
const x0 = r2(50 + R * Math.cos(a0)), y0 = r2(50 + R * Math.sin(a0))
const x1 = r2(50 + R * Math.cos(a1)), y1 = r2(50 + R * Math.sin(a1))
const xm = r2(50 + rm * Math.cos(am)), ym = r2(50 + rm * Math.sin(am))
d += i === 0 ? `M${x0} ${y0}` : ''
d += `Q${xm} ${ym} ${x1} ${y1}`
}
return `${d}Z`
}
/** A circle as four cubics. */
function circle(cx = 50, cy = 50, rx = 50, ry = 50): string {
const kx = rx * K, ky = ry * K
return `M${r2(cx)} ${r2(cy - ry)}`
+ `C${r2(cx + kx)} ${r2(cy - ry)} ${r2(cx + rx)} ${r2(cy - ky)} ${r2(cx + rx)} ${r2(cy)}`
+ `C${r2(cx + rx)} ${r2(cy + ky)} ${r2(cx + kx)} ${r2(cy + ry)} ${r2(cx)} ${r2(cy + ry)}`
+ `C${r2(cx - kx)} ${r2(cy + ry)} ${r2(cx - rx)} ${r2(cy + ky)} ${r2(cx - rx)} ${r2(cy)}`
+ `C${r2(cx - rx)} ${r2(cy - ky)} ${r2(cx - kx)} ${r2(cy - ry)} ${r2(cx)} ${r2(cy - ry)}Z`
}
/** A rounded rectangle, corner radius in the same 0..100 units. */
function roundRect(r: number, x = 0, y = 0, w = 100, h = 100): string {
const k = r * (1 - K)
return `M${r2(x + r)} ${r2(y)}L${r2(x + w - r)} ${r2(y)}`
+ `C${r2(x + w - k)} ${r2(y)} ${r2(x + w)} ${r2(y + k)} ${r2(x + w)} ${r2(y + r)}`
+ `L${r2(x + w)} ${r2(y + h - r)}`
+ `C${r2(x + w)} ${r2(y + h - k)} ${r2(x + w - k)} ${r2(y + h)} ${r2(x + w - r)} ${r2(y + h)}`
+ `L${r2(x + r)} ${r2(y + h)}`
+ `C${r2(x + k)} ${r2(y + h)} ${r2(x)} ${r2(y + h - k)} ${r2(x)} ${r2(y + h - r)}`
+ `L${r2(x)} ${r2(y + r)}`
+ `C${r2(x)} ${r2(y + k)} ${r2(x + k)} ${r2(y)} ${r2(x + r)} ${r2(y)}Z`
}
/**
* The shape table.
*
* `rect` and `ellipse` are here for the panel previews and for masking; the
* page renderer still draws those two as boxes. Everything else is drawn from
* exactly this path, in the editor and in the print.
*/
export const SHAPE_PATHS: Record<BookShapeId, string> = {
// ── Basics ──────────────────────────────────────────────────────────────
rect: 'M0 0L100 0L100 100L0 100Z',
ellipse: circle(),
line: 'M0 50L100 50Z',
triangle: 'M50 0L100 100L0 100Z',
'triangle-down': 'M0 0L100 0L50 100Z',
diamond: 'M50 0L100 50L50 100L0 50Z',
parallelogram: 'M22 0L100 0L78 100L0 100Z',
trapezoid: 'M22 0L78 0L100 100L0 100Z',
pentagon: polygon(5),
hexagon: polygon(6),
'hexagon-flat': polygon(6, 0),
heptagon: polygon(7),
octagon: polygon(8, -112.5),
capsule: roundRect(50),
squircle: roundRect(26),
/** A doorway: square-footed, semicircular head. Reads as a portal or a niche. */
arch: `M0 100L0 50C0 ${r2(50 - 50 * K)} ${r2(50 - 50 * K)} 0 50 0`
+ `C${r2(50 + 50 * K)} 0 100 ${r2(50 - 50 * K)} 100 50L100 100Z`,
'half-circle': `M0 100C0 ${r2(100 - 100 * K)} ${r2(50 - 50 * K)} 0 50 0`
+ `C${r2(50 + 50 * K)} 0 100 ${r2(100 - 100 * K)} 100 100Z`,
'quarter-circle': `M0 100L0 0C${r2(100 * K)} 0 100 ${r2(100 - 100 * K)} 100 100Z`,
// ── Stars ───────────────────────────────────────────────────────────────
'star-4': star(4, 0.3),
'star-5': star(5, 0.382),
'star-6': star(6, 0.5),
'star-8': star(8, 0.58),
'star-12': star(12, 0.72),
burst: star(16, 0.78),
seal: scallop(12, 0.055),
/**
* The four-pointed twinkle. Concave sides, not straight ones — the straight
* version is a diamond with dents, and only the inward curve reads as light.
*/
sparkle: 'M50 0Q56 44 100 50Q56 56 50 100Q44 56 0 50Q44 44 50 0Z',
// ── Arrows ──────────────────────────────────────────────────────────────
'arrow-right': 'M0 30L58 30L58 5L100 50L58 95L58 70L0 70Z',
'arrow-left': 'M100 30L42 30L42 5L0 50L42 95L42 70L100 70Z',
'arrow-up': 'M30 100L30 42L5 42L50 0L95 42L70 42L70 100Z',
'arrow-down': 'M30 0L30 58L5 58L50 100L95 58L70 58L70 0Z',
'arrow-both': 'M0 50L28 8L28 32L72 32L72 8L100 50L72 92L72 68L28 68L28 92Z',
'chevron-right': 'M8 0L58 0L100 50L58 100L8 100L50 50Z',
'chevron-left': 'M92 0L42 0L0 50L42 100L92 100L50 50Z',
/** An arrow that turns a corner — a route that changes direction. */
'arrow-bent': 'M0 62L0 90L62 90L62 100L100 76L62 52L62 62Z',
// ── Speech ──────────────────────────────────────────────────────────────
/*
* A body and a tail, and the tail is wound the *same way round* as the body.
*
* Under the default non-zero fill rule two subpaths that overlap cancel where
* they meet if their windings oppose — which drew the tail as a wedge of hole
* punched through the bubble, joined to nothing. Nothing about the shape is
* wrong; the direction the points are listed in is.
*/
'bubble-round': `${roundRect(22, 0, 0, 100, 74)}M26 74L46 74L26 100Z`,
'bubble-square': 'M0 0L100 0L100 74L46 74L26 100L26 74L0 74Z',
'bubble-oval': `${circle(50, 37, 50, 37)}M28 66L48 71L22 96Z`,
'bubble-think': `${circle(52, 34, 48, 34)}${circle(24, 80, 12, 12)}${circle(8, 95, 6, 5)}`,
// ── Decoration ──────────────────────────────────────────────────────────
/**
* A heart with a real point at the bottom rather than a rounded chin. The two
* lobes are cubics that meet at the top notch; the tangents at the base are
* steep, which is what stops it reading as a spade.
*/
heart: 'M50 100C50 100 0 66 0 30C0 10 16 0 30 0C40 0 46 6 50 14'
+ 'C54 6 60 0 70 0C84 0 100 10 100 30C100 66 50 100 50 100Z',
cloud: 'M18 90C6 90 0 80 0 70C0 60 8 52 18 52C18 34 32 22 48 22'
+ 'C62 22 74 30 78 44C90 44 100 54 100 66C100 80 90 90 78 90Z',
'cloud-puffy': 'M14 88C4 88 0 78 4 70C-2 60 6 48 18 50C20 34 34 24 48 28'
+ 'C56 14 78 14 84 30C96 28 104 40 98 52C106 62 100 82 86 88Z',
drop: 'M50 0C50 0 88 42 88 66C88 86 71 100 50 100C29 100 12 86 12 66C12 42 50 0 50 0Z',
/** A crescent: one circle with a second bitten out of it, as a single path. */
moon: `M62 0C28 0 0 22 0 50C0 78 28 100 62 100C72 100 82 98 90 94`
+ `C64 90 44 72 44 50C44 28 64 10 90 6C82 2 72 0 62 0Z`,
/**
* A disc with rays. One star with a generous valley radius rather than a
* circle plus spikes: two overlapping subpaths would need a fill rule to
* decide whether the middle is a disc or a hole, and this needs no rule.
*/
sun: star(12, 0.68),
'flower-5': scallop(5, 0.28),
'flower-6': scallop(6, 0.24),
leaf: 'M50 0C82 18 100 44 100 66C100 86 78 100 50 100C22 100 0 86 0 66C0 44 18 18 50 0Z',
cross: 'M36 0L64 0L64 36L100 36L100 64L64 64L64 100L36 100L36 64L0 64L0 36L36 36Z',
plus: 'M42 0L58 0L58 42L100 42L100 58L58 58L58 100L42 100L42 58L0 58L0 42L42 42Z',
shield: 'M50 0L100 16L100 52C100 78 78 94 50 100C22 94 0 78 0 52L0 16Z',
/**
* A cog. Twelve teeth cut by a scalloped outer edge with a hole through the
* middle — the hole is a second subpath wound the same way, which `fill-rule:
* evenodd` turns into a hole.
*/
gear: `${star(12, 0.76)}${circle(50, 50, 20, 20)}`,
/** A torn ticket: notched at both ends, the way a stub is perforated. */
ticket: 'M0 8L100 8L100 34C93 34 88 41 88 50C88 59 93 66 100 66L100 92L0 92L0 66'
+ 'C7 66 12 59 12 50C12 41 7 34 0 34Z',
wave: 'M0 30Q25 0 50 30Q75 60 100 30L100 70Q75 100 50 70Q25 40 0 70Z',
mountain: 'M0 100L34 34L52 62L66 44L100 100Z',
/** A compass rose — four long points, four short, as one star of eight. */
compass: star(8, 0.24),
/** A map pin: round head, drawn tail. */
pin: 'M50 100C50 100 88 56 88 36C88 16 71 0 50 0C29 0 12 16 12 36C12 56 50 100 50 100Z',
// ── Organic ─────────────────────────────────────────────────────────────
//
// Hand-drawn blobs, four of them, each asymmetric on purpose: a symmetric
// blob reads as a badly drawn circle. They are the shape a modern travel page
// uses behind a caption or as a photo frame that is not a rectangle.
'blob-1': 'M52 2C74 0 96 14 99 36C102 58 88 78 68 90C48 102 22 98 10 82'
+ 'C-2 66 0 42 8 26C16 10 30 4 52 2Z',
'blob-2': 'M38 0C66 -2 92 16 98 40C104 64 88 88 62 96C36 104 10 92 3 70'
+ 'C-4 48 4 24 18 12C26 5 30 1 38 0Z',
'blob-3': 'M50 0C78 0 100 20 100 48C100 76 80 100 52 100C24 100 0 82 0 54'
+ 'C0 26 22 0 50 0Z',
'blob-4': 'M30 4C56 -6 88 6 96 30C104 54 92 82 68 94C44 106 16 96 6 74'
+ 'C-4 52 4 14 30 4Z',
// ── Banners ─────────────────────────────────────────────────────────────
'banner-ribbon': 'M0 20L100 20L100 80L0 80L14 50Z',
'banner-pennant': 'M0 0L100 0L100 62L50 100L0 62Z',
'banner-bookmark': 'M0 0L100 0L100 100L50 68L0 100Z',
'banner-flag': 'M0 0L100 0L86 30L100 60L0 60Z',
}
/**
* The box a path's ink actually occupies.
*
* Not the extent of its numbers: a curve never reaches its control points, so
* measuring those would report a heart as wider than it is drawn. Cubic and
* quadratic extrema are solved rather than sampled — it is barely more code
* than stepping along the curve and it is exact, which matters when the answer
* is used to normalise every shape in the library.
*/
function pathBounds(path: string): { x: number; y: number; w: number; h: number } {
const nums = (path.match(/-?\d*\.?\d+/g) ?? []).map(Number)
const cmds = path.match(/[MLCQZ]/g) ?? []
let i = 0
let cx = 0
let cy = 0
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
const hit = (x: number, y: number) => {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
}
/** Where a cubic turns on one axis: the roots of its derivative in 0..1. */
const cubicExtrema = (p0: number, p1: number, p2: number, p3: number): number[] => {
const a = -p0 + 3 * p1 - 3 * p2 + p3
const b = 2 * (p0 - 2 * p1 + p2)
const c = p1 - p0
if (Math.abs(a) < 1e-9) return Math.abs(b) < 1e-9 ? [] : [-c / b]
const disc = b * b - 4 * a * c
if (disc < 0) return []
const root = Math.sqrt(disc)
return [(-b + root) / (2 * a), (-b - root) / (2 * a)]
}
const cubicAt = (t: number, p0: number, p1: number, p2: number, p3: number) => {
const u = 1 - t
return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3
}
for (const cmd of cmds) {
if (cmd === 'Z') continue
if (cmd === 'M' || cmd === 'L') {
cx = nums[i++]; cy = nums[i++]
hit(cx, cy)
continue
}
// A quadratic is a cubic whose controls sit two thirds of the way out.
let x1: number, y1: number, x2: number, y2: number, x: number, y: number
if (cmd === 'Q') {
const qx = nums[i++], qy = nums[i++]
x = nums[i++]; y = nums[i++]
x1 = cx + (2 / 3) * (qx - cx); y1 = cy + (2 / 3) * (qy - cy)
x2 = x + (2 / 3) * (qx - x); y2 = y + (2 / 3) * (qy - y)
} else {
x1 = nums[i++]; y1 = nums[i++]
x2 = nums[i++]; y2 = nums[i++]
x = nums[i++]; y = nums[i++]
}
hit(x, y)
for (const t of cubicExtrema(cx, x1, x2, x)) {
if (t > 0 && t < 1) hit(cubicAt(t, cx, x1, x2, x), cubicAt(t, cy, y1, y2, y))
}
for (const t of cubicExtrema(cy, y1, y2, y)) {
if (t > 0 && t < 1) hit(cubicAt(t, cx, x1, x2, x), cubicAt(t, cy, y1, y2, y))
}
cx = x; cy = y
}
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
}
/**
* Normalise a path so its ink fills the 0..100 box exactly.
*
* Applied to every shape in the table, which turns "the paths are normalised"
* from a rule someone has to remember while hand-drawing a cloud into something
* true by construction.
*
* It has to be true, because the editor draws the selection outline, the resize
* handles and every snap target from the element's *frame*. A shape that
* occupies 84% of its frame cannot be aligned against anything you can see: you
* snap the box to a margin and the drawing sits somewhere inside it. Filling the
* box costs a little regularity — a hexagon in a square frame is very slightly
* wide — and buys an editor where what you snap is what you get.
*/
function normalise(path: string): string {
const b = pathBounds(path)
// A rule has no height and a shape with no extent has nothing to fit.
const sx = b.w > 1e-9 ? 100 / b.w : 1
const sy = b.h > 1e-9 ? 100 / b.h : 1
const ox = b.w > 1e-9 ? b.x : 0
const oy = b.h > 1e-9 ? b.y : 0
let axis = 0
return path.replace(/-?\d*\.?\d+/g, m => {
const isX = axis++ % 2 === 0
const v = isX ? (Number(m) - ox) * sx : (Number(m) - oy) * sy
return String(Math.round(v * 100) / 100)
})
}
for (const key of Object.keys(SHAPE_PATHS) as BookShapeId[]) {
SHAPE_PATHS[key] = normalise(SHAPE_PATHS[key])
}
/**
* Fit a 0..100 path to a box of `w` × `h`, in the box's own units.
*
* Scaling the numbers instead of the coordinate system is the whole point — see
* the note at the top of this file. Every path in the table is written so that
* numbers alternate x, y from the start of each command, which makes this a
* scan rather than a parse.
*/
export function scalePath(path: string, w: number, h: number): string {
const sx = w / 100
const sy = h / 100
let axis = 0
return path.replace(/-?\d*\.?\d+/g, m => {
const v = Number(m) * (axis++ % 2 === 0 ? sx : sy)
return String(Math.round(v * 1000) / 1000)
})
}
/**
* The same path on the 0..1 square SVG clip paths use.
*
* `clipPathUnits="objectBoundingBox"` is what lets one clip follow a frame as it
* is resized without re-rendering the path, which is what a photo frame has to
* do. It *does* stretch the shape with the box — a heart on a wide frame is a
* wide heart — and that is correct here: a frame you cannot make wide is an
* ornament, not a frame.
*/
export function unitPath(path: string): string {
return path.replace(/-?\d*\.?\d+/g, m =>
String(Math.round((Number(m) / 100) * 100000) / 100000))
}
/**
* Shapes drawn as two subpaths where the inner one is meant to be a hole.
*
* Only these get `fill-rule: evenodd`. Everywhere else the default matters:
* `bubble-think`'s trailing dots and `bubble-round`'s tail are separate
* subpaths too, and under `evenodd` any overlap between them and the body
* would knock a hole in it.
*/
export const HOLED_SHAPES = new Set<BookShapeId>(['gear'])
export interface ShapeGroup {
/** i18n key under `journey.studio.shapeGroup`. */
id: string
shapes: BookShapeId[]
}
/**
* How the panel is divided.
*
* Grouped the way you go looking for them — "I want an arrow", "I want
* something round and soft" — rather than by how they are built. Sixty
* unlabelled tiles in one grid is a wall; six groups of ten is a menu.
*/
export const SHAPE_GROUPS: ShapeGroup[] = [
{
id: 'basic',
shapes: ['rect', 'squircle', 'ellipse', 'capsule', 'triangle', 'triangle-down',
'diamond', 'parallelogram', 'trapezoid', 'arch', 'half-circle', 'quarter-circle'],
},
{
id: 'polygons',
shapes: ['pentagon', 'hexagon', 'hexagon-flat', 'heptagon', 'octagon'],
},
{
id: 'stars',
shapes: ['star-4', 'star-5', 'star-6', 'star-8', 'star-12', 'burst', 'seal', 'sparkle'],
},
{
id: 'arrows',
shapes: ['arrow-right', 'arrow-left', 'arrow-up', 'arrow-down', 'arrow-both',
'chevron-right', 'chevron-left', 'arrow-bent'],
},
{
id: 'speech',
shapes: ['bubble-round', 'bubble-square', 'bubble-oval', 'bubble-think'],
},
{
id: 'travel',
shapes: ['pin', 'compass', 'mountain', 'sun', 'moon', 'cloud', 'cloud-puffy',
'drop', 'wave', 'leaf', 'shield', 'ticket'],
},
{
id: 'decor',
shapes: ['heart', 'flower-5', 'flower-6', 'cross', 'plus', 'gear',
'blob-1', 'blob-2', 'blob-3', 'blob-4'],
},
{
id: 'banners',
shapes: ['banner-ribbon', 'banner-pennant', 'banner-bookmark', 'banner-flag'],
},
]
/**
* The shapes offered as picture frames.
*
* A subset, and the subset is the point: a photograph cut to a speech bubble's
* tail or to a hairline is a photograph you cannot read. What is here holds an
* image at book size — broad, mostly convex, no thin limbs.
*/
export const FRAME_SHAPES: BookShapeId[] = [
'rect', 'squircle', 'ellipse', 'capsule', 'arch', 'half-circle',
'triangle', 'diamond', 'pentagon', 'hexagon', 'octagon',
'heart', 'star-5', 'star-6', 'seal', 'flower-5', 'flower-6',
'blob-1', 'blob-2', 'blob-3', 'blob-4',
'shield', 'drop', 'leaf', 'pin', 'banner-pennant', 'banner-bookmark',
]