import type { BwFilter, ColorLabel, CropState, CurvePoint, Edits, Flag, HealSpot, LocalComponent, 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; /** Eight masks are packed into two RGBA textures. */ export const MAX_LOCAL_LAYERS = 8; /** More shapes than this in one group stops being quicker than a second layer. */ export const MAX_LOCAL_COMPONENTS = 8; export function defaultLocalAdjust(): LocalLayer['adjust'] { return { exposure: 0, contrast: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0, temp: 0, tint: 0, saturation: 0, vibrance: 0, hue: 0, texture: 0, clarity: 0, dehaze: 0, sharpen: 0, }; } export function defaultLocalComponent(kind: LocalMaskKind): LocalComponent { return { id: `shape-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, kind, mode: 'add', 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 }, }; } 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}`, mode: 'add', components: [defaultLocalComponent(kind)], range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 }, curve: identityCurve(), 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, kelvin: null, exposure: 0, recovery: 0, contrast: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0, texture: 0, clarity: 0, dehaze: 0, vibrance: 0, saturation: 0, redscale: 0, bw: false, bwFilter: 'none', bwFilterAmount: 100, curve: { rgb: identityCurve(), red: identityCurve(), green: identityCurve(), blue: identityCurve(), }, levels: { black: 0, white: 100, gamma: 1 }, 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, intent: 'perceptual' }, cameraProfile: null, 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; 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; 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; 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; 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 }; } /** * Per-mask curve points. Masks saved before the field existed have none, and * they must come back as the identity rather than leaving the shader LUT row * undefined. */ function localCurve(input: unknown): CurvePoint[] { if (!Array.isArray(input)) return identityCurve(); const points: CurvePoint[] = []; for (const raw of input.slice(0, 16)) { if (!raw || typeof raw !== 'object') continue; const point = raw as Partial; points.push({ x: clamp01(num(point.x, 0, 0, 1)), y: clamp01(num(point.y, 0, 0, 1)) }); } points.sort((a, b) => a.x - b.x); return points.length >= 2 ? points : identityCurve(); } /** * One shape from stored edits. It also reads the pre-group flat layout, where * the layer itself carried kind/feather/brush/...: that is how every mask saved * before mask groups existed migrates into `components[0]`. */ function localComponent(input: unknown, index: number): LocalComponent | null { if (!input || typeof input !== 'object') return null; const shape = input as Partial & { kind?: unknown }; const kind: LocalMaskKind = shape.kind === 'linear' || shape.kind === 'radial' || shape.kind === 'raster' ? shape.kind : 'brush'; const linear = (shape.linear ?? {}) as Partial; const radial = (shape.radial ?? {}) as Partial; const raster = kind === 'raster' ? rasterMask(shape.raster) : undefined; // A raster shape without its coverage would composite an empty hole, so it // falls back to a brush shape that can at least be painted over. const resolved: LocalMaskKind = kind === 'raster' && !raster ? 'brush' : kind; return { id: typeof shape.id === 'string' && shape.id ? shape.id.slice(0, 60) : `shape-${index}`, kind: resolved, mode: shape.mode === 'subtract' || shape.mode === 'intersect' ? shape.mode : 'add', inverted: !!shape.inverted, feather: num(shape.feather, 50, 0, 100), brush: { strokes: localStrokes(shape.brush?.strokes) }, raster: resolved === 'raster' ? 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), }, }; } 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; const adjust = (layer.adjust ?? {}) as Partial; const range = (layer.range ?? {}) as Partial; const stored = Array.isArray(layer.components) && layer.components.length ? layer.components : [layer]; const components: LocalComponent[] = []; for (const entry of stored.slice(0, MAX_LOCAL_COMPONENTS)) { const component = localComponent(entry, components.length); if (component) components.push(component); } // A layer must keep at least one shape, or it would adjust nothing with no // way to tell why from the panel. if (!components.length) components.push(defaultLocalComponent('brush')); 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}`, mode: layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add', components, 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), }, curve: localCurve(layer.curve), 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), whites: num(adjust.whites, 0, -100, 100), blacks: num(adjust.blacks, 0, -100, 100), temp: num(adjust.temp, 0, -100, 100), tint: num(adjust.tint, 0, -100, 100), saturation: num(adjust.saturation, 0, -100, 100), vibrance: num(adjust.vibrance, 0, -100, 100), hue: num(adjust.hue, 180, -180, 180), texture: num(adjust.texture, 0, -100, 100), clarity: num(adjust.clarity, 0, -100, 100), dehaze: num(adjust.dehaze, 0, -100, 100), sharpen: num(adjust.sharpen, 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; 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 | 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, // The vignetting map is a flat-field gain applied to the already // tone-mapped proxy, which pushes the corners brighter than the frame // centre and over-exposes the edges. It stays opt-in, so a profile saved // without an explicit flag never brightens the corners. vignetting: corrections?.vignetting === true, }, distance: num(raw.distance, 1000, 0.1, 100000), }; } /** * Keeps a stored camera profile usable: a profile with a missing or non-finite * matrix would black out the photo, so it is dropped instead. */ export function normalizeCameraProfile(value: unknown): Edits['cameraProfile'] { if (!value || typeof value !== 'object') return null; const raw = value as { name?: unknown; matrix?: unknown }; if (!Array.isArray(raw.matrix)) return null; const matrix = raw.matrix.slice(0, 9).map(Number); if (matrix.length !== 9 || !matrix.every(Number.isFinite)) return null; const name = typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim().slice(0, 80) : 'Camera profile'; return { name, matrix }; } export function normalizeEdits(input: Partial | undefined | null): Edits { const d = defaultEdits(); if (!input) return d; const curve = (input.curve ?? {}) as Partial; const levels = (input.levels ?? {}) as Partial; const parametric = (input.parametric ?? {}) as Partial; const grading = (input.grading ?? {}) as Partial; const sharpen = (input.sharpen ?? {}) as Partial; const noise = (input.noise ?? {}) as Partial; const aiDenoise = (input.aiDenoise ?? {}) as Partial; const defringe = (input.defringe ?? {}) as Partial; const vignette = (input.vignette ?? {}) as Partial; const grain = (input.grain ?? {}) as Partial; const crop = (input.crop ?? {}) as Partial; return { ...d, ...input, cameraProfile: normalizeCameraProfile(input.cameraProfile), 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), kelvin: typeof input.kelvin === 'number' && Number.isFinite(input.kelvin) ? clamp(input.kelvin, 1500, 15000) : null, 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), redscale: num(input.redscale, 0, 0, 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), }, levels: { black: num(levels.black, 0, 0, 45), white: Math.max( num(levels.black, 0, 0, 45) + 5, num(levels.white, 100, 55, 100), ), gamma: num(levels.gamma, 1, 0.3, 3), }, 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, intent: input.proof?.intent === 'relative' || input.proof?.intent === 'saturation' ? input.proof.intent : 'perceptual', }, 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(); 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 & { 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, previewVersion: typeof input.previewVersion === 'number' && Number.isFinite(input.previewVersion) ? input.previewVersion : undefined, 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' }, ];