diff --git a/src/depseudonymize-text.tsx b/src/depseudonymize-text.tsx index fbd0957..e9acca6 100644 --- a/src/depseudonymize-text.tsx +++ b/src/depseudonymize-text.tsx @@ -23,6 +23,7 @@ import type { DepseudonymizeResponse, VelumSession } from "./types"; import { markdownCodeBlock, sessionSubtitle } from "./ui"; import { restoreRichHtml } from "./lib/rich-text"; import { copyRichText } from "./rich-clipboard"; +import { mappingForRestoration } from "./lib/mapping-groups"; type FormValues = { text: string; @@ -156,9 +157,10 @@ export default function Command( const projectPath = values.sessionId.slice("project:".length); const saved = (await listRuns(projectPath))[0]; if (!saved) throw new Error("Projektstand nicht gefunden."); + const restorationMapping = mappingForRestoration(saved.run.mapping); const restored = restoreTextWithCount( input, - saved.run.mapping, + restorationMapping, saved.run.matchModes, ); result = { @@ -170,7 +172,7 @@ export default function Command( richSource.html, input, result.original_text, - saved.run.mapping, + restorationMapping, saved.run.matchModes, ); } @@ -179,13 +181,14 @@ export default function Command( } else { const session = await getSession(values.sessionId); if (!session) throw new Error("Sitzung nicht gefunden."); - result = await depseudonymize(input, session.mapping); + const restorationMapping = mappingForRestoration(session.mapping); + result = await depseudonymize(input, restorationMapping); if (richSource?.text === input) { richHtml = restoreRichHtml( richSource.html, input, result.original_text, - session.mapping, + restorationMapping, undefined, true, ); diff --git a/src/lib/mapping-groups.ts b/src/lib/mapping-groups.ts new file mode 100644 index 0000000..986a249 --- /dev/null +++ b/src/lib/mapping-groups.ts @@ -0,0 +1,43 @@ +import type { PlaceholderMapping } from "../types"; + +export function mappingRoot(key: string, mapping: PlaceholderMapping): string { + const initial = mapping[key]; + if (!initial) throw new Error(`Unbekannte Zuordnung: ${key}`); + const seen = new Set(); + let current = key; + while (mapping[current].merged_into) { + if (seen.has(current)) throw new Error(`Zyklische Zuordnung: ${key}`); + seen.add(current); + const target = mapping[current].merged_into!; + if (!mapping[target] || mapping[target].type !== initial.type) { + throw new Error(`Ungültiger Hauptbegriff für ${key}: ${target}`); + } + current = target; + } + return current; +} + +/** Reverse lookups use the group's main term, while the saved variants remain intact. */ +export function mappingForRestoration(mapping: PlaceholderMapping): PlaceholderMapping { + return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key, { + type: entry.type, + original: mapping[mappingRoot(key, mapping)].original, + }])); +} + +export function mergeMappingGroups(mapping: PlaceholderMapping, source: string, target: string): PlaceholderMapping { + const from = mappingRoot(source, mapping); + const into = mappingRoot(target, mapping); + if (from === into) throw new Error("Diese Zuordnungen sind bereits zusammengefasst."); + if (mapping[from].type !== mapping[into].type) { + throw new Error("Nur Zuordnungen derselben Kategorie können zusammengefasst werden."); + } + return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key, + mappingRoot(key, mapping) === from ? { ...entry, merged_into: into } : { ...entry }, + ])); +} + +export function detachMappingGroup(mapping: PlaceholderMapping, key: string): PlaceholderMapping { + if (!mapping[key]?.merged_into) throw new Error("Diese Zuordnung ist kein Verweis."); + return { ...mapping, [key]: { ...mapping[key], merged_into: undefined } }; +} diff --git a/src/lib/velum-project.ts b/src/lib/velum-project.ts index dd71c85..321307a 100644 --- a/src/lib/velum-project.ts +++ b/src/lib/velum-project.ts @@ -6,6 +6,7 @@ import type { EntityType, MappingEntry, PlaceholderMapping } from "../types"; import { whitelistKey } from "./project-whitelist"; import type { ProjectWhitelistEntry } from "./project-whitelist"; import { restoreOriginalCase } from "./restore-case"; +import { mappingForRestoration } from "./mapping-groups"; export { whitelistKey } from "./project-whitelist"; export type { ProjectWhitelistEntry } from "./project-whitelist"; @@ -415,19 +416,19 @@ export function prepareManualMappingEntry(current: PlaceholderMapping, earlier: } /** Save a mapping correction as a new immutable project stand without rewriting project files. */ -export async function addProjectMappingEntry(projectPath: string, - input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise { +export async function updateProjectMapping(projectPath: string, + change: (current: PlaceholderMapping, earlier: PlaceholderMapping[]) => PlaceholderMapping, + support = environment.supportPath): Promise { const entries = await listRuns(projectPath, support); const latest = entries[0]; if (!latest) throw new Error("Für dieses Projekt gibt es noch keinen gespeicherten Stand."); - const { placeholder, entry } = prepareManualMappingEntry(latest.run.mapping, - entries.slice(1).map((saved) => saved.run.mapping), input); + const mapping = change(latest.run.mapping, entries.slice(1).map((saved) => saved.run.mapping)); const created = await createRun(projectPath, support); const { run, directory } = created; run.createdAt = new Date(Math.max(Date.now(), Date.parse(latest.run.createdAt) + 1)).toISOString(); run.origin = latest.run.origin; run.revisedFrom = latest.run.id; - run.mapping = { ...latest.run.mapping, [placeholder]: entry }; + run.mapping = mapping; run.matchModes = { ...latest.run.matchModes }; run.files = latest.run.files.map((file) => ({ ...file })); run.inPlace = latest.run.inPlace; @@ -454,6 +455,14 @@ export async function addProjectMappingEntry(projectPath: string, return run; } +export async function addProjectMappingEntry(projectPath: string, + input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise { + return updateProjectMapping(projectPath, (current, earlier) => { + const { placeholder, entry } = prepareManualMappingEntry(current, earlier, input); + return { ...current, [placeholder]: entry }; + }, support); +} + export function runCopiesPath(run: ProjectRun, directory: string): string { return run.copyPath ?? join(directory, "files"); } @@ -547,7 +556,7 @@ export async function mappingForMatchingSnapshots(relPath: string, currentHash: const matching = await Promise.all(earlier.filter(({ run }) => run.files.some((file) => file.output === relPath)) .map(async ({ run, directory }) => await matchesPreviousOutput(directory, relPath, currentHash) - ? run.mapping : undefined)); + ? mappingForRestoration(run.mapping) : undefined)); return withUnambiguousHistoricalMappings({}, matching.filter((mapping): mapping is PlaceholderMapping => Boolean(mapping))); } diff --git a/src/restore-project-files.tsx b/src/restore-project-files.tsx index 0bdcb35..8c80365 100644 --- a/src/restore-project-files.tsx +++ b/src/restore-project-files.tsx @@ -4,12 +4,13 @@ import { homedir } from "node:os"; import { basename, dirname, join } from "node:path"; import { useEffect, useState } from "react"; import { depseudonymizeDocument } from "./velum"; -import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, withUnambiguousHistoricalMappings } from "./lib/velum-project"; +import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, updateProjectMapping, withUnambiguousHistoricalMappings } from "./lib/velum-project"; import type { ProjectFile, ProjectRun } from "./lib/velum-project"; import type { MappingEntry, PlaceholderMapping } from "./types"; import { canonicalPerson, mergePeople } from "./lib/project-review"; import { planProjectRevision, reviseProjectRun } from "./lib/project-revision"; import { TranslationTable } from "./show-translation-tables"; +import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups"; type SavedRun = { run: ProjectRun; directory: string }; type RestoreDecision = MappingEntry | null; @@ -182,8 +183,9 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo const [busy, setBusy] = useState(false); const [unresolved, setUnresolved] = useState>([]); const [decisions, setDecisions] = useState>>({}); - const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]; - const baseMapping = withUnambiguousHistoricalMappings(props.run.mapping, mappings.slice(1)); + const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)] + .map(mappingForRestoration); + const baseMapping = withUnambiguousHistoricalMappings(mappings[0], mappings.slice(1)); const candidatesFor = (id: string): MappingEntry[] => { const unique = new Map(); for (const mapping of mappings) for (const [key, entry] of Object.entries(mapping)) { @@ -440,6 +442,18 @@ export default function Command() { const updated = await addProjectMappingEntry(run.projectPath, input); await refresh(); return updated.mapping; + }} + onMerge={async (from, into) => { + const updated = await updateProjectMapping(run.projectPath, + (current) => mergeMappingGroups(current, from, into)); + await refresh(); + return updated.mapping; + }} + onDetach={async (key) => { + const updated = await updateProjectMapping(run.projectPath, + (current) => detachMappingGroup(current, key)); + await refresh(); + return updated.mapping; }} />} /> showInFinder(runCopiesPath(run, directory))} /> diff --git a/src/show-translation-tables.tsx b/src/show-translation-tables.tsx index adc45cd..50081d0 100644 --- a/src/show-translation-tables.tsx +++ b/src/show-translation-tables.tsx @@ -1,7 +1,6 @@ import { Action, ActionPanel, - Detail, Form, Icon, List, @@ -10,10 +9,10 @@ import { useNavigation, } from "@raycast/api"; import { useCallback, useEffect, useState } from "react"; -import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry } from "./lib/velum-project"; +import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project"; +import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups"; import { getSession, listSessions, updateSessionMapping } from "./sessions"; import type { PlaceholderMapping } from "./types"; -import { markdownCodeBlock } from "./ui"; type TableSource = { id: string; @@ -54,26 +53,45 @@ export function TranslationTable({ title, mapping, onAdd, + onMerge, + onDetach, }: { title: string; mapping: PlaceholderMapping; onAdd?: (input: ManualEntry) => Promise; + onMerge?: (source: string, target: string) => Promise; + onDetach?: (key: string) => Promise; }) { - const { push } = useNavigation(); + const { push, pop } = useNavigation(); const [visibleMapping, setVisibleMapping] = useState(mapping); + const [busy, setBusy] = useState(false); useEffect(() => setVisibleMapping(mapping), [mapping]); - const groups = new Map>(); - for (const entry of Object.entries(visibleMapping).sort(([a], [b]) => - a.localeCompare(b), - )) { - const type = entry[1].type || "Sonstige"; - const entries = groups.get(type) ?? []; - entries.push(entry); - groups.set(type, entries); + const groups = new Map>(); + for (const [key, entry] of Object.entries(visibleMapping).sort(([a], [b]) => a.localeCompare(b))) { + const type = entry.type || "Sonstige"; + if (!groups.has(type)) groups.set(type, new Map()); + const root = mappingRoot(key, visibleMapping); + const members = groups.get(type)!.get(root) ?? []; + members.push(key); + groups.get(type)!.set(root, members); + } + async function change(action: () => Promise, success: string): Promise { + if (busy) return false; + setBusy(true); + try { + setVisibleMapping(await action()); + await showToast({ style: Toast.Style.Success, title: success }); + return true; + } catch (error) { + await showToast({ style: Toast.Style.Failure, title: "Zuordnungen nicht geändert", + message: (error as Error).message }); + return false; + } finally { setBusy(false); } } return ( @@ -89,64 +107,47 @@ export function TranslationTable({ } {[...groups] .sort(([a], [b]) => a.localeCompare(b)) - .map(([type, entries]) => ( - - {entries.map(([placeholder, entry]) => ( + .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")} />)} + } } @@ -230,6 +231,18 @@ export default function Command() { await refresh(); return run.mapping; }} + onMerge={async (from, into) => { + const run = await updateProjectMapping(source.id, + (current) => mergeMappingGroups(current, from, into)); + await refresh(); + return run.mapping; + }} + onDetach={async (key) => { + const run = await updateProjectMapping(source.id, + (current) => detachMappingGroup(current, key)); + await refresh(); + return run.mapping; + }} /> } /> @@ -267,6 +280,22 @@ export default function Command() { await refresh(); return updated.mapping; }} + onMerge={async (from, into) => { + const session = await getSession(source.id); + if (!session) throw new Error("Sitzung nicht gefunden."); + const updated = await updateSessionMapping(session.id, + mergeMappingGroups(session.mapping, from, into), session.entityTypes); + await refresh(); + return updated.mapping; + }} + onDetach={async (key) => { + const session = await getSession(source.id); + if (!session) throw new Error("Sitzung nicht gefunden."); + const updated = await updateSessionMapping(session.id, + detachMappingGroup(session.mapping, key), session.entityTypes); + await refresh(); + return updated.mapping; + }} /> } /> diff --git a/tests/mapping-groups.test.ts b/tests/mapping-groups.test.ts new file mode 100644 index 0000000..56e974d --- /dev/null +++ b/tests/mapping-groups.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "bun:test"; +import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "../src/lib/mapping-groups"; +import type { PlaceholderMapping } from "../src/types"; + +describe("Zuordnungen gruppieren und wiederherstellen", () => { + const original: PlaceholderMapping = { + PERSON_01: { type: "PERSON", original: "Franz Fuchs" }, + PERSON_02: { type: "PERSON", original: "Franz F.", merged_into: "PERSON_01" }, + PERSON_03: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_02" }, + PERSON_04: { type: "PERSON", original: "Mara Muster" }, + ORG_01: { type: "ORG", original: "Muster GmbH" }, + }; + + it("verwendet für alle Verweise den Hauptbegriff ohne die gespeicherten Varianten zu ändern", () => { + const restored = mappingForRestoration(original); + expect(restored.PERSON_01.original).toBe("Franz Fuchs"); + expect(restored.PERSON_02.original).toBe("Franz Fuchs"); + expect(restored.PERSON_03.original).toBe("Franz Fuchs"); + expect(restored.PERSON_03.merged_into).toBeUndefined(); + expect(original.PERSON_03.original).toBe("Hr. Fuchs"); + }); + + it("fasst ganze Gruppen zusammen und kann einen einzelnen Verweis wieder lösen", () => { + const merged = mergeMappingGroups(original, "PERSON_02", "PERSON_04"); + expect(merged.PERSON_01.merged_into).toBe("PERSON_04"); + expect(merged.PERSON_02.merged_into).toBe("PERSON_04"); + expect(merged.PERSON_03.merged_into).toBe("PERSON_04"); + expect(mappingForRestoration(merged).PERSON_03.original).toBe("Mara Muster"); + expect(detachMappingGroup(merged, "PERSON_03").PERSON_03.merged_into).toBeUndefined(); + expect(original.PERSON_01.merged_into).toBeUndefined(); + expect(() => mergeMappingGroups(original, "PERSON_01", "ORG_01")).toThrow("derselben Kategorie"); + }); + + it("stoppt defekte oder zyklische Verweise vor dem Klartext-Export", () => { + expect(() => mappingForRestoration({ PERSON_01: { type: "PERSON", original: "A", merged_into: "PERSON_99" } })) + .toThrow("Ungültiger Hauptbegriff"); + expect(() => mappingForRestoration({ + PERSON_01: { type: "PERSON", original: "A", merged_into: "PERSON_02" }, + PERSON_02: { type: "PERSON", original: "B", merged_into: "PERSON_01" }, + })).toThrow("Zyklische Zuordnung"); + }); +}); diff --git a/tests/velum-project.test.ts b/tests/velum-project.test.ts index de20b71..ef9d3c8 100644 --- a/tests/velum-project.test.ts +++ b/tests/velum-project.test.ts @@ -6,6 +6,8 @@ import type { RunFile } from "../src/lib/velum-project"; mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() } })); const project = await import("../src/lib/velum-project"); +const { mappingForRestoration } = await import("../src/lib/mapping-groups"); +const { mergeMappingGroups } = await import("../src/lib/mapping-groups"); const roots: string[] = []; afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); }); @@ -186,6 +188,15 @@ describe("Velum-Projektstände", () => { expect(() => project.safeRelativePath("../geheim.txt")).toThrow(); }); + it("stellt alte Personen-Verweise in Text und Dateiname mit dem Hauptbegriff wieder her", () => { + const mapping = mappingForRestoration({ + PERSON_01: { type: "PERSON", original: "Franz Fuchs" }, + PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" }, + }); + expect(project.restoreText("PERSON_02 und PERSON_01", mapping)).toBe("Franz Fuchs und Franz Fuchs"); + expect(project.restorePath("PERSON_02_Entwurf.md", mapping)).toBe("Franz Fuchs_Entwurf.md"); + }); + it("verwendet ältere Zuordnungen nur bei übereinstimmender Bedeutung und meldet übrig gebliebene Markdown-Platzhalter", () => { const current = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } }; const older = [ @@ -209,7 +220,10 @@ describe("Velum-Projektstände", () => { const relPath = "Fragenliste.md"; first.run.files = [{ source: relPath, output: relPath, kind: "text" }]; second.run.files = [{ source: relPath, output: relPath, kind: "text" }]; - first.run.mapping = { PERSON_61: { original: "Alex Beispiel", type: "PERSON" } }; + first.run.mapping = { + PERSON_60: { original: "Alex Beispiel", type: "PERSON" }, + PERSON_61: { original: "Hr. Beispiel", type: "PERSON", merged_into: "PERSON_60" }, + }; second.run.mapping = { PERSON_61: { original: "Mara Muster", type: "PERSON" } }; const source = Buffer.from("Kommentar PERSON_61"); await fs.writeFile(join(first.directory, "files", relPath), source); @@ -242,6 +256,28 @@ describe("Velum-Projektstände", () => { { original: "Weiterer Begriff", type: "PERSON" }).placeholder).toBe("PERSON_62"); }); + it("speichert eine Gruppierung als neuen Projektstand und lässt frühere Dateien unverändert", async () => { + const root = await fs.mkdtemp(join(tmpdir(), "velum-group-mapping-")); + roots.push(root); + const source = join(root, "Quelle"); + await fs.mkdir(source); + const saved = await project.createRun(source, root); + saved.run.mapping = { + PERSON_01: { original: "Franz Fuchs", type: "PERSON" }, + PERSON_02: { original: "Hr. Fuchs", type: "PERSON" }, + }; + saved.run.files = [{ source: "Notiz.md", output: "Notiz.md", kind: "text" }]; + await fs.writeFile(join(saved.directory, "files", "Notiz.md"), "PERSON_02"); + await project.saveRun(saved.directory, saved.run); + const updated = await project.updateProjectMapping(source, + (mapping) => mergeMappingGroups(mapping, "PERSON_02", "PERSON_01"), root); + expect(updated.mapping.PERSON_02.merged_into).toBe("PERSON_01"); + expect((await project.listRuns(source, root))[1].run.mapping.PERSON_02.merged_into).toBeUndefined(); + expect(await fs.readFile(join(project.projectDataRoot(source, root), "runs", updated.id, "files", "Notiz.md"), "utf8")) + .toBe("PERSON_02"); + expect(project.restoreText("PERSON_02", mappingForRestoration(updated.mapping))).toBe("Franz Fuchs"); + }); + it("verhindert eine neue projektweite Zuordnung für eine früher anders belegte ID", () => { expect(() => project.prepareManualMappingEntry({}, [ { PERSON_61: { original: "Alex Beispiel", type: "PERSON" } },