Initial commit: Luminary photo catalog and RAW editor

Browser-based photo catalog with an optional team server (SQLite + LibRaw).
Local database, uploaded photos, build output and dependencies are gitignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-23 15:19:25 +00:00
commit cd52a2f82f
121 changed files with 101872 additions and 0 deletions
+540
View File
@@ -0,0 +1,540 @@
import type {
BwFilter,
ColorLabel,
CropState,
CurvePoint,
Edits,
Flag,
HealSpot,
LocalLayer,
LocalMaskKind,
LocalPoint,
LocalStroke,
LensCorrections,
LensProfile,
RasterMask,
PhotoRecord,
PhotoMeta,
} from '../types';
import { clamp, clamp01, sanitizeCurve } from './curves';
export interface HueBand {
key: string;
name: string;
center: number;
swatch: string;
}
export const HUE_BANDS: HueBand[] = [
{ key: 'red', name: 'Red', center: 0, swatch: '#e2453c' },
{ key: 'orange', name: 'Orange', center: 32, swatch: '#e88b3a' },
{ key: 'yellow', name: 'Yellow', center: 62, swatch: '#e3cd48' },
{ key: 'green', name: 'Green', center: 120, swatch: '#57a95a' },
{ key: 'aqua', name: 'Aqua', center: 180, swatch: '#48b3b8' },
{ key: 'blue', name: 'Blue', center: 230, swatch: '#4a72c9' },
{ key: 'purple', name: 'Purple', center: 280, swatch: '#8a63c6' },
{ key: 'magenta', name: 'Magenta', center: 320, swatch: '#c455a0' },
];
/**
* Photographic contrast filters for black & white: transmission per channel.
* A red filter passes red and blocks blue, so skies print almost black.
*/
export const BW_FILTERS: { id: BwFilter; label: string; rgb: [number, number, number] }[] = [
{ id: 'none', label: 'None', rgb: [1, 1, 1] },
{ id: 'yellow', label: 'Yellow', rgb: [1, 0.9, 0.28] },
{ id: 'orange', label: 'Orange', rgb: [1, 0.66, 0.13] },
{ id: 'red', label: 'Red', rgb: [1, 0.36, 0.05] },
{ id: 'green', label: 'Green', rgb: [0.42, 1, 0.45] },
{ id: 'blue', label: 'Blue', rgb: [0.35, 0.75, 1] },
];
export function bwFilterRgb(id: BwFilter): [number, number, number] {
return BW_FILTERS.find((f) => f.id === id)?.rgb ?? [1, 1, 1];
}
/**
* CSS transform that shows a grid thumbnail in the photo's *current* orientation.
* Uses the same order as the renderer: flips act on the photo, then the quarter
* turns and straighten rotate it, and the result is scaled so the rotated image
* still fills the card (a 90 degree turn of a 4:3 photo would otherwise leave gaps).
*/
export function thumbTransform(photo: PhotoRecord, boxAspect = 4 / 3): string {
const { quarter, angle, flipH, flipV } = photo.edits.crop;
const deg = quarter * 90 + angle;
if (Math.abs(deg) < 1e-6 && !flipH && !flipV) return 'none';
const w = Math.max(1, photo.width || 1);
const h = Math.max(1, photo.height || 1);
const boxH = 1 / boxAspect;
// object-fit: cover — the photo already fills the card before any transform.
const cover = Math.max(1 / w, boxH / h);
const dw = w * cover;
const dh = h * cover;
const rad = (Math.abs(deg) * Math.PI) / 180;
const c = Math.abs(Math.cos(rad));
const s = Math.abs(Math.sin(rad));
// A rotated photo has to contain all four corners of the card, not just its
// bounding box: after un-rotating a card corner by -deg it sits at
// ((c + boxH*s)/2, (s + boxH*c)/2), so the photo must be at least that wide
// and tall. Fitting the bounding box instead leaves gaps on angle-only turns.
const coverFit = Math.max((c + boxH * s) / dw, (s + boxH * c) / dh);
// A thumbnail's rounded pixel size can differ from the record's ratio by a
// fraction of a percent; a hair of slack keeps it from showing a sliver at
// the edge. It is invisible at any real card size.
const fit = Math.abs(deg) > 1e-6 ? coverFit * 1.005 : coverFit;
const parts = [`rotate(${deg.toFixed(2)}deg)`];
// Round up: rounding the scale down would leave a hairline gap at the edge.
const rounded = Math.ceil(fit * 1e4) / 1e4;
if (Math.abs(rounded - 1) > 1e-4) parts.push(`scale(${rounded.toFixed(4)})`);
if (flipH) parts.push('scaleX(-1)');
if (flipV) parts.push('scaleY(-1)');
return parts.join(' ');
}
/** The shader carries a fixed spot array; more than this would silently drop. */
export const MAX_HEAL_SPOTS = 24;
/** Four masks are packed into one RGBA texture. */
export const MAX_LOCAL_LAYERS = 4;
export function defaultLocalAdjust(): LocalLayer['adjust'] {
return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, temp: 0, tint: 0, saturation: 0 };
}
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
kind,
inverted: false,
feather: 50,
brush: { strokes: [] },
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
adjust: defaultLocalAdjust(),
};
}
export const ASPECTS: { id: string; label: string; ratio: number | null }[] = [
{ id: 'original', label: 'Original', ratio: null },
{ id: 'free', label: 'Free', ratio: null },
{ id: '1:1', label: '1 × 1', ratio: 1 },
{ id: '4:5', label: '4 × 5', ratio: 4 / 5 },
{ id: '5:4', label: '5 × 4', ratio: 5 / 4 },
{ id: '4:3', label: '4 × 3', ratio: 4 / 3 },
{ id: '3:2', label: '3 × 2', ratio: 3 / 2 },
{ id: '16:9', label: '16 × 9', ratio: 16 / 9 },
{ id: '2:1', label: '2 × 1', ratio: 2 },
{ id: '9:16', label: '9 × 16', ratio: 9 / 16 },
];
export function defaultCrop(): CropState {
return { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: 'original', flipH: false, flipV: false };
}
export function identityCurve(): CurvePoint[] {
return [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
];
}
export function defaultEdits(): Edits {
return {
temp: 0,
tint: 0,
exposure: 0,
recovery: 0,
contrast: 0,
highlights: 0,
shadows: 0,
whites: 0,
blacks: 0,
texture: 0,
clarity: 0,
dehaze: 0,
vibrance: 0,
saturation: 0,
bw: false,
bwFilter: 'none',
bwFilterAmount: 100,
curve: {
rgb: identityCurve(),
red: identityCurve(),
green: identityCurve(),
blue: identityCurve(),
},
parametric: { highlights: 0, lights: 0, darks: 0, blacks: 0 },
hsl: {
hue: HUE_BANDS.map(() => 0),
sat: HUE_BANDS.map(() => 0),
lum: HUE_BANDS.map(() => 0),
},
grading: {
shadows: { h: 210, s: 0 },
highlights: { h: 45, s: 0 },
balance: 0,
},
sharpen: { amount: 0, radius: 1, detail: 25, mask: 0, lensSoftness: 0 },
proof: { enabled: false, paper: 'matte', blackPoint: 2, gamut: false },
noise: { luminance: 0, detail: 50, chroma: 0, chromaDetail: 50 },
aiDenoise: { amount: 100, key: null, model: 'guided' },
defringe: { purple: 0, green: 0 },
heal: [],
local: [],
geometry: { distortion: 0, vertical: 0, horizontal: 0, rotate: 0, scale: 100 },
vignette: { amount: 0, midpoint: 50, feather: 50 },
grain: { amount: 0, size: 25, roughness: 50 },
crop: defaultCrop(),
};
}
/** Keeps stored spots inside the image and caps the count the shader accepts. */
function healSpots(input: unknown): HealSpot[] {
if (!Array.isArray(input)) return [];
const spots: HealSpot[] = [];
for (const raw of input.slice(0, MAX_HEAL_SPOTS)) {
if (!raw || typeof raw !== 'object') continue;
const s = raw as Partial<HealSpot>;
const x = clamp01(num(s.x, 0.5, 0, 1));
const y = clamp01(num(s.y, 0.5, 0, 1));
spots.push({
x,
y,
r: num(s.r, 0.02, 0.001, 0.35),
feather: num(s.feather, 50, 0, 100),
sx: clamp01(num(s.sx, x + 0.05, 0, 1)),
sy: clamp01(num(s.sy, y, 0, 1)),
});
}
return spots;
}
function clampPoint(input: unknown, fallback: LocalPoint): LocalPoint {
if (!input || typeof input !== 'object') return fallback;
const p = input as Partial<LocalPoint>;
return { x: clamp01(num(p.x, fallback.x, 0, 1)), y: clamp01(num(p.y, fallback.y, 0, 1)) };
}
function localStrokes(input: unknown): LocalStroke[] {
if (!Array.isArray(input)) return [];
const out: LocalStroke[] = [];
for (const raw of input.slice(-300)) {
if (!raw || typeof raw !== 'object') continue;
const stroke = raw as Partial<LocalStroke>;
if (!Array.isArray(stroke.points) || !stroke.points.length) continue;
const points = stroke.points
.slice(-4000)
.map((p) => clampPoint(p, { x: 0.5, y: 0.5 }));
out.push({
points,
size: num(stroke.size, 0.04, 0.002, 0.5),
erase: !!stroke.erase,
});
}
return out;
}
function rasterMask(input: unknown): RasterMask | undefined {
if (!input || typeof input !== 'object') return undefined;
const raw = input as Partial<RasterMask>;
if (typeof raw.data !== 'string' || !raw.data || raw.data.length > 2_000_000) return undefined;
const width = Math.round(num(raw.width, 0, 1, 1024));
const height = Math.round(num(raw.height, 0, 1, 1024));
if (!width || !height) return undefined;
return { data: raw.data, width, height };
}
function localLayers(input: unknown): LocalLayer[] {
if (!Array.isArray(input)) return [];
const out: LocalLayer[] = [];
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
if (!raw || typeof raw !== 'object') continue;
const layer = raw as Partial<LocalLayer>;
const kind: LocalMaskKind =
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>;
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>;
out.push({
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
kind,
inverted: !!layer.inverted,
feather: num(layer.feather, 50, 0, 100),
brush: { strokes: localStrokes(layer.brush?.strokes) },
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
},
radial: {
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5),
},
range: {
enabled: !!range.enabled,
lumaMin: num(range.lumaMin, 0, 0, 100),
lumaMax: num(range.lumaMax, 100, 0, 100),
hue: num(range.hue, 30, 0, 360),
hueRange: num(range.hueRange, 180, 0, 180),
satMin: num(range.satMin, 0, 0, 100),
},
adjust: {
exposure: num(adjust.exposure, 0, -4, 4),
contrast: num(adjust.contrast, 0, -100, 100),
highlights: num(adjust.highlights, 0, -100, 100),
shadows: num(adjust.shadows, 0, -100, 100),
temp: num(adjust.temp, 0, -100, 100),
tint: num(adjust.tint, 0, -100, 100),
saturation: num(adjust.saturation, 0, -100, 100),
},
});
}
return out;
}
function bands(input: unknown): number[] {
const arr = Array.isArray(input) ? input : [];
return HUE_BANDS.map((_, i) => {
const v = arr[i];
return typeof v === 'number' && Number.isFinite(v) ? clamp(v, -100, 100) : 0;
});
}
function num(value: unknown, fallback: number, lo: number, hi: number): number {
return typeof value === 'number' && Number.isFinite(value) ? clamp(value, lo, hi) : fallback;
}
/** Deep-merge stored edits with the current defaults so older records keep working. */
function lensProfile(input: unknown): LensProfile | undefined {
if (!input || typeof input !== 'object') return undefined;
const raw = input as Partial<LensProfile>;
if (typeof raw.maker !== 'string' || typeof raw.model !== 'string') return undefined;
const maker = raw.maker.trim();
const model = raw.model.trim();
if (!maker || !model) return undefined;
const corrections = raw.corrections as Partial<LensCorrections> | undefined;
return {
maker,
model,
crop: num(raw.crop, 1, 0.3, 10),
cameraMaker: typeof raw.cameraMaker === 'string' ? raw.cameraMaker : undefined,
cameraModel: typeof raw.cameraModel === 'string' ? raw.cameraModel : undefined,
corrections: {
distortion: corrections?.distortion !== false,
tca: corrections?.tca !== false,
vignetting: corrections?.vignetting !== false,
},
distance: num(raw.distance, 1000, 0.1, 100000),
};
}
export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits {
const d = defaultEdits();
if (!input) return d;
const curve = (input.curve ?? {}) as Partial<Edits['curve']>;
const parametric = (input.parametric ?? {}) as Partial<Edits['parametric']>;
const grading = (input.grading ?? {}) as Partial<Edits['grading']>;
const sharpen = (input.sharpen ?? {}) as Partial<Edits['sharpen']>;
const noise = (input.noise ?? {}) as Partial<Edits['noise']>;
const aiDenoise = (input.aiDenoise ?? {}) as Partial<Edits['aiDenoise']>;
const defringe = (input.defringe ?? {}) as Partial<Edits['defringe']>;
const vignette = (input.vignette ?? {}) as Partial<Edits['vignette']>;
const grain = (input.grain ?? {}) as Partial<Edits['grain']>;
const crop = (input.crop ?? {}) as Partial<CropState>;
return {
...d,
...input,
aiDenoise: {
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
model: 'guided',
},
temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100),
exposure: num(input.exposure, 0, -5, 5),
recovery: num(input.recovery, 0, 0, 100),
contrast: num(input.contrast, 0, -100, 100),
highlights: num(input.highlights, 0, -100, 100),
shadows: num(input.shadows, 0, -100, 100),
whites: num(input.whites, 0, -100, 100),
blacks: num(input.blacks, 0, -100, 100),
texture: num(input.texture, 0, -100, 100),
clarity: num(input.clarity, 0, -100, 100),
dehaze: num(input.dehaze, 0, -100, 100),
vibrance: num(input.vibrance, 0, -100, 100),
saturation: num(input.saturation, 0, -100, 100),
bw: !!input.bw,
bwFilter: BW_FILTERS.some((f) => f.id === input.bwFilter) ? (input.bwFilter as BwFilter) : 'none',
bwFilterAmount: num(input.bwFilterAmount, d.bwFilterAmount, 0, 100),
curve: {
rgb: sanitizeCurve(curve.rgb),
red: sanitizeCurve(curve.red),
green: sanitizeCurve(curve.green),
blue: sanitizeCurve(curve.blue),
},
parametric: {
highlights: num(parametric.highlights, 0, -100, 100),
lights: num(parametric.lights, 0, -100, 100),
darks: num(parametric.darks, 0, -100, 100),
blacks: num(parametric.blacks, 0, -100, 100),
},
hsl: {
hue: bands(input.hsl?.hue),
sat: bands(input.hsl?.sat),
lum: bands(input.hsl?.lum),
},
grading: {
shadows: {
h: num(grading.shadows?.h, d.grading.shadows.h, 0, 360),
s: num(grading.shadows?.s, 0, 0, 100),
},
highlights: {
h: num(grading.highlights?.h, d.grading.highlights.h, 0, 360),
s: num(grading.highlights?.s, 0, 0, 100),
},
balance: num(grading.balance, 0, -100, 100),
},
sharpen: {
amount: num(sharpen.amount, 0, 0, 150),
radius: num(sharpen.radius, 1, 0.5, 3),
detail: num(sharpen.detail, 25, 0, 100),
mask: num(sharpen.mask, 0, 0, 100),
lensSoftness: num(sharpen.lensSoftness, 0, 0, 100),
},
proof: {
enabled: !!input.proof?.enabled,
paper: input.proof?.paper === 'gloss' || input.proof?.paper === 'newsprint' ? input.proof.paper : 'matte',
blackPoint: num(input.proof?.blackPoint, 2, 0, 20),
gamut: !!input.proof?.gamut,
},
noise: {
luminance: num(noise.luminance, 0, 0, 100),
detail: num(noise.detail, 50, 0, 100),
chroma: num(noise.chroma, 0, 0, 100),
chromaDetail: num(noise.chromaDetail, 50, 0, 100),
},
defringe: {
purple: num(defringe.purple, 0, 0, 100),
green: num(defringe.green, 0, 0, 100),
},
heal: healSpots(input.heal),
local: localLayers(input.local),
geometry: {
distortion: num(input.geometry?.distortion, 0, -100, 100),
vertical: num(input.geometry?.vertical, 0, -100, 100),
horizontal: num(input.geometry?.horizontal, 0, -100, 100),
rotate: num(input.geometry?.rotate, 0, -15, 15),
scale: num(input.geometry?.scale, 100, 50, 200),
},
lens: lensProfile(input.lens),
vignette: {
amount: num(vignette.amount, 0, -100, 100),
midpoint: num(vignette.midpoint, 50, 0, 100),
feather: num(vignette.feather, 50, 0, 100),
},
grain: {
amount: num(grain.amount, 0, 0, 100),
size: num(grain.size, 25, 10, 100),
roughness: num(grain.roughness, 50, 0, 100),
},
crop: {
x: clamp01(num(crop.x, 0, 0, 1)),
y: clamp01(num(crop.y, 0, 0, 1)),
w: clamp01(num(crop.w, 1, 0.02, 1)),
h: clamp01(num(crop.h, 1, 0.02, 1)),
angle: num(crop.angle, 0, -45, 45),
quarter: typeof crop.quarter === 'number' && Number.isFinite(crop.quarter)
? ((Math.round(crop.quarter) % 4) + 4) % 4
: 0,
aspect: typeof crop.aspect === 'string' ? crop.aspect : 'original',
flipH: !!crop.flipH,
flipV: !!crop.flipV,
},
};
}
const editCache = new WeakMap<Edits, boolean>();
export function isEdited(edits: Edits): boolean {
const cached = editCache.get(edits);
if (cached !== undefined) return cached;
const d = defaultEdits();
const strip = (e: Edits) => JSON.stringify({ ...e, crop: { ...e.crop, aspect: undefined } });
const result = strip(edits) !== strip(d);
editCache.set(edits, result);
return result;
}
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
const edits = normalizeEdits(input.edits);
const addedAt = input.addedAt ?? Date.now();
const meta: PhotoMeta = input.meta ?? {};
return {
id: input.id,
eventId: input.eventId ?? '',
order: typeof input.order === 'number' ? input.order : undefined,
raw: !!input.raw,
workspace: input.workspace,
decode: input.decode,
previewUrl: input.previewUrl,
thumbUrl: input.thumbUrl,
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
name: input.name ?? 'Untitled',
width: input.width ?? 0,
height: input.height ?? 0,
size: input.size ?? 0,
mime: input.mime ?? 'image/jpeg',
addedAt,
takenAt: input.takenAt,
meta,
thumb: input.thumb ?? '',
title: typeof input.title === 'string' ? input.title.slice(0, 200) : undefined,
caption: typeof input.caption === 'string' ? input.caption.slice(0, 4000) : undefined,
creator: typeof input.creator === 'string' ? input.creator.slice(0, 200) : undefined,
copyright: typeof input.copyright === 'string' ? input.copyright.slice(0, 300) : undefined,
copyOf: typeof input.copyOf === 'string' && input.copyOf ? input.copyOf : undefined,
copyName: typeof input.copyName === 'string' && input.copyName ? input.copyName.slice(0, 80) : undefined,
snapshots: Array.isArray(input.snapshots)
? input.snapshots
.filter((s) => s && typeof s === 'object' && typeof s.id === 'string' && typeof s.name === 'string')
.slice(-30)
.map((s) => ({ id: s.id, name: s.name.slice(0, 40), ts: Number(s.ts) || Date.now(), edits: normalizeEdits(s.edits) }))
: undefined,
merge: input.merge && (input.merge.kind === 'hdr' || input.merge.kind === 'panorama' || input.merge.kind === 'focus')
? { kind: input.merge.kind, sourceIds: Array.isArray(input.merge.sourceIds) ? input.merge.sourceIds : [] }
: undefined,
rating: clamp(Math.round(input.rating ?? 0), 0, 5),
deletedAt: typeof input.deletedAt === 'number' ? input.deletedAt : undefined,
stackId: typeof input.stackId === 'string' && input.stackId ? input.stackId : undefined,
stackIndex: typeof input.stackIndex === 'number' && Number.isFinite(input.stackIndex)
? Math.max(0, Math.round(input.stackIndex))
: undefined,
flag: (input.flag ?? 'none') as Flag,
color: (input.color ?? '') as ColorLabel,
keywords: Array.isArray(input.keywords) ? input.keywords : [],
edits,
history:
Array.isArray(input.history) && input.history.length
? input.history
: [{ label: 'Import', ts: addedAt, edits }],
};
}
export const COLOR_LABELS: { value: ColorLabel; name: string; hex: string }[] = [
{ value: 'red', name: 'Red', hex: '#e05252' },
{ value: 'yellow', name: 'Yellow', hex: '#e0c04a' },
{ value: 'green', name: 'Green', hex: '#56b268' },
{ value: 'blue', name: 'Blue', hex: '#4f86e0' },
{ value: 'purple', name: 'Purple', hex: '#9b6ede' },
];