From a627d9147e6b880effd01c9f613081248b8bebad Mon Sep 17 00:00:00 2001 From: muena Date: Mon, 19 Oct 2026 06:49:34 +0200 Subject: [PATCH] feat: optionally sort translation mappings by creation date --- src/lib/mapping-created-at.ts | 34 +++++++ src/manage-sessions.tsx | 1 + src/restore-project-files.tsx | 5 +- src/sessions.ts | 19 +++- src/show-translation-tables.tsx | 154 +++++++++++++++++++------------ src/types.ts | 1 + tests/mapping-created-at.test.ts | 50 ++++++++++ tests/text-context.test.ts | 16 ++++ 8 files changed, 218 insertions(+), 62 deletions(-) create mode 100644 src/lib/mapping-created-at.ts create mode 100644 tests/mapping-created-at.test.ts diff --git a/src/lib/mapping-created-at.ts b/src/lib/mapping-created-at.ts new file mode 100644 index 0000000..5ffbb58 --- /dev/null +++ b/src/lib/mapping-created-at.ts @@ -0,0 +1,34 @@ +import type { ProjectRun } from "./velum-project"; +import type { PlaceholderMapping } from "../types"; + +/** Project snapshots are immutable: the first snapshot containing a matching entry dates its first Velum record. */ +export function projectMappingCreatedAt(runs: ProjectRun[], current: PlaceholderMapping): Record { + const createdAt: Record = {}; + const seen = new Set(); + for (const run of [...runs].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))) { + for (const [key, entry] of Object.entries(run.mapping)) { + const active = current[key]; + if (active && active.type === entry.type && active.original === entry.original && !seen.has(key)) { + seen.add(key); + // An imported snapshot records the migration time, not when its terms were first created. + if (run.origin !== "imported" || run.revisedFrom) createdAt[key] = run.createdAt; + } + } + } + return createdAt; +} + +/** Dated entries lead; legacy entries fall back to descending IDs within each category. */ +export function sortMappingRowsByCreatedAt( + rows: T[], createdAt: Record, +): T[] { + const timestamp = (key: string) => { + const value = Date.parse(createdAt[key] ?? ""); + return Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY; + }; + const number = (key: string) => Number(/_(\d+)>?$/u.exec(key)?.[1] ?? -1); + return [...rows].sort((a, b) => timestamp(b.placeholder) - timestamp(a.placeholder) + || a.type.localeCompare(b.type) + || number(b.placeholder) - number(a.placeholder) + || a.placeholder.localeCompare(b.placeholder)); +} diff --git a/src/manage-sessions.tsx b/src/manage-sessions.tsx index 1437c6b..773613c 100644 --- a/src/manage-sessions.tsx +++ b/src/manage-sessions.tsx @@ -151,6 +151,7 @@ export default function Command() { title="Übersetzungstabelle anzeigen" icon={Icon.List} target={ { const updated = await releaseSessionMappingGroup(session.id, root); diff --git a/src/restore-project-files.tsx b/src/restore-project-files.tsx index a5383f2..dda1b1e 100644 --- a/src/restore-project-files.tsx +++ b/src/restore-project-files.tsx @@ -12,6 +12,7 @@ import { planProjectRevision, reviseProjectRun } from "./lib/project-revision"; import { TranslationTable } from "./show-translation-tables"; import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups"; import { releaseProjectMapping } from "./project-mapping-actions"; +import { projectMappingCreatedAt } from "./lib/mapping-created-at"; type SavedRun = { run: ProjectRun; directory: string }; type RestoreDecision = MappingEntry | null; @@ -374,7 +375,8 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) { earlierRuns={props.entries.slice(index + 1)} />)} /> } /> + mapping={run.mapping} + createdAtByKey={projectMappingCreatedAt(props.entries.slice(index).map((entry) => entry.run), run.mapping)} />} /> showInFinder(runCopiesPath(run, directory))} /> @@ -439,6 +441,7 @@ export default function Command() { earlierRuns={entries.slice(1)} />)} /> entry.run), run.mapping)} onAdd={async (input) => { const updated = await addProjectMappingEntry(run.projectPath, input); await refresh(); diff --git a/src/sessions.ts b/src/sessions.ts index a61e7ba..74ef543 100644 --- a/src/sessions.ts +++ b/src/sessions.ts @@ -16,6 +16,21 @@ function sessionSort(a: VelumSession, b: VelumSession): number { return Date.parse(b.updatedAt) - Date.parse(a.updatedAt); } +function mappingDates(previous: VelumSession | undefined, mapping: PlaceholderMapping, + timestamp: string): Record { + const dates: Record = {}; + const previousKeys = new Map(Object.entries(previous?.mapping ?? {}) + .map(([key, entry]) => [key.replace(/^<|>$/g, ""), { key, entry }])); + for (const [key, entry] of Object.entries(mapping)) { + const prior = previousKeys.get(key.replace(/^<|>$/g, "")); + if (prior && prior.entry.type === entry.type && prior.entry.original === entry.original) { + const originalDate = previous?.mappingCreatedAt?.[prior.key]; + if (originalDate) dates[key] = originalDate; + } else dates[key] = timestamp; + } + return dates; +} + async function saveSessions(sessions: VelumSession[]): Promise { const maxSessions = getPreferences().maxSessions; const pruned = [...sessions].sort(sessionSort).slice(0, maxSessions); @@ -102,6 +117,7 @@ export async function updateSessionMapping( mapping, entityTypes, excludedTerms, + mappingCreatedAt: mappingDates(undefined, mapping, timestamp), }; await saveSessions([created, ...sessions]); return created; @@ -112,6 +128,7 @@ export async function updateSessionMapping( mapping, entityTypes, excludedTerms: excludedTerms ?? sessions[index].excludedTerms, + mappingCreatedAt: mappingDates(sessions[index], mapping, timestamp), updatedAt: timestamp, }; const next = [...sessions]; @@ -148,7 +165,7 @@ export async function clearSessionMapping(id: string): Promise { await saveSessions( sessions.map((session) => session.id === id - ? { ...session, mapping: {}, updatedAt: nowIso() } + ? { ...session, mapping: {}, mappingCreatedAt: {}, updatedAt: nowIso() } : session, ), ); diff --git a/src/show-translation-tables.tsx b/src/show-translation-tables.tsx index 078301c..d8ad81a 100644 --- a/src/show-translation-tables.tsx +++ b/src/show-translation-tables.tsx @@ -16,15 +16,19 @@ import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mappi import { getSession, listSessions, releaseSessionMappingGroup, updateSessionMapping } from "./sessions"; import type { PlaceholderMapping } from "./types"; import { releaseProjectMapping } from "./project-mapping-actions"; +import { projectMappingCreatedAt, sortMappingRowsByCreatedAt } from "./lib/mapping-created-at"; +import type { ProjectRun } from "./lib/velum-project"; type TableSource = { id: string; title: string; subtitle: string; mapping: PlaceholderMapping; + createdAtByKey: Record; }; type ManualEntry = { original: string; type: string; placeholder?: string }; +const EMPTY_DATES: Record = {}; function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise; onSaved: (mapping: PlaceholderMapping) => void }) { @@ -55,6 +59,7 @@ function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise; onAdd?: (input: ManualEntry) => Promise; onMerge?: (source: string, target: string) => Promise; onDetach?: (key: string) => Promise; @@ -71,8 +77,23 @@ export function TranslationTable({ }) { const { push, pop } = useNavigation(); const [visibleMapping, setVisibleMapping] = useState(mapping); + const [visibleDates, setVisibleDates] = useState(createdAtByKey); + const [sortOrder, setSortOrder] = useState<"category" | "created-desc">("category"); const [busy, setBusy] = useState(false); - useEffect(() => setVisibleMapping(mapping), [mapping]); + useEffect(() => { setVisibleMapping(mapping); setVisibleDates(createdAtByKey); }, [mapping, createdAtByKey]); + function showMapping(next: PlaceholderMapping) { + setVisibleDates((current) => { + const dates: Record = {}; + const now = new Date().toISOString(); + for (const key of Object.keys(next)) { + const date = current[key] ?? createdAtByKey[key]; + if (date) dates[key] = date; + else if (!(key in visibleMapping)) dates[key] = now; + } + return dates; + }); + setVisibleMapping(next); + } const groups = new Map>(); for (const [key, entry] of Object.entries(visibleMapping).sort(([a], [b]) => a.localeCompare(b))) { const type = entry.type || "Sonstige"; @@ -82,11 +103,14 @@ export function TranslationTable({ members.push(key); groups.get(type)!.set(root, members); } + const rows = [...groups].flatMap(([type, roots]) => [...roots].map(([placeholder, members]) => ({ + type, placeholder, members, + }))); async function change(action: () => Promise, success: string): Promise { if (busy) return false; setBusy(true); try { - setVisibleMapping(await action()); + showMapping(await action()); await showToast({ style: Toast.Style.Success, title: success }); return true; } catch (error) { @@ -104,11 +128,59 @@ export function TranslationTable({ await change(() => onRemove(root), "False Positive freigegeben"); } + function renderRow(type: string, placeholder: string, members: string[]) { + const roots = groups.get(type)!; + const date = visibleDates[placeholder]; + const orderedMembers = sortOrder === "created-desc" + ? sortMappingRowsByCreatedAt(members.map((key) => ({ type, placeholder: key })), visibleDates) + .map((item) => item.placeholder) + : members; + return [key, visibleMapping[key].original])]} + accessories={[ + ...(members.length > 1 ? [{ text: `${members.length} Zuordnungen` }] : []), + ...(sortOrder === "created-desc" ? [{ text: date + ? `Angelegt ${new Date(date).toLocaleString("de-AT")}` : "Datum unbekannt · nach Nummer" }] : []), + ]} + actions={ + + {orderedMembers.map((key) => + {key !== placeholder && onDetach && { if (await change(() => onDetach(key), "Zuordnung aus Gruppe gelöst")) pop(); }} />} + + + } />)} + } /> + {onMerge && roots.size > 1 && + {[...roots.keys()].filter((target) => target !== placeholder).map((target) => + change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)} + } + {onRemove && remove(placeholder, members)} />} + + + } />; + } + return ( setSortOrder(value as "category" | "created-desc")}> + + + } > push()} />} /> + onAction={() => push()} />} /> } - {[...groups] + {sortOrder === "category" ? [...groups] .sort(([a], [b]) => a.localeCompare(b)) .map(([type, roots]) => ( n + members.length, 0)} Zuordnungen`}> - {[...roots].map(([placeholder, members]) => ( - [key, visibleMapping[key].original])} - accessories={members.length > 1 ? [{ text: `${members.length} Zuordnungen` }] : []} - actions={ - - - {members.map((key) => - {key !== placeholder && onDetach && { if (await change(() => onDetach(key), "Zuordnung aus Gruppe gelöst")) pop(); }} />} - - - } />)} - - } - /> - {onMerge && roots.size > 1 && - {[...roots.keys()].filter((target) => target !== placeholder).map((target) => - change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)} - } - {onRemove && remove(placeholder, members)} />} - - - - } - /> - ))} + {[...roots].map(([placeholder, members]) => renderRow(type, placeholder, members))} - ))} + )) : + {sortMappingRowsByCreatedAt(rows, visibleDates) + .map(({ type, placeholder, members }) => renderRow(type, placeholder, members))} + } ); } @@ -184,19 +214,20 @@ export default function Command() { const refresh = useCallback(async () => { await Promise.all([listAllRuns(), listSessions()]) .then(([runs, savedSessions]) => { - const latest = new Map(); + const history = new Map(); for (const { run } of runs) { const path = canonicalProjectPath(run.projectPath); - if (!latest.has(path)) - latest.set(path, { - id: path, - title: run.projectName, - subtitle: `${path} · ${new Date(run.createdAt).toLocaleString("de-AT")}`, - mapping: run.mapping, - }); + if (!history.has(path)) history.set(path, []); + history.get(path)!.push(run); } setProjects( - [...latest.values()].sort((a, b) => a.title.localeCompare(b.title)), + [...history].map(([path, entries]) => { + const latest = entries[0]; + return { id: path, title: latest.projectName, + subtitle: `${path} · ${new Date(latest.createdAt).toLocaleString("de-AT")}`, + mapping: latest.mapping, + createdAtByKey: projectMappingCreatedAt(entries, latest.mapping) }; + }).sort((a, b) => a.title.localeCompare(b.title)), ); setSessions( savedSessions.map((session) => ({ @@ -204,6 +235,7 @@ export default function Command() { title: session.name, subtitle: `${Object.keys(session.mapping).length} Zuordnungen · ${new Date(session.updatedAt).toLocaleString("de-AT")}`, mapping: session.mapping, + createdAtByKey: session.mappingCreatedAt ?? {}, })), ); }); @@ -243,6 +275,7 @@ export default function Command() { { const run = await addProjectMappingEntry(source.id, input); await refresh(); @@ -290,6 +323,7 @@ export default function Command() { { const session = await getSession(source.id); if (!session) throw new Error("Sitzung nicht gefunden."); diff --git a/src/types.ts b/src/types.ts index f2c6ba7..3ed05fd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -36,6 +36,7 @@ export type VelumSession = { mapping: PlaceholderMapping; entityTypes?: EntityType[]; excludedTerms?: Array<{ type: string; original: string }>; + mappingCreatedAt?: Record; }; export type QuickOutput = "copy" | "paste"; diff --git a/tests/mapping-created-at.test.ts b/tests/mapping-created-at.test.ts new file mode 100644 index 0000000..cd40f46 --- /dev/null +++ b/tests/mapping-created-at.test.ts @@ -0,0 +1,50 @@ +import { expect, it } from "bun:test"; +import { projectMappingCreatedAt, sortMappingRowsByCreatedAt } from "../src/lib/mapping-created-at"; +import type { ProjectRun } from "../src/lib/velum-project"; +import type { PlaceholderMapping } from "../src/types"; + +function run(createdAt: string, mapping: PlaceholderMapping): ProjectRun { + return { version: 2, id: createdAt, projectPath: "/synthetic", projectName: "synthetic", + createdAt, mapping, files: [] }; +} + +it("ermittelt die erste gespeicherte Projektfassung je unveränderter Zuordnung", () => { + const earlier = run("2026-01-01T10:00:00.000Z", { + PERSON_01: { type: "PERSON", original: "Beispiel Eins" }, + ORG_01: { type: "ORG", original: "Frühere Organisation" }, + }); + const latest = run("2026-02-01T10:00:00.000Z", { + PERSON_01: { type: "PERSON", original: "Beispiel Eins" }, + PERSON_02: { type: "PERSON", original: "Beispiel Zwei" }, + ORG_01: { type: "ORG", original: "Neue Organisation" }, + }); + expect(projectMappingCreatedAt([latest, earlier], latest.mapping)).toEqual({ + PERSON_01: earlier.createdAt, + PERSON_02: latest.createdAt, + ORG_01: latest.createdAt, + }); +}); + +it("sortiert datierte Zuordnungen zuerst, sonst Nummern je Kategorie absteigend", () => { + const rows = ["PERSON_02", "ORT_03", "PERSON_100", "ORT_20", "ORG_01", "PERSON_10"] + .map((placeholder) => ({ placeholder, type: placeholder.split("_")[0] })); + const sorted = sortMappingRowsByCreatedAt(rows, { + PERSON_02: "2026-05-01T00:00:00.000Z", + ORG_01: "2026-06-01T00:00:00.000Z", + }); + expect(sorted.map((row) => row.placeholder)) + .toEqual(["ORG_01", "PERSON_02", "ORT_20", "ORT_03", "PERSON_100", "PERSON_10"]); +}); + +it("behandelt importierte Erststände ohne echtes Anlagedatum als Nummern-Fallback", () => { + const imported = { ...run("2026-01-01T10:00:00.000Z", { + PERSON_01: { type: "PERSON", original: "Altbestand" }, + }), origin: "imported" as const }; + const later = { ...run("2026-02-01T10:00:00.000Z", { + PERSON_01: { type: "PERSON", original: "Altbestand" }, + PERSON_02: { type: "PERSON", original: "Neu" }, + }), origin: "imported" as const, revisedFrom: imported.id }; + expect(projectMappingCreatedAt([later, imported], later.mapping)).toEqual({ + PERSON_02: later.createdAt, + }); +}); diff --git a/tests/text-context.test.ts b/tests/text-context.test.ts index 1439a75..9a6a336 100644 --- a/tests/text-context.test.ts +++ b/tests/text-context.test.ts @@ -118,6 +118,22 @@ it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten ]); }); +it("bewahrt das Anlagedatum einer Sitzung beim Umklammern und Zusammenfassen", async () => { + const session = await sessions.createSession("Zeitfolge"); + const first = await sessions.updateSessionMapping(session.id, { + PERSON_01: { type: "PERSON", original: "Beispiel Eins" }, + }); + const created = first.mappingCreatedAt?.PERSON_01; + expect(created).toBeTruthy(); + const next = await sessions.updateSessionMapping(session.id, { + "": { type: "PERSON", original: "Beispiel Eins" }, + "": { type: "PERSON", original: "Beispiel Zwei", merged_into: "" }, + }); + expect(next.mappingCreatedAt?.[""]).toBe(created); + expect(next.mappingCreatedAt?.[""]).toBeTruthy(); + expect(next.mappingCreatedAt?.PERSON_01).toBeUndefined(); +}); + it("verlangt eine ausdrückliche Kontextwahl und legt ein Textprojekt nur einmal an", async () => { const root = await fs.mkdtemp(join(tmpdir(), "velum-text-context-")); roots.push(root);