Write ratings, keywords, hierarchy and IPTC to XMP

Sidecars and JPEG exports now carry xmp:Rating, xmp:Label, dc:subject and
lr:hierarchicalSubject plus the IPTC core, and importing a sidecar applies its
cataloguing fields independently of its develop settings. Hierarchical keywords
keep leaf terms in the flat list, so search and filters are unchanged.
This commit is contained in:
2026-12-02 03:30:57 +00:00
parent fa0a7e64ef
commit 7f0838156b
11 changed files with 808 additions and 27 deletions
+27
View File
@@ -994,6 +994,33 @@ listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
--- ---
## Metadata portability
The catalog is not the only copy of what you typed. Ratings, colour labels, keywords and
IPTC fields are written into XMP in both directions, so a library can leave.
- **Two keyword lists, on purpose.** `photo.keywords` holds the leaf terms and is what search
and filters read; `photo.keywordPaths` holds the full `A > B > C` chains. Typing
`Nature > Birds > Robin` records `Nature`, `Nature > Birds` and the full path, and adds
`Robin` to the flat list, so taggers never have to think about the tree and search never
has to.
- **The pair Lightroom writes.** `dc:subject` carries the leaves, `lr:hierarchicalSubject`
the paths, and `xmp:Rating` / `xmp:Label` the rating and colour label. Another editor
sees the same thing Luminary does; a library can be rebuilt from sidecars instead of
from this database.
- **IPTC core.** Headline, credit, source, city, state, country and sublocation are edited
in the Metadata panel and written as `photoshop:` and `Iptc4xmpCore:` properties.
- **Import reads both halves.** Importing a sidecar applies its develop settings and its
cataloguing fields independently: a metadata-only file from a DAM imports without a
`crs:` grade, and a grade imports without keywords. Nothing the file omits is cleared.
- **Exported files carry it too.** A JPEG export embeds the same packet as the sidecar, so a
delivered file keeps its rating, keywords, hierarchy and IPTC.
`src/lib/keywords.ts` owns the path rules (separators, ancestors, pruning a subtree and
leaving no orphan leaves); `src/lib/xmp.ts` owns the mapping to and from XMP.
---
## Lens profiles ## Lens profiles
Lens correction uses the calibration data of the Lens correction uses the calibration data of the
+59 -5
View File
@@ -71,7 +71,7 @@ import type { MergeResult } from './lib/merge';
import { evictBitmap } from './lib/images'; import { evictBitmap } from './lib/images';
import { importFiles, uid } from './lib/import'; import { importFiles, uid } from './lib/import';
import { PRESETS } from './lib/presets'; import { PRESETS } from './lib/presets';
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp'; import { downloadXmp, readXmpFile, xmpToEdits, xmpToMetadata } from './lib/xmp';
import type { import type {
Edits, Edits,
EventRecord, EventRecord,
@@ -2099,12 +2099,63 @@ export default function App() {
try { try {
const xml = await readXmpFile(); const xml = await readXmpFile();
if (!xml) return; if (!xml) return;
// A sidecar can carry a grade, cataloguing fields, or both. Read the two
// halves independently: a metadata-only file from a DAM must not fail for
// lacking crs: settings, and a grade must not be rejected for lacking
// keywords. Whichever half is present is applied; neither wipes the other.
let edits = target.edits;
let settingsNote = '';
try {
const result = xmpToEdits(xml, target.edits); const result = xmpToEdits(xml, target.edits);
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar'); edits = result.edits;
setToast( settingsNote =
result.source === 'luminary' result.source === 'luminary'
? 'Imported Luminary settings from the sidecar' ? 'Luminary settings'
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`, : `${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`;
} catch {
settingsNote = '';
}
const meta = xmpToMetadata(xml);
const patch: Partial<PhotoRecord> = {};
const fields: string[] = [];
if (edits !== target.edits) patch.edits = edits;
if (meta.rating !== undefined) {
patch.rating = meta.rating;
fields.push('rating');
}
if (meta.label) {
patch.color = meta.label;
fields.push('label');
}
const keywords = new Set(target.keywords);
for (const word of meta.keywords) keywords.add(word);
if (keywords.size !== target.keywords.length) {
patch.keywords = [...keywords];
fields.push('keywords');
}
const paths = new Set(target.keywordPaths ?? []);
for (const path of meta.keywordPaths) paths.add(path);
if (paths.size !== (target.keywordPaths?.length ?? 0)) {
patch.keywordPaths = [...paths];
fields.push('keyword paths');
}
if (Object.keys(meta.iptc).length > 0) {
patch.iptc = { ...target.iptc, ...meta.iptc };
fields.push('IPTC');
}
if (meta.title && !target.title) patch.title = meta.title;
if (meta.caption) patch.caption = meta.caption;
if (meta.creator) patch.creator = meta.creator;
if (meta.copyright) patch.copyright = meta.copyright;
if (!patch.edits && fields.length === 0) {
throw new Error('That sidecar has no settings or metadata to import');
}
updatePhoto(target.id, patch, 'Import XMP sidecar');
setToast(
[settingsNote, fields.join(', ')].filter(Boolean).join(' · ') || 'Imported the sidecar',
); );
} catch (err) { } catch (err) {
setToast(err instanceof Error ? err.message : 'Could not import the sidecar'); setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
@@ -2516,6 +2567,9 @@ export default function App() {
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)} onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
metadataPresets={metadataPresets} metadataPresets={metadataPresets}
keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()} keywordLibrary={[...new Set(photos.flatMap((photo) => photo.keywords))].sort()}
keywordPathLibrary={[
...new Set(photos.flatMap((photo) => photo.keywordPaths ?? [])),
].sort()}
onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)} onSaveSnapshot={(name) => saveSnapshot(activePhoto.id, name)}
onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)} onRestoreSnapshot={(snapshot) => restoreSnapshot(activePhoto.id, snapshot)}
onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)} onDeleteSnapshot={(snapshot) => deleteSnapshot(activePhoto.id, snapshot.id)}
+4
View File
@@ -157,6 +157,8 @@ interface Props {
onVirtualCopy: () => void; onVirtualCopy: () => void;
metadataPresets: MetadataPreset[]; metadataPresets: MetadataPreset[];
keywordLibrary: string[]; keywordLibrary: string[];
/** Hierarchical paths already in the library, for metadata suggestions. */
keywordPathLibrary?: string[];
onSaveSnapshot: (name: string) => void; onSaveSnapshot: (name: string) => void;
onRestoreSnapshot: (snapshot: Snapshot) => void; onRestoreSnapshot: (snapshot: Snapshot) => void;
onDeleteSnapshot: (snapshot: Snapshot) => void; onDeleteSnapshot: (snapshot: Snapshot) => void;
@@ -191,6 +193,7 @@ export default function Develop({
onVirtualCopy, onVirtualCopy,
metadataPresets, metadataPresets,
keywordLibrary, keywordLibrary,
keywordPathLibrary = [],
onSaveSnapshot, onSaveSnapshot,
onRestoreSnapshot, onRestoreSnapshot,
onDeleteSnapshot, onDeleteSnapshot,
@@ -1773,6 +1776,7 @@ export default function Develop({
onUpdate={(patch) => onUpdate(photo.id, patch)} onUpdate={(patch) => onUpdate(photo.id, patch)}
presets={metadataPresets} presets={metadataPresets}
keywordLibrary={keywordLibrary} keywordLibrary={keywordLibrary}
keywordPathLibrary={keywordPathLibrary}
onSavePreset={onSaveMetadataPreset} onSavePreset={onSaveMetadataPreset}
onDeletePreset={onDeleteMetadataPreset} onDeletePreset={onDeleteMetadataPreset}
/> />
+107 -3
View File
@@ -11,6 +11,7 @@ import {
} from '../lib/denoiseModels'; } from '../lib/denoiseModels';
import type { DenoiseProgress } from '../lib/api'; import type { DenoiseProgress } from '../lib/api';
import { clamp } from '../lib/curves'; import { clamp } from '../lib/curves';
import { addKeywordPath, removeKeywordPath } from '../lib/keywords';
import type { import type {
CurveChannel, CurveChannel,
Edits, Edits,
@@ -2662,6 +2663,7 @@ export function MetadataPanel({
onUpdate, onUpdate,
presets = [], presets = [],
keywordLibrary = [], keywordLibrary = [],
keywordPathLibrary = [],
onSavePreset, onSavePreset,
onDeletePreset, onDeletePreset,
}: { }: {
@@ -2670,6 +2672,8 @@ export function MetadataPanel({
onUpdate?: (patch: Partial<PhotoRecord>) => void; onUpdate?: (patch: Partial<PhotoRecord>) => void;
presets?: MetadataPreset[]; presets?: MetadataPreset[];
keywordLibrary?: string[]; keywordLibrary?: string[];
/** Existing hierarchical paths in the library, offered as suggestions. */
keywordPathLibrary?: string[];
onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => void; onSavePreset?: (preset: Omit<MetadataPreset, 'id'>) => void;
onDeletePreset?: (id: string) => void; onDeletePreset?: (id: string) => void;
}) { }) {
@@ -2705,11 +2709,21 @@ export function MetadataPanel({
const patch = (next: Partial<PhotoRecord>) => onUpdate?.(next); const patch = (next: Partial<PhotoRecord>) => onUpdate?.(next);
/**
* One entry point for both kinds of tag: a plain word stays flat, and
* `Nature > Birds` records the path and its ancestors. The leaf is added to
* `keywords` either way, so search and filters keep working on flat terms.
*/
const addKeyword = (raw?: string) => { const addKeyword = (raw?: string) => {
const value = (raw ?? keyword).trim().replace(/,$/, ''); const value = (raw ?? keyword).trim().replace(/,$/, '');
if (!value) return; if (!value) return;
const exists = photo.keywords.some((word) => word.toLowerCase() === value.toLowerCase()); patch(
if (!exists) patch({ keywords: [...photo.keywords, value.slice(0, 48)] }); addKeywordPath(
{ keywords: photo.keywords, keywordPaths: photo.keywordPaths ?? [] },
value,
/[>/|]/.test(value),
),
);
setKeyword(''); setKeyword('');
}; };
@@ -2717,6 +2731,19 @@ export function MetadataPanel({
patch({ keywords: photo.keywords.filter((item) => item !== word) }); patch({ keywords: photo.keywords.filter((item) => item !== word) });
}; };
const removePath = (path: string) => {
patch(
removeKeywordPath(
{ keywords: photo.keywords, keywordPaths: photo.keywordPaths ?? [] },
path,
),
);
};
const patchIptc = (field: keyof NonNullable<PhotoRecord['iptc']>, value: string) => {
patch({ iptc: { ...photo.iptc, [field]: value } });
};
const applyPreset = (id: string) => { const applyPreset = (id: string) => {
setPresetId(id); setPresetId(id);
const preset = presets.find((item) => item.id === id); const preset = presets.find((item) => item.id === id);
@@ -2795,11 +2822,32 @@ export function MetadataPanel({
</button> </button>
))} ))}
</div> </div>
{photo.keywordPaths?.length ? (
<>
<div className="metadata-keywords-head">
<span>Keyword paths</span>
<span className="muted small">{photo.keywordPaths.length}</span>
</div>
<div className="keyword-chips">
{photo.keywordPaths.map((path) => (
<button
key={path}
className="keyword-chip"
onClick={() => removePath(path)}
title="Remove this path and everything under it"
>
{path} <span aria-hidden="true">×</span>
</button>
))}
</div>
</>
) : null}
<div className="keyword-add"> <div className="keyword-add">
<input <input
value={keyword} value={keyword}
list="lumen-keyword-library" list="lumen-keyword-library"
placeholder="Add keyword…" placeholder="Add keyword, or Nature > Birds…"
onChange={(e) => setKeyword(e.target.value)} onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ',') { if (e.key === 'Enter' || e.key === ',') {
@@ -2816,9 +2864,65 @@ export function MetadataPanel({
{keywordLibrary.map((word) => ( {keywordLibrary.map((word) => (
<option key={word} value={word} /> <option key={word} value={word} />
))} ))}
{keywordPathLibrary.map((path) => (
<option key={`path:${path}`} value={path} />
))}
</datalist> </datalist>
</div> </div>
<div className="metadata-keywords-head">
<span>IPTC</span>
</div>
<label className="field">
<span>Headline</span>
<input
value={photo.iptc?.headline ?? ''}
placeholder="Who, what, where"
onChange={(e) => patchIptc('headline', e.target.value)}
disabled={!onUpdate}
/>
</label>
<div className="field-row">
<label className="field">
<span>Credit</span>
<input
value={photo.iptc?.credit ?? ''}
placeholder="Photographer credit"
onChange={(e) => patchIptc('credit', e.target.value)}
disabled={!onUpdate}
/>
</label>
<label className="field">
<span>Source</span>
<input
value={photo.iptc?.source ?? ''}
placeholder="Agency or client"
onChange={(e) => patchIptc('source', e.target.value)}
disabled={!onUpdate}
/>
</label>
</div>
<div className="field-row">
<label className="field">
<span>City</span>
<input
value={photo.iptc?.city ?? ''}
placeholder="City"
onChange={(e) => patchIptc('city', e.target.value)}
disabled={!onUpdate}
/>
</label>
<label className="field">
<span>Country</span>
<input
value={photo.iptc?.country ?? ''}
placeholder="Country"
onChange={(e) => patchIptc('country', e.target.value)}
disabled={!onUpdate}
/>
</label>
</div>
<div className="metadata-presets"> <div className="metadata-presets">
<select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}> <select value={presetId} onChange={(e) => applyPreset(e.target.value)} disabled={!presets.length || !onUpdate}>
<option value="">Apply metadata preset…</option> <option value="">Apply metadata preset…</option>
+32
View File
@@ -11,6 +11,7 @@ import type {
LocalMaskKind, LocalMaskKind,
LocalPoint, LocalPoint,
LocalStroke, LocalStroke,
IptcFields,
LensCorrections, LensCorrections,
LensProfile, LensProfile,
RasterMask, RasterMask,
@@ -638,6 +639,31 @@ export function isEdited(edits: Edits): boolean {
return result; return result;
} }
/** Trimmed, capped strings only: IPTC goes into files, so no objects or arrays. */
function textField(value: unknown, max: number): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed ? trimmed.slice(0, max) : undefined;
}
function sanitiseIptc(input: unknown): IptcFields | undefined {
if (!input || typeof input !== 'object') return undefined;
const raw = input as Record<string, unknown>;
const fields: IptcFields = {
headline: textField(raw.headline, 256),
credit: textField(raw.credit, 128),
source: textField(raw.source, 128),
city: textField(raw.city, 128),
state: textField(raw.state, 128),
country: textField(raw.country, 128),
location: textField(raw.location, 128),
};
const kept = Object.fromEntries(
Object.entries(fields).filter(([, value]) => value !== undefined),
) as IptcFields;
return Object.keys(kept).length > 0 ? kept : undefined;
}
export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord { export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): PhotoRecord {
const edits = normalizeEdits(input.edits); const edits = normalizeEdits(input.edits);
const addedAt = input.addedAt ?? Date.now(); const addedAt = input.addedAt ?? Date.now();
@@ -693,6 +719,12 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
flag: (input.flag ?? 'none') as Flag, flag: (input.flag ?? 'none') as Flag,
color: (input.color ?? '') as ColorLabel, color: (input.color ?? '') as ColorLabel,
keywords: Array.isArray(input.keywords) ? input.keywords : [], keywords: Array.isArray(input.keywords) ? input.keywords : [],
keywordPaths: Array.isArray(input.keywordPaths)
? input.keywordPaths.filter(
(path): path is string => typeof path === 'string' && path.trim().length > 0,
).slice(0, 200)
: undefined,
iptc: sanitiseIptc(input.iptc),
edits, edits,
history: history:
Array.isArray(input.history) && input.history.length Array.isArray(input.history) && input.history.length
+14 -11
View File
@@ -1,6 +1,7 @@
import type { Edits, PhotoRecord } from '../types'; import type { Edits, PhotoRecord } from '../types';
import { get16BitSource, getBitmap } from './images'; import { get16BitSource, getBitmap } from './images';
import { normalizeEdits } from './edits'; import { normalizeEdits } from './edits';
import { photoMetadataAttributes, photoMetadataElements } from './xmp';
import { buildLensCorrection } from './lensEngine'; import { buildLensCorrection } from './lensEngine';
import { outputSize, Renderer } from '../gl/renderer'; import { outputSize, Renderer } from '../gl/renderer';
import { getDenoisedBitmap } from './images'; import { getDenoisedBitmap } from './images';
@@ -272,18 +273,20 @@ function paintWatermark(source: HTMLCanvasElement, photo: PhotoRecord, opts: Exp
return canvas; return canvas;
} }
function xmlEscape(value: string) { /**
return value * The XMP packet embedded in an exported file.
.replace(/&/g, '&amp;') *
.replace(/</g, '&lt;') * Built from the same helpers the sidecar writer uses, so a JPEG and its .xmp
.replace(/>/g, '&gt;') * cannot drift: rating, colour label, keywords, the `lr:` hierarchy and the
.replace(/"/g, '&quot;'); * IPTC core all travel with the file.
} */
function buildXmp(photo: PhotoRecord) { function buildXmp(photo: PhotoRecord) {
const title = photo.title || photo.name; return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/"${photoMetadataAttributes(
const keywords = photo.keywords.map((word) => `<rdf:li>${xmlEscape(word)}</rdf:li>`).join(''); photo,
return `<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(title)}</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.caption ?? '')}</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>${xmlEscape(photo.creator ?? '')}</rdf:li></rdf:Seq></dc:creator><dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${xmlEscape(photo.copyright ?? '')}</rdf:li></rdf:Alt></dc:rights><dc:subject><rdf:Bag>${keywords}</rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(0, 65000); )}>${photoMetadataElements(photo)}</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>`.slice(
0,
65000,
);
} }
function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null { function appSegment(marker: number, header: Uint8Array, payload: Uint8Array): Uint8Array | null {
+99
View File
@@ -0,0 +1,99 @@
import { describe, expect, it } from 'vitest';
import {
addKeywordPath,
collectKeywordPaths,
keywordTree,
normalizeKeywordPath,
pathAncestors,
pathLeaf,
pathsUnder,
removeKeywordPath,
} from './keywords';
const empty = { keywords: [] as string[], keywordPaths: [] as string[] };
describe('keyword paths', () => {
it('normalises every separator to the Lightroom form', () => {
expect(normalizeKeywordPath('Nature>Birds>Robin')).toBe('Nature > Birds > Robin');
expect(normalizeKeywordPath('Nature/Birds / Robin ')).toBe('Nature > Birds > Robin');
expect(normalizeKeywordPath('Nature | Birds')).toBe('Nature > Birds');
expect(normalizeKeywordPath(' ')).toBe('');
});
it('reads the leaf and the ancestor chain', () => {
expect(pathLeaf('Nature > Birds > Robin')).toBe('Robin');
expect(pathAncestors('Nature > Birds > Robin')).toEqual([
'Nature',
'Nature > Birds',
'Nature > Birds > Robin',
]);
});
it('records ancestors and puts the leaf in the flat list', () => {
const next = addKeywordPath(empty, 'Nature > Birds > Robin');
expect(next.keywordPaths).toEqual([
'Nature',
'Nature > Birds',
'Nature > Birds > Robin',
]);
expect(next.keywords).toEqual(['Robin']);
});
it('keeps a plain word flat', () => {
const next = addKeywordPath(empty, 'Robin', false);
expect(next.keywords).toEqual(['Robin']);
expect(next.keywordPaths).toEqual([]);
});
it('does not duplicate on case alone', () => {
const first = addKeywordPath(empty, 'Nature > Birds');
const second = addKeywordPath(first, 'nature > birds');
expect(second.keywordPaths).toEqual(['Nature', 'Nature > Birds']);
expect(second.keywords).toEqual(['Birds']);
});
it('removes a subtree and the leaves it stranded', () => {
const full = addKeywordPath(addKeywordPath(empty, 'Nature > Birds > Robin'), 'Nature > Birds > Wren');
const next = removeKeywordPath(full, 'Nature > Birds');
expect(next.keywordPaths).toEqual(['Nature']);
// Robin and Wren came only from the removed branch, Birds was the node.
expect(next.keywords).toEqual([]);
});
it('keeps a leaf that another path still uses', () => {
const both = addKeywordPath(addKeywordPath(empty, 'Nature > Birds > Robin'), 'Garden > Robin');
const next = removeKeywordPath(both, 'Nature > Birds');
expect(next.keywords).toEqual(['Robin']);
expect(next.keywordPaths).toEqual(['Nature', 'Garden', 'Garden > Robin']);
});
it('collects suggestions once, sorted', () => {
const rows = [
{ keywordPaths: ['Nature > Birds', 'Nature'] },
{ keywordPaths: ['nature', 'Places > Coast'] },
{},
];
expect(collectKeywordPaths(rows)).toEqual(['Nature', 'Nature > Birds', 'Places > Coast']);
});
it('builds a tree with parents before children', () => {
const tree = keywordTree(['Nature > Birds > Robin', 'Nature > Plants', 'Places']);
expect(tree.map((node) => node.name)).toEqual(['Nature', 'Places']);
const nature = tree[0];
expect(nature.path).toBe('Nature');
expect(nature.children.map((node) => node.name)).toEqual(['Birds', 'Plants']);
expect(nature.children[0].children.map((node) => node.name)).toEqual(['Robin']);
expect(nature.children[0].children[0].path).toBe('Nature > Birds > Robin');
});
it('expands a node to everything under it', () => {
const paths = ['Nature', 'Nature > Birds', 'Nature > Birds > Robin', 'Places > Coast'];
expect(pathsUnder(paths, 'Nature > Birds')).toEqual([
'Nature > Birds',
'Nature > Birds > Robin',
]);
expect(pathsUnder(paths, 'Places')).toEqual(['Places > Coast']);
// A prefix that is not a path boundary must not match.
expect(pathsUnder(paths, 'Nat')).toEqual([]);
});
});
+181
View File
@@ -0,0 +1,181 @@
/**
* Hierarchical keywords, stored so other software can still read them.
*
* A flat keyword list is portable but useless past a few hundred terms; a tree
* is useful but has no agreed storage format. Lightroom's answer is to write
* both: `dc:subject` carries the leaf terms, `lr:hierarchicalSubject` carries
* the full paths. This module keeps the same pair in the catalog:
*
* keywords ['Robin'] <- what search and filters use
* keywordPaths ['Nature > Birds > Robin'] <- where it sits
*
* Ancestors are included in `keywordPaths` the way Lightroom does, so a path is
* never a dangling leaf and importing a sidecar cannot invent a parent.
*
* The separator is `>` with spaces because that is the convention every DAM
* reads and writes; a user typing `Nature>Birds` gets normalised.
*/
export const KEYWORD_SEPARATOR = ' > ';
const MAX_DEPTH = 6;
const MAX_SEGMENT = 48;
export interface KeywordPaths {
keywords: string[];
keywordPaths: string[];
}
/** Split a typed path into clean segments. Accepts `>`, `/` and `|`. */
export function pathSegments(input: string): string[] {
return input
.split(/\s*(?:>|\/|\|)\s*/)
.map((part) => part.trim())
.filter(Boolean)
.slice(0, MAX_DEPTH)
.map((part) => part.slice(0, MAX_SEGMENT));
}
/** Canonical `A > B > C` form for a typed or imported path. */
export function normalizeKeywordPath(input: string): string {
return pathSegments(input).join(KEYWORD_SEPARATOR);
}
/** The leaf term of a path, which is what `keywords` stores. */
export function pathLeaf(path: string): string {
const segments = pathSegments(path);
return segments[segments.length - 1] ?? '';
}
/** `A > B > C` → `['A', 'A > B', 'A > B > C']`. */
export function pathAncestors(path: string): string[] {
const segments = pathSegments(path);
return segments.map((_, index) => segments.slice(0, index + 1).join(KEYWORD_SEPARATOR));
}
function sameKey(a: string, b: string) {
return a.toLowerCase() === b.toLowerCase();
}
function addUnique(list: string[], value: string) {
if (!value) return;
if (list.some((item) => sameKey(item, value))) return;
list.push(value);
}
/**
* Add a typed path (or a plain keyword) to a photo's pair of lists.
*
* A plain word stays flat; anything with a separator also records its
* ancestors. The leaf always lands in `keywords`, so a photo tagged
* `Nature > Birds > Robin` still matches a search for "Robin".
*/
export function addKeywordPath(
current: KeywordPaths,
input: string,
asPath = input.includes('>') || input.includes('/') || input.includes('|'),
): KeywordPaths {
const keywords = [...current.keywords];
const keywordPaths = [...current.keywordPaths];
const normalized = normalizeKeywordPath(input);
if (!normalized) return { keywords, keywordPaths };
addUnique(keywords, pathLeaf(normalized));
if (asPath) {
for (const ancestor of pathAncestors(normalized)) addUnique(keywordPaths, ancestor);
}
return { keywords, keywordPaths };
}
/**
* Remove a path and everything under it, then drop leaves that nothing refers
* to any more. Removing `Birds` must not leave `Robin` behind as a keyword with
* no tree above it, which is how hierarchies rot.
*/
export function removeKeywordPath(current: KeywordPaths, path: string): KeywordPaths {
const target = normalizeKeywordPath(path);
if (!target) return current;
const removed = current.keywordPaths.filter(
(entry) => entry === target || entry.startsWith(`${target}${KEYWORD_SEPARATOR}`),
);
const keywordPaths = current.keywordPaths.filter((entry) => !removed.includes(entry));
// Every leaf the removal takes with it: the node's own and its descendants'.
const goneLeaves = new Set(removed.map((entry) => pathLeaf(entry).toLowerCase()));
goneLeaves.add(pathLeaf(target).toLowerCase());
const stillUsed = new Set(keywordPaths.map((entry) => pathLeaf(entry).toLowerCase()));
const keywords = current.keywords.filter(
(word) => stillUsed.has(word.toLowerCase()) || !goneLeaves.has(word.toLowerCase()),
);
return { keywords, keywordPaths };
}
/** Every path in a library, sorted, for suggestions. */
export function collectKeywordPaths(rows: { keywordPaths?: string[] }[]): string[] {
// Case-insensitive dedupe, first spelling wins: "nature" and "Nature" are
// one suggestion, not two entries that look like a bug.
const seen = new Map<string, string>();
for (const row of rows) {
for (const path of row.keywordPaths ?? []) {
const normalized = normalizeKeywordPath(path);
const key = normalized.toLowerCase();
if (normalized && !seen.has(key)) seen.set(key, normalized);
}
}
return [...seen.values()].sort((a, b) => a.localeCompare(b));
}
export interface KeywordNode {
/** Segment name, e.g. "Birds". */
name: string;
/** Full path, e.g. "Nature > Birds". */
path: string;
children: KeywordNode[];
}
function insert(nodes: KeywordNode[], segments: string[], prefix: string[] = []) {
const [head, ...rest] = segments;
if (!head) return;
// The path is this node's own, built from the prefix above it -- not the
// whole path being inserted, which would rename every parent to its deepest
// descendant.
const selfPath = [...prefix, head];
let node = nodes.find((entry) => entry.name.toLowerCase() === head.toLowerCase());
if (!node) {
node = { name: head, path: selfPath.join(KEYWORD_SEPARATOR), children: [] };
nodes.push(node);
}
if (rest.length > 0) insert(node.children, rest, selfPath);
}
/** Paths → a tree for rendering. Sorted, with parents before children. */
export function keywordTree(paths: string[]): KeywordNode[] {
const roots: KeywordNode[] = [];
for (const path of paths) {
const segments = pathSegments(path);
if (segments.length === 0) continue;
if (segments.length === 1) {
// A flat keyword appears as its own root, with no children.
if (!roots.some((node) => node.name.toLowerCase() === segments[0].toLowerCase())) {
roots.push({ name: segments[0], path: segments[0], children: [] });
}
continue;
}
insert(roots, segments);
}
const sort = (nodes: KeywordNode[]) => {
nodes.sort((a, b) => a.name.localeCompare(b.name));
for (const node of nodes) sort(node.children);
};
sort(roots);
return roots;
}
/** Every path at or under `root`, so tagging a parent tags its children. */
export function pathsUnder(paths: string[], root: string): string[] {
const target = normalizeKeywordPath(root);
if (!target) return [];
return paths.filter(
(path) => path === target || path.startsWith(`${target}${KEYWORD_SEPARATOR}`),
);
}
+76 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits'; import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp'; import { editsToXmp, xmpFileName, xmpToEdits, xmpToMetadata } from './xmp';
describe('xmp sidecars', () => { describe('xmp sidecars', () => {
it('round-trips every develop field exactly', () => { it('round-trips every develop field exactly', () => {
@@ -55,3 +55,78 @@ describe('xmp sidecars', () => {
expect(xmpFileName('no-extension')).toBe('no-extension.xmp'); expect(xmpFileName('no-extension')).toBe('no-extension.xmp');
}); });
}); });
describe('xmp metadata', () => {
const photo = {
name: 'DSC0123.ARW',
meta: {},
rating: 4,
color: 'green' as const,
keywords: ['Birds', 'Robin'],
keywordPaths: ['Nature', 'Nature > Birds', 'Nature > Birds > Robin'],
iptc: {
headline: 'Dawn chorus',
credit: 'B. Hursey',
source: 'Field notes',
city: 'Bristol',
state: 'Somerset',
country: 'UK',
location: 'Ashton Court',
},
title: 'Robin at dawn',
caption: 'First light, heavy frost',
creator: 'Brian Hursey',
copyright: '© 2026 Brian Hursey',
};
it('writes rating, label, keywords, hierarchy and IPTC, and reads them back', () => {
const xml = editsToXmp(defaultEdits(), photo);
expect(xml).toContain('xmp:Rating="4"');
expect(xml).toContain('xmp:Label="Green"');
expect(xml).toContain('<lr:hierarchicalSubject>');
expect(xml).toContain('photoshop:City="Bristol"');
expect(xml).toContain('Iptc4xmpCore:Location="Ashton Court"');
const meta = xmpToMetadata(xml);
expect(meta.rating).toBe(4);
expect(meta.label).toBe('green');
expect(meta.keywords).toEqual(['Birds', 'Robin']);
expect(meta.keywordPaths).toEqual([
'Nature',
'Nature > Birds',
'Nature > Birds > Robin',
]);
expect(meta.iptc).toEqual(photo.iptc);
expect(meta.title).toBe('Robin at dawn');
expect(meta.caption).toBe('First light, heavy frost');
expect(meta.creator).toBe('Brian Hursey');
expect(meta.copyright).toBe('© 2026 Brian Hursey');
});
it('reads a sidecar written by Lightroom', () => {
const xml = `<?xpacket begin=""?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmp:Rating="2" xmp:Label="Red" photoshop:Headline="Press day" photoshop:Country="Ireland"><dc:subject><rdf:Bag><rdf:li>Portrait</rdf:li><rdf:li>Maya</rdf:li></rdf:Bag></dc:subject><lr:hierarchicalSubject><rdf:Bag><rdf:li>People &gt; Portrait</rdf:li></rdf:Bag></lr:hierarchicalSubject></rdf:Description></rdf:RDF></x:xmpmeta>`;
const meta = xmpToMetadata(xml);
expect(meta.rating).toBe(2);
expect(meta.label).toBe('red');
expect(meta.keywords).toEqual(['Portrait', 'Maya']);
expect(meta.keywordPaths).toEqual(['People > Portrait']);
expect(meta.iptc.headline).toBe('Press day');
expect(meta.iptc.country).toBe('Ireland');
// Nothing the file does not carry is invented.
expect(meta.iptc.city).toBeUndefined();
expect(meta.caption).toBeUndefined();
});
it('stays quiet when the file has no metadata', () => {
const meta = xmpToMetadata(editsToXmp(defaultEdits()));
expect(meta.rating).toBeUndefined();
expect(meta.label).toBeUndefined();
expect(meta.keywords).toEqual([]);
expect(meta.keywordPaths).toEqual([]);
expect(meta.iptc).toEqual({});
});
it('rejects a file that is not a sidecar', () => {
expect(() => xmpToMetadata('<html></html>')).toThrow(/not an XMP/);
});
});
+184 -6
View File
@@ -1,6 +1,60 @@
import type { Edits, PhotoRecord } from '../types'; import type { ColorLabel, Edits, IptcFields, PhotoRecord } from '../types';
import { normalizeEdits } from './edits'; import { normalizeEdits } from './edits';
/**
* Everything a sidecar carries besides the develop settings: rating, label,
* keywords (flat and hierarchical) and the IPTC core.
*
* `dc:subject` and `lr:hierarchicalSubject` are written as a pair, the way
* Lightroom does: the leaves in the first, the full paths in the second. A
* reader that only understands one of them still gets something usable, and a
* library round-tripped through another editor keeps its tree.
*/
export type XmpPhotoFields = Partial<
Pick<
PhotoRecord,
| 'name'
| 'meta'
| 'rating'
| 'color'
| 'keywords'
| 'keywordPaths'
| 'iptc'
| 'title'
| 'caption'
| 'creator'
| 'copyright'
>
>;
/** Lightroom's label names, which are what other software reads. */
const LABEL_NAMES: Record<Exclude<ColorLabel, ''>, string> = {
red: 'Red',
yellow: 'Yellow',
green: 'Green',
blue: 'Blue',
purple: 'Purple',
};
const LABEL_VALUES: Record<string, Exclude<ColorLabel, ''>> = {
red: 'red',
yellow: 'yellow',
green: 'green',
blue: 'blue',
purple: 'purple',
};
/** IPTC field → the XMP property that carries it. */
const IPTC_ATTRS: [keyof IptcFields, string][] = [
['headline', 'photoshop:Headline'],
['credit', 'photoshop:Credit'],
['source', 'photoshop:Source'],
['city', 'photoshop:City'],
['state', 'photoshop:State'],
['country', 'photoshop:Country'],
['location', 'Iptc4xmpCore:Location'],
];
/** /**
* Lightroom-compatible XMP sidecars. * Lightroom-compatible XMP sidecars.
* *
@@ -105,7 +159,70 @@ export function xmpFileName(name: string) {
return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`; return `${name.replace(/\.[^.]+$/, '') || 'photo'}.xmp`;
} }
export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'meta'>): string { /** Rating, colour label and IPTC, as XMP attributes on the Description. */
export function photoMetadataAttributes(photo?: XmpPhotoFields): string {
if (!photo) return '';
const attrs: string[] = [];
const rating = Math.round(photo.rating ?? 0);
if (rating > 0) attrs.push(`xmp:Rating="${Math.max(0, Math.min(5, rating))}"`);
const label = photo.color ? LABEL_NAMES[photo.color] : '';
if (label) attrs.push(`xmp:Label="${label}"`);
const iptc = photo.iptc ?? {};
for (const [field, property] of IPTC_ATTRS) {
const value = iptc[field];
if (typeof value === 'string' && value.trim()) {
attrs.push(`${property}="${escapeXml(value.trim())}"`);
}
}
return attrs.length ? ` ${attrs.join(' ')}` : '';
}
/** Title, caption, creator, rights, keywords and the hierarchy, as elements. */
export function photoMetadataElements(photo?: XmpPhotoFields): string {
const parts: string[] = [];
const title = photo?.title?.trim() || photo?.name?.trim() || 'Luminary edit';
parts.push(
`<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(title)}</rdf:li></rdf:Alt></dc:title>`,
);
if (photo?.caption?.trim()) {
parts.push(
`<dc:description><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(
photo.caption.trim(),
)}</rdf:li></rdf:Alt></dc:description>`,
);
}
if (photo?.creator?.trim()) {
parts.push(
`<dc:creator><rdf:Seq><rdf:li>${escapeXml(photo.creator.trim())}</rdf:li></rdf:Seq></dc:creator>`,
);
}
if (photo?.copyright?.trim()) {
parts.push(
`<dc:rights><rdf:Alt><rdf:li xml:lang="x-default">${escapeXml(
photo.copyright.trim(),
)}</rdf:li></rdf:Alt></dc:rights>`,
);
}
const keywords = (photo?.keywords ?? []).filter((word) => word && word.trim());
if (keywords.length) {
parts.push(
`<dc:subject><rdf:Bag>${keywords
.map((word) => `<rdf:li>${escapeXml(word)}</rdf:li>`)
.join('')}</rdf:Bag></dc:subject>`,
);
}
const paths = (photo?.keywordPaths ?? []).filter((path) => path && path.trim());
if (paths.length) {
parts.push(
`<lr:hierarchicalSubject><rdf:Bag>${paths
.map((path) => `<rdf:li>${escapeXml(path)}</rdf:li>`)
.join('')}</rdf:Bag></lr:hierarchicalSubject>`,
);
}
return parts.join('');
}
export function editsToXmp(edits: Edits, photo?: XmpPhotoFields): string {
const normalized = normalizeEdits(edits); const normalized = normalizeEdits(edits);
const attrs = CRS_FIELDS.map( const attrs = CRS_FIELDS.map(
([name, read]) => `crs:${name}="${num(read(normalized))}"`, ([name, read]) => `crs:${name}="${num(read(normalized))}"`,
@@ -113,16 +230,15 @@ export function editsToXmp(edits: Edits, photo?: Pick<PhotoRecord, 'name' | 'met
attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`); attrs.push(`crs:ConvertToGrayscale="${normalized.bw ? 'True' : 'False'}"`);
if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`); if (normalized.kelvin != null) attrs.push(`crs:Temperature="${Math.round(normalized.kelvin)}"`);
attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`); attrs.push(`lum:Settings="${escapeXml(base64Encode(JSON.stringify(normalized)))}"`);
const label = photo ? escapeXml(photo.name) : 'Luminary edit';
return [ return [
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>', '<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>',
'<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">', '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Luminary">',
' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">', ' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">',
` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}"`, ` <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmlns:lum="${LUM_NS}" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:lr="http://ns.adobe.com/lightroom/1.0/"`,
' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"', ' crs:Version="15.0" crs:ProcessVersion="15.4" crs:HasSettings="True"',
` ${attrs.join('\n ')}>`, ` ${attrs.join('\n ')}${photoMetadataAttributes(photo)}>`,
` <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/"><rdf:Alt><rdf:li xml:lang="x-default">${label}</rdf:li></rdf:Alt></dc:title>`, ` ${photoMetadataElements(photo)}`,
' </rdf:Description>', ' </rdf:Description>',
' </rdf:RDF>', ' </rdf:RDF>',
'</x:xmpmeta>', '</x:xmpmeta>',
@@ -202,6 +318,68 @@ export function xmpToEdits(xml: string, base: Edits): XmpImport {
return { edits: normalizeEdits(next), source: 'lightroom', applied }; return { edits: normalizeEdits(next), source: 'lightroom', applied };
} }
export interface XmpMetadata {
rating?: number;
label?: Exclude<ColorLabel, ''>;
keywords: string[];
keywordPaths: string[];
iptc: IptcFields;
title?: string;
caption?: string;
creator?: string;
copyright?: string;
}
/** `<dc:subject><rdf:Bag><rdf:li>…` → the items, unescaped. */
function bagItems(xml: string, tag: string): string[] {
const block = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`).exec(xml);
if (!block) return [];
return [...block[1].matchAll(/<rdf:li\b[^>]*>([\s\S]*?)<\/rdf:li>/g)]
.map((match) => unescapeXml(match[1].trim()))
.filter(Boolean);
}
/**
* Read the metadata half of a sidecar: rating, label, keywords, hierarchy and
* IPTC. Separate from `xmpToEdits` because a photographer may want the
* cataloguing fields from a file whose grade they do not want to adopt.
*
* Returns the fields the file actually carries; the caller decides what to
* overwrite, so an empty sidecar cannot wipe a photo's existing metadata.
*/
export function xmpToMetadata(xml: string): XmpMetadata {
if (!/<x:xmpmeta|<rdf:RDF/i.test(xml)) {
throw new Error('That file is not an XMP sidecar');
}
const attrs = attributes(xml);
const ratingRaw = attrs.get('xmp:Rating');
const ratingValue = ratingRaw === undefined ? NaN : Number(ratingRaw);
const rating = Number.isFinite(ratingValue)
? Math.max(0, Math.min(5, Math.round(ratingValue)))
: undefined;
const label = LABEL_VALUES[(attrs.get('xmp:Label') ?? '').toLowerCase()];
const iptc: IptcFields = {};
for (const [field, property] of IPTC_ATTRS) {
const value = attrs.get(property);
if (value) iptc[field] = value.slice(0, 256);
}
return {
rating,
label,
keywords: bagItems(xml, 'dc:subject'),
keywordPaths: bagItems(xml, 'lr:hierarchicalSubject'),
iptc,
title: bagItems(xml, 'dc:title')[0],
caption: bagItems(xml, 'dc:description')[0],
creator: bagItems(xml, 'dc:creator')[0],
copyright: bagItems(xml, 'dc:rights')[0],
};
}
/** Opens the OS picker and returns the sidecar text, or null when cancelled. */ /** Opens the OS picker and returns the sidecar text, or null when cancelled. */
export function readXmpFile(): Promise<string | null> { export function readXmpFile(): Promise<string | null> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
+24
View File
@@ -241,6 +241,21 @@ export interface Edits {
crop: CropState; crop: CropState;
} }
/** IPTC core fields, written to XMP so a catalog is readable elsewhere. */
export interface IptcFields {
/** Single-line summary, the "who/what" a picture desk reads first. */
headline?: string;
/** Who gets the credit for the image. */
credit?: string;
/** Agency or organisation that supplied it. */
source?: string;
city?: string;
state?: string;
country?: string;
/** Sublocation inside the city. */
location?: string;
}
export interface PhotoMeta { export interface PhotoMeta {
camera?: string; camera?: string;
lens?: string; lens?: string;
@@ -269,6 +284,8 @@ export interface MetadataPreset {
creator?: string; creator?: string;
copyright?: string; copyright?: string;
keywords: string[]; keywords: string[];
keywordPaths?: string[];
iptc?: IptcFields;
} }
export interface SmartCollection { export interface SmartCollection {
@@ -305,6 +322,13 @@ export interface PhotoRecord {
flag: Flag; flag: Flag;
color: ColorLabel; color: ColorLabel;
keywords: string[]; keywords: string[];
/**
* Full hierarchical paths (`A > B > C`). The leaf of each is also in
* `keywords`, so search and filters do not need to know about the tree.
*/
keywordPaths?: string[];
/** IPTC core, edited in the Metadata panel and written to XMP. */
iptc?: IptcFields;
title?: string; title?: string;
caption?: string; caption?: string;
creator?: string; creator?: string;