feat(studio): photo look with border, hard shadow, zoom, mirror, adjustments, duotone and cutout

Photos get a look beyond crop, mask and frame style, in Studio and for the
assistant alike:

- border (width and colour, following the mask or the corner radius), a hard
  offset shadow and a die-cut cutout edge, all flat vector shapes in print
- zoom 1 to 4 about the focal point and a left to right mirror
- brightness, contrast, saturation and warmth, and a duotone; these are
  filters, labelled raster in print in the inspector
- the print resolution of the selected photo in the inspector, with a warning
  under 200 dpi, measured from the original

PhotoView moves out of SpreadView into its own file and uses per instance
SVG ids, so a spread drawn twice keeps its clips and filters apart. The style
operation takes the look, describe-spread lists it, the dpi and crop findings
account for zoom and mirror, and a new raster_effect finding notes filters on
a large photo. BOOK_SCHEMA_REV goes to 6.
This commit is contained in:
Maurice
2026-10-23 20:57:00 +02:00
parent 9b8626622f
commit 7a7876b9f4
87 changed files with 3077 additions and 245 deletions
+430
View File
@@ -0,0 +1,430 @@
import { photoLookOf, type BookFrame, type BookPhotoElement, type BookShapeId, type PhotoLook } from '@trek/shared';
import type { CSSProperties, ReactNode } from 'react';
import { fontStack } from './bookFonts';
import { photoSrc } from './bookRender';
import { usePaintId } from './paint/usePaintId';
import { pictureFilter, silhouetteShadows, svgFilterMatrices, zoomPlacement } from './photo/photoLook';
import { HOLED_SHAPES, SHAPE_PATHS, scalePath, unitPath } from './shapes';
/**
* A picture on the page: possibly cut to a shape, possibly sitting in
* something, possibly wearing a look (book-photo-look.schema.ts in shared).
*
* Split out of SpreadView.tsx, which draws every kind and had no room left
* for the look. It is still the one renderer: the editor, the page
* thumbnails and the print path all draw a photo through this.
*
* The mask and the decoration are independent on purpose: a heart in a Polaroid
* is a silly thing to want and there is no reason to stop anyone wanting it, and
* keeping them separate means neither has to know about the other.
*
* ── The look, and how each part prints ───────────────────────────────────
*
* Border, hard shadow and cutout are flat shapes of one colour, so they stay
* vector in the PDF. On a rectangular frame (no mask, or a card such as a
* Polaroid around it) the cutout and the shadow are box shadows without blur,
* which follow the corner radius; on a frame cut to a shape they are that
* shape's path, drawn behind the picture. The border is drawn over the edge of
* the picture, inside the frame, so the frame stays the box the fold and trim
* checks measure. Zoom and mirror move the picture inside its clip and change
* nothing around it. Adjustments, warmth and a duotone are filters and print
* as a raster, which the inspector says.
*
* Every SVG id is per instance (usePaintId): the page view draws each spread twice,
* and two clip paths with one id cut the second picture with the first one's
* shape.
*/
/** Two decimals of a millimetre, matching what the document itself stores. */
const round2 = (n: number) => Math.round(n * 100) / 100;
const PHOTO_FILTERS: Record<string, string | undefined> = {
none: undefined,
bw: 'grayscale(1) contrast(1.05)',
warm: 'saturate(1.1) sepia(0.16)',
cool: 'saturate(1.05) hue-rotate(-8deg) brightness(1.02)',
// Faded, the way a print left in the light goes: lifted blacks, less colour.
fade: 'saturate(0.72) contrast(0.88) brightness(1.08)',
contrast: 'contrast(1.22) saturate(1.06)',
};
/**
* How much of the frame the decoration around a picture eats, as a fraction of
* the shorter side.
*
* A Polaroid's chin is the reason this is a table rather than one number: the
* bottom border is roughly three times the others, and getting that ratio wrong
* is the difference between a Polaroid and a photo with a white edge.
*/
const FRAME_INSET: Record<string, { pad: number; bottom: number }> = {
none: { pad: 0, bottom: 0 },
polaroid: { pad: 0.055, bottom: 0.17 },
white: { pad: 0.035, bottom: 0.035 },
shadow: { pad: 0, bottom: 0 },
film: { pad: 0.075, bottom: 0.075 },
tape: { pad: 0, bottom: 0 },
};
/** The frame styles that draw a card around the picture, which makes the frame's outline a rectangle. */
const CARDS = new Set(['polaroid', 'white', 'film']);
/** The cutout and the hard shadow of a frame cut to a shape: its path, grown and offset, behind the picture. */
function ShapeSilhouette({ frame, mask, look }: { frame: BookFrame; mask: BookShapeId; look: PhotoLook }) {
const { w, h } = frame;
const d = scalePath(SHAPE_PATHS[mask], w, h);
const rule = HOLED_SHAPES.has(mask) ? 'evenodd' : undefined;
const grow = look.cutout?.width ?? 0;
const path = (color: string, dx = 0, dy = 0) => (
<path
d={d}
transform={dx || dy ? `translate(${dx} ${dy})` : undefined}
fill={color}
fillRule={rule}
stroke={grow ? color : undefined}
strokeWidth={grow ? grow * 2 : undefined}
strokeLinejoin="round"
/>
);
return (
<svg
aria-hidden
width={`${w}mm`}
height={`${h}mm`}
viewBox={`0 0 ${w} ${h}`}
style={{ position: 'absolute', inset: 0, overflow: 'visible', display: 'block' }}
>
{look.shadow && <g opacity={look.shadow.alpha}>{path(look.shadow.color, look.shadow.dx, look.shadow.dy)}</g>}
{look.cutout && path(look.cutout.color)}
</svg>
);
}
/** The border: a band along the inside of the picture's edge, following its shape. */
function BorderBand({
mask,
radius,
look,
width,
height,
}: {
mask: BookShapeId | null;
radius: number;
look: PhotoLook;
width: number;
height: number;
}) {
const border = look.border;
if (!border || width <= 0 || height <= 0) return null;
if (mask && mask !== 'rect') {
// Stroked twice as wide as the band and cut by the picture's own clip, so
// exactly the inner half shows and the band follows every curve.
return (
<svg
aria-hidden
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="none"
style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block' }}
>
<path
d={scalePath(SHAPE_PATHS[mask], width, height)}
fill="none"
stroke={border.color}
strokeWidth={border.width * 2}
strokeLinejoin="round"
/>
</svg>
);
}
return (
<div
aria-hidden
style={{
position: 'absolute',
inset: 0,
borderStyle: 'solid',
borderWidth: `${border.width}mm`,
borderColor: border.color,
borderRadius: radius ? `${radius}mm` : undefined,
boxSizing: 'border-box',
}}
/>
);
}
/** The picture itself, zoomed about its focal point and mirrored where the look says so. */
function Picture({
el,
photoId,
look,
big,
print,
filterId,
}: {
el: BookPhotoElement;
photoId: number;
look: PhotoLook;
big: boolean;
print: boolean;
filterId: string | null;
}) {
const zoom = zoomPlacement(look.zoom, el.focalX, el.focalY);
const img = (
<img
src={photoSrc(photoId, big)}
alt=""
draggable={false}
// Lazy on the canvas, where a long book scrolls past; eager in print,
// where every sheet is laid out at once and a picture the browser put
// off is a picture missing from the PDF.
loading={print ? 'eager' : 'lazy'}
style={{
width: zoom?.size ?? '100%',
height: zoom?.size ?? '100%',
transform: zoom?.transform,
objectFit: el.fit,
objectPosition: `${el.focalX * 100}% ${el.focalY * 100}%`,
filter: pictureFilter(PHOTO_FILTERS[el.filter], look, filterId),
display: 'block',
}}
/>
);
if (!look.flipX) return img;
// The picture is mirrored inside a box the size of the frame, so the part
// the crop shows stays the same part and the mask is not mirrored with it.
return <div style={{ position: 'absolute', inset: 0, transform: 'scaleX(-1)' }}>{img}</div>;
}
/** What an empty frame shows while editing: a hatch, and where there is room, the instruction. */
function Hatch({ clipped, label, labelSize }: { clipped: boolean; label: ReactNode; labelSize: number }) {
return (
<div
style={{
position: 'absolute',
inset: 0,
/*
* Opaque, and that is the point.
*
* The hatch used to be laid over nothing, so an empty frame showed
* whatever was behind it and every attempt to arrange a shape *under*
* one looked like it had done nothing: the frame appeared to sit at the
* bottom of the stack no matter where it was, right up until a
* photograph landed in it and it suddenly covered things. A frame is a
* promise that a picture goes here, and a picture is not see-through.
*/
background: 'repeating-linear-gradient(45deg, rgba(0,0,0,.055) 0 6px, rgba(0,0,0,.025) 6px 12px), #ffffff', // theme-lint-disable: paper, not app chrome
// A dashed border would be cut in half lengthwise by the clip, so a
// masked placeholder shows its shape through the hatch alone.
border: clipped ? undefined : '1px dashed rgba(0,0,0,.16)',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: '2mm',
}}
>
{label && (
<span
style={{
fontFamily: fontStack('sans'),
fontSize: `${labelSize}mm`,
fontWeight: 600,
letterSpacing: '0.16em',
lineHeight: 1.5,
textAlign: 'center',
textTransform: 'uppercase',
color: 'rgba(0,0,0,.34)',
whiteSpace: 'pre-line',
userSelect: 'none',
}}
>
{label}
</span>
)}
</div>
);
}
export function PhotoView({
el,
big,
print,
dropLabel,
frameStyle,
}: {
el: BookPhotoElement;
big: boolean;
print: boolean;
dropLabel: string;
/** The positioned box every element sits in, from SpreadView. */
frameStyle: CSSProperties;
}) {
const deco = FRAME_INSET[el.frameStyle] ?? FRAME_INSET.none;
const side = Math.min(el.frame.w, el.frame.h);
// Rounded to a hundredth of a millimetre, the same precision the document
// stores. Without it a fraction of the frame lands in the CSS as
// `10.200000000000001mm`, which is not wrong but is float noise in a
// stylesheet that a person may well end up reading.
const pad = round2(deco.pad * side);
const bottom = round2(deco.bottom * side);
const clipId = usePaintId(`c-${el.id}`);
const filterRef = usePaintId(`f-${el.id}`);
// The shape the picture is cut to; a rect mask is no mask at all.
const mask = el.mask && el.mask !== 'rect' ? el.mask : null;
const clipped = mask !== null;
// An empty frame wears the frame style but none of the look: a border or a
// shadow around a hatch would read as part of the picture to come.
const empty = el.photoId == null;
const look = photoLookOf(empty ? {} : el);
const matrices = svgFilterMatrices(look);
const filterId = matrices.length ? filterRef : null;
const card = CARDS.has(el.frameStyle);
/*
* An empty frame is a template's promise: it says where a picture goes before
* anyone has chosen which, and it says it *in the frame it will wear*.
*
* This used to render on its own, ignoring frameStyle entirely, so a Polaroid
* placeholder was an ordinary dashed rectangle until a photograph landed in
* it and the chin appeared from nowhere. The two branches have been folded
* together: the surround is drawn once, and only what goes inside it differs.
*/
// In the printed book an unfilled frame is nothing at all: a hatch and an
// instruction on a page someone paid to have bound would be a defect.
if (empty && print) return null;
// The label is sized in millimetres so it scales with the zoom exactly as the
// page does, and it steps aside on a frame too small to hold it.
const labelSize = Math.max(2.4, Math.min(4.6, side * 0.085));
const roomy = side - pad * 2 > 22 && el.frame.w - pad * 2 > 34;
// A photograph lying on a page, rather than printed into it. Soft and low: a
// hard shadow reads as a UI card, not as paper. The look's own cutout and
// hard shadow join it when the frame's outline is a rectangle.
const soft = el.frameStyle === 'shadow' || el.frameStyle === 'polaroid' ? '0 1.2mm 3mm rgba(0,0,0,.22)' : null;
const boxShadows = [
...(clipped && !card ? [] : silhouetteShadows(look.shadow, look.cutout)),
...(soft ? [soft] : []),
];
const picture = (
<div
style={{
position: 'absolute',
left: `${pad}mm`,
top: `${pad}mm`,
right: `${pad}mm`,
bottom: `${bottom || pad}mm`,
overflow: 'hidden',
borderRadius: !clipped && el.radius ? `${el.radius}mm` : undefined,
clipPath: clipped ? `url(#${clipId})` : undefined,
}}
>
{el.photoId == null ? (
<Hatch clipped={clipped} label={roomy && dropLabel} labelSize={labelSize} />
) : (
<Picture el={el} photoId={el.photoId} look={look} big={big} print={print} filterId={filterId} />
)}
{!empty && (
<BorderBand
mask={el.mask}
radius={el.radius}
look={look}
width={el.frame.w - pad * 2}
height={el.frame.h - pad - (bottom || pad)}
/>
)}
</div>
);
return (
<div
style={{
...frameStyle,
background:
el.frameStyle === 'polaroid' || el.frameStyle === 'white'
? '#ffffff'
: el.frameStyle === 'film'
? '#141414'
: undefined,
borderRadius: !card && !clipped && el.radius ? `${el.radius}mm` : undefined,
boxShadow: boxShadows.length ? boxShadows.join(', ') : undefined,
}}
>
{mask && !card && !empty && (look.shadow || look.cutout) && (
<ShapeSilhouette frame={el.frame} mask={mask} look={look} />
)}
{(mask || filterId) && (
<svg width="0" height="0" style={{ position: 'absolute' }} aria-hidden>
<defs>
{mask && (
<clipPath id={clipId} clipPathUnits="objectBoundingBox">
<path d={unitPath(SHAPE_PATHS[mask])} />
</clipPath>
)}
{filterId && (
<filter id={filterId} colorInterpolationFilters="sRGB">
{matrices.map((values, i) => (
<feColorMatrix key={i} type="matrix" values={values} />
))}
</filter>
)}
</defs>
</svg>
)}
{picture}
{/* Sprocket holes. Drawn as a repeating gradient rather than as elements
so the count follows the width instead of being fixed at a size that
only looks right on one frame. */}
{el.frameStyle === 'film' &&
[0, 1].map((row) => (
<div
key={row}
style={{
position: 'absolute',
left: `${pad * 0.35}mm`,
right: `${pad * 0.35}mm`,
[row ? 'bottom' : 'top']: `${pad * 0.22}mm`,
height: `${pad * 0.42}mm`,
background:
'repeating-linear-gradient(90deg,' +
` #f4f4f4 0 ${pad * 0.5}mm, transparent ${pad * 0.5}mm ${pad * 1.1}mm)`,
}}
/>
))}
{/*
Two strips, one over each top corner, each centred *on* its corner so it
overhangs the picture evenly on both sides, which is what a piece of
tape does. Offsetting by a fraction of the strip instead left them
sitting beside the corners rather than across them.
*/}
{el.frameStyle === 'tape' &&
([-1, 1] as const).map((dir) => {
const tapeW = side * 0.26;
const tapeH = side * 0.075;
return (
<div
key={dir}
style={{
position: 'absolute',
[dir < 0 ? 'left' : 'right']: `${round2(-tapeW / 2)}mm`,
top: `${round2(-tapeH / 2)}mm`,
width: `${round2(tapeW)}mm`,
height: `${round2(tapeH)}mm`,
background: 'rgba(236,228,206,.82)',
boxShadow: '0 .3mm .6mm rgba(0,0,0,.12)',
// Away from the corner on each side: anticlockwise on the left,
// clockwise on the right, so the pair reads as symmetric.
transform: `rotate(${dir * 45}deg)`,
}}
/>
);
})}
</div>
);
}
+5 -235
View File
@@ -1,11 +1,11 @@
import type { CSSProperties } from 'react'
import type {
BookElement, BookIconElement, BookPageSetup, BookPhotoElement, BookShapeElement, BookSpread,
BookElement, BookIconElement, BookPageSetup, BookShapeElement, BookSpread,
} from '@trek/shared'
import { photoSrc } from './bookRender'
import { fontStack, nearestWeight } from './bookFonts'
import { iconComponent } from './iconLibrary'
import { HOLED_SHAPES, SHAPE_PATHS, scalePath, unitPath } from './shapes'
import { PhotoView } from './PhotoView'
import { HOLED_SHAPES, SHAPE_PATHS, scalePath } from './shapes'
import { TravelElementView } from './TravelElements'
import { PageNumbers } from './PageNumbers'
import { PaintedShapeView } from './paint/PaintedShape'
@@ -38,42 +38,12 @@ function frameStyle(el: BookElement): CSSProperties {
}
}
/** Two decimals of a millimetre, matching what the document itself stores. */
const round2 = (n: number) => Math.round(n * 100) / 100
/** #rrggbb plus an alpha, for the fades a cover panel needs. */
function hexToRgba(hex: string, alpha: number): string {
const n = Number.parseInt(hex.slice(1), 16)
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
}
const FILTERS: Record<string, string | undefined> = {
none: undefined,
bw: 'grayscale(1) contrast(1.05)',
warm: 'saturate(1.1) sepia(0.16)',
cool: 'saturate(1.05) hue-rotate(-8deg) brightness(1.02)',
// Faded, the way a print left in the light goes: lifted blacks, less colour.
fade: 'saturate(0.72) contrast(0.88) brightness(1.08)',
contrast: 'contrast(1.22) saturate(1.06)',
}
/**
* How much of the frame the decoration around a picture eats, as a fraction of
* the shorter side.
*
* A Polaroid's chin is the reason this is a table rather than one number: the
* bottom border is roughly three times the others, and getting that ratio wrong
* is the difference between a Polaroid and a photo with a white edge.
*/
const FRAME_INSET: Record<string, { pad: number; bottom: number }> = {
none: { pad: 0, bottom: 0 },
polaroid: { pad: 0.055, bottom: 0.17 },
white: { pad: 0.035, bottom: 0.035 },
shadow: { pad: 0, bottom: 0 },
film: { pad: 0.075, bottom: 0.075 },
tape: { pad: 0, bottom: 0 },
}
/**
* A shape, drawn.
*
@@ -158,206 +128,6 @@ function ShapeView({ el }: { el: BookShapeElement }) {
)
}
/**
* A picture — possibly cut to a shape, possibly sitting in something.
*
* The mask and the decoration are independent on purpose: a heart in a Polaroid
* is a silly thing to want and there is no reason to stop anyone wanting it, and
* keeping them separate means neither has to know about the other.
*/
function PhotoView({ el, big, print, dropLabel }: {
el: BookPhotoElement; big: boolean; print: boolean; dropLabel: string
}) {
const deco = FRAME_INSET[el.frameStyle] ?? FRAME_INSET.none
const side = Math.min(el.frame.w, el.frame.h)
// Rounded to a hundredth of a millimetre — the same precision the document
// stores. Without it a fraction of the frame lands in the CSS as
// `10.200000000000001mm`, which is not wrong but is float noise in a
// stylesheet that a person may well end up reading.
const pad = round2(deco.pad * side)
const bottom = round2(deco.bottom * side)
const clipId = usePaintId(`c-${el.id}`)
const clipped = el.mask && el.mask !== 'rect'
/*
* An empty frame is a template's promise: it says where a picture goes before
* anyone has chosen which — and it says it *in the frame it will wear*.
*
* This used to render on its own, ignoring frameStyle entirely, so a Polaroid
* placeholder was an ordinary dashed rectangle until a photograph landed in
* it and the chin appeared from nowhere. The two branches have been folded
* together: the surround is drawn once, and only what goes inside it differs.
*/
const empty = el.photoId == null
// In the printed book an unfilled frame is nothing at all — a hatch and an
// instruction on a page someone paid to have bound would be a defect.
if (empty && print) return null
// The label is sized in millimetres so it scales with the zoom exactly as the
// page does, and it steps aside on a frame too small to hold it.
const labelSize = Math.max(2.4, Math.min(4.6, side * 0.085))
const roomy = side - pad * 2 > 22 && el.frame.w - pad * 2 > 34
const hatch = (
<div
style={{
position: 'absolute',
inset: 0,
/*
* Opaque, and that is the point.
*
* The hatch used to be laid over nothing, so an empty frame showed
* whatever was behind it and every attempt to arrange a shape *under*
* one looked like it had done nothing: the frame appeared to sit at the
* bottom of the stack no matter where it was, right up until a
* photograph landed in it and it suddenly covered things. A frame is a
* promise that a picture goes here, and a picture is not see-through.
*/
background:
'repeating-linear-gradient(45deg, rgba(0,0,0,.055) 0 6px, rgba(0,0,0,.025) 6px 12px), #ffffff', // theme-lint-disable — paper, not app chrome
// A dashed border would be cut in half lengthwise by the clip, so a
// masked placeholder shows its shape through the hatch alone.
border: clipped ? undefined : '1px dashed rgba(0,0,0,.16)',
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: '2mm',
}}
>
{roomy && dropLabel && (
<span
style={{
fontFamily: fontStack('sans'),
fontSize: `${labelSize}mm`,
fontWeight: 600,
letterSpacing: '0.16em',
lineHeight: 1.5,
textAlign: 'center',
textTransform: 'uppercase',
color: 'rgba(0,0,0,.34)',
whiteSpace: 'pre-line',
userSelect: 'none',
}}
>
{dropLabel}
</span>
)}
</div>
)
const picture = (
<div
style={{
position: 'absolute',
left: `${pad}mm`,
top: `${pad}mm`,
right: `${pad}mm`,
bottom: `${bottom || pad}mm`,
overflow: 'hidden',
borderRadius: !clipped && el.radius ? `${el.radius}mm` : undefined,
clipPath: clipped ? `url(#${clipId})` : undefined,
}}
>
{empty ? hatch : (
<img
src={photoSrc(el.photoId!, big)}
alt=""
draggable={false}
// Lazy on the canvas, where a long book scrolls past; eager in print,
// where every sheet is laid out at once and a picture the browser put
// off is a picture missing from the PDF.
loading={print ? 'eager' : 'lazy'}
style={{
width: '100%',
height: '100%',
objectFit: el.fit,
objectPosition: `${el.focalX * 100}% ${el.focalY * 100}%`,
filter: FILTERS[el.filter],
display: 'block',
}}
/>
)}
</div>
)
return (
<div
style={{
...frameStyle(el),
background: el.frameStyle === 'polaroid' || el.frameStyle === 'white' ? '#ffffff'
: el.frameStyle === 'film' ? '#141414'
: undefined,
// A photograph lying on a page, rather than printed into it. Soft and
// low: a hard shadow reads as a UI card, not as paper.
boxShadow: el.frameStyle === 'shadow' || el.frameStyle === 'polaroid'
? '0 1.2mm 3mm rgba(0,0,0,.22)'
: undefined,
}}
>
{clipped && (
<svg width="0" height="0" style={{ position: 'absolute' }} aria-hidden>
<defs>
<clipPath id={clipId} clipPathUnits="objectBoundingBox">
<path d={unitPath(SHAPE_PATHS[el.mask!])} />
</clipPath>
</defs>
</svg>
)}
{picture}
{/* Sprocket holes. Drawn as a repeating gradient rather than as elements
so the count follows the width instead of being fixed at a size that
only looks right on one frame. */}
{el.frameStyle === 'film' && [0, 1].map(row => (
<div
key={row}
style={{
position: 'absolute',
left: `${pad * 0.35}mm`,
right: `${pad * 0.35}mm`,
[row ? 'bottom' : 'top']: `${pad * 0.22}mm`,
height: `${pad * 0.42}mm`,
background: 'repeating-linear-gradient(90deg,'
+ ` #f4f4f4 0 ${pad * 0.5}mm, transparent ${pad * 0.5}mm ${pad * 1.1}mm)`,
}}
/>
))}
{/* Two strips of tape, held at an angle across opposite corners. */}
{/*
Two strips, one over each top corner, each centred *on* its corner so it
overhangs the picture evenly on both sides — which is what a piece of
tape does. Offsetting by a fraction of the strip instead left them
sitting beside the corners rather than across them.
*/}
{el.frameStyle === 'tape' && ([-1, 1] as const).map(dir => {
const tapeW = side * 0.26
const tapeH = side * 0.075
return (
<div
key={dir}
style={{
position: 'absolute',
[dir < 0 ? 'left' : 'right']: `${round2(-tapeW / 2)}mm`,
top: `${round2(-tapeH / 2)}mm`,
width: `${round2(tapeW)}mm`,
height: `${round2(tapeH)}mm`,
background: 'rgba(236,228,206,.82)',
boxShadow: '0 .3mm .6mm rgba(0,0,0,.12)',
// Away from the corner on each side: anticlockwise on the left,
// clockwise on the right, so the pair reads as symmetric.
transform: `rotate(${dir * 45}deg)`,
}}
/>
)
})}
</div>
)
}
/**
* A lucide drawing, at the size the frame gives it.
*
@@ -394,9 +164,9 @@ export function ElementView({
// A photo left out is drawn as its empty frame, kept even in print, so the
// page still shows where a picture sits without showing the picture.
if (el.photoId != null && hiddenPhotoIds?.has(el.photoId)) {
return <PhotoView el={{ ...el, photoId: null }} big={big} print={false} dropLabel="" />
return <PhotoView el={{ ...el, photoId: null }} big={big} print={false} dropLabel="" frameStyle={frameStyle(el)} />
}
return <PhotoView el={el} big={big} print={print} dropLabel={dropLabel} />
return <PhotoView el={el} big={big} print={print} dropLabel={dropLabel} frameStyle={frameStyle(el)} />
}
if (el.kind === 'shape') {
@@ -19,6 +19,7 @@ import { Choice, Line, NumField, Section, Switch } from './StudioControls'
import { StudioFontPicker } from './StudioFontPicker'
import { WeightLine } from './StudioTypeControls'
import { italicTitle } from './fontPicker'
import { PhotoCropExtras, PhotoLookSections } from './photo/StudioPhotoLook'
import type { JourneySource } from './StudioSidebar'
import { Tooltip } from '../shared/Tooltip'
import { StudioArrangeSection } from './StudioArrangeSection'
@@ -421,6 +422,7 @@ export function StudioInspector({
) : (
<p className="st-hint" style={{ paddingTop: 8 }}>{t('journey.studio.emptyFrame')}</p>
)}
<PhotoCropExtras el={el} set={set} live={live} t={t} />
</Section>
<Section label={t('journey.studio.look')}>
@@ -467,6 +469,8 @@ export function StudioInspector({
)}
</Section>
<PhotoLookSections el={el} set={set} live={live} t={t} />
<Section label={t('journey.studio.mask')} defaultOpen={false}>
<div className="st-mini-shapes">
<button type="button"
@@ -0,0 +1,159 @@
import { PHOTO_DUOTONES, PHOTO_LOOK_STARTS, bookPhotoElementSchema, type BookPhotoElement } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
import { PhotoCropExtras, PhotoLookSections } from './StudioPhotoLook';
/**
* The inspector rows of the photo look: what each control writes, that a part
* turned off is left out of the document, and the print resolution beside
* the crop with its warning.
*/
const pixels = vi.hoisted(() => ({ value: null as { width: number; height: number } | null }));
vi.mock('./usePhotoPixels', () => ({ usePhotoPixels: () => pixels.value }));
const t = (k: string, params?: Record<string, string | number>) =>
params ? `${k} ${Object.values(params).join(' ')}` : k;
const photo = (over: Record<string, unknown> = {}): BookPhotoElement =>
bookPhotoElementSchema.parse({ id: 'p1', kind: 'photo', frame: { x: 0, y: 0, w: 80, h: 60 }, photoId: 7, ...over });
function mount(ui: 'crop' | 'look', el: BookPhotoElement) {
const set = vi.fn();
const live = vi.fn();
const View = ui === 'crop' ? PhotoCropExtras : PhotoLookSections;
render(<View el={el} set={set} live={live} t={t} />);
return { set, live };
}
beforeEach(() => {
pixels.value = null;
});
describe('beside the crop', () => {
it('FE-STUDIO-LOOKUI-001: zooms live while dragging and commits once, and goes back to no zoom at 100%', () => {
const { set, live } = mount('crop', photo());
const slider = screen.getByRole('slider');
fireEvent.change(slider, { target: { value: '1.5' } });
expect(live).toHaveBeenCalledWith({ zoom: 1.5 });
expect(set).not.toHaveBeenCalled();
fireEvent.pointerUp(slider);
expect(set).toHaveBeenCalledWith({ zoom: 1.5 });
fireEvent.change(slider, { target: { value: '1' } });
fireEvent.blur(slider);
expect(set).toHaveBeenLastCalledWith({ zoom: undefined });
});
it('FE-STUDIO-LOOKUI-002: mirrors the picture and takes the mirror away again', () => {
const plain = mount('crop', photo());
fireEvent.click(screen.getByRole('button', { name: /journey.studio.photo.flip/ }));
expect(plain.set).toHaveBeenCalledWith({ flipX: true });
});
it('FE-STUDIO-LOOKUI-003: takes a mirrored picture back to as shot', () => {
const mirrored = mount('crop', photo({ flipX: true }));
const button = screen.getByRole('button', { name: /journey.studio.photo.flip/ });
expect(button.getAttribute('aria-pressed')).toBe('true');
fireEvent.click(button);
expect(mirrored.set).toHaveBeenCalledWith({ flipX: undefined });
});
it('FE-STUDIO-LOOKUI-004: shows the print resolution once the original is measured, and warns under 200 dpi', () => {
pixels.value = { width: 4000, height: 3000 };
mount('crop', photo());
expect(screen.getByText('journey.studio.photo.dpi 1270')).toBeTruthy();
expect(screen.queryByText(/journey.studio.photo.dpiLow/)).toBeNull();
});
it('FE-STUDIO-LOOKUI-005: warns when the zoomed picture prints soft', () => {
pixels.value = { width: 800, height: 600 };
mount('crop', photo({ zoom: 2 }));
expect(screen.getByText('journey.studio.photo.dpi 127')).toBeTruthy();
expect(screen.getByText('journey.studio.photo.dpiLow 200')).toBeTruthy();
expect(screen.getByRole('status').className).toContain('is-low');
});
it('FE-STUDIO-LOOKUI-006: shows nothing for an empty frame', () => {
pixels.value = { width: 4000, height: 3000 };
mount('crop', photo({ photoId: null }));
expect(screen.queryByRole('slider')).toBeNull();
});
});
describe('the look sections', () => {
it('FE-STUDIO-LOOKUI-007: turns a border on with the print border and off by leaving it out', () => {
const off = mount('look', photo());
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.edges' }));
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.border', pressed: false }));
expect(off.set).toHaveBeenCalledWith({ border: { ...PHOTO_LOOK_STARTS.border } });
});
it('FE-STUDIO-LOOKUI-008: edits a border that is on, and removes it', () => {
const { set } = mount('look', photo({ border: { width: 4, color: '#ffffff' } }));
const width = screen.getByRole('spinbutton', { name: /journey.studio.photo.width/ });
fireEvent.change(width, { target: { value: '6' } });
fireEvent.blur(width);
expect(set).toHaveBeenCalledWith({ border: { width: 6, color: '#ffffff' } });
fireEvent.click(screen.getByRole('button', { name: '#c2410c' }));
expect(set).toHaveBeenCalledWith({ border: { width: 4, color: '#c2410c' } });
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.border', pressed: true }));
expect(set).toHaveBeenLastCalledWith({ border: undefined });
});
it('FE-STUDIO-LOOKUI-009: sets how far a hard shadow falls and how strong it is', () => {
const shadow = { dx: 2, dy: 2, color: '#1a1a1a', alpha: 0.35 };
const { set, live } = mount('look', photo({ shadow }));
const across = screen.getByRole('spinbutton', { name: /journey.studio.photo.dx/ });
fireEvent.change(across, { target: { value: '-3' } });
fireEvent.blur(across);
expect(set).toHaveBeenCalledWith({ shadow: { ...shadow, dx: -3 } });
const strength = screen.getByRole('slider', { name: /journey.studio.opacity/ });
fireEvent.change(strength, { target: { value: '0.6' } });
expect(live).toHaveBeenCalledWith({ shadow: { ...shadow, alpha: 0.6 } });
fireEvent.keyUp(strength);
expect(set).toHaveBeenLastCalledWith({ shadow: { ...shadow, alpha: 0.6 } });
});
it('FE-STUDIO-LOOKUI-010: turns the shadow and the cutout on from their starting values', () => {
const { set } = mount('look', photo());
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.edges' }));
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.shadow', pressed: false }));
expect(set).toHaveBeenCalledWith({ shadow: { ...PHOTO_LOOK_STARTS.shadow } });
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.cutout', pressed: false }));
expect(set).toHaveBeenCalledWith({ cutout: { ...PHOTO_LOOK_STARTS.cutout } });
});
it('FE-STUDIO-LOOKUI-011: adjusts one value at a time, says it prints as a raster, and resets', () => {
const { set } = mount('look', photo({ adjust: { contrast: 0.2 } }));
expect(screen.getAllByText('journey.studio.photo.rasterHint').length).toBeGreaterThan(0);
const brightness = screen.getByRole('slider', { name: /journey.studio.photo.brightness/ });
fireEvent.change(brightness, { target: { value: '0.3' } });
fireEvent.pointerUp(brightness);
expect(set).toHaveBeenCalledWith({ adjust: { brightness: 0.3, contrast: 0.2, saturation: 0, warmth: 0 } });
const contrast = screen.getByRole('slider', { name: /journey.studio.photo.contrast/ });
fireEvent.change(contrast, { target: { value: '0' } });
fireEvent.pointerUp(contrast);
expect(set).toHaveBeenLastCalledWith({ adjust: undefined });
fireEvent.click(screen.getByRole('button', { name: /journey.studio.photo.reset/ }));
expect(set).toHaveBeenLastCalledWith({ adjust: undefined });
});
it('FE-STUDIO-LOOKUI-012: picks a ready duotone pair and the inks by hand', () => {
const { set } = mount('look', photo({ duotone: { ...PHOTO_DUOTONES[0] } }));
const pairs = screen.getAllByRole('radio');
expect(pairs).toHaveLength(PHOTO_DUOTONES.length);
expect(pairs[0]?.getAttribute('aria-checked')).toBe('true');
fireEvent.click(pairs[2] as HTMLElement);
expect(set).toHaveBeenCalledWith({ duotone: { ...PHOTO_DUOTONES[2] } });
fireEvent.click(screen.getAllByRole('button', { name: '#9f1239' })[0] as HTMLElement);
expect(set).toHaveBeenLastCalledWith({ duotone: { ...PHOTO_DUOTONES[0], dark: '#9f1239' } });
});
it('FE-STUDIO-LOOKUI-013: turns the duotone on and off', () => {
const { set } = mount('look', photo());
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.duotone', expanded: false }));
fireEvent.click(screen.getByRole('button', { name: 'journey.studio.photo.duotone', pressed: false }));
expect(set).toHaveBeenCalledWith({ duotone: { ...PHOTO_LOOK_STARTS.duotone } });
});
});
@@ -0,0 +1,292 @@
import {
MIN_PRINT_DPI,
PHOTO_ADJUSTMENTS,
PHOTO_DUOTONES,
PHOTO_EDGE_MAX,
PHOTO_LOOK_STARTS,
PHOTO_SHADOW_REACH,
PHOTO_ZOOM,
photoDpi,
photoLookOf,
type BookPhotoAdjust,
type BookPhotoEdge,
type BookPhotoElement,
type PhotoAdjustment,
} from '@trek/shared';
import { FlipHorizontal2, Printer, RotateCcw, TriangleAlert } from 'lucide-react';
import '../../../styles/studio-photo.css';
import { Line, NumField, Section, Switch } from '../StudioControls';
import { Swatches } from '../StudioSwatches';
import { StudioSlider } from './StudioSlider';
import { usePhotoPixels } from './usePhotoPixels';
/**
* The inspector rows of the photo look (book-photo-look.schema.ts in shared):
* zoom, mirror and the print resolution beside the crop, then the border, the
* hard shadow and the cutout, the adjustments and the duotone.
*
* Its own file so the inspector carries two hooks for it and nothing else;
* every other Studio package edits that panel too.
*
* A part that is off is left out of the document (undefined), never stored as
* a neutral value, so a photo nobody restyled stays exactly what it was.
*/
type Patch = Partial<BookPhotoElement>;
type T = (k: string, params?: Record<string, string | number>) => string;
interface RowProps {
el: BookPhotoElement;
/** One undo step. */
set: (patch: Patch) => void;
/** While a slider moves: the page follows, nothing is committed. */
live: (patch: Patch) => void;
t: T;
}
const percent = (v: number) => `${Math.round(v * 100)}%`;
const signed = (v: number) => {
const n = Math.round(v * 100);
return n > 0 ? `+${n}` : String(n);
};
/** What prints when the photo leaves the printer: about this many dots per inch, and a warning under the threshold. */
function PrintResolution({ el, t }: { el: BookPhotoElement; t: T }) {
const pixels = usePhotoPixels(el.photoId);
if (el.photoId == null || !pixels) return null;
const dpi = photoDpi(el, { photoId: el.photoId, ...pixels });
if (dpi === null) return null;
const low = dpi < MIN_PRINT_DPI;
return (
<div className={`st-photo-dpi ${low ? 'is-low' : ''}`} role="status">
{low ? <TriangleAlert size={14} aria-hidden /> : <Printer size={14} aria-hidden />}
<div>
<p className="st-photo-dpi-value">{t('journey.studio.photo.dpi', { dpi })}</p>
{low && <p className="st-photo-dpi-hint">{t('journey.studio.photo.dpiLow', { min: MIN_PRINT_DPI })}</p>}
</div>
</div>
);
}
/** Beside the crop: how far the picture is zoomed about its focal point, whether it is mirrored, and how it prints. */
export function PhotoCropExtras({ el, set, live, t }: RowProps) {
// An empty frame has no picture to zoom, mirror or print.
if (el.photoId == null) return null;
const look = photoLookOf(el);
const zoomOf = (v: number) => (v > PHOTO_ZOOM.min ? Math.round(v * 100) / 100 : undefined);
return (
<div className="st-photo-crop">
<StudioSlider
label={t('journey.studio.photo.zoom')}
value={look.zoom}
min={PHOTO_ZOOM.min}
max={PHOTO_ZOOM.max}
step={0.05}
format={percent}
onLive={(v) => live({ zoom: zoomOf(v) })}
onCommit={(v) => set({ zoom: zoomOf(v) })}
/>
<button
type="button"
className={`st-chip ${look.flipX ? 'is-on' : ''}`}
aria-pressed={look.flipX}
onClick={() => set({ flipX: look.flipX ? undefined : true })}
>
<FlipHorizontal2 size={13} aria-hidden />
{t('journey.studio.photo.flip')}
</button>
<PrintResolution el={el} t={t} />
</div>
);
}
/** A border or a cutout: on or off, how deep, what colour. */
function EdgeRow({
label,
value,
start,
onSet,
t,
}: {
label: string;
value: BookPhotoEdge | null;
start: BookPhotoEdge;
onSet: (edge: BookPhotoEdge | undefined) => void;
t: T;
}) {
return (
<div className="st-photo-part">
<Switch label={label} on={!!value} onToggle={() => onSet(value ? undefined : { ...start })} />
{value && (
<div className="st-photo-part-body">
<NumField
label={t('journey.studio.photo.width')}
value={value.width}
min={0.1}
max={PHOTO_EDGE_MAX}
step={0.5}
unit="mm"
onChange={(width) => onSet({ ...value, width })}
/>
<Line label={t('journey.studio.colour')} wide>
<Swatches value={value.color} onPick={(color) => onSet({ ...value, color })} />
</Line>
</div>
)}
</div>
);
}
/** The hard shadow: on or off, how far it falls, how strong, what colour. */
function ShadowRow({ el, set, live, t }: RowProps) {
const shadow = photoLookOf(el).shadow;
return (
<div className="st-photo-part">
<Switch
label={t('journey.studio.photo.shadow')}
on={!!shadow}
onToggle={() => set({ shadow: shadow ? undefined : { ...PHOTO_LOOK_STARTS.shadow } })}
/>
{shadow && (
<div className="st-photo-part-body">
<div className="st-grid2">
{(['dx', 'dy'] as const).map((axis) => (
<NumField
key={axis}
label={t(`journey.studio.photo.${axis}`)}
value={shadow[axis]}
min={-PHOTO_SHADOW_REACH}
max={PHOTO_SHADOW_REACH}
step={0.5}
unit="mm"
onChange={(v) => set({ shadow: { ...shadow, [axis]: v } })}
/>
))}
</div>
<StudioSlider
label={t('journey.studio.opacity')}
value={shadow.alpha}
min={0}
max={1}
step={0.05}
format={percent}
onLive={(alpha) => live({ shadow: { ...shadow, alpha } })}
onCommit={(alpha) => set({ shadow: { ...shadow, alpha } })}
/>
<Line label={t('journey.studio.colour')} wide>
<Swatches value={shadow.color} onPick={(color) => set({ shadow: { ...shadow, color } })} />
</Line>
</div>
)}
</div>
);
}
/** Brightness, contrast, saturation and warmth, each from -100 to +100, and one press back to the picture as shot. */
function AdjustRows({ el, set, live, t }: RowProps) {
const adjust = photoLookOf(el).adjust;
const next = (key: PhotoAdjustment, v: number): BookPhotoAdjust | undefined => {
const all = { ...(adjust ?? {}), [key]: Math.round(v * 100) / 100 };
return PHOTO_ADJUSTMENTS.some((k) => all[k]) ? all : undefined;
};
return (
<>
{PHOTO_ADJUSTMENTS.map((key) => (
<StudioSlider
key={key}
label={t(`journey.studio.photo.${key}`)}
value={adjust?.[key] ?? 0}
min={-1}
max={1}
step={0.05}
format={signed}
onLive={(v) => live({ adjust: next(key, v) })}
onCommit={(v) => set({ adjust: next(key, v) })}
/>
))}
{adjust && (
<button type="button" className="st-chip st-photo-reset" onClick={() => set({ adjust: undefined })}>
<RotateCcw size={13} aria-hidden />
{t('journey.studio.photo.reset')}
</button>
)}
</>
);
}
/** The duotone: on or off, one of the ready pairs, or the two inks picked by hand. */
function DuotoneRows({ el, set, t }: Omit<RowProps, 'live'>) {
const duotone = photoLookOf(el).duotone;
return (
<>
<Switch
label={t('journey.studio.photo.duotone')}
on={!!duotone}
onToggle={() => set({ duotone: duotone ? undefined : { ...PHOTO_LOOK_STARTS.duotone } })}
/>
{duotone && (
<div className="st-photo-part-body">
<div className="st-photo-duos" role="radiogroup" aria-label={t('journey.studio.photo.duotone')}>
{PHOTO_DUOTONES.map((pair) => {
const on = pair.dark === duotone.dark && pair.light === duotone.light;
return (
<button
type="button"
key={`${pair.dark}${pair.light}`}
role="radio"
aria-checked={on}
aria-label={`${pair.dark} ${pair.light}`}
className={`st-photo-duo ${on ? 'is-on' : ''}`}
// A swatch shows the two inks themselves, half and half.
style={{ backgroundImage: `linear-gradient(135deg, ${pair.dark} 50%, ${pair.light} 50%)` }}
onClick={() => set({ duotone: { ...pair } })}
/>
);
})}
</div>
<Line label={t('journey.studio.photo.duotoneDark')} wide>
<Swatches value={duotone.dark} onPick={(dark) => set({ duotone: { ...duotone, dark } })} />
</Line>
<Line label={t('journey.studio.photo.duotoneLight')} wide>
<Swatches value={duotone.light} onPick={(light) => set({ duotone: { ...duotone, light } })} />
</Line>
</div>
)}
</>
);
}
/** The look's own sections, after the inspector's Look section. */
export function PhotoLookSections(props: RowProps) {
const { el, set, t } = props;
const look = photoLookOf(el);
const raster = t('journey.studio.photo.rasterHint');
return (
<>
<Section label={t('journey.studio.photo.edges')} defaultOpen={!!(look.border || look.shadow || look.cutout)}>
<EdgeRow
label={t('journey.studio.photo.border')}
value={look.border}
start={PHOTO_LOOK_STARTS.border}
onSet={(border) => set({ border })}
t={t}
/>
<ShadowRow {...props} />
<EdgeRow
label={t('journey.studio.photo.cutout')}
value={look.cutout}
start={PHOTO_LOOK_STARTS.cutout}
onSet={(cutout) => set({ cutout })}
t={t}
/>
</Section>
<Section label={t('journey.studio.photo.adjust')} hint={raster} defaultOpen={!!look.adjust}>
<AdjustRows {...props} />
</Section>
<Section label={t('journey.studio.photo.duotone')} hint={raster} defaultOpen={!!look.duotone}>
<DuotoneRows el={el} set={set} t={t} />
</Section>
</>
);
}
@@ -0,0 +1,61 @@
import { useState } from 'react';
/**
* A number set by dragging, for the values a person judges by eye: a zoom, a
* brightness, a shadow's strength.
*
* The page follows the thumb while it moves (`onLive`, no undo step), and the
* value is committed once, when the thumb is let go or the keys are released
* (`onCommit`, one undo step), the way the focal point pad works.
*/
export function StudioSlider({
label,
value,
min,
max,
step,
format,
onLive,
onCommit,
}: {
label: string;
value: number;
min: number;
max: number;
step: number;
/** What the value reads as beside the track. */
format: (v: number) => string;
onLive: (v: number) => void;
onCommit: (v: number) => void;
}) {
const [draft, setDraft] = useState<number | null>(null);
const shown = draft ?? value;
const end = () => {
if (draft === null) return;
setDraft(null);
onCommit(draft);
};
return (
<label className="st-slider">
<span className="st-slider-label">{label}</span>
<input
type="range"
min={min}
max={max}
step={step}
value={shown}
aria-valuetext={format(shown)}
onChange={(e) => {
const v = Number(e.target.value);
setDraft(v);
onLive(v);
}}
onPointerUp={end}
onKeyUp={end}
onBlur={end}
/>
<output className="st-slider-value">{format(shown)}</output>
</label>
);
}
@@ -0,0 +1,92 @@
import { photoLookOf, type PhotoLook } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import {
adjustFilter,
duotoneMatrix,
pictureFilter,
rgba,
silhouetteShadows,
svgFilterMatrices,
warmthMatrix,
zoomPlacement,
} from './photoLook';
/**
* The numbers the photo look prints with: the CSS filter chain, the colour
* matrices of the SVG filter, the box shadows of a rectangular frame and the
* placement of a zoomed picture.
*/
const look = (over: Partial<PhotoLook> = {}): PhotoLook => ({ ...photoLookOf({}), ...over });
const adjust = (a: Partial<NonNullable<PhotoLook['adjust']>>) => ({
brightness: 0,
contrast: 0,
saturation: 0,
warmth: 0,
...a,
});
describe('photo look rendering', () => {
it('FE-STUDIO-LOOK-001: turns adjustments into filter functions, leaving out what does not move', () => {
expect(adjustFilter(null)).toEqual([]);
expect(adjustFilter(adjust({ brightness: 0.2, contrast: -1, saturation: -1 }))).toEqual([
'brightness(1.1)',
'contrast(0.5)',
'saturate(0)',
]);
expect(adjustFilter(adjust({ warmth: 0.5 }))).toEqual([]);
});
it('FE-STUDIO-LOOK-002: chains the preset, the adjustments and the SVG filter, and draws nothing for none', () => {
expect(pictureFilter(undefined, look(), null)).toBeUndefined();
expect(pictureFilter('grayscale(1)', look({ adjust: adjust({ contrast: 0.4 }) }), 'f-x')).toBe(
'grayscale(1) contrast(1.2) url(#f-x)'
);
});
it('FE-STUDIO-LOOK-003: warms by raising red and lowering blue, and cools the other way', () => {
expect(warmthMatrix(0)).toBeNull();
expect(warmthMatrix(1)).toBe('1.12 0 0 0 0 0 1.03 0 0 0 0 0 0.88 0 0 0 0 0 1 0');
expect(warmthMatrix(-1)).toBe('0.88 0 0 0 0 0 0.97 0 0 0 0 0 1.12 0 0 0 0 0 1 0');
});
it('FE-STUDIO-LOOK-004: maps black to the dark ink and white to the light one', () => {
const values = duotoneMatrix({ dark: '#000000', light: '#ffffff' }).split(' ').map(Number);
// Each colour row reads the luminance weights and starts from the dark ink.
expect(values.slice(0, 5)).toEqual([0.213, 0.715, 0.072, 0, 0]);
expect(values.slice(15)).toEqual([0, 0, 0, 1, 0]);
const navy = duotoneMatrix({ dark: '#ff0000', light: '#ff0000' }).split(' ').map(Number);
// The same ink at both ends is that ink, whatever the picture.
expect(navy.slice(0, 5)).toEqual([0, 0, 0, 0, 1]);
expect(navy.slice(5, 10)).toEqual([0, 0, 0, 0, 0]);
});
it('FE-STUDIO-LOOK-005: needs an SVG filter only for warmth or a duotone, warmth first', () => {
expect(svgFilterMatrices(look())).toEqual([]);
expect(svgFilterMatrices(look({ adjust: adjust({ brightness: 0.3 }) }))).toEqual([]);
const both = svgFilterMatrices(
look({ adjust: adjust({ warmth: 1 }), duotone: { dark: '#000000', light: '#ffffff' } })
);
expect(both).toHaveLength(2);
expect(both[0]).toBe(warmthMatrix(1));
});
it('FE-STUDIO-LOOK-006: draws the cutout and a shadow grown by it as flat box shadows', () => {
expect(silhouetteShadows(null, null)).toEqual([]);
expect(silhouetteShadows({ dx: 2, dy: 3, color: '#102030', alpha: 0.5 }, null)).toEqual([
'2mm 3mm 0 0mm rgba(16, 32, 48, 0.5)',
]);
expect(silhouetteShadows({ dx: -1, dy: 1, color: '#000000', alpha: 1 }, { width: 3, color: '#ffffff' })).toEqual([
'0 0 0 3mm #ffffff',
'-1mm 1mm 0 3mm rgba(0, 0, 0, 1)',
]);
expect(rgba('#ff8000', 0.25)).toBe('rgba(255, 128, 0, 0.25)');
});
it('FE-STUDIO-LOOK-007: places a zoomed picture so the focal point stays where it was', () => {
expect(zoomPlacement(1, 0.5, 0.5)).toBeNull();
expect(zoomPlacement(2, 0.5, 0.5)).toEqual({ size: '200%', transform: 'translate(-25%, -25%)' });
expect(zoomPlacement(4, 0, 1)).toEqual({ size: '400%', transform: 'translate(0%, -75%)' });
});
});
@@ -0,0 +1,115 @@
import type { BookPhotoDuotone, BookPhotoEdge, BookPhotoShadow, PhotoLook } from '@trek/shared';
/**
* The photo look (book-photo-look.schema.ts in shared) turned into what the
* page draws: CSS for the picture, the colour matrices of its SVG filter, and
* the box shadows a rectangular frame wears.
*
* Pure, and apart from PhotoView, because these are the numbers the look
* prints with and a rendered component is an awkward place to prove them.
*
* What prints as vector and what does not is decided here: a border, a hard
* shadow and a cutout are boxes and paths of one colour, while adjustments,
* warmth and a duotone are filters on the picture, which the printer receives
* as a raster the way it already received the filter presets.
*/
/** #rrggbb with an alpha, for a shadow drawn at its own strength. */
export function rgba(hex: string, alpha: number): string {
const n = Number.parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
}
const round3 = (v: number) => Math.round(v * 1000) / 1000;
/**
* Brightness, contrast and saturation as CSS filter functions, after the
* preset filter. Half a step either way for the first two, which keeps the
* ends of the slider usable; saturation runs from grey to twice the colour.
*/
export function adjustFilter(adjust: PhotoLook['adjust']): string[] {
if (!adjust) return [];
const out: string[] = [];
if (adjust.brightness) out.push(`brightness(${round3(1 + adjust.brightness * 0.5)})`);
if (adjust.contrast) out.push(`contrast(${round3(1 + adjust.contrast * 0.5)})`);
if (adjust.saturation) out.push(`saturate(${round3(1 + adjust.saturation)})`);
return out;
}
/** The filter on the picture: the preset, the adjustments, then the SVG filter when there is one. */
export function pictureFilter(
preset: string | undefined,
look: PhotoLook,
svgFilterId: string | null
): string | undefined {
const parts = [preset, ...adjustFilter(look.adjust), svgFilterId ? `url(#${svgFilterId})` : undefined].filter(
(p): p is string => !!p
);
return parts.length ? parts.join(' ') : undefined;
}
/**
* Warmth as a colour matrix: red up and blue down for warm, the reverse for
* cool, green a little with red so a warm picture does not turn pink.
*/
export function warmthMatrix(warmth: number): string | null {
if (!warmth) return null;
const r = round3(1 + warmth * 0.12);
const g = round3(1 + warmth * 0.03);
const b = round3(1 - warmth * 0.12);
return `${r} 0 0 0 0 0 ${g} 0 0 0 0 0 ${b} 0 0 0 0 0 1 0`;
}
const channels = (hex: string) => {
const n = Number.parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((c) => c / 255) as [number, number, number];
};
/** Rec. 709 luminance weights, the brightness the duotone maps from. */
const LUMA = [0.2126, 0.7152, 0.0722] as const;
/** A duotone as a colour matrix: the picture's luminance mapped from `dark` (black) to `light` (white). */
export function duotoneMatrix(duotone: BookPhotoDuotone): string {
const dark = channels(duotone.dark);
const light = channels(duotone.light);
const rows = dark.map((d, i) => {
const span = (light[i] ?? 0) - d;
return `${LUMA.map((w) => round3(w * span)).join(' ')} 0 ${round3(d)}`;
});
return `${rows.join(' ')} 0 0 0 1 0`;
}
/** The colour matrices the picture's SVG filter applies, in order; empty when it needs none. */
export function svgFilterMatrices(look: PhotoLook): string[] {
const warm = warmthMatrix(look.adjust?.warmth ?? 0);
return [warm, look.duotone ? duotoneMatrix(look.duotone) : null].filter((m): m is string => m !== null);
}
/**
* The die-cut edge and the hard shadow of a rectangular frame, as box
* shadows: no blur, so each is one flat shape, drawn behind the frame and
* following its corner radius. The shadow is grown by the cutout too, so it
* falls from the whole sticker rather than from the picture inside it.
*/
export function silhouetteShadows(shadow: BookPhotoShadow | null, cutout: BookPhotoEdge | null): string[] {
const out: string[] = [];
const grow = cutout?.width ?? 0;
if (cutout) out.push(`0 0 0 ${cutout.width}mm ${cutout.color}`);
if (shadow) out.push(`${shadow.dx}mm ${shadow.dy}mm 0 ${grow}mm ${rgba(shadow.color, shadow.alpha)}`);
return out;
}
/**
* Where the picture sits inside a zoomed frame, as the image's own size and a
* shift in its own percentages: z times the frame, moved so the focal point
* stays where the frame put it at zoom 1.
*/
export function zoomPlacement(
zoom: number,
focalX: number,
focalY: number
): { size: string; transform: string } | null {
if (zoom <= 1) return null;
const shift = (f: number) => round3((-(zoom - 1) * f * 100) / zoom);
return { size: `${round3(zoom * 100)}%`, transform: `translate(${shift(focalX)}%, ${shift(focalY)}%)` };
}
@@ -0,0 +1,68 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { usePhotoPixels } from './usePhotoPixels';
/**
* The original's pixel size, read off the original itself for the photo the
* inspector shows: nothing until it has loaded, nothing for another photo
* than the one asked about, nothing for an empty frame.
*/
class FakeImage {
static made: FakeImage[] = [];
onload: (() => void) | null = null;
naturalWidth = 0;
naturalHeight = 0;
src = '';
constructor() {
FakeImage.made.push(this);
}
load(width: number, height: number) {
this.naturalWidth = width;
this.naturalHeight = height;
this.onload?.();
}
}
beforeEach(() => {
FakeImage.made = [];
vi.stubGlobal('Image', FakeImage);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('usePhotoPixels', () => {
it('FE-STUDIO-PIXELS-001: loads the original and answers its size once it is in', () => {
const { result } = renderHook(() => usePhotoPixels(7));
expect(result.current).toBeNull();
const img = FakeImage.made[0] as FakeImage;
expect(img.src).toBe('/api/photos/7/original');
act(() => img.load(4000, 3000));
expect(result.current).toEqual({ width: 4000, height: 3000 });
});
it('FE-STUDIO-PIXELS-002: forgets the size when another photo is asked about, and ignores the old one landing late', () => {
const { result, rerender } = renderHook(({ id }: { id: number | null }) => usePhotoPixels(id), {
initialProps: { id: 7 as number | null },
});
const first = FakeImage.made[0] as FakeImage;
rerender({ id: 8 });
expect(first.onload).toBeNull();
act(() => first.load(100, 100));
expect(result.current).toBeNull();
act(() => (FakeImage.made[1] as FakeImage).load(600, 400));
expect(result.current).toEqual({ width: 600, height: 400 });
rerender({ id: null });
expect(result.current).toBeNull();
expect(FakeImage.made).toHaveLength(2);
});
it('FE-STUDIO-PIXELS-003: says nothing for a picture that loads without a size', () => {
const { result } = renderHook(() => usePhotoPixels(9));
act(() => (FakeImage.made[0] as FakeImage).load(0, 0));
expect(result.current).toBeNull();
});
});
@@ -0,0 +1,40 @@
import { useEffect, useState } from 'react';
import { photoSrc } from '../bookRender';
export interface PhotoPixels {
width: number;
height: number;
}
/**
* The pixel size of a photo's original, measured by loading it.
*
* The journey the Studio holds knows which pictures there are but not how
* large their originals are (the server measures that for the book engine and
* keeps it there), and a print resolution is nothing without it. So the
* inspector reads it off the original itself, for the one photo selected: the
* canvas loads that same original from a zoom of a third up, so most of the
* time the browser already has it. Null until it has loaded, and for an empty
* frame or a picture that does not load, which says nothing rather than guess.
*/
export function usePhotoPixels(photoId: number | null): PhotoPixels | null {
const [seen, setSeen] = useState<{ photoId: number; pixels: PhotoPixels } | null>(null);
useEffect(() => {
if (photoId == null) return undefined;
let cancelled = false;
const img = new Image();
img.onload = () => {
if (cancelled || !img.naturalWidth || !img.naturalHeight) return;
setSeen({ photoId, pixels: { width: img.naturalWidth, height: img.naturalHeight } });
};
img.src = photoSrc(photoId, true);
return () => {
cancelled = true;
img.onload = null;
};
}, [photoId]);
return seen && seen.photoId === photoId ? seen.pixels : null;
}