feat(studio): a second shelf of shapes, cut edges and a drawn line with heads and ornaments

- Fifty more shapes: arches, paper cut-outs (leaves, coral, weed, organic
  circles, a wonky star and sun), stamps, a postmark, a rosette, tags and
  ticket stubs, sunbursts, ribbons and bands, speech bubbles, drawn arrows,
  hearts, stars, photo frames and ornaments (scroll, laurel, fleuron, corner).
  The broad ones are photo frames too, and each tile is drawn at its shape's
  own proportions, which a new shape is also placed at.
- A cut edge on rectangles, circles, arches and the other broad shapes, painted
  or not, and on a photo's cut: zigzag, scallop, a postage stamp's perforation,
  wavy, torn and deckle, with a depth in millimetres. Cut in millimetres, so
  holes stay round on a wide frame.
- A line element: two to 32 points dragged on the canvas (a handle pulled from
  the middle adds one, a double-click removes it), straight or curved, solid,
  dashed or dotted, a wave or a zigzag, a hand-drawn wobble, a head on either
  end and an ornament in the middle. A shelf of lines and dividers places them.
- The assistant reaches all of it: add and style take the line (its points on
  the spread in mm) and the edges, describe_book_page says them, and two new
  findings say when a line is too thin to print and when an edge is set on a
  shape that takes none. A photo's mask is checked against the shape set
  rather than listed again, which keeps the page edit's schema smaller.
