feat: group translation mappings and restore canonical terms
This commit is contained in:
@@ -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,
|
||||
);
|
||||
|
||||
43
src/lib/mapping-groups.ts
Normal file
43
src/lib/mapping-groups.ts
Normal file
@@ -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<string>();
|
||||
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 } };
|
||||
}
|
||||
@@ -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<ProjectRun> {
|
||||
export async function updateProjectMapping(projectPath: string,
|
||||
change: (current: PlaceholderMapping, earlier: PlaceholderMapping[]) => PlaceholderMapping,
|
||||
support = environment.supportPath): Promise<ProjectRun> {
|
||||
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<ProjectRun> {
|
||||
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)));
|
||||
}
|
||||
|
||||
@@ -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<Array<{ file: string; id: string }>>([]);
|
||||
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
|
||||
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<string, MappingEntry>();
|
||||
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;
|
||||
}} />} />
|
||||
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
|
||||
onAction={() => showInFinder(runCopiesPath(run, directory))} />
|
||||
|
||||
@@ -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<PlaceholderMapping>;
|
||||
onMerge?: (source: string, target: string) => Promise<PlaceholderMapping>;
|
||||
onDetach?: (key: string) => Promise<PlaceholderMapping>;
|
||||
}) {
|
||||
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<string, Array<[string, PlaceholderMapping[string]]>>();
|
||||
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<string, Map<string, string[]>>();
|
||||
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<PlaceholderMapping>, success: string): Promise<boolean> {
|
||||
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 (
|
||||
<List
|
||||
isLoading={busy}
|
||||
navigationTitle={`Übersetzungstabelle · ${title}`}
|
||||
searchBarPlaceholder="Platzhalter oder Klartext suchen"
|
||||
>
|
||||
@@ -89,64 +107,47 @@ export function TranslationTable({
|
||||
</List.Section>}
|
||||
{[...groups]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([type, entries]) => (
|
||||
<List.Section key={type} title={`${type} · ${entries.length}`}>
|
||||
{entries.map(([placeholder, entry]) => (
|
||||
.map(([type, roots]) => (
|
||||
<List.Section key={type} title={`${type} · ${roots.size} Gruppen / ${[...roots.values()].reduce((n, members) => n + members.length, 0)} Zuordnungen`}>
|
||||
{[...roots].map(([placeholder, members]) => (
|
||||
<List.Item
|
||||
key={placeholder}
|
||||
icon={Icon.ArrowRight}
|
||||
title={placeholder}
|
||||
subtitle={entry.original}
|
||||
keywords={[entry.original, entry.type, entry.merged_into ?? ""]}
|
||||
accessories={
|
||||
entry.merged_into ? [{ text: `→ ${entry.merged_into}` }] : []
|
||||
}
|
||||
subtitle={visibleMapping[placeholder].original}
|
||||
keywords={members.flatMap((key) => [key, visibleMapping[key].original])}
|
||||
accessories={members.length > 1 ? [{ text: `${members.length} Zuordnungen` }] : []}
|
||||
actions={
|
||||
<ActionPanel>
|
||||
<Action.Push
|
||||
title="Eintrag vollständig anzeigen"
|
||||
title="Gruppe und Varianten anzeigen"
|
||||
icon={Icon.Eye}
|
||||
target={
|
||||
<Detail
|
||||
navigationTitle={placeholder}
|
||||
markdown={[
|
||||
`# ${entry.type}`,
|
||||
"",
|
||||
"Platzhalter",
|
||||
markdownCodeBlock(placeholder),
|
||||
"",
|
||||
"Klartext",
|
||||
markdownCodeBlock(entry.original),
|
||||
...(entry.merged_into
|
||||
? [
|
||||
"",
|
||||
"Zusammengeführt mit",
|
||||
markdownCodeBlock(entry.merged_into),
|
||||
]
|
||||
: []),
|
||||
].join("\n")}
|
||||
actions={
|
||||
<ActionPanel>
|
||||
<Action.CopyToClipboard
|
||||
title="Platzhalter kopieren"
|
||||
content={placeholder}
|
||||
/>
|
||||
<Action.CopyToClipboard
|
||||
title="Klartext kopieren"
|
||||
content={entry.original}
|
||||
/>
|
||||
</ActionPanel>
|
||||
}
|
||||
/>
|
||||
<List navigationTitle={`${type} · ${placeholder}`} searchBarPlaceholder="Variante suchen">
|
||||
{members.map((key) => <List.Item key={key} title={key}
|
||||
subtitle={visibleMapping[key].original}
|
||||
accessories={key === placeholder ? [{ text: "Hauptbegriff" }] : [{ text: `→ ${placeholder}` }]}
|
||||
actions={<ActionPanel>
|
||||
{key !== placeholder && onDetach && <Action title="Aus Gruppe lösen" icon={Icon.ArrowLeft}
|
||||
onAction={async () => { if (await change(() => onDetach(key), "Zuordnung aus Gruppe gelöst")) pop(); }} />}
|
||||
<Action.CopyToClipboard title="Platzhalter kopieren" content={key} />
|
||||
<Action.CopyToClipboard title="Klartext kopieren" content={visibleMapping[key].original} />
|
||||
</ActionPanel>} />)}
|
||||
</List>
|
||||
}
|
||||
/>
|
||||
{onMerge && roots.size > 1 && <ActionPanel.Submenu title="Mit Hauptbegriff zusammenfassen" icon={Icon.Link}>
|
||||
{[...roots.keys()].filter((target) => target !== placeholder).map((target) =>
|
||||
<Action key={target} title={`${visibleMapping[target].original} · ${target}`}
|
||||
onAction={() => change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)}
|
||||
</ActionPanel.Submenu>}
|
||||
<Action.CopyToClipboard
|
||||
title="Platzhalter kopieren"
|
||||
content={placeholder}
|
||||
/>
|
||||
<Action.CopyToClipboard
|
||||
title="Klartext kopieren"
|
||||
content={entry.original}
|
||||
content={visibleMapping[placeholder].original}
|
||||
/>
|
||||
</ActionPanel>
|
||||
}
|
||||
@@ -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;
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user