- BOOK_SCHEMA_REV goes to 6.
This commit is contained in:
Maurice
2026-10-23 21:36:08 +02:00
parent 7a7876b9f4
commit ce9c94a77b
102 changed files with 5960 additions and 140 deletions
@@ -0,0 +1,159 @@
import { type BookLineElement, MAX_LINE_POINTS, bookLinePoints, bookLineWithPoints } from '@trek/shared';
import { useRef } from 'react';
import { useStudioStore } from '../../store/studioStore';
import { constrainPoint } from './lineSnap';
/**
* The canvas handles of a selected line: one on each of its points, to drag
* it where it should go, and a smaller one half way along each segment that
* adds a point when it is pulled. Double-clicking a point between the ends
* takes it out again.
*
* Drawn inside the selection box, which carries the line's turn, at the
* points' own fractions of it, so they sit on the drawing at any zoom and any
* angle. The drag itself is measured on the spread, where the pointer is, and
* the frame is refitted around the moved points by `bookLineWithPoints`, the
* same refit the book engine uses.
*
* While dragging, a segment within a couple of degrees of level or plumb is
* made exactly level or plumb, and Shift holds it to 15 degree steps.
*/
type Pt = [number, number];
interface Drag {
index: number;
start: Pt;
pointerX: number;
pointerY: number;
points: Pt[];
}
export function LineHandles({
el,
spreadIndex,
scaled,
t,
}: {
el: BookLineElement;
spreadIndex: number;
/** Screen pixels per millimetre at the current zoom. */
scaled: number;
t: (k: string) => string;
}) {
const update = useStudioStore((s) => s.updateElement);
const beginGesture = useStudioStore((s) => s.beginGesture);
const endGesture = useStudioStore((s) => s.endGesture);
const commit = useStudioStore((s) => s.commit);
const drag = useRef<Drag | null>(null);
const place = (points: Pt[]) => {
const next = bookLineWithPoints(el, points);
update(spreadIndex, el.id, { frame: next.frame, points: next.points });
};
const grab = (e: React.PointerEvent, index: number, points: Pt[]) => {
e.stopPropagation();
e.preventDefault();
(e.target as Element).setPointerCapture?.(e.pointerId);
beginGesture();
drag.current = { index, start: points[index], pointerX: e.clientX, pointerY: e.clientY, points };
};
const onMove = (e: React.PointerEvent) => {
const d = drag.current;
if (!d) return;
e.stopPropagation();
const raw: Pt = [d.start[0] + (e.clientX - d.pointerX) / scaled, d.start[1] + (e.clientY - d.pointerY) / scaled];
const anchor = d.points[d.index === 0 ? 1 : d.index - 1];
const points = d.points.slice();
points[d.index] = constrainPoint(raw, anchor, e.shiftKey);
place(points);
};
const onUp = (e: React.PointerEvent) => {
if (!drag.current) return;
e.stopPropagation();
drag.current = null;
endGesture();
};
/** Pull a new point out of the middle of segment `i`. */
const insert = (e: React.PointerEvent, i: number) => {
const world = bookLinePoints(el) as Pt[];
const a = world[i];
const b = world[i + 1];
const points = [...world.slice(0, i + 1), [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2] as Pt, ...world.slice(i + 1)];
grab(e, i + 1, points);
place(points);
};
const remove = (i: number) => {
const world = bookLinePoints(el) as Pt[];
if (world.length <= 2) return;
const next = bookLineWithPoints(
el,
world.filter((_, k) => k !== i)
);
commit((d) => ({
...d,
spreads: d.spreads.map((sp, k) =>
k !== spreadIndex
? sp
: {
...sp,
elements: sp.elements.map((x) =>
x.kind === 'line' && x.id === el.id ? { ...x, frame: next.frame, points: next.points } : x
),
}
),
}));
};
// A point on the drawing, measured from the frame, not a side of the text.
const pct = (p: { x: number; y: number }) => ({ left: `${p.x * 100}%`, top: `${p.y * 100}%` }); // rtl-lint-disable
const canAdd = el.points.length < MAX_LINE_POINTS;
return (
<>
{canAdd &&
el.points.slice(1).map((p, i) => {
const a = el.points[i];
return (
<span
key={`m${i}`}
className="st-handle is-corner"
style={{
...pct({ x: (a.x + p.x) / 2, y: (a.y + p.y) / 2 }),
cursor: 'copy',
transform: 'scale(.7)',
opacity: 0.7,
}}
title={t('journey.studio.addPoint')}
onPointerDown={(e) => insert(e, i)}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
/>
);
})}
{el.points.map((p, i) => (
<span
key={`p${i}`}
className="st-handle is-corner"
style={{ ...pct(p), cursor: 'crosshair' }}
title={i > 0 && i < el.points.length - 1 ? t('journey.studio.removePoint') : undefined}
onPointerDown={(e) => grab(e, i, bookLinePoints(el) as Pt[])}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
onDoubleClick={(e) => {
e.stopPropagation();
if (i > 0 && i < el.points.length - 1) remove(i);
}}
/>
))}
</>
);
}
+46
View File
@@ -0,0 +1,46 @@
import type { BookLineElement } from '@trek/shared';
import type { CSSProperties } from 'react';
import { useMemo } from 'react';
import { type LineGeometry, lineGeometry } from './lineRender';
/** The paths of a line's geometry in one colour: the body stroked, the heads and the ornament filled. */
export function LinePaths({ g, color, width }: { g: LineGeometry; color: string; width: number }) {
const stroke = { fill: 'none', stroke: color, strokeWidth: width, strokeLinejoin: 'round' as const };
return (
<>
{g.body.map((d, i) => (
<path key={`b${i}`} d={d} {...stroke} strokeLinecap={g.cap} strokeDasharray={g.dash} />
))}
{g.strokes.map((d, i) => (
<path key={`s${i}`} d={d} {...stroke} strokeLinecap="round" />
))}
{g.fills.map((d, i) => (
<path key={`f${i}`} d={d} fill={color} />
))}
</>
);
}
/**
* A line element, drawn: its body stroked, its heads and ornament filled, all
* in the millimetres of its own frame (one SVG unit is one millimetre, as for
* the shapes). Overflow stays visible so a head on a thin frame is not cut.
*/
export function LineView({ el, frameStyle }: { el: BookLineElement; frameStyle: CSSProperties }) {
const { w, h } = el.frame;
const g = useMemo(() => lineGeometry(el, w, h, el.id), [el, w, h]);
return (
<div style={frameStyle}>
<svg
width={`${w}mm`}
height={`${h}mm`}
viewBox={`0 0 ${w} ${h}`}
style={{ display: 'block', overflow: 'visible' }}
aria-hidden
>
<LinePaths g={g} color={el.stroke} width={el.strokeWidth} />
</svg>
</div>
);
}
+6 -3
View File
@@ -5,7 +5,9 @@ import type {
import { fontStack, nearestWeight } from './bookFonts'
import { iconComponent } from './iconLibrary'
import { PhotoView } from './PhotoView'
import { HOLED_SHAPES, SHAPE_PATHS, scalePath } from './shapes'
import { HOLED_SHAPES } from './shapes'
import { hasEdge, shapeOutline } from './shapeOutline'
import { LineView } from './LineView'
import { TravelElementView } from './TravelElements'
import { PageNumbers } from './PageNumbers'
import { PaintedShapeView } from './paint/PaintedShape'
@@ -64,7 +66,7 @@ function ShapeView({ el }: { el: BookShapeElement }) {
const gradientId = usePaintId(`g-${el.id}`)
const gradient = el.gradient !== 'none' && el.fill
if (el.shape === 'rect' || el.shape === 'ellipse') {
if ((el.shape === 'rect' || el.shape === 'ellipse') && !hasEdge(el, el.shape)) {
const background = !gradient
? fill
: `linear-gradient(${el.gradient === 'up' ? 'to top' : 'to bottom'},`
@@ -87,7 +89,7 @@ function ShapeView({ el }: { el: BookShapeElement }) {
const sw = el.stroke ? el.strokeWidth : 0
const w = Math.max(0.01, el.frame.w - sw)
const h = Math.max(0.01, el.frame.h - sw)
const d = scalePath(SHAPE_PATHS[el.shape], w, h)
const d = shapeOutline(el, w, h)
// Proportional to the stroke, so a dashed outline keeps its rhythm whether it
// is a hairline on a caption rule or a 2mm band around a cover panel.
@@ -177,6 +179,7 @@ export function ElementView({
// the travel elements and draws null for anything they do not know.
if (el.kind === 'icon') return <IconView el={el} />
if (el.kind === 'sticker') return <StickerView el={el} frameStyle={frameStyle(el)} />
if (el.kind === 'line') return <LineView el={el} frameStyle={frameStyle(el)} />
if (el.kind !== 'text') {
// map, stats, countries, badge — the elements drawn from the journey's own
@@ -6,6 +6,7 @@ import { PeerCursors } from './PeerCursors'
import type { PeerCursor } from './useBookPresence'
import { bookElementId as elementId } from '@trek/shared'
import { fontStack, nearestWeight } from './bookFonts'
import { LineHandles } from './LineHandles'
import { useSpreadInteraction } from './useSpreadInteraction'
import { useStudioKeys } from './useStudioKeys'
import { selectClass, selectionShape } from './studioGestures'
@@ -408,7 +409,12 @@ export function StudioCanvas({
</div>
))}
{sel.length === 1 && !dragging && !el.locked && <ResizeHandles onResize={startResize} />}
{/* A line is shaped by its points rather than its box. */}
{sel.length === 1 && !el.locked && el.kind === 'line' && (
<LineHandles el={el} spreadIndex={spreadIndex} scaled={scaled} t={t} />
)}
{sel.length === 1 && !dragging && !el.locked && el.kind !== 'line' && <ResizeHandles onResize={startResize} />}
</div>
))}
@@ -0,0 +1,89 @@
import {
BOOK_EDGES,
BOOK_EDGE_SIZE_MAX,
BOOK_EDGE_SIZE_MIN,
type BookEdge,
type BookShapeId,
bookShapeTakesEdge,
} from '@trek/shared';
import { NumField, Section } from './StudioControls';
import { DEFAULT_EDGE_SIZE } from './shapeOutline';
import { edgedPath } from './shapes-edges';
/**
* The edge of a shape or of a photo's cut: a row of tiles, each the edge drawn
* on a little card, and how deep it bites.
*
* Shown for the shapes an edge is cut along and for photos. On an outline that
* takes none (a heart, a star) it stays away, unless an edge is already set
* there, which it then says does nothing and offers to put back.
*/
const CARD = 'M0 0L40 0L40 30L0 30Z';
/** One edge, drawn on a card the size of a tile. Seeded alike, so the torn tile does not change while you look at it. */
function EdgeGlyph({ edge }: { edge: BookEdge }) {
return (
<svg viewBox="-2 -2 44 34" aria-hidden>
<path d={edgedPath(CARD, edge, 5, 3)} fill="currentColor" />
</svg>
);
}
export function EdgeSection({
edge,
edgeSize,
outline,
onSet,
t,
}: {
edge: BookEdge | undefined;
edgeSize: number | undefined;
/** The shape the edge would be cut along; null for a photo's plain rectangle. */
outline: BookShapeId | null;
onSet: (patch: { edge?: BookEdge; edgeSize?: number }) => void;
t: (k: string) => string;
}) {
const current = edge ?? 'straight';
const takes = bookShapeTakesEdge(outline);
// A heart or a star keeps its drawn line, so there is nothing to offer unless an edge is already set on one.
if (!takes && current === 'straight') return null;
return (
<Section label={t('journey.studio.edgeStyle')} defaultOpen={current !== 'straight'}>
{!takes && (
<p className="st-hint" style={{ paddingBottom: 8 }}>
{t('journey.studio.edgeUnavailable')}
</p>
)}
<div className="st-mini-shapes">
{BOOK_EDGES.map((e) => (
<button
type="button"
key={e}
className={`st-mini-shape ${current === e ? 'is-on' : ''}`}
onClick={() => onSet({ edge: e })}
title={t(`journey.studio.edge.${e}`)}
aria-label={t(`journey.studio.edge.${e}`)}
aria-pressed={current === e}
>
<EdgeGlyph edge={e} />
</button>
))}
</div>
{takes && current !== 'straight' && (
<div style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.edgeSize')}
value={edgeSize ?? DEFAULT_EDGE_SIZE}
min={BOOK_EDGE_SIZE_MIN}
max={BOOK_EDGE_SIZE_MAX}
step={0.5}
unit="mm"
onChange={(v) => onSet({ edgeSize: v })}
/>
</div>
)}
</Section>
);
}
@@ -2,8 +2,10 @@ 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 { BOOK_GRIDS as GRIDS, bookElementId, bookGridElements as gridElements, defaultBookGridBox as defaultGridBox } from '@trek/shared'
import { FRAME_SHAPES, HOLED_SHAPES, SHAPE_GROUPS } from './shapes'
import { BOOK_GRIDS as GRIDS, bookElementId, bookShapeSize, bookGridElements as gridElements, defaultBookGridBox as defaultGridBox } from '@trek/shared'
import { shapeTile } from './shapeOutline'
import { StudioLineShelf } from './StudioLineShelf'
import { PanelHead } from './StudioPanelHead'
import { FEATURED_ICONS, iconComponent, iconLabel, searchIcons } from './iconLibrary'
import '../../styles/studio-elements.css'
@@ -35,8 +37,9 @@ type FrameStyle = 'none' | 'polaroid' | 'white' | 'shadow' | 'film' | 'tape'
*/
export function ShapeGlyph({ shape, photo = false }: { shape: BookShapeId; photo?: boolean }) {
const gid = `sg-${photo ? 'p' : 's'}-${shape}`
const tile = shapeTile(shape)
return (
<svg viewBox="0 0 100 100" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" aria-hidden>
<svg viewBox={`0 0 ${tile.w} ${tile.h}`} width="100%" height="100%" preserveAspectRatio="xMidYMid meet" aria-hidden>
{photo && (
<defs>
{/* theme-lint-disable — a frame preview stands in for a photograph, not for UI chrome */}
@@ -49,7 +52,7 @@ export function ShapeGlyph({ shape, photo = false }: { shape: BookShapeId; photo
</defs>
)}
<path
d={SHAPE_PATHS[shape]}
d={tile.d}
fill={photo ? `url(#${gid})` : 'currentColor'}
fillRule={HOLED_SHAPES.has(shape) ? 'evenodd' : undefined}
/>
@@ -145,10 +148,12 @@ export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: s
|| shape === 'capsule'
const tall = shape === 'pin' || shape === 'drop' || shape === 'arrow-up' || shape === 'arrow-down'
const isRule = shape === 'line'
const own = bookShapeSize(shape, side)
addElement(active, {
id: uid('s'), kind: 'shape',
frame: isRule
? centre(page.pageWidth * 0.5, 0.5)
: own ? centre(own.w, own.h)
: centre(wide ? side * 1.7 : side, tall ? side * 1.35 : wide ? side * 0.55 : side),
rotation: 0, opacity: 1, locked: false,
// A rule is a shape too — a hairline box rather than its own element type,
@@ -283,6 +288,8 @@ export function StudioElementsPanel({ page, t }: { page: BookPageSetup; t: (k: s
</div>
</div>
<StudioLineShelf page={page} single={single} onAdd={el => addElement(active, el)} t={t} />
{SHAPE_GROUPS.map(group => (
<div className="st-section" key={group.id}>
<div className="st-section-label">{t(`journey.studio.shapeGroup.${group.id}`)}</div>
@@ -24,6 +24,8 @@ import type { JourneySource } from './StudioSidebar'
import { Tooltip } from '../shared/Tooltip'
import { StudioArrangeSection } from './StudioArrangeSection'
import { selectionTitle } from './studioLayerRows'
import { EdgeSection } from './StudioEdgeControls'
import { LineInspector } from './StudioLineInspector'
/** How many icons the swap grid offers at once. A search narrows it below this. */
const ICON_CHOICES = 60
@@ -492,6 +494,14 @@ export function StudioInspector({
))}
</div>
</Section>
<EdgeSection
edge={el.edge}
edgeSize={el.edgeSize}
outline={el.mask && el.mask !== 'rect' ? el.mask : null}
onSet={patch => set(patch)}
t={t}
/>
</>
)}
@@ -536,6 +546,8 @@ export function StudioInspector({
t={t}
/>
<EdgeSection edge={el.edge} edgeSize={el.edgeSize} outline={el.shape} onSet={patch => set(patch)} t={t} />
<Section label={t('journey.studio.strokeStyle')} defaultOpen={false}>
<Line label={t('journey.studio.strokeStyle')} wide>
<Choice
@@ -623,6 +635,7 @@ export function StudioInspector({
)}
{el.kind === 'sticker' && <StudioStickerInspector el={el} set={set} t={t} />}
{el.kind === 'line' && <LineInspector el={el} spreadIndex={spreadIndex} t={t} />}
<TravelInspector el={el} stats={stats} path={path} set={set} t={t} locale={locale} />
@@ -0,0 +1,214 @@
import {
BOOK_LINE_CAPS,
BOOK_LINE_ORNAMENTS,
type BookLineCap,
type BookLineElement,
type BookLineOrnament,
bookLineStyled,
} from '@trek/shared';
import { ArrowLeftRight } from 'lucide-react';
import { useStudioStore } from '../../store/studioStore';
import { LinePaths } from './LineView';
import { Choice, Line, NumField, Section } from './StudioControls';
import { Swatches } from './StudioSwatches';
import { lineGeometry } from './lineRender';
/**
* The inspector of a drawn line: its colour and weight, dashes, the course it
* takes, a wave or a zigzag, the hand-drawn wobble, what sits on each end and
* in the middle.
*
* Every change goes through `bookLineStyled`, the book engine's own restyle,
* so a wider stroke or a new head refits the frame exactly as the assistant's
* `style` does, and the ends stay where they were drawn.
*/
type Look = Partial<Omit<BookLineElement, 'id' | 'kind' | 'frame' | 'points'>>;
type GlyphLook = Parameters<typeof lineGeometry>[0];
/** A tiny level line for the pickers: a plain rule, with what the picker is choosing set on it. */
function MiniLine({ over }: { over: Partial<GlyphLook> }) {
const el: GlyphLook = {
points: [
{ x: 0.08, y: 0.5 },
{ x: 0.92, y: 0.5 },
],
curve: 'straight',
strokeWidth: 1.4,
dash: 'solid',
squiggle: 'none',
startCap: 'none',
endCap: 'none',
wobble: 0,
ornament: 'none',
...over,
};
const g = lineGeometry(el, 28, 12, 'glyph');
return (
<svg viewBox="0 0 28 12" width="28" height="12" aria-hidden style={{ overflow: 'visible' }}>
<LinePaths g={g} color="currentColor" width={el.strokeWidth} />
</svg>
);
}
/** A tiny line with this end on it, for the end pickers. */
const CapGlyph = ({ cap, start }: { cap: BookLineCap; start: boolean }) => (
<MiniLine over={start ? { startCap: cap } : { endCap: cap }} />
);
/** A tiny rule with this ornament in its middle. */
const OrnamentGlyph = ({ ornament }: { ornament: BookLineOrnament }) => (
<MiniLine over={{ ornament, strokeWidth: 0.7 }} />
);
export function LineInspector({
el,
spreadIndex,
t,
}: {
el: BookLineElement;
spreadIndex: number;
t: (k: string) => string;
}) {
const commit = useStudioStore((s) => s.commit);
const selection = useStudioStore((s) => s.selection);
/** Restyle every selected line, each refitted around its own points. */
const set = (look: Look) =>
commit((d) => ({
...d,
spreads: d.spreads.map((sp, i) =>
i !== spreadIndex
? sp
: {
...sp,
elements: sp.elements.map((e) =>
e.kind === 'line' && selection.includes(e.id) && !e.locked ? bookLineStyled(e, look) : e
),
}
),
}));
/** The line turned round: its points in the other order and its two ends swapped with them. */
const swapEnds = () =>
commit((d) => ({
...d,
spreads: d.spreads.map((sp, i) =>
i !== spreadIndex
? sp
: {
...sp,
elements: sp.elements.map((e) =>
e.kind === 'line' && selection.includes(e.id) && !e.locked
? { ...e, points: [...e.points].reverse(), startCap: e.endCap, endCap: e.startCap }
: e
),
}
),
}));
const caps = (start: boolean) =>
BOOK_LINE_CAPS.map((c) => ({
value: c,
label: <CapGlyph cap={c} start={start} />,
title: t(`journey.studio.cap.${c}`),
}));
return (
<>
<Section label={t('journey.studio.kind.line')}>
<Line label={t('journey.studio.stroke')} wide>
<Swatches value={el.stroke} onPick={(c) => set({ stroke: c })} />
</Line>
<div className="st-grid2" style={{ marginTop: 10 }}>
<NumField
label={t('journey.studio.strokeWidth')}
value={el.strokeWidth}
min={0.05}
max={20}
step={0.05}
unit="mm"
onChange={(v) => set({ strokeWidth: v })}
/>
<NumField
label={t('journey.studio.wobble')}
value={Math.round(el.wobble * 100)}
min={0}
max={100}
step={10}
unit="%"
onChange={(v) => set({ wobble: Math.min(1, Math.max(0, v / 100)) })}
/>
</div>
<div style={{ marginTop: 10 }}>
<Line label={t('journey.studio.strokeStyle')} wide>
<Choice
value={el.dash}
options={(
[
['solid', 'strokeSolid'],
['dashed', 'strokeDashed'],
['dotted', 'strokeDotted'],
] as const
).map(([value, key]) => ({ value, label: t(`journey.studio.${key}`) }))}
onPick={(dash) => set({ dash })}
/>
</Line>
<Line label={t('journey.studio.lineCourseTitle')} wide>
<Choice
value={el.curve}
options={(['straight', 'smooth'] as const).map((value) => ({
value,
label: t(`journey.studio.lineCourse.${value}`),
}))}
onPick={(curve) => set({ curve })}
/>
</Line>
<Line label={t('journey.studio.lineBodyTitle')} wide>
<Choice
value={el.squiggle}
options={(['none', 'wave', 'zigzag'] as const).map((value) => ({
value,
label: t(`journey.studio.lineBody.${value}`),
}))}
onPick={(squiggle) => set({ squiggle })}
/>
</Line>
</div>
<p className="st-hint" style={{ paddingTop: 8 }}>
{t('journey.studio.linePointsHint')}
</p>
</Section>
<Section label={t('journey.studio.lineEnds')}>
<Line label={t('journey.studio.lineStart')} wide>
<Choice value={el.startCap} options={caps(true)} onPick={(startCap) => set({ startCap })} />
</Line>
<Line label={t('journey.studio.lineEnd')} wide>
<Choice value={el.endCap} options={caps(false)} onPick={(endCap) => set({ endCap })} />
</Line>
<div className="st-row" style={{ marginTop: 6 }}>
<button type="button" className="st-chip" onClick={swapEnds}>
<ArrowLeftRight size={13} />
{t('journey.studio.swapEnds')}
</button>
</div>
</Section>
<Section label={t('journey.studio.ornamentTitle')} defaultOpen={el.ornament !== 'none'}>
<Choice
value={el.ornament}
options={BOOK_LINE_ORNAMENTS.map((o) => ({
value: o,
label: <OrnamentGlyph ornament={o} />,
title: t(`journey.studio.ornament.${o}`),
}))}
onPick={(ornament) => set({ ornament })}
ariaLabel={t('journey.studio.ornamentTitle')}
/>
</Section>
</>
);
}
@@ -0,0 +1,86 @@
import { type BookElement, type BookPageSetup, bookElementId, bookNewLine } from '@trek/shared';
import { LinePaths } from './LineView';
import { DIVIDER_PRESETS, LINE_PRESETS, type LinePreset as Preset, presetPoints } from './linePresets';
import { lineGeometry } from './lineRender';
/**
* The drawn lines and dividers of the Elements panel: a straight rule, arrows,
* dashes and dots, a curve, a wave, a zigzag, a line drawn by hand, a dotted
* route, and the rules a title sits between.
*
* Each tile is drawn by the same geometry the page uses, so the tile is the
* line you get. They arrive half a page wide on the right-hand page, where the
* assistant's `add` puts them too, and their ends are moved on the canvas.
*/
/** A line as the page draws it, as a tile. */
function LineGlyph({ preset }: { preset: Preset }) {
const W = 40;
const H = 24;
const el = bookNewLine(
{
...preset.look,
strokeWidth: Math.max(1.2, (preset.look.strokeWidth ?? 0.5) * 2.4),
points: presetPoints(preset, 4, H / 2, W - 8),
},
{ id: preset.id, frame: null, inner: false, page: { pageWidth: W, pageHeight: H } as BookPageSetup }
);
const g = lineGeometry(el, el.frame.w, el.frame.h, preset.id);
return (
<svg viewBox={`${-el.frame.x} ${-el.frame.y} ${W} ${H}`} width="100%" height="100%" aria-hidden>
<LinePaths g={g} color="currentColor" width={el.strokeWidth} />
</svg>
);
}
export function StudioLineShelf({
page,
single,
onAdd,
t,
}: {
page: BookPageSetup;
single: boolean;
onAdd: (el: BookElement) => void;
t: (k: string) => string;
}) {
const add = (preset: Preset) => {
const origin = single ? 0 : page.pageWidth;
const w = page.pageWidth * (preset.id.startsWith('divider') ? 0.4 : 0.5);
const x = origin + (page.pageWidth - w) / 2;
const points = presetPoints(preset, x, page.pageHeight / 2, w);
onAdd(bookNewLine({ ...preset.look, points }, { id: bookElementId('l'), frame: null, inner: !single, page }));
};
const tiles = (list: readonly Preset[]) => (
<div className="st-shape-grid">
{list.map((p) => {
const label = t(`journey.studio.linePreset.${p.id}`);
return (
<button
type="button"
key={p.id}
className="st-shape-btn is-glyph"
onClick={() => add(p)}
title={label}
aria-label={label}
>
<LineGlyph preset={p} />
</button>
);
})}
</div>
);
return (
<>
<div className="st-section">
<div className="st-section-label">{t('journey.studio.drawnLines')}</div>
{tiles(LINE_PRESETS)}
</div>
<div className="st-section">
<div className="st-section-label">{t('journey.studio.dividers')}</div>
{tiles(DIVIDER_PRESETS)}
</div>
</>
);
}
@@ -0,0 +1,55 @@
import type { BookLineElement } from '@trek/shared';
/**
* The lines and dividers the Elements panel offers, as looks for a new line,
* and the points each is placed with.
*/
type Look = Partial<Omit<BookLineElement, 'id' | 'kind' | 'frame' | 'points'>>;
export interface LinePreset {
id: string;
look: Look;
/** A curve through three points rather than a straight rule. */
bend?: boolean;
}
export const LINE_PRESETS: readonly LinePreset[] = [
{ id: 'straight', look: {} },
{ id: 'arrow', look: { endCap: 'arrow' } },
{ id: 'double', look: { startCap: 'arrow', endCap: 'arrow' } },
{ id: 'dashed', look: { dash: 'dashed' } },
{ id: 'dotted', look: { dash: 'dotted', strokeWidth: 0.8 } },
{ id: 'curved', look: { curve: 'smooth', endCap: 'arrow' }, bend: true },
{ id: 'wave', look: { squiggle: 'wave' } },
{ id: 'zigzag', look: { squiggle: 'zigzag' } },
{ id: 'hand', look: { wobble: 0.8, endCap: 'open', strokeWidth: 0.7 } },
{
id: 'route',
look: { dash: 'dotted', strokeWidth: 0.9, curve: 'smooth', startCap: 'dot', endCap: 'arrow' },
bend: true,
},
];
export const DIVIDER_PRESETS: readonly LinePreset[] = (['diamond', 'sun', 'star', 'heart', 'dot'] as const).map(
(o) => ({
id: `divider-${o}`,
look: { ornament: o, strokeWidth: 0.3 },
})
);
/** The points a preset is placed with, in a box `w` wide around a middle line. */
export function presetPoints(p: LinePreset, x: number, y: number, w: number): { x: number; y: number }[] {
if (!p.bend) {
return [
{ x, y },
{ x: x + w, y },
];
}
const rise = w * 0.18;
return [
{ x, y: y + rise },
{ x: x + w * 0.5, y: y - rise },
{ x: x + w, y: y + rise },
];
}
+284
View File
@@ -0,0 +1,284 @@
import { type BookLineCap, type BookLineElement, type BookLineOrnament, bookLineCapSize } from '@trek/shared';
import { type Pt, seeded, seedOf } from './shapeDraw';
/**
* A line element as geometry: the stroked body and the parts drawn on it, in
* the millimetres of its own frame. LineView turns this into SVG; the panel's
* previews draw the same thing at tile size.
*
* Everything is a path, never an SVG `<marker>`. A marker is sized in the
* stroke's own units and drawn by rules browsers and print engines have never
* agreed on, while a path is exactly where it says it is, in every one of
* them and in the PDF.
*
* ── The order things happen in ───────────────────────────────────────────
*
* 1. The points become a centre line: straight between them, or a smooth
* curve through them.
* 2. The body is cut back where a head sits on an end, so a thick line does
* not poke through the point of its own arrow, and opened in the middle
* where an ornament sits.
* 3. A wave or a zigzag is laid along it, then the hand-drawn wobble.
* 4. Heads and the ornament are placed on the clean centre line, so they
* point the way the line goes rather than the way the last wiggle went.
*/
export interface LineGeometry {
/** The stroked parts of the body: one, or two either side of an ornament. */
body: string[];
/** Shapes filled in the line's colour: a filled head, a dot, the ornament. */
fills: string[];
/** Strokes drawn at the line's own width beside the body: an open head, a bar. */
strokes: string[];
dash: string | undefined;
cap: 'round' | 'butt';
}
type LineLook = Pick<
BookLineElement,
'points' | 'curve' | 'strokeWidth' | 'dash' | 'squiggle' | 'startCap' | 'endCap' | 'wobble' | 'ornament'
>;
const r2 = (n: number) => Math.round(n * 100) / 100;
const fmt = ([x, y]: Pt) => `${r2(x)} ${r2(y)}`;
const dist = (a: Pt, b: Pt) => Math.hypot(b[0] - a[0], b[1] - a[1]);
/** A Catmull-Rom curve through the points, sampled about every half millimetre. */
function smoothThrough(pts: readonly Pt[]): Pt[] {
const out: Pt[] = [pts[0]];
for (let i = 0; i < pts.length - 1; i++) {
const p0 = pts[Math.max(0, i - 1)];
const p1 = pts[i];
const p2 = pts[i + 1];
const p3 = pts[Math.min(pts.length - 1, i + 2)];
const n = Math.max(6, Math.min(120, Math.ceil(dist(p1, p2) / 0.5)));
for (let k = 1; k <= n; k++) {
const t = k / n;
const t2 = t * t;
const t3 = t2 * t;
const at = (a: number, b: number, c: number, d: number) =>
0.5 * (2 * b + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t2 + (-a + 3 * b - 3 * c + d) * t3);
out.push([at(p0[0], p1[0], p2[0], p3[0]), at(p0[1], p1[1], p2[1], p3[1])]);
}
}
return out;
}
/** Cumulative lengths along a polyline. */
function lengths(pts: readonly Pt[]): number[] {
const out = [0];
for (let i = 1; i < pts.length; i++) out.push(out[i - 1] + dist(pts[i - 1], pts[i]));
return out;
}
/** The point and the direction `s` millimetres along a polyline. */
function along(pts: readonly Pt[], acc: readonly number[], s: number): { p: Pt; dir: Pt } {
let i = 1;
while (i < pts.length - 1 && acc[i] < s) i++;
const a = pts[i - 1];
const b = pts[i];
const seg = acc[i] - acc[i - 1] || 1;
const t = Math.min(1, Math.max(0, (s - acc[i - 1]) / seg));
return { p: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], dir: [(b[0] - a[0]) / seg, (b[1] - a[1]) / seg] };
}
/** The part of a polyline between two lengths along it, resampled no coarser than `step`. */
function slice(pts: readonly Pt[], acc: readonly number[], from: number, to: number, step: number): Pt[] {
if (to - from <= 0.01) return [];
const n = Math.max(1, Math.ceil((to - from) / step));
const out: Pt[] = [];
// Every original corner inside the slice stays, or a zigzag of points loses its corners.
const marks = new Set<number>();
for (let k = 0; k <= n; k++) marks.add(from + ((to - from) * k) / n);
for (const s of acc) if (s > from && s < to) marks.add(s);
for (const s of [...marks].sort((a, b) => a - b)) out.push(along(pts, acc, s).p);
return out;
}
/** Lay a wave or a zigzag along a centre line. */
function squiggled(pts: Pt[], kind: LineLook['squiggle'], width: number): Pt[] {
if (kind === 'none' || pts.length < 2) return pts;
const acc = lengths(pts);
const total = acc[acc.length - 1];
const wave = Math.max(3, width * 8);
const periods = Math.max(1, Math.round(total / wave));
const lambda = total / periods;
const amp = Math.max(0.8, width * 2.2);
const step = kind === 'zigzag' ? lambda / 4 : Math.min(0.5, lambda / 12);
const out: Pt[] = [];
for (let s = 0; s <= total + 1e-6; s += step) {
const { p, dir } = along(pts, acc, s);
const phase = s / lambda;
const off = kind === 'wave' ? Math.sin(phase * Math.PI * 2) : [0, 1, 0, -1][Math.round(phase * 4) % 4];
// Calmer over the last half wave at each end, so the line runs straight into a head.
const hold = kind === 'wave' ? Math.min(1, s / (lambda / 2), (total - s) / (lambda / 2)) : 1;
out.push([p[0] - dir[1] * amp * off * hold, p[1] + dir[0] * amp * off * hold]);
}
return out;
}
/** The tremor of a line drawn by hand: a slow sideways drift, the same every time for the same element. */
function wobbled(pts: Pt[], amount: number, width: number, seed: number): Pt[] {
if (amount <= 0 || pts.length < 2) return pts;
const rnd = seeded(seed);
const acc = lengths(pts);
const total = acc[acc.length - 1];
const knots = Array.from({ length: Math.ceil(total / 9) + 3 }, () => rnd() * 2 - 1);
const drift = (s: number) => {
const x = s / 9;
const k = Math.floor(x);
const f = x - k;
const e = f * f * (3 - 2 * f);
return knots[k] * (1 - e) + knots[k + 1] * e;
};
const amp = amount * (0.5 + width * 1.2);
const dense = slice(pts, acc, 0, total, 0.6);
const dacc = lengths(dense);
return dense.map((p, i) => {
const { dir } = along(dense, dacc, dacc[i]);
// Held still at the very ends, so a hand-drawn arrow still meets its head.
const hold = Math.min(1, dacc[i] / 3, (total - dacc[i]) / 3);
const off = drift(dacc[i]) * amp * hold;
return [p[0] - dir[1] * off, p[1] + dir[0] * off] as Pt;
});
}
const path = (pts: readonly Pt[]) => (pts.length < 2 ? '' : `M${pts.map(fmt).join('L')}`);
const closed = (pts: readonly Pt[]) => `${path(pts)}Z`;
/** A circle as a closed path, four cubics. */
function disc([cx, cy]: Pt, r: number): string {
const k = r * 0.5523;
return (
`M${fmt([cx, cy - r])}C${fmt([cx + k, cy - r])} ${fmt([cx + r, cy - k])} ${fmt([cx + r, cy])}` +
`C${fmt([cx + r, cy + k])} ${fmt([cx + k, cy + r])} ${fmt([cx, cy + r])}` +
`C${fmt([cx - k, cy + r])} ${fmt([cx - r, cy + k])} ${fmt([cx - r, cy])}` +
`C${fmt([cx - r, cy - k])} ${fmt([cx - k, cy - r])} ${fmt([cx, cy - r])}Z`
);
}
/** A point `a` along the direction and `b` across it from `p`. */
const at = (p: Pt, dir: Pt, a: number, b: number): Pt => [
p[0] + dir[0] * a - dir[1] * b,
p[1] + dir[1] * a + dir[0] * b,
];
/** How far a head cuts the body back from its end. */
function capTrim(cap: BookLineCap, size: number, width: number): number {
if (cap === 'arrow') return size * 0.7;
if (cap === 'open') return width * 0.5;
return 0;
}
/** A head at `tip`, pointing along `dir` (the way the line arrives there). */
function capShape(
cap: BookLineCap,
[tip, dir]: [Pt, Pt],
{ size, width }: { size: number; width: number },
g: LineGeometry
): void {
if (cap === 'arrow') {
g.fills.push(
closed([tip, at(tip, dir, -size, size * 0.42), at(tip, dir, -size * 0.78, 0), at(tip, dir, -size, -size * 0.42)])
);
} else if (cap === 'open') {
const back = size * 0.9;
g.strokes.push(path([at(tip, dir, -back, back * 0.55), tip, at(tip, dir, -back, -back * 0.55)]));
} else if (cap === 'dot') {
g.fills.push(disc(tip, Math.max(width * 1.6, 0.8)));
} else if (cap === 'bar') {
g.strokes.push(path([at(tip, dir, 0, size * 0.45), at(tip, dir, 0, -size * 0.45)]));
}
}
/** The motif in the middle, centred on `p` and turned along the line. */
function ornamentShape(kind: BookLineOrnament, p: Pt, dir: Pt, size: number): string {
const s = size / 2;
switch (kind) {
case 'diamond':
return closed([at(p, dir, -s, 0), at(p, dir, 0, -s * 0.62), at(p, dir, s, 0), at(p, dir, 0, s * 0.62)]);
case 'dot':
return disc(p, s * 0.55);
case 'star': {
const pts: Pt[] = [];
for (let i = 0; i < 10; i++) {
const a = -Math.PI / 2 + (Math.PI / 5) * i;
const r = i % 2 === 0 ? s : s * 0.42;
pts.push([p[0] + r * Math.cos(a), p[1] + r * Math.sin(a)]);
}
return closed(pts);
}
case 'sun': {
const pts: Pt[] = [];
for (let i = 0; i < 24; i++) {
const a = (Math.PI / 12) * i;
const r = i % 2 === 0 ? s : s * 0.62;
pts.push([p[0] + r * Math.cos(a), p[1] + r * Math.sin(a)]);
}
return closed(pts);
}
case 'heart': {
const pts: Pt[] = [];
for (let i = 0; i < 32; i++) {
const t = (i / 32) * Math.PI * 2;
const x = (16 * Math.sin(t) ** 3) / 17;
const y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)) / 17;
pts.push([p[0] + x * s, p[1] + y * s]);
}
return closed(pts);
}
default:
return '';
}
}
/** The dash pattern for a line of this width, in millimetres, kept visible on a hairline. */
export function lineDash(dash: BookLineElement['dash'], width: number): string | undefined {
if (dash === 'dashed') return `${r2(Math.max(width * 3, 1.2))} ${r2(Math.max(width * 2, 0.9))}`;
if (dash === 'dotted') return `0.01 ${r2(Math.max(width * 2, 0.6))}`;
return undefined;
}
/** The whole line, in the millimetres of a frame `w` by `h`. */
export function lineGeometry(el: LineLook, w: number, h: number, id = 'line'): LineGeometry {
const width = el.strokeWidth;
const raw = el.points.map((p) => [p.x * w, p.y * h] as Pt);
const centre = el.curve === 'smooth' && raw.length > 2 ? smoothThrough(raw) : raw;
const acc = lengths(centre);
const total = acc[acc.length - 1];
const size = bookLineCapSize(width);
const g: LineGeometry = {
body: [],
fills: [],
strokes: [],
dash: lineDash(el.dash, width),
cap: el.dash === 'dotted' || el.wobble > 0 ? 'round' : 'butt',
};
if (total < 0.01) return g;
const start = Math.min(total / 2, capTrim(el.startCap, size, width));
const end = Math.max(total / 2, total - capTrim(el.endCap, size, width));
const ornSize = el.ornament === 'none' ? 0 : 2.4 + width * 5;
const gap = ornSize ? ornSize / 2 + Math.max(1.2, ornSize * 0.45) : 0;
const mid = total / 2;
const pieces = gap ? [[start, mid - gap] as const, [mid + gap, end] as const] : [[start, end] as const];
const seed = seedOf(id);
pieces.forEach(([from, to], i) => {
const piece = slice(centre, acc, from, to, el.squiggle === 'none' && !el.wobble ? Infinity : 0.5);
const body = wobbled(squiggled(piece, el.squiggle, width), el.wobble, width, seed + i);
const d = path(body);
if (d) g.body.push(d);
});
const first = along(centre, acc, Math.min(0.01, total));
const last = along(centre, acc, Math.max(0, total - 0.01));
capShape(el.startCap, [centre[0], [-first.dir[0], -first.dir[1]]], { size, width }, g);
capShape(el.endCap, [centre[centre.length - 1], last.dir], { size, width }, g);
if (ornSize) {
const m = along(centre, acc, mid);
g.fills.push(ornamentShape(el.ornament, m.p, m.dir, ornSize));
}
return g;
}
+30
View File
@@ -0,0 +1,30 @@
/**
* How a dragged point of a line settles: level or plumb when it comes within
* a couple of degrees of either, and to 15 degree steps while Shift is held.
* Measured against the point it hangs from, its neighbour on the line.
*/
type Pt = [number, number];
/** How near, in degrees, a segment comes to level or plumb before it is made so. */
const LEVEL_DEG = 2;
const STEP_DEG = 15;
/** The point dragged to `p`, held level, plumb or to a step against the point it hangs from. */
export function constrainPoint(p: Pt, anchor: Pt | undefined, stepped: boolean): Pt {
if (!anchor) return p;
const dx = p[0] - anchor[0];
const dy = p[1] - anchor[1];
const len = Math.hypot(dx, dy);
if (len < 0.01) return p;
const deg = (Math.atan2(dy, dx) * 180) / Math.PI;
let snapped: number | null = null;
if (stepped) snapped = Math.round(deg / STEP_DEG) * STEP_DEG;
else {
const square = Math.round(deg / 90) * 90;
if (Math.abs(deg - square) <= LEVEL_DEG) snapped = square;
}
if (snapped === null) return p;
const a = (snapped * Math.PI) / 180;
return [anchor[0] + Math.cos(a) * len, anchor[1] + Math.sin(a) * len];
}
@@ -1,5 +1,6 @@
import type { BookPaint, BookShapeElement } from '@trek/shared';
import { useMemo, type CSSProperties } from 'react';
import { shapeOutline as edgedOutline, hasEdge } from '../shapeOutline';
import { HOLED_SHAPES } from '../shapes';
import { shapeOutline, strokeDash } from './paintGeometry';
import { PaintedPath } from './paintRender';
@@ -29,7 +30,11 @@ export function PaintedShapeView({
const sw = el.stroke ? el.strokeWidth : 0;
const w = Math.max(0.01, el.frame.w - sw);
const h = Math.max(0.01, el.frame.h - sw);
const d = useMemo(() => shapeOutline(el, w, h, sw / 2), [el, w, h, sw]);
// A cut edge (shapeOutline.ts) replaces the drawn outline, paint or none.
const d = useMemo(
() => (hasEdge(el, el.shape) ? edgedOutline(el, w, h) : shapeOutline(el, w, h, sw / 2)),
[el, w, h, sw]
);
const box = useMemo(() => ({ x: 0, y: 0, w, h }), [w, h]);
return (
+189
View File
@@ -0,0 +1,189 @@
/**
* Drawing tools for the hand-made shapes: smooth outlines through points,
* arcs as cubics, strokes that taper, and a seeded random source for the
* shapes that are meant to look cut by hand.
*
* Everything here returns path text in the subset `scalePath` reads (absolute
* M, L, C, Z, x and y alternating) or plain point lists for it. Coordinates are
* free: the shape table normalises every path to its 0..100 box afterwards, so
* a shape is drawn at whatever size its arithmetic is easiest in.
*/
export type Pt = [number, number];
const r2 = (n: number) => Math.round(n * 100) / 100;
/** A point as path text, to two decimals. */
export const fmt = ([x, y]: Pt) => `${r2(x)} ${r2(y)}`;
/**
* Twice the signed area of a ring, with the sign the shape tests read: a ring
* drawn the way `circle()` is (clockwise on screen) comes out positive.
*/
export function signedArea(pts: readonly Pt[]): number {
let a = 0;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
a += pts[j][0] * pts[i][1] - pts[i][0] * pts[j][1];
}
return a / 2;
}
/**
* The ring wound clockwise on screen, the way every outline in the table is.
*
* Two parts of one shape that overlap must wind the same way, or under the
* non-zero fill rule the overlap cancels into a hole.
*/
export function clockwise(pts: readonly Pt[]): Pt[] {
return signedArea(pts) < 0 ? [...pts].reverse() : [...pts];
}
/** The opposite winding, for the inner ring of a shape with a hole. */
export function anticlockwise(pts: readonly Pt[]): Pt[] {
return clockwise(pts).reverse();
}
/** A closed polygon through the points, straight between them. */
export function polyPath(pts: readonly Pt[]): string {
return `M${pts.map(fmt).join('L')}Z`;
}
/**
* A smooth closed outline through every point: a Catmull-Rom spline written as
* cubics. `tension` 0 is the plain spline; towards 1 the curve tightens onto
* the points, which is how a cut-out keeps a crisp tip without a corner.
*
* `sharp` names points the outline turns at rather than curves through, the
* tip of a leaf or the point of a star.
*/
export function smoothPath(pts: readonly Pt[], tension = 0, sharp: ReadonlySet<number> = new Set()): string {
const n = pts.length;
const at = (i: number) => pts[((i % n) + n) % n];
const k = (1 - tension) / 6;
let d = `M${fmt(at(0))}`;
for (let i = 0; i < n; i++) {
const p0 = at(i - 1);
const p1 = at(i);
const p2 = at(i + 1);
const p3 = at(i + 2);
const k1 = sharp.has(i) ? 0 : k;
const k2 = sharp.has((i + 1) % n) ? 0 : k;
const c1: Pt = [p1[0] + (p2[0] - p0[0]) * k1, p1[1] + (p2[1] - p0[1]) * k1];
const c2: Pt = [p2[0] - (p3[0] - p1[0]) * k2, p2[1] - (p3[1] - p1[1]) * k2];
d += `C${fmt(c1)} ${fmt(c2)} ${fmt(p2)}`;
}
return `${d}Z`;
}
/** Points on a circle, angles in degrees clockwise from three o'clock (screen convention). */
export function onCircle(cx: number, cy: number, r: number, deg: number): Pt {
const a = (deg * Math.PI) / 180;
return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
}
/**
* An arc as cubics, from `a0` to `a1` degrees (either direction), without the
* move to its start: what follows an `M` or an `L` that already stands there.
* Split into pieces of at most 90 degrees, where a cubic is exact to 0.03%.
*/
export function arcTo(cx: number, cy: number, r: number, a0: number, a1: number): string {
const pieces = Math.max(1, Math.ceil(Math.abs(a1 - a0) / 90));
const step = (a1 - a0) / pieces;
const h = (4 / 3) * Math.tan((step * Math.PI) / 720) * r;
let d = '';
for (let i = 0; i < pieces; i++) {
const s = a0 + step * i;
const e = s + step;
const [sx, sy] = onCircle(cx, cy, r, s);
const [ex, ey] = onCircle(cx, cy, r, e);
const sa = (s * Math.PI) / 180;
const ea = (e * Math.PI) / 180;
const c1: Pt = [sx - h * Math.sin(sa), sy + h * Math.cos(sa)];
const c2: Pt = [ex + h * Math.sin(ea), ey - h * Math.cos(ea)];
d += `C${fmt(c1)} ${fmt(c2)} ${fmt([ex, ey])}`;
}
return d;
}
/** A point list along a circular arc, ends included. */
export function arcPoints([cx, cy]: Pt, r: number, [a0, a1]: [number, number], n: number): Pt[] {
return Array.from({ length: n + 1 }, (_, i) => onCircle(cx, cy, r, a0 + ((a1 - a0) * i) / n));
}
/**
* The outline of a stroke along a centre line, `width(t)` wide at each point
* (t from 0 to 1 along it): one side out, the other side back. A width of zero
* at an end gives it a point, which is how a leaf tip or a flourish's tail is
* cut. Returned as points, wound clockwise, for `smoothPath`.
*/
export function taper(centre: readonly Pt[], width: (t: number) => number): Pt[] {
const n = centre.length;
const sideA: Pt[] = [];
const sideB: Pt[] = [];
for (let i = 0; i < n; i++) {
const a = centre[Math.max(0, i - 1)];
const b = centre[Math.min(n - 1, i + 1)];
const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
const nx = -(b[1] - a[1]) / len;
const ny = (b[0] - a[0]) / len;
const half = width(n > 1 ? i / (n - 1) : 0) / 2;
const p = centre[i];
sideA.push([p[0] + nx * half, p[1] + ny * half]);
sideB.push([p[0] - nx * half, p[1] - ny * half]);
}
// A zero width at an end draws the same point twice; keep one.
const same = (a: Pt, b: Pt) => Math.hypot(a[0] - b[0], a[1] - b[1]) <= 0.01;
const ring = [...sideA, ...sideB.reverse()].filter((p, i, all) => i === 0 || !same(p, all[i - 1]));
if (ring.length > 1 && same(ring[0], ring[ring.length - 1])) ring.pop();
return clockwise(ring);
}
/** A leaf of the laurel and fleuron kind: pointed at both ends, `w` wide, along the line from `a` to `b`. */
export function leafAlong(a: Pt, b: Pt, w: number, bend = 0): Pt[] {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
const nx = -dy / len;
const ny = dx / len;
const pts: Pt[] = [];
const steps = 8;
for (let i = 0; i <= steps; i++) {
const t = i / steps;
const half = (w / 2) * Math.sin(Math.PI * t) ** 0.85 * (1 + bend * (t - 0.5));
const sag = bend * len * 0.08 * Math.sin(Math.PI * t);
pts.push([a[0] + dx * t + nx * (half + sag), a[1] + dy * t + ny * (half + sag)]);
}
for (let i = steps - 1; i > 0; i--) {
const t = i / steps;
const half = (w / 2) * Math.sin(Math.PI * t) ** 0.85 * (1 - bend * (t - 0.5));
const sag = bend * len * 0.08 * Math.sin(Math.PI * t);
pts.push([a[0] + dx * t - nx * (half - sag), a[1] + dy * t - ny * (half - sag)]);
}
return clockwise(pts);
}
/**
* A small seeded random source (mulberry32), for the shapes and edges that are
* meant to look cut by hand. Seeded, so a torn edge tears the same way every
* time it is drawn, on screen and in the print.
*/
export function seeded(seed: number): () => number {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** A whole number from a string, the same every time: an element id as the seed of its torn edge. */
export function seedOf(text: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}
@@ -0,0 +1,98 @@
import {
BOOK_SHAPE_ASPECT,
type BookPhotoElement,
type BookShapeElement,
type BookShapeId,
bookShapeTakesEdge,
} from '@trek/shared';
import { seedOf } from './shapeDraw';
import { circle, roundRect } from './shapePrimitives';
import { SHAPE_PATHS, scalePath } from './shapes';
import { edgedPath } from './shapes-edges';
/**
* The outline a shape or a photo's cut is drawn with, in millimetres, once
* its edge is applied. SpreadView asks here rather than reading the table
* directly, so the edge is one decision in one place.
*/
/** The edge depth used when an edge is chosen and no size: about a postage stamp's. */
export const DEFAULT_EDGE_SIZE = 3;
type Edged = Pick<BookShapeElement, 'edge' | 'edgeSize'>;
/** Whether the element's edge is cut along this outline (a heart, for one, keeps its drawn line). */
export function hasEdge(el: Edged, shape: BookShapeId | null): boolean {
return !!el.edge && el.edge !== 'straight' && bookShapeTakesEdge(shape);
}
/** A box `w` by `h` in millimetres, as the outline the edge is cut along: a rect keeps its corner radius. */
function basePath(shape: BookShapeId | null, w: number, h: number, radius: number): string {
if (shape === null || shape === 'rect') {
const r = Math.min(radius, w / 2, h / 2);
return r > 0 ? roundRect(r, 0, 0, w, h) : `M0 0L${w} 0L${w} ${h}L0 ${h}Z`;
}
if (shape === 'ellipse') return circle(w / 2, h / 2, w / 2, h / 2);
return scalePath(SHAPE_PATHS[shape], w, h);
}
/** The outline of a shape `w` by `h` millimetres, its edge cut where it takes one. */
export function shapeOutline(
el: Edged & Pick<BookShapeElement, 'id' | 'shape' | 'radius'>,
w: number,
h: number
): string {
const edge = el.edge ?? 'straight';
if (!hasEdge(el, el.shape)) return scalePath(SHAPE_PATHS[el.shape], w, h);
return edgedPath(basePath(el.shape, w, h, el.radius), edge, el.edgeSize ?? DEFAULT_EDGE_SIZE, seedOf(el.id));
}
/**
* The cut of a photo's picture box (`w` by `h` mm) as an objectBoundingBox
* clip, 0..1 on both axes; null when the picture is the plain rectangle.
*
* The edge is cut in millimetres and only then divided down, so a stamp's
* holes stay round on a wide photo, which they would not if the 0..1 path
* were cut instead.
*/
export function photoClip(
el: Pick<BookPhotoElement, 'id' | 'mask' | 'edge' | 'edgeSize' | 'radius'>,
w: number,
h: number
): string | null {
const mask = el.mask && el.mask !== 'rect' ? el.mask : null;
const edged = hasEdge(el, mask);
if (w <= 0 || h <= 0) return null;
let mm: string;
if (edged) {
mm = edgedPath(
basePath(mask, w, h, el.radius),
el.edge ?? 'straight',
el.edgeSize ?? DEFAULT_EDGE_SIZE,
seedOf(el.id)
);
} else if (mask) {
mm = scalePath(SHAPE_PATHS[mask], w, h);
} else {
return null;
}
let axis = 0;
return mm.replace(/-?\d*\.?\d+/g, (m) => {
const v = Number(m) / (axis++ % 2 === 0 ? w : h);
return String(Math.round(v * 100000) / 100000);
});
}
/**
* A shape as a tile draws it: at the proportions it was drawn at, so a thin
* arrow is a thin arrow in the panel and not a square one. The first shelf
* has no recorded proportions and fills its square, as it always has.
*/
export function shapeTile(shape: BookShapeId): { d: string; w: number; h: number } {
const aspect = (BOOK_SHAPE_ASPECT as Readonly<Record<string, number>>)[shape];
if (!aspect) return { d: SHAPE_PATHS[shape], w: 100, h: 100 };
const w = aspect >= 1 ? 100 : 100 * aspect;
const h = aspect >= 1 ? 100 / aspect : 100;
return { d: scalePath(SHAPE_PATHS[shape], w, h), w, h };
}
@@ -0,0 +1,131 @@
/**
* The building blocks the shape tables are drawn with, on a 0..100 square.
*
* Shared by shapes.ts, shapes-more.ts and shapes-cutouts.ts, which is why they
* live apart from any one table. Every path they build keeps to the subset
* `scalePath` depends on (see the note at the top of shapes.ts): absolute M,
* L, C, Q and Z, numbers alternating x and y.
*/
/** Circle-to-cubic constant: the handle length that makes a quarter arc. */
export const K = 0.5523;
export 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. */
export 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.
*/
export 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.
*/
export 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. */
export 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. */
export 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`
);
}
@@ -0,0 +1,213 @@
import { type Pt, clockwise, leafAlong, onCircle, polyPath, seeded, smoothPath, taper } from './shapeDraw';
import { circle } from './shapePrimitives';
/**
* Paper cut-outs, in the manner of the late Matisse: leaves, coral, weed,
* wonky stars and a sun with flames for rays, and three not-quite circles.
*
* They are drawn from a few numbers and a fixed seed rather than traced, so
* every one is asymmetric the way a hand with scissors is, and the same on
* every machine. A cut-out reads by its silhouette, so each is one fill with
* no inner lines; the parts of the coral and the weed overlap and are wound
* alike, which joins them.
*/
/** A closed outline from a radius at each angle, angles in degrees clockwise from the top. */
function polar(n: number, radius: (deg: number, i: number) => number, cx = 50, cy = 50): Pt[] {
return Array.from({ length: n }, (_, i) => {
const deg = (360 / n) * i;
return onCircle(cx, cy, radius(deg, i), deg - 90);
});
}
/** A circle that wanders: a few slow waves added to its radius. */
function organic(seed: number, amount: number): string {
const rnd = seeded(seed);
const waves = [2, 3, 5].map((k, i) => ({ k, a: amount * [1, 0.55, 0.3][i], p: rnd() * Math.PI * 2 }));
const pts = polar(28, (deg) => {
const t = (deg * Math.PI) / 180;
return 50 * (1 + waves.reduce((sum, w) => sum + w.a * Math.sin(w.k * t + w.p), 0));
});
return smoothPath(clockwise(pts));
}
/** Five points cut by hand: tips of different lengths, sides that bow, nothing quite regular. */
function organicStar(): string {
const rnd = seeded(11);
const pts: Pt[] = [];
const sharp = new Set<number>();
for (let i = 0; i < 5; i++) {
const tipDeg = 72 * i + (rnd() - 0.5) * 10;
const valleyDeg = 72 * i + 36 + (rnd() - 0.5) * 8;
sharp.add(pts.length);
pts.push(onCircle(50, 50, 44 + rnd() * 8, tipDeg - 90));
// A point either side of the valley, pushed out, bows the sides.
pts.push(onCircle(50, 50, 30 + rnd() * 3, valleyDeg - 104));
pts.push(onCircle(50, 50, 19 + rnd() * 4, valleyDeg - 90));
pts.push(onCircle(50, 50, 30 + rnd() * 3, valleyDeg - 76));
}
return smoothPath(clockwise(pts), 0.35, sharp);
}
/** A disc with flames for rays, each one leaning the same way, as a cut sun does. */
function sunCutout(): string {
const rnd = seeded(5);
const rays = 14;
const pts: Pt[] = [];
const sharp = new Set<number>();
for (let i = 0; i < rays; i++) {
const a = (360 / rays) * i;
pts.push(onCircle(50, 50, 31 + rnd() * 2, a - 90));
pts.push(onCircle(50, 50, 40, a + 360 / rays / 2 - 96));
sharp.add(pts.length);
pts.push(onCircle(50, 50, 46 + rnd() * 4, a + 360 / rays / 2 - 84));
}
return smoothPath(clockwise(pts), 0.15, sharp);
}
/** A long willow leaf on a curving midrib, its stem left on. */
function leafLong(): string {
const spine: Pt[] = [];
for (let i = 0; i <= 40; i++) {
const t = i / 40;
const u = 1 - t;
// A quadratic from the stem to the tip, bowed to one side.
spine.push([u * u * 34 + 2 * u * t * 58 + t * t * 44, u * u * 200 + 2 * u * t * 110 + t * t * 0]);
}
const width = (t: number) => (t < 0.07 ? 4 : 44 * Math.sin(Math.PI * ((t - 0.07) / 0.93) ** 1.15) ** 0.9 + 1.2);
return smoothPath(taper(spine, width), 0.1);
}
/** An oak leaf: a midrib with rounded lobes, the two sides out of step. */
function leafOak(): string {
const n = 80;
const sideA: Pt[] = [];
const sideB: Pt[] = [];
for (let i = 0; i <= n; i++) {
const t = i / n;
const y = 200 - t * 200;
const stem = t < 0.08;
const env = stem ? 3 : 46 * Math.sin(Math.PI * ((t - 0.08) / 0.92) ** 0.85) ** 0.75 + 1;
const lobe = (phase: number) => (stem ? 1 : 0.55 + 0.45 * Math.abs(Math.cos(Math.PI * 4.5 * t + phase)) ** 0.6);
sideA.push([50 - env * lobe(0), y]);
sideB.push([50 + env * lobe(0.9), y]);
}
return smoothPath(clockwise([...sideA, ...sideB.reverse()]));
}
/** A palmette: five fingers fanned from one stem, the outer ones shorter. */
function leafPalm(): string {
const pts: Pt[] = [];
const base: Pt = [100, 150];
const steps = 90;
for (let i = 0; i <= steps; i++) {
const u = i / steps;
const deg = 200 + u * 140;
const finger = Math.abs(Math.sin(Math.PI * 5 * u)) ** 0.55;
const reach = 0.72 + 0.28 * Math.sin(Math.PI * u);
pts.push(onCircle(base[0], base[1], 38 + 108 * finger * reach, deg));
}
// The stem, out of the bottom of the fan.
pts.push([108, 156], [106, 200], [96, 200], [93, 156]);
return polyPath(clockwise(pts.map(([x, y]) => [Math.round(x * 100) / 100, Math.round(y * 100) / 100] as Pt)));
}
/** A monstera leaf: a broad heart with its slits cut in from the edge towards the midrib. */
function leafMonstera(): string {
const pts: Pt[] = [];
const slits = [62, 92, 122, 238, 268, 298];
const steps = 240;
for (let i = 0; i < steps; i++) {
const deg = (360 / steps) * i;
const t = (deg * Math.PI) / 180;
// The heart curve, with its notch at the top where the stalk joins.
const x = 16 * Math.sin(t) ** 3;
const y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
const edge: Pt = [50 + x * 3, 48 - y * 3];
const slit = slits.find((s) => Math.abs(deg - s) < 0.75);
if (slit !== undefined) {
// In towards the middle and back out: a cut two scissor strokes wide.
pts.push(edge);
pts.push([50 + (edge[0] - 50) * 0.42, 52 + (edge[1] - 52) * 0.42]);
} else {
pts.push(edge);
}
}
return polyPath(clockwise(pts.map(([x, y]) => [Math.round(x * 100) / 100, Math.round(y * 100) / 100] as Pt)));
}
interface Branch {
from: Pt;
deg: number;
length: number;
width: number;
}
/**
* Coral, grown: stubby branches with round ends, splitting into two or three
* that lean apart, from a few stems at the foot. Seeded, so the same coral
* every time.
*/
function coral(seed: number, depth: number, spread: number, stems: number): string {
const rnd = seeded(seed);
const parts: string[] = [];
const grow = (b: Branch, level: number) => {
const bend = (rnd() - 0.5) * 24;
const spine: Pt[] = [];
for (let i = 0; i <= 8; i++) spine.push(onCircle(b.from[0], b.from[1], b.length * (i / 8), b.deg + bend * (i / 8)));
const tipWidth = b.width * 0.82;
parts.push(smoothPath(taper(spine, (t) => b.width + (tipWidth - b.width) * t)));
const end = spine[spine.length - 1];
// A round end, the way scissors cut a finger of paper.
parts.push(circle(end[0], end[1], tipWidth / 2, tipWidth / 2));
if (level >= depth) return;
const kids = rnd() < 0.4 ? 3 : 2;
for (let k = 0; k < kids; k++) {
const lean = (k - (kids - 1) / 2) * spread + (rnd() - 0.5) * 14;
const next = {
from: end,
deg: b.deg + bend + lean,
length: b.length * (0.74 + rnd() * 0.2),
width: tipWidth * 0.9,
};
grow(next, level + 1);
}
};
for (let i = 0; i < stems; i++) {
const deg = -90 + (i - (stems - 1) / 2) * 30 + (rnd() - 0.5) * 8;
grow({ from: [100 + (i - (stems - 1) / 2) * 8, 200], deg, length: 48 + rnd() * 10, width: 19 }, 0);
}
return parts.join('');
}
/** A frond of weed: a swaying stem with blades along it, alternately left and right. */
function seaweed(): string {
const spine: Pt[] = [];
for (let i = 0; i <= 30; i++) {
const t = i / 30;
spine.push([50 + 12 * Math.sin(t * Math.PI * 2.2), 200 - t * 196]);
}
const parts = [smoothPath(taper(spine, (t) => 9 - t * 6))];
for (let i = 3; i < 28; i += 3) {
const at = spine[i];
const side = i % 2 === 0 ? 1 : -1;
const tip: Pt = [at[0] + side * (34 - i * 0.6), at[1] - 26 + i * 0.2];
parts.push(smoothPath(leafAlong(at, tip, 13 - i * 0.2, 0.4 * side)));
}
return parts.join('');
}
export const CUTOUT_PATHS = {
'leaf-palm': leafPalm(),
'leaf-oak': leafOak(),
'leaf-long': leafLong(),
'leaf-monstera': leafMonstera(),
'coral-1': coral(3, 3, 40, 2),
'coral-2': coral(19, 3, 34, 3),
seaweed: seaweed(),
'star-organic': organicStar(),
'sun-cutout': sunCutout(),
'organic-1': organic(2, 0.07),
'organic-2': organic(9, 0.09),
'organic-3': organic(31, 0.06),
} as const;
@@ -0,0 +1,239 @@
import type { BookEdge } from '@trek/shared';
import { type Pt, seeded, signedArea } from './shapeDraw';
/**
* Cut edges: an outline replaced by pinking-shear teeth, scallops, a postage
* stamp's perforation, a wave, a torn sheet or the soft deckle of handmade
* paper.
*
* ── How it is cut ────────────────────────────────────────────────────────
*
* The outline is first flattened into points in millimetres and split at its
* corners into runs: a rectangle is four, a circle one. Each run gets a whole
* number of teeth, stretched a little to fit, so a tooth never ends half way
* along a side and every corner lands on the outline itself. Then each point
* is pushed inwards along the outline's normal by the profile of the edge.
*
* Inwards, always: the cut bites into the shape and never past its frame, so
* what the editor snaps is still where the shape ends.
*
* Millimetres rather than the 0..100 box, because a tooth is a physical size.
* A stamp's perforation is a few millimetres whatever the stamp, and a frame
* twice as wide gets twice the holes, not holes twice as wide.
*/
/** The most points an edge draws: a spread-wide strip at a fine edge stays under it. */
const MAX_POINTS = 3000;
/** Under this many degrees between two segments the outline is a curve, past it a corner. */
const CORNER_DEG = 24;
const r2 = (n: number) => Math.round(n * 100) / 100;
/** The outline as points, curves flattened; only the first subpath, which is the outline of the shapes that take an edge. */
export function flattenPath(d: string, step = 0.5): Pt[] {
const nums = (d.match(/-?\d*\.?\d+(?:e-?\d+)?/g) ?? []).map(Number);
const cmds = d.match(/[MLCQZ]/g) ?? [];
const pts: Pt[] = [];
let i = 0;
let cx = 0;
let cy = 0;
for (const cmd of cmds) {
if (cmd === 'Z') break;
if (cmd === 'M' || cmd === 'L') {
cx = nums[i++];
cy = nums[i++];
pts.push([cx, cy]);
continue;
}
const c = nums.slice(i, i + (cmd === 'Q' ? 4 : 6));
i += c.length;
const [x, y] = [c[c.length - 2], c[c.length - 1]];
const chord = Math.hypot(x - cx, y - cy) + Math.hypot(c[0] - cx, c[1] - cy);
const n = Math.max(4, Math.min(80, Math.ceil(chord / step)));
for (let k = 1; k <= n; k++) {
const t = k / n;
const u = 1 - t;
if (cmd === 'Q') {
pts.push([u * u * cx + 2 * u * t * c[0] + t * t * x, u * u * cy + 2 * u * t * c[1] + t * t * y]);
} else {
pts.push([
u * u * u * cx + 3 * u * u * t * c[0] + 3 * u * t * t * c[2] + t * t * t * x,
u * u * u * cy + 3 * u * u * t * c[1] + 3 * u * t * t * c[3] + t * t * t * y,
]);
}
}
cx = x;
cy = y;
}
// The closing point repeats the first on most outlines; one is enough.
const out = pts.filter((p, k) => k === 0 || Math.hypot(p[0] - pts[k - 1][0], p[1] - pts[k - 1][1]) > 1e-6);
const first = out[0];
const last = out[out.length - 1];
if (first && last && out.length > 1 && Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6) out.pop();
return out;
}
function turnAt(prev: Pt, here: Pt, next: Pt): number {
const a = Math.atan2(here[1] - prev[1], here[0] - prev[0]);
const b = Math.atan2(next[1] - here[1], next[0] - here[0]);
let d = ((b - a) * 180) / Math.PI;
while (d > 180) d -= 360;
while (d < -180) d += 360;
return Math.abs(d);
}
/** The outline split at its corners into runs, each from one corner to the next; a smooth ring is one run. */
export function outlineRuns(ring: readonly Pt[]): Pt[][] {
const n = ring.length;
const corners: number[] = [];
for (let k = 0; k < n; k++) {
if (turnAt(ring[(k - 1 + n) % n], ring[k], ring[(k + 1) % n]) > CORNER_DEG) corners.push(k);
}
if (!corners.length) return [[...ring, ring[0]]];
return corners.map((start, c) => {
const end = corners[(c + 1) % corners.length];
const run: Pt[] = [];
for (let k = start; ; k = (k + 1) % n) {
run.push(ring[k]);
if (k === end && run.length > 1) break;
}
return run;
});
}
/** A run resampled every `step` along its length, both ends kept. */
function resample(run: readonly Pt[], count: number): { pts: Pt[]; length: number } {
const lengths = [0];
for (let k = 1; k < run.length; k++) {
lengths.push(lengths[k - 1] + Math.hypot(run[k][0] - run[k - 1][0], run[k][1] - run[k - 1][1]));
}
const length = lengths[lengths.length - 1];
const pts: Pt[] = [];
let seg = 1;
for (let k = 0; k <= count; k++) {
const s = (length * k) / count;
while (seg < run.length - 1 && lengths[seg] < s) seg++;
const s0 = lengths[seg - 1];
const s1 = lengths[seg];
const t = s1 > s0 ? (s - s0) / (s1 - s0) : 0;
const a = run[seg - 1];
const b = run[seg];
pts.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
}
return { pts, length };
}
/** How far in an edge cuts at a point `t` teeth along (t in 0..1 within one tooth), as a share of its depth. */
type Profile = (t: number, index: number) => number;
/** Smooth noise along a run: values at whole steps, eased between. */
function noise(rnd: () => number, n: number): (x: number) => number {
const values = Array.from({ length: n + 2 }, () => rnd());
return (x) => {
const k = Math.floor(x);
const f = x - k;
const e = f * f * (3 - 2 * f);
return values[k % values.length] * (1 - e) + values[(k + 1) % values.length] * e;
};
}
interface EdgeSpec {
/** An irregular edge eases out towards a corner, or each corner grows a spike where two tears meet. */
eases?: boolean;
/** Teeth per tooth length: how many points one tooth is drawn with. */
samples: number;
/** Depth of the cut, as a share of the edge size. */
depth: number;
profile: (rnd: () => number, teeth: number) => Profile;
}
/*
* Each profile is 0 at the ends of a tooth, so corners stay on the outline,
* and at most 1 inside it.
*/
const SPECS: Record<Exclude<BookEdge, 'straight'>, EdgeSpec> = {
// Pinking shears: a point at each end, a valley in the middle.
zigzag: { samples: 2, depth: 0.5, profile: () => (t) => (Math.abs(t - 0.5) < 0.01 ? 1 : 0) },
// Half circles bulging out from each end of a tooth, meeting in a valley at its middle.
scallop: {
samples: 12,
depth: 0.5,
profile: () => (t) => 1 - Math.sqrt(Math.max(0, 1 - (2 * Math.min(t, 1 - t)) ** 2)),
},
// The edge runs through a row of round holes: a half circle out of the middle of each tooth.
perforated: {
samples: 16,
depth: 0.3,
profile: () => (t) => {
const r = 0.3;
const u = t - 0.5;
return Math.abs(u) < r ? Math.sqrt(r * r - u * u) / r : 0;
},
},
wavy: { samples: 12, depth: 0.35, profile: () => (t) => 0.5 - 0.5 * Math.cos(Math.PI * 2 * t) },
// Torn paper: an uneven slope with sharp little teeth on it.
torn: {
eases: true,
samples: 3,
depth: 0.8,
profile: (rnd, teeth) => {
const slow = noise(rnd, teeth + 4);
return (t, index) => 0.55 * slow((index + t) / 3) + 0.45 * rnd();
},
},
// Handmade paper: soft, slow, never sharp.
deckle: {
eases: true,
samples: 6,
depth: 0.5,
profile: (rnd, teeth) => {
const slow = noise(rnd, teeth + 4);
const fine = noise(rnd, teeth * 3 + 6);
return (t, index) => 0.7 * slow(index + t) + 0.3 * fine((index + t) * 3);
},
},
};
/**
* The outline `d` (millimetres) with its edge cut, `size` millimetres per
* tooth. `seed` decides how a torn or deckled edge tears; the element id is
* the usual one, so the same element tears the same way every time.
*/
export function edgedPath(d: string, edge: BookEdge, size: number, seed = 1): string {
if (edge === 'straight' || size <= 0) return d;
const ring = flattenPath(d);
if (ring.length < 3) return d;
// Inwards is to the right of travel on a ring wound clockwise on screen.
const inward = signedArea(ring) >= 0 ? 1 : -1;
const spec = SPECS[edge];
const rnd = seeded(seed);
const runs = outlineRuns(ring);
const perimeter = runs.reduce((sum, run) => sum + resample(run, 1).length, 0);
// Coarser teeth past the point cap, rather than a path nobody can render.
const tooth = Math.max(size, (perimeter * spec.samples) / MAX_POINTS);
const depth = tooth * spec.depth;
const out: Pt[] = [];
for (const run of runs) {
const { length } = resample(run, 1);
const teeth = Math.max(1, Math.round(length / tooth));
const { pts } = resample(run, teeth * spec.samples);
const profile = spec.profile(rnd, teeth);
for (let k = 0; k < pts.length - 1; k++) {
const a = pts[Math.max(0, k - 1)];
const b = pts[Math.min(pts.length - 1, k + 1)];
const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
const nx = (-(b[1] - a[1]) / len) * inward;
const ny = ((b[0] - a[0]) / len) * inward;
const index = Math.floor(k / spec.samples);
const t = (k % spec.samples) / spec.samples;
const fromEnd = Math.min(k, pts.length - 1 - k) / spec.samples;
const ease = spec.eases && runs.length > 1 ? Math.min(1, fromEnd / 1.5) : 1;
const cut = k === 0 ? 0 : depth * profile(t, index) * ease;
const p = pts[k];
out.push([p[0] + nx * cut, p[1] + ny * cut]);
}
}
return `M${out.map(([x, y]) => `${r2(x)} ${r2(y)}`).join('L')}Z`;
}
+349
View File
@@ -0,0 +1,349 @@
import type { BOOK_SHAPES_MORE } from '@trek/shared';
import {
type Pt,
anticlockwise,
arcPoints,
arcTo,
clockwise,
fmt,
onCircle,
polyPath,
seeded,
smoothPath,
} from './shapeDraw';
import { K, circle, roundRect, scallop } from './shapePrimitives';
import { CUTOUT_PATHS } from './shapes-cutouts';
import { ORNAMENT_PATHS } from './shapes-ornaments';
/**
* The second shelf of the shape table (book-shapes-more.ts lists the ids).
*
* Each is drawn at the size its arithmetic is easiest in and normalised to
* the 0..100 box by the table, like every other shape. What a shape looks
* like at its natural proportions is in `BOOK_SHAPE_ASPECT` (shared), which is
* what the panel places it at and what its tile is drawn in.
*
* The rules of the first shelf hold here too (see shapes.ts): one fill, every
* part wound clockwise so overlapping parts join, holes only in the shapes
* listed in `HOLED_SHAPES`, and nothing thin enough to vanish in print.
*/
type MoreId = (typeof BOOK_SHAPES_MORE)[number];
type Own = Exclude<MoreId, keyof typeof CUTOUT_PATHS | keyof typeof ORNAMENT_PATHS>;
/** A semicircle over a base line, left foot to right foot, as cubics: the head of an arch. */
function head(x0: number, x1: number, y: number): string {
const r = (x1 - x0) / 2;
const c = x0 + r;
return `C${x0} ${y - r * K} ${c - r * K} ${y - r} ${c} ${y - r}C${c + r * K} ${y - r} ${x1} ${y - r * K} ${x1} ${y}`;
}
/** A half ring over a base line: one band of a rainbow. */
function band(cx: number, base: number, outer: number, inner: number): string {
return `M${cx - outer} ${base}${arcTo(cx, base, outer, 180, 360)}L${cx + inner} ${base}${arcTo(cx, base, inner, 360, 180)}Z`;
}
/**
* A perforated outline, as a sheet of stamps is torn: the edge runs through a
* row of round holes, so it bites a half circle out every `pitch`.
*/
function perforate(ring: readonly Pt[], pitch: number, radius: number): string {
const out: Pt[] = [];
const n = ring.length;
for (let i = 0; i < n; i++) {
const a = ring[i];
const b = ring[(i + 1) % n];
const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
const holes = Math.max(1, Math.round(len / pitch));
const step = len / holes;
const ux = (b[0] - a[0]) / len;
const uy = (b[1] - a[1]) / len;
// Inward is to the right of the direction of travel on a clockwise ring.
const nx = -uy;
const ny = ux;
out.push(a);
for (let h = 0; h < holes; h++) {
const mid = step * (h + 0.5);
for (let s = 0; s <= 8; s++) {
const ang = Math.PI * (s / 8);
const along = mid - radius * Math.cos(ang);
const depth = radius * Math.sin(ang);
out.push([a[0] + ux * along + nx * depth, a[1] + uy * along + ny * depth]);
}
}
}
return polyPath(out);
}
/** A ring of points around a circle, for edges cut along one. */
const circleRing = (cx: number, cy: number, r: number, n: number) => arcPoints([cx, cy], r, [-90, 270], n).slice(0, n);
/** A stamp cut round: a disc whose edge runs through a ring of holes. */
// One hole on every side of a fine polygon: the pitch is the side itself.
const perforatedDisc = (holes: number) => perforate(circleRing(50, 50, 50, holes), Infinity, 2.9);
/** An arrow bent along a circle (its centre and radius): a band between two arcs with a head at the end. */
function arcArrow(
[cx, cy, r]: [number, number, number],
thick: number,
[a0, a1]: [number, number],
head: { length: number; wing: number }
): string {
const ro = r + thick / 2;
const ri = r - thick / 2;
const dir = Math.sign(a1 - a0);
// The head starts short of the end of the arc and points along it.
const aEnd = a1 - (dir * ((head.length / r) * 180)) / Math.PI;
const wing = thick * head.wing;
const at = (rad: number, deg: number) => fmt(onCircle(cx, cy, rad, deg));
return (
`M${at(ro, a0)}${arcTo(cx, cy, ro, a0, aEnd)}L${at(r + wing, aEnd)}L${at(r, a1)}L${at(r - wing, aEnd)}` +
`L${at(ri, aEnd)}${arcTo(cx, cy, ri, aEnd, a0)}Z`
);
}
/** A spiky outline, irregular on purpose: what a shout looks like in a comic. */
function shout(): string {
const rnd = seeded(7);
const pts: Pt[] = [];
const spikes = 13;
for (let i = 0; i < spikes; i++) {
const a = -90 + (360 / spikes) * i;
// The spike at about seven o'clock is the tail, long and pointing down.
const tail = i === 8;
const outer = tail ? 66 : 47 + rnd() * 7;
pts.push(onCircle(50, 50, outer, a + (tail ? -6 : 0)));
pts.push(onCircle(50, 50, 33 + rnd() * 5, a + 360 / spikes / 2));
}
return polyPath(clockwise(pts));
}
/** A torn strip of paper: straight-ish ends, both long edges torn. */
function tornStrip(): string {
const rnd = seeded(23);
const top: Pt[] = [];
const bottom: Pt[] = [];
for (let x = 0; x <= 200; x += 5) {
top.push([x, 4 + rnd() * 6 + (rnd() < 0.2 ? 3 : 0)]);
bottom.push([x, 46 - rnd() * 6 - (rnd() < 0.2 ? 3 : 0)]);
}
return polyPath(clockwise([...top, ...bottom.reverse()]));
}
/** A band whose two long edges are the same wave, so it keeps one width. */
function wavyBand(): string {
const pts: Pt[] = [];
const wave = (x: number) => 14 * Math.sin((x / 200) * Math.PI * 4);
for (let x = 0; x <= 200; x += 5) pts.push([x, 20 + wave(x)]);
for (let x = 200; x >= 0; x -= 5) pts.push([x, 56 + wave(x)]);
return smoothPath(clockwise(pts), 0, new Set([40, 41, 81]));
}
/** A curved banner: an arc of a band with its ends cut into swallow tails. */
function ribbonArc(): string {
const cx = 100;
const cy = 260;
const ro = 240;
const ri = 196;
const mid = (ro + ri) / 2;
const a0 = 248;
const a1 = 292;
const at = (rad: number, deg: number) => fmt(onCircle(cx, cy, rad, deg));
return (
`M${at(ro, a0)}${arcTo(cx, cy, ro, a0, a1)}L${at(mid, a1 - 3.5)}L${at(ri, a1)}` +
`${arcTo(cx, cy, ri, a1, a0)}L${at(mid, a0 + 3.5)}Z`
);
}
/** A star with its tips and valleys rounded off: softer, friendlier, a sticker's star. */
function roundedStar(points: number, inner: number, round: number): string {
const pts: Pt[] = [];
for (let i = 0; i < points * 2; i++) {
pts.push(onCircle(50, 50, i % 2 === 0 ? 50 : 50 * inner, -90 + (180 / points) * i));
}
const n = pts.length;
let d = '';
for (let i = 0; i < n; i++) {
const prev = pts[(i - 1 + n) % n];
const here = pts[i];
const next = pts[(i + 1) % n];
const f = i % 2 === 0 ? round : round * 0.6;
const a: Pt = [here[0] + (prev[0] - here[0]) * f, here[1] + (prev[1] - here[1]) * f];
const b: Pt = [here[0] + (next[0] - here[0]) * f, here[1] + (next[1] - here[1]) * f];
d += `${i === 0 ? 'M' : 'L'}${fmt(a)}Q${fmt(here)} ${fmt(b)}`;
}
return `${d}Z`;
}
/** An eight-ray twinkle: four long rays and four short, every side drawn in. */
function twinkle(): string {
const tip = (i: number) => onCircle(50, 50, i % 2 === 0 ? 50 : 27, -90 + 45 * i);
let d = `M${fmt(tip(0))}`;
for (let i = 0; i < 8; i++) {
d += `Q${fmt(onCircle(50, 50, 7, -90 + 45 * i + 22.5))} ${fmt(tip(i + 1))}`;
}
return `${d}Z`;
}
/** A sun's rays as wedges between gaps, from a small hub, as a sunburst background is printed. */
function sunburst(rays: number): string {
const pts: Pt[] = [];
const half = 360 / rays / 4;
for (let i = 0; i < rays; i++) {
const a = -90 + (360 / rays) * i;
pts.push(onCircle(50, 50, 5, a - half * 1.6));
pts.push(onCircle(50, 50, 50, a - half));
pts.push(onCircle(50, 50, 50, a + half));
pts.push(onCircle(50, 50, 5, a + half * 1.6));
}
return polyPath(clockwise(pts));
}
/** A rosette: a frilled disc over two tails cut into swallow points. */
function rosette(): string {
const disc = scallop(18, 0.07);
// The tails hang from under the disc, splayed, each cut into a V.
const left = polyPath(
clockwise([
[34, 62],
[52, 70],
[38, 132],
[29, 118],
[17, 124],
])
);
const right = polyPath(
clockwise([
[48, 70],
[66, 62],
[83, 124],
[71, 118],
[62, 132],
])
);
return `${disc}${left}${right}`;
}
/** Two hearts, the smaller one tucked in front and tilted, for a page about two people. */
function heartPair(): string {
const heart = (cx: number, cy: number, s: number, turn: number): string => {
const raw: Pt[] = [];
for (let i = 0; i < 48; i++) {
const t = (i / 48) * Math.PI * 2;
// The classic heart curve, which has a real point and two round lobes.
const x = 16 * Math.sin(t) ** 3;
const y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
const a = (turn * Math.PI) / 180;
raw.push([cx + s * (x * Math.cos(a) - y * Math.sin(a)), cy + s * (x * Math.sin(a) + y * Math.cos(a))]);
}
return smoothPath(clockwise(raw), 0.2, new Set([0, 24]));
};
return `${heart(42, 46, 2.5, -12)}${heart(84, 74, 1.7, 14)}`;
}
/** A plump heart: round lobes, a shallow notch and a soft point. */
const HEART_ROUND =
'M50 96C44 92 0 68 0 34C0 14 14 2 30 2C40 2 47 8 50 15C53 8 60 2 70 2C86 2 100 14 100 34C100 68 56 92 50 96Z';
/** A rectangle whose sides bow out a little and whose corners are round: an old television. */
const CUSHION =
'M20 0C40 -4 60 -4 80 0C92 2 98 8 100 20C104 40 104 60 100 80C98 92 92 98 80 100' +
'C60 104 40 104 20 100C8 98 2 92 0 80C-4 60 -4 40 0 20C2 8 8 2 20 0Z';
const MORE_OWN_PATHS: Record<Own, string> = {
'arch-tall': `M0 200L0 50${head(0, 100, 50)}L100 200Z`,
'arch-pointed': 'M0 190L0 86.6C0 50.9 19.1 17.85 50 0C80.9 17.85 100 50.9 100 86.6L100 190Z',
'arch-double': `M0 160L0 50${head(0, 100, 50)}${head(100, 200, 50)}L200 160Z`,
'arch-half': `M0 160L0 100C0 ${100 - 100 * K} ${100 - 100 * K} 0 100 0L100 160Z`,
'arch-rainbow': `${band(100, 100, 100, 76)}${band(100, 100, 68, 44)}${band(100, 100, 36, 12)}`,
'stamp-rect': perforate(
[
[0, 0],
[100, 0],
[100, 124],
[0, 124],
],
11,
4
),
'stamp-circle': perforatedDisc(34),
postmark:
`${circle(50, 50, 50, 50)}${polyPath(anticlockwise(circleRing(50, 50, 43, 48)))}` +
`${circle(50, 50, 37, 37)}${polyPath(anticlockwise(circleRing(50, 50, 34, 48)))}`,
rosette: rosette(),
'scallop-circle': scallop(24, 0.075),
'badge-shield': 'M0 4Q50 18 100 4L100 52C100 78 76 93 50 100C24 93 0 78 0 52Z',
'label-tab':
'M30 0L154 0C157.31 0 160 2.69 160 6L160 74C160 77.31 157.31 80 154 80L30 80L0 54L0 26Z' +
polyPath(anticlockwise(circleRing(24, 40, 7, 24))),
'ticket-stub':
'M0 0L141 0C141 5 145 9 150 9C155 9 159 5 159 0L200 0L200 90L159 90C159 85 155 81 150 81' +
'C145 81 141 85 141 90L0 90Z',
'sunburst-12': sunburst(12),
'sunburst-24': sunburst(24),
'ribbon-ends':
'M30 0L170 0L170 40L30 40Z' +
polyPath(
clockwise([
[0, 14],
[44, 14],
[44, 54],
[0, 54],
[12, 34],
])
) +
polyPath(
clockwise([
[156, 14],
[200, 14],
[188, 34],
[200, 54],
[156, 54],
])
),
'ribbon-arc': ribbonArc(),
'wavy-band': wavyBand(),
'torn-strip': tornStrip(),
'bubble-shout': shout(),
'bubble-side': `${roundRect(20, 16, 0, 84, 70)}${polyPath(
clockwise([
[24, 36],
[24, 60],
[0, 70],
])
)}`,
'bubble-capsule': `${roundRect(35, 0, 0, 200, 70)}${polyPath(
clockwise([
[52, 60],
[84, 60],
[40, 96],
])
)}`,
'arrow-curve': arcArrow([100, 170, 140], 16, [222, 318], { length: 34, wing: 1.55 }),
'arrow-circle': arcArrow([50, 50, 40], 14, [-70, 225], { length: 18, wing: 1.3 }),
'arrow-notched': 'M0 25L130 25L130 0L200 50L130 100L130 75L0 75L22 50Z',
'arrow-thin': 'M0 47L168 47L160 32L200 50L160 68L168 53L0 53Z',
'heart-round': HEART_ROUND,
'heart-pair': heartPair(),
'star-rounded': roundedStar(5, 0.46, 0.2),
'star-twinkle': twinkle(),
'flower-8': scallop(8, 0.34),
'frame-notched':
'M12 0L88 0C88 6.63 93.37 12 100 12L100 88C93.37 88 88 93.37 88 100L12 100' +
'C12 93.37 6.63 88 0 88L0 12C6.63 12 12 6.63 12 0Z',
'frame-chamfer': 'M14 0L86 0L100 14L100 86L86 100L14 100L0 86L0 14Z',
'frame-cushion': CUSHION,
};
export const MORE_SHAPE_PATHS: Record<MoreId, string> = {
...MORE_OWN_PATHS,
...CUTOUT_PATHS,
...ORNAMENT_PATHS,
};
@@ -0,0 +1,142 @@
import { type Pt, clockwise, leafAlong, onCircle, smoothPath, taper } from './shapeDraw';
/**
* Ornaments a title is set between: a scroll, a laurel wreath, a fleuron and
* a corner flourish. Each is drawn as swelling strokes and leaves, wound alike
* so the parts join into one fill.
*
* The strokes taper to a point rather than ending square, and nothing in them
* is thinner than about one unit in a hundred, which at the size a divider is
* set (60 mm and up) is a line a printer still holds.
*/
/** A spiral's centre line, from its outer end inwards, `turns` times round. */
interface Spiral {
/** The centre it winds round. */
at: Pt;
/** The radius it starts at and the one it ends at. */
from: number;
to: number;
/** Where it starts, in degrees clockwise from three o'clock. */
deg: number;
turns: number;
/** 1 winds clockwise, -1 the other way. */
dir: 1 | -1;
}
function spiral({ at: [cx, cy], from: r0, to: r1, deg: deg0, turns, dir }: Spiral): Pt[] {
const n = Math.round(24 * turns);
return Array.from({ length: n + 1 }, (_, i) => {
const t = i / n;
return onCircle(cx, cy, r0 + (r1 - r0) * t, deg0 + dir * 360 * turns * t);
});
}
/** A stroke that swells in the middle and thins to both ends, the way a pen draws a flourish. */
const swell =
(thick: number, end = 0.9) =>
(t: number) =>
end + (thick - end) * Math.sin(Math.PI * t) ** 0.9;
/** One half of the scroll, drawn to the right of the middle; the left is its mirror. */
function scrollHalf(dir: 1 | -1): string[] {
const x = (v: number) => 100 + dir * v;
const arm: Pt[] = [];
for (let i = 0; i <= 24; i++) {
const t = i / 24;
arm.push([x(9 + t * 64), 20 - 7 * Math.sin(t * Math.PI)]);
}
const curl = spiral({ at: [x(82), 22], from: 9, to: 2.5, deg: 270, turns: 0.85, dir });
const line = [...arm, ...curl.slice(1)];
const leaf = leafAlong([x(40), 16], [x(54), 4], 6, 0.6 * dir);
return [smoothPath(taper(line, swell(4.2)), 0.05), smoothPath(leaf)];
}
/** A horizontal scroll: a lozenge in the middle and an arm curling away to each side. */
function flourishScroll(): string {
const lozenge: Pt[] = [
[100, 13],
[108, 20],
[100, 27],
[92, 20],
];
return [smoothPath(lozenge, 0.6, new Set([0, 1, 2, 3])), ...scrollHalf(1), ...scrollHalf(-1)].join('');
}
/** One branch of a laurel: a stem round the circle with paired leaves leaning forwards. */
function laurelBranch(dir: 1 | -1): string[] {
const cx = 100;
const cy = 96;
const r = 82;
const from = dir === 1 ? 98 : 82;
const to = dir === 1 ? 228 : -48;
const stem: Pt[] = Array.from({ length: 31 }, (_, i) => onCircle(cx, cy, r, from + ((to - from) * i) / 30));
const parts = [smoothPath(taper(stem, (t) => 3.6 - t * 2.4))];
const leaves = 9;
for (let i = 0; i < leaves; i++) {
const deg = from + ((to - from) * (i + 0.6)) / (leaves + 0.4);
const at = onCircle(cx, cy, r, deg);
const size = 30 - i * 1.4;
// Each leaf leans along the stem, one outside the circle and one inside it.
const ahead = deg + dir * 14;
parts.push(smoothPath(leafAlong(at, onCircle(cx, cy, r + size * 0.62, ahead), size * 0.36, 0.3)));
if (i < leaves - 1)
parts.push(smoothPath(leafAlong(at, onCircle(cx, cy, r - size * 0.55, ahead), size * 0.32, -0.3)));
}
// A last leaf at the very tip, along the stem.
const tip = onCircle(cx, cy, r, to);
parts.push(smoothPath(leafAlong(tip, onCircle(cx, cy, r, to + dir * 12), 9, 0)));
return parts;
}
/** A laurel wreath, open at the top, its two branches crossing at the foot. */
const laurel = () => [...laurelBranch(1), ...laurelBranch(-1)].join('');
/** The Aldus leaf: a heart-shaped leaf on a stem that curls back on itself. */
function fleuron(): string {
const leaf: Pt[] = [];
const turn = (-32 * Math.PI) / 180;
for (let i = 0; i < 48; i++) {
const t = (i / 48) * Math.PI * 2;
const hx = 16 * Math.sin(t) ** 3;
const hy = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
leaf.push([
96 + 3.2 * (hx * Math.cos(turn) - hy * Math.sin(turn)),
62 + 3.2 * (hx * Math.sin(turn) + hy * Math.cos(turn)),
]);
}
// The stem leaves from the notch of the heart, arches up and curls back.
const notch = leaf[0];
const stem: Pt[] = [
...Array.from({ length: 14 }, (_, i) => {
const t = i / 13;
return [notch[0] + (36 - notch[0]) * t, notch[1] + (22 - notch[1]) * t - Math.sin(t * Math.PI) * 12] as Pt;
}),
...spiral({ at: [26, 34], from: 12, to: 3, deg: 270, turns: 0.9, dir: -1 }).slice(1),
];
return smoothPath(clockwise(leaf), 0.15, new Set([0, 24])) + smoothPath(taper(stem, swell(6, 1.4)), 0.05);
}
/** A corner: two arms along the edges from a curl in the corner, each ending in a small scroll. */
function cornerFlourish(): string {
const arm = (flip: boolean): string[] => {
const p = ([a, b]: Pt): Pt => (flip ? [b, a] : [a, b]);
const line: Pt[] = [];
for (let i = 0; i <= 20; i++) {
const t = i / 20;
line.push(p([18 + t * 64, 10 + 5 * Math.sin(t * Math.PI)]));
}
const curl = spiral({ at: [90, 18], from: 8, to: 2.4, deg: 270, turns: 0.8, dir: 1 }).map(p);
const leaf = leafAlong(p([44, 13]), p([56, 27]), 6, 0.4);
return [smoothPath(taper([...line, ...curl.slice(1)], swell(4)), 0.05), smoothPath(leaf)];
};
const knot = spiral({ at: [17, 17], from: 10, to: 3, deg: 225, turns: 0.9, dir: 1 });
return [...arm(false), ...arm(true), smoothPath(taper(knot, swell(4.4, 1.2)), 0.05)].join('');
}
export const ORNAMENT_PATHS = {
'flourish-scroll': flourishScroll(),
laurel: laurel(),
fleuron: fleuron(),
'corner-flourish': cornerFlourish(),
} as const;
+34 -121
View File
@@ -1,4 +1,6 @@
import type { BookShapeId } from '@trek/shared'
import { K, circle, polygon, r2, roundRect, scallop, star } from './shapePrimitives'
import { MORE_SHAPE_PATHS } from './shapes-more'
/**
* Every shape Studio can draw, as a path on a 0..100 square.
@@ -35,121 +37,6 @@ import type { BookShapeId } from '@trek/shared'
* 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.
*
@@ -284,6 +171,10 @@ export const SHAPE_PATHS: Record<BookShapeId, string> = {
'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 second shelf (shapes-more.ts): arches, cut-outs, stamps, ribbons,
// drawn arrows, hearts, frames and ornaments.
...MORE_SHAPE_PATHS,
}
/**
@@ -430,7 +321,7 @@ export function unitPath(path: string): string {
* 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 const HOLED_SHAPES = new Set<BookShapeId>(['gear', 'postmark', 'label-tab'])
export interface ShapeGroup {
/** i18n key under `journey.studio.shapeGroup`. */
@@ -457,16 +348,18 @@ export const SHAPE_GROUPS: ShapeGroup[] = [
},
{
id: 'stars',
shapes: ['star-4', 'star-5', 'star-6', 'star-8', 'star-12', 'burst', 'seal', 'sparkle'],
shapes: ['star-4', 'star-5', 'star-6', 'star-8', 'star-12', 'burst', 'seal', 'sparkle',
'star-rounded', 'star-twinkle'],
},
{
id: 'arrows',
shapes: ['arrow-right', 'arrow-left', 'arrow-up', 'arrow-down', 'arrow-both',
'chevron-right', 'chevron-left', 'arrow-bent'],
'chevron-right', 'chevron-left', 'arrow-bent', 'arrow-curve', 'arrow-circle', 'arrow-notched', 'arrow-thin'],
},
{
id: 'speech',
shapes: ['bubble-round', 'bubble-square', 'bubble-oval', 'bubble-think'],
shapes: ['bubble-round', 'bubble-square', 'bubble-oval', 'bubble-think',
'bubble-shout', 'bubble-side', 'bubble-capsule'],
},
{
id: 'travel',
@@ -476,12 +369,27 @@ export const SHAPE_GROUPS: ShapeGroup[] = [
{
id: 'decor',
shapes: ['heart', 'flower-5', 'flower-6', 'cross', 'plus', 'gear',
'blob-1', 'blob-2', 'blob-3', 'blob-4'],
'blob-1', 'blob-2', 'blob-3', 'blob-4', 'heart-round', 'heart-pair', 'flower-8'],
},
{
id: 'banners',
shapes: ['banner-ribbon', 'banner-pennant', 'banner-bookmark', 'banner-flag'],
shapes: ['banner-ribbon', 'banner-pennant', 'banner-bookmark', 'banner-flag',
'ribbon-ends', 'ribbon-arc', 'wavy-band', 'torn-strip'],
},
// The second shelf (shapes-more.ts).
{ id: 'arches', shapes: ['arch-tall', 'arch-pointed', 'arch-double', 'arch-half', 'arch-rainbow'] },
{
id: 'cutouts',
shapes: ['leaf-palm', 'leaf-oak', 'leaf-long', 'leaf-monstera', 'coral-1', 'coral-2', 'seaweed',
'star-organic', 'sun-cutout', 'organic-1', 'organic-2', 'organic-3'],
},
{
id: 'stamps',
shapes: ['stamp-rect', 'stamp-circle', 'postmark', 'rosette', 'scallop-circle', 'badge-shield',
'label-tab', 'ticket-stub', 'sunburst-12', 'sunburst-24'],
},
{ id: 'frames', shapes: ['frame-notched', 'frame-chamfer', 'frame-cushion'] },
{ id: 'ornaments', shapes: ['flourish-scroll', 'laurel', 'fleuron', 'corner-flourish'] },
]
/**
@@ -497,4 +405,9 @@ export const FRAME_SHAPES: BookShapeId[] = [
'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',
// The second shelf: arches, stamps and the frames cut for photographs.
'arch-tall', 'arch-pointed', 'arch-double', 'arch-half', 'stamp-rect', 'stamp-circle',
'scallop-circle', 'badge-shield', 'ticket-stub', 'heart-round', 'star-rounded', 'flower-8',
'frame-notched', 'frame-chamfer', 'frame-cushion', 'organic-1', 'organic-2', 'organic-3',
'star-organic', 'sun-cutout', 'bubble-side', 'bubble-capsule',
]
@@ -115,6 +115,7 @@ export function exportSpread(spread: BookSpread, page: BookPageSetup, name?: str
if (typeof out.size === 'number') out.size = round4(out.size / PH)
if (typeof out.radius === 'number') out.radius = round4(out.radius / PW)
if (typeof out.strokeWidth === 'number') out.strokeWidth = round4(out.strokeWidth / PW)
if (typeof out.edgeSize === 'number') out.edgeSize = round4(out.edgeSize / PW)
// The design, not the pictures.
if (out.kind === 'photo') out.photoId = null
/*
@@ -168,6 +169,7 @@ export function importSpread(raw: unknown, page: BookPageSetup): BookSpread | nu
if (typeof scaled.size === 'number') scaled.size = round2(scaled.size * PH)
if (typeof scaled.radius === 'number') scaled.radius = round2(scaled.radius * PW)
if (typeof scaled.strokeWidth === 'number') scaled.strokeWidth = round2(scaled.strokeWidth * PW)
if (typeof scaled.edgeSize === 'number') scaled.edgeSize = round2(scaled.edgeSize * PW)
/*
* A map arrives with no source, whatever the file says.
*